instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public SimpleRabbitListenerContainerFactory defaultContainerFactory(ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); return factory; } @Bean public SimpleRabbitListenerContainerFactory retryContainerFactory(ConnectionFactory connectionFactory, RetryOperationsInterceptor retryInterceptor) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); Advice[] adviceChain = { retryInterceptor }; factory.setAdviceChain(adviceChain); return factory; } @Bean public SimpleRabbitListenerContainerFactory retryQueuesContainerFactory(ConnectionFactory connectionFactory, RetryQueuesInterceptor retryInterceptor) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); Advice[] adviceChain = { retryInterceptor }; factory.setAdviceChain(adviceChain); return factory; } @RabbitListener(queues = "blocking-queue", containerFactory = "retryContainerFactory") public void consumeBlocking(String payload) throws Exception { logger.info("Processing message from blocking-queue: {}", payload);
throw new Exception("exception occured!"); } @RabbitListener(queues = "non-blocking-queue", containerFactory = "retryQueuesContainerFactory", ackMode = "MANUAL") public void consumeNonBlocking(String payload) throws Exception { logger.info("Processing message from non-blocking-queue: {}", payload); throw new Exception("Error occured!"); } @RabbitListener(queues = "retry-wait-ended-queue", containerFactory = "defaultContainerFactory") public void consumeRetryWaitEndedMessage(String payload, Message message, Channel channel) throws Exception { MessageProperties props = message.getMessageProperties(); rabbitTemplate().convertAndSend(props.getHeader("x-original-exchange"), props.getHeader("x-original-routing-key"), message); } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RabbitConfiguration.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } final boolean someSchedsAreStillNotProcessed = receiptScheduleBL.hasUnProcessedRecords(context.getQueryFilter(I_M_ReceiptSchedule.class)); if (!someSchedsAreStillNotProcessed) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_NO_UNPROCESSED_LINES)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt()
{ final int selectionCount = receiptScheduleDAO .createQueryForReceiptScheduleSelection(getCtx(), getProcessInfo().getQueryFilterOrElseFalse()) .create() .createSelection(getPinstanceId()); if (selectionCount <= 0) { throw new AdempiereException(MSG_NO_UNPROCESSED_LINES) .markAsUserValidationError(); } final int updatedCnt = receiptScheduleBL.updateDatePromisedOverrideAndPOReference(getPinstanceId(), datePromisedOverride, poReference); addLog("Updated {} M_ReceiptSchedules", updatedCnt); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_ChangeDatePromised_OverrideAndPOReference.java
1
请完成以下Java代码
public class NotificationDTO { private Date date; private String format; private String productName; public NotificationDTO(Date date, String format, String productName) { this.date = date; this.format = format; this.productName = productName; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; }
public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\modulith\notification\NotificationDTO.java
1
请完成以下Java代码
private Timestamp getMovementDate(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final Properties context) { return movementDateRule.map(new ReceiptMovementDateRule.CaseMapper<Timestamp>() { @Override public Timestamp orderDatePromised() {return getPromisedDate(receiptSchedule, context);} @Override public Timestamp externalDateIfAvailable() {return getExternalMovementDate(receiptSchedule, context);} // Use Login Date as movement date because some roles will rely on the fact that they can override it (08247) @Override public Timestamp currentDate() {return Env.getDate(context);} @Override public Timestamp fixedDate(@NonNull final Instant fixedDate) {return Timestamp.from(fixedDate);} }); } private Timestamp getDateAcct(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final Properties context) { return movementDateRule.map(new ReceiptMovementDateRule.CaseMapper<Timestamp>() {
@Override public Timestamp orderDatePromised() {return getPromisedDate(receiptSchedule, context);} @Override public Timestamp externalDateIfAvailable() {return getExternalDateAcct(receiptSchedule, context);} // Use Login Date as movement date because some roles will rely on the fact that they can override it (08247) @Override public Timestamp currentDate() {return Env.getDate(context);} @Override public Timestamp fixedDate(@NonNull final Instant fixedDate) {return Timestamp.from(fixedDate);} }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\InOutProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class WidgetTypeImportService extends BaseEntityImportService<WidgetTypeId, WidgetTypeDetails, WidgetTypeExportData> { private final WidgetTypeService widgetTypeService; @Override protected void setOwner(TenantId tenantId, WidgetTypeDetails widgetsBundle, IdProvider idProvider) { widgetsBundle.setTenantId(tenantId); } @Override protected WidgetTypeDetails prepare(EntitiesImportCtx ctx, WidgetTypeDetails widgetTypeDetails, WidgetTypeDetails old, WidgetTypeExportData exportData, IdProvider idProvider) { return widgetTypeDetails; } @Override protected WidgetTypeDetails saveOrUpdate(EntitiesImportCtx ctx, WidgetTypeDetails widgetsBundle, WidgetTypeExportData exportData, IdProvider idProvider, CompareResult compareResult) { return widgetTypeService.saveWidgetType(widgetsBundle);
} @Override protected CompareResult compare(EntitiesImportCtx ctx, WidgetTypeExportData exportData, WidgetTypeDetails prepared, WidgetTypeDetails existing) { return new CompareResult(true); } @Override protected WidgetTypeDetails deepCopy(WidgetTypeDetails widgetsBundle) { return new WidgetTypeDetails(widgetsBundle); } @Override public EntityType getEntityType() { return EntityType.WIDGET_TYPE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\WidgetTypeImportService.java
2
请完成以下Spring Boot application配置
server: port: 9000 spring: application: name: Server-Consumer eureka: client: serviceUrl: defaultZone: http://mrbird:123456@peer1:8080/eureka/,http://mrbird:123456@peer2:8081/eureka/ feign: hystrix: enabled: true
logging: level: com: example: demo: service: UserService: debug
repos\SpringAll-master\33.Spring-Cloud-Feign-Declarative-REST-Client\Feign-Consumer\src\main\resources\application.yml
2
请完成以下Java代码
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代码
public class BrandQueryReq extends QueryReq { /** 主键 */ private String id; /** 产品品牌名称 */ private String brand; /** 品牌所属企业 */ private String companyEntityId; public String getId() { return id; } public void setId(String id) { this.id = id; }
public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getCompanyEntityId() { return companyEntityId; } public void setCompanyEntityId(String companyEntityId) { this.companyEntityId = companyEntityId; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\BrandQueryReq.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteEventSubscription(EventSubscriptionEntity eventSubscription) { getEventSubscriptionEntityManager().delete(eventSubscription); } @Override public void deleteEventSubscriptionsByExecutionId(String executionId) { getEventSubscriptionEntityManager().deleteEventSubscriptionsByExecutionId(executionId); } @Override public void deleteEventSubscriptionsForScopeIdAndType(String scopeId, String scopeType) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeIdAndType(scopeId, scopeType); } @Override public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForProcessDefinition(processDefinitionId); } @Override public void deleteEventSubscriptionsForScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionIdAndType(scopeDefinitionId, scopeType); } @Override public void deleteEventSubscriptionsForScopeDefinitionIdAndTypeAndNullScopeId(String scopeDefinitionId, String scopeType) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionIdAndTypeAndNullScopeId(scopeDefinitionId, scopeType); }
@Override public void deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(String processDefinitionId, String eventType, String activityId, String configuration) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(processDefinitionId, eventType, activityId, configuration); } @Override public void deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(String scopeDefinitionId, String eventType, String configuration) { getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(scopeDefinitionId, eventType, configuration); } public EventSubscription createEventSubscription(EventSubscriptionBuilder builder) { return getEventSubscriptionEntityManager().createEventSubscription(builder); } public EventSubscriptionEntityManager getEventSubscriptionEntityManager() { return configuration.getEventSubscriptionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionServiceImpl.java
2
请完成以下Java代码
public class BankTransactionCodeStructure4 { @XmlElement(name = "Domn") protected BankTransactionCodeStructure5 domn; @XmlElement(name = "Prtry") protected ProprietaryBankTransactionCodeStructure1 prtry; /** * Gets the value of the domn property. * * @return * possible object is * {@link BankTransactionCodeStructure5 } * */ public BankTransactionCodeStructure5 getDomn() { return domn; } /** * Sets the value of the domn property. * * @param value * allowed object is * {@link BankTransactionCodeStructure5 } * */ public void setDomn(BankTransactionCodeStructure5 value) { this.domn = value; } /**
* Gets the value of the prtry property. * * @return * possible object is * {@link ProprietaryBankTransactionCodeStructure1 } * */ public ProprietaryBankTransactionCodeStructure1 getPrtry() { return prtry; } /** * Sets the value of the prtry property. * * @param value * allowed object is * {@link ProprietaryBankTransactionCodeStructure1 } * */ public void setPrtry(ProprietaryBankTransactionCodeStructure1 value) { this.prtry = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BankTransactionCodeStructure4.java
1
请完成以下Java代码
public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } /** * Gets the value of the rsn property. * * @return * possible object is * {@link String } * */ public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } * */ public void setRsn(String value) { this.rsn = value; }
/** * Gets the value of the addtlInf property. * * @return * possible object is * {@link String } * */ public String getAddtlInf() { return addtlInf; } /** * Sets the value of the addtlInf property. * * @param value * allowed object is * {@link String } * */ public void setAddtlInf(String value) { this.addtlInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DocumentAdjustment1.java
1
请完成以下Java代码
public Builder authenticationMethods(List<String> authenticationMethods) { return claim(IdTokenClaimNames.AMR, authenticationMethods); } /** * Use this authorization code hash in the resulting {@link OidcIdToken} * @param authorizationCodeHash The authorization code hash to use * @return the {@link Builder} for further configurations */ public Builder authorizationCodeHash(String authorizationCodeHash) { return claim(IdTokenClaimNames.C_HASH, authorizationCodeHash); } /** * Use this authorized party in the resulting {@link OidcIdToken} * @param authorizedParty The authorized party to use * @return the {@link Builder} for further configurations */ public Builder authorizedParty(String authorizedParty) { return claim(IdTokenClaimNames.AZP, authorizedParty); } /** * Use this expiration in the resulting {@link OidcIdToken} * @param expiresAt The expiration to use * @return the {@link Builder} for further configurations */ public Builder expiresAt(Instant expiresAt) { return this.claim(IdTokenClaimNames.EXP, expiresAt); } /** * Use this issued-at timestamp in the resulting {@link OidcIdToken} * @param issuedAt The issued-at timestamp to use * @return the {@link Builder} for further configurations */ public Builder issuedAt(Instant issuedAt) { return this.claim(IdTokenClaimNames.IAT, issuedAt); } /** * Use this issuer in the resulting {@link OidcIdToken} * @param issuer The issuer to use * @return the {@link Builder} for further configurations */ public Builder issuer(String issuer) { return this.claim(IdTokenClaimNames.ISS, issuer); } /** * Use this nonce in the resulting {@link OidcIdToken} * @param nonce The nonce to use
* @return the {@link Builder} for further configurations */ public Builder nonce(String nonce) { return this.claim(IdTokenClaimNames.NONCE, nonce); } /** * Use this subject in the resulting {@link OidcIdToken} * @param subject The subject to use * @return the {@link Builder} for further configurations */ public Builder subject(String subject) { return this.claim(IdTokenClaimNames.SUB, subject); } /** * Build the {@link OidcIdToken} * @return The constructed {@link OidcIdToken} */ public OidcIdToken build() { Instant iat = toInstant(this.claims.get(IdTokenClaimNames.IAT)); Instant exp = toInstant(this.claims.get(IdTokenClaimNames.EXP)); return new OidcIdToken(this.tokenValue, iat, exp, this.claims); } private Instant toInstant(Object timestamp) { if (timestamp != null) { Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant"); } return (Instant) timestamp; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcIdToken.java
1
请在Spring Boot框架中完成以下Java代码
public void add(EntityId profileId, EntityId entityId) { lock.writeLock().lock(); try { if (EntityType.DEVICE.equals(profileId.getEntityType()) || EntityType.ASSET.equals(profileId.getEntityType())) { throw new RuntimeException("Entity type '" + profileId.getEntityType() + "' is not a profileId."); } allEntities.computeIfAbsent(profileId, k -> new HashSet<>()).add(entityId); } finally { lock.writeLock().unlock(); } } public void update(EntityId oldProfileId, EntityId newProfileId, EntityId entityId) { remove(oldProfileId, entityId); add(newProfileId, entityId); } public Collection<EntityId> getEntityIdsByProfileId(EntityId profileId) { lock.readLock().lock();
try { var entities = allEntities.getOrDefault(profileId, Collections.emptySet()); List<EntityId> result = new ArrayList<>(entities.size()); result.addAll(entities); return result; } finally { lock.readLock().unlock(); } } private void removeSafely(Map<EntityId, Set<EntityId>> map, EntityId profileId, EntityId entityId) { var set = map.get(profileId); if (set != null) { set.remove(entityId); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\cache\TenantEntityProfileCache.java
2
请在Spring Boot框架中完成以下Java代码
public String getTimestampFieldName() { return this.timestampFieldName; } public void setTimestampFieldName(String timestampFieldName) { this.timestampFieldName = timestampFieldName; } public boolean isAutoCreateIndex() { return this.autoCreateIndex; } public void setAutoCreateIndex(boolean autoCreateIndex) { this.autoCreateIndex = autoCreateIndex; } public @Nullable String getUserName() { return this.userName; } public void setUserName(@Nullable String userName) { this.userName = userName; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public @Nullable String getPipeline() { return this.pipeline; } public void setPipeline(@Nullable String pipeline) { this.pipeline = pipeline; }
public @Nullable String getApiKeyCredentials() { return this.apiKeyCredentials; } public void setApiKeyCredentials(@Nullable String apiKeyCredentials) { this.apiKeyCredentials = apiKeyCredentials; } public boolean isEnableSource() { return this.enableSource; } public void setEnableSource(boolean enableSource) { this.enableSource = enableSource; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticProperties.java
2
请完成以下Java代码
public static void main(String[] args) { try { getMQMsg(); } catch (Exception e) { e.printStackTrace(); } } public static void getMQMsg() throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://x.x.x.x:61616"); Connection connection = connectionFactory.createConnection("admin","admin"); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue("queuename"); QueueBrowser queueBrowser = session.createBrowser(queue); Enumeration msgs = queueBrowser.getEnumeration(); List<String> temp = new ArrayList<>(); while (msgs.hasMoreElements()) {
try { ActiveMQTextMessage msg = (ActiveMQTextMessage)msgs.nextElement(); JSONObject jsonObject = JSON.parseObject(msg.getText()); temp.add(jsonObject.getString("ResumeId")); } catch (Exception e) { e.printStackTrace(); } } System.out.println("save to file"); try { IOUtils.writeLines(temp,"\n",new FileOutputStream(new File("D:\\activemq-resume-msg.txt")), Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } } }
repos\spring-boot-quick-master\quick-activemq\src\main\java\com\mq\utils\ExtractMsgUtil.java
1
请完成以下Java代码
public void setProduct_BaseFolderName (final String Product_BaseFolderName) { set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName); } @Override public String getProduct_BaseFolderName() { return get_ValueAsString(COLUMNNAME_Product_BaseFolderName); } @Override public void setTCP_Host (final String TCP_Host) { set_Value (COLUMNNAME_TCP_Host, TCP_Host); } @Override
public String getTCP_Host() { return get_ValueAsString(COLUMNNAME_TCP_Host); } @Override public void setTCP_PortNumber (final int TCP_PortNumber) { set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber); } @Override public int getTCP_PortNumber() { return get_ValueAsInt(COLUMNNAME_TCP_PortNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java
1
请完成以下Java代码
public class DefaultAdminRuntimeDelegate extends AbstractAppRuntimeDelegate<AdminPlugin> implements AdminRuntimeDelegate { private static final List<String> MAPPING_FILES = List.of( "org/camunda/bpm/admin/plugin/base/queries/metrics.xml" ); protected final Map<String, CommandExecutor> commandExecutors; public DefaultAdminRuntimeDelegate() { super(AdminPlugin.class); this.commandExecutors = new HashMap<>(); } @Override public QueryService getQueryService(String processEngineName) { CommandExecutor commandExecutor = getCommandExecutor(processEngineName); return new QueryServiceImpl(commandExecutor); } public CommandExecutor getCommandExecutor(String processEngineName) { CommandExecutor commandExecutor = commandExecutors.get(processEngineName); if (commandExecutor == null) { commandExecutor = createCommandExecutor(processEngineName); commandExecutors.put(processEngineName, commandExecutor); } return commandExecutor; }
/** * Create command executor for the engine with the given name * * @param processEngineName the process engine name * @return the command executor */ protected CommandExecutor createCommandExecutor(String processEngineName) { ProcessEngine processEngine = getProcessEngine(processEngineName); if (processEngine == null) { throw new ProcessEngineException("No process engine with name " + processEngineName + " found."); } ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) processEngine) .getProcessEngineConfiguration(); return new CommandExecutorImpl(processEngineConfiguration, MAPPING_FILES); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\DefaultAdminRuntimeDelegate.java
1
请完成以下Java代码
public class MergeArraysAndRemoveDuplicate { public static int[] removeDuplicateOnSortedArray(int[] arr) { // Initialize a new array to store unique elements int[] uniqueArray = new int[arr.length]; uniqueArray[0] = arr[0]; int uniqueCount = 1; // Iterate through the sorted array to remove duplicates for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { uniqueArray[uniqueCount] = arr[i]; uniqueCount++; } } int[] truncatedArray = new int[uniqueCount]; System.arraycopy(uniqueArray, 0, truncatedArray, 0, uniqueCount); return truncatedArray; } public static int[] mergeAndRemoveDuplicatesUsingStream(int[] arr1, int[] arr2) { Stream<Integer> s1 = Arrays.stream(arr1).boxed(); Stream<Integer> s2 = Arrays.stream(arr2).boxed(); return Stream.concat(s1, s2) .distinct() .mapToInt(Integer::intValue) .toArray(); } public static int[] mergeAndRemoveDuplicatesUsingSet(int[] arr1, int[] arr2) { int[] mergedArr = mergeArrays(arr1, arr2); Set<Integer> uniqueInts = new HashSet<>(); for (int el : mergedArr) { uniqueInts.add(el); } return getArrayFromSet(uniqueInts); } private static int[] getArrayFromSet(Set<Integer> set) { int[] mergedArrWithoutDuplicated = new int[set.size()]; int i = 0; for (Integer el: set) { mergedArrWithoutDuplicated[i] = el; i++; } return mergedArrWithoutDuplicated; } public static int[] mergeAndRemoveDuplicates(int[] arr1, int[] arr2) { return removeDuplicate(mergeArrays(arr1, arr2)); } public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) { return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2)); } private static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArrays = new int[arr1.length + arr2.length]; System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length); System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length); return mergedArrays; } private static int[] removeDuplicate(int[] arr) { int[] withoutDuplicates = new int[arr.length]; int i = 0; for(int element : arr) { if(!isElementPresent(withoutDuplicates, element)) { withoutDuplicates[i] = element; i++; } } int[] truncatedArray = new int[i]; System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i); return truncatedArray; } private static boolean isElementPresent(int[] arr, int element) { for(int el : arr) { if(el == element) { return true; } } return false; } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\mergeandremoveduplicate\MergeArraysAndRemoveDuplicate.java
1
请完成以下Java代码
private static final class WarUrlStreamHandlerFactory implements URLStreamHandlerFactory { @Override public @Nullable URLStreamHandler createURLStreamHandler(String protocol) { if ("war".equals(protocol)) { return new WarUrlStreamHandler(); } return null; } } /** * {@link URLStreamHandler} for {@literal war} protocol compatible with jasper's * {@link URL urls} produced by * {@link org.apache.tomcat.util.scan.JarFactory#getJarEntryURL(URL, String)}. */ private static final class WarUrlStreamHandler extends URLStreamHandler { @Override protected void parseURL(URL u, String spec, int start, int limit) { String path = "jar:" + spec.substring("war:".length()); int separator = path.indexOf("*/"); if (separator >= 0) { path = path.substring(0, separator) + "!/" + path.substring(separator + 2); } setURL(u, u.getProtocol(), "", -1, null, null, path, null, null); } @Override protected URLConnection openConnection(URL u) throws IOException { return new WarURLConnection(u); } } /** * {@link URLConnection} to support {@literal war} protocol. */ private static class WarURLConnection extends URLConnection {
private final URLConnection connection; protected WarURLConnection(URL url) throws IOException { super(url); this.connection = new URL(url.getFile()).openConnection(); } @Override public void connect() throws IOException { if (!this.connected) { this.connection.connect(); this.connected = true; } } @Override public InputStream getInputStream() throws IOException { connect(); return this.connection.getInputStream(); } } }
repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\servlet\JasperInitializer.java
1
请完成以下Java代码
private ISideActionsGroupModel getCreateSideActionsGroupFor(final IFacetCategory facetCategory) { final String displayName = facetCategory.getDisplayName(); final boolean defaultCollapsed = facetCategory.isCollapsed(); final String groupId = getClass().getName() + "." + displayName; final ISideActionsGroupsListModel actionsGroupsListModel = getSideActionsGroupsModel(); ISideActionsGroupModel group = actionsGroupsListModel.getGroupByIdOrNull(groupId); if (group == null) { group = new SideActionsGroupModel(groupId, displayName, defaultCollapsed); actionsGroupsListModel.addGroup(group); this.ownActionGroups.add(group); } return group; } @Override
public Set<IFacet<ModelType>> getActiveFacets() { final Set<IFacet<ModelType>> activeFacets = new HashSet<>(); for (final FacetSideAction<ModelType> action : ownActions.values()) { // Skip actions which are not active (i.e. checkbox set by user) if (!action.isToggled()) { continue; } final IFacet<ModelType> facet = action.getFacet(); activeFacets.add(facet); } return activeFacets; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\sideactions\impl\SideActionFacetsPool.java
1
请在Spring Boot框架中完成以下Java代码
public class RateLimitsTriggerProcessor implements NotificationRuleTriggerProcessor<RateLimitsTrigger, RateLimitsNotificationRuleTriggerConfig> { private final TenantService tenantService; private final EntityService entityService; @Override public boolean matchesFilter(RateLimitsTrigger trigger, RateLimitsNotificationRuleTriggerConfig triggerConfig) { return trigger.getLimitLevel() != null && trigger.getApi().getLabel() != null && CollectionsUtil.emptyOrContains(triggerConfig.getApis(), trigger.getApi()); } @Override public RuleOriginatedNotificationInfo constructNotificationInfo(RateLimitsTrigger trigger) { EntityId limitLevel = trigger.getLimitLevel(); String tenantName = tenantService.findTenantById(trigger.getTenantId()).getName(); String limitLevelEntityName = null; if (limitLevel instanceof TenantId) { limitLevelEntityName = tenantName; } else if (limitLevel != null) {
limitLevelEntityName = Optional.ofNullable(trigger.getLimitLevelEntityName()) .orElseGet(() -> entityService.fetchEntityName(trigger.getTenantId(), limitLevel).orElse(null)); } return RateLimitsNotificationInfo.builder() .tenantId(trigger.getTenantId()) .tenantName(tenantName) .api(trigger.getApi()) .limitLevel(limitLevel) .limitLevelEntityName(limitLevelEntityName) .build(); } @Override public NotificationRuleTriggerType getTriggerType() { return NotificationRuleTriggerType.RATE_LIMITS; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\RateLimitsTriggerProcessor.java
2
请完成以下Java代码
private static final PlainContextAware createPlainContextAware(final Object model) { final IContextAware contextAware = InterfaceWrapperHelper.getContextAware(model); final PlainContextAware contextAwarePlainCopy = PlainContextAware.newCopy(contextAware); return contextAwarePlainCopy; } /** * Load items from database. */ private final void loadItems() { final PT parentModel = getParentModel(); final IContextAware ctx = createPlainContextAware(parentModel); // // Retrieve fresh items final List<T> items = retrieveItems(ctx, parentModel); // // Update status this.ctx = ctx; this.items = items == null ? null : new ArrayList<T>(items); // NOTE: we need to do a copy just in case we get an unmodifiable list this.parentModelLoadCount = InterfaceWrapperHelper.getLoadCount(parentModel); this.debugEmptyNotStaledSet = false; } /** * Sets an empty inner list and flag this list as not staled anymore. * * To be used after parent model is created, to start maintaining this list from the very beginning. */ public final void setEmptyNotStaled() { final PT parentModel = getParentModel(); this.ctx = createPlainContextAware(parentModel); this.items = new ArrayList<T>(); this.debugEmptyNotStaledSet = true; debugCheckItemsValid(); } private final void debugCheckItemsValid() { if (!DEBUG)
{ return; } final PT parentModel = getParentModel(); final IContextAware ctx = createPlainContextAware(parentModel); final boolean instancesTrackerEnabled = POJOLookupMapInstancesTracker.ENABLED; POJOLookupMapInstancesTracker.ENABLED = false; try { // // Retrieve fresh items final List<T> itemsRetrievedNow = retrieveItems(ctx, parentModel); if (itemsComparator != null) { Collections.sort(itemsRetrievedNow, itemsComparator); } if (!Objects.equals(this.items, itemsRetrievedNow)) { final int itemsCount = this.items == null ? 0 : this.items.size(); final int itemsRetrievedNowCount = itemsRetrievedNow.size(); throw new AdempiereException("Loaded items and cached items does not match." + "\n Parent: " + parentModelRef.get() + "\n Cached items(" + itemsCount + "): " + this.items + "\n Fresh items(" + itemsRetrievedNowCount + "): " + itemsRetrievedNow + "\n debugEmptyNotStaledSet=" + debugEmptyNotStaledSet // ); } } finally { POJOLookupMapInstancesTracker.ENABLED = instancesTrackerEnabled; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\cache\AbstractModelListCacheLocal.java
1
请完成以下Java代码
public String getAD_Message() { return adMessage; } public KeyStroke getKeyStroke() { return keyStroke; } } /** * Execute cut/copy/paste action of given type. * * @param actionType */ void executeCopyPasteAction(final CopyPasteActionType actionType); /** * Gets the copy/paste {@link Action} associated with given type.
* * @param actionType * @return action or <code>null</code> */ Action getCopyPasteAction(final CopyPasteActionType actionType); /** * Associate given action with given action type. * * @param actionType * @param action * @param keyStroke optional key stroke to be binded to given action. */ void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke); /** * @param actionType * @return true if given action can be performed */ boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\ICopyPasteSupportEditor.java
1
请完成以下Java代码
public CaseSentryPartQueryImpl orderByCaseInstanceId() { orderBy(CaseSentryPartQueryProperty.CASE_INSTANCE_ID); return this; } public CaseSentryPartQueryImpl orderByCaseExecutionId() { orderBy(CaseSentryPartQueryProperty.CASE_EXECUTION_ID); return this; } public CaseSentryPartQueryImpl orderBySentryId() { orderBy(CaseSentryPartQueryProperty.SENTRY_ID); return this; } public CaseSentryPartQueryImpl orderBySource() { orderBy(CaseSentryPartQueryProperty.SOURCE); return this; } // results //////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getCaseSentryPartManager() .findCaseSentryPartCountByQueryCriteria(this); } public List<CaseSentryPartEntity> executeList(CommandContext commandContext, Page page) { checkQueryOk(); List<CaseSentryPartEntity> result = commandContext .getCaseSentryPartManager() .findCaseSentryPartByQueryCriteria(this, page); return result; } // getters ///////////////////////////////////////////// public String getId() { return id; } public String getCaseInstanceId() {
return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public String getSentryId() { return sentryId; } public String getType() { return type; } public String getSourceCaseExecutionId() { return sourceCaseExecutionId; } public String getStandardEvent() { return standardEvent; } public String getVariableEvent() { return variableEvent; } public String getVariableName() { return variableName; } public boolean isSatisfied() { return satisfied; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartQueryImpl.java
1
请完成以下Java代码
public CountResultDto getHistoricTaskInstancesCount(UriInfo uriInfo) { HistoricTaskInstanceQueryDto queryDto = new HistoricTaskInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); return queryHistoricTaskInstancesCount(queryDto); } @Override public CountResultDto queryHistoricTaskInstancesCount(HistoricTaskInstanceQueryDto queryDto) { queryDto.setObjectMapper(objectMapper); HistoricTaskInstanceQuery query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } @Override public Response getHistoricTaskInstanceReport(UriInfo uriInfo) { HistoricTaskInstanceReportQueryDto queryDto = new HistoricTaskInstanceReportQueryDto(objectMapper, uriInfo.getQueryParameters()); Response response; if (AbstractReportDto.REPORT_TYPE_DURATION.equals(queryDto.getReportType())) { List<? extends ReportResult> reportResults = queryDto.executeReport(processEngine); response = Response.ok(generateDurationDto(reportResults)).build(); } else if (AbstractReportDto.REPORT_TYPE_COUNT.equals(queryDto.getReportType())) { List<HistoricTaskInstanceReportResult> reportResults = queryDto.executeCompletedReport(processEngine); response = Response.ok(generateCountDto(reportResults)).build(); } else { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Parameter reportType is not set."); } return response; } protected List<HistoricTaskInstanceReportResultDto> generateCountDto(List<HistoricTaskInstanceReportResult> results) { List<HistoricTaskInstanceReportResultDto> dtoList = new ArrayList<HistoricTaskInstanceReportResultDto>();
for( HistoricTaskInstanceReportResult result : results ) { dtoList.add(HistoricTaskInstanceReportResultDto.fromHistoricTaskInstanceReportResult(result)); } return dtoList; } protected List<ReportResultDto> generateDurationDto(List<? extends ReportResult> results) { List<ReportResultDto> dtoList = new ArrayList<ReportResultDto>(); for( ReportResult result : results ) { dtoList.add(ReportResultDto.fromReportResult(result)); } return dtoList; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricTaskInstanceRestServiceImpl.java
1
请完成以下Java代码
public String toString() { return "Graph{" + "vertexes=" + Arrays.toString(vertexes) + ", edgesTo=" + Arrays.toString(edgesTo) + '}'; } public String printByTo() { StringBuffer sb = new StringBuffer(); sb.append("========按终点打印========\n"); for (int to = 0; to < edgesTo.length; ++to) { List<EdgeFrom> edgeFromList = edgesTo[to]; for (EdgeFrom edgeFrom : edgeFromList) { sb.append(String.format("to:%3d, from:%3d, weight:%05.2f, word:%s\n", to, edgeFrom.from, edgeFrom.weight, edgeFrom.name)); } } return sb.toString(); } /** * 根据节点下标数组解释出对应的路径 * @param path * @return */ public List<Vertex> parsePath(int[] path) { List<Vertex> vertexList = new LinkedList<Vertex>(); for (int i : path) { vertexList.add(vertexes[i]); } return vertexList; } /** * 从一个路径中转换出空格隔开的结果 * @param path
* @return */ public static String parseResult(List<Vertex> path) { if (path.size() < 2) { throw new RuntimeException("路径节点数小于2:" + path); } StringBuffer sb = new StringBuffer(); for (int i = 1; i < path.size() - 1; ++i) { Vertex v = path.get(i); sb.append(v.getRealWord() + " "); } return sb.toString(); } public Vertex[] getVertexes() { return vertexes; } public List<EdgeFrom>[] getEdgesTo() { return edgesTo; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\Graph.java
1
请完成以下Java代码
public static void setCurrentTime(Date currentTime) { DateTimeUtils.setCurrentMillisFixed(currentTime.getTime()); } public static void reset() { resetClock(); } public static Date getCurrentTime() { return now(); } public static Date now() { return new Date(DateTimeUtils.currentTimeMillis()); } /** * Moves the clock by the given offset and keeps it running from that point * on.
* * @param offsetInMillis * the offset to move the clock by * @return the new 'now' */ public static Date offset(Long offsetInMillis) { DateTimeUtils.setCurrentMillisOffset(offsetInMillis); return new Date(DateTimeUtils.currentTimeMillis()); } public static Date resetClock() { DateTimeUtils.setCurrentMillisSystem(); return new Date(DateTimeUtils.currentTimeMillis()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ClockUtil.java
1
请完成以下Java代码
public class PackageItem { private int productId; private float weight; private float estimatedValue; public PackageItem(int productId, float weight, float estimatedValue) { this.productId = productId; this.weight = weight; this.estimatedValue = estimatedValue; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; }
public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public float getEstimatedValue() { return estimatedValue; } public void setEstimatedValue(float estimatedValue) { this.estimatedValue = estimatedValue; } }
repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-shippingcontext\src\main\java\com\baeldung\dddcontexts\shippingcontext\model\PackageItem.java
1
请完成以下Java代码
public Mono<UserView> signup(UserRegistrationRequest request) { return credentialsService.signup(request); } public Mono<UserView> login(UserAuthenticationRequest request) { return credentialsService.login(request); } public Mono<UserView> updateUser(UpdateUserRequest request, UserSession userSession) { var user = userSession.user(); var token = userSession.token(); return userUpdater.updateUser(request, user) .flatMap(userRepository::save) .map(it -> UserView.fromUserAndToken(it, token)); } public Mono<ProfileView> follow(String username, User follower) {
return userRepository.findByUsernameOrFail(username) .flatMap(userToFollow -> { follower.follow(userToFollow); return userRepository.save(follower).thenReturn(userToFollow); }) .map(ProfileView::toFollowedProfileView); } public Mono<ProfileView> unfollow(String username, User follower) { return userRepository.findByUsernameOrFail(username) .flatMap(userToUnfollow -> { follower.unfollow(userToUnfollow); return userRepository.save(follower).thenReturn(userToUnfollow); }) .map(ProfileView::toUnfollowedProfileView); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\UserFacade.java
1
请完成以下Java代码
public int getAD_OrgTrx_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgTrx_ID); if (ii == null) return 0; return ii.intValue(); } @Override protected final GenericPO newInstance() { return new GenericPO(tableName, getCtx(), ID_NewInstanceNoInit); } @Override public final PO copy() { final GenericPO po = (GenericPO)super.copy(); po.tableName = this.tableName; po.tableID = this.tableID; return po; } } // GenericPO
/** * Wrapper class to workaround the limit of PO constructor that doesn't take a tableName or * tableID parameter. Note that in the generated class scenario ( X_ ), tableName and tableId * is generated as a static field. * * @author Low Heng Sin * */ final class PropertiesWrapper extends Properties { /** * */ private static final long serialVersionUID = 8887531951501323594L; protected Properties source; protected String tableName; PropertiesWrapper(Properties source, String tableName) { this.source = source; this.tableName = tableName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GenericPO.java
1
请在Spring Boot框架中完成以下Java代码
public class Book extends BaseEntity<String> implements Serializable { private static final long serialVersionUID = 1L; private String title; private String isbn; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "author_id") private Author author; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } @Override public boolean equals(Object obj) {
if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public Map<String, String> getVariables() { return this.variables; } /** * Creates an instance of {@link MatchResult} that is a match with no variables */ public static MatchResult match() { return new MatchResult(true, Collections.emptyMap()); } /** * Creates an instance of {@link MatchResult} that is a match with the specified * variables */
public static MatchResult match(Map<String, String> variables) { return new MatchResult(true, variables); } /** * Creates an instance of {@link MatchResult} that is not a match. * @return a {@code MatchResult} with match set to false */ public static MatchResult notMatch() { return new MatchResult(false, Collections.emptyMap()); } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\util\matcher\MessageMatcher.java
1
请完成以下Java代码
public class ActionDefinition { private String id; private String name; private String description; private List<VariableDefinition> inputs; private List<VariableDefinition> outputs; public String getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public List<VariableDefinition> getInputs() { return inputs != null ? inputs : emptyList(); } public List<VariableDefinition> getOutputs() { return outputs != null ? outputs : emptyList(); }
public void setId(String id) { this.id = id; } public void setName(String name) { this.name = name; } public void setDescription(String description) { this.description = description; } public void setInputs(List<VariableDefinition> inputs) { this.inputs = inputs; } public void setOutputs(List<VariableDefinition> outputs) { this.outputs = outputs; } }
repos\Activiti-develop\activiti-core-common\activiti-connector-model\src\main\java\org\activiti\core\common\model\connector\ActionDefinition.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal toRealValueAsBigDecimal() {return toRealValueAsMoney().toBigDecimal();} public boolean isAP() {return multiplier.isAP();} public boolean isAPAdjusted() {return multiplier.isAPAdjusted();} public boolean isCreditMemo() {return multiplier.isCreditMemo();} public boolean isCMAdjusted() {return multiplier.isCreditMemoAdjusted();} public InvoiceTotal withAPAdjusted(final boolean isAPAdjusted) { return isAPAdjusted ? withAPAdjusted() : withoutAPAdjusted(); } public InvoiceTotal withAPAdjusted() { if (multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(true)); } } public InvoiceTotal withoutAPAdjusted() { if (!multiplier.isAPAdjusted()) { return this; } else if (multiplier.isAP()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withAPAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withAPAdjusted(false)); } } public InvoiceTotal withCMAdjusted(final boolean isCMAdjusted) { return isCMAdjusted ? withCMAdjusted() : withoutCMAdjusted();
} public InvoiceTotal withCMAdjusted() { if (multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(true)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(true)); } } public InvoiceTotal withoutCMAdjusted() { if (!multiplier.isCreditMemoAdjusted()) { return this; } else if (multiplier.isCreditMemo()) { return new InvoiceTotal(relativeValue.negate(), multiplier.withCMAdjusted(false)); } else { return new InvoiceTotal(relativeValue, multiplier.withCMAdjusted(false)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceTotal.java
2
请完成以下Java代码
public Double getMultiplier() { return this.multiplier; } /** * Specify a multiplier for a delay for the next retry attempt. * @param multiplier value to multiply the current interval by for each attempt (must * be greater than or equal to 1) */ public void setMultiplier(Double multiplier) { this.multiplier = multiplier; } /** * Return the maximum delay for any retry attempt. * @return the maximum delay */ public Duration getMaxDelay() { return this.maxDelay; } /** * Specify the maximum delay for any retry attempt, limiting how far * {@linkplain #getJitter() jitter} and the {@linkplain #getMultiplier() multiplier} * can increase the {@linkplain #getDelay() delay}. * <p> * The default is unlimited. * @param maxDelay the maximum delay (must be positive) * @see #DEFAULT_MAX_DELAY */
public void setMaxDelay(Duration maxDelay) { this.maxDelay = maxDelay; } /** * Set the factory to use to create the {@link RetryPolicy}, or {@code null} to use * the default. The function takes a {@link Builder RetryPolicy.Builder} initialized * with the state of this instance that can be further configured, or ignored to * restart from scratch. * @param factory a factory to customize the retry policy. */ public void setFactory(@Nullable Function<RetryPolicy.Builder, RetryPolicy> factory) { this.factory = factory; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\retry\RetryPolicySettings.java
1
请完成以下Java代码
public abstract class PvmAtomicOperationCancelActivity implements PvmAtomicOperation { public void execute(PvmExecutionImpl execution) { // Assumption: execution is scope PvmActivity cancellingActivity = execution.getNextActivity(); execution.setNextActivity(null); // first, cancel and destroy the current scope execution.setActive(true); PvmExecutionImpl propagatingExecution = null; if(LegacyBehavior.isConcurrentScope(execution)) { // this is legacy behavior LegacyBehavior.cancelConcurrentScope(execution, (PvmActivity) cancellingActivity.getEventScope()); propagatingExecution = execution; } else { // Unlike PvmAtomicOperationTransitionDestroyScope this needs to use delete() (instead of destroy() and remove()). // The reason is that PvmAtomicOperationTransitionDestroyScope is executed when a scope (or non scope) is left using // a sequence flow. In that case the execution will have completed all the work inside the current activity // and will have no more child executions. In PvmAtomicOperationCancelScope the scope is cancelled due to // a boundary event firing. In that case the execution has not completed all the work in the current scope / activity // and it is necessary to delete the complete hierarchy of executions below and including the execution itself. execution.deleteCascade("Cancel scope activity "+cancellingActivity+" executed."); propagatingExecution = execution.getParent(); } propagatingExecution.setActivity(cancellingActivity); setDelayedPayloadToNewScope(propagatingExecution, (CoreModelElement) cancellingActivity); propagatingExecution.setActive(true); propagatingExecution.setEnded(false); activityCancelled(propagatingExecution); } protected abstract void activityCancelled(PvmExecutionImpl execution);
public boolean isAsync(PvmExecutionImpl execution) { return false; } protected void setDelayedPayloadToNewScope(PvmExecutionImpl execution, CoreModelElement scope) { String activityType = (String) scope.getProperty(BpmnProperties.TYPE.getName()); if (ActivityTypes.START_EVENT_MESSAGE.equals(activityType) // Event subprocess message start event || ActivityTypes.BOUNDARY_MESSAGE.equals(activityType)) { PvmExecutionImpl processInstance = execution.getProcessInstance(); if (processInstance.getPayloadForTriggeredScope() != null) { execution.setVariablesLocal(processInstance.getPayloadForTriggeredScope()); // clear the process instance processInstance.setPayloadForTriggeredScope(null); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationCancelActivity.java
1
请在Spring Boot框架中完成以下Java代码
public static class AppEngineRestApiConfiguration extends BaseRestApiConfiguration { @Bean public ServletRegistrationBean appServlet(FlowableAppProperties properties) { return registerServlet(properties.getServlet(), AppEngineRestConfiguration.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CmmnRestUrls.class) @ConditionalOnBean(CmmnEngine.class) public static class CmmnEngineRestApiConfiguration extends BaseRestApiConfiguration { @Bean public ServletRegistrationBean cmmnServlet(FlowableCmmnProperties properties) { return registerServlet(properties.getServlet(), CmmnEngineRestConfiguration.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DmnRestUrls.class) @ConditionalOnBean(DmnEngine.class) public static class DmnEngineRestApiConfiguration extends BaseRestApiConfiguration { @Bean public ServletRegistrationBean dmnServlet(FlowableDmnProperties properties) { return registerServlet(properties.getServlet(), DmnEngineRestConfiguration.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(EventRestUrls.class) @ConditionalOnBean(EventRegistryEngine.class) public static class EventRegistryRestApiConfiguration extends BaseRestApiConfiguration {
@Bean public ServletRegistrationBean eventRegistryServlet(FlowableEventRegistryProperties properties) { return registerServlet(properties.getServlet(), EventRegistryRestConfiguration.class); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(IdmRestResponseFactory.class) @ConditionalOnBean(IdmEngine.class) public static class IdmEngineRestApiConfiguration extends BaseRestApiConfiguration { @Bean public ServletRegistrationBean idmServlet(FlowableIdmProperties properties) { return registerServlet(properties.getServlet(), IdmEngineRestConfiguration.class); } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\RestApiAutoConfiguration.java
2
请完成以下Java代码
private PIAttributes createPIAttributes(final List<I_M_HU_Attribute> huAttributes) { final IHUPIAttributesDAO piAttributesRepo = Services.get(IHUPIAttributesDAO.class); final ImmutableSet<Integer> piAttributeIds = huAttributes.stream().map(I_M_HU_Attribute::getM_HU_PI_Attribute_ID).collect(ImmutableSet.toImmutableSet()); return piAttributesRepo.retrievePIAttributesByIds(piAttributeIds); } private List<I_M_HU_Attribute> retrieveAttributes(final I_M_HU hu, @NonNull final AttributeId attributeId) { final List<I_M_HU_Attribute> huAttributes = Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Attribute.class, hu) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_HU_Attribute.COLUMNNAME_M_HU_ID, hu.getM_HU_ID()) .addEqualsFilter(I_M_HU_Attribute.COLUMNNAME_M_Attribute_ID, attributeId) .create() .list(I_M_HU_Attribute.class); // Optimization: set M_HU link for (final I_M_HU_Attribute huAttribute : huAttributes) { huAttribute.setM_HU(hu); } return huAttributes; } @Override @Nullable public I_M_HU_Attribute retrieveAttribute(final I_M_HU hu, final AttributeId attributeId) {
final List<I_M_HU_Attribute> huAttributes = retrieveAttributes(hu, attributeId); if (huAttributes.isEmpty()) { return null; } else if (huAttributes.size() == 1) { return huAttributes.get(0); } else { throw new AdempiereException("More than one HU Attributes were found for '" + attributeId + "' on " + hu.getM_HU_ID() + ": " + huAttributes); } } @Override public void flush() { // nothing because there is no internal cache } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUAttributesDAO.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
repos\tutorials-master\spring-security-modules\spring-security-authorization\spring-security-url-http-method-auth\src\main\java\com\baeldung\springsecurity\entity\User.java
1
请完成以下Java代码
public SumQueryAggregateColumnBuilder<SourceModelType, TargetModelType> setDynAttribute(final ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute) { this.dynAttribute = dynAttribute; return this; } @Override public ModelDynAttributeAccessor<TargetModelType, BigDecimal> getDynAttribute() { Check.assumeNotNull(dynAttribute, "dynAttribute not null"); return dynAttribute; } @Override public IAggregator<BigDecimal, SourceModelType> createAggregator(final TargetModelType targetModel) { Check.assumeNotNull(targetModel, "targetModel not null"); return new IAggregator<BigDecimal, SourceModelType>() { private final ICompositeQueryFilter<SourceModelType> filters = SumQueryAggregateColumnBuilder.this.filters.copy(); private final ModelDynAttributeAccessor<TargetModelType, BigDecimal> dynAttribute = SumQueryAggregateColumnBuilder.this.dynAttribute; private BigDecimal sum = BigDecimal.ZERO; @Override
public void add(final SourceModelType model) { if (filters.accept(model)) { final Optional<BigDecimal> value = InterfaceWrapperHelper.getValue(model, getAmountColumnName()); if (value.isPresent()) { sum = sum.add(value.get()); } } // Update target model's dynamic attribute dynAttribute.setValue(targetModel, sum); } @Override public BigDecimal getValue() { return sum; } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\SumQueryAggregateColumnBuilder.java
1
请完成以下Java代码
public <T extends I_M_ShipmentSchedule_QtyPicked> ImmutableListMultimap<ShipmentScheduleId, T> retrieveNotOnShipmentLineRecordsByScheduleIds( @NonNull final Set<ShipmentScheduleId> scheduleIds, @NonNull Class<T> type) { return retrieveRecordsByScheduleIds( ShipmentScheduleAndJobScheduleIdSet.ofShipmentScheduleIds(scheduleIds), false, type); } @Override public ImmutableListMultimap<ShipmentScheduleId, I_M_ShipmentSchedule_QtyPicked> retrieveOnShipmentLineRecordsByScheduleIds(@NonNull final Set<ShipmentScheduleId> scheduleIds) { return retrieveOnShipmentLineRecordsByScheduleIds(ShipmentScheduleAndJobScheduleIdSet.ofShipmentScheduleIds(scheduleIds)); } @Override public ImmutableListMultimap<ShipmentScheduleId, I_M_ShipmentSchedule_QtyPicked> retrieveOnShipmentLineRecordsByScheduleIds(@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return retrieveRecordsByScheduleIds( scheduleIds, true, I_M_ShipmentSchedule_QtyPicked.class); } private <T extends I_M_ShipmentSchedule_QtyPicked> ImmutableListMultimap<ShipmentScheduleId, T> retrieveRecordsByScheduleIds( @NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds, final boolean onShipmentLine, @NonNull final Class<T> type) { if (scheduleIds.isEmpty()) { return ImmutableListMultimap.of(); } return stream( type, ShipmentScheduleAllocQuery.builder() .scheduleIds(scheduleIds) .alreadyShipped(onShipmentLine) .build() ) .collect(ImmutableListMultimap.toImmutableListMultimap( record -> ShipmentScheduleId.ofRepoId(record.getM_ShipmentSchedule_ID()), record -> record )); } @NonNull
public <T extends I_M_ShipmentSchedule_QtyPicked> List<T> retrievePickedOnTheFlyAndNotDelivered( @NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull final Class<T> modelClass) { return queryBL .createQueryBuilder(I_M_ShipmentSchedule_QtyPicked.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleId) .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_Processed, false) .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_IsAnonymousHuPickedOnTheFly, true) .create() .list(modelClass); } @Override @NonNull public Set<OrderId> retrieveOrderIds(@NonNull final org.compiere.model.I_M_InOut inOut) { return queryBL.createQueryBuilder(I_M_InOutLine.class, inOut) .addEqualsFilter(I_M_InOutLine.COLUMN_M_InOut_ID, inOut.getM_InOut_ID()) .andCollectChildren(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_InOutLine_ID, I_M_ShipmentSchedule_QtyPicked.class) .andCollect(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_ShipmentSchedule_ID) .andCollect(I_M_ShipmentSchedule.COLUMN_C_Order_ID) .create() .listIds() .stream() .map(OrderId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleAllocDAO.java
1
请完成以下Java代码
public static CreateMatchInvoicePlan ofList(List<CreateMatchInvoicePlanLine> lines) { return new CreateMatchInvoicePlan(lines); } public boolean isEmpty() { return lines.isEmpty(); } @Override public Iterator<CreateMatchInvoicePlanLine> iterator() { return lines.iterator(); } public void setCostAmountInvoiced(@NonNull final Money invoicedAmt, @NonNull final CurrencyPrecision precision) { final CurrencyId currencyId = invoicedAmt.getCurrencyId(); final Money totalCostAmountInOut = getCostAmountInOut(); final Money totalInvoicedAmtDiff = invoicedAmt.subtract(totalCostAmountInOut); if (totalInvoicedAmtDiff.isZero()) { return; } if (isEmpty()) { throw new AdempiereException("Cannot spread invoice amount difference if there is no line"); } Money totalInvoicedAmtDiffDistributed = Money.zero(currencyId); for (int i = 0, lastIndex = lines.size() - 1; i <= lastIndex; i++)
{ final CreateMatchInvoicePlanLine line = lines.get(i); final Money lineCostAmountInOut = line.getCostAmountInOut(); final Money lineInvoicedAmtDiff; if (i != lastIndex) { final Percent percentage = lineCostAmountInOut.percentageOf(totalCostAmountInOut); lineInvoicedAmtDiff = totalInvoicedAmtDiff.multiply(percentage, precision); } else { lineInvoicedAmtDiff = totalInvoicedAmtDiff.subtract(totalInvoicedAmtDiffDistributed); } line.setCostAmountInvoiced(lineCostAmountInOut.add(lineInvoicedAmtDiff)); totalInvoicedAmtDiffDistributed = totalInvoicedAmtDiffDistributed.add(lineInvoicedAmtDiff); } } private Money getCostAmountInOut() { return lines.stream().map(CreateMatchInvoicePlanLine::getCostAmountInOut).reduce(Money::add) .orElseThrow(() -> new AdempiereException("No lines")); // shall not happen } public Money getInvoicedAmountDiff() { return lines.stream().map(CreateMatchInvoicePlanLine::getInvoicedAmountDiff).reduce(Money::add) .orElseThrow(() -> new AdempiereException("No lines")); // shall not happen } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\invoice\CreateMatchInvoicePlan.java
1
请完成以下Java代码
public Builder setDisplayName(final ITranslatableString displayNameTrls) { this.displayNameTrls = displayNameTrls; return this; } public Builder setDisplayName(final String displayName) { displayNameTrls = TranslatableStrings.constant(displayName); return this; } public Builder setDisplayName(final AdMessageKey displayName) { return setDisplayName(TranslatableStrings.adMessage(displayName)); } @Nullable public ITranslatableString getDisplayNameTrls() { if (displayNameTrls != null) { return displayNameTrls; } if (parameters.size() == 1) { return parameters.get(0).getDisplayName(); } return null; } public Builder setFrequentUsed(final boolean frequentUsed) { this.frequentUsed = frequentUsed; return this; } public Builder setInlineRenderMode(final DocumentFilterInlineRenderMode inlineRenderMode) { this.inlineRenderMode = inlineRenderMode; return this; } private DocumentFilterInlineRenderMode getInlineRenderMode() { return inlineRenderMode != null ? inlineRenderMode : DocumentFilterInlineRenderMode.BUTTON; } public Builder setParametersLayoutType(final PanelLayoutType parametersLayoutType) { this.parametersLayoutType = parametersLayoutType; return this; } private PanelLayoutType getParametersLayoutType() { return parametersLayoutType != null ? parametersLayoutType : PanelLayoutType.Panel; } public Builder setFacetFilter(final boolean facetFilter)
{ this.facetFilter = facetFilter; return this; } public boolean hasParameters() { return !parameters.isEmpty(); } public Builder addParameter(final DocumentFilterParamDescriptor.Builder parameter) { parameters.add(parameter); return this; } public Builder addInternalParameter(final String parameterName, final Object constantValue) { return addInternalParameter(DocumentFilterParam.ofNameEqualsValue(parameterName, constantValue)); } public Builder addInternalParameter(final DocumentFilterParam parameter) { internalParameters.add(parameter); return this; } public Builder putDebugProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); if (debugProperties == null) { debugProperties = new LinkedHashMap<>(); } debugProperties.put("debug-" + name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterDescriptor.java
1
请完成以下Java代码
public MediaSize getMediaSize() { return _mediaSize; } // getMediaSize /** * String Representation * * @return string representation */ @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("name", m_name) .add("AD_Language", m_AD_Language) .add("locale", m_locale) .add("decimalPoint", isDecimalPoint()) .toString(); } @Override public int hashCode() { return m_AD_Language.hashCode(); } // hashcode @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof Language) { final Language other = (Language)obj; return Objects.equals(this.m_AD_Language, other.m_AD_Language); } return false; } // equals private static int timeStyleDefault = DateFormat.MEDIUM;
/** * Sets default time style to be used when getting DateTime format or Time format. * * @param timeStyle one of {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM}, {@link DateFormat#LONG}. */ public static void setDefaultTimeStyle(final int timeStyle) { timeStyleDefault = timeStyle; } public static int getDefaultTimeStyle() { return timeStyleDefault; } public int getTimeStyle() { return getDefaultTimeStyle(); } private boolean matchesLangInfo(final String langInfo) { if (langInfo == null || langInfo.isEmpty()) { return false; } return langInfo.equals(getName()) || langInfo.equals(getAD_Language()) || langInfo.equals(getLanguageCode()); } } // Language
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\Language.java
1
请完成以下Java代码
public LogicExpressionBuilder addChild(final ILogicExpression child) { if (getLeft() == null) { setLeft(child); } else if (getRight() == null) { setRight(child); } else { throw new ExpressionCompileException("Cannot add " + child + " to " + this + " because both left and right are already filled"); } return this; } public LogicExpressionBuilder setOperator(final String operator) { this.operator = operator;
return this; } public ILogicExpression getLeft() { return left; } public ILogicExpression getRight() { return right; } public String getOperator() { return operator; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpressionBuilder.java
1
请完成以下Java代码
public class UserAttribute { private List<GrantedAuthority> authorities = new Vector<>(); private @Nullable String password; private boolean enabled = true; public void addAuthority(GrantedAuthority newAuthority) { this.authorities.add(newAuthority); } public List<GrantedAuthority> getAuthorities() { return this.authorities; } /** * Set all authorities for this user. * @param authorities {@link List} &lt;{@link GrantedAuthority}&gt; * @since 1.1 */ public void setAuthorities(List<GrantedAuthority> authorities) { this.authorities = authorities; } /** * Set all authorities for this user from String values. It will create the necessary * {@link GrantedAuthority} objects. * @param authoritiesAsStrings {@link List} &lt;{@link String}&gt; * @since 1.1 */ public void setAuthoritiesAsString(List<String> authoritiesAsStrings) { setAuthorities(new ArrayList<>(authoritiesAsStrings.size())); for (String authority : authoritiesAsStrings) { addAuthority(new SimpleGrantedAuthority(authority));
} } public @Nullable String getPassword() { return this.password; } public boolean isEnabled() { return this.enabled; } public boolean isValid() { return (this.password != null) && (this.authorities.size() > 0); } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setPassword(String password) { this.password = password; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\memory\UserAttribute.java
1
请完成以下Java代码
public void setHelp (final @Nullable java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setIsHUDestroyed (final boolean IsHUDestroyed) { set_Value (COLUMNNAME_IsHUDestroyed, IsHUDestroyed); } @Override public boolean isHUDestroyed() { return get_ValueAsBoolean(COLUMNNAME_IsHUDestroyed); } @Override public org.compiere.model.I_M_ChangeNotice getM_ChangeNotice() { return get_ValueAsPO(COLUMNNAME_M_ChangeNotice_ID, org.compiere.model.I_M_ChangeNotice.class); } @Override public void setM_ChangeNotice(final org.compiere.model.I_M_ChangeNotice M_ChangeNotice) { set_ValueFromPO(COLUMNNAME_M_ChangeNotice_ID, org.compiere.model.I_M_ChangeNotice.class, M_ChangeNotice); } @Override public void setM_ChangeNotice_ID (final int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_Value (COLUMNNAME_M_ChangeNotice_ID, null); else set_Value (COLUMNNAME_M_ChangeNotice_ID, M_ChangeNotice_ID); } @Override public int getM_ChangeNotice_ID() { return get_ValueAsInt(COLUMNNAME_M_ChangeNotice_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); }
@Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @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.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistribution.java
1
请在Spring Boot框架中完成以下Java代码
class WarehouseQuery { /** * Applied if not empty. {@code AND}ed with {@code externalId} if given. At least one of {@code value} or {@code externalId} needs to be given. */ String value; /** * Applied if not {@code null}. {@code AND}ed with {@code value} if given. At least one of {@code value} or {@code externalId} needs to be given. */ ExternalId externalId; OrgId orgId; boolean includeAnyOrg; boolean outOfTrx; @Builder private WarehouseQuery( @Nullable final String value, @Nullable final ExternalId externalId, @NonNull final OrgId orgId, @Nullable final Boolean includeAnyOrg, @Nullable final Boolean outOfTrx) { final boolean valueIsSet = !isEmpty(value, true); final boolean externalIdIsSet = externalId != null; assume(valueIsSet || externalIdIsSet, "At least one of value or externalId need to be specified"); this.value = value; this.externalId = externalId; this.orgId = orgId; this.includeAnyOrg = coalesceNotNull(includeAnyOrg, false); this.outOfTrx = coalesceNotNull(outOfTrx, false); }
} WarehouseId retrieveQuarantineWarehouseId(); WarehouseId retrieveWarehouseIdBy(WarehouseQuery query); WarehouseAndLocatorValue retrieveWarehouseAndLocatorValueByLocatorRepoId(int locatorRepoId); @NonNull Optional<WarehouseId> getOptionalIdByValue(@NonNull String value); @NonNull Optional<Warehouse> getOptionalById(@NonNull WarehouseId id); void save(@NonNull Warehouse warehouse); /** * Create a warehouse and a default locator. */ @NonNull Warehouse createWarehouse(@NonNull CreateWarehouseRequest request); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\IWarehouseDAO.java
2
请完成以下Java代码
public void securityContextChanged(SecurityContextChangedEvent event) { Observation observation = this.registry.getCurrentObservation(); if (observation == null) { return; } if (event.isCleared()) { observation.event(Observation.Event.of(SECURITY_CONTEXT_CLEARED)); return; } Authentication oldAuthentication = getAuthentication(event.getOldContext()); Authentication newAuthentication = getAuthentication(event.getNewContext()); if (oldAuthentication == null && newAuthentication == null) { return; } if (oldAuthentication == null) { // NOTE: NullAway thinks that newAuthentication can be null, but it cannot due // to previous check observation.event(Observation.Event.of(SECURITY_CONTEXT_CREATED, "%s [%s]") .format(SECURITY_CONTEXT_CREATED, newAuthentication.getClass().getSimpleName())); return; } if (newAuthentication == null) { // NOTE: NullAway thinks that oldAuthentication can be null, but it cannot due // to previous check observation.event(Observation.Event.of(SECURITY_CONTEXT_CLEARED, "%s [%s]") .format(SECURITY_CONTEXT_CLEARED, oldAuthentication.getClass().getSimpleName())); return; } if (oldAuthentication.equals(newAuthentication)) {
return; } observation.event(Observation.Event.of(SECURITY_CONTEXT_CHANGED, "%s [%s] -> [%s]") .format(SECURITY_CONTEXT_CHANGED, oldAuthentication.getClass().getSimpleName(), newAuthentication.getClass().getSimpleName())); } private static @Nullable Authentication getAuthentication(SecurityContext context) { if (context == null) { return null; } return context.getAuthentication(); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\context\ObservationSecurityContextChangedListener.java
1
请完成以下Java代码
public class JSONNotificationsList { public static final JSONNotificationsList EMPTY = new JSONNotificationsList(); public static final JSONNotificationsList of(final UserNotificationsList notifications, final JSONOptions jsonOpts) { if (notifications.isEmpty()) { return EMPTY; } return new JSONNotificationsList(notifications, jsonOpts); } @JsonProperty("totalCount") private final int totalCount; @JsonProperty("unreadCount") private final int unreadCount; @JsonProperty("notifications") private final List<JSONNotification> notifications; private JSONNotificationsList(final UserNotificationsList notifications, final JSONOptions jsonOpts) { super(); totalCount = notifications.getTotalCount(); unreadCount = notifications.getTotalUnreadCount(); this.notifications = notifications.getNotifications() .stream() .map(notification -> JSONNotification.of(notification, jsonOpts)) .collect(GuavaCollectors.toImmutableList()); } private JSONNotificationsList() { super(); totalCount = 0; unreadCount = 0; notifications = ImmutableList.of(); } @Override public String toString() {
return MoreObjects.toStringHelper(this) .add("totalCount", totalCount) .add("unreadCount", unreadCount) .add("notifications", notifications) .toString(); } public int getTotalCount() { return totalCount; } public int getUnreadCount() { return unreadCount; } public List<JSONNotification> getNotifications() { return notifications; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\json\JSONNotificationsList.java
1
请完成以下Java代码
public boolean isSendSynchronously() { return sendSynchronously; } public void setSendSynchronously(boolean sendSynchronously) { this.sendSynchronously = sendSynchronously; } public List<IOParameter> getEventInParameters() { return eventInParameters; } public void setEventInParameters(List<IOParameter> eventInParameters) { this.eventInParameters = eventInParameters; } public List<IOParameter> getEventOutParameters() { return eventOutParameters; } public void setEventOutParameters(List<IOParameter> eventOutParameters) { this.eventOutParameters = eventOutParameters; } @Override public SendEventServiceTask clone() { SendEventServiceTask clone = new SendEventServiceTask(); clone.setValues(this);
return clone; } public void setValues(SendEventServiceTask otherElement) { super.setValues(otherElement); setEventType(otherElement.getEventType()); setTriggerEventType(otherElement.getTriggerEventType()); setSendSynchronously(otherElement.isSendSynchronously()); eventInParameters = new ArrayList<>(); if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) { for (IOParameter parameter : otherElement.getEventInParameters()) { eventInParameters.add(parameter.clone()); } } eventOutParameters = new ArrayList<>(); if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) { for (IOParameter parameter : otherElement.getEventOutParameters()) { eventOutParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SendEventServiceTask.java
1
请完成以下Java代码
public Iterable<? extends DistributedMember> getRemainingMembers() { return this.remainingMembers; } /** * Null-safe builder method used to configure an array of failing {@link DistributedMember peer members} * in the {@link DistributedSystem} on the losing side of a network partition. * * @param failedMembers array of failed {@link DistributedMember peer members}; may be {@literal null}. * @return this {@link QuorumLostEvent}. * @see org.apache.geode.distributed.DistributedMember * @see #withFailedMembers(Iterable) * @see #getFailedMembers() */ public QuorumLostEvent withFailedMembers(DistributedMember... failedMembers) { return withFailedMembers(failedMembers != null ? Arrays.asList(failedMembers) : Collections.emptySet()); } /** * Null-safe builder method used to configure an {@link Iterable} of failing {@link DistributedMember peer members} * in the {@link DistributedSystem} on the losing side of a network partition. * * @param failedMembers {@link Iterable} of failed {@link DistributedMember peer members}; may be {@literal null}. * @return this {@link QuorumLostEvent}. * @see org.apache.geode.distributed.DistributedMember * @see #getFailedMembers() * @see java.lang.Iterable */ public QuorumLostEvent withFailedMembers(Iterable<? extends DistributedMember> failedMembers) { this.failedMembers = failedMembers != null ? failedMembers : Collections.emptySet(); return this; } /** * Null-safe builder method used to configure an array of remaining {@link DistributedMember peer members} * in the {@link DistributedSystem} on the winning side of a network partition. * * @param remainingMembers array of remaining {@link DistributedMember peer members}; may be {@literal null}. * @return this {@link QuorumLostEvent}. * @see org.apache.geode.distributed.DistributedMember * @see #withRemainingMembers(Iterable) * @see #getRemainingMembers() */ public QuorumLostEvent withRemainingMembers(DistributedMember... remainingMembers) { return withRemainingMembers(remainingMembers != null ? Arrays.asList(remainingMembers) : Collections.emptyList()); }
/** * Null-safe builder method used to configure an {@link Iterable} of remaining {@link DistributedMember peer members} * in the {@link DistributedSystem} on the winning side of a network partition. * * @param remainingMembers {@link Iterable} of remaining {@link DistributedMember peer members}; * may be {@literal null}. * @return this {@link QuorumLostEvent}. * @see org.apache.geode.distributed.DistributedMember * @see #getRemainingMembers() * @see java.lang.Iterable */ public QuorumLostEvent withRemainingMembers(Iterable<? extends DistributedMember> remainingMembers) { this.remainingMembers = remainingMembers != null ? remainingMembers : Collections.emptyList(); return this; } /** * @inheritDoc */ @Override public final Type getType() { return Type.QUORUM_LOST; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\support\QuorumLostEvent.java
1
请在Spring Boot框架中完成以下Java代码
public Function<RouteProperties, HandlerFunctionDefinition> streamHandlerFunctionDefinition() { return routeProperties -> { Objects.requireNonNull(routeProperties.getUri(), "routeProperties.uri must not be null"); return new HandlerFunctionDefinition.Default("stream", HandlerFunctions.stream(routeProperties.getUri().getSchemeSpecificPart())); }; } private static HandlerFunctionDefinition getResult(String scheme, @Nullable String id, @Nullable URI uri, HandlerFunction<ServerResponse> handlerFunction) { HandlerFilterFunction<ServerResponse, ServerResponse> setId = setIdFilter(id); HandlerFilterFunction<ServerResponse, ServerResponse> setRequest = setRequestUrlFilter(uri); return new HandlerFunctionDefinition.Default(scheme, handlerFunction, Arrays.asList(setId, setRequest), Collections.emptyList()); } private static HandlerFilterFunction<ServerResponse, ServerResponse> setIdFilter(@Nullable String id) {
return (request, next) -> { MvcUtils.setRouteId(request, id); return next.handle(request); }; } private static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestUrlFilter(@Nullable URI uri) { return (request, next) -> { Objects.requireNonNull(uri, "uri must not be null"); MvcUtils.setRequestUrl(request, uri); return next.handle(request); }; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\HandlerFunctionAutoConfiguration.java
2
请完成以下Java代码
public final void setOauth2UserService(OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService) { Assert.notNull(oauth2UserService, "oauth2UserService cannot be null"); this.oauth2UserService = oauth2UserService; } /** * Sets the factory that provides a {@link Converter} used for type conversion of * claim values for an {@link OidcUserInfo}. The default is {@link ClaimTypeConverter} * for all {@link ClientRegistration clients}. * @param claimTypeConverterFactory the factory that provides a {@link Converter} used * for type conversion of claim values for a specific {@link ClientRegistration * client} * @since 5.2 */ public final void setClaimTypeConverterFactory( Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) { Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null"); this.claimTypeConverterFactory = claimTypeConverterFactory; } /** * Sets the {@code Predicate} used to determine if the UserInfo Endpoint should be * called to retrieve information about the End-User (Resource Owner). * <p> * By default, the UserInfo Endpoint is called if all the following are true: * <ul> * <li>The user info endpoint is defined on the ClientRegistration</li> * <li>The Client Registration uses the * {@link AuthorizationGrantType#AUTHORIZATION_CODE}</li> * </ul> * @param retrieveUserInfo the {@code Predicate} used to determine if the UserInfo * Endpoint should be called * @since 6.3
*/ public final void setRetrieveUserInfo(Predicate<OidcUserRequest> retrieveUserInfo) { Assert.notNull(retrieveUserInfo, "retrieveUserInfo cannot be null"); this.retrieveUserInfo = retrieveUserInfo; } /** * Allows converting from the {@link OidcUserSource} to and {@link OidcUser}. * @param oidcUserConverter the {@link Converter} to use. Cannot be null. */ public void setOidcUserConverter(Converter<OidcUserSource, OidcUser> oidcUserConverter) { Assert.notNull(oidcUserConverter, "oidcUserConverter cannot be null"); this.oidcUserConverter = oidcUserConverter; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\userinfo\OidcUserService.java
1
请完成以下Java代码
public boolean isDraftedInProgressOrInvalid() { return this == Drafted || this == InProgress || this == Invalid; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isDraftedInProgressOrCompleted() { return this == Drafted || this == InProgress || this == Completed; }
public boolean isNotProcessed() { return isDraftedInProgressOrInvalid() || this == Approved || this == NotApproved; } public boolean isVoided() {return this == Voided;} public boolean isAccountable() { return this == Completed || this == Reversed || this == Voided; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocStatus.java
1
请完成以下Java代码
public int compareTo(@NonNull final AttributesKeyPart other) { final int cmp1 = compareNullsLast(getAttributeValueIdOrSpecialCodeOrNull(), other.getAttributeValueIdOrSpecialCodeOrNull()); if (cmp1 != 0) { return cmp1; } final int cmp2 = compareNullsLast(getAttributeIdOrNull(), getAttributeIdOrNull()); if (cmp2 != 0) { return cmp2; } return stringRepresentation.compareTo(other.stringRepresentation); } private Integer getAttributeValueIdOrSpecialCodeOrNull() { if (type == AttributeKeyPartType.AttributeValueId) { return attributeValueId.getRepoId(); } else if (type == AttributeKeyPartType.All || type == AttributeKeyPartType.Other || type == AttributeKeyPartType.None) { return specialCode; } else { return null; } }
private Integer getAttributeIdOrNull() { return AttributeKeyPartType.AttributeIdAndValue == type ? attributeId.getRepoId() : null; } private static int compareNullsLast(final Integer i1, final Integer i2) { if (i1 == null) { return +1; } else if (i2 == null) { return -1; } else { return i1 - i2; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKeyPart.java
1
请完成以下Java代码
public class ConditionalEventDefinition extends EventSubscriptionDeclaration implements Serializable { private static final long serialVersionUID = 1L; protected String conditionAsString; protected final Condition condition; protected boolean interrupting; protected String variableName; protected Set<String> variableEvents; protected ActivityImpl conditionalActivity; public ConditionalEventDefinition(Condition condition, ActivityImpl conditionalActivity) { super(null, EventType.CONDITONAL); this.activityId = conditionalActivity.getActivityId(); this.conditionalActivity = conditionalActivity; this.condition = condition; } public ActivityImpl getConditionalActivity() { return conditionalActivity; } public void setConditionalActivity(ActivityImpl conditionalActivity) { this.conditionalActivity = conditionalActivity; } public boolean isInterrupting() { return interrupting; } public void setInterrupting(boolean interrupting) { this.interrupting = interrupting; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } public Set<String> getVariableEvents() { return variableEvents; } public void setVariableEvents(Set<String> variableEvents) { this.variableEvents = variableEvents;
} public String getConditionAsString() { return conditionAsString; } public void setConditionAsString(String conditionAsString) { this.conditionAsString = conditionAsString; } public boolean shouldEvaluateForVariableEvent(VariableEvent event) { return ((variableName == null || event.getVariableInstance().getName().equals(variableName)) && ((variableEvents == null || variableEvents.isEmpty()) || variableEvents.contains(event.getEventName()))); } public boolean evaluate(DelegateExecution execution) { if (condition != null) { return condition.evaluate(execution, execution); } throw new IllegalStateException("Conditional event must have a condition!"); } public boolean tryEvaluate(DelegateExecution execution) { if (condition != null) { return condition.tryEvaluate(execution, execution); } throw new IllegalStateException("Conditional event must have a condition!"); } public boolean tryEvaluate(VariableEvent variableEvent, DelegateExecution execution) { return (variableEvent == null || shouldEvaluateForVariableEvent(variableEvent)) && tryEvaluate(execution); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\ConditionalEventDefinition.java
1
请完成以下Java代码
public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getPickingSlotIdAndCaption(pickingSlotId); } @Override public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final PickingSlotQuery query) { return pickingSlotDAO.retrievePickingSlotIdAndCaptions(query); } @Override public QRCodePDFResource createQRCodesPDF(@NonNull final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions) { Check.assumeNotEmpty(pickingSlotIdAndCaptions, "pickingSlotIdAndCaptions is not empty"); final ImmutableList<PrintableQRCode> qrCodes = pickingSlotIdAndCaptions.stream() .map(PickingSlotQRCode::ofPickingSlotIdAndCaption) .map(PickingSlotQRCode::toPrintableQRCode) .collect(ImmutableList.toImmutableList()); final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class); return globalQRCodeService.createPDF(qrCodes); } @Override public boolean isAvailableForAnyBPartner(@NonNull final PickingSlotId pickingSlotId) {
return isAvailableForAnyBPartner(pickingSlotDAO.getById(pickingSlotId)); } @NonNull public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getById(pickingSlotId); } @Override public boolean isPickingRackSystem(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.isPickingRackSystem(pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotBL.java
1
请完成以下Java代码
public Set<ShipmentScheduleId> getShipmentScheduleIds() { return byShipmentScheduleId.keySet(); } public ShipmentScheduleId getSingleShipmentScheduleId() { final Set<ShipmentScheduleId> shipmentScheduleIds = getShipmentScheduleIds(); if (shipmentScheduleIds.size() != 1) { throw new AdempiereException("Expected only one shipment schedule").setParameter("list", list); } return shipmentScheduleIds.iterator().next(); } public ShipmentScheduleAndJobScheduleIdSet toShipmentScheduleAndJobScheduleIdSet() { return list.stream() .map(PickingJobSchedule::getShipmentScheduleAndJobScheduleId) .collect(ShipmentScheduleAndJobScheduleIdSet.collect()); } public boolean isAllProcessed() { return list.stream().allMatch(PickingJobSchedule::isProcessed); } public Optional<Quantity> getQtyToPick() { return list.stream() .map(PickingJobSchedule::getQtyToPick) .reduce(Quantity::add); }
public Optional<PickingJobSchedule> getSingleScheduleByShipmentScheduleId(@NonNull ShipmentScheduleId shipmentScheduleId) { final ImmutableList<PickingJobSchedule> schedules = byShipmentScheduleId.get(shipmentScheduleId); if (schedules.isEmpty()) { return Optional.empty(); } else if (schedules.size() == 1) { return Optional.of(schedules.get(0)); } else { throw new AdempiereException("Only one schedule was expected for " + shipmentScheduleId + " but found " + schedules); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\model\PickingJobScheduleCollection.java
1
请完成以下Java代码
public String getDeploymentId() { return deploymentId; } @Override public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Date getStartTime() { return startTime; } @Override public void setStartTime(Date startTime) { this.startTime = startTime; } @Override public Date getEndTime() { return endTime; } @Override public void setEndTime(Date endTime) { this.endTime = endTime; } @Override public String getInstanceId() { return instanceId; } @Override public void setInstanceId(String instanceId) { this.instanceId = instanceId; } @Override public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getActivityId() { return activityId; } @Override public void setActivityId(String activityId) { this.activityId = activityId; } @Override public String getScopeType() { return scopeType; } @Override public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public boolean isFailed() { return failed; } @Override public void setFailed(boolean failed) { this.failed = failed; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getExecutionJson() { return executionJson;
} @Override public void setExecutionJson(String executionJson) { this.executionJson = executionJson; } @Override public String getDecisionKey() { return decisionKey; } public void setDecisionKey(String decisionKey) { this.decisionKey = decisionKey; } @Override public String getDecisionName() { return decisionName; } public void setDecisionName(String decisionName) { this.decisionName = decisionName; } @Override public String getDecisionVersion() { return decisionVersion; } public void setDecisionVersion(String decisionVersion) { this.decisionVersion = decisionVersion; } @Override public String toString() { return "HistoricDecisionExecutionEntity[" + id + "]"; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java
1
请完成以下Java代码
public class GetTableNameCmd implements Command<String>, Serializable { private static final long serialVersionUID = 1L; protected Class<?> entityClass; protected boolean withPrefix = true; public GetTableNameCmd(Class<?> entityClass) { this.entityClass = entityClass; } public GetTableNameCmd(Class<?> entityClass, boolean withPrefix) { this.entityClass = entityClass; this.withPrefix = withPrefix; } @Override public String execute(CommandContext commandContext) {
if (entityClass == null) { throw new FlowableIllegalArgumentException("entityClass is null"); } String databaseTablePrefix = getDbSqlSession(commandContext).getDbSqlSessionFactory().getDatabaseTablePrefix(); String tableName = EntityToTableMap.getTableName(entityClass); if (withPrefix) { return databaseTablePrefix + tableName; } else { return tableName; } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetTableNameCmd.java
1
请完成以下Java代码
private Optional<DesadvInOutLine> deleteDesadvInOutLineIfExists( @NonNull final InOutLineId shipmentLineId) { final Optional<DesadvInOutLine> desadvInOutLine = desadvInOutLineDAO.getByInOutLineId(shipmentLineId); desadvInOutLine.ifPresent(desadvInOutLineDAO::delete); return desadvInOutLine; } @NonNull private EDIDesadvQuery buildEDIDesadvQuery(@NonNull final I_C_Order order) { final String poReference = Check.assumeNotNull(order.getPOReference(), "In the DESADV-Context, POReference is mandatory; C_Order_ID={}", order.getC_Order_ID()); final EDIDesadvQuery.EDIDesadvQueryBuilder ediDesadvQueryBuilder = EDIDesadvQuery.builder() .poReference(poReference) .ctxAware(InterfaceWrapperHelper.getContextAware(order)); if (isMatchUsingBPartnerId()) { ediDesadvQueryBuilder.bPartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID())); } if (isMatchUsingOrderId(ClientId.ofRepoId(order.getAD_Client_ID()))) { ediDesadvQueryBuilder.orderId(OrderId.ofRepoId(order.getC_Order_ID())); } return ediDesadvQueryBuilder .build(); } @NonNull private EDIDesadvQuery buildEDIDesadvQuery(@NonNull final I_M_InOut inOut) { final String poReference = Check.assumeNotNull(inOut.getPOReference(), "In the DESADV-Context, POReference is mandatory; M_InOut_ID={}", inOut.getM_InOut_ID()); final EDIDesadvQuery.EDIDesadvQueryBuilder ediDesadvQueryBuilder = EDIDesadvQuery.builder()
.poReference(poReference) .ctxAware(InterfaceWrapperHelper.getContextAware(inOut)); if (isMatchUsingBPartnerId()) { ediDesadvQueryBuilder.bPartnerId(BPartnerId.ofRepoId(inOut.getC_BPartner_ID())); } return ediDesadvQueryBuilder .build(); } private boolean isMatchUsingBPartnerId() { return sysConfigBL.getBooleanValue(SYS_CONFIG_MATCH_USING_BPARTNER_ID, false); } private static void setExternalBPartnerInfo(@NonNull final I_EDI_DesadvLine newDesadvLine, @NonNull final I_C_OrderLine orderLineRecord) { newDesadvLine.setExternalSeqNo(orderLineRecord.getExternalSeqNo()); newDesadvLine.setC_UOM_BPartner_ID(orderLineRecord.getC_UOM_BPartner_ID()); newDesadvLine.setQtyEnteredInBPartnerUOM(ZERO); newDesadvLine.setBPartner_QtyItemCapacity(orderLineRecord.getBPartner_QtyItemCapacity()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\DesadvBL.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentService { // DB repository mock private Map<Long, Student> repository = Arrays.asList( new Student[]{ new Student(1, "Alan","Turing"), new Student(2, "Sebastian","Bach"), new Student(3, "Pablo","Picasso"), }).stream() .collect(Collectors.toConcurrentMap(Student::getId, Function.identity())); // DB id sequence mock private AtomicLong sequence = new AtomicLong(3); public List<Student> readAll() { return repository.values().stream().collect(Collectors.toList()); } public Student read(Long id) { return repository.get(id);
} public Student create(Student student) { long key = sequence.incrementAndGet(); student.setId(key); repository.put(key, student); return student; } public Student update(Long id, Student student) { student.setId(id); Student oldStudent = repository.replace(id, student); return oldStudent == null ? null : student; } public void delete(Long id) { repository.remove(id); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc\src\main\java\com\baeldung\students\StudentService.java
2
请完成以下Java代码
public void setName(String name) { nameAttribute.setValue(this, name); } public Collection<CaseRole> getCaseRoles() { return caseRolesCollection.get(this); } public CaseRoles getRoles() { return caseRolesChild.getChild(this); } public void setRoles(CaseRoles caseRole) { caseRolesChild.setChild(this, caseRole); } public Collection<InputCaseParameter> getInputs() { return inputCollection.get(this); } public Collection<OutputCaseParameter> getOutputs() { return outputCollection.get(this); } public CasePlanModel getCasePlanModel() { return casePlanModelChild.getChild(this); } public void setCasePlanModel(CasePlanModel casePlanModel) { casePlanModelChild.setChild(this, casePlanModel); } public CaseFileModel getCaseFileModel() { return caseFileModelChild.getChild(this); } public void setCaseFileModel(CaseFileModel caseFileModel) { caseFileModelChild.setChild(this, caseFileModel); } public Integer getCamundaHistoryTimeToLive() { String ttl = getCamundaHistoryTimeToLiveString(); if (ttl != null) { return Integer.parseInt(ttl); } return null; } public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) { setCamundaHistoryTimeToLiveString(String.valueOf(historyTimeToLive)); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Case.class, CMMN_ELEMENT_CASE) .extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Case>() { public Case newInstance(ModelTypeInstanceContext instanceContext) { return new CaseImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); camundaHistoryTimeToLive = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); caseFileModelChild = sequenceBuilder.element(CaseFileModel.class) .build(); casePlanModelChild = sequenceBuilder.element(CasePlanModel.class) .build(); caseRolesCollection = sequenceBuilder.elementCollection(CaseRole.class) .build(); caseRolesChild = sequenceBuilder.element(CaseRoles.class) .build(); inputCollection = sequenceBuilder.elementCollection(InputCaseParameter.class) .build(); outputCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class) .build(); typeBuilder.build(); } @Override public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLive.getValue(this); } @Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { camundaHistoryTimeToLive.setValue(this, historyTimeToLive); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseImpl.java
1
请完成以下Java代码
public final class JsonExpirationDate { @JsonCreator public static JsonExpirationDate ofJson(@NonNull final String json) { if (json.contains("-")) { final LocalDate localDate = LocalDate.parse(json, FORMAT_yyyy_MM_dd); final String yyMMdd = toYYMMDD(localDate); return new JsonExpirationDate(yyMMdd, localDate); } else { final String yyMMdd = json; final LocalDate localDate = toLocalDate(yyMMdd); return new JsonExpirationDate(yyMMdd, localDate); } } public static JsonExpirationDate ofLocalDate(@NonNull final LocalDate date) { return new JsonExpirationDate(toYYMMDD(date), date); } public static JsonExpirationDate ofNullableLocalDate(@Nullable final LocalDate date) { return date != null ? ofLocalDate(date) : null; } private static final DateTimeFormatter FORMAT_yyMMdd = DateTimeFormatter.ofPattern("yyMMdd"); private static final DateTimeFormatter FORMAT_yyMM = DateTimeFormatter.ofPattern("yyMM"); private static final DateTimeFormatter FORMAT_yyyy_MM_dd = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private final String yyMMdd; private final LocalDate localDate; private JsonExpirationDate(@NonNull final String yyMMdd, @NonNull final LocalDate localDate) { this.yyMMdd = yyMMdd; this.localDate = localDate; } private static LocalDate toLocalDate(@NonNull final String yyMMdd) { if (yyMMdd.length() != 6) { throw new AdempiereException("Invalid expire date format: " + yyMMdd); } final String dd = yyMMdd.substring(4, 6); if (dd.endsWith("00")) // last day of month indicator { final String yyMM = yyMMdd.substring(0, 4); return YearMonth.parse(yyMM, FORMAT_yyMM).atEndOfMonth(); } else { return LocalDate.parse(yyMMdd, FORMAT_yyMMdd);
} } private static String toYYMMDD(@NonNull final LocalDate localDate) { if (TimeUtil.isLastDayOfMonth(localDate)) { return FORMAT_yyMM.format(localDate) + "00"; } else { return FORMAT_yyMMdd.format(localDate); } } @JsonValue public String toJson() { return toYYMMDDString(); } public String toYYMMDDString() { return yyMMdd; } public LocalDate toLocalDate() { return localDate; } public Timestamp toTimestamp() { return TimeUtil.asTimestamp(toLocalDate()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\client\schema\JsonExpirationDate.java
1
请在Spring Boot框架中完成以下Java代码
public class MapSessionRepository implements SessionRepository<MapSession> { private Duration defaultMaxInactiveInterval = Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); private final Map<String, Session> sessions; private SessionIdGenerator sessionIdGenerator = UuidSessionIdGenerator.getInstance(); /** * Creates a new instance backed by the provided {@link java.util.Map}. This allows * injecting a distributed {@link java.util.Map}. * @param sessions the {@link java.util.Map} to use. Cannot be null. */ public MapSessionRepository(Map<String, Session> sessions) { if (sessions == null) { throw new IllegalArgumentException("sessions cannot be null"); } this.sessions = sessions; } /** * Set the maximum inactive interval in seconds between requests before newly created * sessions will be invalidated. A negative time indicates that the session will never * time out. The default is 30 minutes. * @param defaultMaxInactiveInterval the default maxInactiveInterval */ public void setDefaultMaxInactiveInterval(Duration defaultMaxInactiveInterval) { Assert.notNull(defaultMaxInactiveInterval, "defaultMaxInactiveInterval must not be null"); this.defaultMaxInactiveInterval = defaultMaxInactiveInterval; } @Override public void save(MapSession session) { if (!session.getId().equals(session.getOriginalId())) { this.sessions.remove(session.getOriginalId()); } MapSession saved = new MapSession(session); saved.setSessionIdGenerator(this.sessionIdGenerator); this.sessions.put(session.getId(), saved); } @Override public MapSession findById(String id) { Session saved = this.sessions.get(id); if (saved == null) {
return null; } if (saved.isExpired()) { deleteById(saved.getId()); return null; } MapSession result = new MapSession(saved); result.setSessionIdGenerator(this.sessionIdGenerator); return result; } @Override public void deleteById(String id) { this.sessions.remove(id); } @Override public MapSession createSession() { MapSession result = new MapSession(this.sessionIdGenerator); result.setMaxInactiveInterval(this.defaultMaxInactiveInterval); return result; } public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { Assert.notNull(sessionIdGenerator, "sessionIdGenerator cannot be null"); this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSessionRepository.java
2
请完成以下Java代码
public int getAD_Client_ID() { return adClientId; } @Override public I_AD_Org getAD_Org() { return adOrg; } @Override public int getAD_Org_ID() { return adOrgId; } @Override public I_M_Warehouse getM_Warehouse() { return warehouse; } @Override public int getM_Warehouse_ID() { return warehouseId; } @Override public IMRPSegment setM_Warehouse(final I_M_Warehouse warehouse) { final int warehouseIdNew; if (warehouse == null || warehouse.getM_Warehouse_ID() <= 0) { warehouseIdNew = -1; } else { warehouseIdNew = warehouse.getM_Warehouse_ID(); } // No change => return this if (warehouseIdNew == this.warehouseId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.warehouseId = warehouseIdNew; mrpSegmentNew.warehouse = warehouse; return mrpSegmentNew; } @Override public I_S_Resource getPlant() { return plant; } @Override public int getPlant_ID() { return plantId; } @Override public IMRPSegment setPlant(final I_S_Resource plant) { final int plantIdNew;
if (plant == null || plant.getS_Resource_ID() <= 0) { plantIdNew = -1; } else { plantIdNew = plant.getS_Resource_ID(); } // No change => return this if (plantIdNew == this.plantId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.plantId = plantIdNew; mrpSegmentNew.plant = plant; return mrpSegmentNew; } @Override public I_M_Product getM_Product() { return product; } @Override public int getM_Product_ID() { return productId; } @Override public IMRPSegment setM_Product(final I_M_Product product) { final int productIdNew; if (product == null || product.getM_Product_ID() <= 0) { productIdNew = -1; } else { productIdNew = product.getM_Product_ID(); } // No change => return this if (productIdNew == this.productId) { return this; } final MRPSegment mrpSegmentNew = new MRPSegment(this); mrpSegmentNew.productId = productIdNew; mrpSegmentNew.product = product; return mrpSegmentNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPSegment.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Warehouse Picking Group. @param M_Warehouse_PickingGroup_ID Warehouse Picking Group */ @Override public void setM_Warehouse_PickingGroup_ID (int M_Warehouse_PickingGroup_ID) { if (M_Warehouse_PickingGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_PickingGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_PickingGroup_ID, Integer.valueOf(M_Warehouse_PickingGroup_ID)); } /** Get Warehouse Picking Group. @return Warehouse Picking Group */ @Override public int getM_Warehouse_PickingGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_PickingGroup_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse_PickingGroup.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id private Name id; private @Attribute(name = "cn") String username; private @Attribute(name = "sn") String password; public User() { } public User(String username, String password) { this.username = username; this.password = password; } public Name getId() { return id; } public void setId(Name id) { this.id = id; } public String getUsername() { return username;
} public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return username; } }
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\ldap\data\repository\User.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setIsOneQRCodeForAggregatedHUs (final boolean IsOneQRCodeForAggregatedHUs) { set_Value (COLUMNNAME_IsOneQRCodeForAggregatedHUs, IsOneQRCodeForAggregatedHUs); } @Override public boolean isOneQRCodeForAggregatedHUs() { return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForAggregatedHUs); } @Override public void setIsOneQRCodeForMatchingAttributes (final boolean IsOneQRCodeForMatchingAttributes) { set_Value (COLUMNNAME_IsOneQRCodeForMatchingAttributes, IsOneQRCodeForMatchingAttributes); } @Override public boolean isOneQRCodeForMatchingAttributes() { return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForMatchingAttributes); }
@Override public void setName (final String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setQRCode_Configuration_ID (final int QRCode_Configuration_ID) { if (QRCode_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, QRCode_Configuration_ID); } @Override public int getQRCode_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_QRCode_Configuration_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_QRCode_Configuration.java
1
请完成以下Java代码
public class IoSpecificationImpl extends BaseElementImpl implements IoSpecification { protected static ChildElementCollection<DataInput> dataInputCollection; protected static ChildElementCollection<DataOutput> dataOutputCollection; protected static ChildElementCollection<InputSet> inputSetCollection; protected static ChildElementCollection<OutputSet> outputSetCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(IoSpecification.class, BPMN_ELEMENT_IO_SPECIFICATION) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<IoSpecification>() { public IoSpecification newInstance(ModelTypeInstanceContext instanceContext) { return new IoSpecificationImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); dataInputCollection = sequenceBuilder.elementCollection(DataInput.class) .build(); dataOutputCollection = sequenceBuilder.elementCollection(DataOutput.class) .build(); inputSetCollection = sequenceBuilder.elementCollection(InputSet.class) .required() .build(); outputSetCollection = sequenceBuilder.elementCollection(OutputSet.class) .required() .build(); typeBuilder.build(); } public IoSpecificationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext); } public Collection<DataInput> getDataInputs() { return dataInputCollection.get(this); } public Collection<DataOutput> getDataOutputs() { return dataOutputCollection.get(this); } public Collection<InputSet> getInputSets() { return inputSetCollection.get(this); } public Collection<OutputSet> getOutputSets() { return outputSetCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\IoSpecificationImpl.java
1
请完成以下Java代码
public String getName() { return _name; } @Override public InputStream getInputStream() throws IOException { if (_data == null) { throw new IOException("no data"); } // a new stream must be returned each time. return new ByteArrayInputStream(_data); } /** * Throws exception
*/ @Override public OutputStream getOutputStream() throws IOException { throw new IOException("cannot do this"); } /** * Get Content Type * * @return MIME type e.g. text/html */ @Override public String getContentType() { return _mimeType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\ByteArrayBackedDataSource.java
1
请在Spring Boot框架中完成以下Java代码
public class OLCandQuery { /** * ID (e.g. document number), of a source document in a remote system; multiple OLCands can have the same ID */ String externalHeaderId; /** * {@link de.metas.externalsystem.model.I_ExternalSystem#COLUMNNAME_Value} of the external system the candidates in question were added with. */ ExternalSystemType externalSystemType; /** * {@link I_AD_InputDataSource#COLUMNNAME_InternalName} of the data source the candidates in question were added with. */ String inputDataSourceName; String externalLineId; OrgId orgId; @Builder private OLCandQuery( final String externalHeaderId, final ExternalSystemType externalSystemType, final String inputDataSourceName, final String externalLineId, final OrgId orgId)
{ if (externalHeaderId != null) { Check.assumeNotEmpty(externalHeaderId, "If externalHeaderId is specified, then it may not be empty"); if (externalSystemType == null && externalLineId == null) { throw new AdempiereException("If externalHeaderId is specified, then externalSystemType or externalLineId should be defined; externalHeaderId=" + externalHeaderId); } } this.externalHeaderId = externalHeaderId; this.externalSystemType = externalSystemType; this.inputDataSourceName = inputDataSourceName; this.externalLineId = externalLineId; this.orgId = orgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandQuery.java
2
请完成以下Java代码
public List<QualityInspectionLineType> getPPOrderReportLineTypes() { return PP_Order_ReportLineTypes; } @Override public String getFeeNameForProducedProduct(final I_M_Product product) { Check.assumeNotNull(product, "product not null"); // TODO: configure some where // e.g. for product "Futterkarotten" return "Zusätzliche Sortierkosten" //return product.getName(); return "Zus\u00e4tzliche Sortierkosten"; } @Override public List<QualityInvoiceLineGroupType> getQualityInvoiceLineGroupTypes() { return QualityInvoiceLineGroupType_ForInvoicing; } @Override public int getC_DocTypeInvoice_DownPayment_ID() { if (_invoiceDocTypeDownPaymentId == null) { final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_DownPayment; _invoiceDocTypeDownPaymentId = loadDocType(DocSubType.ofCode(docSubType)); } return _invoiceDocTypeDownPaymentId.getRepoId(); } @Override public int getC_DocTypeInvoice_FinalSettlement_ID() { if (_invoiceDocTypeFinalSettlementId == null) { final String docSubType = IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement; _invoiceDocTypeFinalSettlementId = loadDocType(DocSubType.ofCode(docSubType)); } return _invoiceDocTypeFinalSettlementId.getRepoId(); }
/** * Returns true if the scrap percentage treshold is less than 100. */ @Override public boolean isFeeForScrap() { return getScrapPercentageTreshold().compareTo(new BigDecimal("100")) < 0; } private DocTypeId loadDocType(final DocSubType docSubType) { final IContextAware context = getContext(); final Properties ctx = context.getCtx(); final int adClientId = Env.getAD_Client_ID(ctx); final int adOrgId = Env.getAD_Org_ID(ctx); // FIXME: not sure if it's ok return Services.get(IDocTypeDAO.class).getDocTypeId( DocTypeQuery.builder() .docBaseType(X_C_DocType.DOCBASETYPE_APInvoice) .docSubType(docSubType) .adClientId(adClientId) .adOrgId(adOrgId) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\AbstractQualityBasedConfig.java
1
请完成以下Java代码
public Builder setFilterDescriptorsProvidersService(final DocumentFilterDescriptorsProvidersService filterDescriptorsProvidersService) { this.filterDescriptorsProvidersService = filterDescriptorsProvidersService; return this; } @NonNull public Builder setDocumentDecorators(final ImmutableList<IDocumentDecorator> documentDecorators) { this.documentDecorators = documentDecorators; return this; } @Nullable public ImmutableList<IDocumentDecorator> getDocumentDecorators() { return this.documentDecorators; } public Builder setRefreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents) { this._refreshViewOnChangeEvents = refreshViewOnChangeEvents; return this; } private boolean isRefreshViewOnChangeEvents() { return _refreshViewOnChangeEvents; } public Builder setPrintProcessId(final AdProcessId printProcessId) { _printProcessId = printProcessId; return this; } private AdProcessId getPrintProcessId() { return _printProcessId; } private boolean isCloneEnabled()
{ return isCloneEnabled(_tableName); } private static boolean isCloneEnabled(@Nullable final Optional<String> tableName) { if (tableName == null || !tableName.isPresent()) { return false; } return CopyRecordFactory.isEnabledForTableName(tableName.get()); } public DocumentQueryOrderByList getDefaultOrderBys() { return getFieldBuilders() .stream() .filter(DocumentFieldDescriptor.Builder::isDefaultOrderBy) .sorted(Ordering.natural().onResultOf(DocumentFieldDescriptor.Builder::getDefaultOrderByPriority)) .map(field -> DocumentQueryOrderBy.byFieldName(field.getFieldName(), field.isDefaultOrderByAscending())) .collect(DocumentQueryOrderByList.toDocumentQueryOrderByList()); } public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder notFoundMessages(@Nullable final NotFoundMessages notFoundMessages) { this.notFoundMessages = notFoundMessages; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentEntityDescriptor.java
1
请完成以下Java代码
public InputData getRequiredInput() { return requiredInputRef.getReferenceTargetElement(this); } public void setRequiredInput(InputData requiredInput) { requiredInputRef.setReferenceTargetElement(this, requiredInput); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InformationRequirement.class, DMN_ELEMENT_INFORMATION_REQUIREMENT) .namespaceUri(LATEST_DMN_NS) .instanceProvider(new ModelTypeInstanceProvider<InformationRequirement>() { public InformationRequirement newInstance(ModelTypeInstanceContext instanceContext) { return new InformationRequirementImpl(instanceContext); } });
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); requiredDecisionRef = sequenceBuilder.element(RequiredDecisionReference.class) .uriElementReference(Decision.class) .build(); requiredInputRef = sequenceBuilder.element(RequiredInputReference.class) .uriElementReference(InputData.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\InformationRequirementImpl.java
1
请完成以下Java代码
public class C_BP_BankAccount { private final ICountryDAO countryDAO = Services.get(ICountryDAO.class); @ModelChange( timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_AFTER_NEW }, ifColumnsChanged = { I_C_BP_BankAccount.COLUMNNAME_IBAN } ) public void validateIBAN(final I_C_BP_BankAccount bp_bankAccount) { String ibanCode = bp_bankAccount.getIBAN(); if (!Check.isEmpty(ibanCode, true)) { // remove empty spaces ibanCode = ibanCode.replaceAll("\\s", ""); // remove spaces // validate IBAN final boolean isValidateIBAN = Services.get(ISysConfigBL.class).getBooleanValue("C_BP_BankAccount.validateIBAN", false); if (isValidateIBAN) { try { Services.get(IIBANValidationBL.class).validate(ibanCode); } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e).markAsUserValidationError(); } } } } @ModelChange( timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_AFTER_NEW }, ifColumnsChanged = { I_C_BP_BankAccount.COLUMNNAME_A_Country_ID } ) public void setA_Country(final I_C_BP_BankAccount bp_bankAccount) {
final int countryId = bp_bankAccount.getA_Country_ID(); if (countryId > 0) { final String countryCode = countryDAO.getCountryCode(CountryId.ofRepoId(countryId)); bp_bankAccount.setA_Country(countryCode); } else { bp_bankAccount.setA_Country(null); } } @ModelChange( timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_AFTER_NEW }, ifColumnsChanged = { I_C_BP_BankAccount.COLUMNNAME_A_Country } ) public void validateA_Country(final I_C_BP_BankAccount bp_bankAccount) { final String A_Country = bp_bankAccount.getA_Country(); if (Check.isNotBlank(A_Country)) { final CountryId countryId = countryDAO.getCountryIdByCountryCodeOrNull(A_Country); if (countryId == null) { throw new AdempiereException("Country code " + A_Country + " not found"); } else { bp_bankAccount.setA_Country_ID(countryId.getRepoId()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\model\validator\C_BP_BankAccount.java
1
请完成以下Java代码
public boolean isValid(UpdateUserCommand value, ConstraintValidatorContext context) { String inputEmail = value.getParam().getEmail(); String inputUsername = value.getParam().getUsername(); final User targetUser = value.getTargetUser(); boolean isEmailValid = userRepository.findByEmail(inputEmail).map(user -> user.equals(targetUser)).orElse(true); boolean isUsernameValid = userRepository .findByUsername(inputUsername) .map(user -> user.equals(targetUser)) .orElse(true); if (isEmailValid && isUsernameValid) { return true; } else { context.disableDefaultConstraintViolation();
if (!isEmailValid) { context .buildConstraintViolationWithTemplate("email already exist") .addPropertyNode("email") .addConstraintViolation(); } if (!isUsernameValid) { context .buildConstraintViolationWithTemplate("username already exist") .addPropertyNode("username") .addConstraintViolation(); } return false; } } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\user\UserService.java
1
请完成以下Java代码
public String getPlantName() { return plantInfo != null ? plantInfo.getCaption() : null; } public Stream<DistributionJobStep> streamSteps() { return lines.stream().flatMap(line -> line.getSteps().stream()); } public boolean isFullyMoved() { return lines.stream().allMatch(DistributionJobLine::isFullyMoved); } public boolean isInTransit() { return lines.stream().anyMatch(DistributionJobLine::isInTransit); } @Nullable public LocatorId getSinglePickFromLocatorIdOrNull() { return lines.stream() .map(DistributionJobLine::getPickFromLocatorId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } public Optional<LocatorInfo> getSinglePickFromLocator() { return lines.stream() .map(DistributionJobLine::getPickFromLocator) .distinct() .collect(GuavaCollectors.singleElementOrEmpty()); } @Nullable public LocatorId getSingleDropToLocatorIdOrNull() { return lines.stream() .map(DistributionJobLine::getDropToLocatorId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } public Optional<LocatorInfo> getSingleDropToLocator()
{ return lines.stream() .map(DistributionJobLine::getDropToLocator) .distinct() .collect(GuavaCollectors.singleElementOrEmpty()); } @Nullable public ProductId getSingleProductIdOrNull() { return lines.stream() .map(DistributionJobLine::getProductId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } @Nullable public Quantity getSingleUnitQuantityOrNull() { final MixedQuantity qty = lines.stream() .map(DistributionJobLine::getQtyToMove) .distinct() .collect(MixedQuantity.collectAndSum()); return qty.toNoneOrSingleValue().orElse(null); } public Optional<DistributionJobLineId> getNextEligiblePickFromLineId(@NonNull final ProductId productId) { return lines.stream() .filter(line -> ProductId.equals(line.getProductId(), productId)) .filter(DistributionJobLine::isEligibleForPicking) .map(DistributionJobLine::getId) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJob.java
1
请完成以下Java代码
public final class KerberosTicketValidation { private final String username; private final Subject subject; private final byte[] responseToken; private final GSSContext gssContext; private final GSSCredential delegationCredential; public KerberosTicketValidation(String username, String servicePrincipal, byte[] responseToken, GSSContext gssContext) { this(username, servicePrincipal, responseToken, gssContext, null); } public KerberosTicketValidation(String username, String servicePrincipal, byte[] responseToken, GSSContext gssContext, GSSCredential delegationCredential) { final HashSet<KerberosPrincipal> princs = new HashSet<KerberosPrincipal>(); princs.add(new KerberosPrincipal(servicePrincipal)); this.username = username; this.subject = new Subject(false, princs, new HashSet<Object>(), new HashSet<Object>()); this.responseToken = responseToken; this.gssContext = gssContext; this.delegationCredential = delegationCredential; } public KerberosTicketValidation(String username, Subject subject, byte[] responseToken, GSSContext gssContext) { this(username, subject, responseToken, gssContext, null); } public KerberosTicketValidation(String username, Subject subject, byte[] responseToken, GSSContext gssContext, GSSCredential delegationCredential) { this.username = username; this.subject = subject; this.responseToken = responseToken; this.gssContext = gssContext; this.delegationCredential = delegationCredential; } public String username() {
return this.username; } public byte[] responseToken() { return this.responseToken; } public GSSContext getGssContext() { return this.gssContext; } public Subject subject() { return this.subject; } public GSSCredential getDelegationCredential() { return this.delegationCredential; } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosTicketValidation.java
1
请完成以下Java代码
private void updateOrderState(String orderId, OrderStateEnum targetOrderState) { // 构造OrderStateTimeEntity OrderStateTimeEntity orderStateTimeEntity = buildOrderStateTimeEntity(orderId, targetOrderState); // 删除该订单的该条状态 orderDAO.deleteOrderStateTime(orderStateTimeEntity); // 插入该订单的该条状态 orderDAO.insertOrderStateTime(orderStateTimeEntity); // 更新order表中的订单状态 OrdersEntity ordersEntity = new OrdersEntity(); ordersEntity.setId(orderId); ordersEntity.setOrderStateEnum(targetOrderState); orderDAO.updateOrder(ordersEntity); } /** * 构造用于更新订单状态的buildOrderStateTimeEntity * @param orderId 订单ID * @param targetOrderState 订单状态 * @return OrderStateTimeEntity */ private OrderStateTimeEntity buildOrderStateTimeEntity(String orderId, OrderStateEnum targetOrderState) { OrderStateTimeEntity orderStateTimeEntity = new OrderStateTimeEntity(); orderStateTimeEntity.setOrderId(orderId); orderStateTimeEntity.setOrderStateEnum(targetOrderState); orderStateTimeEntity.setTime(new Timestamp(System.currentTimeMillis())); return orderStateTimeEntity; }
private void checkParam(OrderStateEnum targetOrderState) { if (targetOrderState == null) { throw new CommonSysException(ExpCodeEnum.TARGETSTATE_NULL); } } @Override public void handle(OrderProcessContext orderProcessContext) { // 设置目标状态 setTargetOrderState(); // 前置处理 this.preHandle(orderProcessContext); if (this.isStop) { return; } // 改变状态 this.changeState(orderProcessContext, this.targetOrderState); if (this.isStop) { return; } // 后置处理 this.afterHandle(orderProcessContext); } public abstract void setTargetOrderState(); }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\changestate\BaseChangeStateComponent.java
1
请完成以下Java代码
public boolean addAssignedCustomer(Customer customer) { ShortCustomerInfo customerInfo = customer.toShortCustomerInfo(); if (this.assignedCustomers != null && this.assignedCustomers.contains(customerInfo)) { return false; } else { if (this.assignedCustomers == null) { this.assignedCustomers = new HashSet<>(); } this.assignedCustomers.add(customerInfo); return true; } } public boolean updateAssignedCustomer(Customer customer) { ShortCustomerInfo customerInfo = customer.toShortCustomerInfo(); if (this.assignedCustomers != null && this.assignedCustomers.contains(customerInfo)) { this.assignedCustomers.remove(customerInfo); this.assignedCustomers.add(customerInfo); return true; } else { return false; } } public boolean removeAssignedCustomer(Customer customer) { ShortCustomerInfo customerInfo = customer.toShortCustomerInfo(); if (this.assignedCustomers != null && this.assignedCustomers.contains(customerInfo)) { this.assignedCustomers.remove(customerInfo); return true; } else { return false; } } @Schema(description = "Same as title of the dashboard. Read-only field. Update the 'title' to change the 'name' of the dashboard.", accessMode = Schema.AccessMode.READ_ONLY) @Override @JsonProperty(access = JsonProperty.Access.READ_ONLY) public String getName() { return title;
} @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; DashboardInfo that = (DashboardInfo) o; return mobileHide == that.mobileHide && Objects.equals(tenantId, that.tenantId) && Objects.equals(title, that.title) && Objects.equals(image, that.image) && Objects.equals(assignedCustomers, that.assignedCustomers) && Objects.equals(mobileOrder, that.mobileOrder); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DashboardInfo [tenantId="); builder.append(tenantId); builder.append(", title="); builder.append(title); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\DashboardInfo.java
1
请完成以下Java代码
public Quantity getQtyAvailableToAllocateInHuUom() { final Quantity qtyStorageInHuUom = getStorageQtyInHuUom(); return qtyAllocatedInHuUom != null ? qtyStorageInHuUom.subtract(qtyAllocatedInHuUom) : qtyStorageInHuUom; } private Quantity getStorageQtyInHuUom() { Quantity storageQtyInHuUom = this._storageQtyInHuUom; if (storageQtyInHuUom == null) { storageQtyInHuUom = this._storageQtyInHuUom = storageFactory.getStorage(topLevelHU).getProductStorage(productId).getQty(); } return storageQtyInHuUom; } public void addQtyAllocated(@NonNull final Quantity qtyAllocatedToAdd0) { final Quantity storageQtyInHuUom = getStorageQtyInHuUom();
final Quantity qtyAllocatedToAddInHuUom = uomConverter.convertQuantityTo(qtyAllocatedToAdd0, productId, storageQtyInHuUom.getUomId()); final Quantity newQtyAllocatedInHuUom = this.qtyAllocatedInHuUom != null ? this.qtyAllocatedInHuUom.add(qtyAllocatedToAddInHuUom) : qtyAllocatedToAddInHuUom; if (newQtyAllocatedInHuUom.isGreaterThan(storageQtyInHuUom)) { throw new AdempiereException("Over-allocating is not allowed") .appendParametersToMessage() .setParameter("this.qtyAllocated", this.qtyAllocatedInHuUom) .setParameter("newQtyAllocated", newQtyAllocatedInHuUom) .setParameter("storageQty", storageQtyInHuUom); } this.qtyAllocatedInHuUom = newQtyAllocatedInHuUom; } public boolean hasQtyAvailable() { return getQtyAvailableToAllocateInHuUom().signum() > 0; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\manufacturing\issue\plan\AllocableHU.java
1
请完成以下Java代码
public IdmEngineConfiguration setTablePrefixIsSchema(boolean tablePrefixIsSchema) { this.tablePrefixIsSchema = tablePrefixIsSchema; return this; } public PasswordEncoder getPasswordEncoder() { return passwordEncoder; } public IdmEngineConfiguration setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; return this; } public PasswordSalt getPasswordSalt() { return passwordSalt; } public IdmEngineConfiguration setPasswordSalt(PasswordSalt passwordSalt) { this.passwordSalt = passwordSalt; return this; } @Override public IdmEngineConfiguration setSessionFactories(Map<Class<?>, SessionFactory> sessionFactories) { this.sessionFactories = sessionFactories; return this; } @Override public IdmEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) { this.databaseSchemaUpdate = databaseSchemaUpdate; return this; } @Override public IdmEngineConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher; return this; } @Override public IdmEngineConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; return this; } @Override public IdmEngineConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { this.eventListeners = eventListeners; return this; } @Override public IdmEngineConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } @Override public IdmEngineConfiguration setClock(Clock clock) { this.clock = clock; return this; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngineConfiguration.java
1
请完成以下Java代码
public TelemetryDataImpl getTelemetryData() { return telemetryData; } public ProcessEngineConfigurationImpl setTelemetryData(TelemetryDataImpl telemetryData) { this.telemetryData = telemetryData; return this; } public boolean isReevaluateTimeCycleWhenDue() { return reevaluateTimeCycleWhenDue; } public ProcessEngineConfigurationImpl setReevaluateTimeCycleWhenDue(boolean reevaluateTimeCycleWhenDue) { this.reevaluateTimeCycleWhenDue = reevaluateTimeCycleWhenDue; return this; } public int getRemovalTimeUpdateChunkSize() { return removalTimeUpdateChunkSize; } public ProcessEngineConfigurationImpl setRemovalTimeUpdateChunkSize(int removalTimeUpdateChunkSize) { this.removalTimeUpdateChunkSize = removalTimeUpdateChunkSize; return this; }
/** * @return a exception code interceptor. The interceptor is not registered in case * {@code disableExceptionCode} is configured to {@code true}. */ protected ExceptionCodeInterceptor getExceptionCodeInterceptor() { return new ExceptionCodeInterceptor(builtinExceptionCodeProvider, customExceptionCodeProvider); } public DiagnosticsRegistry getDiagnosticsRegistry() { return diagnosticsRegistry; } public ProcessEngineConfiguration setDiagnosticsRegistry(DiagnosticsRegistry diagnosticsRegistry) { this.diagnosticsRegistry = diagnosticsRegistry; return this; } public boolean isLegacyJobRetryBehaviorEnabled() { return legacyJobRetryBehaviorEnabled; } public ProcessEngineConfiguration setLegacyJobRetryBehaviorEnabled(boolean legacyJobRetryBehaviorEnabled) { this.legacyJobRetryBehaviorEnabled = legacyJobRetryBehaviorEnabled; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<UserId> getDefaultDunningContact(@NonNull final BPartnerId bPartnerId) { return userRepository.getDefaultDunningContact(bPartnerId); } @NonNull @Override public Optional<VATIdentifier> getVATTaxId(@NonNull final BPartnerLocationId bpartnerLocationId) { final I_C_BPartner_Location bpartnerLocation = bpartnersRepo.getBPartnerLocationByIdEvenInactive(bpartnerLocationId); if (bpartnerLocation != null && Check.isNotBlank(bpartnerLocation.getVATaxID())) { return Optional.of(VATIdentifier.of(bpartnerLocation.getVATaxID())); } // if is set on Y, we will not use the vatid from partner final boolean ignorePartnerVATID = sysConfigBL.getBooleanValue(SYS_CONFIG_IgnorePartnerVATID, false); if (ignorePartnerVATID) { return Optional.empty(); } else { final I_C_BPartner bPartner = getById(bpartnerLocationId.getBpartnerId()); if (bPartner != null && Check.isNotBlank(bPartner.getVATaxID())) { return Optional.of(VATIdentifier.of(bPartner.getVATaxID())); } } return Optional.empty(); } @Override
public boolean isInvoiceEmailCcToMember(@NonNull final BPartnerId bpartnerId) { final I_C_BPartner bpartner = getById(bpartnerId); return bpartner.isInvoiceEmailCcToMember(); } @Override public I_C_BPartner_Location getBPartnerLocationByIdEvenInactive(@NonNull final BPartnerLocationId bpartnerLocationId) { return bpartnersRepo.getBPartnerLocationByIdEvenInactive(bpartnerLocationId); } @Override public List<I_C_BPartner_Location> getBPartnerLocationsByIds(final Set<BPartnerLocationId> bpartnerLocationIds) { return bpartnersRepo.retrieveBPartnerLocationsByIds(bpartnerLocationIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerBL.java
2
请完成以下Java代码
public void process(final I_EDI_Desadv desadv) { // make sure the desadvs that don't meet the sum percentage requirement won't get enqueued final BigDecimal currentSumPercentage = desadv.getFulfillmentPercent(); if (currentSumPercentage.compareTo(desadv.getFulfillmentPercentMin()) < 0) { skippedDesadvCollector.add(desadv); } else { // note: in here, the desadv has the item processor's trxName (as of this task) enqueueDesadv(enqueueDesadvRequest.getPInstanceId(), queue, desadv); } } }) .process(enqueueDesadvRequest.getDesadvIterator()); return EnqueueDesadvResult.builder() .skippedDesadvList(skippedDesadvCollector.build()) .build();
} private void enqueueDesadv( @Nullable final PInstanceId pInstanceId, @NonNull final IWorkPackageQueue queue, @NonNull final I_EDI_Desadv desadv) { final String trxName = InterfaceWrapperHelper.getTrxName(desadv); queue .newWorkPackage() .setAD_PInstance_ID(pInstanceId) .bindToTrxName(trxName) .addElement(desadv) .buildAndEnqueue(); desadv.setEDI_ExportStatus(X_EDI_Desadv.EDI_EXPORTSTATUS_Enqueued); InterfaceWrapperHelper.save(desadv); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\enqueue\DesadvEnqueuer.java
1
请完成以下Java代码
public class CrudInput { @NotNull private long id; @NotBlank private String title; private String body; private List<URI> tagUris; @JsonCreator public CrudInput(@JsonProperty("id") long id, @JsonProperty("title") String title, @JsonProperty("body") String body, @JsonProperty("tags") List<URI> tagUris) { this.id=id; this.title = title; this.body = body; this.tagUris = tagUris == null ? Collections.<URI> emptyList() : tagUris; } public String getTitle() { return title; } public String getBody() { return body; }
public long getId() { return id; } public void setId(long id) { this.id = id; } public void setTitle(String title) { this.title = title; } public void setBody(String body) { this.body = body; } public void setTagUris(List<URI> tagUris) { this.tagUris = tagUris; } @JsonProperty("tags") public List<URI> getTagUris() { return this.tagUris; } }
repos\tutorials-master\spring-5-rest-docs\src\main\java\com\baeldung\restdocs\CrudInput.java
1
请完成以下Java代码
public String getConfigurationLevel () { return (String)get_Value(COLUMNNAME_ConfigurationLevel); } /** 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); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) {
set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SysConfig.java
1
请完成以下Java代码
public BPartnerId getBPartnerId(@NonNull final ShipmentScheduleId shipmentScheduleId) { final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId); return scheduleEffectiveBL.getBPartnerId(shipmentSchedule); } @Nullable public ShipperId getShipperId(@Nullable final String shipperInternalName) { if (Check.isBlank(shipperInternalName)) { return null; } final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper); return shipper != null ? ShipperId.ofRepoId(shipper.getM_Shipper_ID()) : null;
} @Nullable public String getTrackingURL(@NonNull final String shipperInternalName) { final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper); return shipper != null ? shipper.getTrackingURL() : null; } @Nullable private I_M_Shipper loadShipper(@NonNull final String shipperInternalName) { return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentService.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getDeviceId() { return this.deviceId; } public void setDeviceId(@Nullable String deviceId) { this.deviceId = deviceId; } public @Nullable String getGroup() { return this.group; } public void setGroup(@Nullable String group) { this.group = group; } 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
请完成以下Java代码
public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) { Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, execution, fieldExtensions); if (delegate instanceof HttpRequestHandler) { ((HttpRequestHandler) delegate).handleHttpRequest(execution, httpRequest, client); } else { throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpRequestHandler.class); } } @Override public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) { Object delegate = resolveDelegateExpression(expression, execution, fieldExtensions); if (delegate instanceof HttpResponseHandler) { ((HttpResponseHandler) delegate).handleHttpResponse(execution, httpResponse); } else { throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpResponseHandler.class); } } /** * returns the expression text for this execution listener. Comes in handy if you want to check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); }
public static Object resolveDelegateExpression(Expression expression, VariableContainer variableScope, List<FieldExtension> fieldExtensions) { // Note: we can't cache the result of the expression, because the // execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}' Object delegate = expression.getValue(variableScope); if (fieldExtensions != null && fieldExtensions.size() > 0) { DelegateExpressionFieldInjectionMode injectionMode = CommandContextUtil.getCmmnEngineConfiguration().getDelegateExpressionFieldInjectionMode(); if (injectionMode == DelegateExpressionFieldInjectionMode.COMPATIBILITY) { CmmnClassDelegate.applyFieldExtensions(fieldExtensions, delegate, true); } else if (injectionMode == DelegateExpressionFieldInjectionMode.MIXED) { CmmnClassDelegate.applyFieldExtensions(fieldExtensions, delegate, false); } } return delegate; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\http\handler\DelegateExpressionHttpHandler.java
1
请完成以下Java代码
public void setM_HU_Item(final de.metas.handlingunits.model.I_M_HU_Item M_HU_Item) { set_ValueFromPO(COLUMNNAME_M_HU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, M_HU_Item); } @Override public void setM_HU_Item_ID (final int M_HU_Item_ID) { if (M_HU_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, M_HU_Item_ID); } @Override public int getM_HU_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID); } @Override public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID) { if (M_HU_Item_Storage_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID); } @Override public int getM_HU_Item_Storage_ID() {
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage.java
1
请完成以下Java代码
public String getCardId() { return cardId; } /** * Sets the value of the cardId property. * * @param value * allowed object is * {@link String } * */ public void setCardId(String value) { this.cardId = value; } /** * Gets the value of the expiryDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getExpiryDate() { return expiryDate; } /** * Sets the value of the expiryDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setExpiryDate(XMLGregorianCalendar value) { this.expiryDate = value; } /** * Gets the value of the validationDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getValidationDate() { return validationDate; } /** * Sets the value of the validationDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setValidationDate(XMLGregorianCalendar value) { this.validationDate = value; } /** * Gets the value of the validationId property. * * @return * possible object is * {@link String } * */ public String getValidationId() { return validationId;
} /** * Sets the value of the validationId property. * * @param value * allowed object is * {@link String } * */ public void setValidationId(String value) { this.validationId = value; } /** * Gets the value of the validationServer property. * * @return * possible object is * {@link String } * */ public String getValidationServer() { return validationServer; } /** * Sets the value of the validationServer property. * * @param value * allowed object is * {@link String } * */ public void setValidationServer(String value) { this.validationServer = 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\PatientAddressType.java
1
请在Spring Boot框架中完成以下Java代码
public class PeopleController { private static final SecureRandom SECURE_RANDOM = new SecureRandom(); @GetMapping("/people") @Timed(value = "people.all", longTask = true) public List<String> listPeople() throws InterruptedException { int seconds2Sleep = SECURE_RANDOM.nextInt(500); System.out.println(seconds2Sleep); TimeUnit.MILLISECONDS.sleep(seconds2Sleep); return Arrays.asList("Jim", "Tom", "Tim"); } @PostMapping("/people") @Timed(value = "people.update", longTask = true) public List<String> putPeople() throws InterruptedException { int seconds2Sleep = SECURE_RANDOM.nextInt(1000);
System.out.println(seconds2Sleep); TimeUnit.MILLISECONDS.sleep(seconds2Sleep); return Arrays.asList("Jim", "Tom", "Tim"); } @GetMapping("/asset") @Timed(value = "people.asset", longTask = true) public void test() throws Exception { throw new Exception("error!"); } @GetMapping("/property") @Timed(value = "people.property", longTask = true) public void property(HttpServletResponse response) throws IOException { response.sendRedirect("/asset"); } }
repos\tutorials-master\metrics\src\main\java\com\baeldung\metrics\micrometer\PeopleController.java
2
请完成以下Java代码
default DocumentEntityDescriptor getDocumentEntityDescriptor(final int AD_Window_ID) { final WindowId windowId = WindowId.of(AD_Window_ID); return getDocumentDescriptor(windowId).getEntityDescriptor(); } default DocumentEntityDescriptor getDocumentEntityDescriptor(@NonNull final WindowId windowId) { return getDocumentDescriptor(windowId).getEntityDescriptor(); } default String getTableNameOrNull(final int AD_Window_ID) { return getDocumentEntityDescriptor(AD_Window_ID).getTableName(); } default String getTableNameOrNull(final int AD_Window_ID, final DetailId detailId) { final DocumentEntityDescriptor descriptor = getDocumentEntityDescriptor(AD_Window_ID); if (detailId == null) { return descriptor.getTableName(); } else { return descriptor.getIncludedEntityByDetailId(detailId).getTableName(); } } default DocumentEntityDescriptor getDocumentEntityDescriptor(final DocumentPath documentPath) { final DocumentEntityDescriptor rootEntityDescriptor = getDocumentEntityDescriptor(documentPath.getWindowId()); if (documentPath.isRootDocument()) { return rootEntityDescriptor; } else { return rootEntityDescriptor.getIncludedEntityByDetailId(documentPath.getDetailId()); } } default TableRecordReference getTableRecordReference(@NonNull final DocumentPath documentPath) { return getTableRecordReferenceIfPossible(documentPath) .orElseThrow(() -> new AdempiereException("Cannot determine table/record from " + documentPath)); } default Optional<TableRecordReference> getTableRecordReferenceIfPossible(@NonNull final DocumentPath documentPath) {
if (documentPath.getWindowIdOrNull() == null || !documentPath.getWindowId().isInt()) { return Optional.empty(); } final DocumentEntityDescriptor rootEntityDescriptor = getDocumentEntityDescriptor(documentPath.getWindowId()); if (documentPath.isRootDocument()) { final DocumentId rootDocumentId = documentPath.getDocumentId(); if (!rootDocumentId.isInt()) { return Optional.empty(); } final String tableName = rootEntityDescriptor.getTableName(); final int recordId = rootDocumentId.toInt(); return Optional.of(TableRecordReference.of(tableName, recordId)); } else { final DocumentId includedRowId = documentPath.getSingleRowId(); if (!includedRowId.isInt()) { return Optional.empty(); } final DocumentEntityDescriptor includedEntityDescriptor = rootEntityDescriptor.getIncludedEntityByDetailId(documentPath.getDetailId()); final String tableName = includedEntityDescriptor.getTableName(); final int recordId = includedRowId.toInt(); return Optional.of(TableRecordReference.of(tableName, recordId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\DocumentDescriptorFactory.java
1
请在Spring Boot框架中完成以下Java代码
public ApplicationFactory applicationFactory(InstanceProperties instance, ManagementServerProperties management, ServerProperties server, PathMappedEndpoints pathMappedEndpoints, WebEndpointProperties webEndpoint, ObjectProvider<List<MetadataContributor>> metadataContributors, WebFluxProperties webFluxProperties) { return new ReactiveApplicationFactory(instance, management, server, pathMappedEndpoints, webEndpoint, new CompositeMetadataContributor(metadataContributors.getIfAvailable(Collections::emptyList)), webFluxProperties); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(RestTemplateBuilder.class) public static class BlockingRegistrationClientConfig { @Bean @ConditionalOnMissingBean public RegistrationClient registrationClient(ClientProperties client) { RestTemplateBuilder builder = new RestTemplateBuilder().connectTimeout(client.getConnectTimeout()) .readTimeout(client.getReadTimeout()); if (client.getUsername() != null && client.getPassword() != null) { builder = builder.basicAuthentication(client.getUsername(), client.getPassword()); } RestTemplate build = builder.build(); return new BlockingRegistrationClient(build); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean({ RestClient.Builder.class, ClientHttpRequestFactoryBuilder.class }) public static class RestClientRegistrationClientConfig { @Bean @ConditionalOnMissingBean public RegistrationClient registrationClient(ClientProperties client, RestClient.Builder restClientBuilder, ClientHttpRequestFactoryBuilder<?> clientHttpRequestFactoryBuilder) { var factorySettings = ClientHttpRequestFactorySettings.defaults() .withConnectTimeout(client.getConnectTimeout()) .withReadTimeout(client.getReadTimeout()); var clientHttpRequestFactory = clientHttpRequestFactoryBuilder.build(factorySettings); restClientBuilder = restClientBuilder.requestFactory(clientHttpRequestFactory); if (client.getUsername() != null && client.getPassword() != null) { restClientBuilder = restClientBuilder .requestInterceptor(new BasicAuthenticationInterceptor(client.getUsername(), client.getPassword())); } var restClient = restClientBuilder.build();
return new RestClientRegistrationClient(restClient); } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(WebClient.Builder.class) public static class ReactiveRegistrationClientConfig { @Bean @ConditionalOnMissingBean public RegistrationClient registrationClient(ClientProperties client, WebClient.Builder webClient) { if (client.getUsername() != null && client.getPassword() != null) { webClient = webClient.filter(basicAuthentication(client.getUsername(), client.getPassword())); } return new ReactiveRegistrationClient(webClient.build(), client.getReadTimeout()); } } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\config\SpringBootAdminClientAutoConfiguration.java
2
请完成以下Java代码
private static PInstanceId createOLCandsSelection(final List<OLCand> olCands) { final ImmutableSet<OLCandId> olCandIds = extractOLCandIds(olCands); return DB.createT_Selection(olCandIds, ITrx.TRXNAME_None); } private static ImmutableSet<OLCandId> extractOLCandIds(final List<OLCand> olCands) { return olCands.stream().map(olCand -> OLCandId.ofRepoId(olCand.getId())).collect(ImmutableSet.toImmutableSet()); } private void allocatePayments(final POSOrder posOrder) { trxManager.assertThreadInheritedTrxExists(); final I_C_Invoice invoice = getSingleInvoice(posOrder); for (final POSPayment posPayment : posOrder.getPaymentsNotDeleted()) { final I_C_Payment paymentReceipt; if (posPayment.getPaymentReceiptId() != null) { paymentReceipt = paymentBL.getById(posPayment.getPaymentReceiptId()); } else { paymentReceipt = createPaymentReceipt(posPayment, posOrder); final PaymentId paymentReceiptId = PaymentId.ofRepoId(paymentReceipt.getC_Payment_ID()); posOrder.updatePaymentById(posPayment.getLocalIdNotNull(), payment -> payment.withPaymentReceipt(paymentReceiptId)); } allocationBL.autoAllocateSpecificPayment(invoice, paymentReceipt, true); } } private I_C_Invoice getSingleInvoice(final POSOrder posOrder) {
final OrderId salesOrderId = posOrder.getSalesOrderId(); if (salesOrderId == null) { throw new AdempiereException("No sales order generated for " + posOrder); } final List<I_C_Invoice> invoices = invoiceDAO.getInvoicesForOrderIds(ImmutableList.of(salesOrderId)); if (invoices.isEmpty()) { throw new AdempiereException("No invoices were generated for " + posOrder); } else if (invoices.size() > 1) { throw new AdempiereException("More than one invoice was generated for " + posOrder); } return invoices.get(0); } private I_C_Payment createPaymentReceipt(@NonNull final POSPayment posPayment, @NonNull POSOrder posOrder) { posPayment.assertNoPaymentReceipt(); return paymentBL.newInboundReceiptBuilder() .adOrgId(posOrder.getOrgId()) .orgBankAccountId(posOrder.getCashbookId()) .bpartnerId(posOrder.getShipToCustomerId()) .payAmt(posPayment.getAmount().toBigDecimal()) .currencyId(posPayment.getAmount().getCurrencyId()) .tenderType(posPayment.getPaymentMethod().getTenderType()) .dateTrx(posOrder.getDate()) .createAndProcess(); // TODO: add the payment to bank statement } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\async\C_POSOrder_CreateInvoiceAndShipment.java
1
请完成以下Java代码
public boolean isDayAvailable(final Instant date) { return isActive() && isDayAvailable(date.atZone(SystemTime.zoneId()).getDayOfWeek()); } public int getAvailableDaysPerWeek() { return availableDaysOfWeek.size(); } public boolean isDayAvailable(@NonNull final DayOfWeek dayOfWeek) { return availableDaysOfWeek.contains(dayOfWeek); } @Deprecated public Timestamp getDayStart(final Timestamp date) { final Instant dayStart = getDayStart(date.toInstant()); return Timestamp.from(dayStart); } public Instant getDayStart(@NonNull final Instant date) { return getDayStart(date.atZone(SystemTime.zoneId())).toInstant(); } public LocalDateTime getDayStart(final LocalDateTime date) { return getDayStart(date.atZone(SystemTime.zoneId())).toLocalDateTime(); } public ZonedDateTime getDayStart(final ZonedDateTime date) { if (isTimeSlot()) {
return date.toLocalDate().atTime(getTimeSlotStart()).atZone(date.getZone()); } else { return date.toLocalDate().atStartOfDay().atZone(date.getZone()); } } @Deprecated public Timestamp getDayEnd(final Timestamp date) { final LocalDateTime dayEnd = getDayEnd(TimeUtil.asLocalDateTime(date)); return TimeUtil.asTimestamp(dayEnd); } public Instant getDayEnd(final Instant date) { return getDayEnd(date.atZone(SystemTime.zoneId())).toInstant(); } public LocalDateTime getDayEnd(final LocalDateTime date) { return getDayEnd(date.atZone(SystemTime.zoneId())).toLocalDateTime(); } public ZonedDateTime getDayEnd(final ZonedDateTime date) { if (isTimeSlot()) { return date.toLocalDate().atTime(timeSlotEnd).atZone(date.getZone()); } else { return date.toLocalDate().atTime(LocalTime.MAX).atZone(date.getZone()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\ResourceType.java
1
请完成以下Java代码
public StringBuilder asStringBuilder() { return sb; } public boolean isAutoAppendSeparator() { return autoAppendSeparator; } public TokenizedStringBuilder setAutoAppendSeparator(boolean autoAppendSeparator) { this.autoAppendSeparator = autoAppendSeparator; return this; } public boolean isLastAppendedIsSeparator() { return lastAppendedIsSeparator; } public String getSeparator() { return separator; } public TokenizedStringBuilder append(final Object obj) { if (autoAppendSeparator) { appendSeparatorIfNeeded(); } sb.append(obj); lastAppendedIsSeparator = false;
return this; } public TokenizedStringBuilder appendSeparatorIfNeeded() { if (lastAppendedIsSeparator) { return this; } if (sb.length() <= 0) { return this; } sb.append(separator); lastAppendedIsSeparator = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\TokenizedStringBuilder.java
1