instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private LookupValuesList hourLookupProvider() { return LookupValuesList.fromCollection( IntStream.range(0, 24) .mapToObj(this::toStringLookupValue) .collect(ImmutableList.toImmutableList()) ); } @ProcessParamLookupValuesProvider(parameterName = PARAM_Minute, numericKey = false, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.list) private LookupValuesList minuteLookupProvider() { final ResourcePlanningPrecision precision = ppOrderCandidateService.getResourcePlanningPrecision(); final ImmutableSet<LookupValue.StringLookupValue> minutes = precision.getMinutes() .stream() .map(this::toStringLookupValue) .collect(ImmutableSet.toImmutableSet()); return LookupValuesList.fromCollection(minutes); } private ImmutableSet<PPOrderCandidateId> getSelectedPPOrderCandidateIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isAll()) { return getView().streamByIds(selectedRowIds) .limit(rowsLimit) .map(PP_Order_Candidate_SetStartDate::extractPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } else {
return selectedRowIds.stream() .map(PP_Order_Candidate_SetStartDate::toPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } } @NonNull private Timestamp convertParamsToTimestamp() { return Timestamp.valueOf(TimeUtil.asLocalDate(p_Date) .atTime(Integer.parseInt(p_Hour), Integer.parseInt(p_Minute))); } @NonNull private LookupValue.StringLookupValue toStringLookupValue(final int value) { final String formattedValue = String.format("%02d", value); return LookupValue.StringLookupValue.of(formattedValue, formattedValue); } @NonNull private static PPOrderCandidateId extractPPOrderCandidateId(final IViewRow row) {return toPPOrderCandidateId(row.getId());} @NonNull private static PPOrderCandidateId toPPOrderCandidateId(final DocumentId rowId) {return PPOrderCandidateId.ofRepoId(rowId.toInt());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.webui\src\main\java\de\metas\manufacturing\webui\process\PP_Order_Candidate_SetStartDate.java
1
请在Spring Boot框架中完成以下Java代码
public class UserInfoController { @Autowired private UserInfoService userInfoService; @RequestMapping public PageInfo<UserInfo> getAll(UserInfo userInfo) { List<UserInfo> userInfoList = userInfoService.getAll(userInfo); return new PageInfo<UserInfo>(userInfoList); } @RequestMapping(value = "/add") public UserInfo add() { return new UserInfo(); } @RequestMapping(value = "/view/{id}") public UserInfo view(@PathVariable Integer id) { ModelAndView result = new ModelAndView(); UserInfo userInfo = userInfoService.getById(id); return userInfo; } @RequestMapping(value = "/delete/{id}") public ModelMap delete(@PathVariable Integer id) { ModelMap result = new ModelMap();
userInfoService.deleteById(id); result.put("msg", "删除成功!"); return result; } @RequestMapping(value = "/save", method = RequestMethod.POST) public ModelMap save(UserInfo userInfo) { ModelMap result = new ModelMap(); String msg = userInfo.getId() == null ? "新增成功!" : "更新成功!"; userInfoService.save(userInfo); result.put("userInfo", userInfo); result.put("msg", msg); return result; } }
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\controller\UserInfoController.java
2
请在Spring Boot框架中完成以下Java代码
public void setProdName(String prodName) { this.prodName = prodName; } public String getMarketPrice() { return marketPrice; } public void setMarketPrice(String marketPrice) { this.marketPrice = marketPrice; } public String getShopPrice() { return shopPrice; } public void setShopPrice(String shopPrice) { this.shopPrice = shopPrice; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public CategoryEntity getTopCateEntity() { return topCateEntity; } public void setTopCateEntity(CategoryEntity topCateEntity) { this.topCateEntity = topCateEntity; } public CategoryEntity getSubCategEntity() { return subCategEntity; } public void setSubCategEntity(CategoryEntity subCategEntity) { this.subCategEntity = subCategEntity; } public BrandEntity getBrandEntity() { return brandEntity; } public void setBrandEntity(BrandEntity brandEntity) { this.brandEntity = brandEntity; } public ProdStateEnum getProdStateEnum() { return prodStateEnum; } public void setProdStateEnum(ProdStateEnum prodStateEnum) { this.prodStateEnum = prodStateEnum; } public List<ProdImageEntity> getProdImageEntityList() { return prodImageEntityList;
} public void setProdImageEntityList(List<ProdImageEntity> prodImageEntityList) { this.prodImageEntityList = prodImageEntityList; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public UserEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(UserEntity companyEntity) { this.companyEntity = companyEntity; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; } @Override public String toString() { return "ProductEntity{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntity=" + topCateEntity + ", subCategEntity=" + subCategEntity + ", brandEntity=" + brandEntity + ", prodStateEnum=" + prodStateEnum + ", prodImageEntityList=" + prodImageEntityList + ", content='" + content + '\'' + ", companyEntity=" + companyEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java
2
请完成以下Spring Boot application配置
swagger.title=spring-boot-starter-swagger swagger.description=Starter for swagger 2.x swagger.version=1.9.0.RELEASE swagger.license=Apache License, Version 2.0 swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger swagger.contact.name=di
di swagger.contact.url=http://blog.didispace.com swagger.contact.email=dyc87112@qq.com swagger.base-package=com.didispace swagger.base-path=/**
repos\SpringBoot-Learning-master\2.x\chapter2-2\src\main\resources\application.properties
2
请完成以下Java代码
public abstract class AbstractCassandraCluster { @Value("${cassandra.jmx}") private Boolean jmx; @Value("${cassandra.metrics}") private Boolean metrics; @Value("${cassandra.local_datacenter:datacenter1}") private String localDatacenter; @Value("${cassandra.cloud.secure_connect_bundle_path:}") private String cloudSecureConnectBundlePath; @Value("${cassandra.cloud.client_id:}") private String cloudClientId; @Value("${cassandra.cloud.client_secret:}") private String cloudClientSecret; @Autowired private CassandraDriverOptions driverOptions; @Autowired private Environment environment; private GuavaSessionBuilder sessionBuilder; private GuavaSession session; private JmxReporter reporter; private String keyspaceName; protected void init(String keyspaceName) { this.keyspaceName = keyspaceName; this.sessionBuilder = GuavaSessionUtils.builder().withConfigLoader(this.driverOptions.getLoader()); if (!isInstall()) { initSession(); } } public GuavaSession getSession() { if (!isInstall()) { return session; } else { if (session == null) { initSession(); } return session; } } public String getKeyspaceName() { return keyspaceName; } private boolean isInstall() { return environment.acceptsProfiles(Profiles.of("install")); } private void initSession() { if (this.keyspaceName != null) {
this.sessionBuilder.withKeyspace(this.keyspaceName); } this.sessionBuilder.withLocalDatacenter(localDatacenter); if (StringUtils.isNotBlank(cloudSecureConnectBundlePath)) { this.sessionBuilder.withCloudSecureConnectBundle(Paths.get(cloudSecureConnectBundlePath)); this.sessionBuilder.withAuthCredentials(cloudClientId, cloudClientSecret); } session = sessionBuilder.build(); if (this.metrics && this.jmx) { MetricRegistry registry = session.getMetrics().orElseThrow( () -> new IllegalStateException("Metrics are disabled")) .getRegistry(); this.reporter = JmxReporter.forRegistry(registry) .inDomain("com.datastax.oss.driver") .build(); this.reporter.start(); } } @PreDestroy public void close() { if (reporter != null) { reporter.stop(); } if (session != null) { session.close(); } } public ConsistencyLevel getDefaultReadConsistencyLevel() { return driverOptions.getDefaultReadConsistencyLevel(); } public ConsistencyLevel getDefaultWriteConsistencyLevel() { return driverOptions.getDefaultWriteConsistencyLevel(); } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\AbstractCassandraCluster.java
1
请完成以下Java代码
public class LinkedHashSetWithConversion { public static <E> List<E> convertToList(Set<E> set) { return new ArrayList<>(set); } public static <E> int getIndexByConversion(Set<E> set, E element) { List<E> list = new ArrayList<>(set); return list.indexOf(element); } public static <E> E getElementByIndex(Set<E> set, int index) { List<E> list = new ArrayList<>(set); if (index >= 0 && index < list.size()) { return list.get(index); } throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + list.size()); }
@SuppressWarnings("unchecked") public static <E> E[] convertToArray(Set<E> set, Class<E> clazz) { return set.toArray((E[]) java.lang.reflect.Array.newInstance(clazz, set.size())); } public static <E> int getIndexByArray(Set<E> set, E element, Class<E> clazz) { E[] array = convertToArray(set, clazz); for (int i = 0; i < array.length; i++) { if (array[i].equals(element)) { return i; } } return -1; } }
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\LinkedHashSetWithConversion.java
1
请在Spring Boot框架中完成以下Java代码
protected static class WsConfiguration { } static class WsdlDefinitionBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware { @SuppressWarnings("NullAway.Init") private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Binder binder = Binder.get(this.applicationContext.getEnvironment()); List<String> wsdlLocations = binder.bind("spring.webservices.wsdl-locations", Bindable.listOf(String.class)) .orElse(Collections.emptyList()); for (String wsdlLocation : wsdlLocations) { registerBeans(wsdlLocation, "*.wsdl", SimpleWsdl11Definition.class, SimpleWsdl11Definition::new, registry); registerBeans(wsdlLocation, "*.xsd", SimpleXsdSchema.class, SimpleXsdSchema::new, registry); } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } private <T> void registerBeans(String location, String pattern, Class<T> type, Function<Resource, T> beanSupplier, BeanDefinitionRegistry registry) { for (Resource resource : getResources(location, pattern)) { BeanDefinition beanDefinition = BeanDefinitionBuilder .rootBeanDefinition(type, () -> beanSupplier.apply(resource)) .getBeanDefinition(); String filename = resource.getFilename();
Assert.state(filename != null, "'filename' must not be null"); registry.registerBeanDefinition(StringUtils.stripFilenameExtension(filename), beanDefinition); } } private Resource[] getResources(String location, String pattern) { try { return this.applicationContext.getResources(ensureTrailingSlash(location) + pattern); } catch (IOException ex) { return new Resource[0]; } } private String ensureTrailingSlash(String path) { return path.endsWith("/") ? path : path + "/"; } } }
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\autoconfigure\WebServicesAutoConfiguration.java
2
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getProcessInstanceIds() { return null; } public String getBusinessKey() { return businessKey; } public String getExecutionId() { return executionId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public boolean isExcludeSubprocesses() { return excludeSubprocesses; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public boolean isIncludeChildExecutionsWithBusinessKeyQuery() { return includeChildExecutionsWithBusinessKeyQuery; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public boolean isActive() { return isActive; } public String getInvolvedUser() { return involvedUser; } public void setInvolvedUser(String involvedUser) { this.involvedUser = involvedUser; } public Set<String> getProcessDefinitionIds() { return processDefinitionIds; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getParentId() { return parentId; }
public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Spec getSpec() { return this.spec; } public static class Spec { /** * Sub-protocols to use in websocket handshake signature. */ private @Nullable String protocols; /** * Maximum allowable frame payload length. */ private DataSize maxFramePayloadLength = DataSize.ofBytes(65536); /** * Whether to proxy websocket ping frames or respond to them. */ private boolean handlePing; /** * Whether the websocket compression extension is enabled. */ private boolean compress; public @Nullable String getProtocols() { return this.protocols; } public void setProtocols(@Nullable String protocols) { this.protocols = protocols; } public DataSize getMaxFramePayloadLength() { return this.maxFramePayloadLength; }
public void setMaxFramePayloadLength(DataSize maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isHandlePing() { return this.handlePing; } public void setHandlePing(boolean handlePing) { this.handlePing = handlePing; } public boolean isCompress() { return this.compress; } public void setCompress(boolean compress) { this.compress = compress; } } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class HazelcastProperties { /** * The location of the configuration file to use to initialize Hazelcast. */ private @Nullable Resource config; public @Nullable Resource getConfig() { return this.config; } public void setConfig(@Nullable Resource config) { this.config = config; }
/** * Resolve the config location if set. * @return the location or {@code null} if it is not set * @throws IllegalArgumentException if the config attribute is set to an unknown * location */ public @Nullable Resource resolveConfigLocation() { Resource config = this.config; if (config == null) { return null; } Assert.state(config.exists(), () -> "Hazelcast configuration does not exist '" + config.getDescription() + "'"); return config; } }
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\autoconfigure\HazelcastProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void set50(String shade50) { this.shade50 = shade50; } public void set100(String shade100) { this.shade100 = shade100; } public void set200(String shade200) { this.shade200 = shade200; } public void set300(String shade300) { this.shade300 = shade300; } public void set400(String shade400) { this.shade400 = shade400; } public void set500(String shade500) { this.shade500 = shade500; }
public void set600(String shade600) { this.shade600 = shade600; } public void set700(String shade700) { this.shade700 = shade700; } public void set800(String shade800) { this.shade800 = shade800; } public void set900(String shade900) { this.shade900 = shade900; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiProperties.java
2
请完成以下Java代码
default Optional<TableRecordReference> getTableRecordReferenceIfPossible(@NonNull final DocumentPath documentPath) { if (documentPath.getWindowIdOrNull() == null || !documentPath.getWindowId().isInt()) { return Optional.empty(); } final DocumentEntityDescriptor rootEntityDescriptor = getDocumentEntityDescriptor(documentPath.getWindowId()); if (documentPath.isRootDocument()) { final DocumentId rootDocumentId = documentPath.getDocumentId(); if (!rootDocumentId.isInt()) { return Optional.empty(); } final String tableName = rootEntityDescriptor.getTableName(); final int recordId = rootDocumentId.toInt();
return Optional.of(TableRecordReference.of(tableName, recordId)); } else { final DocumentId includedRowId = documentPath.getSingleRowId(); if (!includedRowId.isInt()) { return Optional.empty(); } final DocumentEntityDescriptor includedEntityDescriptor = rootEntityDescriptor.getIncludedEntityByDetailId(documentPath.getDetailId()); final String tableName = includedEntityDescriptor.getTableName(); final int recordId = includedRowId.toInt(); return Optional.of(TableRecordReference.of(tableName, recordId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\DocumentDescriptorFactory.java
1
请完成以下Java代码
public class SetUserPictureCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String userId; protected Picture picture; public SetUserPictureCmd(String userId, Picture picture) { this.userId = userId; this.picture = picture; } public Void execute(CommandContext commandContext) { ensureNotNull("userId", userId); IdentityInfoEntity pictureInfo = commandContext.getIdentityInfoManager() .findUserInfoByUserIdAndKey(userId, "picture"); if (pictureInfo != null) { String byteArrayId = pictureInfo.getValue(); if (byteArrayId != null) { commandContext.getByteArrayManager() .deleteByteArrayById(byteArrayId); } } else {
pictureInfo = new IdentityInfoEntity(); pictureInfo.setUserId(userId); pictureInfo.setKey("picture"); commandContext.getDbEntityManager().insert(pictureInfo); } ByteArrayEntity byteArrayEntity = new ByteArrayEntity(picture.getMimeType(), picture.getBytes(), ResourceTypes.REPOSITORY); commandContext.getByteArrayManager() .insertByteArray(byteArrayEntity); pictureInfo.setValue(byteArrayEntity.getId()); return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetUserPictureCmd.java
1
请完成以下Java代码
public static long updateDateField() { Document document = new Document().append("title", "Piano lessons"); Bson update = Updates.currentDate("updatedAt"); UpdateOptions options = new UpdateOptions().upsert(false); try { UpdateResult result = collection.updateOne(document, update, options); return result.getModifiedCount(); } catch (MongoException me) { System.err.println("Failed to update with error: " + me); throw me; } } public static long updateManyEventsWithDateCriteria(LocalDate updateManyFrom, LocalDate updateManyTo) { Bson query = and(gte("dateTime", updateManyFrom), lt("dateTime", updateManyTo)); Bson updates = Updates.currentDate("dateTime"); try { UpdateResult result = collection.updateMany(query, updates); return result.getModifiedCount(); } catch(MongoException me) { System.err.println("Failed to replace/update with error: " + me); throw me; } }
public static long deleteEventsByDate(LocalDate from, LocalDate to) { Bson query = and(gte("dateTime", from), lt("dateTime", to)); try { DeleteResult result = collection.deleteMany(query); return result.getDeletedCount(); } catch (MongoException me) { System.err.println("Failed to delete with error: " + me); throw me; } } public static void dropDb() { db.drop(); } public static void main(String[] args) { } }
repos\tutorials-master\persistence-modules\java-mongodb-queries\src\main\java\com\baeldung\mongo\crud\CrudClient.java
1
请在Spring Boot框架中完成以下Java代码
public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public String getMetaInfo() { return metaInfo; } @Override public void setMetaInfo(String metaInfo) { this.metaInfo = metaInfo; } // The methods below are not relevant, as getValue() is used directly to return the value set during the transaction @Override public String getTextValue() { return null; } @Override public void setTextValue(String textValue) { } @Override public String getTextValue2() { return null; } @Override public void setTextValue2(String textValue2) { } @Override public Long getLongValue() { return null; } @Override public void setLongValue(Long longValue) { } @Override public Double getDoubleValue() {
return null; } @Override public void setDoubleValue(Double doubleValue) { } @Override public byte[] getBytes() { return null; } @Override public void setBytes(byte[] bytes) { } @Override public Object getCachedValue() { return null; } @Override public void setCachedValue(Object cachedValue) { } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
2
请完成以下Java代码
public int getAD_PrinterHW_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_ID); } @Override public void setAD_PrinterHW_MediaTray_ID (int AD_PrinterHW_MediaTray_ID) { if (AD_PrinterHW_MediaTray_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaTray_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaTray_ID, Integer.valueOf(AD_PrinterHW_MediaTray_ID)); } @Override public int getAD_PrinterHW_MediaTray_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaTray_ID); } @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setName (java.lang.String Name) {
set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public void setTrayNumber (int TrayNumber) { set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber)); } @Override public int getTrayNumber() { return get_ValueAsInt(COLUMNNAME_TrayNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_MediaTray.java
1
请在Spring Boot框架中完成以下Java代码
RSocketStrategiesCustomizer jackson2JsonRSocketStrategyCustomizer(ObjectMapper objectMapper) { return (strategy) -> { strategy.decoder( new org.springframework.http.codec.json.Jackson2JsonDecoder(objectMapper, SUPPORTED_TYPES)); strategy.encoder( new org.springframework.http.codec.json.Jackson2JsonEncoder(objectMapper, SUPPORTED_TYPES)); }; } } } static class NoJacksonOrJackson2Preferred extends AnyNestedCondition { NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper") static class NoJackson { } @ConditionalOnProperty(name = "spring.rsocket.preferred-mapper", havingValue = "jackson2") static class Jackson2Preferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketStrategiesAutoConfiguration.java
2
请完成以下Java代码
protected List<Integer> extractFeature(String text, FeatureMap featureMap) { List<Integer> featureList = new LinkedList<Integer>(); String givenName = extractGivenName(text); // 特征模板1:g[0] addFeature("1" + givenName.substring(0, 1), featureMap, featureList); // 特征模板2:g[1] addFeature("2" + givenName.substring(1), featureMap, featureList); // 特征模板3:g // addFeature("3" + givenName, featureMap, featureList); // 偏置特征(代表标签的先验分布,当样本不均衡时有用,但此处的男女预测无用) // addFeature("b", featureMap, featureList); return featureList; }
/** * 去掉姓氏,截取中国人名中的名字 * * @param name 姓名 * @return 名 */ public static String extractGivenName(String name) { if (name.length() <= 2) return "_" + name.substring(name.length() - 1); else return name.substring(name.length() - 2); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronNameGenderClassifier.java
1
请完成以下Java代码
public HttpServletRequest transform(HttpServletRequest request) { HttpServletRequest wrapped = new AttributesSupportingHttpServletRequest(request); ServletRequestPathUtils.parseAndCache(wrapped); return wrapped; } private static final class AttributesSupportingHttpServletRequest extends HttpServletRequestWrapper { private final Map<String, Object> attributes = new HashMap<>(); AttributesSupportingHttpServletRequest(HttpServletRequest request) { super(request); } @Override public @Nullable Object getAttribute(String name) { return this.attributes.get(name);
} @Override public void setAttribute(String name, Object value) { this.attributes.put(name, value); } @Override public void removeAttribute(String name) { this.attributes.remove(name); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\PathPatternRequestTransformer.java
1
请完成以下Java代码
public final class AndRequestMatcher implements RequestMatcher { private final List<RequestMatcher> requestMatchers; /** * Creates a new instance * @param requestMatchers the {@link RequestMatcher} instances to try */ public AndRequestMatcher(List<RequestMatcher> requestMatchers) { Assert.notEmpty(requestMatchers, "requestMatchers must contain a value"); Assert.noNullElements(requestMatchers, "requestMatchers cannot contain null values"); this.requestMatchers = requestMatchers; } /** * Creates a new instance * @param requestMatchers the {@link RequestMatcher} instances to try */ public AndRequestMatcher(RequestMatcher... requestMatchers) { this(Arrays.asList(requestMatchers)); } @Override public boolean matches(HttpServletRequest request) { for (RequestMatcher matcher : this.requestMatchers) { if (!matcher.matches(request)) { return false; } } return true; } /** * Returns a {@link MatchResult} for this {@link HttpServletRequest}. In the case of a * match, request variables are a composition of the request variables in underlying * matchers. In the event that two matchers have the same key, the last key is the one * propagated. * @param request the HTTP request * @return a {@link MatchResult} based on the given HTTP request * @since 6.1 */ @Override
public MatchResult matcher(HttpServletRequest request) { Map<String, String> variables = new LinkedHashMap<>(); for (RequestMatcher matcher : this.requestMatchers) { MatchResult result = matcher.matcher(request); if (!result.isMatch()) { return MatchResult.notMatch(); } variables.putAll(result.getVariables()); } return MatchResult.match(variables); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AndRequestMatcher that = (AndRequestMatcher) o; return Objects.equals(this.requestMatchers, that.requestMatchers); } @Override public int hashCode() { return Objects.hash(this.requestMatchers); } @Override public String toString() { return "And " + this.requestMatchers; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\AndRequestMatcher.java
1
请完成以下Java代码
public I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException { return (I_M_AttributeSetInstance)MTable.get(getCtx(), I_M_AttributeSetInstance.Table_Name) .getPO(getM_AttributeSetInstance_ID(), get_TrxName()); } /** Set Attribute Set Instance. @param M_AttributeSetInstance_ID Product Attribute Set Instance */ public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Attribute Set Instance. @return Product Attribute Set Instance */ public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_CostElement getM_CostElement() throws RuntimeException { return (I_M_CostElement)MTable.get(getCtx(), I_M_CostElement.Table_Name) .getPO(getM_CostElement_ID(), get_TrxName()); } /** Set Cost Element. @param M_CostElement_ID Product Cost Element */ public void setM_CostElement_ID (int M_CostElement_ID) { if (M_CostElement_ID < 1) set_Value (COLUMNNAME_M_CostElement_ID, null); else set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID)); } /** Get Cost Element. @return Product Cost Element */ public int getM_CostElement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCostAllocation.java
1
请完成以下Java代码
public static HierarchyContract cast(@Nullable final CommissionContract contract) { return castOrEmpty(contract) .orElseThrow(() -> new AdempiereException("Cannot cast the given contract to HierarchyContract") .appendParametersToMessage() .setParameter("contract", contract)); } @JsonCreator @Builder public HierarchyContract( @JsonProperty("id") @NonNull final FlatrateTermId id, @JsonProperty("percent") @NonNull final Percent commissionPercent, @JsonProperty("pointsPrecision") final int pointsPrecision, @JsonProperty("commissionSettingsLineId") @Nullable final CommissionSettingsLineId commissionSettingsLineId, @JsonProperty("isSimulation") final boolean isSimulation) { this.id = id; this.commissionPercent = commissionPercent;
this.pointsPrecision = assumeGreaterOrEqualToZero(pointsPrecision, "pointsPrecision"); this.commissionSettingsLineId = commissionSettingsLineId; this.isSimulation = isSimulation; } /** * Note: add "Hierarchy" as method parameters if and when we have a commission type where it makes a difference. */ public Percent getCommissionPercent() { return commissionPercent; } public int getPointsPrecision() { return pointsPrecision; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\algorithms\hierarchy\HierarchyContract.java
1
请完成以下Java代码
public void onQtyCU_Set_Intercept(final I_DD_OrderLine ddOrderLine) { // Make sure the QtyTU is not changed for the second time if the QtyCU change was triggered by the QtyTU setting in the first place final boolean qtyTUChanged = InterfaceWrapperHelper.isValueChanged(ddOrderLine, I_DD_OrderLine.COLUMNNAME_QtyEnteredTU); if (!qtyTUChanged) { updateQtyPacks(ddOrderLine); } } @CalloutMethod(columnNames = { I_DD_OrderLine.COLUMNNAME_QtyEntered }) public void onQtyCU_Set_Callout(final I_DD_OrderLine ddOrderLine) { // update QtyTU updateQtyPacks(ddOrderLine); } private void updateQtyPacks(final I_DD_OrderLine ddOrderLine) { final IHUPackingAware packingAware = new DDOrderLineHUPackingAware(ddOrderLine); Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware); } private void updateQtyCU(final I_DD_OrderLine ddOrderLine) {
final IHUPackingAware packingAware = new DDOrderLineHUPackingAware(ddOrderLine); // if the QtyTU was set to 0 or deleted, do nothing if (packingAware.getQtyTU().signum() <= 0) { return; } // if the QtyTU was changed but there is no M_HU_PI_Item_Product set, do nothing if (packingAware.getM_HU_PI_Item_Product_ID() <= 0) { return; } // update the QtyCU only if the QtyTU requires it. If the QtyCU is already fine and fits the QtyTU and M_HU_PI_Item_Product, leave it like it is. final QtyTU qtyPacks = QtyTU.ofBigDecimal(packingAware.getQtyTU()); final Quantity qtyCU = Quantitys.of(packingAware.getQty(), UomId.ofRepoId(packingAware.getC_UOM_ID())); Services.get(IHUPackingAwareBL.class).updateQtyIfNeeded(packingAware, qtyPacks.toInt(), qtyCU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\interceptor\DD_OrderLine.java
1
请在Spring Boot框架中完成以下Java代码
public class AmazonAthenaConfiguration { private final AwsConfigurationProperties awsConfigurationProperties; @Bean public AthenaClient athenaClient() { return AthenaClient.builder() .credentialsProvider(constructCredentials()) .build(); } @Bean public QueryExecutionContext queryExecutionContext() { final var database = awsConfigurationProperties.getAthena().getDatabase(); return QueryExecutionContext.builder() .database(database) .build(); }
@Bean public ResultConfiguration resultConfiguration() { final var outputLocation = awsConfigurationProperties.getAthena().getS3OutputLocation(); return ResultConfiguration.builder() .outputLocation(outputLocation) .build(); } private StaticCredentialsProvider constructCredentials() { final var accessKey = awsConfigurationProperties.getAccessKey(); final var secretKey = awsConfigurationProperties.getSecretKey(); final var awsCredentials = AwsBasicCredentials.create(accessKey, secretKey); return StaticCredentialsProvider.create(awsCredentials); } }
repos\tutorials-master\aws-modules\amazon-athena\src\main\java\com\baeldung\athena\configuration\AmazonAthenaConfiguration.java
2
请完成以下Java代码
public class AD_User_Regenerate2FA_ForLoggedInUser extends JavaProcess implements IProcessPrecondition { private final User2FAService user2FAService = SpringContextHolder.instance.getBean(User2FAService.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal(); } final UserId loggedUserId = getLoggedUserId(); final UserId userId = UserId.ofRepoId(context.getSingleSelectedRecordId()); if (!UserId.equals(userId, loggedUserId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("not logged in user"); } if (!user2FAService.isEnabled(userId)) { return ProcessPreconditionsResolution.rejectWithInternalReason("Not enabled"); }
return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final UserId userId = UserId.ofRepoId(getRecord_ID()); final TOTPInfo totpInfo = user2FAService.enable(userId, true); getResult().setDisplayQRCode(ProcessExecutionResult.DisplayQRCode.builder() .code(totpInfo.toQRCodeString()) .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\process\AD_User_Regenerate2FA_ForLoggedInUser.java
1
请完成以下Java代码
public class DebeziumListener { private final Executor executor = Executors.newSingleThreadExecutor(); private final DebeziumEngine<RecordChangeEvent<SourceRecord>> debeziumEngine; public DebeziumListener(Configuration customerConnectorConfiguration) { this.debeziumEngine = DebeziumEngine.create(ChangeEventFormat.of(Connect.class)) .using(customerConnectorConfiguration.asProperties()) .notifying(this::handleChangeEvent) .build(); } private void handleChangeEvent(RecordChangeEvent<SourceRecord> sourceRecordRecordChangeEvent) { SourceRecord sourceRecord = sourceRecordRecordChangeEvent.record(); log.info("Key = {}, Value = {}", sourceRecord.key(), sourceRecord.value()); Object sourceRecordChangeValue= (Struct) sourceRecord.value(); log.info("SourceRecordChangeValue = '{}'",sourceRecordRecordChangeEvent); // if (sourceRecordChangeValue != null) { // Operation operation = Operation.forCode((String) sourceRecordChangeValue.get(OPERATION)); // Operation.READ operation events are always triggered when application initializes // We're only interested in CREATE operation which are triggered upon new insert registry // if(operation != Operation.READ) { // String record = operation == Operation.DELETE ? BEFORE : AFTER; // Handling Update & Insert operations. // Struct struct = (Struct) sourceRecordChangeValue.get(record); // Map<String, Object> payload = struct.schema().fields().stream() // .map(Field::name) // .filter(fieldName -> struct.get(fieldName) != null) // .map(fieldName -> Pair.of(fieldName, struct.get(fieldName))) // .collect(toMap(Pair::getKey, Pair::getValue)); // // this.customerService.replicateData(payload, operation);
// log.info("Updated Data: {} with Operation: {}", payload, operation.name()); // } // } } @PostConstruct private void start() { this.executor.execute(debeziumEngine); } @PreDestroy private void stop() throws IOException { if (Objects.nonNull(this.debeziumEngine)) { this.debeziumEngine.close(); } } }
repos\springboot-demo-master\postgre\src\main\java\com\et\postgres\listener\DebeziumListener.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getDefaultVersion() { return this.defaultVersion; } public void setDefaultVersion(@Nullable String defaultVersion) { this.defaultVersion = defaultVersion; } public @Nullable List<String> getSupported() { return this.supported; } public void setSupported(@Nullable List<String> supported) { this.supported = supported; } public @Nullable Boolean getDetectSupported() { return this.detectSupported; } public void setDetectSupported(@Nullable Boolean detectSupported) { this.detectSupported = detectSupported; } public Use getUse() { return this.use; } public static class Use { /** * Use the HTTP header with the given name to obtain the version. */ private @Nullable String header; /** * Use the query parameter with the given name to obtain the version. */ private @Nullable String queryParameter; /** * Use the path segment at the given index to obtain the version. */ private @Nullable Integer pathSegment; /** * Use the media type parameter with the given name to obtain the version. */ private Map<MediaType, String> mediaTypeParameter = new LinkedHashMap<>(); public @Nullable String getHeader() {
return this.header; } public void setHeader(@Nullable String header) { this.header = header; } public @Nullable String getQueryParameter() { return this.queryParameter; } public void setQueryParameter(@Nullable String queryParameter) { this.queryParameter = queryParameter; } public @Nullable Integer getPathSegment() { return this.pathSegment; } public void setPathSegment(@Nullable Integer pathSegment) { this.pathSegment = pathSegment; } public Map<MediaType, String> getMediaTypeParameter() { return this.mediaTypeParameter; } public void setMediaTypeParameter(Map<MediaType, String> mediaTypeParameter) { this.mediaTypeParameter = mediaTypeParameter; } } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\WebFluxProperties.java
2
请完成以下Java代码
private static int[][] transpose(int[][] input) { int[][] result = new int[input.length][]; for (int x = 0; x < input.length; ++x) { result[x] = new int[input[0].length]; for (int y = 0; y < input[0].length; ++y) { result[x][y] = input[y][x]; } } return result; } private static int[][] reverse(int[][] input) { int[][] result = new int[input.length][]; for (int x = 0; x < input.length; ++x) { result[x] = new int[input[0].length]; for (int y = 0; y < input[0].length; ++y) { result[x][y] = input[x][input.length - y - 1]; } } return result; } @Override public String toString() { return Arrays.deepToString(board); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Board board1 = (Board) o; return Arrays.deepEquals(board, board1.board); } @Override public int hashCode() { return Arrays.deepHashCode(board); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\play2048\Board.java
1
请完成以下Java代码
public CostDetailCreateRequest withCostElement(@NonNull final CostElement costElement) { if (Objects.equals(this.costElement, costElement)) { return this; } return toBuilder().costElement(costElement).build(); } public CostDetailCreateRequest withAmount(@NonNull final CostAmount amt) { return withAmountAndType(amt, this.amtType); } public CostDetailCreateRequest withAmountAndType(@NonNull final CostAmount amt, @NonNull final CostAmountType amtType) { if (Objects.equals(this.amt, amt) && Objects.equals(this.amtType, amtType)) { return this; } return toBuilder().amt(amt).amtType(amtType).build(); } public CostDetailCreateRequest withAmountAndTypeAndQty(@NonNull final CostAmount amt, @NonNull final CostAmountType amtType, @NonNull final Quantity qty) { if (Objects.equals(this.amt, amt) && Objects.equals(this.amtType, amtType) && Objects.equals(this.qty, qty)) { return this; } return toBuilder().amt(amt).amtType(amtType).qty(qty).build(); } public CostDetailCreateRequest withAmountAndTypeAndQty(@NonNull final CostAmountAndQty amtAndQty, @NonNull final CostAmountType amtType) { return withAmountAndTypeAndQty(amtAndQty.getAmt(), amtType, amtAndQty.getQty()); } public CostDetailCreateRequest withAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty) { if (Objects.equals(this.amt, amt) && Objects.equals(this.qty, qty)) { return this; } return toBuilder().amt(amt).qty(qty).build(); } public CostDetailCreateRequest withProductId(@NonNull final ProductId productId) { if (ProductId.equals(this.productId, productId)) { return this; } return toBuilder().productId(productId).build(); } public CostDetailCreateRequest withProductIdAndQty( @NonNull final ProductId productId, @NonNull final Quantity qty) { if (ProductId.equals(this.productId, productId) && Objects.equals(this.qty, qty)) {
return this; } return toBuilder().productId(productId).qty(qty).build(); } public CostDetailCreateRequest withQty(@NonNull final Quantity qty) { if (Objects.equals(this.qty, qty)) { return this; } return toBuilder().qty(qty).build(); } public CostDetailCreateRequest withQtyZero() { return withQty(qty.toZero()); } public CostDetailBuilder toCostDetailBuilder() { final CostDetailBuilder costDetail = CostDetail.builder() .clientId(getClientId()) .orgId(getOrgId()) .acctSchemaId(getAcctSchemaId()) .productId(getProductId()) .attributeSetInstanceId(getAttributeSetInstanceId()) // .amtType(getAmtType()) .amt(getAmt()) .qty(getQty()) // .documentRef(getDocumentRef()) .description(getDescription()) .dateAcct(getDate()); if (isExplicitCostElement()) { costDetail.costElementId(getCostElementId()); } return costDetail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateRequest.java
1
请完成以下Java代码
public int getRfQ_Win_PrintFormat_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_PrintFormat_ID); if (ii == null) return 0; return ii.intValue(); } /** * RfQType AD_Reference_ID=540661 * Reference name: RfQType */ public static final int RFQTYPE_AD_Reference_ID=540661; /** Default = D */ public static final String RFQTYPE_Default = "D"; /** Procurement = P */ public static final String RFQTYPE_Procurement = "P"; /** Set Ausschreibung Art.
@param RfQType Ausschreibung Art */ @Override public void setRfQType (java.lang.String RfQType) { set_Value (COLUMNNAME_RfQType, RfQType); } /** Get Ausschreibung Art. @return Ausschreibung Art */ @Override public java.lang.String getRfQType () { return (java.lang.String)get_Value(COLUMNNAME_RfQType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_Topic.java
1
请完成以下Java代码
public static VariableValueDto fromFormPart(String type, FormPart binaryDataFormPart) { VariableValueDto dto = new VariableValueDto(); dto.type = type; dto.value = binaryDataFormPart.getBinaryContent(); if (ValueType.FILE.getName().equals(fromRestApiTypeName(type))) { String contentType = binaryDataFormPart.getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } dto.valueInfo = new HashMap<>(); dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_NAME, binaryDataFormPart.getFileName()); MimeType mimeType = null; try { mimeType = new MimeType(contentType); } catch (MimeTypeParseException e) { throw new RestException(Status.BAD_REQUEST, "Invalid mime type given"); }
dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_MIME_TYPE, mimeType.getBaseType()); String encoding = mimeType.getParameter("encoding"); if (encoding != null) { dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_ENCODING, encoding); } String transientString = mimeType.getParameter("transient"); boolean isTransient = Boolean.parseBoolean(transientString); if (isTransient) { dto.valueInfo.put(AbstractValueTypeImpl.VALUE_INFO_TRANSIENT, isTransient); } } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\VariableValueDto.java
1
请完成以下Java代码
public class FakeNumExample { // Here we use some String constants to represents countries. static final @Fenum("country") String ITALY = "IT"; static final @Fenum("country") String US = "US"; static final @Fenum("country") String UNITED_KINGDOM = "UK"; // Here we use other String constants to represent planets instead. static final @Fenum("planet") String MARS = "Mars"; static final @Fenum("planet") String EARTH = "Earth"; static final @Fenum("planet") String VENUS = "Venus"; // Now we write this method and we want to be sure that // the String parameter has a value of a country, not that is just a String. void greetCountries(@Fenum("country") String country) { System.out.println("Hello " + country); } // Similarly we're enforcing here that the provided
// parameter is a String that represent a planet. void greetPlanets(@Fenum("planet") String planet) { System.out.println("Hello " + planet); } public static void main(String[] args) { FakeNumExample obj = new FakeNumExample(); // This will fail because we pass a planet-String to a method that // accept a country-String. obj.greetCountries(MARS); // Here the opposite happens. obj.greetPlanets(US); } }
repos\tutorials-master\checker-framework\src\main\java\com\baeldung\typechecker\FakeNumExample.java
1
请完成以下Java代码
public String getResultVariableName() { return resultVariableName; } public void setResultVariableName(String resultVariableName) { this.resultVariableName = resultVariableName; } public List<String> getRuleNames() { return ruleNames; } public void setRuleNames(List<String> ruleNames) { this.ruleNames = ruleNames; } public List<String> getInputVariables() { return inputVariables; } public void setInputVariables(List<String> inputVariables) { this.inputVariables = inputVariables; } public String getClassName() { return className; } public void setClassName(String className) {
this.className = className; } public BusinessRuleTask clone() { BusinessRuleTask clone = new BusinessRuleTask(); clone.setValues(this); return clone; } public void setValues(BusinessRuleTask otherElement) { super.setValues(otherElement); setResultVariableName(otherElement.getResultVariableName()); setExclude(otherElement.isExclude()); setClassName(otherElement.getClassName()); ruleNames = new ArrayList<String>(otherElement.getRuleNames()); inputVariables = new ArrayList<String>(otherElement.getInputVariables()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BusinessRuleTask.java
1
请完成以下Java代码
public JsonResolveHUResponse resolveHU(@RequestBody @NonNull final JsonResolveHURequest request) { assertApplicationAccess(); final ResolveHUResponse response = jobService.resolveHU( ResolveHURequest.builder() .scannedCode(request.getScannedCode()) .callerId(Env.getLoggedUserId()) .wfProcessId(request.getWfProcessId()) .lineId(request.getLineId()) .locatorId(request.getLocatorQRCode().getLocatorId()) .build() ); return mappers.newJsonResolveHUResponse(newJsonOpts()).toJson(response); } @PostMapping("/count") public JsonWFProcess reportCounting(@RequestBody @NonNull final JsonCountRequest request) { assertApplicationAccess(); final Inventory inventory = jobService.reportCounting(request, Env.getLoggedUserId()); return toJsonWFProcess(inventory); } private JsonWFProcess toJsonWFProcess(final Inventory inventory) { return workflowRestController.toJson(WFProcessMapper.toWFProcess(inventory)); } @GetMapping("/lineHU") public JsonInventoryLineHU getLineHU( @RequestParam("wfProcessId") @NonNull String wfProcessIdStr, @RequestParam("lineId") @NonNull String lineIdStr, @RequestParam("lineHUId") @NonNull String lineHUIdStr)
{ assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr); final InventoryLineHUId lineHUId = InventoryLineHUId.ofObject(lineHUIdStr); final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId); return mappers.newJsonInventoryJobMapper(newJsonOpts()) .loadAllDetails(true) .toJson(line, lineHUId); } @GetMapping("/lineHUs") public JsonGetLineHUsResponse getLineHUs( @RequestParam("wfProcessId") @NonNull String wfProcessIdStr, @RequestParam("lineId") @NonNull String lineIdStr) { assertApplicationAccess(); final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr); final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr); final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId); return JsonGetLineHUsResponse.builder() .wfProcessId(wfProcessId) .lineId(lineId) .lineHUs(mappers.newJsonInventoryJobMapper(newJsonOpts()).toJsonInventoryLineHUs(line)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\InventoryRestController.java
1
请完成以下Java代码
public void springUnSupportedFieldPatch(HttpServletResponse response) throws IOException { response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value()); } // @Validate For Validating Path Variables and Request Parameters @ExceptionHandler(ConstraintViolationException.class) public void constraintViolationException(HttpServletResponse response) throws IOException { response.sendError(HttpStatus.BAD_REQUEST.value()); } // error handle for @Valid @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { Map<String, Object> body = new LinkedHashMap<>(); body.put("timestamp", new Date()); body.put("status", status.value());
//Get all errors List<String> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(x -> x.getDefaultMessage()) .collect(Collectors.toList()); body.put("errors", errors); return new ResponseEntity<>(body, headers, status); //Map<String, String> fieldErrors = ex.getBindingResult().getFieldErrors().stream().collect( // Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)); } }
repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\error\CustomGlobalExceptionHandler.java
1
请完成以下Java代码
public Mono<OAuth2AuthorizationRequest> loadAuthorizationRequest(ServerWebExchange exchange) { String state = getStateParameter(exchange); if (state == null) { return Mono.empty(); } // @formatter:off return getSessionAttributes(exchange) .filter((sessionAttrs) -> sessionAttrs.containsKey(this.sessionAttributeName)) .map(this::getAuthorizationRequest) .filter((authorizationRequest) -> state.equals(authorizationRequest.getState())); // @formatter:on } @Override public Mono<Void> saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, ServerWebExchange exchange) { Assert.notNull(authorizationRequest, "authorizationRequest cannot be null"); Assert.notNull(exchange, "exchange cannot be null"); // @formatter:off return getSessionAttributes(exchange) .doOnNext((sessionAttrs) -> { Assert.hasText(authorizationRequest.getState(), "authorizationRequest.state cannot be empty"); sessionAttrs.put(this.sessionAttributeName, authorizationRequest); }) .then(); // @formatter:on } @Override public Mono<OAuth2AuthorizationRequest> removeAuthorizationRequest(ServerWebExchange exchange) { String state = getStateParameter(exchange); if (state == null) { return Mono.empty(); } // @formatter:off return getSessionAttributes(exchange) .filter((sessionAttrs) -> sessionAttrs.containsKey(this.sessionAttributeName)) .flatMap((sessionAttrs) -> { OAuth2AuthorizationRequest authorizationRequest = (OAuth2AuthorizationRequest) sessionAttrs.get(this.sessionAttributeName); if (state.equals(authorizationRequest.getState())) {
sessionAttrs.remove(this.sessionAttributeName); return Mono.just(authorizationRequest); } return Mono.empty(); }); // @formatter:on } /** * Gets the state parameter from the {@link ServerHttpRequest} * @param exchange the exchange to use * @return the state parameter or null if not found */ private String getStateParameter(ServerWebExchange exchange) { Assert.notNull(exchange, "exchange cannot be null"); return exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.STATE); } private Mono<Map<String, Object>> getSessionAttributes(ServerWebExchange exchange) { return exchange.getSession().map(WebSession::getAttributes); } private OAuth2AuthorizationRequest getAuthorizationRequest(Map<String, Object> sessionAttrs) { return (OAuth2AuthorizationRequest) sessionAttrs.get(this.sessionAttributeName); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\WebSessionOAuth2ServerAuthorizationRequestRepository.java
1
请完成以下Java代码
public String classify(String text) throws IllegalArgumentException, IllegalStateException { Map<String, Double> scoreMap = predict(text); return CollectionUtility.max(scoreMap); } @Override public String classify(Document document) throws IllegalArgumentException, IllegalStateException { Map<String, Double> scoreMap = predict(document); return CollectionUtility.max(scoreMap); } @Override public void train(String folderPath, String charsetName) throws IOException { IDataSet dataSet = new MemoryDataSet(); dataSet.load(folderPath, charsetName); train(dataSet); } @Override public void train(Map<String, String[]> trainingDataSet) throws IllegalArgumentException { IDataSet dataSet = new MemoryDataSet(); logger.start("正在构造训练数据集..."); int total = trainingDataSet.size(); int cur = 0; for (Map.Entry<String, String[]> entry : trainingDataSet.entrySet()) { String category = entry.getKey(); logger.out("[%s]...", category); for (String doc : entry.getValue()) { dataSet.add(category, doc); } ++cur; logger.out("%.2f%%...", MathUtility.percentage(cur, total)); } logger.finish(" 加载完毕\n"); train(dataSet); } @Override public void train(String folderPath) throws IOException { train(folderPath, "UTF-8"); }
@Override public Map<String, Double> predict(Document document) { AbstractModel model = getModel(); if (model == null) { throw new IllegalStateException("未训练模型!无法执行预测!"); } if (document == null) { throw new IllegalArgumentException("参数 text == null"); } double[] probs = categorize(document); Map<String, Double> scoreMap = new TreeMap<String, Double>(); for (int i = 0; i < probs.length; i++) { scoreMap.put(model.catalog[i], probs[i]); } return scoreMap; } @Override public int label(Document document) throws IllegalArgumentException, IllegalStateException { AbstractModel model = getModel(); if (model == null) { throw new IllegalStateException("未训练模型!无法执行预测!"); } if (document == null) { throw new IllegalArgumentException("参数 text == null"); } double[] probs = categorize(document); double max = Double.NEGATIVE_INFINITY; int best = -1; for (int i = 0; i < probs.length; i++) { if (probs[i] > max) { max = probs[i]; best = i; } } return best; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\classifiers\AbstractClassifier.java
1
请在Spring Boot框架中完成以下Java代码
public static String getErrorMessage(ConstraintViolation<Object> constraintViolation) { ConstraintDescriptor<?> constraintDescriptor = constraintViolation.getConstraintDescriptor(); String property = (String) constraintDescriptor.getAttributes().get("fieldName"); if (StringUtils.isEmpty(property) && !(constraintDescriptor.getAnnotation() instanceof AssertTrue)) { property = Iterators.getLast(constraintViolation.getPropertyPath().iterator()).toString(); } String error = ""; if (StringUtils.isNotEmpty(property)) { error += property + " "; } error += constraintViolation.getMessage(); return error; } private static void initializeValidators() { HibernateValidatorConfiguration validatorConfiguration = Validation.byProvider(HibernateValidator.class).configure(); ConstraintMapping constraintMapping = getCustomConstraintMapping(); validatorConfiguration.addMapping(constraintMapping); try (var validatorFactory = validatorConfiguration.buildValidatorFactory()) { fieldsValidator = validatorFactory.getValidator(); } }
@Bean public LocalValidatorFactoryBean validatorFactoryBean() { LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); localValidatorFactoryBean.setConfigurationInitializer(configuration -> { ((ConfigurationImpl) configuration).addMapping(getCustomConstraintMapping()); }); return localValidatorFactoryBean; } private static ConstraintMapping getCustomConstraintMapping() { ConstraintMapping constraintMapping = new DefaultConstraintMapping(null); constraintMapping.constraintDefinition(NoXss.class).validatedBy(NoXssValidator.class); constraintMapping.constraintDefinition(Length.class).validatedBy(StringLengthValidator.class); constraintMapping.constraintDefinition(RateLimit.class).validatedBy(RateLimitValidator.class); constraintMapping.constraintDefinition(NoNullChar.class).validatedBy(NoNullCharValidator.class); constraintMapping.constraintDefinition(ValidJsonSchema.class).validatedBy(JsonSchemaValidator.class); return constraintMapping; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\ConstraintValidator.java
2
请完成以下Java代码
public void setProcessDefinitionVersion(Integer processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ProcessInstanceImpl that = (ProcessInstanceImpl) o; return ( Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(processDefinitionId, that.processDefinitionId) && Objects.equals(processDefinitionKey, that.processDefinitionKey) && Objects.equals(initiator, that.initiator) && Objects.equals(startDate, that.startDate) && Objects.equals(completedDate, that.completedDate) && Objects.equals(businessKey, that.businessKey) && status == that.status && Objects.equals(parentId, that.parentId) && Objects.equals(processDefinitionVersion, that.processDefinitionVersion) && Objects.equals(processDefinitionName, that.processDefinitionName) ); } @Override public int hashCode() { return Objects.hash( super.hashCode(), id, name, processDefinitionId, processDefinitionKey, initiator, startDate, completedDate, businessKey, status, parentId, processDefinitionVersion, processDefinitionName ); }
@Override public String toString() { return ( "ProcessInstance{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", processDefinitionId='" + processDefinitionId + '\'' + ", processDefinitionKey='" + processDefinitionKey + '\'' + ", parentId='" + parentId + '\'' + ", initiator='" + initiator + '\'' + ", startDate=" + startDate + ", completedDate=" + completedDate + ", businessKey='" + businessKey + '\'' + ", status=" + status + ", processDefinitionVersion='" + processDefinitionVersion + '\'' + ", processDefinitionName='" + processDefinitionName + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessInstanceImpl.java
1
请完成以下Java代码
public void setCarrier_Service_ID (final int Carrier_Service_ID) { if (Carrier_Service_ID < 1) set_Value (COLUMNNAME_Carrier_Service_ID, null); else set_Value (COLUMNNAME_Carrier_Service_ID, Carrier_Service_ID); } @Override public int getCarrier_Service_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_Service_ID); } @Override public void setM_ShipmentSchedule_Carrier_Service_ID (final int M_ShipmentSchedule_Carrier_Service_ID) { if (M_ShipmentSchedule_Carrier_Service_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_Carrier_Service_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_Carrier_Service_ID, M_ShipmentSchedule_Carrier_Service_ID); }
@Override public int getM_ShipmentSchedule_Carrier_Service_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_Carrier_Service_ID); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ShipmentSchedule_Carrier_Service.java
1
请完成以下Java代码
public void setCosts (BigDecimal Costs) { set_Value (COLUMNNAME_Costs, Costs); } /** Get Costs. @return Costs in accounting currency */ public BigDecimal getCosts () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Costs); if (bd == null) return Env.ZERO; return bd; } /** 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 End Date. @param EndDate Last effective date (inclusive) */ public void setEndDate (Timestamp EndDate) { set_Value (COLUMNNAME_EndDate, EndDate); } /** Get End Date. @return Last effective date (inclusive) */ public Timestamp getEndDate () { return (Timestamp)get_Value(COLUMNNAME_EndDate); } /** Set Summary Level. @param IsSummary This is a summary entity */ public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Summary Level. @return This is a summary entity */ public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDefault() { return true; } }, /** * OpenMetrics text version 1.0.0. */ CONTENT_TYPE_OPENMETRICS_100(OpenMetricsTextFormatWriter.CONTENT_TYPE) { @Override void write(ExpositionFormats expositionFormats, OutputStream outputStream, MetricSnapshots snapshots) throws IOException { expositionFormats.getOpenMetricsTextFormatWriter().write(outputStream, snapshots); } }, /** * Prometheus metrics protobuf. */ CONTENT_TYPE_PROTOBUF(PrometheusProtobufWriter.CONTENT_TYPE) { @Override void write(ExpositionFormats expositionFormats, OutputStream outputStream, MetricSnapshots snapshots) throws IOException { expositionFormats.getPrometheusProtobufWriter().write(outputStream, snapshots); }
}; private final MimeType mimeType; PrometheusOutputFormat(String mimeType) { this.mimeType = MimeTypeUtils.parseMimeType(mimeType); } @Override public MimeType getProducedMimeType() { return this.mimeType; } abstract void write(ExpositionFormats expositionFormats, OutputStream outputStream, MetricSnapshots snapshots) throws IOException; }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusOutputFormat.java
2
请完成以下Spring Boot application配置
spring: datasource: url: jdbc:h2:mem:passkey sql: init: mode: always security: webauthn: rpName: "WebAuthn Demo" # Replace with the domainname of your application rpId: localhost allowedOrigins: # Replace with the UR
L of your application. Notice: this _MUST_ be an HTTPS URL with a valid certificate - "http://localhost:8080"
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\resources\application-local.yaml
2
请完成以下Java代码
public void purgeExpiredSessionsNoFail() { try { purgeExpiredSessions(); } catch (final Throwable ex) { logger.warn("Failed purging expired sessions. Ignored.", ex); } } public void purgeExpiredSessions() { final Stopwatch stopwatch = Stopwatch.createStarted();
int countExpiredSessions = 0; final List<MapSession> sessionsToCheck = new ArrayList<>(sessions.values()); for (final MapSession session : sessionsToCheck) { if (session.isExpired()) { deleteAndFireEvent(session.getId(), true /* expired */); countExpiredSessions++; } } logger.debug("Purged {}/{} expired sessions in {}", countExpiredSessions, sessionsToCheck.size(), stopwatch); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\FixedMapSessionRepository.java
1
请完成以下Java代码
public void setReadWrite (boolean rw) { if (super.isEditable() != rw) super.setEditable (rw); setBackground(false); } // setEditable /** * Is it possible to edit * @return true, if editable */ @Override public boolean isReadWrite() { return super.isEditable(); } // isReadWrite /** * Set Background based on editable / mandatory / error * @param error if true, set background to error color, otherwise mandatory/editable */ @Override public void setBackground (boolean error) { if (error) setBackground(AdempierePLAF.getFieldBackground_Error()); else if (!isReadWrite()) setBackground(AdempierePLAF.getFieldBackground_Inactive()); else if (m_mandatory) setBackground(AdempierePLAF.getFieldBackground_Mandatory()); else setBackground(AdempierePLAF.getFieldBackground_Normal()); } // setBackground /** * Set Background * @param bg */ @Override public void setBackground (Color bg) { if (bg.equals(getBackground())) return; super.setBackground(bg); } // setBackground /** * Set Editor to value * @param value value of the editor
*/ @Override public void setValue (Object value) { if (value == null) setText(""); else setText(value.toString()); } // setValue /** * Return Editor value * @return current value */ @Override public Object getValue() { return new String(super.getPassword()); } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { return new String(super.getPassword()); } // getDisplay }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPassword.java
1
请完成以下Java代码
protected RouteDefinition buildRouteDefinition(Expression urlExpr, ServiceInstance serviceInstance) { String serviceId = serviceInstance.getServiceId(); RouteDefinition routeDefinition = new RouteDefinition(); routeDefinition.setId(this.routeIdPrefix + serviceId); String uri = urlExpr.getValue(this.evalCtxt, serviceInstance, String.class); if (uri != null) { routeDefinition.setUri(URI.create(uri)); } // add instance metadata routeDefinition.setMetadata(new LinkedHashMap<>(serviceInstance.getMetadata())); return routeDefinition; } private @Nullable String getValueFromExpr(SimpleEvaluationContext evalCtxt, SpelExpressionParser parser, ServiceInstance instance, Map.Entry<String, String> entry) { try { Expression valueExpr = parser.parseExpression(entry.getValue()); return valueExpr.getValue(evalCtxt, instance, String.class); } catch (ParseException | EvaluationException e) { if (log.isDebugEnabled()) { log.debug("Unable to parse " + entry.getValue(), e); } throw e; } } private static class DelegatingServiceInstance implements ServiceInstance { final ServiceInstance delegate; private final DiscoveryLocatorProperties properties; private DelegatingServiceInstance(ServiceInstance delegate, DiscoveryLocatorProperties properties) { this.delegate = delegate; this.properties = properties; } @Override public String getServiceId() { if (properties.isLowerCaseServiceId()) { return delegate.getServiceId().toLowerCase(Locale.ROOT); } return delegate.getServiceId(); } @Override public String getHost() { return delegate.getHost();
} @Override public int getPort() { return delegate.getPort(); } @Override public boolean isSecure() { return delegate.isSecure(); } @Override public URI getUri() { return delegate.getUri(); } @Override public @Nullable Map<String, String> getMetadata() { return delegate.getMetadata(); } @Override public @Nullable String getScheme() { return delegate.getScheme(); } @Override public String toString() { return new ToStringCreator(this).append("delegate", delegate).append("properties", properties).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryClientRouteDefinitionLocator.java
1
请完成以下Java代码
public int hashCode() { return getClass().hashCode(); } /** * Dump out abstract syntax tree for a given expression * * @param args array with one element, containing the expression string */ public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java " + Builder.class.getName() + " <expression string>"); System.exit(1); } PrintWriter out = new PrintWriter(System.out); Tree tree = null; try { tree = new Builder(Feature.METHOD_INVOCATIONS).build(args[0]); } catch (TreeBuilderException e) { System.out.println(e.getMessage()); System.exit(0); } NodePrinter.dump(out, tree.getRoot()); if (!tree.getFunctionNodes().iterator().hasNext() && !tree.getIdentifierNodes().iterator().hasNext()) { ELContext context = new ELContext() { @Override
public VariableMapper getVariableMapper() { return null; } @Override public FunctionMapper getFunctionMapper() { return null; } @Override public ELResolver getELResolver() { return null; } }; out.print(">> "); try { out.println(tree.getRoot().getValue(new Bindings(null, null), context, null)); } catch (ELException e) { out.println(e.getMessage()); } } out.flush(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Builder.java
1
请在Spring Boot框架中完成以下Java代码
public class LimitAspect { private final RedisTemplate<Object,Object> redisTemplate; private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class); public LimitAspect(RedisTemplate<Object,Object> redisTemplate) { this.redisTemplate = redisTemplate; } @Pointcut("@annotation(me.zhengjie.annotation.Limit)") public void pointcut() { } @Around("pointcut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = RequestHolder.getHttpServletRequest(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method signatureMethod = signature.getMethod(); Limit limit = signatureMethod.getAnnotation(Limit.class); LimitType limitType = limit.limitType(); String key = limit.key(); if (StringUtils.isEmpty(key)) { if (limitType == LimitType.IP) { key = StringUtils.getIp(request); } else { key = signatureMethod.getName(); } }
ImmutableList<Object> keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replace("/","_"))); String luaScript = buildLuaScript(); RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class); Long count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period()); if (ObjUtil.isNotNull(count) && count.intValue() <= limit.count()) { logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name()); return joinPoint.proceed(); } else { throw new BadRequestException("访问次数受限制"); } } /** * 限流脚本 */ private String buildLuaScript() { return "local c" + "\nc = redis.call('get',KEYS[1])" + "\nif c and tonumber(c) > tonumber(ARGV[1]) then" + "\nreturn c;" + "\nend" + "\nc = redis.call('incr',KEYS[1])" + "\nif tonumber(c) == 1 then" + "\nredis.call('expire',KEYS[1],ARGV[2])" + "\nend" + "\nreturn c;"; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\aspect\LimitAspect.java
2
请完成以下Java代码
public ResponseEntity<Object> queryAllTables(){ return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK); } @ApiOperation("查询数据库数据") @GetMapping(value = "/tables") public ResponseEntity<PageResult<TableInfo>> queryTables(@RequestParam(defaultValue = "") String name, @RequestParam(defaultValue = "0")Integer page, @RequestParam(defaultValue = "10")Integer size){ int[] startEnd = PageUtil.transToStartEnd(page, size); return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK); } @ApiOperation("查询字段数据") @GetMapping(value = "/columns") public ResponseEntity<PageResult<ColumnInfo>> queryColumns(@RequestParam String tableName){ List<ColumnInfo> columnInfos = generatorService.getColumns(tableName); return new ResponseEntity<>(PageUtil.toPage(columnInfos,columnInfos.size()), HttpStatus.OK); } @ApiOperation("保存字段数据") @PutMapping public ResponseEntity<HttpStatus> saveColumn(@RequestBody List<ColumnInfo> columnInfos){ generatorService.save(columnInfos); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("同步字段数据") @PostMapping(value = "sync") public ResponseEntity<HttpStatus> syncColumn(@RequestBody List<String> tables){ for (String table : tables) { generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); }
return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("生成代码") @PostMapping(value = "/{tableName}/{type}") public ResponseEntity<Object> generatorCode(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response){ if(!generatorEnabled && type == 0){ throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); } switch (type){ // 生成代码 case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); break; // 预览 case 1: return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); // 打包 case 2: generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); break; default: throw new BadRequestException("没有这个选项"); } return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\rest\GeneratorController.java
1
请完成以下Java代码
public String jwtFromUser(User user) { final var messageToSign = JWT_HEADER.concat(".").concat(jwtPayloadFromUser(user)); final var signature = HmacSHA256.sign(secret, messageToSign); return messageToSign.concat(".").concat(base64URLFromBytes(signature)); } private String jwtPayloadFromUser(User user) { var jwtPayload = UserJWTPayload.of(user, now().getEpochSecond() + durationSeconds); return base64URLFromString(jwtPayload.toString()); } @Override public JWTPayload jwtPayloadFromJWT(String jwtToken) { if (!JWT_PATTERN.matcher(jwtToken).matches()) { throw new IllegalArgumentException("Malformed JWT: " + jwtToken); } final var splintedTokens = jwtToken.split("\\."); if (!splintedTokens[0].equals(JWT_HEADER)) { throw new IllegalArgumentException("Malformed JWT! Token must starts with header: " + JWT_HEADER); }
final var signatureBytes = HmacSHA256.sign(secret, splintedTokens[0].concat(".").concat(splintedTokens[1])); if (!base64URLFromBytes(signatureBytes).equals(splintedTokens[2])) { throw new IllegalArgumentException("Token has invalid signature: " + jwtToken); } try { final var decodedPayload = stringFromBase64URL(splintedTokens[1]); final var jwtPayload = objectMapper.readValue(decodedPayload, UserJWTPayload.class); if (jwtPayload.isExpired()) { throw new IllegalArgumentException("Token expired"); } return jwtPayload; } catch (Exception exception) { throw new IllegalArgumentException(exception); } } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\infrastructure\jwt\HmacSHA256JWTService.java
1
请完成以下Java代码
public SqlAndParamsExpression build() { return new SqlAndParamsExpression(this); } public Builder appendIfNotEmpty(@Nullable final String sqlToAppend) { if (sqlToAppend != null) { sql.appendIfNotEmpty(sqlToAppend); } return this; } public Builder append(@NonNull final String sqlToAppend, final Object... sqlParamsToAppend) { sql.append(sqlToAppend); sqlParams.addAll(Arrays.asList(sqlParamsToAppend)); return this; } public Builder append(@Nullable final SqlAndParams sqlAndParams) { if (sqlAndParams != null) { sql.append(sqlAndParams.getSql()); sqlParams.addAll(sqlAndParams.getSqlParams()); } return this; } public Builder append(@NonNull final SqlAndParamsExpression sqlToAppend) { sql.append(sqlToAppend.getSql()); sqlParams.addAll(sqlToAppend.getSqlParams()); return this; } public Builder append(@NonNull final SqlAndParamsExpression.Builder sqlToAppend) { sql.append(sqlToAppend.sql); sqlParams.addAll(sqlToAppend.sqlParams); return this; } public Builder append(@NonNull final IStringExpression sqlToAppend) { sql.append(sqlToAppend); return this; } public Builder append(@Nullable final String sqlToAppend) {
if (sqlToAppend != null) { sql.append(sqlToAppend); } return this; } public Builder appendSqlList(@NonNull final String sqlColumnName, @NonNull final Collection<?> values) { final String sqlToAppend = DB.buildSqlList(sqlColumnName, values, sqlParams); sql.append(sqlToAppend); return this; } public boolean isEmpty() { return sql.isEmpty() && sqlParams.isEmpty(); } public Builder wrap(@NonNull final IStringExpressionWrapper wrapper) { sql.wrap(wrapper); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParamsExpression.java
1
请在Spring Boot框架中完成以下Java代码
public void setId(String _id) { this._id = _id; } public Region label(String label) { this.label = label; return this; } /** * Get label * @return label **/ @Schema(example = "Nordost", description = "") public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Region parent(String parent) { this.parent = parent; return this; } /** * Id der übergeordneten Region * @return parent **/ @Schema(example = "5afc1d30b37364c26e9ca501", description = "Id der übergeordneten Region") public String getParent() { return parent; } public void setParent(String parent) { this.parent = parent; } public Region timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Region region = (Region) o; return Objects.equals(this._id, region._id) && Objects.equals(this.label, region.label) && Objects.equals(this.parent, region.parent) && Objects.equals(this.timestamp, region.timestamp); } @Override public int hashCode() { return Objects.hash(_id, label, parent, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Region {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" label: ").append(toIndentedString(label)).append("\n"); sb.append(" parent: ").append(toIndentedString(parent)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Region.java
2
请完成以下Java代码
public class DLM_Partition_Create_Async extends AbstractDLM_Partition_Create { private final IDLMService dlmService = Services.get(IDLMService.class); @Param(mandatory = true, parameterName = I_DLM_Partition_Config.COLUMNNAME_DLM_Partition_Config_ID) private I_DLM_Partition_Config configDB; /** * How many async workpackages do we want? * Mandatory because we want to user to make a conscious decision about how long the async work shall run. */ @Param(mandatory = true, parameterName = "Count") private int count; /** * After which time shall the async-work stop? * Mandatory because we want to user to make a conscious decision about how long the async work shall run. */ @Param(mandatory = true, parameterName = "DontReEnqueueAfter") private Timestamp dontReEnqueueAfter; @Param(mandatory = true, parameterName = "DLMOldestFirst") private boolean oldestFirst; @Param(mandatory = false, parameterName = "AD_Table_ID") private I_AD_Table adTable; @Param(mandatory = false, parameterName = "Record_ID") private int recordId; @Override protected String doIt() throws Exception { ITableRecordReference recordToAttach = null; if (adTable != null && recordId > 0) {
recordToAttach = TableRecordReference.of(adTable.getAD_Table_ID(), recordId); } final PartitionConfig config = dlmService.loadPartitionConfig(configDB); final CreatePartitionAsyncRequest request = PartitionRequestFactory.asyncBuilder() .setConfig(config) .setOldestFirst(oldestFirst) .setRecordToAttach(recordToAttach) .setPartitionToComplete(getPartitionToCompleteOrNull()) .setOnNotDLMTable(OnNotDLMTable.FAIL) // the processing will run unattended. See the javadoc of ADD_TO_DLM on why it's not an option. .setCount(count) .setDontReEnqueueAfter(dontReEnqueueAfter) .build(); final I_C_Queue_WorkPackage newWorkpackage = DLMPartitionerWorkpackageProcessor.schedule(request, getPinstanceId()); addLog("Scheduled " + newWorkpackage); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_Partition_Create_Async.java
1
请在Spring Boot框架中完成以下Java代码
public class NewRelicProperties extends StepRegistryProperties { /** * Whether to send the meter name as the event type instead of using the 'event-type' * configuration property value. Can be set to 'true' if New Relic guidelines are not * being followed or event types consistent with previous Spring Boot releases are * required. */ private boolean meterNameEventTypeEnabled; /** * The event type that should be published. This property will be ignored if * 'meter-name-event-type-enabled' is set to 'true'. */ private String eventType = "SpringBootSample"; /** * Client provider type to use. */ private ClientProviderType clientProviderType = ClientProviderType.INSIGHTS_API; /** * New Relic API key. */ private @Nullable String apiKey; /** * New Relic account ID. */ private @Nullable String accountId; /** * URI to ship metrics to. */ private String uri = "https://insights-collector.newrelic.com"; public boolean isMeterNameEventTypeEnabled() { return this.meterNameEventTypeEnabled; } public void setMeterNameEventTypeEnabled(boolean meterNameEventTypeEnabled) { this.meterNameEventTypeEnabled = meterNameEventTypeEnabled; }
public String getEventType() { return this.eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public ClientProviderType getClientProviderType() { return this.clientProviderType; } public void setClientProviderType(ClientProviderType clientProviderType) { this.clientProviderType = clientProviderType; } public @Nullable String getApiKey() { return this.apiKey; } public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; } public @Nullable String getAccountId() { return this.accountId; } public void setAccountId(@Nullable String accountId) { this.accountId = accountId; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicProperties.java
2
请完成以下Java代码
public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystem_Config_ProCareManagement_ID (final int ExternalSystem_Config_ProCareManagement_ID) { if (ExternalSystem_Config_ProCareManagement_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID, ExternalSystem_Config_ProCareManagement_ID); } @Override public int getExternalSystem_Config_ProCareManagement_ID() {
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ProCareManagement_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ProCareManagement.java
1
请完成以下Java代码
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { invoiceLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return invoiceLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { invoiceLine.setC_UOM_ID(uomId); } @Override public void setQty(@NonNull final BigDecimal qtyInHUsUOM) { invoiceLine.setQtyEntered(qtyInHUsUOM); final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID()); final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID()); final BigDecimal qtyInvoiced = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qtyInHUsUOM); invoiceLine.setQtyInvoiced(qtyInvoiced); } @Override public BigDecimal getQty() { return invoiceLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { // // Check the invoice line first final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID(); if (invoiceLine_PIItemProductId > 0) { return invoiceLine_PIItemProductId; } // // Check order line final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class); if (orderline == null) { // // C_OrderLine not found (i.e Manual Invoice) return -1; } return orderline.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
} @Override public BigDecimal getQtyTU() { return invoiceLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { invoiceLine.setQtyEnteredTU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
1
请完成以下Java代码
public void setText (String text) { m_text.setText (text); validateOnTextChanged(); } // setText /** * Get Text (clear) * @return text */ public String getText () { String text = m_text.getText(); return text; } // getText /** * Focus Gained. * Enabled with Obscure * @param e event */ public void focusGained (FocusEvent e) { m_infocus = true; setText(getText()); // clear } // focusGained /** * Focus Lost * Enabled with Obscure * @param e event */
public void focusLost (FocusEvent e) { m_infocus = false; setText(getText()); // obscure } // focus Lost // metas @Override public boolean isAutoCommit() { return true; } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VURL
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java
1
请完成以下Java代码
public <R> R forProcessInstanceWritable(final DocumentId pinstanceId, final IDocumentChangesCollector changesCollector, final Function<IProcessInstanceController, R> processor) { final ViewActionInstance actionInstance = getActionInstance(pinstanceId); // Make sure the process was not already executed. // If it was executed we are not allowed to change it. actionInstance.assertNotExecuted(); return processor.apply(actionInstance); } @Override public void cacheReset() { viewActionInstancesByViewId.reset(); } @ToString private static final class ViewActionInstancesList { private final String viewId; private final AtomicInteger nextIdSupplier = new AtomicInteger(1); private final ConcurrentHashMap<DocumentId, ViewActionInstance> instances = new ConcurrentHashMap<>(); public ViewActionInstancesList(@NonNull final String viewId) { this.viewId = viewId; } public ViewActionInstance getByInstanceId(final DocumentId pinstanceId) { final ViewActionInstance actionInstance = instances.get(pinstanceId); if (actionInstance == null)
{ throw new EntityNotFoundException("No view action instance found for " + pinstanceId); } return actionInstance; } private DocumentId nextPInstanceId() { final int nextId = nextIdSupplier.incrementAndGet(); return DocumentId.ofString(viewId + "_" + nextId); } public static String extractViewId(@NonNull final DocumentId pinstanceId) { final String pinstanceIdStr = pinstanceId.toJson(); final int idx = pinstanceIdStr.indexOf("_"); return pinstanceIdStr.substring(0, idx); } public void add(final ViewActionInstance viewActionInstance) { instances.put(viewActionInstance.getInstanceId(), viewActionInstance); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewProcessInstancesRepository.java
1
请完成以下Java代码
public static SecuritySignResp sign(SecuritySignReq req) { SecretKey secretKey = SecureUtil.generateKey(ALGORITHM); byte[] key= secretKey.getEncoded(); String prikey=req.getPrikey(); String data=req.getData(); AES aes = SecureUtil.aes(key); aes.getSecretKey().getEncoded(); String encrptData =aes.encryptBase64(data); RSA rsa=new RSA(prikey,null); byte[] encryptAesKey = rsa.encrypt(secretKey.getEncoded(), KeyType.PrivateKey); //log.info(("rsa加密过的秘钥=="+Base64Encoder.encode(encryptAesKey)); Sign sign= new Sign(SignAlgorithm.SHA1withRSA,prikey,null); byte[] signed = sign.sign(data.getBytes()); //log.info(("签名数据===》》"+Base64Encoder.encode(signed)); SecuritySignResp resp=new SecuritySignResp();
resp.setAesKey(Base64Encoder.encode(encryptAesKey)); resp.setData(encrptData); resp.setSignData(Base64Encoder.encode(signed)); return resp; } public static MyKeyPair generateKeyPair(){ KeyPair keyPair= SecureUtil.generateKeyPair(SignAlgorithm.SHA1withRSA.getValue(),2048); String priKey= Base64Encoder.encode(keyPair.getPrivate().getEncoded()); String pubkey= Base64Encoder.encode(keyPair.getPublic().getEncoded()); MyKeyPair resp=new MyKeyPair(); resp.setPriKey(priKey); resp.setPubKey(pubkey); return resp; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\SecurityTools.java
1
请在Spring Boot框架中完成以下Java代码
public List<TimerJobEntity> findTimerJobsByProcessInstanceId(String processInstanceId) { return getTimerJobEntityManager().findJobsByProcessInstanceId(processInstanceId); } @Override public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionId(String type, String processDefinitionId) { return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionId(type, processDefinitionId); } @Override public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyNoTenantId(String type, String processDefinitionKey) { return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyNoTenantId(type, processDefinitionKey); } @Override public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyAndTenantId(String type, String processDefinitionKey, String tenantId) { return getTimerJobEntityManager().findJobsByTypeAndProcessDefinitionKeyAndTenantId(type, processDefinitionKey, tenantId); } @Override public void scheduleTimerJob(TimerJobEntity timerJob) { getJobManager().scheduleTimerJob(timerJob); } @Override public AbstractRuntimeJobEntity moveJobToTimerJob(JobEntity job) { return getJobManager().moveJobToTimerJob(job); } @Override
public TimerJobEntity createTimerJob() { return getTimerJobEntityManager().create(); } @Override public void insertTimerJob(TimerJobEntity timerJob) { getTimerJobEntityManager().insert(timerJob); } @Override public void deleteTimerJob(TimerJobEntity timerJob) { getTimerJobEntityManager().delete(timerJob); } @Override public void deleteTimerJobsByExecutionId(String executionId) { TimerJobEntityManager timerJobEntityManager = getTimerJobEntityManager(); Collection<TimerJobEntity> timerJobsForExecution = timerJobEntityManager.findJobsByExecutionId(executionId); for (TimerJobEntity job : timerJobsForExecution) { timerJobEntityManager.delete(job); if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent( FlowableEngineEventType.JOB_CANCELED, job), configuration.getEngineName()); } } } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\TimerJobServiceImpl.java
2
请完成以下Java代码
public static HistoricDecisionInstanceDto fromHistoricDecisionInstance(HistoricDecisionInstance historicDecisionInstance) { HistoricDecisionInstanceDto dto = new HistoricDecisionInstanceDto(); dto.id = historicDecisionInstance.getId(); dto.decisionDefinitionId = historicDecisionInstance.getDecisionDefinitionId(); dto.decisionDefinitionKey = historicDecisionInstance.getDecisionDefinitionKey(); dto.decisionDefinitionName = historicDecisionInstance.getDecisionDefinitionName(); dto.evaluationTime = historicDecisionInstance.getEvaluationTime(); dto.removalTime = historicDecisionInstance.getRemovalTime(); dto.processDefinitionId = historicDecisionInstance.getProcessDefinitionId(); dto.processDefinitionKey = historicDecisionInstance.getProcessDefinitionKey(); dto.processInstanceId = historicDecisionInstance.getProcessInstanceId(); dto.caseDefinitionId = historicDecisionInstance.getCaseDefinitionId(); dto.caseDefinitionKey = historicDecisionInstance.getCaseDefinitionKey(); dto.caseInstanceId = historicDecisionInstance.getCaseInstanceId(); dto.activityId = historicDecisionInstance.getActivityId(); dto.activityInstanceId = historicDecisionInstance.getActivityInstanceId(); dto.userId = historicDecisionInstance.getUserId(); dto.collectResultValue = historicDecisionInstance.getCollectResultValue(); dto.rootDecisionInstanceId = historicDecisionInstance.getRootDecisionInstanceId(); dto.rootProcessInstanceId = historicDecisionInstance.getRootProcessInstanceId(); dto.decisionRequirementsDefinitionId = historicDecisionInstance.getDecisionRequirementsDefinitionId(); dto.decisionRequirementsDefinitionKey = historicDecisionInstance.getDecisionRequirementsDefinitionKey(); dto.tenantId = historicDecisionInstance.getTenantId(); try { List<HistoricDecisionInputInstanceDto> inputs = new ArrayList<HistoricDecisionInputInstanceDto>();
for (HistoricDecisionInputInstance input : historicDecisionInstance.getInputs()) { HistoricDecisionInputInstanceDto inputDto = HistoricDecisionInputInstanceDto.fromHistoricDecisionInputInstance(input); inputs.add(inputDto); } dto.inputs = inputs; } catch (ProcessEngineException e) { // no inputs fetched } try { List<HistoricDecisionOutputInstanceDto> outputs = new ArrayList<HistoricDecisionOutputInstanceDto>(); for (HistoricDecisionOutputInstance output : historicDecisionInstance.getOutputs()) { HistoricDecisionOutputInstanceDto outputDto = HistoricDecisionOutputInstanceDto.fromHistoricDecisionOutputInstance(output); outputs.add(outputDto); } dto.outputs = outputs; } catch (ProcessEngineException e) { // no outputs fetched } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionInstanceDto.java
1
请完成以下Java代码
protected void prepare() { final ProcessInfoParameter[] parameters = this.getParametersAsArray(); for (final ProcessInfoParameter p : parameters) { if (p.getParameterName().equals("CalendarYear")) { year = p.getParameter().toString(); return; } } year = SystemTime.asZonedDateTime().getYear() + ""; } @Override protected String doIt() throws Exception { PreparedStatement insertStmt = null; try { insertStmt = DB .prepareStatement( "INSERT INTO AD_Sequence_No(AD_SEQUENCE_ID, CALENDARYEAR,CALENDARMONTH,CALENDARDAY, " + "AD_CLIENT_ID, AD_ORG_ID, ISACTIVE, CREATED, CREATEDBY, " + "UPDATED, UPDATEDBY, CURRENTNEXT) " + "(SELECT AD_Sequence_ID, ?, ?, ?, " + "AD_Client_ID, AD_Org_ID, IsActive, Created, CreatedBy, " + "Updated, UpdatedBy, StartNo " + "FROM AD_Sequence a " + "WHERE RestartFrequency IS NOT NULL AND NOT EXISTS ( " + "SELECT AD_Sequence_ID " + "FROM AD_Sequence_No b " + "WHERE a.AD_Sequence_ID = b.AD_Sequence_ID " + " AND CalendarYear = ?" + " AND CalendarMonth = ?" + " AND CalendarDay = ?)) ", get_TrxName()); insertStmt.setString(1, year); insertStmt.setString(4, year); final Year selectedYear = Year.of(Integer.parseInt(year)); for (int month = 1; month <= 12; month++)
{ final String monthAsString = month + ""; final int days = selectedYear.atMonth(month).lengthOfMonth(); for (int day = 1; day <= days; day++) { final String dayAsString = day + ""; insertStmt.setString(2, monthAsString); insertStmt.setString(3, dayAsString); insertStmt.setString(5, monthAsString); insertStmt.setString(6, dayAsString); insertStmt.executeUpdate(); } } } finally { DB.close(insertStmt); } return "Sequence No updated successfully"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\UpdateSequenceNo.java
1
请在Spring Boot框架中完成以下Java代码
public class PostgresqlPubSubExample { private static final Logger log = LoggerFactory.getLogger(PostgresqlPubSubExample.class); private final Map<String,BigDecimal> orderSummary = new HashMap<>(); private final ObjectMapper om = new ObjectMapper(); private final Semaphore orderSemaphore = new Semaphore(0); @MessagingGateway public interface OrdersGateway { @Gateway(requestChannel = "orders") void publish(Order order); } @Bean static SubscribableChannel orders(@Value("${db.url}") String url,@Value("${db.username}") String username, @Value("${db.password}")String password) { // Connection supplier SingleConnectionDataSource ds = new SingleConnectionDataSource(url, username, password, true); Supplier<Connection> connectionSupplier = () -> { try { return ds.getConnection(); } catch(SQLException ex) { throw new RuntimeException(ex); } }; // DataSource PGSimpleDataSource pgds = new PGSimpleDataSource(); pgds.setUrl(url); pgds.setUser(username); pgds.setPassword(password); return new PostgresSubscribableChannel("orders", connectionSupplier, pgds, new ObjectMapper()); } @Transformer(inputChannel = "orders" , outputChannel = "orderProcessor" ) Order validatedOrders(Message<?> orderMessage) throws JsonProcessingException { ObjectNode on = (ObjectNode) orderMessage.getPayload(); Order order = om.treeToValue(on, Order.class); return order; } @ServiceActivator(inputChannel = "orderProcessor") void processOrder(Order order){ log.info("Processing order: id={}, symbol={}, qty={}, price={}", order.getId(), order.getSymbol(),
order.getQuantity(), order.getPrice()); BigDecimal orderTotal = order.getQuantity().multiply(order.getPrice()); if ( order.getOrderType() == OrderType.SELL) { orderTotal = orderTotal.negate(); } BigDecimal sum = orderSummary.get(order.getSymbol()); if ( sum == null) { sum = orderTotal; } else { sum = sum.add(orderTotal); } orderSummary.put(order.getSymbol(), sum); orderSemaphore.release(); } public BigDecimal getTotalBySymbol(String symbol) { return orderSummary.get(symbol); } public boolean awaitNextMessage(long time, TimeUnit unit) throws InterruptedException { return orderSemaphore.tryAcquire(time, unit); } }
repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\postgresqlnotify\PostgresqlPubSubExample.java
2
请完成以下Java代码
public void setId(long id) { this.id = id; } @Column(name = "first_name", nullable = false) public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column(name = "last_name", nullable = false) public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name = "email_address", nullable = false) public String getEmailId() { return emailId;
} public void setEmailId(String emailId) { this.emailId = emailId; } @Column(name = "passport_number", nullable = false) public String getPassportNumber() { return passportNumber; } public void setPassportNumber(String passportNumber) { this.passportNumber = passportNumber; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-crud-rest-api-validation\src\main\java\net\alanbinu\springboot\springbootcrudrestapivalidation\model\Employee.java
1
请完成以下Java代码
private static List<String> getAquiredConnectionInfos(final AbstractPoolBackedDataSource poolBackedDataSource) throws SQLException { final C3P0PooledConnectionPoolManager poolManager = AbstractPoolBackedDataSource_MetashfreshObserver.getPoolManager(poolBackedDataSource); final C3P0PooledConnectionPool pool = poolManager.getPool(); final ResourcePool resourcePool = C3P0PooledConnectionPool_MetasfreshObserver.getResourcePool(pool); final BasicResourcePool basicResourcePool = BasicResourcePool.class.cast(resourcePool); return getAquiredConnectionInfos(basicResourcePool); } private List<String> getAquiredConnectionInfos(@NonNull final BasicResourcePool pool) { synchronized (pool) { final ArrayList<String> result = new ArrayList<>(); @SuppressWarnings("unchecked") final Map<Object, PunchCard> managed = new HashMap<>(pool.managed); @SuppressWarnings("unchecked") final List<Object> unused = new ArrayList<>(pool.unused); for (final Map.Entry<Object, PunchCard> e : managed.entrySet()) { final Object resource = e.getKey(); if (unused.contains(resource)) { continue; } final PunchCard punchCard = e.getValue();
result.add(toInfoString(punchCard)); } return result; } } private static String toInfoString(final PunchCard connectionPunchCard) { final StringBuilder info = new StringBuilder(); final Instant checkoutTime = Instant.ofEpochMilli(connectionPunchCard.checkout_time); info.append("checkout=").append(checkoutTime); // final Instant acquisitionTime = Instant.ofEpochMilli(connectionPunchCard.acquisition_time); // info.append(", acquired=").append(acquisitionTime); final Exception checkoutStackTraceException = connectionPunchCard.checkoutStackTraceException; if (checkoutStackTraceException != null) { final String stackTraceString = Trace.toOneLineStackTraceString(checkoutStackTraceException.getStackTrace()); info.append(", stacktrace=").append(stackTraceString); } return info.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\com\mchange\v2\resourcepool\BasicResourcePool_MetasfreshObserver.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getUser() { return this.user; } public void setUser(@Nullable String user) { this.user = user; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } public Embedded getEmbedded() { return this.embedded; } public Duration getCloseTimeout() { return this.closeTimeout; } public void setCloseTimeout(Duration closeTimeout) { this.closeTimeout = closeTimeout; } public boolean isNonBlockingRedelivery() { return this.nonBlockingRedelivery; } public void setNonBlockingRedelivery(boolean nonBlockingRedelivery) { this.nonBlockingRedelivery = nonBlockingRedelivery; } public Duration getSendTimeout() { return this.sendTimeout; } public void setSendTimeout(Duration sendTimeout) { this.sendTimeout = sendTimeout; } public JmsPoolConnectionFactoryProperties getPool() { return this.pool; } public Packages getPackages() { return this.packages; } String determineBrokerUrl() { if (this.brokerUrl != null) { return this.brokerUrl; } if (this.embedded.isEnabled()) { return DEFAULT_EMBEDDED_BROKER_URL; } return DEFAULT_NETWORK_BROKER_URL; } /** * Configuration for an embedded ActiveMQ broker. */ public static class Embedded { /** * Whether to enable embedded mode if the ActiveMQ Broker is available. */ private boolean enabled = true;
public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } public static class Packages { /** * Whether to trust all packages. */ private @Nullable Boolean trustAll; /** * List of specific packages to trust (when not trusting all packages). */ private List<String> trusted = new ArrayList<>(); public @Nullable Boolean getTrustAll() { return this.trustAll; } public void setTrustAll(@Nullable Boolean trustAll) { this.trustAll = trustAll; } public List<String> getTrusted() { return this.trusted; } public void setTrusted(List<String> trusted) { this.trusted = trusted; } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java
2
请完成以下Java代码
private void assertNotBuilt() { if (_built != null) { throw new AdempiereException("Filters were already built"); } } private CompositeSqlLookupFilter build() { final IValidationRuleFactory validationRuleFactory = Services.get(IValidationRuleFactory.class); final ArrayList<SqlLookupFilter> filters = new ArrayList<>(); for (LookupDescriptorProvider.LookupScope scope : adValRuleIdByScope.keySet()) { final AdValRuleId adValRuleId = adValRuleIdByScope.get(scope); if (adValRuleId != null) { final IValidationRule valRule = validationRuleFactory.create(lookupTableName.getAsString(), adValRuleId, ctxTableName, ctxColumnName); for (final IValidationRule childValRule : CompositeValidationRule.unbox(valRule)) { filters.add(SqlLookupFilter.of(childValRule, scope)); } } } // // Case: DocAction button => inject the DocActionValidationRule // FIXME: hardcoded if (displayType == DisplayType.Button && WindowConstants.FIELDNAME_DocAction.equals(ctxColumnName)) { filters.add(SqlLookupFilter.of(DocActionValidationRule.instance, LookupDescriptorProvider.LookupScope.DocumentField)); } // // Additional validation rules registered filters.addAll(this.filters); return CompositeSqlLookupFilter.ofFilters(filters); } public void setAdValRuleId(@NonNull final LookupDescriptorProvider.LookupScope lookupScope, @Nullable final AdValRuleId adValRuleId) { if (adValRuleId != null) { adValRuleIdByScope.put(lookupScope, adValRuleId); } else { adValRuleIdByScope.remove(lookupScope); } } public void setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds) { adValRuleIdByScope.clear(); adValRuleIdByScope.putAll(adValRuleIds); } public void setLookupTableName(final TableName lookupTableName) { assertNotBuilt(); this.lookupTableName = lookupTableName; } public void setCtxTableName(final String ctxTableName) { assertNotBuilt(); this.ctxTableName = ctxTableName; }
public void setCtxColumnName(final String ctxColumnName) { assertNotBuilt(); this.ctxColumnName = ctxColumnName; } public void setDisplayType(final int displayType) { assertNotBuilt(); this.displayType = displayType; } public void addFilter(@NonNull final Collection<IValidationRule> validationRules, @Nullable LookupDescriptorProvider.LookupScope scope) { for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRules)) { addFilter(SqlLookupFilter.of(valRule, scope)); } } public void addFilter(@Nullable final IValidationRule validationRule, @Nullable LookupDescriptorProvider.LookupScope scope) { for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRule)) { addFilter(SqlLookupFilter.of(valRule, scope)); } } private void addFilter(@NonNull final SqlLookupFilter filter) { assertNotBuilt(); filters.add(filter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilterBuilder.java
1
请完成以下Java代码
public class ProductBean { String id; String name; String price; public ProductBean(String id, String name, String price) { super(); this.id = id; this.name = name; this.price = price; } public String getId() { return id; } @Field("id") protected void setId(String id) { this.id = id; } public String getName() {
return name; } @Field("name") protected void setName(String name) { this.name = name; } public String getPrice() { return price; } @Field("price") protected void setPrice(String price) { this.price = price; } }
repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\apache\solrjava\ProductBean.java
1
请完成以下Java代码
private Map<TableRecordReference, I_C_Order> getSalesOrdersRecordRef(@NonNull final List<I_C_Order> salesOrders) { return salesOrders .stream() .collect(ImmutableMap.toImmutableMap(order -> TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID()), Function.identity())); } @NonNull private ImmutableSet<TableRecordReference> getSalesOrderPartnersRecordRef(@NonNull final List<I_C_Order> salesOrders) { return salesOrders .stream() .map(order -> TableRecordReference.of(I_C_BPartner.Table_Name, order.getC_BPartner_ID())) .collect(ImmutableSet.toImmutableSet()); }
@NonNull private Optional<Map<TableRecordReference, I_Alberta_PrescriptionRequest>> getAlbertaPrescriptionsRecordRefs(@NonNull final Set<OrderId> salesOrderIds) { if (salesOrderIds.isEmpty()) { return Optional.empty(); } return Optional.of(albertaPrescriptionRequestDAO.getByOrderIds(salesOrderIds) .stream() .collect(ImmutableMap.toImmutableMap(prescription -> TableRecordReference.of(I_Alberta_PrescriptionRequest.Table_Name, prescription.getAlberta_PrescriptionRequest_ID()), Function.identity()))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentRowsLoader.java
1
请在Spring Boot框架中完成以下Java代码
public void applyTo(GenerationContext generationContext, BeanFactoryInitializationCode beanFactoryInitializationCode) { RuntimeHints runtimeHints = generationContext.getRuntimeHints(); for (String locationSuffix : locationSuffixes) { String path = locationPrefix + locationSuffix; try { for (Resource resource : resolver.getResources(path)) { ClassPathResource classPathResource = asClasspathResource(resource); if (classPathResource != null && classPathResource.exists()) { logger.debug("Registering hints for {}", classPathResource); applyToResource(classPathResource, runtimeHints); } } } catch (IOException e) { throw new UncheckedIOException("Failed to find resources for " + path, e); } } } protected void applyToResource(ClassPathResource resource, RuntimeHints hints) { hints.resources().registerResource(resource); } protected ClassPathResource asClasspathResource(Resource resource) { if (resource instanceof ClassPathResource) { return (ClassPathResource) resource; } try {
logger.debug("Transforming {} to a classpath resource", resource); String marker = "jar!"; String externalFormOfUrl = resource.getURL().toExternalForm(); if (externalFormOfUrl.contains(marker)) { String rest = externalFormOfUrl.substring(externalFormOfUrl.lastIndexOf(marker) + marker.length()); return new ClassPathResource(rest); } else { // ugh i think this only works for maven? what about gradle? var classesSubstring = "classes/"; var locationOfClassesInUrl = externalFormOfUrl.indexOf(classesSubstring); if (locationOfClassesInUrl != -1) { return new ClassPathResource(externalFormOfUrl.substring(locationOfClassesInUrl + classesSubstring.length())); } } logger.error("Could not resolve {} as a classpath resource", resource); return null; } catch (IOException e) { throw new RuntimeException(e); } } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\aot\BaseAutoDeployResourceContribution.java
2
请完成以下Java代码
public static Access ofCode(@NonNull final String code) { final Access access = accessesByCode.get(code); if (access == null) { throw new AdempiereException("No Access found for code: " + code); } return access; } public static Set<Access> values() { return ALL_ACCESSES; } @NonNull String name; @NonNull String code; private Access(@NonNull final String name, final @NotNull String code) { Check.assumeNotEmpty(name, "name not empty"); this.name = name; this.code = code; } @Override public String toString() { return getName(); } @Override @JsonValue
public @NotNull String getCode() { return code; } public boolean isReadOnly() { return READ.equals(this); } public boolean isReadWrite() { return WRITE.equals(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\Access.java
1
请在Spring Boot框架中完成以下Java代码
private static final class BootstrapExecutorCondition extends AnyNestedCondition { BootstrapExecutorCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "deferred") static class DeferredBootstrapMode { } @ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "lazy") static class LazyBootstrapMode { } }
static class JpaRepositoriesImportSelector implements ImportSelector { private static final boolean ENVERS_AVAILABLE = ClassUtils.isPresent( "org.springframework.data.envers.repository.config.EnableEnversRepositories", JpaRepositoriesImportSelector.class.getClassLoader()); @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[] { determineImport() }; } private String determineImport() { return ENVERS_AVAILABLE ? EnversRevisionRepositoriesRegistrar.class.getName() : DataJpaRepositoriesRegistrar.class.getName(); } } }
repos\spring-boot-4.0.1\module\spring-boot-data-jpa\src\main\java\org\springframework\boot\data\jpa\autoconfigure\DataJpaRepositoriesAutoConfiguration.java
2
请完成以下Java代码
public void staleRootDocument(final WindowId windowId, final DocumentId documentId) { staleRootDocument(windowId, documentId, false); } public void staleRootDocument(final WindowId windowId, final DocumentId documentId, final boolean markActiveTabStaled) { forCollector(collector -> collector.staleRootDocument(windowId, documentId, markActiveTabStaled)); } public void staleTabs(final WindowId windowId, final DocumentId documentId, final Set<DetailId> tabIds) { forCollector(collector -> collector.staleTabs(windowId, documentId, tabIds)); } public void staleIncludedDocuments(final WindowId windowId, final DocumentId documentId, final DetailId tabId, final DocumentIdsSelection rowIds) { forCollector(collector -> collector.staleIncludedDocuments(windowId, documentId, tabId, rowIds)); } public void convertAndPublish(final List<JSONDocument> jsonDocumentEvents) { if (jsonDocumentEvents == null || jsonDocumentEvents.isEmpty()) { return; } final JSONDocumentChangedWebSocketEventCollector collectorToMerge = JSONDocumentChangedWebSocketEventCollector.newInstance(); for (final JSONDocument jsonDocumentEvent : jsonDocumentEvents) { collectFrom(collectorToMerge, jsonDocumentEvent); } if (collectorToMerge.isEmpty()) { return; } forCollector(collector -> collector.mergeFrom(collectorToMerge)); } private static void collectFrom(final JSONDocumentChangedWebSocketEventCollector collector, final JSONDocument event) { final WindowId windowId = event.getWindowId(); if (windowId == null) { return; } // Included document => nothing to publish about it if (event.getTabId() != null) { return; } final DocumentId documentId = event.getId(); collector.staleRootDocument(windowId, documentId); event.getIncludedTabsInfos().forEach(tabInfo -> collector.mergeFrom(windowId, documentId, tabInfo)); } public CloseableCollector temporaryCollectOnThisThread() { final CloseableCollector closeableCollector = new CloseableCollector(); closeableCollector.open(); return closeableCollector; } public class CloseableCollector implements IAutoCloseable {
@NonNull private final JSONDocumentChangedWebSocketEventCollector collector = JSONDocumentChangedWebSocketEventCollector.newInstance(); @NonNull private final AtomicBoolean closed = new AtomicBoolean(false); @Override public String toString() { return "CloseableCollector[" + collector + "]"; } private void open() { if (THREAD_LOCAL_COLLECTOR.get() != null) { throw new AdempiereException("A thread level collector was already set"); } THREAD_LOCAL_COLLECTOR.set(collector); } @Override public void close() { if (closed.getAndSet(true)) { return; // already closed } THREAD_LOCAL_COLLECTOR.set(null); sendAllAndClose(collector, websocketSender); } @VisibleForTesting ImmutableList<JSONDocumentChangedWebSocketEvent> getEvents() {return collector.getEvents();} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\DocumentWebsocketPublisher.java
1
请完成以下Java代码
public void setErrorVariableName(String errorVariableName) { this.errorVariableName = errorVariableName; } public Boolean getErrorVariableTransient() { return errorVariableTransient; } public void setErrorVariableTransient(Boolean errorVariableTransient) { this.errorVariableTransient = errorVariableTransient; } public Boolean getErrorVariableLocalScope() { return errorVariableLocalScope; } public void setErrorVariableLocalScope(Boolean errorVariableLocalScope) {
this.errorVariableLocalScope = errorVariableLocalScope; } @Override public ErrorEventDefinition clone() { ErrorEventDefinition clone = new ErrorEventDefinition(); clone.setValues(this); return clone; } public void setValues(ErrorEventDefinition otherDefinition) { super.setValues(otherDefinition); setErrorCode(otherDefinition.getErrorCode()); setErrorVariableName(otherDefinition.getErrorVariableName()); setErrorVariableLocalScope(otherDefinition.getErrorVariableLocalScope()); setErrorVariableTransient(otherDefinition.getErrorVariableTransient()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ErrorEventDefinition.java
1
请完成以下Java代码
public I_C_ValidCombination getV_Prepayment_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getV_Prepayment_Acct(), get_TrxName()); } /** Set Vendor Prepayment. @param V_Prepayment_Acct Account for Vendor Prepayments */ public void setV_Prepayment_Acct (int V_Prepayment_Acct) { set_Value (COLUMNNAME_V_Prepayment_Acct, Integer.valueOf(V_Prepayment_Acct)); } /** Get Vendor Prepayment. @return Account for Vendor Prepayments */ public int getV_Prepayment_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_V_Prepayment_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getWriteOff_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getWriteOff_Acct(), get_TrxName()); } /** Set Write-off. @param WriteOff_Acct Account for Receivables write-off
*/ public void setWriteOff_Acct (int WriteOff_Acct) { set_Value (COLUMNNAME_WriteOff_Acct, Integer.valueOf(WriteOff_Acct)); } /** Get Write-off. @return Account for Receivables write-off */ public int getWriteOff_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_WriteOff_Acct); 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_C_BP_Group_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public LegacyReference getLegacyReference() { return legacyReference; } public void setLegacyReference(LegacyReference legacyReference) { this.legacyReference = legacyReference; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RefundItem refundItem = (RefundItem)o; return Objects.equals(this.refundAmount, refundItem.refundAmount) && Objects.equals(this.lineItemId, refundItem.lineItemId) && Objects.equals(this.legacyReference, refundItem.legacyReference); } @Override public int hashCode() { return Objects.hash(refundAmount, lineItemId, legacyReference); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RefundItem {\n"); sb.append(" refundAmount: ").append(toIndentedString(refundAmount)).append("\n");
sb.append(" lineItemId: ").append(toIndentedString(lineItemId)).append("\n"); sb.append(" legacyReference: ").append(toIndentedString(legacyReference)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\RefundItem.java
2
请完成以下Java代码
public com.baeldung.schema.EmployeeKey.Builder setId(int value) { validate(fields()[0], value); this.id = value; fieldSetFlags()[0] = true; return this; } /** * Checks whether the 'id' field has been set. * @return True if the 'id' field has been set, false otherwise. */ public boolean hasId() { return fieldSetFlags()[0]; } /** * Clears the value of the 'id' field. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder clearId() { fieldSetFlags()[0] = false; return this; } /** * Gets the value of the 'departmentName' field. * @return The value. */ public java.lang.CharSequence getDepartmentName() { return departmentName; } /** * Sets the value of the 'departmentName' field. * @param value The value of 'departmentName'. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder setDepartmentName(java.lang.CharSequence value) { validate(fields()[1], value); this.departmentName = value; fieldSetFlags()[1] = true; return this; } /** * Checks whether the 'departmentName' field has been set. * @return True if the 'departmentName' field has been set, false otherwise. */ public boolean hasDepartmentName() { return fieldSetFlags()[1]; } /** * Clears the value of the 'departmentName' field. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder clearDepartmentName() { departmentName = null;
fieldSetFlags()[1] = false; return this; } @Override @SuppressWarnings("unchecked") public EmployeeKey build() { try { EmployeeKey record = new EmployeeKey(); record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]); record.departmentName = fieldSetFlags()[1] ? this.departmentName : (java.lang.CharSequence) defaultValue(fields()[1]); return record; } catch (java.lang.Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumWriter<EmployeeKey> WRITER$ = (org.apache.avro.io.DatumWriter<EmployeeKey>)MODEL$.createDatumWriter(SCHEMA$); @Override public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { WRITER$.write(this, SpecificData.getEncoder(out)); } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumReader<EmployeeKey> READER$ = (org.apache.avro.io.DatumReader<EmployeeKey>)MODEL$.createDatumReader(SCHEMA$); @Override public void readExternal(java.io.ObjectInput in) throws java.io.IOException { READER$.read(this, SpecificData.getDecoder(in)); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\EmployeeKey.java
1
请完成以下Java代码
private class Client { final String name; final ByteBuffer readOnlyBuffer; final AtomicLong readPos = new AtomicLong(); Client(String name, ByteBuffer source) { this.name = name; this.readOnlyBuffer = source.asReadOnlyBuffer(); } void readTradeData() { while (readPos.get() < writePos.get()) { try { final int pos = this.readOnlyBuffer.position(); final MarketData data = MarketDataUtil.readAndDecode(this.readOnlyBuffer); readPos.addAndGet(this.readOnlyBuffer.position() - pos); log.info("<readTradeData> client: {}, read/write gap: {}, data: {}", name, writePos.get() - readPos.get(), data); } catch (IndexOutOfBoundsException e) { this.readOnlyBuffer.clear(); // ring buffer } catch (Exception e) { log.error("<readTradeData> cannot read from buffer {}", readOnlyBuffer); } } if (this.readOnlyBuffer.remaining() == 0) { this.readOnlyBuffer.clear(); // ring buffer } } void read() { readerThreadPool.scheduleAtFixedRate(this::readTradeData, 1, 1, TimeUnit.SECONDS); } } private Client newClient(String name) { return new Client(name, buffer); } private void writeTradeData(MarketData data) { try {
final int writtenBytes = MarketDataUtil.encodeAndWrite(buffer, data); writePos.addAndGet(writtenBytes); log.info("<writeTradeData> buffer size remaining: %{}, data: {}", 100 * buffer.remaining() / buffer.capacity(), data); } catch (IndexOutOfBoundsException e) { buffer.clear(); // ring buffer writeTradeData(data); } catch (Exception e) { log.error("<writeTradeData> cannot write into buffer {}", buffer); } } private void run(MarketDataSource source) { writerThread.scheduleAtFixedRate(() -> { if (source.hasNext()) { writeTradeData(source.next()); } }, 1, 2, TimeUnit.SECONDS); } public static void main(String[] args) { MarketDataStreamServer server = new MarketDataStreamServer(); Client client1 = server.newClient("client1"); client1.read(); Client client2 = server.newClient("client2"); client2.read(); server.run(new MarketDataSource()); } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketDataStreamServer.java
1
请完成以下Java代码
public void setPA_DashboardContent_ID (int PA_DashboardContent_ID) { if (PA_DashboardContent_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_DashboardContent_ID, Integer.valueOf(PA_DashboardContent_ID)); } /** Get PA_DashboardContent_ID. @return PA_DashboardContent_ID */ public int getPA_DashboardContent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_DashboardContent_ID); if (ii == null) return 0; return ii.intValue(); } public I_PA_Goal getPA_Goal() throws RuntimeException { return (I_PA_Goal)MTable.get(getCtx(), I_PA_Goal.Table_Name) .getPO(getPA_Goal_ID(), get_TrxName()); } /** Set Goal. @param PA_Goal_ID Performance Goal */ public void setPA_Goal_ID (int PA_Goal_ID) { if (PA_Goal_ID < 1) set_Value (COLUMNNAME_PA_Goal_ID, null); else set_Value (COLUMNNAME_PA_Goal_ID, Integer.valueOf(PA_Goal_ID)); } /** Get Goal. @return Performance Goal */
public int getPA_Goal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Goal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZUL File Path. @param ZulFilePath Absolute path to zul file */ public void setZulFilePath (String ZulFilePath) { set_Value (COLUMNNAME_ZulFilePath, ZulFilePath); } /** Get ZUL File Path. @return Absolute path to zul file */ public String getZulFilePath () { return (String)get_Value(COLUMNNAME_ZulFilePath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_DashboardContent.java
1
请完成以下Java代码
@Override public void exitId(LabeledExprParser.IdContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterInt(LabeledExprParser.IntContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitInt(LabeledExprParser.IntContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /**
* {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprBaseListener.java
1
请完成以下Java代码
protected TreeNode createNode(Object cell) { TreeNode node = new TreeNode(cell); mxRectangle geo = getVertexBounds(cell); if (geo != null) { if (horizontal) { node.width = geo.getHeight(); node.height = geo.getWidth(); } else { node.width = geo.getWidth(); node.height = geo.getHeight(); } } return node; } /** * */ protected mxRectangle apply(TreeNode node, mxRectangle bounds) { mxRectangle g = graph.getModel().getGeometry(node.cell); if (node.cell != null && g != null) { if (isVertexMovable(node.cell)) { g = setVertexLocation(node.cell, node.x, node.y); } if (bounds == null) { bounds = new mxRectangle(g.getX(), g.getY(), g.getWidth(), g.getHeight()); } else { bounds = new mxRectangle( Math.min(bounds.getX(), g.getX()), Math.min(bounds.getY(), g.getY()), Math.max(bounds.getX() + bounds.getWidth(), g.getX() + g.getWidth()), Math.max(bounds.getY() + bounds.getHeight(), g.getY() + g.getHeight()) ); } } return bounds; } /** * */ protected Polyline createLine(double dx, double dy, Polyline next) { return new Polyline(dx, dy, next); } /** * */ protected static class TreeNode { /** * */ protected Object cell; /** * */ protected double x, y, width, height, offsetX, offsetY; /**
* */ protected TreeNode child, next; // parent, sibling /** * */ protected Polygon contour = new Polygon(); /** * */ public TreeNode(Object cell) { this.cell = cell; } } /** * */ protected static class Polygon { /** * */ protected Polyline lowerHead, lowerTail, upperHead, upperTail; } /** * */ protected static class Polyline { /** * */ protected double dx, dy; /** * */ protected Polyline next; /** * */ protected Polyline(double dx, double dy, Polyline next) { this.dx = dx; this.dy = dy; this.next = next; } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BPMNLayout.java
1
请完成以下Java代码
protected Optional<? extends I_M_ProductPrice> findMatchingProductPriceAttribute(final IPricingContext pricingCtx) { final I_M_AttributeSetInstance attributeSetInstance = getM_AttributeSetInstance(pricingCtx); if (attributeSetInstance == null) { Loggables.withLogger(logger, Level.DEBUG).addLog("findMatchingProductPriceAttribute - Return empty because no M_AttributeSetInstance_ID found: {}", pricingCtx); return Optional.empty(); } final I_M_PriceList_Version ctxPriceListVersion = pricingCtx.getM_PriceList_Version(); if (ctxPriceListVersion == null) { Loggables.withLogger(logger, Level.DEBUG).addLog("findMatchingProductPriceAttribute - Return empty because no M_PriceList_Version found: {}", pricingCtx); return Optional.empty(); } final I_M_ProductPrice productPrice = ProductPrices.newQuery(ctxPriceListVersion) .setProductId(pricingCtx.getProductId()) .onlyValidPrices(true) .matching(_defaultMatchers) .strictlyMatchingAttributes(attributeSetInstance) .firstMatching(); if (productPrice == null) { Loggables.withLogger(logger, Level.DEBUG).addLog("findMatchingProductPriceAttribute - Return empty because no product price found: {}", pricingCtx); return Optional.empty(); // no matching } return Optional.of(productPrice); } /**
* Extracts an ASI from the given {@code pricingCtx}. * * @return <ul> * <li>ASI * <li><code>null</code> if the given <code>pricingCtx</code> has no <code>ReferencedObject</code><br/> * or if the referenced object can't be converted to an {@link IAttributeSetInstanceAware}<br/> * or if the referenced object has M_AttributeSetInstance_ID less or equal zero. * </ul> */ @Nullable protected static I_M_AttributeSetInstance getM_AttributeSetInstance(final IPricingContext pricingCtx) { final IAttributeSetInstanceAware asiAware = pricingCtx.getAttributeSetInstanceAware().orElse(null); if (asiAware == null) { return null; } // // Get M_AttributeSetInstance_ID and return it. // NOTE: to respect the method contract, ALWAYS return ZERO if it's not set, no matter if the getter returned -1. final AttributeSetInstanceId attributeSetInstanceId = AttributeSetInstanceId.ofRepoIdOrNone(asiAware.getM_AttributeSetInstance_ID()); if (attributeSetInstanceId.isNone()) { return null; } return Services.get(IAttributeSetInstanceBL.class).getById(attributeSetInstanceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\attributebased\impl\AttributePricing.java
1
请完成以下Java代码
public class M_RequisitionLine { @CalloutMethod(columnNames = I_M_RequisitionLine.COLUMNNAME_M_Product_ID) public void onProductChanged(final I_M_RequisitionLine line) { if (line.getM_Product_ID() <= 0) { return; } updatePrice(line); final UomId uomId = Services.get(IProductBL.class).getStockUOMId(line.getM_Product_ID()); line.setC_UOM_ID(uomId.getRepoId()); } // product @CalloutMethod(columnNames = I_M_RequisitionLine.COLUMNNAME_Qty) public void onQtyChanged(final I_M_RequisitionLine line) { updatePrice(line); } @CalloutMethod(columnNames = I_M_RequisitionLine.COLUMNNAME_PriceActual) public void onPriceActualChanged(final I_M_RequisitionLine line) { updateLineNetAmt(line); } private void updatePrice(final I_M_RequisitionLine line) { final int C_BPartner_ID = line.getC_BPartner_ID(); final BigDecimal Qty = line.getQty(); final boolean isSOTrx = false; final MProductPricing pp = new MProductPricing( OrgId.ofRepoId(line.getAD_Org_ID()), line.getM_Product_ID(), C_BPartner_ID, null, Qty, isSOTrx); // final I_M_Requisition req = line.getM_Requisition(); final int M_PriceList_ID = req.getM_PriceList_ID(); pp.setM_PriceList_ID(M_PriceList_ID); final Timestamp orderDate = req.getDateRequired();
pp.setPriceDate(orderDate); // line.setPriceActual(pp.getPriceStd()); updateLineNetAmt(line); } private void updateLineNetAmt(final I_M_RequisitionLine line) { final BigDecimal qty = line.getQty(); final BigDecimal priceActual = line.getPriceActual(); // Multiply final BigDecimal lineNetAmt = qty.multiply(priceActual); // int stdPrecision = Env.getContextAsInt(ctx, WindowNo, "StdPrecision"); // if (lineNetAmt.scale() > stdPrecision) // lineNetAmt = lineNetAmt.setScale(stdPrecision, BigDecimal.ROUND_HALF_UP); line.setLineNetAmt(lineNetAmt); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\requisition\callout\M_RequisitionLine.java
1
请完成以下Java代码
public class SessionCookieFilter implements Filter { protected CookieConfigurator cookieConfigurator = new CookieConfigurator(); @Override public void init(FilterConfig filterConfig) throws ServletException { cookieConfigurator.parseParams(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if ((servletRequest instanceof HttpServletRequest) && (servletResponse instanceof HttpServletResponse)) { // create a session if none exists yet ((HttpServletRequest) servletRequest).getSession(); // execute filter chain with a response wrapper that handles sameSite attributes filterChain.doFilter(servletRequest, new SameSiteResponseProxy((HttpServletResponse) servletResponse)); } } @Override public void destroy() { } protected class SameSiteResponseProxy extends HttpServletResponseWrapper { protected HttpServletResponse response; public SameSiteResponseProxy(HttpServletResponse resp) { super(resp); response = resp; } @Override public void sendError(int sc) throws IOException { appendSameSiteIfMissing(); super.sendError(sc); } @Override public void sendError(int sc, String msg) throws IOException { appendSameSiteIfMissing(); super.sendError(sc, msg);
} @Override public void sendRedirect(String location) throws IOException { appendSameSiteIfMissing(); super.sendRedirect(location); } @Override public PrintWriter getWriter() throws IOException { appendSameSiteIfMissing(); return super.getWriter(); } @Override public ServletOutputStream getOutputStream() throws IOException { appendSameSiteIfMissing(); return super.getOutputStream(); } protected void appendSameSiteIfMissing() { Collection<String> cookieHeaders = response.getHeaders(CookieConstants.SET_COOKIE_HEADER_NAME); boolean firstHeader = true; String cookieHeaderStart = cookieConfigurator.getCookieName("JSESSIONID") + "="; for (String cookieHeader : cookieHeaders) { if (cookieHeader.startsWith(cookieHeaderStart)) { cookieHeader = cookieConfigurator.getConfig(cookieHeader); } if (firstHeader) { response.setHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader); firstHeader = false; } else { response.addHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader); } } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SessionCookieFilter.java
1
请完成以下Java代码
public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } /** * Gets the value of the othr property. * * @return * possible object is
* {@link String } * */ public String getOthr() { return othr; } /** * Sets the value of the othr property. * * @param value * allowed object is * {@link String } * */ public void setOthr(String value) { this.othr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ContactDetails2CH.java
1
请完成以下Java代码
public class ES_FTS_Config_Sync extends JavaProcess { private final FTSConfigService ftsConfigService = SpringContextHolder.instance.getBean(FTSConfigService.class); private final ModelsToIndexQueueService modelsToIndexQueueService = SpringContextHolder.instance.getBean(ModelsToIndexQueueService.class); private final IESSystem elasticsearchSystem = Services.get(IESSystem.class); private final IQueryBL queryBL = Services.get(IQueryBL.class); @Param(parameterName = "ES_DeleteIndex") private boolean p_esDropIndex; @Override protected String doIt() throws Exception { final FTSConfigId ftsConfigId = FTSConfigId.ofRepoId(getRecord_ID()); final FTSConfig ftsConfig = ftsConfigService.getConfigById(ftsConfigId); deleteESIndexIfRequired(ftsConfig); enqueueModels(ftsConfig); return MSG_OK; } public void deleteESIndexIfRequired(final FTSConfig config) throws IOException { if (p_esDropIndex) { final String esIndexName = config.getEsIndexName(); elasticsearchSystem.elasticsearchClient() .indices() .delete(new DeleteIndexRequest(esIndexName), RequestOptions.DEFAULT); addLog("Elasticsearch index dropped: {}", esIndexName); } } private void enqueueModels(final FTSConfig ftsConfig) { final FTSConfigSourceTablesMap sourceTables = FTSConfigSourceTablesMap.ofList(ftsConfigService.getSourceTables().getByConfigId(ftsConfig.getId())); for (final TableName sourceTableName : sourceTables.getTableNames()) { enqueueModels(sourceTableName, sourceTables); } } private void enqueueModels( @NonNull final TableName sourceTableName, @NonNull final FTSConfigSourceTablesMap sourceTablesMap)
{ final Stream<ModelToIndexEnqueueRequest> requestsStream = queryBL.createQueryBuilder(sourceTableName.getAsString()) .addOnlyActiveRecordsFilter() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .iterateAndStream() .flatMap(model -> extractRequests(model, sourceTablesMap).stream()); GuavaCollectors.batchAndStream(requestsStream, 500) .forEach(requests -> { modelsToIndexQueueService.enqueueNow(requests); addLog("Enqueued {} records from {} table", requests.size(), sourceTableName); }); } private List<ModelToIndexEnqueueRequest> extractRequests( @NonNull final Object model, @NonNull final FTSConfigSourceTablesMap sourceTables) { return EnqueueSourceModelInterceptor.extractRequests( model, ModelToIndexEventType.CREATED_OR_UPDATED, sourceTables); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\process\ES_FTS_Config_Sync.java
1
请完成以下Java代码
protected void configureProcessDefinitionQuery(ProcessDefinitionQueryImpl query) { getAuthorizationManager().configureProcessDefinitionQuery(query); getTenantManager().configureQuery(query); } protected ListQueryParameterObject configureParameterizedQuery(Object parameter) { return getTenantManager().configureQuery(parameter); } @Override public ProcessDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestProcessDefinitionByKey(key); } @Override public ProcessDefinitionEntity findLatestDefinitionById(String id) { return findLatestProcessDefinitionById(id); } @Override public ProcessDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(ProcessDefinitionEntity.class, definitionId); } @Override public ProcessDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestProcessDefinitionByKeyAndTenantId(definitionKey, tenantId); }
@Override public ProcessDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findProcessDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { return findProcessDefinitionByKeyVersionTagAndTenantId(definitionKey, definitionVersionTag, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findProcessDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessDefinitionManager.java
1
请完成以下Java代码
private int updateUserEntity(PublicKeyCredentialUserEntity userEntity) { List<SqlParameterValue> parameters = this.userEntityParametersMapper.apply(userEntity); SqlParameterValue userEntityId = parameters.remove(0); parameters.add(userEntityId); PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray()); return this.jdbcOperations.update(UPDATE_USER_SQL, pss); } @Override public void delete(Bytes id) { Assert.notNull(id, "id cannot be null"); SqlParameterValue[] parameters = new SqlParameterValue[] { new SqlParameterValue(Types.VARCHAR, id.toBase64UrlString()), }; PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters); this.jdbcOperations.update(DELETE_USER_SQL, pss); } private static class UserEntityParametersMapper implements Function<PublicKeyCredentialUserEntity, List<SqlParameterValue>> { @Override public List<SqlParameterValue> apply(PublicKeyCredentialUserEntity userEntity) { List<SqlParameterValue> parameters = new ArrayList<>(); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getId().toBase64UrlString())); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getName())); parameters.add(new SqlParameterValue(Types.VARCHAR, userEntity.getDisplayName())); return parameters; }
} private static class UserEntityRecordRowMapper implements RowMapper<PublicKeyCredentialUserEntity> { @Override public PublicKeyCredentialUserEntity mapRow(ResultSet rs, int rowNum) throws SQLException { Bytes id = Bytes.fromBase64(new String(rs.getString("id").getBytes())); String name = rs.getString("name"); String displayName = rs.getString("display_name"); return ImmutablePublicKeyCredentialUserEntity.builder().id(id).name(name).displayName(displayName).build(); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\management\JdbcPublicKeyCredentialUserEntityRepository.java
1
请完成以下Java代码
public String getLastName() { return lastName; } public String getFirstName() { return firstName; } public long getId() { return id; } public void setLastName(final String lastName) { this.lastName = lastName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public void setId(final long id) { this.id = id; } public Optional<Salary> getSalary() { return salary; }
public void setSalary(final Optional<Salary> salary) { this.salary = salary; } @Override public String toString() { return "Employee{" + "lastName='" + lastName + '\'' + ", firstName='" + firstName + '\'' + ", id=" + id + ", salary=" + salary + '}'; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\jsonignore\absentfields\Employee.java
1
请完成以下Java代码
public VariableInstance getVariableInstance(String taskId, String variableName) { return commandExecutor.execute(new GetTaskVariableInstanceCmd(taskId, variableName, false)); } @Override public VariableInstance getVariableInstanceLocal(String taskId, String variableName) { return commandExecutor.execute(new GetTaskVariableInstanceCmd(taskId, variableName, true)); } @Override public Map<String, VariableInstance> getVariableInstances(String taskId) { return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, null, false)); } @Override public Map<String, VariableInstance> getVariableInstances(String taskId, Collection<String> variableNames) { return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, variableNames, false)); } @Override public Map<String, VariableInstance> getVariableInstancesLocal(String taskId) { return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, null, true)); } @Override public Map<String, VariableInstance> getVariableInstancesLocal(String taskId, Collection<String> variableNames) { return commandExecutor.execute(new GetTaskVariableInstancesCmd(taskId, variableNames, true)); } @Override public Map<String, DataObject> getDataObjects(String taskId) { return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null)); } @Override public Map<String, DataObject> getDataObjects(String taskId, String locale, boolean withLocalizationFallback) { return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, null, locale, withLocalizationFallback)); } @Override public Map<String, DataObject> getDataObjects(String taskId, Collection<String> dataObjectNames) { return commandExecutor.execute(new GetTaskDataObjectsCmd(taskId, dataObjectNames)); } @Override public Map<String, DataObject> getDataObjects( String taskId, Collection<String> dataObjectNames, String locale,
boolean withLocalizationFallback ) { return commandExecutor.execute( new GetTaskDataObjectsCmd(taskId, dataObjectNames, locale, withLocalizationFallback) ); } @Override public DataObject getDataObject(String taskId, String dataObject) { return commandExecutor.execute(new GetTaskDataObjectCmd(taskId, dataObject)); } @Override public DataObject getDataObject( String taskId, String dataObjectName, String locale, boolean withLocalizationFallback ) { return commandExecutor.execute( new GetTaskDataObjectCmd(taskId, dataObjectName, locale, withLocalizationFallback) ); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Bean public ViewResolver htmlViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); resolver.setContentType("text/html"); resolver.setCharacterEncoding("UTF-8"); resolver.setViewNames(ArrayUtil.array("*.html")); return resolver; } private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); engine.setTemplateResolver(templateResolver); engine.setTemplateEngineMessageSource(messageSource()); return engine; } private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-5\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请完成以下Java代码
public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_WF_Responsible_ID (final int AD_WF_Responsible_ID) { if (AD_WF_Responsible_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Responsible_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Responsible_ID, AD_WF_Responsible_ID); } @Override public int getAD_WF_Responsible_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Responsible_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @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); } /** * ResponsibleType AD_Reference_ID=304 * Reference name: WF_Participant Type */ public static final int RESPONSIBLETYPE_AD_Reference_ID=304; /** Organisation = O */ public static final String RESPONSIBLETYPE_Organisation = "O"; /** Human = H */ public static final String RESPONSIBLETYPE_Human = "H"; /** Rolle = R */ public static final String RESPONSIBLETYPE_Rolle = "R"; /** Systemressource = S */ public static final String RESPONSIBLETYPE_Systemressource = "S"; /** Other = X */ public static final String RESPONSIBLETYPE_Other = "X"; @Override public void setResponsibleType (final java.lang.String ResponsibleType) { set_Value (COLUMNNAME_ResponsibleType, ResponsibleType); } @Override public java.lang.String getResponsibleType() { return get_ValueAsString(COLUMNNAME_ResponsibleType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Responsible.java
1
请完成以下Java代码
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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ 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;
} public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_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_AD_AlertProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public List<Task> findTasksByParentTaskId(String parentTaskId) { return getDbSqlSession().selectList("selectTasksByParentTaskId", parentTaskId); } @Override public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateTaskTenantIdForDeployment", params); } @Override public void updateAllTaskRelatedEntityCountFlags(boolean newValue) { getDbSqlSession().directUpdate("updateTaskRelatedEntityCountEnabled", newValue); } @Override public void deleteTasksByExecutionId(String executionId) { DbSqlSession dbSqlSession = getDbSqlSession(); if (isEntityInserted(dbSqlSession, "execution", executionId)) { deleteCachedEntities(dbSqlSession, tasksByExecutionIdMatcher, executionId); } else { bulkDelete("deleteTasksByExecutionId", tasksByExecutionIdMatcher, executionId); } } @Override protected IdGenerator getIdGenerator() { return taskServiceConfiguration.getIdGenerator(); }
protected void setSafeInValueLists(TaskQueryImpl taskQuery) { if (taskQuery.getCandidateGroups() != null) { taskQuery.setSafeCandidateGroups(createSafeInValuesList(taskQuery.getCandidateGroups())); } if (taskQuery.getInvolvedGroups() != null) { taskQuery.setSafeInvolvedGroups(createSafeInValuesList(taskQuery.getInvolvedGroups())); } if (taskQuery.getScopeIds() != null) { taskQuery.setSafeScopeIds(createSafeInValuesList(taskQuery.getScopeIds())); } if (taskQuery.getOrQueryObjects() != null && !taskQuery.getOrQueryObjects().isEmpty()) { for (TaskQueryImpl orTaskQuery : taskQuery.getOrQueryObjects()) { setSafeInValueLists(orTaskQuery); } } } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MybatisTaskDataManager.java
2
请完成以下Java代码
public class FlywayExtension implements Extension { DataSourceDefinition dataSourceDefinition = null; public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) { bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName()); } public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType<?> patEvent) { AnnotatedType at = patEvent.getAnnotatedType(); dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class); } public void processAnnotatedType(@Observes ProcessAnnotatedType<Flyway> patEvent) { patEvent.configureAnnotatedType() //Add Scope .add(ApplicationScoped.Literal.INSTANCE) //Add Qualifier .add(new AnnotationLiteral<FlywayType>() { }) //Decorate setDataSource(DataSource dataSource){} with @Inject .filterMethods(annotatedMethod -> { return annotatedMethod.getParameters().size() == 1 && annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class); }) .findFirst().get().add(InjectLiteral.INSTANCE); } void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
abdEvent.addBean() .types(javax.sql.DataSource.class, DataSource.class) .qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {}) .scope(ApplicationScoped.class) .name(DataSource.class.getName()) .beanClass(DataSource.class) .createWith(creationalContext -> { DataSource instance = new DataSource(); instance.setUrl(dataSourceDefinition.url()); instance.setDriverClassName(dataSourceDefinition.className()); return instance; }); } void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) { Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral<FlywayType>() {}).get(); flyway.migrate(); } }
repos\tutorials-master\di-modules\flyway-cdi-extension\src\main\java\com\baeldung\cdi\extension\FlywayExtension.java
1
请在Spring Boot框架中完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID) { if (SUMUP_CardReader_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_CardReader_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID); } @Override public int getSUMUP_CardReader_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID); } @Override public de.metas.payment.sumup.repository.model.I_SUMUP_Config getSUMUP_Config()
{ return get_ValueAsPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class); } @Override public void setSUMUP_Config(final de.metas.payment.sumup.repository.model.I_SUMUP_Config SUMUP_Config) { set_ValueFromPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class, SUMUP_Config); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_CardReader.java
2
请完成以下Java代码
public static Collector<ScannableCodeFormat, ?, ScannableCodeFormatsCollection> collect() { return GuavaCollectors.collectUsingListAccumulator(ScannableCodeFormatsCollection::ofList); } public static ScannableCodeFormatsCollection ofList(@Nullable final List<ScannableCodeFormat> formats) { return formats != null && !formats.isEmpty() ? new ScannableCodeFormatsCollection(ImmutableList.copyOf(formats)) : EMPTY; } public ExplainedOptional<ParsedScannedCode> parse(@NonNull final ScannedCode scannedCode) { if (formats.isEmpty()) { return ExplainedOptional.emptyBecause("No formats configured"); } final TranslatableStringBuilder notMatchingExplanation = TranslatableStrings.builder(); for (final ScannableCodeFormat format : formats) {
final ExplainedOptional<ParsedScannedCode> result = format.parse(scannedCode); if (result.isPresent()) { return result; } if (!notMatchingExplanation.isEmpty()) { notMatchingExplanation.append(" | "); } notMatchingExplanation.append(format.getName()).append(" ").append(result.getExplanation()); } return ExplainedOptional.emptyBecause(notMatchingExplanation.build()); } public boolean isEmpty() {return formats.isEmpty();} public ImmutableList<ScannableCodeFormat> toList() {return formats;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\format\ScannableCodeFormatsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public String getMerchantNo() { return merchantNo; } public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo; } public String getPayOrderNo() { return payOrderNo; } public void setPayOrderNo(String payOrderNo) { this.payOrderNo = payOrderNo; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; }
public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpUserBankAuth.java
2
请完成以下Java代码
public final class UIComponentType { private static final ConcurrentMap<String, UIComponentType> cache = new MapMaker().makeMap(); // IMPORTANT to have it before the constants public static final UIComponentType SCAN_BARCODE = createAndCache("common/scanBarcode"); public static final UIComponentType SCAN_AND_VALIDATE_BARCODE = createAndCache("common/scanAndValidateBarcode"); public static final UIComponentType CONFIRM_BUTTON = createAndCache("common/confirmButton"); @JsonCreator public static UIComponentType ofString(@NonNull final String value) { return cache.computeIfAbsent(value, UIComponentType::new); } private static UIComponentType createAndCache(@NonNull final String value) { final UIComponentType type = new UIComponentType(value); cache.put(type.value, type); return type; } private final String value;
private UIComponentType(@NonNull final String value) {this.value = Check.assumeNotEmpty(value, "value");} @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\UIComponentType.java
1
请完成以下Java代码
public HUPPOrderIssueProducer fixedQtyToIssue(@Nullable final Quantity fixedQtyToIssue) { this.fixedQtyToIssue = fixedQtyToIssue; return this; } public HUPPOrderIssueProducer considerIssueMethodForQtyToIssueCalculation(final boolean considerIssueMethodForQtyToIssueCalculation) { this.considerIssueMethodForQtyToIssueCalculation = considerIssueMethodForQtyToIssueCalculation; return this; } public HUPPOrderIssueProducer processCandidates(@NonNull final ProcessIssueCandidatesPolicy processCandidatesPolicy) { this.processCandidatesPolicy = processCandidatesPolicy; return this; } private boolean isProcessCandidates() { final ProcessIssueCandidatesPolicy processCandidatesPolicy = this.processCandidatesPolicy; if (ProcessIssueCandidatesPolicy.NEVER.equals(processCandidatesPolicy)) { return false; } else if (ProcessIssueCandidatesPolicy.ALWAYS.equals(processCandidatesPolicy)) { return true; } else if (ProcessIssueCandidatesPolicy.IF_ORDER_PLANNING_STATUS_IS_COMPLETE.equals(processCandidatesPolicy))
{ final I_PP_Order ppOrder = getPpOrder(); final PPOrderPlanningStatus orderPlanningStatus = PPOrderPlanningStatus.ofCode(ppOrder.getPlanningStatus()); return PPOrderPlanningStatus.COMPLETE.equals(orderPlanningStatus); } else { throw new AdempiereException("Unknown processCandidatesPolicy: " + processCandidatesPolicy); } } public HUPPOrderIssueProducer changeHUStatusToIssued(final boolean changeHUStatusToIssued) { this.changeHUStatusToIssued = changeHUStatusToIssued; return this; } public HUPPOrderIssueProducer generatedBy(final IssueCandidateGeneratedBy generatedBy) { this.generatedBy = generatedBy; return this; } public HUPPOrderIssueProducer failIfIssueOnlyForReceived(final boolean fail) { this.failIfIssueOnlyForReceived = fail; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueProducer.java
1