instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public BooleanWithReason getEnabled() { return esSystem.getEnabled(); } public RestHighLevelClient elasticsearchClient() { return esSystem.elasticsearchClient(); } public void addListener(@NonNull final FTSConfigChangedListener listener) { ftsConfigRepository.addListener(listener); } public FTSConfig getConfigByESIndexName(@NonNull final String esIndexName) { return ftsConfigRepository.getByESIndexName(esIndexName); } public FTSConfig getConfigById(@NonNull final FTSConfigId ftsConfigId) { return ftsConfigRepository.getConfigById(ftsConfigId); } public FTSConfigSourceTablesMap getSourceTables() { return ftsConfigRepository.getSourceTables(); } public Optional<FTSFilterDescriptor> getFilterByTargetTableName(@NonNull final String targetTableName) {
return ftsFilterDescriptorRepository.getByTargetTableName(targetTableName); } public FTSFilterDescriptor getFilterById(@NonNull final FTSFilterDescriptorId id) { return ftsFilterDescriptorRepository.getById(id); } public void updateConfigFields(@NonNull final I_ES_FTS_Config record) { final FTSConfigId configId = FTSConfigId.ofRepoId(record.getES_FTS_Config_ID()); final Set<ESFieldName> esFieldNames = ESDocumentToIndexTemplate.ofJsonString(record.getES_DocumentToIndexTemplate()).getESFieldNames(); ftsConfigRepository.setConfigFields(configId, esFieldNames); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSConfigService.java
2
请完成以下Java代码
public class PeakElementFinder { public List<Integer> findPeakElements(int[] arr) { int n = arr.length; List<Integer> peaks = new ArrayList<>(); if (n == 0) { return peaks; } for (int i = 0; i < n; i++) { if (isPeak(arr, i, n)) { peaks.add(arr[i]); } while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } } return peaks; }
private boolean isPeak(int[] arr, int index, int n) { if (index == 0) { return n > 1 ? arr[index] >= arr[index + 1] : true; } else if (index == n - 1) { return arr[index] >= arr[index - 1]; } else if (arr[index] == arr[index + 1] && arr[index] > arr[index - 1]) { int i = index; while (i < n - 1 && arr[i] == arr[i + 1]) { i++; } return i == n - 1 || arr[i] > arr[i + 1]; } else { return arr[index] >= arr[index - 1] && arr[index] >= arr[index + 1]; } } }
repos\tutorials-master\core-java-modules\core-java-collections-array-list-2\src\main\java\com\baeldung\peakelements\PeakElementFinder.java
1
请完成以下Java代码
private StockDataAggregateItem viewRowToStockDataItem(@NonNull final I_MD_Stock_WarehouseAndProduct_v record) { return StockDataAggregateItem.builder() .productCategoryId(record.getM_Product_Category_ID()) .productId(record.getM_Product_ID()) .productValue(record.getProductValue()) .warehouseId(record.getM_Warehouse_ID()) .qtyOnHand(record.getQtyOnHand()) .build(); } /** Used when running against a real DB */ private StockDataAggregateItem recordRowToStockDataItem(@NonNull final I_T_MD_Stock_WarehouseAndProduct record) { return StockDataAggregateItem.builder() .productCategoryId(record.getM_Product_Category_ID()) .productId(record.getM_Product_ID()) .productValue(record.getProductValue()) .warehouseId(record.getM_Warehouse_ID()) .qtyOnHand(record.getQtyOnHand()) .build(); } public Stream<StockDataItem> streamStockDataItems(@NonNull final StockDataMultiQuery multiQuery) { final IQuery<I_MD_Stock> query = multiQuery .getStockDataQueries() .stream() .map(this::createStockDataItemQuery) .reduce(IQuery.unionDistict()) .orElse(null); if (query == null) { return Stream.empty(); } return query .iterateAndStream() .map(this::recordToStockDataItem); }
private IQuery<I_MD_Stock> createStockDataItemQuery(@NonNull final StockDataQuery query) { final IQueryBuilder<I_MD_Stock> queryBuilder = queryBL.createQueryBuilder(I_MD_Stock.class); queryBuilder.addEqualsFilter(I_MD_Stock.COLUMNNAME_M_Product_ID, query.getProductId()); if (!query.getWarehouseIds().isEmpty()) { queryBuilder.addInArrayFilter(I_MD_Stock.COLUMNNAME_M_Warehouse_ID, query.getWarehouseIds()); } // // Storage Attributes Key { final AttributesKeyQueryHelper<I_MD_Stock> helper = AttributesKeyQueryHelper.createFor(I_MD_Stock.COLUMN_AttributesKey); final IQueryFilter<I_MD_Stock> attributesKeysFilter = helper.createFilter(ImmutableList.of(AttributesKeyPatternsUtil.ofAttributeKey(query.getStorageAttributesKey()))); queryBuilder.filter(attributesKeysFilter); } return queryBuilder.create(); } private StockDataItem recordToStockDataItem(@NonNull final I_MD_Stock record) { return StockDataItem.builder() .productId(ProductId.ofRepoId(record.getM_Product_ID())) .warehouseId(WarehouseId.ofRepoId(record.getM_Warehouse_ID())) .storageAttributesKey(AttributesKey.ofString(record.getAttributesKey())) .qtyOnHand(record.getQtyOnHand()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\StockRepository.java
1
请完成以下Java代码
public class CdiResolver extends ELResolver { protected BeanManager getBeanManager() { return BeanManagerLookup.getBeanManager(); } protected javax.el.ELResolver getWrappedResolver() { BeanManager beanManager = getBeanManager(); javax.el.ELResolver resolver = beanManager.getELResolver(); return resolver; } @Override public Class< ? > getCommonPropertyType(ELContext context, Object base) { return getWrappedResolver().getCommonPropertyType(wrapContext(context), base); } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return getWrappedResolver().getFeatureDescriptors(wrapContext(context), base); } @Override public Class< ? > getType(ELContext context, Object base, Object property) { return getWrappedResolver().getType(wrapContext(context), base, property); } @Override public Object getValue(ELContext context, Object base, Object property) { //we need to resolve a bean only for the first "member" of expression, e.g. bean.property1.property2
if (base == null) { Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager()); if (result != null) { context.setPropertyResolved(true); } return result; } else { return null; } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return getWrappedResolver().isReadOnly(wrapContext(context), base, property); } @Override public void setValue(ELContext context, Object base, Object property, Object value) { getWrappedResolver().setValue(wrapContext(context), base, property, value); } @Override public Object invoke(ELContext context, Object base, Object method, java.lang.Class< ? >[] paramTypes, Object[] params) { return getWrappedResolver().invoke(wrapContext(context), base, method, paramTypes, params); } protected javax.el.ELContext wrapContext(ELContext context) { return new ElContextDelegate(context, getWrappedResolver()); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\el\CdiResolver.java
1
请在Spring Boot框架中完成以下Java代码
public void setProjectType (final java.lang.String ProjectType) { set_Value (COLUMNNAME_ProjectType, ProjectType); } @Override public java.lang.String getProjectType() { return get_ValueAsString(COLUMNNAME_ProjectType); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() {
return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setS_ExternalProjectReference_ID (final int S_ExternalProjectReference_ID) { if (S_ExternalProjectReference_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, S_ExternalProjectReference_ID); } @Override public int getS_ExternalProjectReference_ID() { return get_ValueAsInt(COLUMNNAME_S_ExternalProjectReference_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalProjectReference.java
2
请在Spring Boot框架中完成以下Java代码
public String getSuperExecutionUrl() { return superExecutionUrl; } public void setSuperExecutionUrl(String superExecutionUrl) { this.superExecutionUrl = superExecutionUrl; } @ApiModelProperty(example = "5") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "http://localhost:8182/runtime/process-instances/5") public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } public boolean isSuspended() {
return suspended; } public void setSuspended(boolean suspended) { this.suspended = suspended; } @ApiModelProperty(example = "null") public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionResponse.java
2
请完成以下Java代码
public IdentityLinkQueryObject getInvolvedUserIdentityLink() { return involvedUserIdentityLink; } public IdentityLinkQueryObject getInvolvedGroupIdentityLink() { return involvedGroupIdentityLink; } public boolean isWithJobException() { return withJobException; } public String getLocale() { return locale; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } }
return hasOrderByForColumn(HistoricProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public String getRootScopeId() { return rootScopeId; } public String getParentScopeId() { return parentScopeId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请完成以下Java代码
public Builder setJoinAnd(final boolean joinAnd) { this.joinAnd = joinAnd; return this; } public Builder setFieldName(final String fieldName) { this.fieldName = fieldName; return this; } public Builder setOperator(@NonNull final Operator operator) { this.operator = operator; return this; } public Builder setOperator()
{ operator = valueTo != null ? Operator.BETWEEN : Operator.EQUAL; return this; } public Builder setValue(@Nullable final Object value) { this.value = value; return this; } public Builder setValueTo(@Nullable final Object valueTo) { this.valueTo = valueTo; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParam.java
1
请完成以下Spring Boot application配置
spring.jpa.hibernate.ddl-auto=none spring.jpa.database=mysql spring.jpa.open-in-view=true spring.jpa.show-sql=true server.port=8088 #logging.level.org.hibernate=DEBUG logging.level.org.hibernate.SQL=DEBUG spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.hibernate.use-new-id-generator-mappings= false # book api db" sp
ring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root
repos\springboot-demo-master\GraphQL\src\main\resources\application.properties
2
请完成以下Java代码
protected void sortResolvedResources(List<HalResource<?>> resolvedResources) { Comparator<HalResource<?>> comparator = getResourceComparator(); if (comparator != null) { Collections.sort(resolvedResources, comparator); } } /** * @return the cache for this resolver */ protected Cache getCache() { return Hal.getInstance().getHalRelationCache(getHalResourceClass()); } /** * Returns a list with all resources which are cached. * * @param linkedIds the ids to resolve * @param cache the cache to use * @param notCachedLinkedIds a list with ids which are not found in the cache * @return the cached resources */ protected List<HalResource<?>> resolveCachedLinks(String[] linkedIds, Cache cache, List<String> notCachedLinkedIds) { ArrayList<HalResource<?>> resolvedResources = new ArrayList<HalResource<?>>(); for (String linkedId : linkedIds) { HalResource<?> resource = (HalResource<?>) cache.get(linkedId); if (resource != null) { resolvedResources.add(resource); } else { notCachedLinkedIds.add(linkedId); } } return resolvedResources; } /** * Put a resource into the cache. */ protected void putIntoCache(List<HalResource<?>> notCachedResources) { Cache cache = getCache(); for (HalResource<?> notCachedResource : notCachedResources) { cache.put(getResourceId(notCachedResource), notCachedResource);
} } /** * @return the class of the entity which is resolved */ protected abstract Class<?> getHalResourceClass(); /** * @return a comparator for this HAL resource if not overridden sorting is skipped */ protected Comparator<HalResource<?>> getResourceComparator() { return null; } /** * @return the resolved resources which are currently not cached */ protected abstract List<HalResource<?>> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine); /** * @return the id which identifies a resource in the cache */ protected abstract String getResourceId(HalResource<?> resource); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\cache\HalCachingLinkResolver.java
1
请在Spring Boot框架中完成以下Java代码
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("MyShiroRealm.doGetAuthenticationInfo()"); String username = (String)token.getPrincipal(); System.out.println(token.getCredentials()); //query user by username //in here ,you can cache some data for efficient UserInfo userInfo = userInfoService.findByUsername(username); System.out.println("----->>userInfo="+userInfo); if(userInfo == null){ return null; } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( userInfo, //username userInfo.getPassword(), //password new MyByteSource(userInfo.getCredentialsSalt()), //ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt getName() //realm name ); return authenticationInfo; }
//authority controller @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("authority config-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal(); for(SysRole role:userInfo.getRoleList()){ authorizationInfo.addRole(role.getRole()); for(SysPermission p:role.getPermissions()){ authorizationInfo.addStringPermission(p.getPermission()); } } return authorizationInfo; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\config\MyShiroRealm.java
2
请完成以下Java代码
public Class<? extends BaseElement> getHandledType() { return SequenceFlow.class; } @Override protected void executeParse(BpmnParse bpmnParse, SequenceFlow sequenceFlow) { ScopeImpl scope = bpmnParse.getCurrentScope(); ActivityImpl sourceActivity = scope.findActivity(sequenceFlow.getSourceRef()); ActivityImpl destinationActivity = scope.findActivity(sequenceFlow.getTargetRef()); Expression skipExpression; if (StringUtils.isNotEmpty(sequenceFlow.getSkipExpression())) { ExpressionManager expressionManager = bpmnParse.getExpressionManager(); skipExpression = expressionManager.createExpression(sequenceFlow.getSkipExpression()); } else { skipExpression = null;
} TransitionImpl transition = sourceActivity.createOutgoingTransition(sequenceFlow.getId(), skipExpression); bpmnParse.getSequenceFlows().put(sequenceFlow.getId(), transition); transition.setProperty("name", sequenceFlow.getName()); transition.setProperty("documentation", sequenceFlow.getDocumentation()); transition.setDestination(destinationActivity); if (StringUtils.isNotEmpty(sequenceFlow.getConditionExpression())) { Condition expressionCondition = new UelExpressionCondition(sequenceFlow.getConditionExpression()); transition.setProperty(PROPERTYNAME_CONDITION_TEXT, sequenceFlow.getConditionExpression()); transition.setProperty(PROPERTYNAME_CONDITION, expressionCondition); } createExecutionListenersOnTransition(bpmnParse, sequenceFlow.getExecutionListeners(), transition); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SequenceFlowParseHandler.java
1
请完成以下Java代码
public void customize(MutableProjectDescription description) { if (!StringUtils.hasText(description.getApplicationName())) { description .setApplicationName(this.metadata.getConfiguration().generateApplicationName(description.getName())); } String targetArtifactId = determineValue(description.getArtifactId(), () -> this.metadata.getArtifactId().getContent()); description.setArtifactId(cleanMavenCoordinate(targetArtifactId, "-")); if (targetArtifactId.equals(description.getBaseDirectory())) { description.setBaseDirectory(cleanMavenCoordinate(targetArtifactId, "-")); } if (!StringUtils.hasText(description.getDescription())) { description.setDescription(this.metadata.getDescription().getContent()); } String targetGroupId = determineValue(description.getGroupId(), () -> this.metadata.getGroupId().getContent()); description.setGroupId(cleanMavenCoordinate(targetGroupId, ".")); if (!StringUtils.hasText(description.getName())) { description.setName(this.metadata.getName().getContent()); } else if (targetArtifactId.equals(description.getName())) { description.setName(cleanMavenCoordinate(targetArtifactId, "-")); } description.setPackageName(this.metadata.getConfiguration() .cleanPackageName(description.getPackageName(), description.getLanguage(), this.metadata.getPackageName().getContent())); if (description.getPlatformVersion() == null) { description.setPlatformVersion(Version.parse(this.metadata.getBootVersions().getDefault().getId())); } if (!StringUtils.hasText(description.getVersion())) { description.setVersion(this.metadata.getVersion().getContent()); } } private String cleanMavenCoordinate(String coordinate, String delimiter) { String[] elements = coordinate.split("[^\\w\\-.]+"); if (elements.length == 1) { return coordinate; } StringBuilder builder = new StringBuilder(); for (String element : elements) {
if (shouldAppendDelimiter(element, builder)) { builder.append(delimiter); } builder.append(element); } return builder.toString(); } private boolean shouldAppendDelimiter(String element, StringBuilder builder) { if (builder.isEmpty()) { return false; } for (char c : VALID_MAVEN_SPECIAL_CHARACTERS) { int prevIndex = builder.length() - 1; if (element.charAt(0) == c || builder.charAt(prevIndex) == c) { return false; } } return true; } private String determineValue(String candidate, Supplier<String> fallback) { return (StringUtils.hasText(candidate)) ? candidate : fallback.get(); } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\project\MetadataProjectDescriptionCustomizer.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("adLanguage", adLanguage) .addValue(userRolePermissionsKey) .toString(); } @Override public int hashCode() { return Objects.hash(userRolePermissionsKey, adLanguage); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof MenuTreeKey) { final MenuTreeKey other = (MenuTreeKey)obj; return Objects.equals(userRolePermissionsKey, other.userRolePermissionsKey) && Objects.equals(adLanguage, other.adLanguage); } else { return false; } } public UserRolePermissionsKey getUserRolePermissionsKey() { return userRolePermissionsKey; } public String getAD_Language() { return adLanguage; } } private static final class UserMenuFavorites { private static Builder builder() { return new Builder(); } private final UserId adUserId; private final Set<Integer> menuIds = ConcurrentHashMap.newKeySet(); private UserMenuFavorites(final Builder builder) { adUserId = builder.adUserId; Check.assumeNotNull(adUserId, "Parameter adUserId is not null");
menuIds.addAll(builder.menuIds); } public UserId getAdUserId() { return adUserId; } public boolean isFavorite(final MenuNode menuNode) { return menuIds.contains(menuNode.getAD_Menu_ID()); } public void setFavorite(final int adMenuId, final boolean favorite) { if (favorite) { menuIds.add(adMenuId); } else { menuIds.remove(adMenuId); } } public static class Builder { private UserId adUserId; private final Set<Integer> menuIds = new HashSet<>(); private Builder() { } public MenuTreeRepository.UserMenuFavorites build() { return new UserMenuFavorites(this); } public Builder adUserId(final UserId adUserId) { this.adUserId = adUserId; return this; } public Builder addMenuIds(final List<Integer> adMenuIds) { if (adMenuIds.isEmpty()) { return this; } menuIds.addAll(adMenuIds); return this; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuTreeRepository.java
1
请完成以下Java代码
public BigDecimal getIntegrationAmount() { return integrationAmount; } public void setIntegrationAmount(BigDecimal integrationAmount) { this.integrationAmount = integrationAmount; } public BigDecimal getRealAmount() { return realAmount; } public void setRealAmount(BigDecimal realAmount) { this.realAmount = realAmount; } public Integer getGiftIntegration() { return giftIntegration; } public void setGiftIntegration(Integer giftIntegration) { this.giftIntegration = giftIntegration; } public Integer getGiftGrowth() { return giftGrowth; } public void setGiftGrowth(Integer giftGrowth) { this.giftGrowth = giftGrowth; } public String getProductAttr() { return productAttr; } public void setProductAttr(String productAttr) { this.productAttr = productAttr; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" [");
sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", orderId=").append(orderId); sb.append(", orderSn=").append(orderSn); sb.append(", productId=").append(productId); sb.append(", productPic=").append(productPic); sb.append(", productName=").append(productName); sb.append(", productBrand=").append(productBrand); sb.append(", productSn=").append(productSn); sb.append(", productPrice=").append(productPrice); sb.append(", productQuantity=").append(productQuantity); sb.append(", productSkuId=").append(productSkuId); sb.append(", productSkuCode=").append(productSkuCode); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", promotionName=").append(promotionName); sb.append(", promotionAmount=").append(promotionAmount); sb.append(", couponAmount=").append(couponAmount); sb.append(", integrationAmount=").append(integrationAmount); sb.append(", realAmount=").append(realAmount); sb.append(", giftIntegration=").append(giftIntegration); sb.append(", giftGrowth=").append(giftGrowth); sb.append(", productAttr=").append(productAttr); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderItem.java
1
请完成以下Java代码
public void setup() { switch (type) { case "array-list": collection = new ArrayList<String>(); break; case "tree-set": collection = new TreeSet<String>(); break; default: throw new UnsupportedOperationException(); } for (int i = 0; i < size; i++) { collection.add(String.valueOf(i)); } } @Benchmark public String[] zero_sized() { return collection.toArray(new String[0]); }
@Benchmark public String[] pre_sized() { return collection.toArray(new String[collection.size()]); } public static void main(String[] args) { try { org.openjdk.jmh.Main.main(args); } catch (IOException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\toarraycomparison\ToArrayBenchmark.java
1
请完成以下Java代码
public void setCaffeine(CacheProperties.Caffeine caffeine) { this.caffeine = caffeine; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class CaffeineCacheProviderProperties { private boolean allowNullValues = true; private boolean useSystemScheduler = true; private String defaultSpec = ""; public boolean isAllowNullValues() { return allowNullValues; } public String getDefaultSpec() { return defaultSpec; } public void setAllowNullValues(boolean allowNullValues) { this.allowNullValues = allowNullValues; } public void setDefaultSpec(String defaultSpec) { this.defaultSpec = defaultSpec; }
public boolean isUseSystemScheduler() { return useSystemScheduler; } public void setUseSystemScheduler(boolean useSystemScheduler) { this.useSystemScheduler = useSystemScheduler; } } public static class SimpleCacheProviderProperties { private boolean allowNullValues = true; public boolean isAllowNullValues() { return allowNullValues; } public void setAllowNullValues(boolean allowNullValues) { this.allowNullValues = allowNullValues; } } }
repos\Activiti-develop\activiti-core-common\activiti-spring-cache-manager\src\main\java\org\activiti\spring\cache\ActivitiSpringCacheManagerProperties.java
1
请完成以下Java代码
String buildAddress2(@NonNull final I_I_Pharma_BPartner importRecord) { final StringBuilder sb = new StringBuilder(); if (!Check.isEmpty(importRecord.getb00hnrb())) { sb.append(importRecord.getb00hnrb()); } if (!Check.isEmpty(importRecord.getb00hnrbz())) { if (sb.length() > 0) { sb.append(" "); } sb.append(importRecord.getb00hnrbz()); } return sb.toString(); } @VisibleForTesting String buildPOBox(@NonNull final I_I_Pharma_BPartner importRecord) { final StringBuilder sb = new StringBuilder(); if (!Check.isEmpty(importRecord.getb00plzpf1())) { sb.append(importRecord.getb00plzpf1()); } if (!Check.isEmpty(importRecord.getb00ortpf())) { if (sb.length() > 0) { sb.append("\\n"); } sb.append(importRecord.getb00plzpf1()); } if (!Check.isEmpty(importRecord.getb00pf1())) { if (sb.length() > 0) { sb.append("\\n"); } sb.append(importRecord.getb00pf1()); } if (!Check.isEmpty(importRecord.getb00plzgk1())) { if (sb.length() > 0) { sb.append("\\n"); } sb.append(importRecord.getb00plzgk1()); } return sb.toString(); } private void updatePhoneAndFax(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_C_BPartner_Location bpartnerLocation) { if (!Check.isEmpty(importRecord.getb00tel1()))
{ bpartnerLocation.setPhone(importRecord.getb00tel1()); } if (!Check.isEmpty(importRecord.getb00tel2())) { bpartnerLocation.setPhone2(importRecord.getb00tel2()); } if (!Check.isEmpty(importRecord.getb00fax1())) { bpartnerLocation.setFax(importRecord.getb00fax1()); } if (!Check.isEmpty(importRecord.getb00fax2())) { bpartnerLocation.setFax2(importRecord.getb00fax2()); } } private void updateEmails(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_C_BPartner_Location bpartnerLocation) { if (!Check.isEmpty(importRecord.getb00email())) { bpartnerLocation.setEMail(importRecord.getb00email()); } if (!Check.isEmpty(importRecord.getb00email2())) { bpartnerLocation.setEMail2(importRecord.getb00email2()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerLocationImportHelper.java
1
请在Spring Boot框架中完成以下Java代码
public String login(// @ApiParam("Username") @RequestParam String username, // @ApiParam("Password") @RequestParam String password) { return userService.signin(username, password); } @PostMapping("/signup") @ApiOperation(value = "${UserController.signup}") @ApiResponses(value = {// @ApiResponse(code = 400, message = "Something went wrong"), // @ApiResponse(code = 403, message = "Access denied"), // @ApiResponse(code = 422, message = "Username is already in use"), // @ApiResponse(code = 500, message = "Expired or invalid JWT token")}) public String signup(@ApiParam("Signup User") @RequestBody UserDataDTO user) { return userService.signup(modelMapper.map(user, User.class)); } @DeleteMapping(value = "/{username}") @PreAuthorize("hasRole('ROLE_ADMIN')") @ApiOperation(value = "${UserController.delete}") @ApiResponses(value = {// @ApiResponse(code = 400, message = "Something went wrong"), // @ApiResponse(code = 403, message = "Access denied"), // @ApiResponse(code = 404, message = "The user doesn't exist"), // @ApiResponse(code = 500, message = "Expired or invalid JWT token")}) public String delete(@ApiParam("Username") @PathVariable String username) { userService.delete(username); return username; }
@GetMapping(value = "/{username}") @PreAuthorize("hasRole('ROLE_ADMIN')") @ApiOperation(value = "${UserController.search}", response = UserResponseDTO.class) @ApiResponses(value = {// @ApiResponse(code = 400, message = "Something went wrong"), // @ApiResponse(code = 403, message = "Access denied"), // @ApiResponse(code = 404, message = "The user doesn't exist"), // @ApiResponse(code = 500, message = "Expired or invalid JWT token")}) public UserResponseDTO search(@ApiParam("Username") @PathVariable String username) { return modelMapper.map(userService.search(username), UserResponseDTO.class); } @GetMapping(value = "/me") @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_CLIENT')") @ApiOperation(value = "${UserController.me}", response = UserResponseDTO.class) @ApiResponses(value = {// @ApiResponse(code = 400, message = "Something went wrong"), // @ApiResponse(code = 403, message = "Access denied"), // @ApiResponse(code = 500, message = "Expired or invalid JWT token")}) public UserResponseDTO whoami(HttpServletRequest req) { return modelMapper.map(userService.whoami(req), UserResponseDTO.class); } }
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\controller\UserController.java
2
请在Spring Boot框架中完成以下Java代码
private String makeToken(XxlJobUser xxlJobUser){ String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser); String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16); return tokenHex; } private XxlJobUser parseToken(String tokenHex){ XxlJobUser xxlJobUser = null; if (tokenHex != null) { String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray()); // username_password(md5) xxlJobUser = JacksonUtil.readValue(tokenJson, XxlJobUser.class); } return xxlJobUser; } public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean ifRemember){ // param if (username==null || username.trim().length()==0 || password==null || password.trim().length()==0){ return new ReturnT<String>(500, I18nUtil.getString("login_param_empty")); } // valid passowrd XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(username); if (xxlJobUser == null) { return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid")); } String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes()); if (!passwordMd5.equals(xxlJobUser.getPassword())) { return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid")); } String loginToken = makeToken(xxlJobUser); // do login CookieUtil.set(response, LOGIN_IDENTITY_KEY, loginToken, ifRemember); return ReturnT.SUCCESS; } /**
* logout * * @param request * @param response */ public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY); return ReturnT.SUCCESS; } /** * logout * * @param request * @return */ public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response){ String cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY); if (cookieToken != null) { XxlJobUser cookieUser = null; try { cookieUser = parseToken(cookieToken); } catch (Exception e) { logout(request, response); } if (cookieUser != null) { XxlJobUser dbUser = xxlJobUserDao.loadByUserName(cookieUser.getUsername()); if (dbUser != null) { if (cookieUser.getPassword().equals(dbUser.getPassword())) { return dbUser; } } } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\service\LoginService.java
2
请完成以下Java代码
public ExtendedResponse createExtendedResponse(String id, byte[] berValue, int offset, int length) { return null; } /** * Only minimal support for <a target="_blank" href= * "https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf"> BER * encoding </a>; just what is necessary for the Password Modify request. * */ private void berEncode(byte type, byte[] src, ByteArrayOutputStream dest) { int length = src.length; dest.write(type); if (length < 128) { dest.write(length); } else if ((length & 0x0000_00FF) == length) { dest.write((byte) 0x81); dest.write((byte) (length & 0xFF)); } else if ((length & 0x0000_FFFF) == length) { dest.write((byte) 0x82); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF));
} else if ((length & 0x00FF_FFFF) == length) { dest.write((byte) 0x83); dest.write((byte) ((length >> 16) & 0xFF)); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } else { dest.write((byte) 0x84); dest.write((byte) ((length >> 24) & 0xFF)); dest.write((byte) ((length >> 16) & 0xFF)); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } try { dest.write(src); } catch (IOException ex) { throw new IllegalArgumentException("Failed to BER encode provided value of type: " + type); } } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsManager.java
1
请完成以下Java代码
public int getMSV3_BestellungAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwort_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3_BestellungAntwortAuftrag. @param MSV3_BestellungAntwortAuftrag_ID MSV3_BestellungAntwortAuftrag */ @Override public void setMSV3_BestellungAntwortAuftrag_ID (int MSV3_BestellungAntwortAuftrag_ID) { if (MSV3_BestellungAntwortAuftrag_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAntwortAuftrag_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAntwortAuftrag_ID, Integer.valueOf(MSV3_BestellungAntwortAuftrag_ID)); } /** Get MSV3_BestellungAntwortAuftrag. @return MSV3_BestellungAntwortAuftrag */ @Override public int getMSV3_BestellungAntwortAuftrag_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwortAuftrag_ID); if (ii == null) return 0; return ii.intValue(); } /** Set GebindeId. @param MSV3_GebindeId GebindeId */ @Override public void setMSV3_GebindeId (java.lang.String MSV3_GebindeId) { set_Value (COLUMNNAME_MSV3_GebindeId, MSV3_GebindeId); } /** Get GebindeId. @return GebindeId */ @Override public java.lang.String getMSV3_GebindeId ()
{ return (java.lang.String)get_Value(COLUMNNAME_MSV3_GebindeId); } /** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAntwortAuftrag.java
1
请完成以下Java代码
public Optional<String> getJsonValue() { return kv.getJsonValue(); } @Override public Object getValue() { return kv.getValue(); } @Override public String getValueAsString() { return kv.getValueAsString(); } @Override public int getDataPoints() {
int length; switch (getDataType()) { case STRING: length = getStrValue().get().length(); break; case JSON: length = getJsonValue().get().length(); break; default: return 1; } return Math.max(1, (length + MAX_CHARS_PER_DATA_POINT - 1) / MAX_CHARS_PER_DATA_POINT); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicTsKvEntry.java
1
请完成以下Java代码
public CompletionCondition getCompletionCondition() { return completionConditionChild.getChild(this); } public void setCompletionCondition(CompletionCondition completionCondition) { completionConditionChild.setChild(this, completionCondition); } public boolean isSequential() { return isSequentialAttribute.getValue(this); } public void setSequential(boolean sequential) { isSequentialAttribute.setValue(this, sequential); } public MultiInstanceFlowCondition getBehavior() { return behaviorAttribute.getValue(this); } public void setBehavior(MultiInstanceFlowCondition behavior) { behaviorAttribute.setValue(this, behavior); } public EventDefinition getOneBehaviorEventRef() { return oneBehaviorEventRefAttribute.getReferenceTargetElement(this); } public void setOneBehaviorEventRef(EventDefinition oneBehaviorEventRef) { oneBehaviorEventRefAttribute.setReferenceTargetElement(this, oneBehaviorEventRef); } public EventDefinition getNoneBehaviorEventRef() { return noneBehaviorEventRefAttribute.getReferenceTargetElement(this); } public void setNoneBehaviorEventRef(EventDefinition noneBehaviorEventRef) { noneBehaviorEventRefAttribute.setReferenceTargetElement(this, noneBehaviorEventRef); } public boolean isCamundaAsyncBefore() { return camundaAsyncBefore.getValue(this); } public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) { camundaAsyncBefore.setValue(this, isCamundaAsyncBefore); }
public boolean isCamundaAsyncAfter() { return camundaAsyncAfter.getValue(this); } public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) { camundaAsyncAfter.setValue(this, isCamundaAsyncAfter); } public boolean isCamundaExclusive() { return camundaExclusive.getValue(this); } public void setCamundaExclusive(boolean isCamundaExclusive) { camundaExclusive.setValue(this, isCamundaExclusive); } public String getCamundaCollection() { return camundaCollection.getValue(this); } public void setCamundaCollection(String expression) { camundaCollection.setValue(this, expression); } public String getCamundaElementVariable() { return camundaElementVariable.getValue(this); } public void setCamundaElementVariable(String variableName) { camundaElementVariable.setValue(this, variableName); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MultiInstanceLoopCharacteristicsImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class MultipleVendorDocumentsException extends PaymentAllocationException { private static final AdMessageKey MSG = AdMessageKey.of("PaymentAllocation.CannotAllocateMultipleDocumentsException"); private final ImmutableList<IPaymentDocument> payments; MultipleVendorDocumentsException( final Collection<? extends IPaymentDocument> payments) { super(); this.payments = ImmutableList.copyOf(payments); } @Override protected ITranslatableString buildMessage() {
return TranslatableStrings.builder() .appendADMessage(MSG) .append(toCommaSeparatedDocumentNos(payments)) .build(); } private static String toCommaSeparatedDocumentNos(final List<IPaymentDocument> payments) { final Stream<String> paymentDocumentNos = payments.stream() .map(IPaymentDocument::getDocumentNo); return paymentDocumentNos .collect(Collectors.joining(", ")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\MultipleVendorDocumentsException.java
2
请完成以下Java代码
public class DBRes extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][]{ { "CConnectionDialog", "Server Connection" }, { "Name", "Name" }, { "AppsHost", "Application Host" }, { "AppsPort", "Application Port" }, { "TestApps", "Test Application Server" }, { "DBHost", "Database Host" }, { "DBPort", "Database Port" }, { "DBName", "Database Name" }, { "DBUidPwd", "User / Password" }, { "ViaFirewall", "via Firewall" }, { "FWHost", "Firewall Host" }, { "FWPort", "Firewall Port" }, { "TestConnection", "Test Database" }, { "Type", "Database Type" }, { "BequeathConnection", "Bequeath Connection" }, { "Overwrite", "Overwrite" }, { "ConnectionProfile", "Connection" },
{ "LAN", "LAN" }, { "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "Connection Error" }, { "ServerNotActive", "Server Not Active" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes.java
1
请在Spring Boot框架中完成以下Java代码
public final class SystemTime { private static final TimeSource defaultTimeSource = new TimeSource() { @Override public long millis() { return System.currentTimeMillis(); } }; private static TimeSource timeSource; private SystemTime() { } public static long millis() { return SystemTime.getTimeSource().millis(); } public static GregorianCalendar asGregorianCalendar() { final GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(SystemTime.millis()); return cal; } public static Date asDate() { return new Date(SystemTime.millis()); } public static Timestamp asTimestamp() {
return new Timestamp(SystemTime.millis()); } private static TimeSource getTimeSource() { return SystemTime.timeSource == null ? SystemTime.defaultTimeSource : SystemTime.timeSource; } /** * After invocation of this method, the time returned will be the system time again. */ public static void resetTimeSource() { SystemTime.timeSource = null; } /** * * @param newTimeSource the given TimeSource will be used for the time returned by the methods of this class (unless it is null). * */ public static void setTimeSource(final TimeSource newTimeSource) { SystemTime.timeSource = newTimeSource; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\SystemTime.java
2
请完成以下Java代码
protected static class OutputStreamWrapper extends OutputStream { private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private final OutputStream output; private OutputStreamWrapper(OutputStream output) { this.output = output; } @Override public void write(int i) throws IOException { buffer.write(i); output.write(i); } @Override public void write(byte[] b) throws IOException { buffer.write(b); output.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { buffer.write(b, off, len); output.write(b, off, len); }
@Override public void flush() throws IOException { output.flush(); } @Override public void close() throws IOException { output.close(); } public byte[] getBytes() { return buffer.toByteArray(); } } }
repos\springBoot-master\springboot-dubbo\abel-user-provider\src\main\java\cn\abel\user\filter\RestInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public class CamundaBpmRunConfiguration { @Bean @ConditionalOnProperty(name = "enabled", havingValue = "true", prefix = CamundaBpmRunLdapProperties.PREFIX) public LdapIdentityProviderPlugin ldapIdentityProviderPlugin(CamundaBpmRunProperties properties) { return properties.getLdap(); } @Bean @ConditionalOnProperty(name = "enabled", havingValue = "true", prefix = CamundaBpmRunAdministratorAuthorizationProperties.PREFIX) public AdministratorAuthorizationPlugin administratorAuthorizationPlugin(CamundaBpmRunProperties properties) { return properties.getAdminAuth(); } @Bean public ProcessEngineConfigurationImpl processEngineConfigurationImpl(List<ProcessEnginePlugin> processEnginePluginsFromContext, CamundaBpmRunProperties properties,
CamundaBpmRunDeploymentConfiguration deploymentConfig) { String normalizedDeploymentDir = deploymentConfig.getNormalizedDeploymentDir(); boolean deployChangedOnly = properties.getDeployment().isDeployChangedOnly(); var processEnginePluginsFromYaml = properties.getProcessEnginePlugins(); return new CamundaBpmRunProcessEngineConfiguration(normalizedDeploymentDir, deployChangedOnly, processEnginePluginsFromContext, processEnginePluginsFromYaml); } @Bean public CamundaBpmRunDeploymentConfiguration camundaDeploymentConfiguration(@Value("${camunda.deploymentDir:#{null}}") String deploymentDir) { return new CamundaBpmRunDeploymentConfiguration(deploymentDir); } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\CamundaBpmRunConfiguration.java
2
请完成以下Java代码
public Object execute(CommandContext commandContext) { if (executionId == null) { throw new FlowableIllegalArgumentException("executionId is null"); } if (variableName == null) { throw new FlowableIllegalArgumentException("variableName is null"); } ExecutionEntity execution = CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId); if (execution == null) { throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class); } if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, execution.getProcessDefinitionId())) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); return compatibilityHandler.getExecutionVariable(executionId, variableName, isLocal); } Object value; if (isLocal) { value = execution.getVariableLocal(variableName, false); } else { value = execution.getVariable(variableName, false); } return value; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetExecutionVariableCmd.java
1
请完成以下Java代码
public class SwingUserInterface implements IUserInterface { private final transient Logger log = Logger.getLogger(getClass().getName()); private final Component parent; public SwingUserInterface(final Component parent) { if (parent == null) { throw new IllegalArgumentException("parent is null"); } this.parent = parent; } @Override public void showError(final String title, final Throwable ex) { final String message = buildErrorMessage(ex); JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, title + " - " + message, ex); } } private String buildErrorMessage(final Throwable ex) { final StringBuilder msg = new StringBuilder(); if (ex.getLocalizedMessage() != null) { msg.append(ex.getLocalizedMessage());
} final Throwable cause = ex.getCause(); if (cause != null) { if (msg.length() > 0) { msg.append(": "); } msg.append(cause.toString()); } return msg.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\ui\SwingUserInterface.java
1
请完成以下Java代码
public class NavProcessor extends AbstractElementTagProcessor { private static final String TAG_NAME = "shownav"; private static final String DEFAULT_FRAGMENT_NAME = "~{temporalwebdialect :: shownav}"; private static final int PRECEDENCE = 10000; private final ApplicationContext ctx; private WorkflowClient workflowClient; public NavProcessor(final String dialectPrefix, ApplicationContext ctx, WorkflowClient workflowClient) { super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PRECEDENCE); this.ctx = ctx; this.workflowClient = workflowClient; }
@Override protected void doProcess(ITemplateContext templateContext, IProcessableElementTag processInstancesTag, IElementTagStructureHandler structureHandler) { final IEngineConfiguration configuration = templateContext.getConfiguration(); IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration); DialectUtils dialectUtils = new DialectUtils(workflowClient); final IModelFactory modelFactory = templateContext.getModelFactory(); final IModel model = modelFactory.createModel(); model.add(modelFactory.createOpenElementTag("div", "th:replace", dialectUtils.getFragmentName( processInstancesTag.getAttributeValue("fragment"), DEFAULT_FRAGMENT_NAME, parser, templateContext))); model.add(modelFactory.createCloseElementTag("div")); structureHandler.replaceWith(model, true); } }
repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\processor\NavProcessor.java
1
请在Spring Boot框架中完成以下Java代码
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((authorize) -> authorize.anyRequest() .authenticated()) .formLogin(Customizer.withDefaults()); return http.cors(Customizer.withDefaults()) .build(); } @Bean UserDetailsService userDetailsService() { PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); UserDetails userDetails = User.builder() .username("john") .password("password") .passwordEncoder(passwordEncoder::encode) .roles("USER") .build(); return new InMemoryUserDetailsManager(userDetails);
} @Bean CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.addAllowedOrigin("http://127.0.0.1:3000"); config.setAllowCredentials(true); source.registerCorsConfiguration("/**", config); return source; } }
repos\tutorials-master\spring-security-modules\spring-security-pkce-spa\pkce-spa-auth-server\src\main\java\com\baeldung\SecurityConfiguration.java
2
请完成以下Java代码
protected String getActivityIdExceptionMessage(VariableScope variableScope) { String activityId = null; String definitionIdMessage = ""; if (variableScope instanceof DelegateExecution) { activityId = ((DelegateExecution) variableScope).getCurrentActivityId(); definitionIdMessage = " in the process definition with id '" + ((DelegateExecution) variableScope).getProcessDefinitionId() + "'"; } else if (variableScope instanceof TaskEntity) { TaskEntity task = (TaskEntity) variableScope; if (task.getExecution() != null) { activityId = task.getExecution().getActivityId(); definitionIdMessage = " in the process definition with id '" + task.getProcessDefinitionId() + "'"; } if (task.getCaseExecution() != null) { activityId = task.getCaseExecution().getActivityId(); definitionIdMessage = " in the case definition with id '" + task.getCaseDefinitionId() + "'"; }
} else if (variableScope instanceof DelegateCaseExecution) { activityId = ((DelegateCaseExecution) variableScope).getActivityId(); definitionIdMessage = " in the case definition with id '" + ((DelegateCaseExecution) variableScope).getCaseDefinitionId() + "'"; } if (activityId == null) { return ""; } else { return " while executing activity '" + activityId + "'" + definitionIdMessage; } } protected abstract Object evaluate(ScriptEngine scriptEngine, VariableScope variableScope, Bindings bindings); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\ExecutableScript.java
1
请完成以下Java代码
public static boolean isDay(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355()); return X12DE355.DAY.equals(x12de355); } public static boolean isWorkDay(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355()); return X12DE355.DAY_WORK.equals(x12de355); } public static boolean isWeek(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355()); return X12DE355.WEEK.equals(x12de355); } public static boolean isMonth(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355()); return X12DE355.MONTH.equals(x12de355); } public static boolean isWorkMonth(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355()); return X12DE355.MONTH_WORK.equals(x12de355); }
public static boolean isYear(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofNullableCode(uom.getX12DE355()); return X12DE355.YEAR.equals(x12de355); } /** * @return true if is time UOM */ public static boolean isTime(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355()); return x12de355.isTemporalUnit(); } @NonNull public static TemporalUnit toTemporalUnit(final I_C_UOM uom) { final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355()); return x12de355.getTemporalUnit(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\uom\UOMUtil.java
1
请完成以下Java代码
public List<EventSubscriptionEntity> findEventSubscriptionsByTypeAndProcessDefinitionId(String type, String processDefinitionId, String tenantId) { final String query = "selectEventSubscriptionsByTypeAndProcessDefinitionId"; Map<String, String> params = new HashMap<>(); if (type != null) { params.put("eventType", type); } params.put("processDefinitionId", processDefinitionId); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } return getDbSqlSession().selectList(query, params); } public List<EventSubscriptionEntity> findEventSubscriptionsByName(String type, String eventName, String tenantId) { final String query = "selectEventSubscriptionsByName"; Map<String, String> params = new HashMap<>(); params.put("eventType", type); params.put("eventName", eventName); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } return getDbSqlSession().selectList(query, params); } public List<EventSubscriptionEntity> findEventSubscriptionsByNameAndExecution(String type, String eventName, String executionId) {
final String query = "selectEventSubscriptionsByNameAndExecution"; Map<String, String> params = new HashMap<>(); params.put("eventType", type); params.put("eventName", eventName); params.put("executionId", executionId); return getDbSqlSession().selectList(query, params); } public MessageEventSubscriptionEntity findMessageStartEventSubscriptionByName(String messageName, String tenantId) { Map<String, String> params = new HashMap<>(); params.put("eventName", messageName); if (tenantId != null && !tenantId.equals(ProcessEngineConfiguration.NO_TENANT_ID)) { params.put("tenantId", tenantId); } MessageEventSubscriptionEntity entity = (MessageEventSubscriptionEntity) getDbSqlSession().selectOne("selectMessageStartEventSubscriptionByName", params); return entity; } public void updateEventSubscriptionTenantId(String oldTenantId, String newTenantId) { Map<String, String> params = new HashMap<>(); params.put("oldTenantId", oldTenantId); params.put("newTenantId", newTenantId); getDbSqlSession().update("updateTenantIdOfEventSubscriptions", params); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntityManager.java
1
请完成以下Java代码
public class X_MSV3_VerfuegbarkeitsanfrageEinzelne extends org.compiere.model.PO implements I_MSV3_VerfuegbarkeitsanfrageEinzelne, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -1006750286L; /** Standard Constructor */ public X_MSV3_VerfuegbarkeitsanfrageEinzelne (Properties ctx, int MSV3_VerfuegbarkeitsanfrageEinzelne_ID, String trxName) { super (ctx, MSV3_VerfuegbarkeitsanfrageEinzelne_ID, trxName); /** if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID == 0) { setMSV3_Id (null); setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (0); } */ } /** Load Constructor */ public X_MSV3_VerfuegbarkeitsanfrageEinzelne (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id.
@return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne. @param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID) { if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne. @return MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne.java
1
请完成以下Java代码
public abstract class TbAbstractAlarmNodeConfiguration { static final String ALARM_DETAILS_BUILD_JS_TEMPLATE = "" + "var details = {};\n" + "if (metadata.prevAlarmDetails) {\n" + " details = JSON.parse(metadata.prevAlarmDetails);\n" + " //remove prevAlarmDetails from metadata\n" + " delete metadata.prevAlarmDetails;\n" + " //now metadata is the same as it comes IN this rule node\n" + "}\n" + "\n" + "\n" + "return details;"; static final String ALARM_DETAILS_BUILD_TBEL_TEMPLATE = "" + "var details = {};\n" + "if (metadata.prevAlarmDetails != null) {\n" + " details = JSON.parse(metadata.prevAlarmDetails);\n" + " //remove prevAlarmDetails from metadata\n" +
" metadata.remove('prevAlarmDetails');\n" + " //now metadata is the same as it comes IN this rule node\n" + "}\n" + "\n" + "\n" + "return details;"; @NoXss private String alarmType; private ScriptLanguage scriptLang; private String alarmDetailsBuildJs; private String alarmDetailsBuildTbel; }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbAbstractAlarmNodeConfiguration.java
1
请完成以下Java代码
public class CombiningSets { public static Set<Object> usingNativeJava(Set<Object> first, Set<Object> second) { Set<Object> combined = new HashSet<>(); combined.addAll(first); combined.addAll(second); return combined; } public static Set<Object> usingJava8ObjectStream(Set<Object> first, Set<Object> second) { Set<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet()); return combined; } public static Set<Object> usingJava8FlatMaps(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet()); return combined; } public static Set<Object> usingApacheCommons(Set<Object> first, Set<Object> second) { Set<Object> combined = SetUtils.union(first, second); return combined; } public static Set<Object> usingGuava(Set<Object> first, Set<Object> second) { Set<Object> combined = Sets.union(first, second); return combined; } }
repos\tutorials-master\core-java-modules\core-java-collections\src\main\java\com\baeldung\collections\combiningcollections\CombiningSets.java
1
请完成以下Java代码
public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; }
public boolean isWithoutTenantId() { return withoutTenantId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public boolean isLatestVersion() { return latestVersion; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeploymentQueryImpl.java
1
请完成以下Java代码
public static int getByteSize(String content) { int size = 0; if (null != content) { try { // 汉字采用utf-8编码时占3个字节 size = content.getBytes("utf-8").length; } catch (UnsupportedEncodingException e) { LOG.error(e); } } return size; } /** * 函数功能说明 : 截取字符串拼接in查询参数. 修改者名字: 修改日期: 修改内容: * * @参数: @param ids * @参数: @return * @return String * @throws */ public static List<String> getInParam(String param) { boolean flag = param.contains(","); List<String> list = new ArrayList<String>();
if (flag) { list = Arrays.asList(param.split(",")); } else { list.add(param); } return list; } /** * 判断对象是否为空 * * @param obj * @return */ public static boolean isNotNull(Object obj) { if (obj != null && obj.toString() != null && !"".equals(obj.toString().trim())) { return true; } else { return false; } } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\StringUtil.java
1
请完成以下Java代码
public static String getTableNameByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); return arr[0].trim(); } else { return tableSql; } } /** * 判断两个数组是否存在交集 * @param set1 * @param arr2 * @return */ public static boolean hasIntersection(Set<String> set1, String[] arr2) { if (set1 == null) { return false; } if(set1.size()>0){ for (String str : arr2) { if (set1.contains(str)) {
return true; } } } return false; } /** * 输出info日志,会捕获异常,防止因为日志问题导致程序异常 * * @param msg * @param objects */ public static void logInfo(String msg, Object... objects) { try { log.info(msg, objects); } catch (Exception e) { log.warn("{} —— {}", msg, e.getMessage()); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\CommonUtils.java
1
请完成以下Java代码
public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public String getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(String lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
repos\Activiti-develop\activiti-core-common\activiti-project-model\src\main\java\org\activiti\core\common\project\model\ProjectManifest.java
1
请完成以下Java代码
public Integer getCamundaHistoryTimeToLive() { String ttl = getCamundaHistoryTimeToLiveString(); if (ttl != null) { return Integer.parseInt(ttl); } return null; } @Override public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) { var value = historyTimeToLive == null ? null : String.valueOf(historyTimeToLive); setCamundaHistoryTimeToLiveString(value); } @Override public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLiveAttribute.getValue(this); } @Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { if (historyTimeToLive == null) { camundaHistoryTimeToLiveAttribute.removeAttribute(this); } else { camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive); } } @Override public Boolean isCamundaStartableInTasklist() {
return camundaIsStartableInTasklistAttribute.getValue(this); } @Override public void setCamundaIsStartableInTasklist(Boolean isStartableInTasklist) { camundaIsStartableInTasklistAttribute.setValue(this, isStartableInTasklist); } @Override public String getCamundaVersionTag() { return camundaVersionTagAttribute.getValue(this); } @Override public void setCamundaVersionTag(String versionTag) { camundaVersionTagAttribute.setValue(this, versionTag); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ProcessImpl.java
1
请完成以下Java代码
public ResponseEntity<String> returnPage(HttpServletRequest request, HttpServletResponse response) { AlipayConfig alipay = alipayService.find(); response.setContentType("text/html;charset=" + alipay.getCharset()); //内容验签,防止黑客篡改参数 if (alipayUtils.rsaCheck(request, alipay)) { //商户订单号 String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //支付宝交易号 String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); System.out.println("商户订单号" + outTradeNo + " " + "第三方交易号" + tradeNo); // 根据业务需要返回数据,这里统一返回OK return new ResponseEntity<>("payment successful", HttpStatus.OK); } else { // 根据业务需要返回数据 return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @ApiIgnore @RequestMapping("/notify") @AnonymousAccess @ApiOperation("支付异步通知(要公网访问),接收异步通知,检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致,根据trade_status进行后续业务处理") public ResponseEntity<Object> notify(HttpServletRequest request) { AlipayConfig alipay = alipayService.find(); Map<String, String[]> parameterMap = request.getParameterMap(); //内容验签,防止黑客篡改参数
if (alipayUtils.rsaCheck(request, alipay)) { //交易状态 String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); // 商户订单号 String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //支付宝交易号 String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //付款金额 String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //验证 if (tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue()) || tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())) { // 验证通过后应该根据业务需要处理订单 } return new ResponseEntity<>(HttpStatus.OK); } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\AliPayController.java
1
请在Spring Boot框架中完成以下Java代码
public String getPortHeader() { return this.portHeader; } public void setPortHeader(String portHeader) { this.portHeader = portHeader; } public @Nullable String getRemoteIpHeader() { return this.remoteIpHeader; } public void setRemoteIpHeader(@Nullable String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } public @Nullable String getTrustedProxies() { return this.trustedProxies; } public void setTrustedProxies(@Nullable String trustedProxies) { this.trustedProxies = trustedProxies; } } /** * When to use APR. */ public enum UseApr {
/** * Always use APR and fail if it's not available. */ ALWAYS, /** * Use APR if it is available. */ WHEN_AVAILABLE, /** * Never use APR. */ NEVER } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\TomcatServerProperties.java
2
请完成以下Java代码
public PaymentString parse(@NonNull final String qrCode) { final List<String> lines = SPLITTER.splitToList(qrCode); Check.assumeEquals(lines.get(0), "SPC"); // QR Type Check.assumeEquals(lines.get(1), "0200"); // Version Check.assumeEquals(lines.get(2), "1"); // Coding final String iban = lines.get(3); Check.assumeNotNull(lines.get(18), "invoice total not null"); Check.assumeNotNull(lines.get(27), "code type not null"); Check.assumeNotNull(lines.get(28), "reference not null"); final String amountString = lines.get(18); final String reference = lines.get(28); final Timestamp paymentDate = null; final Timestamp accountDate = null; final List<String> collectedErrors = new ArrayList<>(); final BigDecimal amount = extractAmountFromString(amountString, collectedErrors); final PaymentString paymentString = PaymentString.builder()
.collectedErrors(collectedErrors) .rawPaymentString(qrCode) .IBAN(iban) .amount(amount) .referenceNoComplete(reference) .paymentDate(paymentDate) .accountDate(accountDate) .build(); final IPaymentStringDataProvider dataProvider = new QRPaymentStringDataProvider(paymentString); paymentString.setDataProvider(dataProvider); return paymentString; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\spi\impl\QRCodeStringParser.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final ImmutableSet<ResourceId> resourceIds = getSelectedResourceIds(); final QRCodePDFResource pdf = resourceQRCodePrintService.createPDF(resourceIds); getResult().setReportData(pdf, pdf.getFilename(), pdf.getContentType()); return MSG_OK; } private ImmutableSet<ResourceId> getSelectedResourceIds() { final IView view = getView(); return getSelectedRowIdsAsSet() .stream() .map(view::getTableRecordReferenceOrNull) .filter(Objects::nonNull) .map(recordRef -> ResourceId.ofRepoId(recordRef.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); } private Set<DocumentId> getSelectedRowIdsAsSet() { final IView view = getView(); final DocumentIdsSelection rowIds = getSelectedRowIds();
final Set<DocumentId> rowIdsEffective; if (rowIds.isEmpty()) { return ImmutableSet.of(); } else if (rowIds.isAll()) { rowIdsEffective = view.streamByIds(DocumentIdsSelection.ALL) .map(IViewRow::getId) .collect(ImmutableSet.toImmutableSet()); } else { rowIdsEffective = rowIds.toSet(); } return rowIdsEffective; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\resource\process\S_Resource_PrintQRCodes.java
1
请在Spring Boot框架中完成以下Java代码
private @NonNull ImmutableSet<HuId> getPPOrderSourceHUIds() { if (_ppOrderSourceHUIds == null) { _ppOrderSourceHUIds = ppOrderSourceHUService.getSourceHUIds(ppOrderId); } return _ppOrderSourceHUIds; } @NonNull private SourceHUsCollection retrieveActiveSourceHusFromWarehouse(@NonNull final ProductId productId) { final List<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveMatchingSourceHuMarkers( SourceHUsService.MatchingSourceHusQuery.builder() .productId(productId) .warehouseIds(getIssueFromWarehouseIds()) .build() ); final List<I_M_HU> hus = handlingUnitsDAO.getByIds(extractHUIdsFromSourceHUs(sourceHUs)); return SourceHUsCollection.builder() .husThatAreFlaggedAsSource(ImmutableList.copyOf(hus)) .sourceHUs(sourceHUs) .build(); } @NonNull private SourceHUsCollection retrieveActiveSourceHusForHus(@NonNull final ProductId productId) { final ImmutableList<I_M_HU> activeHUsMatchingProduct = handlingUnitsDAO.createHUQueryBuilder() .setOnlyActiveHUs(true) .setAllowEmptyStorage() .addOnlyHUIds(getPPOrderSourceHUIds())
.addOnlyWithProductId(productId) .createQuery() .listImmutable(I_M_HU.class); final ImmutableList<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveSourceHuMarkers(extractHUIdsFromHUs(activeHUsMatchingProduct)); return SourceHUsCollection.builder() .husThatAreFlaggedAsSource(activeHUsMatchingProduct) .sourceHUs(sourceHUs) .build(); } private static ImmutableSet<HuId> extractHUIdsFromSourceHUs(final Collection<I_M_Source_HU> sourceHUs) { return sourceHUs.stream().map(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID())).collect(ImmutableSet.toImmutableSet()); } private static ImmutableSet<HuId> extractHUIdsFromHUs(final Collection<I_M_HU> hus) { return hus.stream().map(I_M_HU::getM_HU_ID).map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\SourceHUsCollectionProvider.java
2
请完成以下Java代码
public Set<String> getVariableNames() { return Collections.EMPTY_SET; } public Set<String> getVariableNamesLocal() { return null; } public void setVariable(String variableName, Object value) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariableLocal(String variableName, Object value) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariables(Map<String, ? extends Object> variables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariablesLocal(Map<String, ? extends Object> variables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public boolean hasVariables() { return false; } public boolean hasVariablesLocal() { return false; } public boolean hasVariable(String variableName) { return false; } public boolean hasVariableLocal(String variableName) { return false; } public void removeVariable(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); }
public void removeVariableLocal(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariables() { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariablesLocal() { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariables(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariablesLocal(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public Map<String, CoreVariableInstance> getVariableInstances() { return Collections.emptyMap(); } public CoreVariableInstance getVariableInstance(String name) { return null; } public Map<String, CoreVariableInstance> getVariableInstancesLocal() { return Collections.emptyMap(); } public CoreVariableInstance getVariableInstanceLocal(String name) { return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\StartProcessVariableScope.java
1
请完成以下Java代码
public final class JSONNotificationEvent implements Serializable { public static final JSONNotificationEvent eventNew(final JSONNotification notification, final int unreadCount) { String notificationId = notification.getId(); return new JSONNotificationEvent(EventType.New, notificationId, notification, unreadCount); } public static final JSONNotificationEvent eventRead(final String notificationId, final int unreadCount) { final JSONNotification notification = null; return new JSONNotificationEvent(EventType.Read, notificationId, notification, unreadCount); } public static final JSONNotificationEvent eventReadAll() { final String notificationId = null; final JSONNotification notification = null; final int unreadCount = 0; return new JSONNotificationEvent(EventType.ReadAll, notificationId, notification, unreadCount); } public static final JSONNotificationEvent eventDeleted(final String notificationId, final int unreadCount) { final JSONNotification notification = null; return new JSONNotificationEvent(EventType.Delete, notificationId, notification, unreadCount); } public static final JSONNotificationEvent eventDeletedAll() { final String notificationId = null; final JSONNotification notification = null; final int unreadCount = 0; return new JSONNotificationEvent(EventType.DeleteAll, notificationId, notification, unreadCount); } public static enum EventType { New, Read, ReadAll, Delete, DeleteAll }; @JsonProperty("eventType") private final EventType eventType;
@JsonProperty("notificationId") private final String notificationId; @JsonProperty("notification") @JsonInclude(JsonInclude.Include.NON_ABSENT) private final JSONNotification notification; @JsonProperty("unreadCount") @JsonInclude(JsonInclude.Include.NON_ABSENT) private final Integer unreadCount; private JSONNotificationEvent(final EventType eventType, final String notificationId, final JSONNotification notification, final Integer unreadCount) { this.eventType = eventType; this.notificationId = notificationId; this.notification = notification; this.unreadCount = unreadCount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\json\JSONNotificationEvent.java
1
请在Spring Boot框架中完成以下Java代码
public HttpResponse<String> endpoint3(@Nullable @Header("skip-error") String isErrorSkipped) { log.info("endpoint3"); if (isErrorSkipped == null) { throw new CustomException("something else went wrong"); } return HttpResponse.ok("Endpoint 3"); } @Get("/custom-child-error") public HttpResponse<String> endpoint4(@Nullable @Header("skip-error") String isErrorSkipped) { log.info("endpoint4"); if (isErrorSkipped == null) { throw new CustomChildException("something else went wrong"); } return HttpResponse.ok("Endpoint 4"); }
@Error(exception = UnsupportedOperationException.class) public HttpResponse<JsonError> unsupportedOperationExceptions(HttpRequest<?> request) { log.info("Unsupported Operation Exception handled"); JsonError error = new JsonError("Unsupported Operation").link(Link.SELF, Link.of(request.getUri())); return HttpResponse.<JsonError> notFound() .body(error); } @Get("/unsupported-operation") public HttpResponse<String> endpoint5() { log.info("endpoint5"); throw new UnsupportedOperationException(); } }
repos\tutorials-master\microservices-modules\micronaut-configuration\src\main\java\com\baeldung\micronaut\globalexceptionhandler\controller\ErroneousController.java
2
请在Spring Boot框架中完成以下Java代码
public List<ValueHint> getKeyHints() { return this.keyHints; } /** * The value providers that are applicable to the keys of this item. Only applicable * if the type of the related item is a {@link java.util.Map}. Only one * {@link ValueProvider} is enabled for a key: the first in the list that is supported * should be used. * @return the key providers */ public List<ValueProvider> getKeyProviders() { return this.keyProviders; } /** * The list of well-defined values, if any. If no extra {@link ValueProvider provider} * is specified, these values are to be considered a closed-set of the available * values for this item.
* @return the value hints */ public List<ValueHint> getValueHints() { return this.valueHints; } /** * The value providers that are applicable to this item. Only one * {@link ValueProvider} is enabled for an item: the first in the list that is * supported should be used. * @return the value providers */ public List<ValueProvider> getValueProviders() { return this.valueProviders; } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\Hints.java
2
请完成以下Java代码
default boolean hasAttributes() { return false; } default IViewRowAttributes getAttributes() { throw new EntityNotFoundException("Row does not support attributes"); } // @formatter:on // // IncludedView // @formatter:off default ViewId getIncludedViewId() { return null; } // @formatter:on // // Single column row // @formatter:off /** @return true if frontend shall display one single column */ default boolean isSingleColumn() { return false; }
/** @return text to be displayed if {@link #isSingleColumn()} */ default ITranslatableString getSingleColumnCaption() { return TranslatableStrings.empty(); } // @formatter:on /** * @return a stream of given row and all it's included rows recursively */ default Stream<IViewRow> streamRecursive() { return this.getIncludedRows() .stream() .map(IViewRow::streamRecursive) .reduce(Stream.of(this), Stream::concat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewRow.java
1
请完成以下Java代码
public void setCause(String cause) { this.cause = cause; } /** * @return the cause. * @since 1.4 */ public @Nullable String getCause() { return this.cause; } /** * True if a returned message has been received. * @return true if there is a return. * @since 2.2.10 */ public boolean isReturned() { return this.returned; } /** * Indicate that a returned message has been received. * @param isReturned true if there is a return. * @since 2.2.10 */ public void setReturned(boolean isReturned) { this.returned = isReturned; } /** * Return true if a return has been passed to the listener or if no return has been * received. * @return false if an expected returned message has not been passed to the listener. * @throws InterruptedException if interrupted. * @since 2.2.10 */
public boolean waitForReturnIfNeeded() throws InterruptedException { return !this.returned || this.latch.await(RETURN_CALLBACK_TIMEOUT, TimeUnit.SECONDS); } /** * Count down the returned message latch; call after the listener has been called. * @since 2.2.10 */ public void countDown() { this.latch.countDown(); } @Override public String toString() { return "PendingConfirm [correlationData=" + this.correlationData + (this.cause == null ? "" : " cause=" + this.cause) + "]"; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\PendingConfirm.java
1
请在Spring Boot框架中完成以下Java代码
public ByteArrayRef getExceptionByteArrayRef() { return exceptionByteArrayRef; } @Override public void setExceptionByteArrayRef(ByteArrayRef exceptionByteArrayRef) { this.exceptionByteArrayRef = exceptionByteArrayRef; } private String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) { if (jobByteArrayRef == null) { return null; } return jobByteArrayRef.asString(getEngineType()); } protected String getEngineType() { if (StringUtils.isNotEmpty(scopeType)) { return scopeType; } else { return ScopeTypes.BPMN; } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName().replace("Impl", "")).append("[") .append("id=").append(id) .append(", jobHandlerType=").append(jobHandlerType) .append(", jobType=").append(jobType); if (category != null) { sb.append(", category=").append(category); } if (elementId != null) {
sb.append(", elementId=").append(elementId); } if (correlationId != null) { sb.append(", correlationId=").append(correlationId); } if (executionId != null) { sb.append(", processInstanceId=").append(processInstanceId) .append(", executionId=").append(executionId); } else if (scopeId != null) { sb.append(", scopeId=").append(scopeId) .append(", subScopeId=").append(subScopeId) .append(", scopeType=").append(scopeType); } if (processDefinitionId != null) { sb.append(", processDefinitionId=").append(processDefinitionId); } else if (scopeDefinitionId != null) { if (scopeId == null) { sb.append(", scopeType=").append(scopeType); } sb.append(", scopeDefinitionId=").append(scopeDefinitionId); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\AbstractJobEntityImpl.java
2
请完成以下Java代码
public Job findOldestByTenantIdAndTypeAndStatusForUpdate(TenantId tenantId, JobType type, JobStatus status) { return DaoUtil.getData(jobRepository.findOldestByTenantIdAndTypeAndStatusForUpdate(tenantId.getId(), type.name(), status.name())); } @Override public void removeByTenantId(TenantId tenantId) { jobRepository.deleteByTenantId(tenantId.getId()); } @Override public int removeByEntityId(TenantId tenantId, EntityId entityId) { return jobRepository.deleteByEntityId(entityId.getId()); } @Override
public EntityType getEntityType() { return EntityType.JOB; } @Override protected Class<JobEntity> getEntityClass() { return JobEntity.class; } @Override protected JpaRepository<JobEntity, UUID> getRepository() { return jobRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\job\JpaJobDao.java
1
请完成以下Java代码
public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWeightInKg (final BigDecimal WeightInKg) { set_Value (COLUMNNAME_WeightInKg, WeightInKg); } @Override
public BigDecimal getWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java
1
请完成以下Java代码
public String getVrsnNb() { return vrsnNb; } /** * Sets the value of the vrsnNb property. * * @param value * allowed object is * {@link String } * */ public void setVrsnNb(String value) { this.vrsnNb = value; } /** * Gets the value of the srlNb property. * * @return * possible object is * {@link String } * */ public String getSrlNb() { return srlNb; } /** * Sets the value of the srlNb property. * * @param value * allowed object is * {@link String } * */ public void setSrlNb(String value) { this.srlNb = value; } /** * Gets the value of the apprvlNb property.
* * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the apprvlNb property. * * <p> * For example, to add a new item, do as follows: * <pre> * getApprvlNb().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getApprvlNb() { if (apprvlNb == null) { apprvlNb = new ArrayList<String>(); } return this.apprvlNb; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteractionComponent1.java
1
请完成以下Java代码
public Mono<List<Map<String, Object>>> routes() { Mono<Map<String, RouteDefinition>> routeDefs = this.routeDefinitionLocator.getRouteDefinitions() .collectMap(RouteDefinition::getId); Mono<List<Route>> routes = this.routeLocator.getRoutes().collectList(); return Mono.zip(routeDefs, routes).map(tuple -> { Map<String, RouteDefinition> defs = tuple.getT1(); List<Route> routeList = tuple.getT2(); List<Map<String, Object>> allRoutes = new ArrayList<>(); routeList.forEach(route -> { HashMap<String, Object> r = new HashMap<>(); r.put("route_id", route.getId()); r.put("order", route.getOrder()); if (defs.containsKey(route.getId())) { r.put("route_definition", defs.get(route.getId())); } else { HashMap<String, Object> obj = new HashMap<>(); obj.put("predicate", route.getPredicate().toString()); if (!route.getFilters().isEmpty()) { ArrayList<String> filters = new ArrayList<>(); for (GatewayFilter filter : route.getFilters()) { filters.add(filter.toString()); } obj.put("filters", filters); } if (!CollectionUtils.isEmpty(route.getMetadata())) { obj.put("metadata", route.getMetadata()); } if (!obj.isEmpty()) {
r.put("route_object", obj); } } allRoutes.add(r); }); return allRoutes; }); } @GetMapping("/routes/{id}") public Mono<ResponseEntity<RouteDefinition>> route(@PathVariable String id) { // TODO: missing RouteLocator return this.routeDefinitionLocator.getRouteDefinitions() .filter(route -> route.getId().equals(id)) .singleOrEmpty() .map(ResponseEntity::ok) .switchIfEmpty(Mono.just(ResponseEntity.notFound().build())); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\actuate\GatewayLegacyControllerEndpoint.java
1
请完成以下Java代码
private static String readResponse(HttpResponse response) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String result = new String(); String line; while ((line = in.readLine()) != null) { result += line; } return result; } /** * 创建模拟客户端(针对 https 客户端禁用 SSL 验证) * * @param cookieStore 缓存的 Cookies 信息 * @return * @throws Exception */ private static CloseableHttpClient createHttpClientWithNoSsl() throws Exception { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // don't check } @Override
public void checkServerTrusted(X509Certificate[] certs, String authType) { // don't check } } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, trustAllCerts, null); LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx); return HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\CasServiceUtil.java
1
请完成以下Java代码
protected void prepare() { } // prepare /** * Perform process. * (see also MSequenve.validate) * * @return Message to be translated * @throws Exception */ @Override protected String doIt() throws java.lang.Exception { log.info(""); // checkSequences(Env.getCtx()); return "Sequence Check"; } // doIt public static final void checkSequences(final Properties ctx) { final ITableSequenceChecker tableSequenceChecker = Services.get(ISequenceDAO.class).createTableSequenceChecker(ctx); tableSequenceChecker.setSequenceRangeCheck(true); tableSequenceChecker.setFailOnFirstError(false); tableSequenceChecker.run(); checkClientSequences(ctx); } /** * Validate Sequences * * @param ctx context */ public static void validate(final Properties ctx) { try {
checkSequences(ctx); } catch (final Exception e) { s_log.error("validate", e); } } // validate /** * Check/Initialize DocumentNo/Value Sequences for all Clients * * @param ctx context * @param sp server process or null */ private static void checkClientSequences(final Properties ctx) { final IClientDAO clientDAO = Services.get(IClientDAO.class); final String trxName = null; // Sequence for DocumentNo/Value for (final I_AD_Client client : clientDAO.retrieveAllClients(ctx)) { if (!client.isActive()) { continue; } MSequence.checkClientSequences(ctx, client.getAD_Client_ID(), trxName); } } // checkClientSequences } // SequenceCheck
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\SequenceCheck.java
1
请完成以下Java代码
public class HTMLEditorPane extends JEditorPane { /** * */ private static final long serialVersionUID = -3894172494918474160L; boolean antiAlias = true; public HTMLEditorPane(String text) { super("text/html", text); } public boolean isAntialiasOn() { return antiAlias; } public void setAntiAlias(boolean on) { antiAlias = on; } @Override
public void paint(Graphics g) { if (antiAlias) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); /*g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);*/ super.paint(g2); } else { super.paint(g); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditorPane.java
1
请完成以下Java代码
<T extends Converter<?>> void conversionRule(String conversionWord, Class<T> converterClass, Supplier<T> converterSupplier) { info("Adding conversion rule of type '" + converterClass.getName() + "' for word '" + conversionWord + "'"); super.conversionRule(conversionWord, converterClass, converterSupplier); } @Override void appender(String name, Appender<?> appender) { info("Adding appender '" + appender + "' named '" + name + "'"); super.appender(name, appender); } @Override void logger(String name, @Nullable Level level, boolean additive, @Nullable Appender<ILoggingEvent> appender) { info("Configuring logger '" + name + "' with level '" + level + "'. Additive: " + additive); if (appender != null) { info("Adding appender '" + appender + "' to logger '" + name + "'");
} super.logger(name, level, additive, appender); } @Override void start(LifeCycle lifeCycle) { info("Starting '" + lifeCycle + "'"); super.start(lifeCycle); } private void info(String message) { getContext().getStatusManager().add(new InfoStatus(message, this)); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\DebugLogbackConfigurator.java
1
请完成以下Java代码
private void removeGroup(final FavoritesGroup group) { if (group == null) { return; } for (final Iterator<FavoritesGroup> it = topNodeId2group.values().iterator(); it.hasNext();) { final FavoritesGroup g = it.next(); if (Objects.equals(group, g)) { it.remove(); } } panel.remove(group.getComponent()); updateUI(); } private static MTreeNode getTopParent(final MTreeNode nd) { if (nd == null) { // shall not happen return null; } MTreeNode currentNode = nd; while (currentNode != null) { // If parent node is null or it has no ID (i.e. like the root node), // we consider current node as the top node final MTreeNode parent = (MTreeNode)currentNode.getParent(); if (parent == null || parent.getNode_ID() <= 0) { return currentNode; } // navigate up to parent, and check currentNode = parent; } return null; } public void removeItem(final FavoriteItem item) { if (item == null) { return; } // Database sync final MTreeNode node = item.getNode(); favoritesDAO.remove(getLoggedUserId(), node.getNode_ID()); // UI final FavoritesGroup group = item.getGroup(); group.removeItem(item); if (group.isEmpty()) { removeGroup(group); } updateUI(); } private void clearGroups() { for (final FavoritesGroup group : topNodeId2group.values()) { group.removeAllItems(); } topNodeId2group.clear(); panel.removeAll(); } public boolean isEmpty() { return topNodeId2group.isEmpty(); } private final void updateUI() { final JComponent comp = getComponent(); panel.invalidate(); panel.repaint(); final boolean visible = !isEmpty(); final boolean visibleOld = comp.isVisible(); if (visible == visibleOld)
{ return; } comp.setVisible(visible); // // If this group just became visible if (visible) { updateParentSplitPaneDividerLocation(); } } private final void updateParentSplitPaneDividerLocation() { final JComponent comp = getComponent(); if (!comp.isVisible()) { return; // nothing to update } // Find parent split pane if any JSplitPane parentSplitPane = null; for (Component c = comp.getParent(); c != null; c = c.getParent()) { if (c instanceof JSplitPane) { parentSplitPane = (JSplitPane)c; break; } } // Update it's divider location. // NOTE: if we would not do this, user would have to manually drag it when the first component is added. if (parentSplitPane != null) { if (parentSplitPane.getDividerLocation() <= 0) { parentSplitPane.setDividerLocation(Ini.getDividerLocation()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\FavoritesGroupContainer.java
1
请完成以下Java代码
public BigDecimal getPastDue8_30 () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue8_30); if (bd == null) return Env.ZERO; return bd; } /** Set Past Due > 91. @param PastDue91_Plus Past Due > 91 */ public void setPastDue91_Plus (BigDecimal PastDue91_Plus) { set_Value (COLUMNNAME_PastDue91_Plus, PastDue91_Plus); } /** Get Past Due > 91. @return Past Due > 91 */ public BigDecimal getPastDue91_Plus () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue91_Plus); if (bd == null) return Env.ZERO; return bd; } /** Set Past Due. @param PastDueAmt Past Due */ public void setPastDueAmt (BigDecimal PastDueAmt) { set_Value (COLUMNNAME_PastDueAmt, PastDueAmt); } /** Get Past Due. @return Past Due */ public BigDecimal getPastDueAmt () {
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDueAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Statement date. @param StatementDate Date of the statement */ public void setStatementDate (Timestamp StatementDate) { set_Value (COLUMNNAME_StatementDate, StatementDate); } /** Get Statement date. @return Date of the statement */ public Timestamp getStatementDate () { return (Timestamp)get_Value(COLUMNNAME_StatementDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Aging.java
1
请完成以下Java代码
public static WFState ofCode(@NonNull final String code) { return typesByCode.ofCode(code); } /** * @return true if open (running, not started, suspended) */ public boolean isOpen() { return Running.equals(this) || NotStarted.equals(this) || Suspended.equals(this); } /** * State is Not Running * * @return true if not running (not started, suspended) */ public boolean isNotRunning() { return NotStarted.equals(this) || Suspended.equals(this); } // isNotRunning /** * State is Closed * * @return true if closed (completed, aborted, terminated) */ public boolean isClosed() { return Completed.equals(this) || Aborted.equals(this) || Terminated.equals(this); } public boolean isNotStarted() { return NotStarted.equals(this); } // isNotStarted public boolean isRunning() { return Running.equals(this); } public boolean isSuspended() { return Suspended.equals(this); } public boolean isCompleted() { return Completed.equals(this); } public boolean isError() { return isAborted() || isTerminated(); } /** * @return true if state is Aborted (Environment/Setup issue) */ public boolean isAborted() { return Aborted.equals(this); } /** * @return true if state is Terminated (Execution issue) */ public boolean isTerminated() { return Terminated.equals(this); } /** * Get New State Options based on current State */ private WFState[] getNewStateOptions() { if (isNotStarted()) return new WFState[] { Running, Aborted, Terminated }; else if (isRunning()) return new WFState[] { Suspended, Completed, Aborted, Terminated }; else if (isSuspended()) return new WFState[] { Running, Aborted, Terminated }; else return new WFState[] {};
} /** * Is the new State valid based on current state * * @param newState new state * @return true valid new state */ public boolean isValidNewState(final WFState newState) { final WFState[] options = getNewStateOptions(); for (final WFState option : options) { if (option.equals(newState)) return true; } return false; } /** * @return true if the action is valid based on current state */ public boolean isValidAction(final WFAction action) { final WFAction[] options = getActionOptions(); for (final WFAction option : options) { if (option.equals(action)) { return true; } } return false; } /** * @return valid actions based on current State */ private WFAction[] getActionOptions() { if (isNotStarted()) return new WFAction[] { WFAction.Start, WFAction.Abort, WFAction.Terminate }; if (isRunning()) return new WFAction[] { WFAction.Suspend, WFAction.Complete, WFAction.Abort, WFAction.Terminate }; if (isSuspended()) return new WFAction[] { WFAction.Resume, WFAction.Abort, WFAction.Terminate }; else return new WFAction[] {}; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFState.java
1
请完成以下Java代码
public void setPaymentRule (String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } /** Get Payment Rule. @return How you pay the invoice */ @Override public String getPaymentRule () { return (String)get_Value(COLUMNNAME_PaymentRule); } /** Set Processed. @param Processed The document has been processed */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
} /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ @Override 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 */ @Override 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\eevolution\model\X_HR_Payroll.java
1
请完成以下Java代码
public final class WebsocketSubscriptionId { public static WebsocketSubscriptionId of( @NonNull final WebsocketSessionId sessionId, @NonNull final String subscriptionId) { return new WebsocketSubscriptionId(sessionId, subscriptionId); } @Getter private final WebsocketSessionId sessionId; private final String subscriptionId; private WebsocketSubscriptionId( @NonNull final WebsocketSessionId sessionId, @NonNull final String subscriptionId) { Check.assumeNotEmpty(subscriptionId, "subscriptionId is not empty"); this.sessionId = sessionId; this.subscriptionId = subscriptionId; }
/** * @deprecated please use {@link #getAsString()} */ @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return sessionId.getAsString() + "/" + subscriptionId; } public boolean isMatchingSessionId(final WebsocketSessionId sessionId) { return Objects.equals(this.sessionId, sessionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\websocket\WebsocketSubscriptionId.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .add("uiSubClassID", uiSubClassID) .toString(); } public final Color getColor(final String name, final Color defaultColor) { Color color = UIManager.getColor(buildUIDefaultsKey(name)); if (color == null && uiSubClassID != null) { color = UIManager.getColor(name); } if (color == null) { color = defaultColor; } return color; } public final Color getColor(final String name) { final Color defaultColor = null; return getColor(name, defaultColor); } public final Border getBorder(final String name, final Border defaultBorder) { Border border = UIManager.getBorder(buildUIDefaultsKey(name)); if (border == null && uiSubClassID != null) { border = UIManager.getBorder(name); } if (border == null) { border = defaultBorder; } return border; } private final String buildUIDefaultsKey(final String name) { return buildUIDefaultsKey(uiSubClassID, name); } private static final String buildUIDefaultsKey(final String uiSubClassID, final String name) { if (uiSubClassID == null) { return name; } else { return uiSubClassID + "." + name; } } public boolean getBoolean(final String name, final boolean defaultValue)
{ Object value = UIManager.getDefaults().get(buildUIDefaultsKey(name)); if (value instanceof Boolean) { return (boolean)value; } if (uiSubClassID != null) { value = UIManager.getDefaults().get(name); if (value instanceof Boolean) { return (boolean)value; } } return defaultValue; } /** * Convert all keys from given UI defaults key-value list by applying the <code>uiSubClassID</code> prefix to them. * * @param uiSubClassID * @param keyValueList * @return converted <code>keyValueList</code> */ public static final Object[] applyUISubClassID(final String uiSubClassID, final Object[] keyValueList) { if (keyValueList == null || keyValueList.length <= 0) { return keyValueList; } Check.assumeNotEmpty(uiSubClassID, "uiSubClassID not empty"); final Object[] keyValueListConverted = new Object[keyValueList.length]; for (int i = 0, max = keyValueList.length; i < max; i += 2) { final Object keyOrig = keyValueList[i]; final Object value = keyValueList[i + 1]; final Object key; if (keyOrig instanceof String) { key = buildUIDefaultsKey(uiSubClassID, (String)keyOrig); } else { key = keyOrig; } keyValueListConverted[i] = key; keyValueListConverted[i + 1] = value; } return keyValueListConverted; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UISubClassIDHelper.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Method_ID())); } /** Set DepreciationType. @param DepreciationType DepreciationType */ public void setDepreciationType (String DepreciationType) { set_Value (COLUMNNAME_DepreciationType, DepreciationType); } /** Get DepreciationType. @return DepreciationType */ public String getDepreciationType () { return (String)get_Value(COLUMNNAME_DepreciationType); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); }
/** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Method.java
1
请完成以下Java代码
public int getExecutorTimeout() { return executorTimeout; } public void setExecutorTimeout(int executorTimeout) { this.executorTimeout = executorTimeout; } public int getExecutorFailRetryCount() { return executorFailRetryCount; } public void setExecutorFailRetryCount(int executorFailRetryCount) { this.executorFailRetryCount = executorFailRetryCount; } public String getGlueType() { return glueType; } public void setGlueType(String glueType) { this.glueType = glueType; } public String getGlueSource() { return glueSource; } public void setGlueSource(String glueSource) { this.glueSource = glueSource; } public String getGlueRemark() { return glueRemark; } public void setGlueRemark(String glueRemark) { this.glueRemark = glueRemark; }
public Date getGlueUpdatetime() { return glueUpdatetime; } public void setGlueUpdatetime(Date glueUpdatetime) { this.glueUpdatetime = glueUpdatetime; } public String getChildJobId() { return childJobId; } public void setChildJobId(String childJobId) { this.childJobId = childJobId; } public int getTriggerStatus() { return triggerStatus; } public void setTriggerStatus(int triggerStatus) { this.triggerStatus = triggerStatus; } public long getTriggerLastTime() { return triggerLastTime; } public void setTriggerLastTime(long triggerLastTime) { this.triggerLastTime = triggerLastTime; } public long getTriggerNextTime() { return triggerNextTime; } public void setTriggerNextTime(long triggerNextTime) { this.triggerNextTime = triggerNextTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java
1
请完成以下Java代码
public void setIsPayFrom (final boolean IsPayFrom) { set_Value (COLUMNNAME_IsPayFrom, IsPayFrom); } @Override public boolean isPayFrom() { return get_ValueAsBoolean(COLUMNNAME_IsPayFrom); } @Override public void setIsRemitTo (final boolean IsRemitTo) { set_Value (COLUMNNAME_IsRemitTo, IsRemitTo); } @Override public boolean isRemitTo() { return get_ValueAsBoolean(COLUMNNAME_IsRemitTo); } @Override public void setIsShipTo (final boolean IsShipTo) { set_Value (COLUMNNAME_IsShipTo, IsShipTo); } @Override public boolean isShipTo() { return get_ValueAsBoolean(COLUMNNAME_IsShipTo); } @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); } /**
* Role AD_Reference_ID=541254 * Reference name: Role */ public static final int ROLE_AD_Reference_ID=541254; /** Main Producer = MP */ public static final String ROLE_MainProducer = "MP"; /** Hostpital = HO */ public static final String ROLE_Hostpital = "HO"; /** Physician Doctor = PD */ public static final String ROLE_PhysicianDoctor = "PD"; /** General Practitioner = GP */ public static final String ROLE_GeneralPractitioner = "GP"; /** Health Insurance = HI */ public static final String ROLE_HealthInsurance = "HI"; /** Nursing Home = NH */ public static final String ROLE_NursingHome = "NH"; /** Caregiver = CG */ public static final String ROLE_Caregiver = "CG"; /** Preferred Pharmacy = PP */ public static final String ROLE_PreferredPharmacy = "PP"; /** Nursing Service = NS */ public static final String ROLE_NursingService = "NS"; /** Payer = PA */ public static final String ROLE_Payer = "PA"; /** Payer = PA */ public static final String ROLE_Pharmacy = "PH"; @Override public void setRole (final @Nullable java.lang.String Role) { set_Value (COLUMNNAME_Role, Role); } @Override public java.lang.String getRole() { return get_ValueAsString(COLUMNNAME_Role); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java
1
请完成以下Java代码
public IWeightable wrap(@NonNull final IAttributeStorage attributeStorage) { return new AttributeStorageWeightableWrapper(attributeStorage); } public PlainWeightable plainOf(@NonNull final IAttributeStorage attributeStorage) { return PlainWeightable.copyOf(wrap(attributeStorage)); } public static void updateWeightNet(@NonNull final IWeightable weightable) { // NOTE: we calculate WeightGross, no matter if our HU is allowed to be weighted by user // final boolean weightUOMFriendly = weightable.isWeightable(); final BigDecimal weightTare = weightable.getWeightTareTotal(); final BigDecimal weightGross = weightable.getWeightGross(); final BigDecimal weightNet = weightGross.subtract(weightTare); final BigDecimal weightNetActual; // // If Gross < Tare, we need to propagate the net value with the initial container's Tare value re-added (+) to preserve the real mathematical values if (weightNet.signum() >= 0)
{ weightNetActual = weightNet; // propagate net value below normally weightable.setWeightNet(weightNetActual); } else { weightNetActual = weightNet.add(weightable.getWeightTareInitial()); // only subtract seed value (the container's weight) weightable.setWeightNet(weightNetActual); weightable.setWeightNetNoPropagate(weightNet); // directly set the correct value we're expecting } } public static boolean isWeightableAttribute(@NonNull final AttributeCode attributeCode) { return Weightables.ATTR_WeightGross.equals(attributeCode) || Weightables.ATTR_WeightNet.equals(attributeCode) || Weightables.ATTR_WeightTare.equals(attributeCode) || Weightables.ATTR_WeightTareAdjust.equals(attributeCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\Weightables.java
1
请在Spring Boot框架中完成以下Java代码
public Builder setConsiderNullStringAsNull(final boolean considerNullStringAsNull) { this.considerNullStringAsNull = considerNullStringAsNull; return this; } public Builder setConsiderEmptyStringAsNull(final boolean considerEmptyStringAsNull) { this.considerEmptyStringAsNull = considerEmptyStringAsNull; return this; } public Builder setRowNumberMapKey(final String rowNumberMapKey) { this.rowNumberMapKey = rowNumberMapKey; return this; } /** * Sets if we shall detect repeating headers and discard them.
*/ public Builder setDiscardRepeatingHeaders(final boolean discardRepeatingHeaders) { this.discardRepeatingHeaders = discardRepeatingHeaders; return this; } /** * If enabled, the XLS converter will look for first not null column and it will expect to have one of the codes from {@link RowType}. * If no row type would be found, the row would be ignored entirely. * * task 09045 */ public Builder setUseRowTypeColumn(final boolean useTypeColumn) { this.useTypeColumn = useTypeColumn; return this; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\ExcelToMapListConverter.java
2
请完成以下Java代码
public IQualityInspectionLine getByType(final QualityInspectionLineType type) { final List<IQualityInspectionLine> linesFound = getAllByType(type); if (linesFound.isEmpty()) { throw new AdempiereException("No line found for type: " + type); } else if (linesFound.size() > 1) { throw new AdempiereException("More then one line found for type " + type + ": " + linesFound); } return linesFound.get(0); } @Override public List<IQualityInspectionLine> getAllByType(final QualityInspectionLineType... types) { Check.assumeNotEmpty(types, "types not empty"); final List<QualityInspectionLineType> typesList = Arrays.asList(types);
final List<IQualityInspectionLine> linesFound = new ArrayList<>(); for (final IQualityInspectionLine line : lines) { final QualityInspectionLineType lineType = line.getQualityInspectionLineType(); if (typesList.contains(lineType)) { linesFound.add(line); } } return linesFound; } @Override public IQualityInspectionOrder getQualityInspectionOrder() { return this.qiOrder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLinesCollection.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalReferenceAuditService implements IMasterDataExportAuditService { //dev-note: meant to capture any rest calls made against `EXTERNAL_REFERENCE_RESOURCE` private final static String EXTERNAL_REFERENCE_RESOURCE = ExternalReferenceRestController.EXTERNAL_REFERENCE_REST_CONTROLLER_PATH_V2 + "/**"; private final DataExportAuditService dataExportAuditService; public ExternalReferenceAuditService(@NonNull final DataExportAuditService dataExportAuditService) { this.dataExportAuditService = dataExportAuditService; } @Override public void performDataAuditForRequest(final GenericDataExportAuditRequest genericDataExportAuditRequest) { if (!isHandled(genericDataExportAuditRequest)) { return; } final Object exportedObject = genericDataExportAuditRequest.getExportedObject(); final Optional<JsonExternalReferenceLookupResponse> jsonExternalReferenceLookupResponse = JsonMapperUtil.tryDeserializeToType(exportedObject, JsonExternalReferenceLookupResponse.class); final ExternalSystemParentConfigId externalSystemParentConfigId = genericDataExportAuditRequest.getExternalSystemParentConfigId(); final PInstanceId pInstanceId = genericDataExportAuditRequest.getPInstanceId(); jsonExternalReferenceLookupResponse.ifPresent(lookupResponse -> lookupResponse.getItems() .forEach(item -> auditExternalReference(item, externalSystemParentConfigId, pInstanceId))); }
@Override public boolean isHandled(final GenericDataExportAuditRequest genericDataExportAuditRequest) { final AntPathMatcher antPathMatcher = new AntPathMatcher(); return antPathMatcher.match(EXTERNAL_REFERENCE_RESOURCE, genericDataExportAuditRequest.getRequestURI()); } private void auditExternalReference( @NonNull final JsonExternalReferenceItem jsonExternalReferenceItem, @Nullable final ExternalSystemParentConfigId externalSystemParentConfigId, @Nullable final PInstanceId pInstanceId) { if (jsonExternalReferenceItem.getExternalReferenceId() == null) { return; } final DataExportAuditRequest jsonExternalReferenceItemRequest = DataExportAuditRequest.builder() .tableRecordReference(TableRecordReference.of(I_S_ExternalReference.Table_Name, jsonExternalReferenceItem.getExternalReferenceId().getValue())) .action(Action.Standalone) .externalSystemConfigId(externalSystemParentConfigId) .adPInstanceId(pInstanceId) .build(); dataExportAuditService.createExportAudit(jsonExternalReferenceItemRequest); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\audit\ExternalReferenceAuditService.java
2
请完成以下Spring Boot application配置
spring: profiles: active: dev output: ansi: enabled: always logging: # level: # root: INFO # org.springframework: WARN # file: # name: ./logs/javastack.log # logback: # rollingpolicy: # max-file-size: 100MB structured: format: console: cn.javastack.springboot.logging.SimpleStructuredLogFormat # ecs file: cn.javastack.springboot.logging.SimpleStructuredLogFormat # ecs json: exclude: - process - service rename: log.logger: class message: msg
add: encrypt: false # stacktrace: # root: first # max-length: 1024 # include-common-frames: true # include-hashes: true charset: console: UTF-8 file: UTF-8 register-shutdown-hook: true
repos\spring-boot-best-practice-master\spring-boot-logging\src\main\resources\application.yml
2
请完成以下Java代码
public class ResourceAccessAPI { private static final Logger LOGGER = LoggerFactory.getLogger(ResourceAccessAPI.class); @GET @Path("/default") @Produces(MediaType.TEXT_PLAIN) public Response getDefaultResource() throws IOException { return Response.ok(readResource("default-resource.txt")).build(); } @GET @Path("/default-nested") @Produces(MediaType.TEXT_PLAIN) public Response getDefaultNestedResource() throws IOException { return Response.ok(readResource("text/another-resource.txt")).build(); } @GET @Path("/json")
@Produces(MediaType.APPLICATION_JSON) public Response getJsonResource() throws IOException { return Response.ok(readResource("resources.json")).build(); } private String readResource(String resourcePath) throws IOException { LOGGER.info("Reading resource from path: {}", resourcePath); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath)) { if (in == null) { LOGGER.error("Resource not found at path: {}", resourcePath); throw new IOException("Resource not found: " + resourcePath); } LOGGER.info("Successfully read resource: {}", resourcePath); return new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)).lines() .collect(Collectors.joining("\n")); } } }
repos\tutorials-master\quarkus-modules\quarkus-resources\src\main\java\com\baeldung\quarkus\resources\ResourceAccessAPI.java
1
请完成以下Java代码
public class Entity implements Serializable{ private static final long serialVersionUID = -763638353551774166L; public static final String INDEX_NAME = "index_entity"; public static final String TYPE = "tstype"; private Long id; private String name; public Entity() { super(); } public Entity(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; }
public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\Spring-Boot-In-Action-master\springboot_es_demo\src\main\java\com\hansonwang99\springboot_es_demo\entity\Entity.java
1
请完成以下Java代码
private TbResultSetFuture executeAsync(TbContext ctx, Statement statement, ConsistencyLevel level) { if (log.isDebugEnabled()) { log.debug("Execute cassandra async statement {}", statementToString(statement)); } if (statement.getConsistencyLevel() == null) { statement.setConsistencyLevel(level); } return ctx.submitCassandraWriteTask(new CassandraStatementTask(ctx.getTenantId(), getSession(), statement)); } private static String statementToString(Statement statement) { if (statement instanceof BoundStatement) { return ((BoundStatement) statement).getPreparedStatement().getQuery(); } else { return statement.toString(); } }
@Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: if (!oldConfiguration.has("defaultTtl")) { hasChanges = true; ((ObjectNode) oldConfiguration).put("defaultTtl", 0); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbSaveToCustomCassandraTableNode.java
1
请完成以下Java代码
public Set<String> keySet() { return this.session.getAttributeNames(); } @Override public Collection<Object> values() { return this.values; } @Override public Set<Entry<String, Object>> entrySet() { Set<String> attrNames = keySet(); Set<Entry<String, Object>> entries = new HashSet<>(attrNames.size()); for (String attrName : attrNames) { Object value = this.session.getAttribute(attrName); entries.add(new AbstractMap.SimpleEntry<>(attrName, value)); } return Collections.unmodifiableSet(entries); } private class SessionValues extends AbstractCollection<Object> { @Override public Iterator<Object> iterator() { return new Iterator<Object>() { private Iterator<Entry<String, Object>> i = entrySet().iterator(); @Override public boolean hasNext() { return this.i.hasNext(); } @Override public Object next() { return this.i.next().getValue(); } @Override public void remove() { this.i.remove();
} }; } @Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); } @Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** 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 Benchmark. @param PA_Benchmark_ID Performance Benchmark */ public void setPA_Benchmark_ID (int PA_Benchmark_ID) { if (PA_Benchmark_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID)); } /** Get Benchmark. @return Performance Benchmark */ public int getPA_Benchmark_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Benchmark.java
1
请完成以下Java代码
public void setS_ResourceType_ID (final int S_ResourceType_ID) { if (S_ResourceType_ID < 1) set_Value (COLUMNNAME_S_ResourceType_ID, null); else set_Value (COLUMNNAME_S_ResourceType_ID, S_ResourceType_ID); } @Override public int getS_ResourceType_ID() { return get_ValueAsInt(COLUMNNAME_S_ResourceType_ID); } @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); } @Override public void setWaitingTime (final @Nullable BigDecimal WaitingTime) { set_Value (COLUMNNAME_WaitingTime, WaitingTime); } @Override public BigDecimal getWaitingTime() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WaitingTime); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Resource.java
1
请完成以下Java代码
private static void loadUOMs(Properties ctx) { List<MUOM> list = new Query(ctx, Table_Name, "IsActive='Y'", null) .setRequiredAccess(Access.READ) .list(MUOM.class); // for (MUOM uom : list) { s_cache.put(uom.get_ID(), uom); } } // loadUOMs public MUOM(Properties ctx, int C_UOM_ID, String trxName) { super(ctx, C_UOM_ID, trxName);
if (is_new()) { // setName (null); // setX12DE355 (null); setIsDefault(false); setStdPrecision(2); setCostingPrecision(6); } } // UOM public MUOM(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // UOM } // MUOM
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MUOM.java
1
请完成以下Java代码
private BigDecimal pick(final BigDecimal qtyToPickTarget) { if (qtyToPickTarget.signum() <= 0) { return BigDecimal.ZERO; } if (pickingBOM == null) { return BigDecimal.ZERO; } final BigDecimal qtyAvailableToPick = computeQtyAvailableToPick().toBigDecimal(); final BigDecimal qtyToPickEffective = qtyToPickTarget.min(qtyAvailableToPick); if (qtyToPickEffective.signum() <= 0) { return BigDecimal.ZERO; } for (final QtyCalculationsBOMLine bomLine : pickingBOM.getLines()) { final Quantity componentQty = bomLine.computeQtyRequired(qtyToPickEffective); subtractComponentQtyOnHand(bomLine.getProductId(), componentQty); } return qtyToPickEffective; } private void subtractComponentQtyOnHand(@NonNull final ProductId componentId, @NonNull final Quantity qtyToRemove) { if (qtyToRemove.isZero()) { return; } final ImmutableList<ShipmentScheduleAvailableStockDetail> stockDetails = componentStockDetails.get(componentId); if (stockDetails.isEmpty()) { // shall not happen throw new AdempiereException("No component stock details defined for " + componentId);
} BigDecimal qtyToRemoveRemaining = qtyToRemove.toBigDecimal(); for (final ShipmentScheduleAvailableStockDetail componentStockDetail : stockDetails) { if (qtyToRemoveRemaining.signum() == 0) { break; } final BigDecimal componentQtyToRemoveEffective = qtyToRemoveRemaining.min(componentStockDetail.getQtyAvailable()); componentStockDetail.subtractQtyOnHand(componentQtyToRemoveEffective); qtyToRemoveRemaining = qtyToRemoveRemaining.subtract(componentQtyToRemoveEffective); } if (qtyToRemoveRemaining.signum() != 0) { final ShipmentScheduleAvailableStockDetail lastStockDetail = stockDetails.get(stockDetails.size() - 1); lastStockDetail.subtractQtyOnHand(qtyToRemoveRemaining); qtyToRemoveRemaining = BigDecimal.ZERO; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentScheduleAvailableStockDetail.java
1
请完成以下Java代码
class ProductPriceImporter { private final ProductPriceCreateRequest request; public ProductPriceImporter(@NonNull final ProductPriceCreateRequest request) { this.request = request; } public void createProductPrice_And_PriceListVersionIfNeeded() { if (!isValidPriceRecord()) { throw new AdempiereException("ProductPriceImporter.InvalidProductPriceList"); } if (request.getPrice().signum() >= 0) { if ((request.getPrice().signum() == 0 && request.isUseNewestPriceListversion()) || request.getPrice().signum() > 0)
{ final I_M_PriceList_Version plv = Services.get(IPriceListDAO.class).getCreatePriceListVersion(request); ProductPrices.createProductPriceOrUpdateExistentOne(request, plv); } } } private boolean isValidPriceRecord() { return request.getProductId() > 0 && request.getPriceListId() > 0 && request.getValidDate() != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\product\ProductPriceImporter.java
1
请完成以下Java代码
protected void configureExecutionQuery(ProcessInstanceQueryDto query) { configureAuthorizationCheck(query); configureTenantCheck(query); addPermissionCheck(query, PROCESS_INSTANCE, "RES.PROC_INST_ID_", READ); addPermissionCheck(query, PROCESS_DEFINITION, "P.KEY_", READ_INSTANCE); } protected void injectObjectMapper(ProcessInstanceQueryDto queryParameter) { queryParameter.setObjectMapper(objectMapper); } public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /* The Command interface should always be implemented as a regular, or inner class so that invoked commands are correctly counted with Telemetry. */ protected class QueryProcessInstancesCmd implements Command<List<ProcessInstanceDto>> { protected ProcessInstanceQueryDto queryParameter; protected Integer firstResult; protected Integer maxResults; public QueryProcessInstancesCmd(ProcessInstanceQueryDto queryParameter, Integer firstResult, Integer maxResults) { this.queryParameter = queryParameter; this.firstResult = firstResult; this.maxResults = maxResults; } @Override public List<ProcessInstanceDto> execute(CommandContext commandContext) { injectObjectMapper(queryParameter); injectEngineConfig(queryParameter); paginate(queryParameter, firstResult, maxResults); configureExecutionQuery(queryParameter); return getQueryService().executeQuery("selectRunningProcessInstancesIncludingIncidents", queryParameter); } }
protected class QueryProcessInstancesCountCmd implements Command<CountResultDto> { protected ProcessInstanceQueryDto queryParameter; public QueryProcessInstancesCountCmd(ProcessInstanceQueryDto queryParameter) { this.queryParameter = queryParameter; } @Override public CountResultDto execute(CommandContext commandContext) { injectEngineConfig(queryParameter); configureExecutionQuery(queryParameter); long result = getQueryService().executeQueryRowCount("selectRunningProcessInstancesCount", queryParameter); return new CountResultDto(result); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\ProcessInstanceRestService.java
1
请完成以下Java代码
private static class OneTimeTokenParametersMapper implements Function<OneTimeToken, List<SqlParameterValue>> { @Override public List<SqlParameterValue> apply(OneTimeToken oneTimeToken) { List<SqlParameterValue> parameters = new ArrayList<>(); parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue())); parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getUsername())); parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(oneTimeToken.getExpiresAt()))); return parameters; } } /** * The default {@link RowMapper} that maps the current row in * {@code java.sql.ResultSet} to {@link OneTimeToken}. * * @author Max Batischev
* @since 6.4 */ private static class OneTimeTokenRowMapper implements RowMapper<OneTimeToken> { @Override public OneTimeToken mapRow(ResultSet rs, int rowNum) throws SQLException { String tokenValue = rs.getString("token_value"); String userName = rs.getString("username"); Instant expiresAt = rs.getTimestamp("expires_at").toInstant(); return new DefaultOneTimeToken(tokenValue, userName, expiresAt); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ott\JdbcOneTimeTokenService.java
1
请完成以下Java代码
public void setM_IolCandHandler_ID (final int M_IolCandHandler_ID) { if (M_IolCandHandler_ID < 1) set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, null); else set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, M_IolCandHandler_ID); } @Override public int getM_IolCandHandler_ID() { return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_ID); } @Override public void setM_ShipmentSchedule_AttributeConfig_ID (final int M_ShipmentSchedule_AttributeConfig_ID) { if (M_ShipmentSchedule_AttributeConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID, M_ShipmentSchedule_AttributeConfig_ID); }
@Override public int getM_ShipmentSchedule_AttributeConfig_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID); } @Override public void setOnlyIfInReferencedASI (final boolean OnlyIfInReferencedASI) { set_Value (COLUMNNAME_OnlyIfInReferencedASI, OnlyIfInReferencedASI); } @Override public boolean isOnlyIfInReferencedASI() { return get_ValueAsBoolean(COLUMNNAME_OnlyIfInReferencedASI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_AttributeConfig.java
1
请完成以下Java代码
private void enqueueForInvoicing(final Set<InvoiceCandidateId> invoiceCandIds, final @NonNull I_C_Async_Batch asyncBatch) { trxManager.assertThreadInheritedTrxNotExists(); invoiceCandBL.enqueueForInvoicing() .setContext(getCtx()) .setAsyncBatchId(AsyncBatchId.ofRepoId(asyncBatch.getC_Async_Batch_ID())) .setInvoicingParams(getIInvoicingParams()) .setFailIfNothingEnqueued(true) .enqueueInvoiceCandidateIds(invoiceCandIds); } @NonNull private Iterator<I_C_Invoice> retrieveSelection(@NonNull final PInstanceId pinstanceId) { return queryBL .createQueryBuilder(I_C_Invoice.class) .setOnlySelection(pinstanceId) .create() .iterate(I_C_Invoice.class); } private boolean canVoidPaidInvoice(@NonNull final I_C_Invoice invoice) { final I_C_Invoice inv = InterfaceWrapperHelper.create(invoice, I_C_Invoice.class); if (hasAnyNonPaymentAllocations(inv)) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .contentADMessage(MSG_SKIPPED_INVOICE_NON_PAYMENT_ALLOC_INVOLVED) .contentADMessageParam(inv.getDocumentNo()) .recipientUserId(Env.getLoggedUserId()) .build(); notificationBL.send(userNotificationRequest); return false; } if (commissionTriggerService.isContainsCommissionTriggers(InvoiceId.ofRepoId(invoice.getC_Invoice_ID()))) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder()
.contentADMessage(MSG_SKIPPED_INVOICE_DUE_TO_COMMISSION) .contentADMessageParam(inv.getDocumentNo()) .recipientUserId(Env.getLoggedUserId()) .build(); notificationBL.send(userNotificationRequest); return false; } return true; } @NonNull private IInvoicingParams getIInvoicingParams() { final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); invoicingParams.setUpdateLocationAndContactForInvoice(true); invoicingParams.setIgnoreInvoiceSchedule(false); return invoicingParams; } private boolean hasAnyNonPaymentAllocations(@NonNull final I_C_Invoice invoice) { final List<I_C_AllocationLine> availableAllocationLines = allocationDAO.retrieveAllocationLines(invoice); return availableAllocationLines.stream() .anyMatch(allocationLine -> allocationLine.getC_Payment_ID() <= 0); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\RecreateInvoiceWorkpackageProcessor.java
1
请完成以下Spring Boot application配置
spring: # 对应 RedisProperties 类 redis: host: 127.0.0.1 port: 6379 password: # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码! database: 0 # Redis 数据库号,默认为 0 。 timeout: 0 # Redis 连接超时时间,单位:毫秒。 # 对应 RedisProperties.Jedis 内部类 jedis: pool: max-active: 8 # 连接池最大连接数,默认为 8 。使用负数表示没有限制。 max-idle: 8 #
默认连接数最小空闲的连接数,默认为 8 。使用负数表示没有限制。 min-idle: 0 # 默认连接池最小空闲的连接数,默认为 0 。允许设置 0 和 正数。 max-wait: -1 # 连接池最大阻塞等待时间,单位:毫秒。默认为 -1 ,表示不限制。
repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-with-jedis\src\main\resources\application.yml
2
请完成以下Java代码
public Collection<Artifact> getArtifacts() { return artifactList; } @Override public Map<String, Artifact> getArtifactMap() { return artifactMap; } @Override public void addArtifact(Artifact artifact) { artifactList.add(artifact); addArtifactToMap(artifact); } @Override public void addArtifactToMap(Artifact artifact) { if (artifact != null && StringUtils.isNotEmpty(artifact.getId())) { artifactMap.put(artifact.getId(), artifact); if (getParentContainer() != null) { getParentContainer().addArtifactToMap(artifact); } } } @Override public void removeArtifact(String artifactId) { Artifact artifact = getArtifact(artifactId); if (artifact != null) { artifactList.remove(artifact); } } @Override public SubProcess clone() { SubProcess clone = new SubProcess(); clone.setValues(this); return clone; } public void setValues(SubProcess otherElement) { super.setValues(otherElement); /* * This is required because data objects in Designer have no DI info and are added as properties, not flow elements * * Determine the differences between the 2 elements' data object */
for (ValuedDataObject thisObject : getDataObjects()) { boolean exists = false; for (ValuedDataObject otherObject : otherElement.getDataObjects()) { if (thisObject.getId().equals(otherObject.getId())) { exists = true; break; } } if (!exists) { // missing object removeFlowElement(thisObject.getId()); } } dataObjects = new ArrayList<>(); if (otherElement.getDataObjects() != null && !otherElement.getDataObjects().isEmpty()) { for (ValuedDataObject dataObject : otherElement.getDataObjects()) { ValuedDataObject clone = dataObject.clone(); dataObjects.add(clone); // add it to the list of FlowElements // if it is already there, remove it first so order is same as // data object list removeFlowElement(clone.getId()); addFlowElement(clone); } } flowElementList.clear(); for (FlowElement flowElement : otherElement.getFlowElements()) { addFlowElement(flowElement.clone()); } artifactList.clear(); for (Artifact artifact : otherElement.getArtifacts()) { addArtifact(artifact.clone()); } } public List<ValuedDataObject> getDataObjects() { return dataObjects; } public void setDataObjects(List<ValuedDataObject> dataObjects) { this.dataObjects = dataObjects; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SubProcess.java
1
请在Spring Boot框架中完成以下Java代码
public class TbAlarmStatusSubscription extends TbSubscription<AlarmSubscriptionUpdate> { @Getter private final Set<UUID> alarmIds = new HashSet<>(); @Getter @Setter private boolean hasMoreAlarmsInDB; @Getter private final List<String> typeList; @Getter private final List<AlarmSeverity> severityList; @Builder public TbAlarmStatusSubscription(String serviceId, String sessionId, int subscriptionId, TenantId tenantId, EntityId entityId, BiConsumer<TbSubscription<AlarmSubscriptionUpdate>, AlarmSubscriptionUpdate> updateProcessor,
List<String> typeList, List<AlarmSeverity> severityList) { super(serviceId, sessionId, subscriptionId, tenantId, entityId, TbSubscriptionType.ALARMS, updateProcessor); this.typeList = typeList; this.severityList = severityList; } public boolean matches(AlarmInfo alarm) { return !alarm.isCleared() && (this.typeList == null || this.typeList.contains(alarm.getType())) && (this.severityList == null || this.severityList.contains(alarm.getSeverity())); } public boolean hasAlarms() { return !alarmIds.isEmpty(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAlarmStatusSubscription.java
2
请完成以下Java代码
public final CommissionShare addFact(@NonNull final CommissionFact fact) { facts.add(fact); switch (fact.getState()) { case FORECASTED: forecastedPointsSum = forecastedPointsSum.add(fact.getPoints()); break; case INVOICEABLE: invoiceablePointsSum = invoiceablePointsSum.add(fact.getPoints()); break; case INVOICED: invoicedPointsSum = invoicedPointsSum.add(fact.getPoints()); break; default: throw new AdempiereException("fact has unsupported state " + fact.getState()) .appendParametersToMessage() .setParameter("fact", fact); } return this; } public ImmutableList<CommissionFact> getFacts() {
return ImmutableList.copyOf(facts); } public CommissionContract getContract() { return soTrx.isSales() ? config.getContractFor(payer.getBPartnerId()) : config.getContractFor(beneficiary.getBPartnerId()); } public ProductId getCommissionProductId() { return config.getCommissionProductId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\CommissionShare.java
1
请在Spring Boot框架中完成以下Java代码
public class ResilientAppController { private final ExternalAPICaller externalAPICaller; @Autowired public ResilientAppController(ExternalAPICaller externalApi) { this.externalAPICaller = externalApi; } @GetMapping("/circuit-breaker") @CircuitBreaker(name = "CircuitBreakerService") public String circuitBreakerApi() { return externalAPICaller.callApi(); } @GetMapping("/retry") @Retry(name = "retryApi", fallbackMethod = "fallbackAfterRetry") public String retryApi() { return externalAPICaller.callApi(); } @GetMapping("/time-limiter") @TimeLimiter(name = "timeLimiterApi")
public CompletableFuture<String> timeLimiterApi() { return CompletableFuture.supplyAsync(externalAPICaller::callApiWithDelay); } @GetMapping("/bulkhead") @Bulkhead(name = "bulkheadApi") public String bulkheadApi() { return externalAPICaller.callApi(); } @GetMapping("/rate-limiter") @RateLimiter(name = "rateLimiterApi") public String rateLimitApi() { return externalAPICaller.callApi(); } public String fallbackAfterRetry(Exception ex) { return "all retries have exhausted"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\resilientapp\ResilientAppController.java
2
请完成以下Java代码
public class DocumentType { @XmlElement(required = true) protected byte[] base64; @XmlAttribute(name = "title", required = true) protected String title; @XmlAttribute(name = "filename", required = true) protected String filename; @XmlAttribute(name = "mimeType", required = true) protected String mimeType; /** * Gets the value of the base64 property. * * @return * possible object is * byte[] */ public byte[] getBase64() { return base64; } /** * Sets the value of the base64 property. * * @param value * allowed object is * byte[] */ public void setBase64(byte[] value) { this.base64 = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link String } * */ public String getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link String } * */ public void setTitle(String value) { this.title = value; } /** * Gets the value of the filename property. * * @return * possible object is * {@link String } * */
public String getFilename() { return filename; } /** * Sets the value of the filename property. * * @param value * allowed object is * {@link String } * */ public void setFilename(String value) { this.filename = value; } /** * Gets the value of the mimeType property. * * @return * possible object is * {@link String } * */ public String getMimeType() { return mimeType; } /** * Sets the value of the mimeType property. * * @param value * allowed object is * {@link String } * */ public void setMimeType(String value) { this.mimeType = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\DocumentType.java
1
请在Spring Boot框架中完成以下Java代码
private ShipmentScheduleInfo getShipmentScheduleInfo() { return shipmentSchedulesCache.computeIfAbsent(getScheduleId().getShipmentScheduleId(), shipmentScheduleService::getById); } private HUInfo getSingleTUInfo(@NonNull final TU tu) { tu.assertSingleTU(); return getHUInfo(tu.getId()); } private HUInfo getHUInfo(@NonNull final HuId huId) { return HUInfo.builder() .id(huId) .qrCode(huService.getQRCodeByHuId(huId)) .build(); } public Quantity getStorageQty(@NonNull final TU tu, @NonNull final ProductId productId) { final IHUStorageFactory huStorageFactory = HUContextHolder.getCurrent().getHUStorageFactory(); return huStorageFactory.getStorage(tu.toHU()).getQuantity(productId).orElseThrow(() -> new AdempiereException(NO_QTY_ERROR_MSG, tu, productId)); } private HUQRCode getQRCode(@NonNull final LU lu) {return huService.getQRCodeByHuId(lu.getId());} private HUQRCode getQRCode(@NonNull final TU tu) {return huService.getQRCodeByHuId(tu.getId());} private void addToPickingSlotQueue(final LUTUResult packedHUs) { final PickingSlotId pickingSlotId = getPickingSlotId().orElse(null); if (pickingSlotId == null) { return; } final CurrentPickingTarget currentPickingTarget = getPickingJob().getCurrentPickingTarget(); final LinkedHashSet<HuId> huIdsToAdd = new LinkedHashSet<>(); for (final LU lu : packedHUs.getLus()) { if (lu.isPreExistingLU()) { continue; } // do not add it if is current picking target, we will add it when closing the picking target. if (currentPickingTarget.matches(lu.getId())) {
continue; } huIdsToAdd.add(lu.getId()); } for (final TU tu : packedHUs.getTopLevelTUs()) { // do not add it if is current picking target, we will add it when closing the picking target. if (currentPickingTarget.matches(tu.getId())) { continue; } huIdsToAdd.add(tu.getId()); } if (!huIdsToAdd.isEmpty()) { pickingSlotService.addToPickingSlotQueue(pickingSlotId, huIdsToAdd); } } private Optional<PickingSlotId> getPickingSlotId() { return getPickingJob().getPickingSlotIdEffective(getLineId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\pick\PickingJobPickCommand.java
2
请完成以下Java代码
public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Indication. @param M_Indication_ID Indication */ @Override public void setM_Indication_ID (int M_Indication_ID) { if (M_Indication_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Indication_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Indication_ID, Integer.valueOf(M_Indication_ID)); } /** Get Indication. @return Indication */ @Override public int getM_Indication_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Indication_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.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_Indication.java
1
请在Spring Boot框架中完成以下Java代码
public class PP_Order { private static final AdMessageKey ERROR_MSG_MANUFACTURING_WITH_UNPROCESSED_CANDIDATES = AdMessageKey.of("ManufacturingOrderUnprocessedCandidates"); private final IHUPPOrderBL ppOrderBL = Services.get(IHUPPOrderBL.class); private final IHUPPOrderQtyDAO huPPOrderQtyDAO = Services.get(IHUPPOrderQtyDAO.class); private final PPOrderIssueScheduleRepository ppOrderIssueScheduleRepository; private final PPOrderCandidateDAO ppOrderCandidateDAO; public PP_Order( @NonNull final PPOrderIssueScheduleRepository ppOrderIssueScheduleRepository, @NonNull final PPOrderCandidateDAO ppOrderCandidateDAO) { this.ppOrderIssueScheduleRepository = ppOrderIssueScheduleRepository; this.ppOrderCandidateDAO = ppOrderCandidateDAO; } @DocValidate(timings = ModelValidator.TIMING_BEFORE_CLOSE) public void onBeforeClose(@NonNull final I_PP_Order order) { final PPOrderId ppOrderId = PPOrderId.ofRepoId(order.getPP_Order_ID()); if (huPPOrderQtyDAO.hasUnprocessedOrderQty(ppOrderId)) { throw new AdempiereException(ERROR_MSG_MANUFACTURING_WITH_UNPROCESSED_CANDIDATES); } ppOrderIssueScheduleRepository.deleteNotProcessedByOrderId(ppOrderId); final PPOrderPlanningStatus planningStatus = PPOrderPlanningStatus.ofCode(order.getPlanningStatus()); if (!planningStatus.isComplete()) { ppOrderBL.processPlanning(PPOrderPlanningStatus.COMPLETE, ppOrderId); } } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_VOID, ModelValidator.TIMING_BEFORE_REACTIVATE, ModelValidator.TIMING_BEFORE_REVERSECORRECT, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL }) public void onBeforeReverse(@NonNull final I_PP_Order order) {
final PPOrderId ppOrderId = PPOrderId.ofRepoId(order.getPP_Order_ID()); reverseIssueSchedules(ppOrderId); } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void onAfterComplete(@NonNull final I_PP_Order order) { final PPOrderId ppOrderId = PPOrderId.ofRepoId(order.getPP_Order_ID()); final ImmutableList<I_PP_Order_Candidate> candidates = ppOrderCandidateDAO.getByOrderId(ppOrderId); if (!ppOrderBL.isAtLeastOneCandidateMaturing(candidates)) { return; } if (candidates.size() > 1) { throw new AdempiereException("More than one candidate found for maturing !"); } // dev-note: use WorkPackage, otherwise PP_Cost_Collector is posted before PP_Order and therefore posting is failing HUMaturingWorkpackageProcessor.prepareWorkpackage() .ppOrder(order) .enqueue(); } private void reverseIssueSchedules(@NonNull final PPOrderId ppOrderId) { ppOrderIssueScheduleRepository.deleteNotProcessedByOrderId(ppOrderId); if (ppOrderIssueScheduleRepository.matchesByOrderId(ppOrderId)) { throw new AdempiereException("Reversing processed issue schedules is not allowed"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\interceptor\PP_Order.java
2