instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
}
public void setName(final String name)
{
this.name = name;
this.nameSet = true;
}
public void setName2(final String name2)
{
this.name2 = name2;
this.name2Set = true;
}
public void setName3(final String name3)
{
this.name3 = name3;
this.name3Set = true;
}
public void setCompanyName(final String companyName)
{
this.companyName = companyName;
this.companyNameSet = true;
}
public void setVendor(final Boolean vendor)
{
this.vendor = vendor;
this.vendorSet = true;
}
public void setCustomer(final Boolean customer)
{
this.customer = customer;
this.customerSet = true;
}
public void setParentId(final JsonMetasfreshId parentId)
{
this.parentId = parentId;
this.parentIdSet = true;
}
public void setPhone(final String phone)
{
this.phone = phone;
this.phoneSet = true;
}
public void setLanguage(final String language)
{
this.language = language;
this.languageSet = true;
} | public void setInvoiceRule(final JsonInvoiceRule invoiceRule)
{
this.invoiceRule = invoiceRule;
this.invoiceRuleSet = true;
}
public void setUrl(final String url)
{
this.url = url;
this.urlSet = true;
}
public void setUrl2(final String url2)
{
this.url2 = url2;
this.url2Set = true;
}
public void setUrl3(final String url3)
{
this.url3 = url3;
this.url3Set = true;
}
public void setGroup(final String group)
{
this.group = group;
this.groupSet = true;
}
public void setGlobalId(final String globalId)
{
this.globalId = globalId;
this.globalIdset = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
public void setVatId(final String vatId)
{
this.vatId = vatId;
this.vatIdSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBPartner.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LanguageKey getCurrentLang()
{
final HttpSession httpSession = getCurrentHttpSessionOrNull();
if (httpSession == null)
{
return LanguageKey.ofLocale(Locale.getDefault());
}
final LanguageKey languageKey = (LanguageKey)httpSession.getAttribute(HTTP_SESSION_language);
return languageKey != null
? languageKey
: LanguageKey.ofLocale(Locale.getDefault());
}
public Locale getCurrentLocale()
{
final HttpSession httpSession = getCurrentHttpSessionOrNull();
if (httpSession == null)
{
return Locale.getDefault();
}
final LanguageKey languageKey = (LanguageKey)httpSession.getAttribute(HTTP_SESSION_language);
return languageKey != null
? languageKey.toLocale()
: Locale.getDefault();
}
@Nullable
private HttpSession getCurrentHttpSessionOrNull()
{
final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
if (servletRequestAttributes == null)
{
return null;
}
return servletRequestAttributes.getRequest().getSession();
}
private LanguageData getLanguageData(@Nullable final LanguageKey language)
{
final LanguageKey languageEffective = language != null ? language : LanguageKey.getDefault();
return cache.computeIfAbsent(languageEffective, LanguageData::new);
} | public ImmutableMap<String, String> getMessagesMap(@NonNull final LanguageKey language)
{
return getLanguageData(language).getFrontendMessagesMap();
}
private static class LanguageData
{
@Getter
private final ResourceBundle resourceBundle;
@Getter
private final ImmutableMap<String, String> frontendMessagesMap;
private LanguageData(final @NonNull LanguageKey language)
{
resourceBundle = ResourceBundle.getBundle("messages", language.toLocale());
frontendMessagesMap = computeMessagesMap(resourceBundle);
}
private static ImmutableMap<String, String> computeMessagesMap(@NonNull final ResourceBundle bundle)
{
final Set<String> keys = bundle.keySet();
final HashMap<String, String> map = new HashMap<>(keys.size());
for (final String key : keys)
{
// shall not happen
if (key == null || key.isBlank())
{
continue;
}
final String value = Strings.nullToEmpty(bundle.getString(key));
map.put(key, value);
}
return ImmutableMap.copyOf(map);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\I18N.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() { | return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\defaultvalues\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GRSSignumExportHURouteBuilder extends RouteBuilder
{
@VisibleForTesting
static final String EXPORT_HU_ROUTE_ID = "GRSSignum-exportHU";
@Override
public void configure() throws Exception
{
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(EXPORT_HU_ROUTE_ID))
.routeId(EXPORT_HU_ROUTE_ID)
.streamCache("true")
.process(this::buildAndAttachContext)
.process(this::buildRetrieveHUCamelRequest)
.to(direct(MF_RETRIEVE_HU_V2_CAMEL_ROUTE_ID))
.unmarshal(CamelRouteUtil.setupJacksonDataFormatFor(getContext(), JsonGetSingleHUResponse.class))
.process(new ExportHUProcessor())
.to(direct(GRSSignumDispatcherRouteBuilder.GRS_DISPATCHER_ROUTE_ID));
}
private void buildAndAttachContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final String remoteUrl = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL);
if (Check.isBlank(remoteUrl))
{
throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_HTTP_URL);
}
final String authToken = request.getParameters().get(ExternalSystemConstants.PARAM_EXTERNAL_SYSTEM_AUTH_TOKEN);
final ExportHURouteContext context = ExportHURouteContext.builder()
.remoteUrl(remoteUrl)
.authToken(authToken)
.build(); | exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_EXPORT_HU_CONTEXT, context);
}
private void buildRetrieveHUCamelRequest(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final String huIdentifier = request.getParameters().get(ExternalSystemConstants.PARAM_HU_ID);
if (Check.isBlank(huIdentifier))
{
throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_HU_ID);
}
final JsonMetasfreshId externalSystemConfigId = request.getExternalSystemConfigId();
final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId();
final RetrieveHUCamelRequest retrieveHUCamelRequest = RetrieveHUCamelRequest.builder()
.huIdentifier(huIdentifier)
.externalSystemConfigId(externalSystemConfigId)
.adPInstanceId(adPInstanceId)
.build();
exchange.getIn().setBody(retrieveHUCamelRequest);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\hu\GRSSignumExportHURouteBuilder.java | 2 |
请完成以下Java代码 | public PlatformPlaceholderDatabaseDriverResolver withDriverPlatform(DatabaseDriver driver, String platform) {
Map<DatabaseDriver, String> driverMappings = new LinkedHashMap<>(this.driverMappings);
driverMappings.put(driver, platform);
return new PlatformPlaceholderDatabaseDriverResolver(this.placeholder, driverMappings);
}
/**
* Resolves the placeholders in the given {@code values}, replacing them with the
* platform derived from the {@link DatabaseDriver} of the given {@code dataSource}.
* @param dataSource the DataSource from which the {@link DatabaseDriver} is derived
* @param values the values in which placeholders are resolved
* @return the values with their placeholders resolved
*/
public List<String> resolveAll(DataSource dataSource, String... values) {
Assert.notNull(dataSource, "'dataSource' must not be null");
return resolveAll(() -> determinePlatform(dataSource), values);
}
/**
* Resolves the placeholders in the given {@code values}, replacing them with the
* given platform.
* @param platform the platform to use
* @param values the values in which placeholders are resolved
* @return the values with their placeholders resolved
* @since 2.6.2
*/
public List<String> resolveAll(String platform, String... values) {
Assert.notNull(platform, "'platform' must not be null");
return resolveAll(() -> platform, values);
}
private List<String> resolveAll(Supplier<String> platformProvider, String... values) {
if (ObjectUtils.isEmpty(values)) {
return Collections.emptyList();
}
List<String> resolved = new ArrayList<>(values.length);
String platform = null;
for (String value : values) {
if (StringUtils.hasLength(value)) {
if (value.contains(this.placeholder)) {
platform = (platform != null) ? platform : platformProvider.get();
value = value.replace(this.placeholder, platform);
}
}
resolved.add(value); | }
return Collections.unmodifiableList(resolved);
}
private String determinePlatform(DataSource dataSource) {
DatabaseDriver databaseDriver = getDatabaseDriver(dataSource);
Assert.state(databaseDriver != DatabaseDriver.UNKNOWN, "Unable to detect database type");
return this.driverMappings.getOrDefault(databaseDriver, databaseDriver.getId());
}
DatabaseDriver getDatabaseDriver(DataSource dataSource) {
try {
String productName = JdbcUtils.commonDatabaseName(
JdbcUtils.extractDatabaseMetaData(dataSource, DatabaseMetaData::getDatabaseProductName));
return DatabaseDriver.fromProductName(productName);
}
catch (Exception ex) {
throw new IllegalStateException("Failed to determine DatabaseDriver", ex);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\init\PlatformPlaceholderDatabaseDriverResolver.java | 1 |
请完成以下Java代码 | public String toString()
{
return stringRepresentation;
}
@Override
public int compareTo(@NonNull final AttributesKeyPart other)
{
final int cmp1 = compareNullsLast(getAttributeValueIdOrSpecialCodeOrNull(), other.getAttributeValueIdOrSpecialCodeOrNull());
if (cmp1 != 0)
{
return cmp1;
}
final int cmp2 = compareNullsLast(getAttributeIdOrNull(), getAttributeIdOrNull());
if (cmp2 != 0)
{
return cmp2;
}
return stringRepresentation.compareTo(other.stringRepresentation);
}
private Integer getAttributeValueIdOrSpecialCodeOrNull()
{
if (type == AttributeKeyPartType.AttributeValueId)
{
return attributeValueId.getRepoId();
}
else if (type == AttributeKeyPartType.All
|| type == AttributeKeyPartType.Other
|| type == AttributeKeyPartType.None) | {
return specialCode;
}
else
{
return null;
}
}
private Integer getAttributeIdOrNull()
{
return AttributeKeyPartType.AttributeIdAndValue == type ? attributeId.getRepoId() : null;
}
private static int compareNullsLast(final Integer i1, final Integer i2)
{
if (i1 == null)
{
return +1;
}
else if (i2 == null)
{
return -1;
}
else
{
return i1 - i2;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKeyPart.java | 1 |
请完成以下Java代码 | public static Object executeRule(String ruleCode, JSONObject formData) {
if (!StringUtils.isEmpty(ruleCode)) {
try {
// 获取 Service
ServiceImpl impl = (ServiceImpl) SpringContextUtils.getBean("sysFillRuleServiceImpl");
// 根据 ruleCode 查询出实体
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("rule_code", ruleCode);
JSONObject entity = JSON.parseObject(JSON.toJSONString(impl.getOne(queryWrapper)));
if (entity == null) {
log.warn("填值规则:" + ruleCode + " 不存在");
return null;
}
// 获取必要的参数
String ruleClass = entity.getString("ruleClass");
JSONObject params = entity.getJSONObject("ruleParams");
if (params == null) {
params = new JSONObject();
}
HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
// 解析 params 中的变量
// 优先级:queryString > 系统变量 > 默认值
for (String key : params.keySet()) {
// 1. 判断 queryString 中是否有该参数,如果有就优先取值
//noinspection ConstantValue
if (request != null) {
String parameter = request.getParameter(key);
if (oConvertUtils.isNotEmpty(parameter)) { | params.put(key, parameter);
continue;
}
}
String value = params.getString(key);
// 2. 用于替换 系统变量的值 #{sys_user_code}
if (value != null && value.contains(SymbolConstant.SYS_VAR_PREFIX)) {
value = QueryGenerator.getSqlRuleValue(value);
params.put(key, value);
}
}
if (formData == null) {
formData = new JSONObject();
}
// 通过反射执行配置的类里的方法
IFillRuleHandler ruleHandler = (IFillRuleHandler) Class.forName(ruleClass).newInstance();
return ruleHandler.execute(params, formData);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\FillRuleUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void persistAuthorWithBooks() {
Author author = new Author();
author.setName("Alicia Tom");
author.setAge(38);
author.setGenre("Anthology");
Book book = new Book();
book.setIsbn("001-AT");
book.setTitle("The book of swords");
Paperback paperback = new Paperback();
paperback.setIsbn("002-AT");
paperback.setTitle("The beatles anthology");
paperback.setSizeIn("7.5 x 1.3 x 9.2");
paperback.setWeightLbs("2.7");
Ebook ebook = new Ebook(); | ebook.setIsbn("003-AT");
ebook.setTitle("Anthology myths");
ebook.setFormat("kindle");
// author.addBook(book); // use addBook() helper
author.addBook(paperback);
author.addBook(ebook);
authorRepository.save(author);
}
public void applyVisitor(Class<? extends Visitor> clazzVisitor) {
visitorService.accept(clazzVisitor);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinedAndVisitor\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTrxNo() {
return trxNo;
}
public void setTrxNo(String trxNo) {
this.trxNo = trxNo == null ? null : trxNo.trim();
}
public String getBankOrderNo() {
return bankOrderNo;
}
public void setBankOrderNo(String bankOrderNo) {
this.bankOrderNo = bankOrderNo == null ? null : bankOrderNo.trim();
}
public String getBankTrxNo() {
return bankTrxNo;
}
public void setBankTrxNo(String bankTrxNo) {
this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim();
}
public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
public BigDecimal getPlatIncome() {
return platIncome;
}
public void setPlatIncome(BigDecimal platIncome) {
this.platIncome = platIncome;
}
public BigDecimal getFeeRate() {
return feeRate;
}
public void setFeeRate(BigDecimal feeRate) {
this.feeRate = feeRate;
}
public BigDecimal getPlatCost() {
return platCost;
}
public void setPlatCost(BigDecimal platCost) {
this.platCost = platCost;
}
public BigDecimal getPlatProfit() {
return platProfit;
} | public void setPlatProfit(BigDecimal platProfit) {
this.platProfit = platProfit;
}
public String getPayWayCode() {
return payWayCode;
}
public void setPayWayCode(String payWayCode) {
this.payWayCode = payWayCode == null ? null : payWayCode.trim();
}
public String getPayWayName() {
return payWayName;
}
public void setPayWayName(String payWayName) {
this.payWayName = payWayName == null ? null : payWayName.trim();
}
public Date getPaySuccessTime() {
return paySuccessTime;
}
public void setPaySuccessTime(Date paySuccessTime) {
this.paySuccessTime = paySuccessTime;
}
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
public String getIsRefund() {
return isRefund;
}
public void setIsRefund(String isRefund) {
this.isRefund = isRefund == null ? null : isRefund.trim();
}
public Short getRefundTimes() {
return refundTimes;
}
public void setRefundTimes(Short refundTimes) {
this.refundTimes = refundTimes;
}
public BigDecimal getSuccessRefundAmount() {
return successRefundAmount;
}
public void setSuccessRefundAmount(BigDecimal successRefundAmount) {
this.successRefundAmount = successRefundAmount;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java | 2 |
请完成以下Java代码 | protected @NonNull CrudRepository<T, ID> getRepository() {
return this.repository;
}
@Override
@SuppressWarnings("unchecked")
public void configure(String beanName, ClientRegionFactoryBean<?, ?> bean) {
if (getRegionBeanName().test(beanName)) {
bean.setCacheWriter(newRepositoryCacheWriter());
}
}
@Override
@SuppressWarnings("unchecked")
public void configure(String beanName, PeerRegionFactoryBean<?, ?> bean) {
if (getRegionBeanName().test(beanName)) {
bean.setCacheWriter(newRepositoryCacheWriter()); | }
}
/**
* Constructs a new instance of {@link RepositoryCacheWriter} adapting the {@link CrudRepository}
* as an instance of a {@link CacheWriter}.
*
* @return a new {@link RepositoryCacheWriter}.
* @see org.springframework.geode.cache.RepositoryCacheWriter
* @see org.springframework.data.repository.CrudRepository
* @see org.apache.geode.cache.CacheWriter
* @see #getRepository()
*/
@SuppressWarnings("rawtypes")
protected RepositoryCacheWriter newRepositoryCacheWriter() {
return new RepositoryCacheWriter<>(getRepository());
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\RepositoryCacheWriterRegionConfigurer.java | 1 |
请完成以下Java代码 | private void enableSecureProcessing(final DocumentBuilderFactory dbf) {
try {
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setAttribute(JAXP_ACCESS_EXTERNAL_SCHEMA, resolveAccessExternalSchemaProperty());
} catch (ParserConfigurationException | IllegalArgumentException ignored) {
// ignored
}
}
/*
* JAXP allows users to override the default value via system properties and
* a central properties file (see https://docs.oracle.com/javase/tutorial/jaxp/properties/scope.html).
* However, both are overridden by an explicit configuration in code, as we apply it.
* Since we want users to customize the value, we take the system property into account.
* The properties file is not supported at the moment.
*/
protected String resolveAccessExternalSchemaProperty() {
String systemProperty = System.getProperty(JAXP_ACCESS_EXTERNAL_SCHEMA_SYSTEM_PROPERTY);
if (systemProperty != null) {
return systemProperty;
} else {
return JAXP_ACCESS_EXTERNAL_SCHEMA_ALL;
}
}
public ModelInstance parseModelFromStream(InputStream inputStream) {
DomDocument document = null;
synchronized(documentBuilderFactory) {
document = DomUtil.parseInputStream(documentBuilderFactory, inputStream);
}
validateModel(document);
return createModelInstance(document);
}
public ModelInstance getEmptyModel() {
DomDocument document = null;
synchronized(documentBuilderFactory) {
document = DomUtil.getEmptyDocument(documentBuilderFactory);
}
return createModelInstance(document);
}
/**
* Validate DOM document
*
* @param document the DOM document to validate
*/
public void validateModel(DomDocument document) {
Schema schema = getSchema(document);
if (schema == null) {
return;
}
Validator validator = schema.newValidator(); | try {
synchronized(document) {
validator.validate(document.getDomSource());
}
} catch (IOException e) {
throw new ModelValidationException("Error during DOM document validation", e);
} catch (SAXException e) {
throw new ModelValidationException("DOM document is not valid", e);
}
}
protected Schema getSchema(DomDocument document) {
DomElement rootElement = document.getRootElement();
String namespaceURI = rootElement.getNamespaceURI();
return schemas.get(namespaceURI);
}
protected void addSchema(String namespaceURI, Schema schema) {
schemas.put(namespaceURI, schema);
}
protected Schema createSchema(String location, ClassLoader classLoader) {
URL cmmnSchema = ReflectUtil.getResource(location, classLoader);
try {
return schemaFactory.newSchema(cmmnSchema);
} catch (SAXException e) {
throw new ModelValidationException("Unable to parse schema:" + cmmnSchema);
}
}
protected abstract ModelInstance createModelInstance(DomDocument document);
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\parser\AbstractModelParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class PathPatternRequestMatcherFactoryBean
implements FactoryBean<PathPatternRequestMatcher>, ApplicationContextAware, InitializingBean {
private final String pattern;
private String basePath;
private HttpMethod method;
private PathPatternRequestMatcher.Builder builder;
PathPatternRequestMatcherFactoryBean(String pattern) {
this.pattern = pattern;
}
PathPatternRequestMatcherFactoryBean(String pattern, String method) {
this.pattern = pattern;
this.method = StringUtils.hasText(method) ? HttpMethod.valueOf(method) : null;
}
@Override
public @Nullable PathPatternRequestMatcher getObject() throws Exception {
return this.builder.matcher(this.method, this.pattern);
} | @Override
public @Nullable Class<?> getObjectType() {
return PathPatternRequestMatcher.class;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.builder = context.getBeanProvider(PathPatternRequestMatcher.Builder.class)
.getIfUnique(PathPatternRequestMatcher::withDefaults);
}
@Override
public void afterPropertiesSet() throws Exception {
if (this.basePath != null) {
this.builder.basePath(this.basePath);
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\PathPatternRequestMatcherFactoryBean.java | 2 |
请完成以下Java代码 | public boolean isUseLocalScopeForResultVariable() {
return useLocalScopeForResultVariable;
}
public void setUseLocalScopeForResultVariable(boolean useLocalScopeForResultVariable) {
this.useLocalScopeForResultVariable = useLocalScopeForResultVariable;
}
public boolean isTriggerable() {
return triggerable;
}
public void setTriggerable(boolean triggerable) {
this.triggerable = triggerable;
}
public boolean isStoreResultVariableAsTransient() {
return storeResultVariableAsTransient;
}
public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) {
this.storeResultVariableAsTransient = storeResultVariableAsTransient;
}
@Override
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
} | public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
setUseLocalScopeForResultVariable(otherElement.isUseLocalScopeForResultVariable());
setTriggerable(otherElement.isTriggerable());
setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient());
fieldExtensions = new ArrayList<>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ServiceTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ImmutableList<T> drainAll()
{
final ArrayList<T> objectList = new ArrayList<>();
try
{
final Optional<T> object = Optional.ofNullable(queue.poll(2, TimeUnit.SECONDS));
object.ifPresent(objectList::add);
queue.drainTo(objectList);
log.debug(" {} drained {} objects for processing!", logPrefix, objectList.size());
}
catch (final InterruptedException e)
{
Loggables.withLogger(log, Level.ERROR).addLog(logPrefix + e.getMessage(),e);
}
return ImmutableList.copyOf(objectList);
}
public boolean isEmpty()
{ | return queue.isEmpty();
}
public void add(@NonNull final T object)
{
try
{
queue.put(object);
}
catch (final InterruptedException e)
{
Loggables.withLogger(log, Level.ERROR).addLog(logPrefix + e.getMessage(),e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\ImportQueue.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SimplePostController {
@RequestMapping(value = "/users", method = RequestMethod.POST)
public String postUser(@RequestParam final String username, @RequestParam final String password) {
return "Success" + username;
}
@RequestMapping(value = "/users/detail", method = RequestMethod.POST)
public String postUserDetail(@RequestBody final Foo entity) {
return "Success" + entity.getId();
}
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
if (!file.isEmpty()) {
try {
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
final String fileName = dateFormat.format(new Date());
final File fileServer = new File(fileName);
fileServer.createNewFile();
final byte[] bytes = file.getBytes();
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + username;
} catch (final Exception e) {
return "You failed to upload " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
} | @RequestMapping(value = "/users/upload", method = RequestMethod.POST)
public String postMultipart(@RequestParam("file") final MultipartFile file) {
if (!file.isEmpty()) {
try {
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
final String fileName = dateFormat.format(new Date());
final File fileServer = new File(fileName);
fileServer.createNewFile();
final byte[] bytes = file.getBytes();
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
stream.write(bytes);
stream.close();
return "You successfully uploaded ";
} catch (final Exception e) {
return "You failed to upload " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\SimplePostController.java | 2 |
请完成以下Spring Boot application配置 | logging.config=classpath:log4j2.xml
#logging.level.root=error
server.port=80
# REDIS (RedisProperties)
spring.redis.database=1
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring. | redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=500 | repos\spring-boot-quick-master\quick-redies\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public class SignalInfo {
private String workflowId;
private String workflowRunId;
private String signalName;
private String signalJson;
public String getWorkflowId() {
return workflowId;
}
public void setWorkflowId(String workflowId) {
this.workflowId = workflowId;
}
public String getWorkflowRunId() {
return workflowRunId;
}
public void setWorkflowRunId(String workflowRunId) { | this.workflowRunId = workflowRunId;
}
public String getSignalName() {
return signalName;
}
public void setSignalName(String signalName) {
this.signalName = signalName;
}
public String getSignalJson() {
return signalJson;
}
public void setSignalJson(String signalJson) {
this.signalJson = signalJson;
}
} | repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\model\SignalInfo.java | 1 |
请完成以下Java代码 | public class JoinTables {
public static Result<Record> usingJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.BOOK)
.join(Tables.BOOKAUTHOR)
.on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));
return query.fetch();
}
public static Result<Record> usingMultipleJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.BOOK)
.join(Tables.BOOKAUTHOR)
.on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)))
.join(Tables.STORE)
.on(field(Tables.BOOK.STORE_ID).eq(field(Tables.STORE.ID)));
return query.fetch();
}
public static Result<Record> usingLeftOuterJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.BOOK)
.leftOuterJoin(Tables.BOOKAUTHOR)
.on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));
return query.fetch();
}
public static Result<Record> usingRightOuterJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.BOOK)
.rightOuterJoin(Tables.BOOKAUTHOR)
.on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));
return query.fetch(); | }
public static Result<Record> usingFullOuterJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.BOOK)
.fullOuterJoin(Tables.BOOKAUTHOR)
.on(field(Tables.BOOK.AUTHOR_ID).eq(field(Tables.BOOKAUTHOR.ID)));
return query.fetch();
}
public static Result<Record> usingNaturalJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.BOOK)
.naturalJoin(Tables.BOOKAUTHOR);
return query.fetch();
}
public static Result<Record> usingCrossJoinMethod(DSLContext context) {
SelectJoinStep<Record> query = context.select()
.from(Tables.STORE)
.crossJoin(Tables.BOOK);
return query.fetch();
}
public static void printResult(Result<Record> result) {
for (Record record : result) {
System.out.println(record);
}
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\JoinTables.java | 1 |
请完成以下Java代码 | protected CommandInterceptor createTransactionInterceptor(boolean requiresNew) {
return new JtaTransactionInterceptor(transactionManager, requiresNew, this);
}
@Override
protected void initTransactionManager() {
if(transactionManager == null){
if(transactionManagerJndiName == null || transactionManagerJndiName.length() == 0) {
throw LOG.invalidConfigTransactionManagerIsNull();
}
try {
transactionManager = (TransactionManager) new InitialContext().lookup(transactionManagerJndiName);
} catch(NamingException e) {
throw LOG.invalidConfigCannotFindTransactionManger(transactionManagerJndiName+"'.", e);
}
}
} | @Override
protected void initTransactionContextFactory() {
if(transactionContextFactory == null) {
transactionContextFactory = new JtaTransactionContextFactory(transactionManager);
}
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\JtaProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | public KnowledgeSource getRequiredAuthority() {
return requiredAuthorityRef.getReferenceTargetElement(this);
}
public void setRequiredAuthority(KnowledgeSource requiredAuthority) {
requiredAuthorityRef.setReferenceTargetElement(this, requiredAuthority);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(AuthorityRequirement.class, DMN_ELEMENT_AUTHORITY_REQUIREMENT)
.namespaceUri(LATEST_DMN_NS)
.instanceProvider(new ModelTypeInstanceProvider<AuthorityRequirement>() {
public AuthorityRequirement newInstance(ModelTypeInstanceContext instanceContext) {
return new AuthorityRequirementImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence(); | requiredDecisionRef = sequenceBuilder.element(RequiredDecisionReference.class)
.uriElementReference(Decision.class)
.build();
requiredInputRef = sequenceBuilder.element(RequiredInputReference.class)
.uriElementReference(InputData.class)
.build();
requiredAuthorityRef = sequenceBuilder.element(RequiredAuthorityReference.class)
.uriElementReference(KnowledgeSource.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\AuthorityRequirementImpl.java | 1 |
请完成以下Java代码 | public class UmsMemberTask implements Serializable {
private Long id;
private String name;
@ApiModelProperty(value = "赠送成长值")
private Integer growth;
@ApiModelProperty(value = "赠送积分")
private Integer intergration;
@ApiModelProperty(value = "任务类型:0->新手任务;1->日常任务")
private Integer type;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGrowth() {
return growth;
} | public void setGrowth(Integer growth) {
this.growth = growth;
}
public Integer getIntergration() {
return intergration;
}
public void setIntergration(Integer intergration) {
this.intergration = intergration;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", growth=").append(growth);
sb.append(", intergration=").append(intergration);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static SettRecordStatusEnum getEnum(String enumName) {
SettRecordStatusEnum resultEnum = null;
SettRecordStatusEnum[] enumAry = SettRecordStatusEnum.values();
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
resultEnum = enumAry[i];
break;
}
}
return resultEnum;
}
public static Map<String, Map<String, Object>> toMap() {
SettRecordStatusEnum[] ary = SettRecordStatusEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map);
}
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
SettRecordStatusEnum[] ary = SettRecordStatusEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list;
} | /**
* 判断填入审核状态
*
* @param enumName
* @return
*/
public static boolean checkConfirm(String enumName) {
SettRecordStatusEnum[] enumAry = { SettRecordStatusEnum.CANCEL, SettRecordStatusEnum.CONFIRMED };
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
return true;
}
}
return false;
}
/**
* 判断填入打款状态
*
* @param enumName
* @return
*/
public static boolean checkRemit(String enumName) {
SettRecordStatusEnum[] enumAry = { SettRecordStatusEnum.REMIT_FAIL, SettRecordStatusEnum.REMIT_SUCCESS };
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
return true;
}
}
return false;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\SettRecordStatusEnum.java | 2 |
请完成以下Java代码 | public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* {@inheritDoc}
*/
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy strategy) { | this.securityContextHolderStrategy = () -> strategy;
}
/**
* Filter a {@code returnedObject} using the {@link PostFilter} annotation that the
* {@link MethodInvocation} specifies.
* @param mi the {@link MethodInvocation} to check check
* @return filtered {@code returnedObject}
*/
@Override
public @Nullable Object invoke(MethodInvocation mi) throws Throwable {
Object returnedObject = mi.proceed();
ExpressionAttribute attribute = this.registry.getAttribute(mi);
if (attribute == null) {
return returnedObject;
}
MethodSecurityExpressionHandler expressionHandler = this.registry.getExpressionHandler();
EvaluationContext ctx = expressionHandler.createEvaluationContext(this::getAuthentication, mi);
return expressionHandler.filter(returnedObject, attribute.getExpression(), ctx);
}
private Authentication getAuthentication() {
Authentication authentication = this.securityContextHolderStrategy.get().getContext().getAuthentication();
if (authentication == null) {
throw new AuthenticationCredentialsNotFoundException(
"An Authentication object was not found in the SecurityContext");
}
return authentication;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationMethodInterceptor.java | 1 |
请完成以下Java代码 | public void setIsReconciled (final boolean IsReconciled)
{
set_Value (COLUMNNAME_IsReconciled, IsReconciled);
}
@Override
public boolean isReconciled()
{
return get_ValueAsBoolean(COLUMNNAME_IsReconciled);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed); | }
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
throw new IllegalArgumentException ("Processing is virtual column"); }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java | 1 |
请完成以下Java代码 | public void setF_CANTONID(String f_CANTONID) {
F_CANTONID = f_CANTONID;
}
public String getF_OFFICEID() {
return F_OFFICEID;
}
public void setF_OFFICEID(String f_OFFICEID) {
F_OFFICEID = f_OFFICEID;
}
public String getF_TOLLID() {
return F_TOLLID;
}
public void setF_TOLLID(String f_TOLLID) {
F_TOLLID = f_TOLLID;
}
public Integer getF_ORDER() {
return F_ORDER;
}
public void setF_ORDER(Integer f_ORDER) {
F_ORDER = f_ORDER;
}
public BigDecimal getF_SHARE() {
return F_SHARE;
}
public void setF_SHARE(BigDecimal f_SHARE) {
F_SHARE = f_SHARE;
}
public String getF_ISRATION() {
return F_ISRATION;
}
public void setF_ISRATION(String f_ISRATION) {
F_ISRATION = f_ISRATION;
}
public String getF_INCANTONID() {
return F_INCANTONID;
}
public void setF_INCANTONID(String f_INCANTONID) {
F_INCANTONID = f_INCANTONID;
}
public String getF_INOFFICEID() {
return F_INOFFICEID;
}
public void setF_INOFFICEID(String f_INOFFICEID) {
F_INOFFICEID = f_INOFFICEID;
}
public Integer getF_INACCOUNTTYPE() {
return F_INACCOUNTTYPE;
}
public void setF_INACCOUNTTYPE(Integer f_INACCOUNTTYPE) {
F_INACCOUNTTYPE = f_INACCOUNTTYPE;
}
public String getF_INACCOUNTID() {
return F_INACCOUNTID;
}
public void setF_INACCOUNTID(String f_INACCOUNTID) {
F_INACCOUNTID = f_INACCOUNTID;
}
public String getF_STARTDATE() {
return F_STARTDATE;
}
public void setF_STARTDATE(String f_STARTDATE) {
F_STARTDATE = f_STARTDATE;
}
public String getF_ENDDATE() {
return F_ENDDATE;
}
public void setF_ENDDATE(String f_ENDDATE) {
F_ENDDATE = f_ENDDATE;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_STATUS() { | return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_ISAUDIT() {
return F_ISAUDIT;
}
public void setF_ISAUDIT(String f_ISAUDIT) {
F_ISAUDIT = f_ISAUDIT;
}
public String getF_AUDITER() {
return F_AUDITER;
}
public void setF_AUDITER(String f_AUDITER) {
F_AUDITER = f_AUDITER;
}
public String getF_AUDITTIME() {
return F_AUDITTIME;
}
public void setF_AUDITTIME(String f_AUDITTIME) {
F_AUDITTIME = f_AUDITTIME;
}
public String getF_VERSION() {
return F_VERSION;
}
public void setF_VERSION(String f_VERSION) {
F_VERSION = f_VERSION;
}
public String getF_BUDGETCODE() {
return F_BUDGETCODE;
}
public void setF_BUDGETCODE(String f_BUDGETCODE) {
F_BUDGETCODE = f_BUDGETCODE;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollSpecialShare.java | 1 |
请完成以下Java代码 | public final String getName()
{
final I_AD_Form form = getAD_Form();
if (form == null)
{
return "-";
}
return form.getName();
}
@Override
public final String getTitle()
{
return getName();
}
@Override
public final String getIcon()
{
return null;
}
@Override
public final boolean isAvailable()
{
final I_AD_Form form = getAD_Form();
return form != null;
}
@Override
public final boolean isRunnable()
{
final I_AD_Form form = getAD_Form();
if (form == null)
{
return false;
}
if (!isFormRunnable())
{
return false;
}
return true;
}
/**
* Check if the form is available and shall be opened in current context.
*
* To be implemented in extending class.
*
* @return true if form is available and it shall be opened.
*/
protected boolean isFormRunnable()
{
// nothing at this level
return true;
}
@Override
public final void run()
{
final FormFrame formFrame = AEnv.createForm(getAD_Form());
if (formFrame == null)
{
return;
}
customizeBeforeOpen(formFrame);
AEnv.showCenterWindow(getCallingFrame(), formFrame); | }
protected void customizeBeforeOpen(final FormFrame formFrame)
{
// nothing on this level
}
/** @return the {@link Frame} in which this action was executed or <code>null</code> if not available. */
protected final Frame getCallingFrame()
{
final GridField gridField = getContext().getEditor().getField();
if (gridField == null)
{
return null;
}
final int windowNo = gridField.getWindowNo();
final Frame frame = Env.getWindow(windowNo);
return frame;
}
protected final int getAD_Form_ID()
{
return _adFormId;
}
private final synchronized I_AD_Form getAD_Form()
{
if (!_adFormLoaded)
{
_adForm = retrieveAD_Form();
_adFormLoaded = true;
}
return _adForm;
}
private final I_AD_Form retrieveAD_Form()
{
final IContextMenuActionContext context = getContext();
Check.assumeNotNull(context, "context not null");
final Properties ctx = context.getCtx();
// Check if user has access to Payment Allocation form
final int adFormId = getAD_Form_ID();
final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId);
if (formAccess == null || !formAccess)
{
return null;
}
// Retrieve the form
final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None);
// Translate it to user's language
final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class);
return formTrl;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java | 1 |
请完成以下Java代码 | public PageData<Job> findByTenantIdAndFilter(TenantId tenantId, JobFilter filter, PageLink pageLink) {
return DaoUtil.toPageData(jobRepository.findByTenantIdAndTypesAndStatusesAndEntitiesAndTimeAndSearchText(tenantId.getId(),
CollectionsUtil.isEmpty(filter.getTypes()) ? null : filter.getTypes(),
CollectionsUtil.isEmpty(filter.getStatuses()) ? null : filter.getStatuses(),
CollectionsUtil.isEmpty(filter.getEntities()) ? null : filter.getEntities(),
filter.getStartTime() != null ? filter.getStartTime() : 0,
filter.getEndTime() != null ? filter.getEndTime() : 0,
Strings.emptyToNull(pageLink.getTextSearch()), DaoUtil.toPageable(pageLink)));
}
@Override
public Job findByIdForUpdate(TenantId tenantId, JobId jobId) {
return DaoUtil.getData(jobRepository.findByIdForUpdate(jobId.getId()));
}
@Override
public Job findLatestByTenantIdAndKey(TenantId tenantId, String key) {
return DaoUtil.getData(jobRepository.findLatestByTenantIdAndKey(tenantId.getId(), key, Limit.of(1)));
}
@Override
public boolean existsByTenantAndKeyAndStatusOneOf(TenantId tenantId, String key, JobStatus... statuses) {
return jobRepository.existsByTenantIdAndKeyAndStatusIn(tenantId.getId(), key, Arrays.stream(statuses).toList());
}
@Override
public boolean existsByTenantIdAndTypeAndStatusOneOf(TenantId tenantId, JobType type, JobStatus... statuses) {
return jobRepository.existsByTenantIdAndTypeAndStatusIn(tenantId.getId(), type, Arrays.stream(statuses).toList());
}
@Override
public boolean existsByTenantIdAndEntityIdAndStatusOneOf(TenantId tenantId, EntityId entityId, JobStatus... statuses) {
return jobRepository.existsByTenantIdAndEntityIdAndStatusIn(tenantId.getId(), entityId.getId(), Arrays.stream(statuses).toList());
}
@Override
public Job findOldestByTenantIdAndTypeAndStatusForUpdate(TenantId tenantId, JobType type, JobStatus status) {
return DaoUtil.getData(jobRepository.findOldestByTenantIdAndTypeAndStatusForUpdate(tenantId.getId(), type.name(), status.name())); | }
@Override
public void removeByTenantId(TenantId tenantId) {
jobRepository.deleteByTenantId(tenantId.getId());
}
@Override
public int removeByEntityId(TenantId tenantId, EntityId entityId) {
return jobRepository.deleteByEntityId(entityId.getId());
}
@Override
public EntityType getEntityType() {
return EntityType.JOB;
}
@Override
protected Class<JobEntity> getEntityClass() {
return JobEntity.class;
}
@Override
protected JpaRepository<JobEntity, UUID> getRepository() {
return jobRepository;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\job\JpaJobDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExceptionHandle {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 业务异常处理
* @param exception
* @param <T>
* @return
*/
@ExceptionHandler(CommonBizException.class)
public <T> Result<T> exceptionHandler(CommonBizException exception) {
return Result.newFailureResult(exception);
}
/**
* 请求方法不正确
* @param exception
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) | public Result HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
throw new CommonBizException(ExpCodeEnum.HTTP_REQ_METHOD_ERROR);
}
/**
* 系统异常处理
* @param exception
* @return
*/
@ExceptionHandler(Exception.class)
public <T> Result<T> sysExpHandler(Exception exception) {
logger.error("系统异常 ",exception);
return Result.newFailureResult();
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\handle\ExceptionHandle.java | 2 |
请完成以下Java代码 | public void setFinishedAfter(Date finishedAfter) {
this.finishedAfter = finishedAfter;
}
@CamundaQueryParam(value = "finishedBefore", converter = DateConverter.class)
public void setFinishedBefore(Date finishedBefore) {
this.finishedBefore = finishedBefore;
}
@CamundaQueryParam(value = "processInstanceIdIn", converter = StringArrayConverter.class)
public void setProcessInstanceIdIn(String[] processInstanceIdIn) {
this.processInstanceIdIn = processInstanceIdIn;
}
@Override
protected boolean isValidSortByValue(String value) {
return SORT_ORDER_ACTIVITY_ID.equals(value);
}
@Override
protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId);
}
@Override
protected void applyFilters(HistoricActivityStatisticsQuery query) {
if (includeCanceled != null && includeCanceled) {
query.includeCanceled();
}
if (includeFinished != null && includeFinished) {
query.includeFinished();
}
if (includeCompleteScope != null && includeCompleteScope) {
query.includeCompleteScope();
}
if (includeIncidents !=null && includeIncidents) {
query.includeIncidents();
}
if (startedAfter != null) {
query.startedAfter(startedAfter);
}
if (startedBefore != null) {
query.startedBefore(startedBefore); | }
if (finishedAfter != null) {
query.finishedAfter(finishedAfter);
}
if (finishedBefore != null) {
query.finishedBefore(finishedBefore);
}
if (processInstanceIdIn != null) {
query.processInstanceIdIn(processInstanceIdIn);
}
}
@Override
protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) {
query.orderByActivityId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityStatisticsQueryDto.java | 1 |
请完成以下Java代码 | public HistoricIncidentQuery orderByIncidentState() {
orderBy(HistoricIncidentQueryProperty.INCIDENT_STATE);
return this;
}
public HistoricIncidentQuery orderByTenantId() {
return orderBy(HistoricIncidentQueryProperty.TENANT_ID);
}
// results ////////////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricIncidentManager()
.findHistoricIncidentCountByQueryCriteria(this);
}
public List<HistoricIncident> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricIncidentManager()
.findHistoricIncidentByQueryCriteria(this, page);
}
// getters /////////////////////////////////////////////////////
public String getId() {
return id;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() { | return processDefinitionId;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getCauseIncidentId() {
return causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public IncidentState getIncidentState() {
return incidentState;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricIncidentQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Specification<User> resolveSpecification(String searchParameters) {
UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
String operationSetExper = Joiner.on("|")
.join(SearchOperation.SIMPLE_OPERATION_SET);
Pattern pattern = Pattern.compile("(\\p{Punct}?)(\\w+?)(" + operationSetExper + ")(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
Matcher matcher = pattern.matcher(searchParameters + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(5), matcher.group(4), matcher.group(6));
}
return builder.build();
}
@RequestMapping(method = RequestMethod.GET, value = "/myusers")
@ResponseBody
public Iterable<MyUser> findAllByQuerydsl(@RequestParam(value = "search") String search) {
MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
if (search != null) {
Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
Matcher matcher = pattern.matcher(search + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
}
}
BooleanExpression exp = builder.build();
return myUserRepository.findAll(exp);
}
@RequestMapping(method = RequestMethod.GET, value = "/users/rsql")
@ResponseBody
public List<User> findAllByRsql(@RequestParam(value = "search") String search) {
Node rootNode = new RSQLParser().parse(search);
Specification<User> spec = rootNode.accept(new CustomRsqlVisitor<User>());
return dao.findAll(spec);
} | @RequestMapping(method = RequestMethod.GET, value = "/api/myusers")
@ResponseBody
public Iterable<MyUser> findAllByWebQuerydsl(@QuerydslPredicate(root = MyUser.class) Predicate predicate) {
return myUserRepository.findAll(predicate);
}
// API - WRITE
@RequestMapping(method = RequestMethod.POST, value = "/users")
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody User resource) {
Preconditions.checkNotNull(resource);
dao.save(resource);
}
@RequestMapping(method = RequestMethod.POST, value = "/myusers")
@ResponseStatus(HttpStatus.CREATED)
public void addMyUser(@RequestBody MyUser resource) {
Preconditions.checkNotNull(resource);
myUserRepository.save(resource);
}
} | repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\controller\UserController.java | 2 |
请完成以下Java代码 | public Integer[] arrayCreation() {
return new Integer[1000000];
}
@Benchmark
public ArrayList<Integer> arrayListCreation() {
return new ArrayList<>(1000000);
}
@Benchmark
public Integer[] arrayItemsSetting() {
for (int i = 0; i < 1000000; i++) {
array[i] = i;
}
return array;
}
@Benchmark
public ArrayList<Integer> arrayListItemsSetting() {
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
return list;
}
@Benchmark
public void arrayItemsRetrieval(Blackhole blackhole) { | for (int i = 0; i < 1000000; i++) {
int item = array[i];
blackhole.consume(item);
}
}
@Benchmark
public void arrayListItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 1000000; i++) {
int item = list.get(i);
blackhole.consume(item);
}
}
@Benchmark
public void arrayCloning(Blackhole blackhole) {
Integer[] newArray = array.clone();
blackhole.consume(newArray);
}
@Benchmark
public void arrayListCloning(Blackhole blackhole) {
ArrayList<Integer> newList = new ArrayList<>(list);
blackhole.consume(newList);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\arrayandlistperformance\ArrayAndArrayListPerformance.java | 1 |
请完成以下Java代码 | public class Main {
public static void main(String[] args) throws JsonProcessingException {
System.out.println(serializeUser());
System.out.println(customSerialize());
System.out.println(customDeserialize());
}
static String serializeUser() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(new JavaTimeModule());
User user = new User();
user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));
return objectMapper.writeValueAsString(user);
}
static String customSerialize() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new SimpleModule().addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer())); | User user = new User();
user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));
return objectMapper.writeValueAsString(user);
}
static String customDeserialize() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new SimpleModule().addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer()));
String jsonString = "{\"createdAt\":\"30-09-2021 15:30:00 +01:00\"}";
User returnedUser = objectMapper.readValue(jsonString, User.class);
return returnedUser.getCreatedAt().toString();
}
} | repos\tutorials-master\jackson-modules\jackson-custom-conversions\src\main\java\com\baeldung\offsetdatetime\Main.java | 1 |
请完成以下Java代码 | public String nextElement() {
String headerNames = names.nextElement();
validateAllowedHeaderName(headerNames);
return headerNames;
}
};
}
@Override
public String getParameter(String name) {
if (name != null) {
validateAllowedParameterName(name);
}
String value = super.getParameter(name);
if (value != null) {
validateAllowedParameterValue(name, value);
}
return value;
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> parameterMap = super.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String[] values = entry.getValue();
validateAllowedParameterName(name);
for (String value : values) {
validateAllowedParameterValue(name, value);
}
}
return parameterMap;
}
@Override
public Enumeration<String> getParameterNames() {
Enumeration<String> paramaterNames = super.getParameterNames();
return new Enumeration<>() {
@Override
public boolean hasMoreElements() {
return paramaterNames.hasMoreElements();
}
@Override
public String nextElement() {
String name = paramaterNames.nextElement();
validateAllowedParameterName(name);
return name;
}
};
}
@Override
public String[] getParameterValues(String name) {
if (name != null) {
validateAllowedParameterName(name);
}
String[] values = super.getParameterValues(name);
if (values != null) {
for (String value : values) {
validateAllowedParameterValue(name, value);
}
}
return values;
} | private void validateAllowedHeaderName(String headerNames) {
if (!StrictHttpFirewall.this.allowedHeaderNames.test(headerNames)) {
throw new RequestRejectedException(
"The request was rejected because the header name \"" + headerNames + "\" is not allowed.");
}
}
private void validateAllowedHeaderValue(String name, String value) {
if (!StrictHttpFirewall.this.allowedHeaderValues.test(value)) {
throw new RequestRejectedException("The request was rejected because the header: \"" + name
+ " \" has a value \"" + value + "\" that is not allowed.");
}
}
private void validateAllowedParameterName(String name) {
if (!StrictHttpFirewall.this.allowedParameterNames.test(name)) {
throw new RequestRejectedException(
"The request was rejected because the parameter name \"" + name + "\" is not allowed.");
}
}
private void validateAllowedParameterValue(String name, String value) {
if (!StrictHttpFirewall.this.allowedParameterValues.test(value)) {
throw new RequestRejectedException("The request was rejected because the parameter: \"" + name
+ " \" has a value \"" + value + "\" that is not allowed.");
}
}
@Override
public void reset() {
}
};
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\firewall\StrictHttpFirewall.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Buyer
{
public static final String SERIALIZED_NAME_TAX_ADDRESS = "taxAddress";
@SerializedName(SERIALIZED_NAME_TAX_ADDRESS)
private TaxAddress taxAddress;
public static final String SERIALIZED_NAME_TAX_IDENTIFIER = "taxIdentifier";
@SerializedName(SERIALIZED_NAME_TAX_IDENTIFIER)
private TaxIdentifier taxIdentifier;
public static final String SERIALIZED_NAME_USERNAME = "username";
@SerializedName(SERIALIZED_NAME_USERNAME)
private String username;
public Buyer taxAddress(TaxAddress taxAddress)
{
this.taxAddress = taxAddress;
return this;
}
/**
* Get taxAddress
*
* @return taxAddress
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public TaxAddress getTaxAddress()
{
return taxAddress;
}
public void setTaxAddress(TaxAddress taxAddress)
{
this.taxAddress = taxAddress;
}
public Buyer taxIdentifier(TaxIdentifier taxIdentifier)
{
this.taxIdentifier = taxIdentifier;
return this;
}
/**
* Get taxIdentifier
*
* @return taxIdentifier
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public TaxIdentifier getTaxIdentifier()
{
return taxIdentifier;
}
public void setTaxIdentifier(TaxIdentifier taxIdentifier)
{
this.taxIdentifier = taxIdentifier;
}
public Buyer username(String username)
{
this.username = username;
return this;
}
/**
* The buyer's eBay user ID.
*
* @return username
**/
@javax.annotation.Nullable | @ApiModelProperty(value = "The buyer's eBay user ID.")
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Buyer buyer = (Buyer)o;
return Objects.equals(this.taxAddress, buyer.taxAddress) &&
Objects.equals(this.taxIdentifier, buyer.taxIdentifier) &&
Objects.equals(this.username, buyer.username);
}
@Override
public int hashCode()
{
return Objects.hash(taxAddress, taxIdentifier, username);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Buyer {\n");
sb.append(" taxAddress: ").append(toIndentedString(taxAddress)).append("\n");
sb.append(" taxIdentifier: ").append(toIndentedString(taxIdentifier)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).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\Buyer.java | 2 |
请完成以下Java代码 | public void setProcessDefinitionCache(DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache) {
this.processDefinitionCache = processDefinitionCache;
}
public ProcessDefinitionInfoCache getProcessDefinitionInfoCache() {
return processDefinitionInfoCache;
}
public void setProcessDefinitionInfoCache(ProcessDefinitionInfoCache processDefinitionInfoCache) {
this.processDefinitionInfoCache = processDefinitionInfoCache;
}
public DeploymentCache<Object> getKnowledgeBaseCache() {
return knowledgeBaseCache;
}
public void setKnowledgeBaseCache(DeploymentCache<Object> knowledgeBaseCache) {
this.knowledgeBaseCache = knowledgeBaseCache;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
} | public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
public ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return processDefinitionEntityManager;
}
public void setProcessDefinitionEntityManager(ProcessDefinitionEntityManager processDefinitionEntityManager) {
this.processDefinitionEntityManager = processDefinitionEntityManager;
}
public DeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(DeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\DeploymentManager.java | 1 |
请完成以下Spring Boot application配置 | ---
info:
scm-url: "@scm.url@"
build-url: "https://travis-ci.org/codecentric/spring-boot-admin"
logging:
level:
ROOT: info
de.codecentric: trace
org.springframework.web: debug
file:
name: "target/spring-boot-admin-3-graalvm.log"
pattern:
file: "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx"
management:
info:
java:
enabled: true
env:
enabled: true
endpoints:
web:
exposure:
include: "*"
spring:
application:
| name: spring-boot-admin-3-graalvm
main:
lazy-initialization: true
boot:
admin:
client:
url: http://localhost:8080
ui:
external-views:
- label: 'Is it Christmas yet?'
url: https://isitchristmas.com/ | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet-graalvm\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() { | return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\model\Address.java | 1 |
请完成以下Java代码 | public class MetricsUtil {
/**
* Resolves the internal name of the metric by the public name.
*
* @param publicName the public name
* @return the internal name
*/
public static String resolveInternalName(final String publicName) {
if (publicName == null) return null;
switch (publicName) {
case Metrics.TASK_USERS: return Metrics.UNIQUE_TASK_WORKERS;
case Metrics.PROCESS_INSTANCES: return Metrics.ROOT_PROCESS_INSTANCE_START;
case Metrics.DECISION_INSTANCES: return Metrics.EXECUTED_DECISION_INSTANCES;
case Metrics.FLOW_NODE_INSTANCES: return Metrics.ACTIVTY_INSTANCE_START;
default: return publicName;
}
}
/** | * Resolves the public name of the metric by the internal name.
*
* @param internalName the internal name
* @return the public name
*/
public static String resolvePublicName(final String internalName) {
if (internalName == null) return null;
switch (internalName) {
case Metrics.UNIQUE_TASK_WORKERS: return Metrics.TASK_USERS;
case Metrics.ROOT_PROCESS_INSTANCE_START: return Metrics.PROCESS_INSTANCES;
case Metrics.EXECUTED_DECISION_INSTANCES: return Metrics.DECISION_INSTANCES;
case Metrics.ACTIVTY_INSTANCE_START: return Metrics.FLOW_NODE_INSTANCES;
default: return internalName;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\util\MetricsUtil.java | 1 |
请完成以下Java代码 | public Collection<DrgElement> getDrgElements() {
return drgElementCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
public Collection<ElementCollection> getElementCollections() {
return elementCollectionCollection.get(this);
}
public Collection<BusinessContextElement> getBusinessContextElements() {
return businessContextElementCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, DMN_ELEMENT_DEFINITIONS)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() {
public Definitions newInstance(ModelTypeInstanceContext instanceContext) {
return new DefinitionsImpl(instanceContext);
}
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE)
.defaultValue("http://www.omg.org/spec/FEEL/20140401")
.build();
namespaceAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_NAMESPACE)
.required()
.build(); | exporterAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER)
.build();
exporterVersionAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPORTER_VERSION)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importCollection = sequenceBuilder.elementCollection(Import.class)
.build();
itemDefinitionCollection = sequenceBuilder.elementCollection(ItemDefinition.class)
.build();
drgElementCollection = sequenceBuilder.elementCollection(DrgElement.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
elementCollectionCollection = sequenceBuilder.elementCollection(ElementCollection.class)
.build();
businessContextElementCollection = sequenceBuilder.elementCollection(BusinessContextElement.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DefinitionsImpl.java | 1 |
请完成以下Java代码 | public DistributionManager getDistributionManager() {
return (DistributionManager) getSource();
}
/**
* Returns the {@link Type} of this {@link MembershipEvent}, such as {@link Type#MEMBER_JOINED}.
*
* @return the {@link MembershipEvent.Type}.
*/
public Type getType() {
return Type.UNQUALIFIED;
}
/**
* Null-safe builder method used to configure the {@link DistributedMember member} that is the subject
* of this event.
*
* @param distributedMember {@link DistributedMember} that is the subject of this event.
* @return this {@link MembershipEvent}.
* @see org.apache.geode.distributed.DistributedMember
* @see #getDistributedMember()
*/
@SuppressWarnings("unchecked")
public T withMember(DistributedMember distributedMember) {
this.distributedMember = distributedMember;
return (T) this; | }
/**
* An {@link Enum enumeration} of different type of {@link MembershipEvent MembershipEvents}.
*/
public enum Type {
MEMBER_DEPARTED,
MEMBER_JOINED,
MEMBER_SUSPECT,
QUORUM_LOST,
UNQUALIFIED;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipEvent.java | 1 |
请完成以下Java代码 | public boolean hasChildElements() {
return true;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
Stage stage = new Stage();
stage.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
stage.setAutoComplete(Boolean.valueOf(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IS_AUTO_COMPLETE)));
stage.setAutoCompleteCondition(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_AUTO_COMPLETE_CONDITION));
String displayOrderString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_DISPLAY_ORDER);
if (StringUtils.isNotEmpty(displayOrderString)) {
stage.setDisplayOrder(Integer.valueOf(displayOrderString));
}
String includeInStageOverviewString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INCLUDE_IN_STAGE_OVERVIEW);
if (StringUtils.isNotEmpty(includeInStageOverviewString)) {
stage.setIncludeInStageOverview(includeInStageOverviewString);
} else {
stage.setIncludeInStageOverview("true"); // True by default
} | stage.setCase(conversionHelper.getCurrentCase());
stage.setParent(conversionHelper.getCurrentPlanFragment());
conversionHelper.setCurrentStage(stage);
conversionHelper.addStage(stage);
String businessStatus = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_BUSINESS_STATUS);
if (StringUtils.isNotEmpty(businessStatus)) {
stage.setBusinessStatus(businessStatus);
}
return stage;
}
@Override
protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) {
super.elementEnd(xtr, conversionHelper);
conversionHelper.removeCurrentStage();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\StageXmlConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isUseHttp() {
return this.useHttp;
}
public void setUseHttp(boolean useHttp) {
this.useHttp = useHttp;
}
public static class HttpServiceProperties {
private static final int DEFAULT_PORT = 7070;
private static final String DEFAULT_HOST = "localhost";
private int port = DEFAULT_PORT;
private String host = DEFAULT_HOST; | public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ManagementProperties.java | 2 |
请完成以下Java代码 | public Tag name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@ApiModelProperty(value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(this.id, tag.id) &&
Objects.equals(this.name, tag.name);
}
@Override
public int hashCode() { | return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Tag.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDecisionDefinitionId() {
return decisionDefinitionId;
}
public void setDecisionDefinitionId(String decisionDefinitionId) {
this.decisionDefinitionId = decisionDefinitionId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Boolean getFailed() {
return failed;
}
public void setFailed(Boolean failed) {
this.failed = failed;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() { | return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
} | repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\history\HistoricDecisionExecutionResponse.java | 2 |
请完成以下Java代码 | public class ExecuteAsyncJobCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(ExecuteAsyncJobCmd.class);
protected String jobId;
public ExecuteAsyncJobCmd(String jobId) {
this.jobId = jobId;
}
public Object execute(CommandContext commandContext) {
if (jobId == null) {
throw new ActivitiIllegalArgumentException("jobId is null");
}
// We need to refetch the job, as it could have been deleted by another concurrent job
// For exampel: an embedded subprocess with a couple of async tasks and a timer on the boundary of the subprocess
// when the timer fires, all executions and thus also the jobs inside of the embedded subprocess are destroyed.
// However, the async task jobs could already have been fetched and put in the queue.... while in reality they have been deleted.
// A refetch is thus needed here to be sure that it exists for this transaction.
Job job = commandContext.getJobEntityManager().findById(jobId);
if (job == null) {
log.debug(
"Job does not exist anymore and will not be executed. It has most likely been deleted " +
"as part of another concurrent part of the process instance."
);
return null;
}
if (log.isDebugEnabled()) { | log.debug("Executing async job {}", job.getId());
}
executeInternal(commandContext, job);
return null;
}
protected void executeInternal(CommandContext commandContext, Job job) {
commandContext.getJobManager().execute(job);
if (commandContext.getEventDispatcher().isEnabled()) {
commandContext
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_EXECUTION_SUCCESS, job));
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ExecuteAsyncJobCmd.java | 1 |
请完成以下Java代码 | public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper)
{
return toImmutableList(idMapper.compose(DocumentId::toInt));
}
public Set<String> toJsonSet()
{
if (all)
{
return ALL_StringSet;
}
return toSet(DocumentId::toJson);
}
public SelectionSize toSelectionSize()
{
if (isAll())
{
return SelectionSize.ofAll();
}
return SelectionSize.ofSize(size());
}
public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection)
{
if (this.isEmpty())
{
return documentIdsSelection;
}
else if (documentIdsSelection.isEmpty())
{
return this;
}
if (this.all)
{
return this; | }
else if (documentIdsSelection.all)
{
return documentIdsSelection;
}
final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet());
final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds);
if (this.equals(result))
{
return this;
}
else if (documentIdsSelection.equals(result))
{
return documentIdsSelection;
}
else
{
return result;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class PickingTerminalViewInvalidationAdvisor implements IViewInvalidationAdvisor
{
@Autowired
private PickingCandidateRepository pickingCandidateRepository;
@Override
public WindowId getWindowId()
{
return PickingConstants.WINDOWID_PackageableView;
}
@Override
public Set<DocumentId> findAffectedRowIds(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend,
@NonNull IView view)
{
final Set<ShipmentScheduleId> shipmentScheduleIds = extractShipmentScheduleIds(recordRefs);
if (shipmentScheduleIds.isEmpty())
{
return ImmutableSet.of();
}
final SqlViewKeyColumnNamesMap keyColumnNamesMap = SqlViewKeyColumnNamesMap.ofIntKeyField(I_M_Packageable_V.COLUMNNAME_M_ShipmentSchedule_ID);
return SqlViewRowIdsOrderedSelectionFactory.retrieveRowIdsForLineIds(
keyColumnNamesMap,
view.getViewId(),
ShipmentScheduleId.toIntSet(shipmentScheduleIds));
}
private Set<ShipmentScheduleId> extractShipmentScheduleIds(final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
return ImmutableSet.of();
}
final Set<ShipmentScheduleId> shipmentScheduleIds = new HashSet<>(); | final Set<PickingCandidateId> pickingCandidateIds = new HashSet<>();
for (TableRecordReference recordRef : recordRefs)
{
final String tableName = recordRef.getTableName();
if (I_M_ShipmentSchedule.Table_Name.equals(tableName))
{
shipmentScheduleIds.add(ShipmentScheduleId.ofRepoId(recordRef.getRecord_ID()));
}
else if (I_M_Picking_Candidate.Table_Name.equals(tableName))
{
pickingCandidateIds.add(PickingCandidateId.ofRepoId(recordRef.getRecord_ID()));
}
}
if (!pickingCandidateIds.isEmpty())
{
shipmentScheduleIds.addAll(pickingCandidateRepository.getShipmentScheduleIdsByPickingCandidateIds(pickingCandidateIds));
}
return shipmentScheduleIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\PickingTerminalViewInvalidationAdvisor.java | 2 |
请完成以下Java代码 | public Class<? extends HistoricVariableInstanceEntity> getManagedEntityClass() {
return HistoricVariableInstanceEntityImpl.class;
}
@Override
public HistoricVariableInstanceEntity create() {
return new HistoricVariableInstanceEntityImpl();
}
@Override
public void insert(HistoricVariableInstanceEntity entity) {
super.insert(entity);
}
@Override
public List<HistoricVariableInstanceEntity> findHistoricVariableInstancesByProcessInstanceId(
final String processInstanceId
) {
return getList(
"selectHistoricVariableInstanceByProcessInstanceId",
processInstanceId,
historicVariableInstanceByProcInstMatcher,
true
);
}
@Override
public List<HistoricVariableInstanceEntity> findHistoricVariableInstancesByTaskId(final String taskId) {
return getList("selectHistoricVariableInstanceByTaskId", taskId, historicVariableInstanceByTaskIdMatcher, true);
}
@Override
public long findHistoricVariableInstanceCountByQueryCriteria(
HistoricVariableInstanceQueryImpl historicProcessVariableQuery
) {
return (Long) getDbSqlSession().selectOne(
"selectHistoricVariableInstanceCountByQueryCriteria",
historicProcessVariableQuery
);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricVariableInstance> findHistoricVariableInstancesByQueryCriteria(
HistoricVariableInstanceQueryImpl historicProcessVariableQuery,
Page page
) {
return getDbSqlSession().selectList(
"selectHistoricVariableInstanceByQueryCriteria",
historicProcessVariableQuery,
page | );
}
@Override
public HistoricVariableInstanceEntity findHistoricVariableInstanceByVariableInstanceId(String variableInstanceId) {
return (HistoricVariableInstanceEntity) getDbSqlSession().selectOne(
"selectHistoricVariableInstanceByVariableInstanceId",
variableInstanceId
);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectHistoricVariableInstanceByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricVariableInstanceCountByNativeQuery", parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricVariableInstanceDataManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Person\":{" );
sb.append( "\"lastName\":\"" )
.append( lastName ).append( '\"' );
sb.append( ",\"age\":" ) | .append( age );
sb.append( ",\"boss\":" )
.append( boss );
sb.append( ",\"birth\":\"" )
.append( birth ).append( '\"' );
sb.append( ",\"map\":" )
.append( map );
sb.append( ",\"list\":" )
.append( list );
sb.append( ",\"dog\":" )
.append( dog );
sb.append( "}}" );
return sb.toString();
}
} | repos\SpringBootLearning-master (1)\springboot-config\src\main\java\com\gf\entity\Person.java | 2 |
请完成以下Java代码 | public class GatewayHttpTagsProvider implements GatewayTagsProvider {
@Override
public Tags apply(ServerWebExchange exchange) {
String outcome = "CUSTOM";
String status = "CUSTOM";
String httpStatusCodeStr = "NA";
String httpMethod = exchange.getRequest().getMethod().name();
// a non standard HTTPS status could be used. Let's be defensive here
// it needs to be checked for first, otherwise the delegate response
// who's status DIDN'T change, will be used
Integer statusInt = null;
HttpStatusCode statusCode = exchange.getResponse().getStatusCode();
if (statusCode != null) {
statusInt = statusCode.value();
if (statusInt != null) { | status = String.valueOf(statusInt);
httpStatusCodeStr = status;
HttpStatus resolved = HttpStatus.resolve(statusInt);
if (resolved != null) {
// this is not a CUSTOM status, so use series here.
outcome = resolved.series().name();
status = resolved.name();
}
}
}
return Tags.of("outcome", outcome, "status", status, "httpStatusCode", httpStatusCodeStr, "httpMethod",
httpMethod);
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\tagsprovider\GatewayHttpTagsProvider.java | 1 |
请完成以下Java代码 | protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) {
String className = type.getRawClass().getName();
if (!validator.validate(className) && !invalidTypes.contains(className)) {
invalidTypes.add(className);
}
}
protected ProcessEngineConfiguration getProcessEngineConfiguration() {
return engine.getProcessEngineConfiguration();
}
@Override
public void deleteVariable(String variableName) {
try {
removeVariableEntity(variableName);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
String errorMessage = String.format("Cannot delete %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage());
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage);
}
}
@Override
public void modifyVariables(PatchVariablesDto patch) {
VariableMap variableModifications = null;
try {
variableModifications = VariableValueDto.toMap(patch.getModifications(), engine, objectMapper);
} catch (RestException e) {
String errorMessage = String.format("Cannot modify variables for %s: %s", getResourceTypeName(), e.getMessage());
throw new InvalidRequestException(e.getStatus(), e, errorMessage);
} | List<String> variableDeletions = patch.getDeletions();
try {
updateVariableEntities(variableModifications, variableDeletions);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
String errorMessage = String.format("Cannot modify variables for %s %s: %s", getResourceTypeName(), resourceId, e.getMessage());
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage);
}
}
protected abstract VariableMap getVariableEntities(boolean deserializeValues);
protected abstract void updateVariableEntities(VariableMap variables, List<String> deletions);
protected abstract TypedValue getVariableEntity(String variableKey, boolean deserializeValue);
protected abstract void setVariableEntity(String variableKey, TypedValue variableValue);
protected abstract void removeVariableEntity(String variableKey);
protected abstract String getResourceTypeName();
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\impl\AbstractVariablesResource.java | 1 |
请完成以下Java代码 | public void setIsAllCurrencies (boolean IsAllCurrencies)
{
set_Value (COLUMNNAME_IsAllCurrencies, Boolean.valueOf(IsAllCurrencies));
}
/** Get Include All Currencies.
@return Report not just foreign currency Invoices
*/
public boolean isAllCurrencies ()
{
Object oo = get_Value(COLUMNNAME_IsAllCurrencies);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Percent.
@param Percent | Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
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_T_InvoiceGL.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final OrderLineId orderLineId = OrderLineId.ofRepoId(Check.singleElement(getSelectedIncludedRecordIds(I_C_OrderLine.class)));
final I_C_Order salesOrder = orderDAO.getById(OrderId.ofRepoId(getRecord_ID()));
final OrderLineDescriptor orderLineDescriptor = OrderLineDescriptor.builder()
.orderId(salesOrder.getC_Order_ID())
.orderLineId(orderLineId.getRepoId())
.orderBPartnerId(salesOrder.getC_BPartner_ID())
.docTypeId(salesOrder.getC_DocType_ID())
.build();
try
{
productionSimulationService.processSimulatedDemand(orderLineId, salesOrder, orderLineDescriptor);
final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(ProductionSimulationViewFactory.WINDOWID)
.setParameter(VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR, orderLineDescriptor)
.build())
.getViewId(); | getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder()
.viewId(viewId.getViewId())
.target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay)
.build());
}
catch (final Exception exception)
{
log.error("Error encountered while launching ProductionSimulationModal:", exception);
postMaterialEventService.enqueueEventNow(DeactivateAllSimulatedCandidatesEvent.builder()
.eventDescriptor(EventDescriptor.ofClientAndOrg(Env.getClientAndOrgId()))
.build());
throw AdempiereException.wrapIfNeeded(exception);
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\process\C_Order_ProductionSimulationView_Launcher.java | 1 |
请完成以下Java代码 | public JwkSourceReactiveJwtDecoderBuilder validateType(boolean shouldValidateTypHeader) {
this.typeVerifier = shouldValidateTypHeader ? JWT_TYPE_VERIFIER : NO_TYPE_VERIFIER;
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusReactiveJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link JwkSourceReactiveJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public JwkSourceReactiveJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<JWKSecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
/**
* Build the configured {@link NimbusReactiveJwtDecoder}.
* @return the configured {@link NimbusReactiveJwtDecoder}
*/
public NimbusReactiveJwtDecoder build() {
return new NimbusReactiveJwtDecoder(processor());
} | Converter<JWT, Mono<JWTClaimsSet>> processor() {
JWKSecurityContextJWKSet jwkSource = new JWKSecurityContextJWKSet();
JWSKeySelector<JWKSecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(this.jwsAlgorithm,
jwkSource);
DefaultJWTProcessor<JWKSecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
jwtProcessor.setJWSTypeVerifier(this.typeVerifier);
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return (jwt) -> {
if (jwt instanceof SignedJWT) {
return this.jwkSource.apply((SignedJWT) jwt)
.onErrorMap((e) -> new IllegalStateException("Could not obtain the keys", e))
.collectList()
.map((jwks) -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwks)));
}
throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
};
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\NimbusReactiveJwtDecoder.java | 1 |
请完成以下Java代码 | public class HashMapTest {
public static void main(String[] args) {
AtomicInteger integer = new AtomicInteger();
ExecutorService cachedThreadPool = Executors.newFixedThreadPool(50);
Map<User, Integer> map = new ConcurrentHashMap<>();
for (int i = 0; i < 10000; i++) {
cachedThreadPool.execute(() -> {
User user = new User(1);
map.put(user, 1);
});
}
}
static class User {
int age; | public User(int age) {
this.age = age;
}
@Override
public int hashCode() {
return age;
}
@Override
public String toString() {
return "" + age;
}
}
} | repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\HashMapTest.java | 1 |
请完成以下Java代码 | public AccountIdentification4ChoiceCH getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link AccountIdentification4ChoiceCH }
*
*/
public void setId(AccountIdentification4ChoiceCH value) {
this.id = value;
}
/**
* Gets the value of the ccy property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getCcy() {
return ccy;
}
/**
* Sets the value of the ccy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCcy(String value) {
this.ccy = 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\CashAccount16CHIdAndCurrency.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public InstanceExchangeFilterFunction auditLog() {
return (instance, request, next) -> next.exchange(request).doOnSubscribe((s) -> {
if (HttpMethod.DELETE.equals(request.method()) || HttpMethod.POST.equals(request.method())) {
log.info("{} for {} on {}", request.method(), instance.getId(), request.url());
}
});
}
// end::customization-instance-exchange-filter-function[]
@Bean
public CustomNotifier customNotifier(InstanceRepository repository) {
return new CustomNotifier(repository);
}
@Bean
public CustomEndpoint customEndpoint() {
return new CustomEndpoint();
}
// tag::customization-http-headers-providers[]
@Bean
public HttpHeadersProvider customHttpHeadersProvider() {
return (instance) -> {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("X-CUSTOM", "My Custom Value");
return httpHeaders;
};
} | // end::customization-http-headers-providers[]
@Bean
public HttpExchangeRepository httpTraceRepository() {
return new InMemoryHttpExchangeRepository();
}
@Bean
public AuditEventRepository auditEventRepository() {
return new InMemoryAuditEventRepository();
}
@Bean
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("org/springframework/session/jdbc/schema-hsqldb.sql")
.build();
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminServletApplication.java | 2 |
请完成以下Java代码 | public void onManualChange_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct, final ICalloutField field)
{
updateItemProduct(itemProduct);
setUOMItemProduct(itemProduct);
Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct);
}
private void updateItemProduct(final I_M_HU_PI_Item_Product itemProduct)
{
if (itemProduct.isAllowAnyProduct())
{
itemProduct.setM_Product_ID(-1);
itemProduct.setIsInfiniteCapacity(true);
}
}
private void setUOMItemProduct(final I_M_HU_PI_Item_Product huPiItemProduct)
{
final ProductId productId = ProductId.ofRepoIdOrNull(huPiItemProduct.getM_Product_ID());
if (productId == null)
{
// nothing to do
return;
} | final UomId stockingUOMId = Services.get(IProductBL.class).getStockUOMId(productId);
huPiItemProduct.setC_UOM_ID(stockingUOMId.getRepoId());
}
private void validateItemProduct(final I_M_HU_PI_Item_Product itemProduct)
{
if (Services.get(IHUCapacityBL.class).isValidItemProduct(itemProduct))
{
return;
}
final String errorMsg = Services.get(IMsgBL.class).getMsg(InterfaceWrapperHelper.getCtx(itemProduct), M_HU_PI_Item_Product.MSG_QUANTITY_INVALID);
throw new AdempiereException(errorMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU_PI_Item_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private List<I_C_CommissionSettingsLine> retrieveHierarchySettings(@NonNull final ImmutableSet<Integer> settingsRecordIds)
{
final Collection<List<I_C_CommissionSettingsLine>> allRecords = commissionSettingsLineRecordCache.getAllOrLoad(
settingsRecordIds,
this::retrieveHierarchySettings0);
return allRecords
.stream()
.flatMap(Collection::stream)
.collect(ImmutableList.toImmutableList());
}
private Map<Integer, List<I_C_CommissionSettingsLine>> retrieveHierarchySettings0(@NonNull final Collection<Integer> settingsRecordIds)
{
final List<I_C_CommissionSettingsLine> settingsLineRecords = queryBL.createQueryBuilderOutOfTrx(I_C_CommissionSettingsLine.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_C_CommissionSettingsLine.COLUMN_C_HierarchyCommissionSettings_ID, settingsRecordIds)
.orderBy(I_C_CommissionSettingsLine.COLUMN_C_HierarchyCommissionSettings_ID)
.orderBy(I_C_CommissionSettingsLine.COLUMN_SeqNo)
.create()
.list();
final HashMap<Integer, List<I_C_CommissionSettingsLine>> result = new HashMap<>();
for (final I_C_CommissionSettingsLine settingsLineRecord : settingsLineRecords)
{
final List<I_C_CommissionSettingsLine> settingsLines = result.computeIfAbsent(settingsLineRecord.getC_HierarchyCommissionSettings_ID(), ignored -> new ArrayList<I_C_CommissionSettingsLine>());
settingsLines.add(settingsLineRecord);
}
return ImmutableMap.copyOf(result);
} | @Value
@Builder
public static class StagingData
{
@NonNull
ImmutableMap<Integer, I_C_Flatrate_Term> id2TermRecord;
@NonNull
ImmutableMap<Integer, I_C_Flatrate_Conditions> id2ConditionsRecord;
@NonNull
ImmutableMap<Integer, I_C_HierarchyCommissionSettings> id2SettingsRecord;
@NonNull
ImmutableMap<Integer, I_C_CommissionSettingsLine> id2SettingsLineRecord;
@NonNull
ImmutableListMultimap<BPartnerId, FlatrateTermId> bPartnerId2FlatrateTermIds;
@NonNull
ImmutableListMultimap<Integer, BPartnerId> conditionRecordId2BPartnerIds;
@NonNull
ImmutableMultimap<Integer, Integer> settingsId2termIds;
@NonNull
ImmutableListMultimap<Integer, Integer> settingsId2settingsLineIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionConfigStagingDataService.java | 2 |
请完成以下Java代码 | public DataFetcherResult<ArticlePayload> unfavoriteArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
articleFavoriteRepository
.find(article.getId(), user.getId())
.ifPresent(
favorite -> {
articleFavoriteRepository.remove(favorite);
});
return DataFetcherResult.<ArticlePayload>newResult()
.data(ArticlePayload.newBuilder().build())
.localContext(article)
.build();
} | @DgsMutation(field = MUTATION.DeleteArticle)
public DeletionStatus deleteArticle(@InputArgument("slug") String slug) {
User user = SecurityUtil.getCurrentUser().orElseThrow(AuthenticationException::new);
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
if (!AuthorizationService.canWriteArticle(user, article)) {
throw new NoAuthorizationException();
}
articleRepository.remove(article);
return DeletionStatus.newBuilder().success(true).build();
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\ArticleMutation.java | 1 |
请完成以下Java代码 | protected Mono<Health> doHealthCheck(Health.Builder builder) {
return this.client.cluster().health((b) -> b).map((response) -> processResponse(builder, response));
}
private Health processResponse(Health.Builder builder, HealthResponse response) {
if (!response.timedOut()) {
HealthStatus status = response.status();
builder.status((HealthStatus.Red == status) ? Status.OUT_OF_SERVICE : Status.UP);
builder.withDetail("cluster_name", response.clusterName());
builder.withDetail("status", response.status().jsonValue());
builder.withDetail("timed_out", response.timedOut());
builder.withDetail("number_of_nodes", response.numberOfNodes());
builder.withDetail("number_of_data_nodes", response.numberOfDataNodes());
builder.withDetail("active_primary_shards", response.activePrimaryShards());
builder.withDetail("active_shards", response.activeShards()); | builder.withDetail("relocating_shards", response.relocatingShards());
builder.withDetail("initializing_shards", response.initializingShards());
builder.withDetail("unassigned_shards", response.unassignedShards());
builder.withDetail("delayed_unassigned_shards", response.delayedUnassignedShards());
builder.withDetail("number_of_pending_tasks", response.numberOfPendingTasks());
builder.withDetail("number_of_in_flight_fetch", response.numberOfInFlightFetch());
builder.withDetail("task_max_waiting_in_queue_millis", response.taskMaxWaitingInQueueMillis());
builder.withDetail("active_shards_percent_as_number", response.activeShardsPercentAsNumber());
builder.withDetail("unassigned_primary_shards", response.unassignedPrimaryShards());
return builder.build();
}
return builder.down().build();
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-elasticsearch\src\main\java\org\springframework\boot\data\elasticsearch\health\DataElasticsearchReactiveHealthIndicator.java | 1 |
请完成以下Java代码 | public String toString() {
StringBuilder sb = new StringBuilder();
if (namespacePrefix != null) {
sb.append(namespacePrefix);
if (name != null) {
sb.append(":").append(name);
}
} else {
sb.append(name);
}
if (value != null) {
sb.append("=").append(value);
}
return sb.toString();
} | @Override
public ExtensionAttribute clone() {
ExtensionAttribute clone = new ExtensionAttribute();
clone.setValues(this);
return clone;
}
public void setValues(ExtensionAttribute otherAttribute) {
setName(otherAttribute.getName());
setValue(otherAttribute.getValue());
setNamespacePrefix(otherAttribute.getNamespacePrefix());
setNamespace(otherAttribute.getNamespace());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ExtensionAttribute.java | 1 |
请完成以下Java代码 | public boolean isCached()
{
return true;
}
@Override
@Nullable
public String getCachePrefix()
{
return null; // not important because isCached() returns false
}
@Override
public void cacheInvalidate()
{
labelsValuesLookupDataSource.cacheInvalidate();
}
@Override
public boolean isHighVolume()
{
return false;
}
@Override
public LookupSource getLookupSourceType()
{
return LookupSource.lookup;
}
@Override
public boolean hasParameters()
{
return true;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return CtxNames.toNames(parameters);
}
@Override
public boolean isNumericKey()
{
return false;
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builder(tableName)
.putFilterById(IdsToFilter.ofSingleValue(id));
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final Object id = evalCtx.getSingleIdToFilterAsObject();
if (id == null)
{
throw new IllegalStateException("No ID provided in " + evalCtx);
}
return labelsValuesLookupDataSource.findById(id);
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(tableName)
.setRequiredParameters(parameters)
.requiresAD_Language()
.requiresUserRolePermissionsKey();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final String filter = evalCtx.getFilter();
return labelsValuesLookupDataSource.findEntities(evalCtx, filter);
}
public Set<Object> normalizeStringIds(final Set<String> stringIds)
{ | if (stringIds.isEmpty())
{
return ImmutableSet.of();
}
if (isLabelsValuesUseNumericKey())
{
return stringIds.stream()
.map(LabelsLookup::convertToInt)
.collect(ImmutableSet.toImmutableSet());
}
else
{
return ImmutableSet.copyOf(stringIds);
}
}
private static int convertToInt(final String stringId)
{
try
{
return Integer.parseInt(stringId);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting `" + stringId + "` to int.", ex);
}
}
public ColumnSql getSqlForFetchingValueIdsByLinkId(@NonNull final String tableNameOrAlias)
{
final String sql = "SELECT array_agg(" + labelsValueColumnName + ")"
+ " FROM " + labelsTableName
+ " WHERE " + labelsLinkColumnName + "=" + tableNameOrAlias + "." + linkColumnName
+ " AND IsActive='Y'";
return ColumnSql.ofSql(sql, tableNameOrAlias);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LabelsLookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Course {
@Id
@Column(name = "id")
private Long id;
@ManyToMany(mappedBy = "likedCourses")
private Set<Student> likes = new HashSet<>();
@OneToMany(mappedBy = "course")
private Set<CourseRating> ratings = new HashSet<>();
@OneToMany(mappedBy = "course")
private Set<CourseRegistration> registrations = new HashSet<>();
// additional properties
public Course() {
}
public Course(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<Student> getLikes() {
return likes;
}
public void setLikes(Set<Student> likes) {
this.likes = likes;
}
public Set<CourseRating> getRatings() {
return ratings; | }
public void setRatings(Set<CourseRating> ratings) {
this.ratings = ratings;
}
public Set<CourseRegistration> getRegistrations() {
return registrations;
}
public void setRegistrations(Set<CourseRegistration> registrations) {
this.registrations = registrations;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\Course.java | 2 |
请完成以下Java代码 | public List<TaxAmountAndType1> getTaxAmt() {
if (taxAmt == null) {
taxAmt = new ArrayList<TaxAmountAndType1>();
}
return this.taxAmt;
}
/**
* Gets the value of the adjstmntAmtAndRsn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the adjstmntAmtAndRsn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdjstmntAmtAndRsn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentAdjustment1 }
*
*
*/
public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() {
if (adjstmntAmtAndRsn == null) {
adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>();
}
return this.adjstmntAmtAndRsn;
}
/**
* Gets the value of the rmtdAmt property.
*
* @return
* possible object is | * {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() {
return rmtdAmt;
}
/**
* Sets the value of the rmtdAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.rmtdAmt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\RemittanceAmount2.java | 1 |
请完成以下Java代码 | public static DurationStyle detect(String value) {
Assert.notNull(value, "'value' must not be null");
for (DurationStyle candidate : values()) {
if (candidate.matches(value)) {
return candidate;
}
}
throw new IllegalArgumentException("'" + value + "' is not a valid duration");
}
/**
* Units that we support.
*/
enum Unit {
/**
* Nanoseconds.
*/
NANOS(ChronoUnit.NANOS, "ns", Duration::toNanos),
/**
* Microseconds.
*/
MICROS(ChronoUnit.MICROS, "us", (duration) -> duration.toNanos() / 1000L),
/**
* Milliseconds.
*/
MILLIS(ChronoUnit.MILLIS, "ms", Duration::toMillis),
/**
* Seconds.
*/
SECONDS(ChronoUnit.SECONDS, "s", Duration::getSeconds),
/**
* Minutes.
*/
MINUTES(ChronoUnit.MINUTES, "m", Duration::toMinutes),
/**
* Hours.
*/
HOURS(ChronoUnit.HOURS, "h", Duration::toHours),
/**
* Days.
*/
DAYS(ChronoUnit.DAYS, "d", Duration::toDays);
private final ChronoUnit chronoUnit;
private final String suffix;
private final Function<Duration, Long> longValue; | Unit(ChronoUnit chronoUnit, String suffix, Function<Duration, Long> toUnit) {
this.chronoUnit = chronoUnit;
this.suffix = suffix;
this.longValue = toUnit;
}
public Duration parse(String value) {
return Duration.of(Long.parseLong(value), this.chronoUnit);
}
public String print(Duration value) {
return longValue(value) + this.suffix;
}
public long longValue(Duration value) {
return this.longValue.apply(value);
}
public static Unit fromChronoUnit(@Nullable ChronoUnit chronoUnit) {
if (chronoUnit == null) {
return Unit.MILLIS;
}
for (Unit candidate : values()) {
if (candidate.chronoUnit == chronoUnit) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit " + chronoUnit);
}
public static Unit fromSuffix(String suffix) {
for (Unit candidate : values()) {
if (candidate.suffix.equalsIgnoreCase(suffix)) {
return candidate;
}
}
throw new IllegalArgumentException("Unknown unit '" + suffix + "'");
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DurationStyle.java | 1 |
请完成以下Java代码 | public class StringStartsWithFilter<T> implements IQueryFilter<T>, ISqlQueryFilter
{
@NonNull private final ModelColumnNameValue<T> operand;
@NonNull private final String prefix;
private boolean sqlBuilt = false;
private String sqlWhereClause = null;
private List<Object> sqlParams = null;
public StringStartsWithFilter(
@NonNull final String columnName,
@NonNull final String prefix)
{
if (prefix.isEmpty())
{
throw new AdempiereException("Prefix must be not empty");
}
this.operand = ModelColumnNameValue.forColumnName(columnName);
this.prefix = prefix;
}
@Override
public boolean accept(final T model)
{
final Object value = operand.getValue(model);
return value != null && value.toString().startsWith(prefix);
}
@Override
public final String getSql()
{
buildSql(); | return sqlWhereClause;
}
@Override
public final List<Object> getSqlParams(final Properties ctx_NOTUSED)
{
return getSqlParams();
}
public final List<Object> getSqlParams()
{
buildSql();
return sqlParams;
}
private void buildSql()
{
if (sqlBuilt)
{
return;
}
final String sqlLikeValue = prefix.replace("%", "\\%") + "%";
sqlWhereClause = operand.getColumnName() + " LIKE ? ESCAPE '\\'";
sqlParams = Collections.singletonList(sqlLikeValue);
sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringStartsWithFilter.java | 1 |
请完成以下Java代码 | public void setApplyFeeTo (final String ApplyFeeTo)
{
set_Value (COLUMNNAME_ApplyFeeTo, ApplyFeeTo);
}
@Override
public String getApplyFeeTo()
{
return get_ValueAsString(COLUMNNAME_ApplyFeeTo);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_QualityInsp_LagerKonf_AdditionalFee_ID (final int M_QualityInsp_LagerKonf_AdditionalFee_ID)
{
if (M_QualityInsp_LagerKonf_AdditionalFee_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID, M_QualityInsp_LagerKonf_AdditionalFee_ID);
}
@Override
public int getM_QualityInsp_LagerKonf_AdditionalFee_ID()
{
return get_ValueAsInt(COLUMNNAME_M_QualityInsp_LagerKonf_AdditionalFee_ID);
}
@Override
public I_M_QualityInsp_LagerKonf_Version getM_QualityInsp_LagerKonf_Version()
{
return get_ValueAsPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class);
}
@Override
public void setM_QualityInsp_LagerKonf_Version(final I_M_QualityInsp_LagerKonf_Version M_QualityInsp_LagerKonf_Version) | {
set_ValueFromPO(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, I_M_QualityInsp_LagerKonf_Version.class, M_QualityInsp_LagerKonf_Version);
}
@Override
public void setM_QualityInsp_LagerKonf_Version_ID (final int M_QualityInsp_LagerKonf_Version_ID)
{
if (M_QualityInsp_LagerKonf_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, M_QualityInsp_LagerKonf_Version_ID);
}
@Override
public int getM_QualityInsp_LagerKonf_Version_ID()
{
return get_ValueAsInt(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_AdditionalFee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
private static Log log = LogFactory.getLog(User.class);
@Id
@GeneratedValue
private int id;
private String userName;
private String firstName;
private String lastName;
@Transient
private String fullName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName() {
return fullName; | }
@PrePersist
public void logNewUserAttempt() {
log.info("Attempting to add new user with username: " + userName);
}
@PostPersist
public void logNewUserAdded() {
log.info("Added user '" + userName + "' with ID: " + id);
}
@PreRemove
public void logUserRemovalAttempt() {
log.info("Attempting to delete user: " + userName);
}
@PostRemove
public void logUserRemoval() {
log.info("Deleted user: " + userName);
}
@PreUpdate
public void logUserUpdateAttempt() {
log.info("Attempting to update user: " + userName);
}
@PostUpdate
public void logUserUpdate() {
log.info("Updated user: " + userName);
}
@PostLoad
public void logUserLoad() {
fullName = firstName + " " + lastName;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-annotations\src\main\java\com\baeldung\lifecycleevents\model\User.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AvailableToPromiseResultGroup build()
{
return AvailableToPromiseResultGroup.builder()
.bpartner(bpartner)
.warehouse(warehouse)
.productId(productId)
.storageAttributesKey(storageAttributesKey)
.qty(qty)
.build();
}
/**
* IMPORTANT: supposed to be used only from {@link AvailableToPromiseRepository},
* because it needs to be sure that the callers know what they do;
* in particular the requests be applied to applied in a particular ordering, with the no-bpartner-requests last.
* <p>
* Returns true if the given {@code request}
* <li>has no bPartnerID (i.e. are applicable to) all partners,
* <li>and has the same product, attributes and warehouse
* <li>and has a date not after this result group's date.
*
* That's because those "bpartner-unspecific" requests' quantities are already in the respective later specific requests.
* <p>
* Also see the service in materialdispo-services that is responsible for updating stock-candidates
*/
boolean isAlreadyIncluded(@NonNull final AddToResultGroupRequest request)
{
// assume it's matching
// if (!isMatchting(request))
// {
// return false; // only matching requests were ever included
// }
if (request.getBpartner().isSpecificBPartner())
{
return false;
}
final ArrayKey key = request.computeKey();
if (!includedRequestKeys.containsKey(key))
{
return false; | }
final DateAndSeqNo dateAndSeq = includedRequestKeys.get(key);
// if our bpartnerless request is "earlier" than the latest request (with same key) that we already added, then the quantity of the bpartnerless request is contained within that other request which we already added
return DateAndSeqNo.ofAddToResultGroupRequest(request).isBefore(dateAndSeq);
}
public void addQty(@NonNull final AddToResultGroupRequest request)
{
qty = qty.add(request.getQty());
final ArrayKey computeKey = request.computeKey();
final DateAndSeqNo oldTimeAndSeqNo = includedRequestKeys.get(computeKey);
final DateAndSeqNo latest = DateAndSeqNo.ofAddToResultGroupRequest(request).max(oldTimeAndSeqNo);
includedRequestKeys.put(computeKey, latest);
}
boolean isZeroQty()
{
return getQty().signum() == 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultGroupBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected Object extractModelToEnqueueFromItem(final Collector collector, final BPartnerToUpdate item)
{
return TableRecordReference.of(I_C_BPartner.Table_Name, item.getBpartnerId());
}
@Override
protected Map<String, Object> extractParametersFromItem(BPartnerToUpdate item)
{
return ImmutableMap.of(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP, item.isAlsoResetCreditStatusFromBPGroup());
}
};
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workpackage, final String localTrxName)
{
// Services
final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class);
final List<I_C_BPartner> bpartners = retrieveAllItems(I_C_BPartner.class);
final boolean alsoSetCreditStatusBaseOnBPGroup = getParameters().getParameterAsBool(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP); | for (final I_C_BPartner bpartner : bpartners)
{
if (alsoSetCreditStatusBaseOnBPGroup)
{
Services.get(IBPartnerStatsBL.class).resetCreditStatusFromBPGroup(bpartner);
}
final BPartnerStats stats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(bpartner);
bpartnerStatsDAO.updateBPartnerStatistics(stats);
}
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\service\async\spi\impl\C_BPartner_UpdateStatsFromBPartner.java | 2 |
请完成以下Java代码 | public LiteralExpression getDefaultOutputEntry() {
return defaultOutputEntry;
}
public void setDefaultOutputEntry(LiteralExpression defaultOutputEntry) {
this.defaultOutputEntry = defaultOutputEntry;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTypeRef() { | return typeRef;
}
public void setTypeRef(String typeRef) {
this.typeRef = typeRef;
}
public int getOutputNumber() {
return outputNumber;
}
public void setOutputNumber(int outputNumber) {
this.outputNumber = outputNumber;
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\OutputClause.java | 1 |
请完成以下Java代码 | public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
public org.compiere.model.I_EXP_Processor getEXP_Processor() throws RuntimeException
{
return (org.compiere.model.I_EXP_Processor)MTable.get(getCtx(), org.compiere.model.I_EXP_Processor.Table_Name)
.getPO(getEXP_Processor_ID(), get_TrxName()); }
/** Set Export Processor.
@param EXP_Processor_ID Export Processor */
public void setEXP_Processor_ID (int EXP_Processor_ID)
{
if (EXP_Processor_ID < 1)
set_Value (COLUMNNAME_EXP_Processor_ID, null);
else
set_Value (COLUMNNAME_EXP_Processor_ID, Integer.valueOf(EXP_Processor_ID));
}
/** Get Export Processor.
@return Export Processor */
public int getEXP_Processor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_Processor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{ | set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReplicationStrategy.java | 1 |
请完成以下Java代码 | public void registerFactories()
{
Services.get(IShipmentScheduleHandlerBL.class).registerVetoer(new ShipmentScheduleFromSubscriptionOrderLineVetoer(), I_C_OrderLine.Table_Name);
Services.get(IShipmentScheduleHandlerBL.class).registerVetoer(new ShipmentScheduleCallOrderVetoer(callOrderContractService), I_C_OrderLine.Table_Name);
Services.get(IShipmentScheduleHandlerBL.class).registerHandler(new SubscriptionShipmentScheduleHandler());
Services.get(IShipmentScheduleUpdater.class).registerCandidateProcessor(new ShipmentScheduleSubscriptionProcessor());
// material balance matcher
Services.get(IMaterialBalanceConfigBL.class).addMaterialBalanceConfigMather(new FlatrateMaterialBalanceConfigMatcher());
Services.get(IImportProcessFactory.class).registerImportProcess(I_I_Flatrate_Term.class, FlatrateTermImportProcess.class);
ExcludeSubscriptionOrderLines.registerFilterForInvoiceCandidateCreation();
registerInOutLinesWithMissingInvoiceCandidateFilter();
final IInvoiceCandidateListeners invoiceCandidateListeners = Services.get(IInvoiceCandidateListeners.class);
invoiceCandidateListeners.addListener(FlatrateTermInvoiceCandidateListener.instance);
}
/**
* Make sure that no {@link I_C_Invoice_Candidate}s are created for inout lines that belong to a subscription contract.
*/
private void registerInOutLinesWithMissingInvoiceCandidateFilter()
{
final IQueryFilter<I_M_InOutLine> filter = Services.get(IQueryBL.class)
.createCompositeQueryFilter(I_M_InOutLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(de.metas.contracts.model.I_M_InOutLine.COLUMNNAME_C_SubscriptionProgress_ID, null);
inoutLinesWithMissingInvoiceCandidateRepo.addAdditionalFilter(filter);
}
@Override
protected void registerInterceptors(final IModelValidationEngine engine)
{
engine.addModelValidator(C_Flatrate_Conditions.INSTANCE);
engine.addModelValidator(C_SubscriptionProgress.instance); | engine.addModelValidator(C_Flatrate_DataEntry.instance);
engine.addModelValidator(C_Flatrate_Matching.instance);
engine.addModelValidator(new C_Flatrate_Term(contractOrderService, documentLocationBL, glCategoryRepository));
engine.addModelValidator(new C_Invoice_Candidate());
engine.addModelValidator(new C_Invoice_Clearing_Alloc());
engine.addModelValidator(new C_Order());
engine.addModelValidator(new C_OrderLine(groupChangesHandler));
engine.addModelValidator(new C_Invoice_Rejection_Detail());
engine.addModelValidator(new C_BPartner_Location());
// 03742
engine.addModelValidator(new C_Flatrate_Transition());
// 04360
engine.addModelValidator(new C_Period());
engine.addModelValidator(new M_InOutLine());
engine.addModelValidator(new M_ShipmentSchedule_QtyPicked());
// 09869
engine.addModelValidator(M_ShipmentSchedule.INSTANCE);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\MainValidator.java | 1 |
请完成以下Java代码 | public void deleteCandidateStarterGroup(String caseDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForCaseDefinitionCmd(caseDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterUser(String caseDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForCaseDefinitionCmd(caseDefinitionId, userId, null));
}
@Override
public List<IdentityLink> getIdentityLinksForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForCaseDefinitionCmd(caseDefinitionId));
}
@Override
public void setCaseDefinitionCategory(String caseDefinitionId, String category) {
commandExecutor.execute(new SetCaseDefinitionCategoryCmd(caseDefinitionId, category)); | }
@Override
public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) {
commandExecutor.execute(new SetDeploymentParentDeploymentIdCmd(deploymentId, newParentDeploymentId));
}
@Override
public List<DmnDecision> getDecisionsForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetDecisionsForCaseDefinitionCmd(caseDefinitionId));
}
@Override
public List<FormDefinition> getFormDefinitionsForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetFormDefinitionsForCaseDefinitionCmd(caseDefinitionId));
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnRepositoryServiceImpl.java | 1 |
请完成以下Java代码 | private ObjectMapper newObjectMapper() {
return new ObjectMapper();
}
/**
* Returns a reference to the configured {@link JsonToPdxConverter} used to convert from a single object,
* {@literal JSON} {@link String} to PDX (i.e. as a {@link PdxInstance}.
*
* @return a reference to the configured {@link JsonToPdxConverter}; never {@literal null}.
* @see org.springframework.geode.data.json.converter.JsonToPdxConverter
*/
protected @NonNull JsonToPdxConverter getJsonToPdxConverter() {
return this.converter;
}
/**
* Returns a reference to the configured Jackson {@link ObjectMapper}.
*
* @return a reference to the configured Jackson {@link ObjectMapper}; never {@literal null}.
* @see com.fasterxml.jackson.databind.ObjectMapper
*/
protected @NonNull ObjectMapper getObjectMapper() {
return this.objectMapper;
}
/**
* Converts the given {@link String JSON} containing multiple objects into an array of {@link PdxInstance} objects.
*
* @param json {@link String JSON} data to convert.
* @return an array of {@link PdxInstance} objects from the given {@link String JSON}.
* @throws IllegalStateException if the {@link String JSON} does not start with
* either a JSON array or a JSON object.
* @see org.apache.geode.pdx.PdxInstance
*/
@Nullable @Override
public PdxInstance[] convert(String json) {
try {
JsonNode jsonNode = getObjectMapper().readTree(json);
List<PdxInstance> pdxList = new ArrayList<>();
if (isArray(jsonNode)) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
JsonToPdxConverter converter = getJsonToPdxConverter();
for (JsonNode object : asIterable(CollectionUtils.nullSafeIterator(arrayNode.elements()))) {
pdxList.add(converter.convert(object.toString()));
}
}
else if (isObject(jsonNode)) {
ObjectNode objectNode = (ObjectNode) jsonNode; | pdxList.add(getJsonToPdxConverter().convert(objectNode.toString()));
}
else {
String message = String.format("Unable to process JSON node of type [%s];"
+ " expected either an [%s] or an [%s]", jsonNode.getNodeType(),
JsonNodeType.OBJECT, JsonNodeType.ARRAY);
throw new IllegalStateException(message);
}
return pdxList.toArray(new PdxInstance[0]);
}
catch (JsonProcessingException cause) {
throw new DataRetrievalFailureException("Failed to read JSON content", cause);
}
}
private boolean isArray(@Nullable JsonNode node) {
return node != null && (node.isArray() || JsonNodeType.ARRAY.equals(node.getNodeType()));
}
private boolean isObject(@Nullable JsonNode node) {
return node != null && (node.isObject() || JsonNodeType.OBJECT.equals(node.getNodeType()));
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToPdxConverter.java | 1 |
请完成以下Java代码 | public String getZip() {
return zip;
}
void setZip(String zip) {
this.zip = zip;
this.persisted = true;
}
public void setId(String zip) {
this.zip = zip;
this.persisted = false;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county; | }
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
@JsonIgnore
@Override public String getId() {
return zip;
}
@JsonIgnore
@Override public boolean isNew() {
return !persisted;
}
} | repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\domain\ZipCode.java | 1 |
请完成以下Java代码 | private List<Object> retrieveNextOrNull()
{
final ResultSet rs = getResultSet(); // NOPMD by tsa on 3/17/13 1:11 PM
List<Object> row = null;
boolean ok = false;
try
{
if (!rs.next())
{
// close(); // no need to close it if there is no more data to read because it will be closed in finally block
return null;
}
row = readLine(rs, sqlFields);
ok = true;
}
catch (SQLException e)
{
close();
throw new DBException(e);
}
finally
{
if (!ok)
{
close();
}
}
return row;
}
@Override
public void prepare()
{
// Just opening the ResultSet if is not already opened.
// Following method will make sure that the ResultSet was not already opened and closed.
getResultSet();
}
@Override
public List<String> getFieldNames()
{
return fields;
}
@Override
public void close()
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
DB.close(conn);
conn = null;
currentRow = null;
closed = true;
}
@Override
public boolean hasNext()
{
if (currentRow == null)
{
currentRow = retrieveNextOrNull();
}
return currentRow != null;
}
@Override
public List<Object> next()
{
if (currentRow != null)
{
final List<Object> rowToReturn = currentRow;
currentRow = null;
return rowToReturn;
}
currentRow = retrieveNextOrNull();
if (currentRow == null)
{
throw new NoSuchElementException();
}
return currentRow;
} | @Override
public void remove()
{
throw new UnsupportedOperationException();
}
private List<Object> readLine(ResultSet rs, List<String> sqlFields) throws SQLException
{
final List<Object> values = new ArrayList<Object>();
for (final String columnName : sqlFields)
{
final Object value = rs.getObject(columnName);
values.add(value);
}
return values;
}
private Integer rowsCount = null;
@Override
public int size()
{
if (Check.isEmpty(sqlCount, true))
{
throw new IllegalStateException("Counting is not supported");
}
if (rowsCount == null)
{
logger.info("SQL: {}", sqlCount);
logger.info("SQL Params: {}", sqlParams);
rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams);
logger.info("Rows Count: {}" + rowsCount);
}
return rowsCount;
}
public String getSqlSelect()
{
return sqlSelect;
}
public List<Object> getSqlParams()
{
if (sqlParams == null)
{
return Collections.emptyList();
}
return sqlParams;
}
public String getSqlWhereClause()
{
return sqlWhereClause;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java | 1 |
请完成以下Java代码 | public static void pushOperationUsingDBObject() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName);
DBObject listItem = new BasicDBObject("items", new BasicDBObject("itemName", "PIZZA MANIA").append("quantity", 1)
.append("price", 800));
BasicDBObject searchFilter = new BasicDBObject("customerId", 1023);
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$push", listItem);
UpdateResult updateResult = collection.updateOne(searchFilter, updateQuery);
System.out.println("updateResult:- " + updateResult);
}
public static void pushOperationUsingDocument() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName);
Document item = new Document().append("itemName", "PIZZA MANIA")
.append("quantity", 1)
.append("price", 800);
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.push("items", item));
System.out.println("updateResult:- " + updateResult);
}
public static void addToSetOperation() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName);
Document item = new Document().append("itemName", "PIZZA MANIA")
.append("quantity", 1)
.append("price", 800);
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
System.out.println("updateResult:- " + updateResult);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp(); | //
// Push document into the array using DBObject
//
pushOperationUsingDBObject();
//
// Push document into the array using Document.
//
pushOperationUsingDocument();
//
// Push document into the array using addToSet operator.
//
addToSetOperation();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\PushOperations.java | 1 |
请完成以下Java代码 | public class SLAMeasureProcess extends JavaProcess
{
/** Goal */
private int p_PA_SLA_Measure_ID;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else
log.error("prepare - Unknown Parameter: " + name);
}
p_PA_SLA_Measure_ID = getRecord_ID();
} // prepare
/**
* Process
* @return info
* @throws Exception
*/
protected String doIt () throws Exception
{
log.info("PA_SLA_Measure_ID=" + p_PA_SLA_Measure_ID);
MSLAMeasure measure = new MSLAMeasure (getCtx(), p_PA_SLA_Measure_ID, get_TrxName());
if (measure.get_ID() == 0)
throw new AdempiereUserError("@PA_SLA_Measure_ID@ " + p_PA_SLA_Measure_ID); | MSLAGoal goal = new MSLAGoal(getCtx(), measure.getPA_SLA_Goal_ID(), get_TrxName());
if (goal.get_ID() == 0)
throw new AdempiereUserError("@PA_SLA_Goal_ID@ " + measure.getPA_SLA_Goal_ID());
MSLACriteria criteria = MSLACriteria.get(getCtx(), goal.getPA_SLA_Criteria_ID(), get_TrxName());
if (criteria.get_ID() == 0)
throw new AdempiereUserError("@PA_SLA_Criteria_ID@ " + goal.getPA_SLA_Criteria_ID());
SLACriteria pgm = criteria.newSLACriteriaInstance();
//
goal.setMeasureActual(pgm.calculateMeasure(goal));
goal.setDateLastRun(new Timestamp(System.currentTimeMillis()));
goal.save();
//
return "@MeasureActual@=" + goal.getMeasureActual();
} // doIt
} // SLAMeasureProcess | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\sla\SLAMeasureProcess.java | 1 |
请完成以下Java代码 | public void setData_Export_Audit_ID (final int Data_Export_Audit_ID)
{
if (Data_Export_Audit_ID < 1)
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID);
}
@Override
public int getData_Export_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID);
}
@Override
public org.compiere.model.I_Data_Export_Audit getData_Export_Audit_Parent()
{
return get_ValueAsPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class);
}
@Override
public void setData_Export_Audit_Parent(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit_Parent)
{
set_ValueFromPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit_Parent);
}
@Override
public void setData_Export_Audit_Parent_ID (final int Data_Export_Audit_Parent_ID)
{
if (Data_Export_Audit_Parent_ID < 1)
set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, null); | else
set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, Data_Export_Audit_Parent_ID);
}
@Override
public int getData_Export_Audit_Parent_ID()
{
return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Parent_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit.java | 1 |
请完成以下Java代码 | public AuthUser getAuthUser(HttpServletRequest request) {
HttpSession session = request.getSession();
Object sentinelUserObj = session.getAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY);
if (sentinelUserObj != null && sentinelUserObj instanceof AuthUser) {
return (AuthUser) sentinelUserObj;
}
return null;
}
public static final class SimpleWebAuthUserImpl implements AuthUser {
private String username;
public SimpleWebAuthUserImpl(String username) {
this.username = username;
}
@Override
public boolean authTarget(String target, PrivilegeType privilegeType) {
return true;
}
@Override
public boolean isSuperUser() {
return true;
}
@Override | public String getNickName() {
return username;
}
@Override
public String getLoginName() {
return username;
}
@Override
public String getId() {
return username;
}
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\auth\SimpleWebAuthServiceImpl.java | 1 |
请完成以下Java代码 | public class M_ShipmentSchedule_OpenProcessed extends JavaProcess implements IProcessPrecondition
{
// Services
private final transient IQueryBL queryBL = Services.get(IQueryBL.class);
private final transient IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class);
private static final AdMessageKey MSG_SHIPMENT_SCHEDULES_ALL_NOT_PROCESSED = AdMessageKey.of("M_ShipmentSchedule_OpenProcessed.ShipmentSchedulesAllNotProcessed");
private static final AdMessageKey MSG_SHIPMENT_SCHEDULES_SKIP_OPEN = AdMessageKey.of("M_ShipmentSchedule_OpenProcessed.SkipOpen_1P");
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
// Make sure at least one shipment schedule is processed
final boolean someSchedsAreProcessed = context.streamSelectedModels(I_M_ShipmentSchedule.class)
.anyMatch(I_M_ShipmentSchedule::isProcessed);
if (!someSchedsAreProcessed)
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_SHIPMENT_SCHEDULES_ALL_NOT_PROCESSED));
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final Iterator<I_M_ShipmentSchedule> scheds = getSelectedShipmentSchedules();
int counter = 0;
for (final I_M_ShipmentSchedule shipmentSchedule : IteratorUtils.asIterable(scheds))
{
if (!shipmentSchedule.isProcessed())
{
addLog(msgBL.getMsg(getCtx(), MSG_SHIPMENT_SCHEDULES_SKIP_OPEN, new Object[] { shipmentSchedule.getM_ShipmentSchedule_ID() }));
continue;
}
openInTrx(shipmentSchedule);
counter++;
}
return "@Processed@: " + counter; | }
private Iterator<I_M_ShipmentSchedule> getSelectedShipmentSchedules()
{
final IQueryFilter<I_M_ShipmentSchedule> selectedSchedsFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
return queryBL.createQueryBuilder(I_M_ShipmentSchedule.class)
.addOnlyActiveRecordsFilter()
.filter(selectedSchedsFilter)
.create()
.iterate(I_M_ShipmentSchedule.class);
}
private void openInTrx(final I_M_ShipmentSchedule shipmentSchedule)
{
Services.get(ITrxManager.class)
.runInNewTrx((TrxRunnable)localTrxName -> {
InterfaceWrapperHelper.setThreadInheritedTrxName(shipmentSchedule);
shipmentScheduleBL.openShipmentSchedule(shipmentSchedule);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_OpenProcessed.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class AlreadyInitializedAppEngineConfiguration {
@Bean
public EventRegistryEngine eventRegistryEngine(@SuppressWarnings("unused") AppEngine appEngine) {
// The app engine needs to be injected, as otherwise it won't be initialized, which means that the EventRegistryEngine is not initialized yet
if (!EventRegistryEngines.isInitialized()) {
throw new IllegalStateException("Event registry has not been initialized");
}
return EventRegistryEngines.getDefaultEventRegistryEngine();
}
}
/**
* If there is no process engine configuration, then trigger a creation of the event registry.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(type = {
"org.flowable.eventregistry.impl.EventRegistryEngine",
"org.flowable.engine.ProcessEngine",
"org.flowable.app.engine.AppEngine"
})
static class StandaloneEventRegistryConfiguration extends BaseEngineConfigurationWithConfigurers<SpringEventRegistryEngineConfiguration> {
@Bean
public EventRegistryFactoryBean formEngine(SpringEventRegistryEngineConfiguration eventEngineConfiguration) { | EventRegistryFactoryBean factory = new EventRegistryFactoryBean();
factory.setEventEngineConfiguration(eventEngineConfiguration);
invokeConfigurers(eventEngineConfiguration);
return factory;
}
}
@Bean
public EventRepositoryService eventRepositoryService(EventRegistryEngine eventRegistryEngine) {
return eventRegistryEngine.getEventRepositoryService();
}
@Bean
public EventManagementService eventManagementService(EventRegistryEngine eventRegistryEngine) {
return eventRegistryEngine.getEventManagementService();
}
@Bean
public EventRegistry eventRegistry(EventRegistryEngine eventRegistryEngine) {
return eventRegistryEngine.getEventRegistry();
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\eventregistry\EventRegistryServicesAutoConfiguration.java | 2 |
请完成以下Java代码 | public @Nullable RewriteFunction getRewriteFunction() {
return rewriteFunction;
}
public Config setRewriteFunction(RewriteFunction rewriteFunction) {
this.rewriteFunction = rewriteFunction;
return this;
}
public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass,
RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public <T, R> Config setRewriteFunction(ParameterizedTypeReference<T> inClass, | ParameterizedTypeReference<R> outClass, RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
public @Nullable String getContentType() {
return contentType;
}
public Config setContentType(@Nullable String contentType) {
this.contentType = contentType;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\ModifyRequestBodyGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public static void recognition(List<Vertex> segResult, WordNet wordNetOptimum, WordNet wordNetAll)
{
StringBuilder sbName = new StringBuilder();
int appendTimes = 0;
ListIterator<Vertex> listIterator = segResult.listIterator();
listIterator.next();
int line = 1;
int activeLine = 1;
while (listIterator.hasNext())
{
Vertex vertex = listIterator.next();
if (appendTimes > 0)
{
if (vertex.guessNature() == Nature.nrf || TranslatedPersonDictionary.containsKey(vertex.realWord))
{
sbName.append(vertex.realWord);
++appendTimes;
}
else
{
// 识别结束
if (appendTimes > 1)
{
if (HanLP.Config.DEBUG)
{
System.out.println("音译人名识别出:" + sbName.toString());
}
wordNetOptimum.insert(activeLine, new Vertex(Predefine.TAG_PEOPLE, sbName.toString(), new CoreDictionary.Attribute(Nature.nrf), WORD_ID), wordNetAll); | }
sbName.setLength(0);
appendTimes = 0;
}
}
else
{
// nrf触发识别
if (vertex.guessNature() == Nature.nrf
// || TranslatedPersonDictionary.containsKey(vertex.realWord)
)
{
sbName.append(vertex.realWord);
++appendTimes;
activeLine = line;
}
}
line += vertex.realWord.length();
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\recognition\nr\TranslatedPersonRecognition.java | 1 |
请完成以下Java代码 | public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result; | }
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\model\Product.java | 1 |
请完成以下Java代码 | public void setPP_Order_Node_ID(final int PP_Order_Node_ID)
{
if (PP_Order_Node_ID < 1)
set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, null);
else
set_ValueNoCheck(COLUMNNAME_PP_Order_Node_ID, PP_Order_Node_ID);
}
@Override
public int getPP_Order_Node_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Node_Product_ID);
}
@Override
public void setPP_Order_Node_Product_ID(final int PP_Order_Node_Product_ID)
{
if (PP_Order_Node_Product_ID < 1)
set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, null);
else
set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, PP_Order_Node_Product_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class);
}
@Override
public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow);
}
@Override
public int getPP_Order_Workflow_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID);
}
@Override
public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID)
{
if (PP_Order_Workflow_ID < 1)
set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null);
else
set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty(final @Nullable BigDecimal Qty)
{
set_Value(COLUMNNAME_Qty, Qty);
}
@Override | public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNo(final int SeqNo)
{
set_Value(COLUMNNAME_SeqNo, SeqNo);
}
@Override
public java.lang.String getSpecification()
{
return get_ValueAsString(COLUMNNAME_Specification);
}
@Override
public void setSpecification(final @Nullable java.lang.String Specification)
{
set_Value(COLUMNNAME_Specification, Specification);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setYield(final @Nullable BigDecimal Yield)
{
set_Value(COLUMNNAME_Yield, Yield);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java | 1 |
请完成以下Java代码 | public void delete(@NonNull final DDOrderCandidateAllocList list)
{
final Set<Integer> ids = list.getIds();
if (ids.isEmpty())
{
return;
}
queryBL.createQueryBuilder(I_DD_Order_Candidate_DDOrder.class)
.addInArrayFilter(I_DD_Order_Candidate_DDOrder.COLUMN_DD_Order_Candidate_DDOrder_ID, ids)
.create()
.delete();
}
public void deleteByQuery(@NonNull final DeleteDDOrderCandidateAllocQuery deleteAllocQuery)
{
final IQueryBuilder<I_DD_Order_Candidate_DDOrder> queryBuilder = queryBL.createQueryBuilder(I_DD_Order_Candidate_DDOrder.class);
if (deleteAllocQuery.getDdOrderCandidateId() != null)
{
queryBuilder.addEqualsFilter(I_DD_Order_Candidate_DDOrder.COLUMNNAME_DD_Order_Candidate_ID, deleteAllocQuery.getDdOrderCandidateId());
}
if (deleteAllocQuery.getDdOrderLineId() != null)
{
queryBuilder.addEqualsFilter(I_DD_Order_Candidate_DDOrder.COLUMNNAME_DD_OrderLine_ID, deleteAllocQuery.getDdOrderLineId());
}
if (queryBuilder.getCompositeFilter().isEmpty())
{
throw new AdempiereException("Deleting all DD_Order_Candidate_DDOrder records is not allowed!");
}
queryBuilder.create().delete();
}
@Value(staticConstructor = "of")
private static class DDOrderCandidateAllocKey | {
@NonNull DDOrderCandidateId ddOrderCandidateId;
@NonNull DDOrderAndLineId ddOrderAndLineId;
}
private static DDOrderCandidateAllocKey extractKey(final DDOrderCandidateAlloc alloc)
{
return DDOrderCandidateAllocKey.of(alloc.getDdOrderCandidateId(), alloc.getDdOrderAndLineId());
}
private static DDOrderCandidateAllocKey extractKey(final I_DD_Order_Candidate_DDOrder record)
{
return DDOrderCandidateAllocKey.of(extractDDOrderCandidateId(record), extractDDOrderAndLineId(record));
}
private static DDOrderCandidateId extractDDOrderCandidateId(final I_DD_Order_Candidate_DDOrder record)
{
return DDOrderCandidateId.ofRepoId(record.getDD_Order_Candidate_ID());
}
private static DDOrderAndLineId extractDDOrderAndLineId(final I_DD_Order_Candidate_DDOrder record)
{
return DDOrderAndLineId.ofRepoIds(record.getDD_Order_ID(), record.getDD_OrderLine_ID());
}
private static void updateRecord(final I_DD_Order_Candidate_DDOrder record, final DDOrderCandidateAlloc from)
{
//record.setAD_Org_ID(??);
record.setIsActive(true);
record.setDD_Order_Candidate_ID(from.getDdOrderCandidateId().getRepoId());
record.setDD_Order_ID(from.getDdOrderAndLineId().getDdOrderId().getRepoId());
record.setDD_OrderLine_ID(from.getDdOrderAndLineId().getDdOrderLineId().getRepoId());
record.setC_UOM_ID(from.getQty().getUomId().getRepoId());
record.setQty(from.getQty().toBigDecimal());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\DDOrderCandidateAllocRepository.java | 1 |
请完成以下Java代码 | private void updateStatus()
{
this.status = computeStatus();
}
private DDOrderMoveScheduleStatus computeStatus()
{
if (isDropTo())
{
return DDOrderMoveScheduleStatus.COMPLETED;
}
else if (isPickedFrom())
{
return DDOrderMoveScheduleStatus.IN_PROGRESS;
}
else
{
return DDOrderMoveScheduleStatus.NOT_STARTED;
}
}
@NonNull
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{ | if (pickedHUs == null)
{
return ExplainedOptional.emptyBecause("Schedule is not picked yet");
}
return pickedHUs.getInTransitLocatorId();
}
@NonNull
public ImmutableSet<HuId> getPickedHUIds()
{
final DDOrderMoveSchedulePickedHUs pickedHUs = Check.assumeNotNull(this.pickedHUs, "Expected to be already picked: {}", this);
return pickedHUs.getActualHUIdsPicked();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedule.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-provider
cloud:
# Sentinel 配置项,对应 SentinelProperties 配置属性类
sentinel:
enabled: true # 是否开启。默认为 true 开启
eager: true # 是否饥饿加载。默认为 false 关闭
transport:
da | shboard: 127.0.0.1:7070 # Sentinel 控制台地址
filter:
url-patterns: /** # 拦截请求的地址。默认为 /* | repos\SpringBoot-Labs-master\labx-04-spring-cloud-alibaba-sentinel\labx-04-sca-sentinel-demo01-provider\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public class DecisionDefinitionHandler extends DmnDecisionTransformHandler {
protected boolean skipEnforceTtl = false;
@Override
protected DmnDecisionImpl createDmnElement() {
return new DecisionDefinitionEntity();
}
@Override
protected DmnDecisionImpl createFromDecision(DmnElementTransformContext context, Decision decision) {
DecisionDefinitionEntity decisionDefinition = (DecisionDefinitionEntity) super.createFromDecision(context, decision);
String category = context.getModelInstance().getDefinitions().getNamespace();
decisionDefinition.setCategory(category);
decisionDefinition.setVersionTag(decision.getVersionTag());
validateAndSetHTTL(decision, decisionDefinition, isSkipEnforceTtl()); | return decisionDefinition;
}
protected void validateAndSetHTTL(Decision decision, DecisionDefinitionEntity decisionDefinition, boolean skipEnforceTtl) {
Integer historyTimeToLive = HistoryTimeToLiveParser.create().parse(decision, decisionDefinition.getKey(), skipEnforceTtl);
decisionDefinition.setHistoryTimeToLive(historyTimeToLive);
}
public boolean isSkipEnforceTtl() {
return skipEnforceTtl;
}
public void setSkipEnforceTtl(boolean skipEnforceTtl) {
this.skipEnforceTtl = skipEnforceTtl;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\transformer\DecisionDefinitionHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JwtResponse dynamicBuildercompress(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
String jws = Jwts.builder()
.setClaims(claims)
.compressWith(new DeflateCompressionAlgorithm())
.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes())
.compact();
return new JwtResponse(jws);
}
@RequestMapping(value = "/dynamic-builder-specific", method = POST)
public JwtResponse dynamicBuilderSpecific(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
JwtBuilder builder = Jwts.builder();
claims.forEach((key, value) -> {
switch (key) {
case "iss":
ensureType(key, value, String.class);
builder.setIssuer((String) value);
break;
case "sub":
ensureType(key, value, String.class);
builder.setSubject((String) value);
break;
case "aud":
ensureType(key, value, String.class);
builder.setAudience((String) value);
break;
case "exp":
ensureType(key, value, Long.class);
builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break;
case "nbf": | ensureType(key, value, Long.class);
builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break;
case "iat":
ensureType(key, value, Long.class);
builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
break;
case "jti":
ensureType(key, value, String.class);
builder.setId((String) value);
break;
default:
builder.claim(key, value);
}
});
builder.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes());
return new JwtResponse(builder.compact());
}
private void ensureType(String registeredClaim, Object value, Class expectedType) {
boolean isCorrectType = expectedType.isInstance(value) || expectedType == Long.class && value instanceof Integer;
if (!isCorrectType) {
String msg = "Expected type: " + expectedType.getCanonicalName() + " for registered claim: '" + registeredClaim + "', but got value: " + value + " of type: " + value.getClass()
.getCanonicalName();
throw new JwtException(msg);
}
}
} | repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\controller\DynamicJWTController.java | 2 |
请完成以下Java代码 | public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
public String getVersionTag() {
return versionTag;
}
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
public boolean isNotStartableInTasklist() {
return isNotStartableInTasklist;
}
public boolean isStartablePermissionCheck() {
return startablePermissionCheck;
}
public void setProcessDefinitionCreatePermissionChecks(List<PermissionCheck> processDefinitionCreatePermissionChecks) {
this.processDefinitionCreatePermissionChecks = processDefinitionCreatePermissionChecks;
}
public List<PermissionCheck> getProcessDefinitionCreatePermissionChecks() {
return processDefinitionCreatePermissionChecks;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
public void addProcessDefinitionCreatePermissionCheck(CompositePermissionCheck processDefinitionCreatePermissionCheck) {
processDefinitionCreatePermissionChecks.addAll(processDefinitionCreatePermissionCheck.getAllPermissionChecks()); | }
public List<String> getCandidateGroups() {
if (cachedCandidateGroups != null) {
return cachedCandidateGroups;
}
if(authorizationUserId != null) {
List<Group> groups = Context.getCommandContext()
.getReadOnlyIdentityProvider()
.createGroupQuery()
.groupMember(authorizationUserId)
.list();
cachedCandidateGroups = groups.stream().map(Group::getId).collect(Collectors.toList());
}
return cachedCandidateGroups;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | 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;
}
/** Set Size X.
@param SizeX
X (horizontal) dimension size
*/
public void setSizeX (BigDecimal SizeX)
{
set_Value (COLUMNNAME_SizeX, SizeX);
}
/** Get Size X.
@return X (horizontal) dimension size
*/
public BigDecimal getSizeX ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeX); | if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Size Y.
@param SizeY
Y (vertical) dimension size
*/
public void setSizeY (BigDecimal SizeY)
{
set_Value (COLUMNNAME_SizeY, SizeY);
}
/** Get Size Y.
@return Y (vertical) dimension size
*/
public BigDecimal getSizeY ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeY);
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_AD_PrintPaper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
return Objects.hash(evidenceType, files, lineItems);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class AddEvidencePaymentDisputeRequest {\n");
sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n");
sb.append(" files: ").append(toIndentedString(files)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).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\AddEvidencePaymentDisputeRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Person {
@Id
private int id;
@Column
private String firstName;
@Column
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} | public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-h2\src\main\java\com\baeldung\h2\tablenotfound\entity\Person.java | 2 |
请完成以下Java代码 | public class Employee {
String name;
String title;
List<String> skills;
int yearsOfService;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getSkills() { | return skills;
}
public void setSkills(List<String> skills) {
this.skills = skills;
}
public int getYearsOfService() {
return yearsOfService;
}
public void setYearsOfService(int yearsOfService) {
this.yearsOfService = yearsOfService;
}
} | repos\tutorials-master\persistence-modules\elasticsearch\src\main\java\com\baeldung\jest\Employee.java | 1 |
请完成以下Java代码 | protected void createEventListeners(BpmnParse bpmnParse, List<EventListener> eventListeners) {
if (eventListeners != null && !eventListeners.isEmpty()) {
for (EventListener eventListener : eventListeners) {
// Extract specific event-types (if any)
FlowableEngineEventType[] types = FlowableEngineEventType.getTypesFromString(eventListener.getEvents());
if (ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(eventListener.getImplementationType())) {
getEventSupport(bpmnParse.getBpmnModel()).addEventListener(bpmnParse.getListenerFactory().createClassDelegateEventListener(eventListener), types);
} else if (ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(eventListener.getImplementationType())) {
getEventSupport(bpmnParse.getBpmnModel()).addEventListener(bpmnParse.getListenerFactory().createDelegateExpressionEventListener(eventListener), types);
} else if (ImplementationType.IMPLEMENTATION_TYPE_THROW_SIGNAL_EVENT.equals(eventListener.getImplementationType())
|| ImplementationType.IMPLEMENTATION_TYPE_THROW_GLOBAL_SIGNAL_EVENT.equals(eventListener.getImplementationType())
|| ImplementationType.IMPLEMENTATION_TYPE_THROW_MESSAGE_EVENT.equals(eventListener.getImplementationType())
|| ImplementationType.IMPLEMENTATION_TYPE_THROW_ERROR_EVENT.equals(eventListener.getImplementationType())) { | getEventSupport(bpmnParse.getBpmnModel()).addEventListener(bpmnParse.getListenerFactory().createEventThrowingEventListener(eventListener), types);
} else {
LOGGER.warn("Unsupported implementation type for EventListener: {} for element {}", eventListener.getImplementationType(), bpmnParse.getCurrentFlowElement().getId());
}
}
}
}
protected FlowableEventSupport getEventSupport(BpmnModel bpmnModel) {
return (FlowableEventSupport) bpmnModel.getEventSupport();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\parser\handler\ProcessParseHandler.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.