instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public C_AllocationLine_Builder paymentWriteOffAmt(final BigDecimal paymentWriteOffAmt)
{
allocLine.setPaymentWriteOffAmt(paymentWriteOffAmt);
return this;
}
public final C_AllocationLine_Builder skipIfAllAmountsAreZero()
{
this.skipIfAllAmountsAreZero = true;
return this;
}
private boolean isSkipBecauseAllAmountsAreZero()
{
if (!skipIfAllAmountsAreZero)
{
return false;
}
// NOTE: don't check the OverUnderAmt because that amount is not affecting allocation,
// so an allocation is Zero with our without the over/under amount.
return allocLine.getAmount().signum() == 0
&& allocLine.getDiscountAmt().signum() == 0
&& allocLine.getWriteOffAmt().signum() == 0
//
&& allocLine.getPaymentWriteOffAmt().signum() == 0;
}
public final C_AllocationHdr_Builder lineDone()
{
return parent;
}
/**
* @param allocHdrSupplier allocation header supplier which will provide the allocation header created & saved, just in time, so call it ONLY if you are really gonna create an allocation line.
* @return created {@link I_C_AllocationLine} or <code>null</code> if it was not needed.
*/
@Nullable
final I_C_AllocationLine create(@NonNull final Supplier<I_C_AllocationHdr> allocHdrSupplier) | {
if (isSkipBecauseAllAmountsAreZero())
{
return null;
}
//
// Get the allocation header, created & saved.
final I_C_AllocationHdr allocHdr = allocHdrSupplier.get();
Check.assumeNotNull(allocHdr, "Param 'allocHdr' not null");
Check.assume(allocHdr.getC_AllocationHdr_ID() > 0, "Param 'allocHdr' has C_AllocationHdr_ID>0");
allocLine.setC_AllocationHdr(allocHdr);
allocLine.setAD_Org_ID(allocHdr.getAD_Org_ID());
allocationDAO.save(allocLine);
return allocLine;
}
public final C_AllocationHdr_Builder getParent()
{
return parent;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\C_AllocationLine_Builder.java | 1 |
请完成以下Java代码 | public class AutoPoiDictConfig implements AutoPoiDictServiceI {
final static String EXCEL_SPLIT_TAG = "_";
final static String TEMP_EXCEL_SPLIT_TAG = "---";
@Lazy
@Resource
private CommonAPI commonApi;
/**
* 通过字典查询easypoi,所需字典文本
*
* @Author:scott
* @since:2019-04-09
* @return
*/
@Override
public String[] queryDict(String dicTable, String dicCode, String dicText) {
List<String> dictReplaces = new ArrayList<String>();
List<DictModel> dictList = null;
// step.1 如果没有字典表则使用系统字典表
if (oConvertUtils.isEmpty(dicTable)) {
dictList = commonApi.queryDictItemsByCode(dicCode);
} else {
try {
dicText = oConvertUtils.getString(dicText, dicCode);
dictList = commonApi.queryTableDictItemsByCode(dicTable, dicText, dicCode);
} catch (Exception e) {
log.error(e.getMessage(),e); | }
}
for (DictModel t : dictList) {
// 代码逻辑说明: [issues/4917]excel 导出异常---
if(t!=null && t.getText()!=null && t.getValue()!=null){
// 代码逻辑说明: [issues/I4MBB3]@Excel dicText字段的值有下划线时,导入功能不能正确解析---
if(t.getValue().contains(EXCEL_SPLIT_TAG)){
String val = t.getValue().replace(EXCEL_SPLIT_TAG,TEMP_EXCEL_SPLIT_TAG);
dictReplaces.add(t.getText() + EXCEL_SPLIT_TAG + val);
}else{
dictReplaces.add(t.getText() + EXCEL_SPLIT_TAG + t.getValue());
}
}
}
if (dictReplaces != null && dictReplaces.size() != 0) {
log.info("---AutoPoi--Get_DB_Dict------"+ dictReplaces.toString());
return dictReplaces.toArray(new String[dictReplaces.size()]);
}
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\AutoPoiDictConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CachingAnnotationsAspect {
private static final Logger logger = LoggerFactory.getLogger(CachingAnnotationsAspect.class);
@Autowired
private CacheSupport cacheSupport;
private <T extends Annotation> List<T> getMethodAnnotations(AnnotatedElement ae, Class<T> annotationType) {
List<T> anns = new ArrayList<T>(2);
// look for raw annotation
T ann = ae.getAnnotation(annotationType);
if (ann != null) {
anns.add(ann);
}
// look for meta-annotations
for (Annotation metaAnn : ae.getAnnotations()) {
ann = metaAnn.annotationType().getAnnotation(annotationType);
if (ann != null) {
anns.add(ann);
}
}
return (anns.isEmpty() ? null : anns);
}
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
Method method = methodSignature.getMethod();
// The method may be on an interface, but we need attributes from the
// target class. If the target class is null, the method will be
// unchanged.
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
if (targetClass == null && pjp.getTarget() != null) {
targetClass = pjp.getTarget().getClass();
}
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
// If we are dealing with method with generic parameters, find the
// original method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
return specificMethod;
}
@Pointcut("@annotation(org.springframework.cache.annotation.Cacheable)")
public void pointcut() {
} | @Around("pointcut()")
public Object registerInvocation(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = this.getSpecificmethod(joinPoint);
List<Cacheable> annotations = this.getMethodAnnotations(method, Cacheable.class);
Set<String> cacheSet = new HashSet<String>();
String cacheKey = null;
for (Cacheable cacheables : annotations) {
cacheSet.addAll(Arrays.asList(cacheables.value()));
cacheKey = cacheables.key();
}
if (joinPoint.getSignature() instanceof MethodSignature) {
Class[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
cacheSupport.registerInvocation(joinPoint.getTarget(), method, parameterTypes,
joinPoint.getArgs(), cacheSet, cacheKey);
}
return joinPoint.proceed();
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CachingAnnotationsAspect.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Pharma Product Category.
@param M_PharmaProductCategory_ID Pharma Product Category */
@Override
public void setM_PharmaProductCategory_ID (int M_PharmaProductCategory_ID)
{
if (M_PharmaProductCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PharmaProductCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PharmaProductCategory_ID, Integer.valueOf(M_PharmaProductCategory_ID));
}
/** Get Pharma Product Category.
@return Pharma Product Category */
@Override
public int getM_PharmaProductCategory_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_M_PharmaProductCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_PharmaProductCategory.java | 1 |
请完成以下Java代码 | public Optional<OrderId> getOrderId(@NonNull final JsonOrderRevertRequest request, @NonNull final MasterdataProvider masterdataProvider)
{
final OrgId orgId = masterdataProvider.getOrgId(request.getOrgCode());
final ExternalSystemId externalSystemId = masterdataProvider.getExternalSystemId(ExternalSystemType.ofValue(request.getExternalSystemCode()));
final OrderQuery orderQuery = OrderQuery.builder()
.orgId(orgId)
.externalId(ExternalId.of(request.getExternalId()))
.externalSystemId(externalSystemId)
.build();
return orderDAO.retrieveByOrderCriteria(orderQuery)
.map(I_C_Order::getC_Order_ID)
.map(OrderId::ofRepoId);
}
public Optional<OrderId> resolveOrderId(@NonNull final IdentifierString orderIdentifier, @NonNull final OrgId orgId)
{
final OrderQuery.OrderQueryBuilder queryBuilder = OrderQuery.builder().orgId(orgId);
switch (orderIdentifier.getType())
{
case METASFRESH_ID:
final OrderId orderId = OrderId.ofRepoId(orderIdentifier.asMetasfreshId().getValue());
return Optional.of(orderId);
case DOC:
final OrderQuery getOrderByDocQuery = queryBuilder
.documentNo(orderIdentifier.asDoc())
.build();
return orderDAO.retrieveByOrderCriteria(getOrderByDocQuery)
.map(I_C_Order::getC_Order_ID)
.map(OrderId::ofRepoId);
case EXTERNAL_ID: | final OrderQuery getOrderByExternalId = queryBuilder
.externalId(orderIdentifier.asExternalId())
.build();
return orderDAO.retrieveByOrderCriteria(getOrderByExternalId)
.map(I_C_Order::getC_Order_ID)
.map(OrderId::ofRepoId);
default:
throw new InvalidIdentifierException("Given IdentifierString type is not supported!")
.appendParametersToMessage()
.setParameter("IdentifierStringType", orderIdentifier.getType())
.setParameter("rawIdentifierString", orderIdentifier.getRawIdentifierString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\sales\OrderService.java | 1 |
请完成以下Java代码 | public class EmployeeAlreadyExists_Exception
extends Exception
{
/**
* Java type that goes as soapenv:Fault detail element.
*
*/
private EmployeeAlreadyExists faultInfo;
/**
*
* @param faultInfo
* @param message
*/
public EmployeeAlreadyExists_Exception(String message, EmployeeAlreadyExists faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
/**
* | * @param faultInfo
* @param cause
* @param message
*/
public EmployeeAlreadyExists_Exception(String message, EmployeeAlreadyExists faultInfo, Throwable cause) {
super(message, cause);
this.faultInfo = faultInfo;
}
/**
*
* @return
* returns fault bean: com.baeldung.jaxws.client.EmployeeAlreadyExists
*/
public EmployeeAlreadyExists getFaultInfo() {
return faultInfo;
}
} | repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\EmployeeAlreadyExists_Exception.java | 1 |
请完成以下Spring Boot application配置 | ##########################################################
################## 所有profile共有的配置 #################
##########################################################
################### spring配置 ###################
spring:
profiles:
active: dev
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&autoReconnect=true&tinyInt1isBit=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456
################### mybatis-plus配置 ###################
mybatis-plus:
mapper-locations: classpath*:com/xncoding/pos/dao/repository/mapping/*.xml
typeAliasesPackage: >
com.xncoding.pos.dao.entity
global-config:
id-type: 0 # 0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid)
db-column-underline: false
refresh-mapper: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: true #配置的缓存的全局开关
lazyLoadingEnabled: true #延时加载的开关
multipleResultSetsEnabled: true #开启的话,延时加载一个属性时会加载该对象全部属性,否则按需加载属性
logging:
level:
org.springframework.web.servlet: ERROR
---
#################################### | #################################
######################## 开发环境profile ##########################
#####################################################################
spring:
profiles: dev
redis:
host: 127.0.0.1
port: 6379
database: 0
lettuce:
shutdown-timeout: 200ms
pool:
max-active: 7
max-idle: 7
min-idle: 2
max-wait: -1ms
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: D:/logs/app.log | repos\SpringBootBucket-master\springboot-redis\src\main\resources\application.yml | 2 |
请完成以下Java代码 | private I_MKTG_Consent getConsentRecord(@NonNull final ContactPersonId contactPersonId)
{
return queryBL.createQueryBuilder(I_MKTG_Consent.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MKTG_Consent.COLUMNNAME_ConsentRevokedOn, null)
.addEqualsFilter(I_MKTG_Consent.COLUMNNAME_MKTG_ContactPerson_ID, contactPersonId.getRepoId())
.orderByDescending(I_MKTG_Consent.COLUMNNAME_ConsentDeclaredOn)
.create()
.first(I_MKTG_Consent.class);
}
public void updateBPartnerLocation(final ContactPerson contactPerson, BPartnerLocationId bpLocationId)
{
contactPerson.toBuilder()
.bpLocationId(bpLocationId)
.build();
save(contactPerson);
}
public Set<ContactPerson> getByBPartnerLocationId(@NonNull final BPartnerLocationId bpLocationId)
{
return queryBL
.createQueryBuilder(I_MKTG_ContactPerson.class)
.addOnlyActiveRecordsFilter() | .addEqualsFilter(I_MKTG_ContactPerson.COLUMN_C_BPartner_Location_ID, bpLocationId.getRepoId())
.create()
.stream()
.map(ContactPersonRepository::toContactPerson)
.collect(ImmutableSet.toImmutableSet());
}
public Set<ContactPerson> getByUserId(@NonNull final UserId userId)
{
return queryBL
.createQueryBuilder(I_MKTG_ContactPerson.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MKTG_ContactPerson.COLUMN_AD_User_ID, userId.getRepoId())
.create()
.stream()
.map(ContactPersonRepository::toContactPerson)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\ContactPersonRepository.java | 1 |
请完成以下Java代码 | public static EmbeddedStorageManager initializeStorageWithCustomTypeAsRoot(Path directory, String root, List<Book> booksToStore) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
RootInstance rootInstance = new RootInstance(root);
storageManager.setRoot(rootInstance);
storageManager.storeRoot();
List<Book> books = rootInstance.getBooks();
books.addAll(booksToStore);
storageManager.store(books);
return storageManager;
}
public static EmbeddedStorageManager loadOrCreateStorageWithCustomTypeAsRoot(Path directory, String root) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
if (storageManager.root() == null) {
RootInstance rootInstance = new RootInstance(root);
storageManager.setRoot(rootInstance);
storageManager.storeRoot(); | }
return storageManager;
}
public static EmbeddedStorageManager lazyLoadOrCreateStorageWithCustomTypeAsRoot(Path directory, String root, List<Book> booksToStore) {
EmbeddedStorageManager storageManager = EmbeddedStorage.start(directory);
if (storageManager.root() == null) {
RootInstanceLazy rootInstance = new RootInstanceLazy(root);
rootInstance.getBooks().addAll(booksToStore);
storageManager.setRoot(rootInstance);
storageManager.storeRoot();
}
return storageManager;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-2\src\main\java\com\baeldung\microstream\StorageManager.java | 1 |
请完成以下Java代码 | public void setCharset(@Nullable Charset charset) {
this.charset = charset;
}
/**
* Set the name of the charset to use.
* @param charset the charset
* @deprecated since 4.1.0 for removal in 4.3.0 in favor of
* {@link #setCharset(Charset)}
*/
@Deprecated(since = "4.1.0", forRemoval = true)
public void setCharset(@Nullable String charset) {
setCharset((charset != null) ? Charset.forName(charset) : null);
}
@Override
protected Class<?> requiredViewClass() {
return MustacheView.class; | }
@Override
protected AbstractUrlBasedView createView(String viewName) {
MustacheView view = (MustacheView) super.createView(viewName);
view.setCompiler(this.compiler);
view.setCharset(this.charset);
return view;
}
@Override
protected AbstractUrlBasedView instantiateView() {
return (getViewClass() == MustacheView.class) ? new MustacheView() : super.instantiateView();
}
} | repos\spring-boot-main\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\reactive\view\MustacheViewResolver.java | 1 |
请完成以下Java代码 | public void setSecureRandom(SecureRandom secureRandom) {
Assert.notNull(secureRandom, "secureRandom cannot be null");
this.secureRandom = secureRandom;
}
@Override
public void handle(ServerWebExchange exchange, Mono<CsrfToken> csrfToken) {
Assert.notNull(exchange, "exchange cannot be null");
Assert.notNull(csrfToken, "csrfToken cannot be null");
Mono<CsrfToken> updatedCsrfToken = csrfToken
.map((token) -> new DefaultCsrfToken(token.getHeaderName(), token.getParameterName(),
createXoredCsrfToken(this.secureRandom, token.getToken())))
.cast(CsrfToken.class)
.cache();
super.handle(exchange, updatedCsrfToken);
}
@Override
public Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) {
return super.resolveCsrfTokenValue(exchange, csrfToken)
.flatMap((actualToken) -> Mono.justOrEmpty(getTokenValue(actualToken, csrfToken.getToken())));
}
private static @Nullable String getTokenValue(String actualToken, String token) {
byte[] actualBytes;
try {
actualBytes = Base64.getUrlDecoder().decode(actualToken);
}
catch (Exception ex) {
logger.trace(LogMessage.format("Not returning the CSRF token since it's not Base64-encoded"), ex);
return null;
}
byte[] tokenBytes = Utf8.encode(token);
int tokenSize = tokenBytes.length;
if (actualBytes.length != tokenSize * 2) {
logger.trace(LogMessage.format(
"Not returning the CSRF token since its Base64-decoded length (%d) is not equal to (%d)",
actualBytes.length, tokenSize * 2));
return null;
} | // extract token and random bytes
byte[] xoredCsrf = new byte[tokenSize];
byte[] randomBytes = new byte[tokenSize];
System.arraycopy(actualBytes, 0, randomBytes, 0, tokenSize);
System.arraycopy(actualBytes, tokenSize, xoredCsrf, 0, tokenSize);
byte[] csrfBytes = xorCsrf(randomBytes, xoredCsrf);
return (csrfBytes != null) ? Utf8.decode(csrfBytes) : null;
}
private static String createXoredCsrfToken(SecureRandom secureRandom, String token) {
byte[] tokenBytes = Utf8.encode(token);
byte[] randomBytes = new byte[tokenBytes.length];
secureRandom.nextBytes(randomBytes);
byte[] xoredBytes = xorCsrf(randomBytes, tokenBytes);
byte[] combinedBytes = new byte[tokenBytes.length + randomBytes.length];
System.arraycopy(randomBytes, 0, combinedBytes, 0, randomBytes.length);
System.arraycopy(xoredBytes, 0, combinedBytes, randomBytes.length, xoredBytes.length);
return Base64.getUrlEncoder().encodeToString(combinedBytes);
}
private static byte[] xorCsrf(byte[] randomBytes, byte[] csrfBytes) {
Assert.isTrue(randomBytes.length == csrfBytes.length, "arrays must be equal length");
int len = csrfBytes.length;
byte[] xoredCsrf = new byte[len];
System.arraycopy(csrfBytes, 0, xoredCsrf, 0, len);
for (int i = 0; i < len; i++) {
xoredCsrf[i] ^= randomBytes[i];
}
return xoredCsrf;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\XorServerCsrfTokenRequestAttributeHandler.java | 1 |
请完成以下Java代码 | private void syncInvoiceRuleOverrideToCandidate(
@NonNull final NewManualInvoiceCandidateBuilder candidate,
@Nullable final JsonInvoiceRule invoiceRuleOverride)
{
candidate.invoiceRuleOverride(BPartnerCompositeRestUtils.getInvoiceRule(invoiceRuleOverride));
}
private void syncPriceEnteredOverrideToCandidate(
@NonNull final NewManualInvoiceCandidateBuilder candidate,
@NonNull final ProductId productId,
@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
final JsonPrice priceEnteredOverride = item.getPriceEnteredOverride();
final ProductPrice price = createProductPriceOrNull(priceEnteredOverride, productId, item);
candidate.priceEnteredOverride(price);
}
private ProductPrice createProductPriceOrNull(
@Nullable final JsonPrice jsonPrice,
@NonNull final ProductId productId,
@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
if (jsonPrice == null)
{
return null;
}
final CurrencyId currencyId = lookupCurrencyId(jsonPrice);
final UomId priceUomId = lookupUomId(
X12DE355.ofNullableCode(jsonPrice.getPriceUomCode()),
productId,
item);
final ProductPrice price = ProductPrice.builder()
.money(Money.of(jsonPrice.getValue(), currencyId))
.productId(productId)
.uomId(priceUomId)
.build();
return price;
}
private CurrencyId lookupCurrencyId(@NonNull final JsonPrice jsonPrice)
{
final CurrencyId result = currencyService.getCurrencyId(jsonPrice.getCurrencyCode());
if (result == null)
{
throw MissingResourceException.builder().resourceName("currency").resourceIdentifier(jsonPrice.getPriceUomCode()).parentResource(jsonPrice).build();
}
return result;
}
private UomId lookupUomId(
@Nullable final X12DE355 uomCode,
@NonNull final ProductId productId,
@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
if (uomCode == null)
{
return productBL.getStockUOMId(productId);
} | final UomId priceUomId;
try
{
priceUomId = uomDAO.getUomIdByX12DE355(uomCode);
}
catch (final AdempiereException e)
{
throw MissingResourceException.builder().resourceName("uom").resourceIdentifier("priceUomCode").parentResource(item).cause(e).build();
}
return priceUomId;
}
private InvoiceCandidateLookupKey createInvoiceCandidateLookupKey(@NonNull final JsonCreateInvoiceCandidatesRequestItem item)
{
try
{
return InvoiceCandidateLookupKey.builder()
.externalHeaderId(JsonExternalIds.toExternalIdOrNull(item.getExternalHeaderId()))
.externalLineId(JsonExternalIds.toExternalIdOrNull(item.getExternalLineId()))
.build();
}
catch (final AdempiereException e)
{
throw InvalidEntityException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoicecandidates\impl\CreateInvoiceCandidatesService.java | 1 |
请完成以下Java代码 | /* package */ IAutoCloseable lockForReading()
{
final ReadLock readLock = readwriteLock.readLock();
logger.debug("Acquiring read lock for {}: {}", this, readLock);
readLock.lock();
logger.debug("Acquired read lock for {}: {}", this, readLock);
return () -> {
readLock.unlock();
logger.debug("Released read lock for {}: {}", this, readLock);
};
}
/* package */ IAutoCloseable lockForWriting()
{
final WriteLock writeLock = readwriteLock.writeLock();
logger.debug("Acquiring write lock for {}: {}", this, writeLock);
writeLock.lock();
logger.debug("Acquired write lock for {}: {}", this, writeLock);
return () -> {
writeLock.unlock();
logger.debug("Released write lock for {}: {}", this, writeLock);
};
}
/**
* Try to get the target output type from the specific process param {@link de.metas.report.server.ReportConstants#REPORT_PARAM_REPORT_FORMAT},
* if the parameter is missing, the default output type is returned. | *
* @see OutputType#getDefault()
*/
private OutputType getTargetOutputType()
{
final IDocumentFieldView formatField = parameters.getFieldViewOrNull(REPORT_PARAM_REPORT_FORMAT);
if (formatField != null)
{
final LookupValue outputTypeParamValue = formatField.getValueAs(LookupValue.class);
if (outputTypeParamValue != null)
{
final Optional<OutputType> targetOutputType = OutputType.getOutputTypeByFileExtension(String.valueOf(formatField.getValueAs(LookupValue.class).getId()));
if (targetOutputType.isPresent())
{
return targetOutputType.get();
}
}
}
return OutputType.getDefault();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessInstanceController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AddCommentHandler implements CommandHandler<AddCommentResult, AddComment> {
private final AuthenticationService authenticationService;
private final ArticleRepository articleRepository;
private final CommentRepository commentRepository;
private final ConversionService conversionService;
@Transactional
@Override
public AddCommentResult handle(AddComment command) {
var currentUserId = authenticationService.getRequiredCurrentUserId();
var articleId = articleRepository.findIdBySlug(command.getSlug())
.orElseThrow(() -> notFound("article [slug=%s] does not exist", command.getSlug())); | var comment = Comment.builder()
.articleId(articleId)
.authorId(currentUserId)
.body(command.getBody())
.build();
var savedComment = commentRepository.save(comment);
var commentAssembly = commentRepository.findAssemblyById(currentUserId, savedComment.id()).orElseThrow();
var data = conversionService.convert(commentAssembly, CommentDto.class);
return new AddCommentResult(data);
}
} | repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\application\command\AddCommentHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void renameTableSequence(final Properties ctx, final String tableNameOld, final String tableNameNew)
{
//
// Rename the AD_Sequence
final I_AD_Sequence adSequence = retrieveTableSequenceOrNull(ctx, tableNameOld, ITrx.TRXNAME_ThreadInherited);
if (adSequence != null)
{
adSequence.setName(tableNameNew);
InterfaceWrapperHelper.save(adSequence);
}
//
// Rename the database native sequence
{
final String dbSequenceNameOld = DB.getTableSequenceName(tableNameOld);
final String dbSequenceNameNew = DB.getTableSequenceName(tableNameNew);
DB.getDatabase().renameSequence(dbSequenceNameOld, dbSequenceNameNew);
}
}
@Override
@NonNull
public Optional<I_AD_Sequence> retrieveSequenceByName(@NonNull final String sequenceName, @NonNull final ClientId clientId)
{
return queryBL
.createQueryBuilder(I_AD_Sequence.class)
.addEqualsFilter(I_AD_Sequence.COLUMNNAME_Name, sequenceName)
.addEqualsFilter(I_AD_Sequence.COLUMNNAME_AD_Client_ID, clientId) | .addEqualsFilter(I_AD_Sequence.COLUMNNAME_IsTableID, false)
.addOnlyActiveRecordsFilter()
.create()
.firstOptional(I_AD_Sequence.class);
}
@Override
public DocSequenceId cloneToOrg(@NonNull final DocSequenceId fromDocSequenceId, @NonNull final OrgId toOrgId)
{
final I_AD_Sequence fromSequence = InterfaceWrapperHelper.load(fromDocSequenceId, I_AD_Sequence.class);
final I_AD_Sequence newSequence = InterfaceWrapperHelper.copy()
.setFrom(fromSequence)
.setSkipCalculatedColumns(true)
.copyToNew(I_AD_Sequence.class);
newSequence.setAD_Org_ID(toOrgId.getRepoId());
newSequence.setCurrentNext(100000);
InterfaceWrapperHelper.save(newSequence);
return DocSequenceId.ofRepoId(newSequence.getAD_Sequence_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\SequenceDAO.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RelatedDocuments
{
@NonNull RelatedDocumentsId id;
@NonNull String internalName;
@NonNull ITranslatableString caption;
@Nullable
ITranslatableString filterByFieldCaption;
@NonNull MQuery query;
@NonNull RelatedDocumentsTargetWindow targetWindow;
@NonNull Priority priority;
@Builder
private RelatedDocuments(
@NonNull final RelatedDocumentsId id,
@NonNull final String internalName,
@NonNull final RelatedDocumentsTargetWindow targetWindow,
@NonNull final Priority priority,
@NonNull final ITranslatableString caption,
@Nullable final ITranslatableString filterByFieldCaption,
@NonNull final MQuery query)
{
this.id = id;
this.internalName = Check.assumeNotEmpty(internalName, "internalName is not empty");
this.targetWindow = targetWindow;
this.priority = priority;
this.caption = caption;
this.filterByFieldCaption = filterByFieldCaption;
this.query = query;
}
@Override | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", id)
.add("internalName", internalName)
.add("caption", caption.getDefaultValue())
.add("filterByFieldCaption", filterByFieldCaption != null ? filterByFieldCaption.getDefaultValue() : null)
.add("targetWindow", targetWindow)
.add("RecordCount", query.getRecordCount())
.toString();
}
public AdWindowId getAdWindowId()
{
return getTargetWindow().getAdWindowId();
}
public int getRecordCount()
{
return query.getRecordCount();
}
@Nullable
public Duration getRecordCountDuration()
{
return query.getRecordCountDuration();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\RelatedDocuments.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException {
Student createdStudent = service.create(student);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdStudent.getId())
.toUri();
return ResponseEntity.created(uri)
.body(createdStudent);
}
@PutMapping("/{id}")
public ResponseEntity<Student> update(@RequestBody Student student, @PathVariable Long id) { | Student updatedStudent = service.update(id, student);
if (updatedStudent == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(updatedStudent);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<Object> deleteStudent(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\controller\students\StudentController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static ESFieldName ofString(@NonNull final String name)
{
final String nameNorm = normalizeName(name);
if (nameNorm == null)
{
throw new AdempiereException("Invalid name `" + name + "`");
}
else if (ID.name.equals(name))
{
return ID;
}
else
{
return new ESFieldName(nameNorm);
}
}
@NonNull
private final String name;
public ESFieldName(@NonNull final String nameNorm)
{
this.name = nameNorm;
}
@Nullable
private static String normalizeName(final @NonNull String name)
{ | return StringUtils.trimBlankToNull(name);
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
public String getAsString()
{
return name;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\ESFieldName.java | 2 |
请完成以下Java代码 | public HostInfo getCurrentKafkaStreamsApplicationHostInfo() {
Properties streamsConfiguration = this.streamsBuilderFactoryBean
.getStreamsConfiguration();
if (streamsConfiguration != null && streamsConfiguration.containsKey("application.server")) {
String applicationServer = (String) streamsConfiguration.get("application.server");
String[] appServerComponents = StringUtils.split(applicationServer, ":");
if (appServerComponents != null) {
return new HostInfo(appServerComponents[0], Integer.parseInt(appServerComponents[1]));
}
}
return null;
}
/**
* Retrieve the {@link HostInfo} where the provided store and key are hosted on. This may
* not be the current host that is running the application. Kafka Streams will look
* through all the consumer instances under the same application id and retrieve the
* proper host. Note that the end user applications must provide `application.server` as a
* configuration property for all the application instances when calling this method.
* If this is not available, then null maybe returned.
* @param <K> generic type for key
* @param store store name
* @param key key to look for
* @param serializer {@link Serializer} for the key
* @return the {@link HostInfo} where the key for the provided store is hosted currently
*/
public <K> HostInfo getKafkaStreamsApplicationHostInfo(String store, K key, Serializer<K> serializer) {
populateKafkaStreams();
try {
return getActiveHost(store, key, serializer); | }
catch (RetryException ex) {
throw new IllegalStateException("Error when retrieving state store.", ex.getCause());
}
}
private <K> HostInfo getActiveHost(String store, K key, Serializer<K> serializer) throws RetryException {
return Objects.requireNonNull(this.retryTemplate.execute(() -> {
KeyQueryMetadata keyQueryMetadata = this.kafkaStreams.queryMetadataForKey(store, key, serializer);
if (keyQueryMetadata != null) {
return keyQueryMetadata.activeHost();
}
throw new IllegalStateException("KeyQueryMetadata is not yet available.");
}));
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\streams\KafkaStreamsInteractiveQueryService.java | 1 |
请完成以下Java代码 | public void warn(Marker marker, String msg) {
logger.warn(marker, mdcValue(msg));
}
@Override
public void warn(Marker marker, String format, Object arg) {
logger.warn(marker, mdcValue(format), arg);
}
@Override
public void warn(Marker marker, String format, Object arg1, Object arg2) {
logger.warn(marker, mdcValue(format), arg1, arg2);
}
@Override
public void warn(Marker marker, String format, Object... arguments) {
logger.warn(marker, mdcValue(format), arguments);
}
@Override
public void warn(Marker marker, String msg, Throwable t) {
logger.warn(marker, mdcValue(msg), t);
}
@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}
@Override
public void error(String msg) {
logger.error(mdcValue(msg));
}
@Override
public void error(String format, Object arg) {
logger.error(mdcValue(format), arg);
}
@Override
public void error(String format, Object arg1, Object arg2) {
logger.error(mdcValue(format), arg1, arg2);
}
@Override
public void error(String format, Object... arguments) {
logger.error(mdcValue(format), arguments);
}
@Override
public void error(String msg, Throwable t) {
logger.error(mdcValue(msg), t);
}
@Override
public boolean isErrorEnabled(Marker marker) {
return logger.isErrorEnabled(marker);
}
@Override
public void error(Marker marker, String msg) {
logger.error(marker, mdcValue(msg));
}
@Override
public void error(Marker marker, String format, Object arg) { | logger.error(marker, mdcValue(format), arg);
}
@Override
public void error(Marker marker, String format, Object arg1, Object arg2) {
logger.error(marker, mdcValue(format), arg1, arg2);
}
@Override
public void error(Marker marker, String format, Object... arguments) {
logger.error(marker, mdcValue(format), arguments);
}
@Override
public void error(Marker marker, String msg, Throwable t) {
logger.error(marker, mdcValue(msg), t);
}
/**
* 输出MDC容器中的值
*
* @param msg
* @return
*/
private String mdcValue(String msg) {
try {
StringBuilder sb = new StringBuilder();
sb.append(" [");
try {
sb.append(MDC.get(MdcConstant.SESSION_KEY) + ", ");
} catch (IllegalArgumentException e) {
sb.append(" , ");
}
try {
sb.append(MDC.get(MdcConstant.REQUEST_KEY));
} catch (IllegalArgumentException e) {
sb.append(" ");
}
sb.append("] ");
sb.append(msg);
return sb.toString();
} catch (Exception e) {
return msg;
}
}
} | repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\core\TrackLogger.java | 1 |
请完成以下Java代码 | public class ThreadDumpEndpoint {
private final PlainTextThreadDumpFormatter plainTextFormatter = new PlainTextThreadDumpFormatter();
@ReadOperation
public ThreadDumpDescriptor threadDump() {
return getFormattedThreadDump(ThreadDumpDescriptor::new);
}
@ReadOperation(produces = "text/plain;charset=UTF-8")
public String textThreadDump() {
return getFormattedThreadDump(this.plainTextFormatter::format);
}
private <T> T getFormattedThreadDump(Function<ThreadInfo[], T> formatter) {
return formatter.apply(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true));
}
/**
* Description of a thread dump. | */
public static final class ThreadDumpDescriptor implements OperationResponseBody {
private final List<ThreadInfo> threads;
private ThreadDumpDescriptor(ThreadInfo[] threads) {
this.threads = Arrays.asList(threads);
}
public List<ThreadInfo> getThreads() {
return this.threads;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\ThreadDumpEndpoint.java | 1 |
请完成以下Java代码 | public ImmutableSet<LocatorId> getLocatorIdsByRepoId(@NonNull final Collection<Integer> locatorIds)
{
return warehouseDAO.getLocatorIdsByRepoId(locatorIds);
}
@Override
public LocatorQRCode getLocatorQRCode(@NonNull final LocatorId locatorId)
{
final I_M_Locator locator = warehouseDAO.getLocatorById(locatorId);
return LocatorQRCode.ofLocator(locator);
}
@Override
@NonNull
public ExplainedOptional<LocatorQRCode> getLocatorQRCodeByValue(@NonNull String locatorValue)
{
final List<I_M_Locator> locators = getActiveLocatorsByValue(locatorValue);
if (locators.isEmpty())
{
return ExplainedOptional.emptyBecause(AdempiereException.MSG_NotFound);
}
else if (locators.size() > 1)
{
return ExplainedOptional.emptyBecause(DBMoreThanOneRecordsFoundException.MSG_QueryMoreThanOneRecordsFound); | }
else
{
final I_M_Locator locator = locators.get(0);
return ExplainedOptional.of(LocatorQRCode.ofLocator(locator));
}
}
@Override
public List<I_M_Locator> getActiveLocatorsByValue(final @NotNull String locatorValue)
{
return warehouseDAO.retrieveActiveLocatorsByValue(locatorValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseBL.java | 1 |
请完成以下Java代码 | public void toStop(){
toStop = true;
// stop registryOrRemoveThreadPool
registryOrRemoveThreadPool.shutdownNow();
// stop monitir (interrupt and wait)
registryMonitorThread.interrupt();
try {
registryMonitorThread.join();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
// ---------------------- helper ----------------------
public ReturnT<String> registry(RegistryParam registryParam) {
// valid
if (!StringUtils.hasText(registryParam.getRegistryGroup())
|| !StringUtils.hasText(registryParam.getRegistryKey())
|| !StringUtils.hasText(registryParam.getRegistryValue())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument.");
}
// async execute
registryOrRemoveThreadPool.execute(new Runnable() {
@Override
public void run() {
int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryUpdate(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date());
if (ret < 1) {
XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registrySave(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue(), new Date());
// fresh
freshGroupRegistryInfo(registryParam);
}
}
});
return ReturnT.SUCCESS;
} | public ReturnT<String> registryRemove(RegistryParam registryParam) {
// valid
if (!StringUtils.hasText(registryParam.getRegistryGroup())
|| !StringUtils.hasText(registryParam.getRegistryKey())
|| !StringUtils.hasText(registryParam.getRegistryValue())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "Illegal Argument.");
}
// async execute
registryOrRemoveThreadPool.execute(new Runnable() {
@Override
public void run() {
int ret = XxlJobAdminConfig.getAdminConfig().getXxlJobRegistryDao().registryDelete(registryParam.getRegistryGroup(), registryParam.getRegistryKey(), registryParam.getRegistryValue());
if (ret > 0) {
// fresh
freshGroupRegistryInfo(registryParam);
}
}
});
return ReturnT.SUCCESS;
}
private void freshGroupRegistryInfo(RegistryParam registryParam){
// Under consideration, prevent affecting core tables
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobRegistryHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ApiResponse<NursingService> getNursingServiceWithHttpInfo(String albertaApiKey, String _id) throws ApiException {
com.squareup.okhttp.Call call = getNursingServiceValidateBeforeCall(albertaApiKey, _id, null, null);
Type localVarReturnType = new TypeToken<NursingService>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Daten eines einzelnen Pflegedienstes abrufen (asynchronously)
* Szenario - das WaWi fragt bei Alberta nach, wie die Daten des Pflegedienstes mit der angegebenen Id sind
* @param albertaApiKey (required)
* @param _id eindeutige id des Pflegedienstes (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getNursingServiceAsync(String albertaApiKey, String _id, final ApiCallback<NursingService> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) { | progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getNursingServiceValidateBeforeCall(albertaApiKey, _id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<NursingService>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\NursingServiceApi.java | 2 |
请完成以下Java代码 | public String getIBAN() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIBAN(String value) {
this.iban = value;
}
/**
* Gets the value of the othr property.
*
* @return | * possible object is
* {@link GenericAccountIdentification1 }
*
*/
public GenericAccountIdentification1 getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link GenericAccountIdentification1 }
*
*/
public void setOthr(GenericAccountIdentification1 value) {
this.othr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\AccountIdentification4Choice.java | 1 |
请完成以下Java代码 | public XmlTransport withMod(@Nullable final TransportMod transportMod)
{
if (transportMod == null)
{
return this;
}
final XmlTransportBuilder builder = toBuilder();
if (transportMod.getFrom() != null)
{
builder.from(transportMod.getFrom());
}
final List<String> replacementViaEANs = transportMod.getReplacementViaEANs();
if (replacementViaEANs != null && !replacementViaEANs.isEmpty())
{
builder.clearVias();
int currentMaxSeqNo = 0;
for (final String replacementViaEAN : replacementViaEANs)
{
currentMaxSeqNo += 1;
final XmlVia xmlVia = XmlVia.builder()
.via(replacementViaEAN)
.sequenceId(currentMaxSeqNo)
.build();
builder.via(xmlVia);
}
}
final List<String> additionalViaEANs = transportMod.getAdditionalViaEANs();
if (additionalViaEANs != null)
{
int currentMaxSeqNo = getVias()
.stream()
.map(XmlVia::getSequenceId) // is never null | .max(Comparator.naturalOrder())
.orElse(0);
for (final String additionalViaEAN : additionalViaEANs)
{
currentMaxSeqNo += 1;
final XmlVia xmlVia = XmlVia.builder()
.via(additionalViaEAN)
.sequenceId(currentMaxSeqNo)
.build();
builder.via(xmlVia);
}
}
return builder
.build();
}
@Value
@Builder
public static class TransportMod
{
@Nullable
String from;
/** {@code null} or an empty list both mean "don't replace" */
@Singular
List<String> replacementViaEANs;
@Singular
List<String> additionalViaEANs;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\processing\XmlTransport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getKanbanCardNumberRange1Start() {
return kanbanCardNumberRange1Start;
}
/**
* Sets the value of the kanbanCardNumberRange1Start property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKanbanCardNumberRange1Start(String value) {
this.kanbanCardNumberRange1Start = value;
}
/**
* Gets the value of the kanbanCardNumberRange1End property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getKanbanCardNumberRange1End() {
return kanbanCardNumberRange1End;
}
/**
* Sets the value of the kanbanCardNumberRange1End property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKanbanCardNumberRange1End(String value) {
this.kanbanCardNumberRange1End = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PackagingIdentificationType.java | 2 |
请完成以下Java代码 | public DataLoader<?, ?> getDataLoader() {
return this.dataLoader;
}
/**
* Return the keys for loading by the {@link org.dataloader.DataLoader}.
*/
public List<?> getKeys() {
return this.keys;
}
/**
* Return the list of values resolved by the {@link org.dataloader.DataLoader},
* or an empty list if none were resolved.
*/
public List<?> getResult() {
return this.result;
} | /**
* Set the list of resolved values by the {@link org.dataloader.DataLoader}.
* @param result the values resolved by the data loader
*/
public void setResult(List<?> result) {
this.result = result;
}
/**
* Return the {@link BatchLoaderEnvironment environment} given to the batch loading function.
*/
public BatchLoaderEnvironment getEnvironment() {
return this.environment;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\DataLoaderObservationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Config {
@NotEmpty
private List<String> sources = new ArrayList<>();
@NotNull
private RemoteAddressResolver remoteAddressResolver = new RemoteAddressResolver() {
};
public List<String> getSources() {
return sources;
}
public Config setSources(List<String> sources) {
this.sources = sources; | return this;
}
public Config setSources(String... sources) {
this.sources = Arrays.asList(sources);
return this;
}
public Config setRemoteAddressResolver(RemoteAddressResolver remoteAddressResolver) {
this.remoteAddressResolver = remoteAddressResolver;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\RemoteAddrRoutePredicateFactory.java | 2 |
请完成以下Java代码 | public class SunJaasKerberosClient implements KerberosClient {
private boolean debug = false;
private boolean multiTier = false;
private static final Log LOG = LogFactory.getLog(SunJaasKerberosClient.class);
@Override
public JaasSubjectHolder login(String username, String password) {
LOG.debug("Trying to authenticate " + username + " with Kerberos");
JaasSubjectHolder result;
try {
LoginContext loginContext = new LoginContext("", null,
new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
loginContext.login();
Subject jaasSubject = loginContext.getSubject();
if (LOG.isDebugEnabled()) {
LOG.debug("Kerberos authenticated user: " + jaasSubject);
}
String validatedUsername = jaasSubject.getPrincipals().iterator().next().toString();
Subject subjectCopy = JaasUtil.copySubject(jaasSubject);
result = new JaasSubjectHolder(subjectCopy, validatedUsername);
if (!this.multiTier) {
loginContext.logout();
}
}
catch (LoginException ex) {
throw new BadCredentialsException("Kerberos authentication failed", ex);
}
return result;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public void setMultiTier(boolean multiTier) {
this.multiTier = multiTier;
}
private static final class LoginConfig extends Configuration {
private boolean debug;
private LoginConfig(boolean debug) {
super();
this.debug = debug;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put("storeKey", "true");
if (this.debug) {
options.put("debug", "true");
}
return new AppConfigurationEntry[] {
new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), };
}
} | static final class KerberosClientCallbackHandler implements CallbackHandler {
private String username;
private String password;
private KerberosClientCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback ncb = (NameCallback) callback;
ncb.setName(this.username);
}
else if (callback instanceof PasswordCallback) {
PasswordCallback pwcb = (PasswordCallback) callback;
pwcb.setPassword(this.password.toCharArray());
}
else {
throw new UnsupportedCallbackException(callback,
"We got a " + callback.getClass().getCanonicalName()
+ ", but only NameCallback and PasswordCallback is supported");
}
}
}
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\SunJaasKerberosClient.java | 1 |
请完成以下Java代码 | public String toString()
{
return String.valueOf(value);
}
@Override
public int hashCode()
{
return value;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof MutableInt)
{
final MutableInt other = (MutableInt)obj;
return value == other.value;
}
else
{
return false;
}
}
@Override
public int compareTo(final MutableInt obj)
{
return value - obj.value;
}
public void add(final int valueToAdd)
{
value += valueToAdd;
}
public void increment()
{
value++;
}
public int incrementAndGet()
{
value++; | return value;
}
public int decrementAndGet()
{
value--;
return value;
}
public int incrementIf(final boolean condition)
{
if (condition)
{
value++;
}
return value;
}
public boolean isZero()
{
return value == 0;
}
public boolean isGreaterThanZero()
{
return value > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\MutableInt.java | 1 |
请完成以下Java代码 | List<ArticleWithAuthor> articleRightJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "RIGHT JOIN");
return executeQuery(query);
}
List<ArticleWithAuthor> articleFullJoinAuthor() {
String query = String.format(QUERY_TEMPLATE, "FULL JOIN");
return executeQuery(query);
}
private List<ArticleWithAuthor> executeQuery(String query) {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(query);
return mapToList(resultSet);
} catch (SQLException e) {
e.printStackTrace(); | }
return null;
}
private List<ArticleWithAuthor> mapToList(ResultSet resultSet) throws SQLException {
List<ArticleWithAuthor> list = new ArrayList<>();
while (resultSet.next()) {
ArticleWithAuthor articleWithAuthor = new ArticleWithAuthor(
resultSet.getString("TITLE"),
resultSet.getString("FIRST_NAME"),
resultSet.getString("LAST_NAME")
);
list.add(articleWithAuthor);
}
return list;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\joins\ArticleWithAuthorDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShipmentCosts
{
//
// P_Asset -> P_COGS
@NonNull CostAmountAndQty shippedButNotNotified;
@Builder
private ShipmentCosts(
@NonNull final CostAmountAndQty shippedButNotNotified)
{
this.shippedButNotNotified = Check.assumeNotNull(shippedButNotNotified, "shippedButNotNotified");
}
public static ShipmentCosts extractAccountableFrom(@NonNull final CostDetailCreateResultsList results, @NonNull final AcctSchema acctSchema)
{
return builder()
.shippedButNotNotified(Objects.requireNonNull(results.getAmtAndQtyToPost(CostAmountType.MAIN, acctSchema).map(CostAmountAndQty::negate).orElse(null)))
.build();
}
public static ShipmentCosts extractFrom(@NonNull final CostDetailCreateRequest request)
{
final CostAmountAndQty amtAndQty = CostAmountAndQty.of(request.getAmt(), request.getQty());
final ShipmentCosts shipmentCosts;
if (request.getAmtType() == CostAmountType.MAIN)
{
shipmentCosts = builder().shippedButNotNotified(amtAndQty.negate()).build();
}
else
{
throw new IllegalArgumentException();
}
return shipmentCosts; | }
public interface CostAmountAndQtyAndTypeMapper
{
CostDetailCreateResult shippedButNotNotified(CostAmountAndQty amtAndQty, CostAmountType type);
}
public CostDetailCreateResultsList toCostDetailCreateResultsList(@NonNull final CostAmountAndQtyAndTypeMapper mapper)
{
final ArrayList<CostDetailCreateResult> resultsList = new ArrayList<>();
{
final CostDetailCreateResult result = mapper.shippedButNotNotified(shippedButNotNotified, CostAmountType.MAIN);
resultsList.add(Check.assumeNotNull(result, "result shall not be null"));
}
return CostDetailCreateResultsList.ofList(resultsList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\ShipmentCosts.java | 2 |
请完成以下Java代码 | public class EntityTypes {
public static final String APPLICATION = "Application";
public static final String ATTACHMENT = "Attachment";
public static final String AUTHORIZATION = "Authorization";
public static final String FILTER = "Filter";
public static final String GROUP = "Group";
public static final String GROUP_MEMBERSHIP = "Group membership";
public static final String IDENTITY_LINK = "IdentityLink";
public static final String TASK = "Task";
public static final String HISTORIC_TASK = "HistoricTask";
public static final String USER = "User";
public static final String PROCESS_INSTANCE = "ProcessInstance";
public static final String HISTORIC_PROCESS_INSTANCE = "HistoricProcessInstance";
public static final String PROCESS_DEFINITION = "ProcessDefinition";
public static final String JOB = "Job";
public static final String JOB_DEFINITION = "JobDefinition";
public static final String VARIABLE = "Variable";
public static final String DEPLOYMENT = "Deployment";
public static final String DECISION_DEFINITION = "DecisionDefinition";
public static final String CASE_DEFINITION = "CaseDefinition";
public static final String EXTERNAL_TASK = "ExternalTask";
public static final String TENANT = "Tenant"; | public static final String TENANT_MEMBERSHIP = "TenantMembership";
public static final String BATCH = "Batch";
public static final String DECISION_REQUIREMENTS_DEFINITION = "DecisionRequirementsDefinition";
public static final String DECISION_INSTANCE = "DecisionInstance";
public static final String REPORT = "Report";
public static final String DASHBOARD = "Dashboard";
public static final String METRICS = "Metrics";
public static final String TASK_METRICS = "TaskMetrics";
public static final String CASE_INSTANCE = "CaseInstance";
public static final String PROPERTY = "Property";
public static final String OPERATION_LOG_CATEGORY = "OperationLogCatgeory";
public static final String OPTIMIZE = "Optimize";
public static final String OPERATION_LOG = "OperationLog";
public static final String INCIDENT = "Incident";
public static final String SYSTEM = "System";
public static final String COMMENT = "Comment";
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\EntityTypes.java | 1 |
请完成以下Java代码 | private String toSummaryString(final DataImportResult importResult)
{
final StringBuilder result = new StringBuilder();
result.append("@IsImportScheduled@");
final InsertIntoImportTableResult insertIntoImportTable = importResult.getInsertIntoImportTable();
if (insertIntoImportTable != null)
{
result.append("#").append(insertIntoImportTable.getCountValidRows())
.append(", @IsError@ #").append(insertIntoImportTable.getErrors().size());
}
result.append(" (took " + importResult.getDuration() + ")");
return result.toString();
}
private AttachmentEntryId getAttachmentEntryId() | {
return p_AD_AttachmentEntry_ID;
}
private DataImportConfigId getDataImportConfigId()
{
return DataImportConfigId.ofRepoId(getRecord_ID());
}
private void deleteAttachmentEntry()
{
final AttachmentEntry attachmentEntry = attachmentEntryService.getById(getAttachmentEntryId());
attachmentEntryService.unattach(getDataImportConfigId().toRecordRef(), attachmentEntry);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\process\C_DataImport_ImportAttachment.java | 1 |
请完成以下Java代码 | public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<String> getInvolvedGroups() { | return involvedGroups;
}
public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public final IQualityInspectionLineBuilder setNegateQty(final boolean negateQty)
{
_negateQty = negateQty;
return this;
}
protected final boolean isNegateQty()
{
return _negateQty;
}
@Override
public final IQualityInspectionLineBuilder setQtyProjected(final BigDecimal qtyProjected)
{
_qtyProjected = qtyProjected;
_qtyProjectedSet = true;
return this;
}
protected boolean isQtyProjectedSet()
{
return _qtyProjectedSet;
}
protected BigDecimal getQtyProjected()
{
return _qtyProjected;
}
@Override
public final IQualityInspectionLineBuilder setC_UOM(final I_C_UOM uom)
{
_uom = uom;
_uomSet = true;
return this;
}
protected final I_C_UOM getC_UOM()
{
if (_uomSet)
{
return _uom;
}
else
{
final IProductionMaterial productionMaterial = getProductionMaterial();
return productionMaterial.getC_UOM();
}
}
@Override
public final IQualityInspectionLineBuilder setPercentage(final BigDecimal percentage)
{
_percentage = percentage;
return this;
}
private BigDecimal getPercentage()
{
return _percentage;
}
@Override
public final IQualityInspectionLineBuilder setName(final String name)
{
_name = name;
return this;
}
protected final String getName() | {
return _name;
}
private IHandlingUnitsInfo getHandlingUnitsInfoToSet()
{
if (_handlingUnitsInfoSet)
{
return _handlingUnitsInfo;
}
return null;
}
@Override
public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo)
{
_handlingUnitsInfo = handlingUnitsInfo;
_handlingUnitsInfoSet = true;
return this;
}
private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet()
{
if (_handlingUnitsInfoProjectedSet)
{
return _handlingUnitsInfoProjected;
}
return null;
}
@Override
public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo)
{
_handlingUnitsInfoProjected = handlingUnitsInfo;
_handlingUnitsInfoProjectedSet = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java | 1 |
请完成以下Java代码 | public Optional<Article> findBySlug(String slug) {
return articleJpaRepository.findBySlug(slug);
}
@Override
public List<Article> findByAuthors(Collection<User> authors, ArticleFacets facets) {
return articleJpaRepository
.findByAuthorInOrderByCreatedAtDesc(authors, PageRequest.of(facets.page(), facets.size()))
.getContent();
}
@Override
@Transactional(readOnly = true)
public ArticleDetails findArticleDetails(Article article) {
int totalFavorites = articleFavoriteJpaRepository.countByArticle(article);
return ArticleDetails.unauthenticated(article, totalFavorites);
}
@Override
@Transactional(readOnly = true)
public ArticleDetails findArticleDetails(User requester, Article article) {
int totalFavorites = articleFavoriteJpaRepository.countByArticle(article);
boolean favorited = articleFavoriteJpaRepository.existsByUserAndArticle(requester, article); | return new ArticleDetails(article, totalFavorites, favorited);
}
@Override
@Transactional
public void delete(Article article) {
articleCommentJpaRepository.deleteByArticle(article);
articleJpaRepository.delete(article);
}
@Override
public boolean existsBy(String title) {
return articleJpaRepository.existsByTitle(title);
}
} | repos\realworld-java21-springboot3-main\module\persistence\src\main\java\io\zhc1\realworld\persistence\ArticleRepositoryAdapter.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final Plan plan = creatPlan().orElseThrow();
final PaymentAmtMultiplier amtMultiplier = plan.getAmtMultiplier();
final Amount amountToWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToWriteOff());
paymentBL.paymentWriteOff(
plan.getPaymentId(),
amountToWriteOff.toMoney(moneyService::getCurrencyIdByCurrencyCode),
p_DateTrx.atStartOfDay(SystemTime.zoneId()).toInstant(),
null);
return MSG_OK;
}
//
//
//
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<PaymentRow> paymentRows)
{
if (paymentRows.size() != 1)
{
return ExplainedOptional.emptyBecause("Only one payment row can be selected for write-off");
}
final PaymentRow paymentRow = CollectionUtils.singleElement(paymentRows);
final Amount openAmt = paymentRow.getOpenAmt();
if (openAmt.signum() == 0)
{
return ExplainedOptional.emptyBecause("Zero open amount. Nothing to write-off"); | }
return ExplainedOptional.of(
Plan.builder()
.paymentId(paymentRow.getPaymentId())
.amtMultiplier(paymentRow.getPaymentAmtMultiplier())
.amountToWriteOff(openAmt)
.build());
}
@Value
@Builder
private static class Plan
{
@NonNull PaymentId paymentId;
@NonNull PaymentAmtMultiplier amtMultiplier;
@NonNull Amount amountToWriteOff;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_PaymentWriteOff.java | 1 |
请完成以下Java代码 | public static void jdkFlatMapping() {
System.out.println("Java flatMapping");
System.out.println("====================================");
java.util.stream.Stream.of(42).flatMap(i -> java.util.stream.Stream.generate(() -> {
System.out.println("nested call");
return 42;
})).findAny();
}
public static void vavrFlatMapping() {
System.out.println("Vavr flatMapping");
System.out.println("====================================");
Stream.of(42)
.flatMap(i -> Stream.continually(() -> {
System.out.println("nested call");
return 42;
}))
.get(0);
}
public static void vavrStreamManipulation() {
System.out.println("Vavr Stream Manipulation");
System.out.println("====================================");
List<String> stringList = new ArrayList<>();
stringList.add("foo");
stringList.add("bar");
stringList.add("baz");
Stream<String> vavredStream = Stream.ofAll(stringList);
vavredStream.forEach(item -> System.out.println("Vavr Stream item: " + item));
Stream<String> vavredStream2 = vavredStream.insert(2, "buzz"); | vavredStream2.forEach(item -> System.out.println("Vavr Stream item after stream addition: " + item));
stringList.forEach(item -> System.out.println("List item after stream addition: " + item));
Stream<String> deletionStream = vavredStream.remove("bar");
deletionStream.forEach(item -> System.out.println("Vavr Stream item after stream item deletion: " + item));
}
public static void vavrStreamDistinct() {
Stream<String> vavredStream = Stream.of("foo", "bar", "baz", "buxx", "bar", "bar", "foo");
Stream<String> distinctVavrStream = vavredStream.distinctBy((y, z) -> {
return y.compareTo(z);
});
distinctVavrStream.forEach(item -> System.out.println("Vavr Stream item after distinct query " + item));
}
} | repos\tutorials-master\vavr-modules\vavr\src\main\java\com\baeldung\samples\java\vavr\VavrSampler.java | 1 |
请完成以下Java代码 | public String toString()
{
return "HUStorage [hu=" + hu + ", virtualHU=" + virtualHU + "]";
}
@Override
public I_C_UOM getC_UOMOrNull()
{
return dao.getC_UOMOrNull(hu);
}
@Override
public boolean isSingleProductWithQtyEqualsTo(@NonNull final ProductId productId, @NonNull final Quantity qty)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return productStorages.size() == 1
&& ProductId.equals(productStorages.get(0).getProductId(), productId)
&& productStorages.get(0).getQty(qty.getUOM()).compareTo(qty) == 0;
} | @Override
public boolean isSingleProductStorageMatching(@NonNull final ProductId productId)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return isSingleProductStorageMatching(productStorages, productId);
}
private static boolean isSingleProductStorageMatching(@NonNull final List<IHUProductStorage> productStorages, @NotNull final ProductId productId)
{
return productStorages.size() == 1 && ProductId.equals(productStorages.get(0).getProductId(), productId);
}
@Override
public boolean isEmptyOrSingleProductStorageMatching(@NonNull final ProductId productId)
{
final List<IHUProductStorage> productStorages = getProductStorages();
return productStorages.isEmpty() || isSingleProductStorageMatching(productStorages, productId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorage.java | 1 |
请完成以下Java代码 | private static String encode(byte[] bytes) {
ByteArrayOutputStream result = new ByteArrayOutputStream(bytes.length);
for (byte b : bytes) {
if (isAllowed(b)) {
result.write(b);
}
else {
result.write('%');
result.write(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16)));
result.write(Character.toUpperCase(Character.forDigit(b & 0xF, 16)));
}
}
return result.toString(StandardCharsets.UTF_8);
}
private static boolean isAllowed(int ch) { | for (char allowed : ALLOWED) {
if (ch == allowed) {
return true;
}
}
return isAlpha(ch) || isDigit(ch);
}
private static boolean isAlpha(int ch) {
return (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z');
}
private static boolean isDigit(int ch) {
return (ch >= '0' && ch <= '9');
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\UriPathEncoder.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final UomId uomId = productBL.getStockUOMId(productId);
final StockQtyAndUOMQty levelMin = StockQtyAndUOMQtys.createConvert(this.levelMin, productId, uomId);
final StockQtyAndUOMQty levelMax = this.levelMax == null ? levelMin : StockQtyAndUOMQtys.createConvert(this.levelMax, productId, uomId);
replenishInfoRepository.save(ReplenishInfo.builder()
.identifier(ReplenishInfo.Identifier.builder()
.productId(productId)
.warehouseId(warehouseId)
.build())
.min(levelMin)
.max(levelMax)
.build());
return MSG_OK;
}
@Nullable
@Override
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final MaterialNeedsPlannerRow materialNeedsPlannerRow = MaterialNeedsPlannerRow.ofViewRow(getSingleSelectedRow());
if (PARAM_M_Product_ID.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getProductId();
}
else if (PARAM_M_Warehouse_ID.equals(parameter.getColumnName())) | {
return materialNeedsPlannerRow.getWarehouseId();
}
else if (PARAM_Level_Min.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getLevelMin();
}
else if (PARAM_Level_Max.equals(parameter.getColumnName()))
{
return materialNeedsPlannerRow.getLevelMax();
}
else
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
protected void postProcess(final boolean success)
{
getView().invalidateSelection();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\process\WEBUI_M_Replenish_Add_Update_Demand.java | 1 |
请完成以下Java代码 | private BPartnerLocationAndCaptureId getHandOverLocationEffectiveId(@NonNull final I_C_OLCand olCand)
{
return coalesceSuppliers(
() -> BPartnerLocationAndCaptureId.ofRepoIdOrNull(olCand.getHandOver_Partner_Override_ID(), olCand.getHandOver_Location_Override_ID(), olCand.getHandOver_Location_Override_Value_ID()),
() -> BPartnerLocationAndCaptureId.ofRepoIdOrNull(olCand.getHandOver_Partner_ID(), olCand.getHandOver_Location_ID(), olCand.getHandOver_Location_Value_ID()),
() -> getLocationAndCaptureEffectiveId(olCand, Type.SHIP_TO));
}
@Override
public Optional<StockQtyAndUOMQty> getQtyShipped(final I_C_OLCand olCand)
{
if (InterfaceWrapperHelper.isNull(olCand, I_C_OLCand.COLUMNNAME_QtyShipped))
{
return Optional.empty();
}
final Quantity qtyShipped = Quantity.of(olCand.getQtyShipped(), getC_UOM_Effective(olCand));
final ProductId productId = ProductId.ofRepoId(olCand.getM_Product_ID());
final Quantity qtyShippedProductUOM = uomConversionBL.convertToProductUOM(qtyShipped, productId);
final StockQtyAndUOMQty.StockQtyAndUOMQtyBuilder builder = StockQtyAndUOMQty.builder()
.productId(productId)
.stockQty(qtyShippedProductUOM);
final UomId catchWeightUomId = UomId.ofRepoIdOrNull(olCand.getQtyShipped_CatchWeight_UOM_ID());
if (catchWeightUomId != null) | {
final Quantity catchWeight = Quantity.of(olCand.getQtyShipped_CatchWeight(), uomDAO.getById(catchWeightUomId));
builder.uomQty(catchWeight);
}
return Optional.of(builder.build());
}
@Override
public Optional<BigDecimal> getManualQtyInPriceUOM(final @NonNull I_C_OLCand record)
{
return !InterfaceWrapperHelper.isNull(record, I_C_OLCand.COLUMNNAME_ManualQtyInPriceUOM)
? Optional.of(record.getManualQtyInPriceUOM())
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\impl\OLCandEffectiveValuesBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PmsProductAttributeCategoryController {
@Autowired
private PmsProductAttributeCategoryService productAttributeCategoryService;
@ApiOperation("添加商品属性分类")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestParam String name) {
int count = productAttributeCategoryService.create(name);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("修改商品属性分类")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestParam String name) {
int count = productAttributeCategoryService.update(id, name);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("删除单个商品属性分类")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = productAttributeCategoryService.delete(id);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
} | @ApiOperation("获取单个商品属性分类信息")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsProductAttributeCategory> getItem(@PathVariable Long id) {
PmsProductAttributeCategory productAttributeCategory = productAttributeCategoryService.getItem(id);
return CommonResult.success(productAttributeCategory);
}
@ApiOperation("分页获取所有商品属性分类")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<PmsProductAttributeCategory>> getList(@RequestParam(defaultValue = "5") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum) {
List<PmsProductAttributeCategory> productAttributeCategoryList = productAttributeCategoryService.getList(pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(productAttributeCategoryList));
}
@ApiOperation("获取所有商品属性分类及其下属性")
@RequestMapping(value = "/list/withAttr", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<PmsProductAttributeCategoryItem>> getListWithAttr() {
List<PmsProductAttributeCategoryItem> productAttributeCategoryResultList = productAttributeCategoryService.getListWithAttr();
return CommonResult.success(productAttributeCategoryResultList);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsProductAttributeCategoryController.java | 2 |
请完成以下Java代码 | public I_C_UOM getC_UOM()
{
return storage.getC_UOM();
}
@Override
public BigDecimal getQtyAllocated()
{
return storage.getQtyFree();
}
@Override
public BigDecimal getQtyToAllocate()
{
return storage.getQty().toBigDecimal();
}
@Override
public Object getTrxReferencedModel()
{
return referenceModel;
}
protected IProductStorage getStorage()
{
return storage;
}
@Override
public IAllocationSource createAllocationSource(final I_M_HU hu)
{
return HUListAllocationSourceDestination.of(hu);
} | @Override
public boolean isReadOnly()
{
return readonly;
}
@Override
public void setReadOnly(final boolean readonly)
{
this.readonly = readonly;
}
@Override
public I_M_HU_Item getInnerHUItem()
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java | 1 |
请完成以下Java代码 | public void setKeyInfo(KeyInfoType value) {
this.keyInfo = value;
}
/**
* Gets the value of the cipherData property.
*
* @return
* possible object is
* {@link CipherDataType }
*
*/
public CipherDataType getCipherData() {
return cipherData;
}
/**
* Sets the value of the cipherData property.
*
* @param value
* allowed object is
* {@link CipherDataType }
*
*/
public void setCipherData(CipherDataType value) {
this.cipherData = value;
}
/**
* Gets the value of the encryptionProperties property.
*
* @return
* possible object is
* {@link EncryptionPropertiesType }
*
*/
public EncryptionPropertiesType getEncryptionProperties() {
return encryptionProperties;
}
/**
* Sets the value of the encryptionProperties property.
*
* @param value
* allowed object is
* {@link EncryptionPropertiesType }
*
*/
public void setEncryptionProperties(EncryptionPropertiesType value) {
this.encryptionProperties = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/** | * Gets the value of the mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
/**
* Gets the value of the encoding property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEncoding() {
return encoding;
}
/**
* Sets the value of the encoding property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEncoding(String value) {
this.encoding = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptedType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setIdentificationOfUse(String value) {
this.identificationOfUse = value;
}
/**
* Gets the value of the specialConditions property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecialConditions() {
return specialConditions;
}
/**
* Sets the value of the specialConditions property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialConditions(String value) {
this.specialConditions = value;
}
/**
* Gets the value of the progressNumberDifference property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getProgressNumberDifference() {
return progressNumberDifference;
}
/**
* Sets the value of the progressNumberDifference property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setProgressNumberDifference(BigInteger value) {
this.progressNumberDifference = value;
}
/**
* Gets the value of the kanbanID 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 kanbanID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getKanbanID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getKanbanID() {
if (kanbanID == null) {
kanbanID = new ArrayList<String>();
}
return this.kanbanID;
}
/**
* The classification of the product/service in free-text form.Gets the value of the classification 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 classification property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getClassification().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ClassificationType }
*
*
*/
public List<ClassificationType> getClassification() {
if (classification == null) {
classification = new ArrayList<ClassificationType>();
}
return this.classification;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AdditionalLineItemInformationType.java | 2 |
请完成以下Java代码 | public boolean checkPassword(String userId, String password) {
return getIdmIdentityService().checkPassword(userId, password);
}
@Override
public void deleteUser(String userId) {
getIdmIdentityService().deleteUser(userId);
}
@Override
public void setUserPicture(String userId, Picture picture) {
getIdmIdentityService().setUserPicture(userId, picture);
}
@Override
public Picture getUserPicture(String userId) {
return getIdmIdentityService().getUserPicture(userId);
}
@Override
public void setAuthenticatedUserId(String authenticatedUserId) {
Authentication.setAuthenticatedUserId(authenticatedUserId);
}
@Override
public String getUserInfo(String userId, String key) {
return getIdmIdentityService().getUserInfo(userId, key); | }
@Override
public List<String> getUserInfoKeys(String userId) {
return getIdmIdentityService().getUserInfoKeys(userId);
}
@Override
public void setUserInfo(String userId, String key, String value) {
getIdmIdentityService().setUserInfo(userId, key, value);
}
@Override
public void deleteUserInfo(String userId, String key) {
getIdmIdentityService().deleteUserInfo(userId, key);
}
protected IdmIdentityService getIdmIdentityService() {
IdmIdentityService idmIdentityService = EngineServiceUtil.getIdmIdentityService(configuration);
if (idmIdentityService == null) {
throw new FlowableException("Trying to use idm identity service when it is not initialized");
}
return idmIdentityService;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\IdentityServiceImpl.java | 1 |
请完成以下Java代码 | class UnixDomainSocketClient {
public static void main(String[] args) throws Exception {
new UnixDomainSocketClient().runClient();
}
void runClient() throws IOException {
Path socketPath = Path.of(System.getProperty("user.home"))
.resolve("baeldung.socket");
UnixDomainSocketAddress socketAddress = getAddress(socketPath);
SocketChannel channel = openSocketChannel(socketAddress);
String message = "Hello from Baeldung Unix domain socket article";
writeMessage(channel, message);
}
UnixDomainSocketAddress getAddress(Path socketPath) {
return UnixDomainSocketAddress.of(socketPath);
} | SocketChannel openSocketChannel(UnixDomainSocketAddress socketAddress) throws IOException {
SocketChannel channel = SocketChannel
.open(StandardProtocolFamily.UNIX);
channel.connect(socketAddress);
return channel;
}
void writeMessage(SocketChannel socketChannel, String message) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
buffer.put(message.getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
socketChannel.write(buffer);
}
}
} | repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\socket\UnixDomainSocketClient.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonReaderCheckoutRequest
{
@Nullable String description;
@JsonProperty("return_url")
@Nullable String return_url;
@JsonProperty("total_amount")
@NonNull JsonAmount total_amount;
//
//
//
@Value
@Builder
@Jacksonized
public static class JsonAmount
{
/**
* Currency ISO 4217 code
*/ | @NonNull String currency;
int minor_unit;
int value;
public static JsonAmount ofAmount(@NonNull final Amount amount, @NonNull CurrencyPrecision precision)
{
final BigDecimal amountBD = precision.round(amount.toBigDecimal());
if (amountBD.compareTo(amount.toBigDecimal()) != 0)
{
throw new AdempiereException("Expected " + amount + " to have maximum " + precision + " decimals precision");
}
final int amountInt = amountBD.movePointRight(precision.toInt()).intValueExact();
return builder()
.currency(amount.getCurrencyCode().toThreeLetterCode())
.value(amountInt)
.minor_unit(precision.toInt())
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\json\JsonReaderCheckoutRequest.java | 2 |
请完成以下Java代码 | public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class Service {
private String url;
private String token;
private String description;
public String getUrl() { | return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yaml\YAMLConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getBookedSeconds()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_BookedSeconds);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setComments (final @Nullable java.lang.String Comments)
{
set_Value (COLUMNNAME_Comments, Comments);
}
@Override
public java.lang.String getComments()
{
return get_ValueAsString(COLUMNNAME_Comments);
}
@Override
public void setHoursAndMinutes (final java.lang.String HoursAndMinutes)
{
set_Value (COLUMNNAME_HoursAndMinutes, HoursAndMinutes);
}
@Override
public java.lang.String getHoursAndMinutes()
{
return get_ValueAsString(COLUMNNAME_HoursAndMinutes);
}
@Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue()
{
return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class);
}
@Override
public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
} | @Override
public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
}
@Override
public void setS_TimeBooking_ID (final int S_TimeBooking_ID)
{
if (S_TimeBooking_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeBooking_ID, S_TimeBooking_ID);
}
@Override
public int getS_TimeBooking_ID()
{
return get_ValueAsInt(COLUMNNAME_S_TimeBooking_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_TimeBooking.java | 2 |
请完成以下Java代码 | public void setAD_WF_Responsible(org.compiere.model.I_AD_WF_Responsible AD_WF_Responsible)
{
set_ValueFromPO(COLUMNNAME_AD_WF_Responsible_ID, org.compiere.model.I_AD_WF_Responsible.class, AD_WF_Responsible);
}
/** Set Workflow - Verantwortlicher.
@param AD_WF_Responsible_ID
Verantwortlicher für die Ausführung des Workflow
*/
@Override
public void setAD_WF_Responsible_ID (int AD_WF_Responsible_ID)
{
if (AD_WF_Responsible_ID < 1)
set_Value (COLUMNNAME_AD_WF_Responsible_ID, null);
else
set_Value (COLUMNNAME_AD_WF_Responsible_ID, Integer.valueOf(AD_WF_Responsible_ID));
}
/** Get Workflow - Verantwortlicher.
@return Verantwortlicher für die Ausführung des Workflow
*/
@Override
public int getAD_WF_Responsible_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Responsible_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workflow - Verantwortlicher (text).
@param AD_WF_Responsible_Name Workflow - Verantwortlicher (text) */
@Override
public void setAD_WF_Responsible_Name (java.lang.String AD_WF_Responsible_Name)
{
set_Value (COLUMNNAME_AD_WF_Responsible_Name, AD_WF_Responsible_Name);
}
/** Get Workflow - Verantwortlicher (text).
@return Workflow - Verantwortlicher (text) */
@Override
public java.lang.String getAD_WF_Responsible_Name ()
{
return (java.lang.String)get_Value(COLUMNNAME_AD_WF_Responsible_Name);
}
/** Set Document Responsible.
@param C_Doc_Responsible_ID Document Responsible */
@Override
public void setC_Doc_Responsible_ID (int C_Doc_Responsible_ID)
{
if (C_Doc_Responsible_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, null);
else | set_ValueNoCheck (COLUMNNAME_C_Doc_Responsible_ID, Integer.valueOf(C_Doc_Responsible_ID));
}
/** Get Document Responsible.
@return Document Responsible */
@Override
public int getC_Doc_Responsible_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Doc_Responsible_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\workflow\model\X_C_Doc_Responsible.java | 1 |
请完成以下Java代码 | public ITrxItemExecutorBuilder<IT, RT> setProcessor(final ITrxItemProcessor<IT, RT> processor)
{
this._processor = processor;
return this;
}
private final ITrxItemProcessor<IT, RT> getProcessor()
{
Check.assumeNotNull(_processor, "processor is set");
return _processor;
}
@Override
public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler)
{
this._exceptionHandler = exceptionHandler;
return this;
}
private final ITrxItemExceptionHandler getExceptionHandler()
{
return _exceptionHandler;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy) | {
this._onItemErrorPolicy = onItemErrorPolicy;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch)
{
if (itemsPerBatch == Integer.MAX_VALUE)
{
this.itemsPerBatch = null;
}
else
{
this.itemsPerBatch = itemsPerBatch;
}
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints)
{
this._useTrxSavepoints = useTrxSavepoints;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java | 1 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
} | public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
} | repos\springBoot-master\springboot-elasticsearch\src\main\java\cn\abel\bean\User.java | 1 |
请完成以下Java代码 | private IAutoCloseable updateLoggerContextFrom(final BusinessRuleTrigger trigger)
{
return logger.temporaryChangeContext(contextBuilder -> contextBuilder.triggerId(trigger.getId()));
}
private ImmutableList<BusinessRuleAndTriggers> getRuleAndTriggers()
{
return rules.getByTriggerTableId(sourceModelRef.getAdTableId());
}
private BooleanWithReason checkTriggerMatching(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger)
{
final BusinessRuleStopwatch stopwatch = logger.newStopwatch();
BooleanWithReason matching = BooleanWithReason.FALSE;
try
{
if (!trigger.isChangeTypeMatching(timing))
{
return BooleanWithReason.falseBecause("timing not matching");
}
matching = checkConditionMatching(trigger.getCondition());
}
catch (final Exception ex)
{
logger.debug("Failed evaluating trigger condition {}/{} for {}/{}", rule, trigger, sourceModel, timing, ex);
matching = BooleanWithReason.falseBecause(ex);
}
finally
{
logger.debug(stopwatch, "Checked if trigger is matching source: {}", matching); | }
return matching;
}
private BooleanWithReason checkConditionMatching(@Nullable final Validation condition)
{
return condition == null || recordMatcher.isRecordMatching(sourceModelRef, condition)
? BooleanWithReason.TRUE
: BooleanWithReason.FALSE;
}
private void enqueueToRecompute(@NonNull final BusinessRule rule, @NonNull final BusinessRuleTrigger trigger)
{
eventRepository.create(BusinessRuleEventCreateRequest.builder()
.clientAndOrgId(clientAndOrgId)
.triggeringUserId(triggeringUserId)
.recordRef(sourceModelRef)
.businessRuleId(rule.getId())
.triggerId(trigger.getId())
.build());
logger.debug("Enqueued event for re-computation");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\trigger\BusinessRuleFireTriggersCommand.java | 1 |
请完成以下Java代码 | static I_C_UOM extractUOM(@NonNull final I_M_HU_PI_Item_Product itemProduct)
{
final I_C_UOM uom = extractUOMOrNull(itemProduct);
if (uom == null)
{
throw new AdempiereException("Cannot determine UOM of " + itemProduct.getName());
}
return uom;
}
I_M_HU_PI_Item_Product extractHUPIItemProduct(final I_C_Order order, final I_C_OrderLine orderLine);
int getRequiredLUCount(@NonNull Quantity qty, I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM);
static StockQtyAndUOMQty getMaxQtyCUsPerLU(final @NonNull StockQtyAndUOMQty qty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM, final ProductId productId)
{
final StockQtyAndUOMQty maxQtyCUsPerLU;
if (lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert(
qty.getStockQty(),
productId,
qty.getUOMQtyNotNull().getUomId());
}
else
{
maxQtyCUsPerLU = StockQtyAndUOMQtys.createConvert(
lutuConfigurationInStockUOM.getQtyCUsPerTU().multiply(lutuConfigurationInStockUOM.getQtyTU()),
productId,
qty.getUOMQtyNotNull().getUomId());
}
return maxQtyCUsPerLU;
}
static Quantity getQtyCUsPerTUInStockUOM(final @NonNull I_C_OrderLine orderLineRecord, final @NonNull Quantity stockQty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM)
{
final Quantity qtyCUsPerTUInStockUOM; | if (orderLineRecord.getQtyItemCapacity().signum() > 0)
{
// we use the capacity which the goods were ordered in
qtyCUsPerTUInStockUOM = Quantitys.of(orderLineRecord.getQtyItemCapacity(), stockQty.getUomId());
}
else if (!lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
// we make an educated guess, based on the packing-instruction's information
qtyCUsPerTUInStockUOM = Quantitys.of(lutuConfigurationInStockUOM.getQtyCUsPerTU(), stockQty.getUomId());
}
else
{
// we just don't have the info. So we assume that everything was put into one TU
qtyCUsPerTUInStockUOM = stockQty;
}
return qtyCUsPerTUInStockUOM;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\IHUPIItemProductBL.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent == null ? null : continent.trim();
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region == null ? null : region.trim();
}
public Float getSurfacearea() {
return surfacearea;
}
public void setSurfacearea(Float surfacearea) {
this.surfacearea = surfacearea;
}
public Short getIndepyear() {
return indepyear;
}
public void setIndepyear(Short indepyear) {
this.indepyear = indepyear;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public Float getLifeexpectancy() {
return lifeexpectancy;
}
public void setLifeexpectancy(Float lifeexpectancy) {
this.lifeexpectancy = lifeexpectancy;
}
public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold; | }
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname;
}
public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
}
public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
} | repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java | 1 |
请完成以下Java代码 | public List<Task> findTasksByQueryCriteria(TaskQueryImpl taskQuery) {
return taskDataManager.findTasksByQueryCriteria(taskQuery);
}
@Override
public List<Task> findTasksAndVariablesByQueryCriteria(TaskQueryImpl taskQuery) {
return taskDataManager.findTasksAndVariablesByQueryCriteria(taskQuery);
}
@Override
public long findTaskCountByQueryCriteria(TaskQueryImpl taskQuery) {
return taskDataManager.findTaskCountByQueryCriteria(taskQuery);
}
@Override
public List<Task> findTasksByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return taskDataManager.findTasksByNativeQuery(parameterMap, firstResult, maxResults);
}
@Override
public long findTaskCountByNativeQuery(Map<String, Object> parameterMap) {
return taskDataManager.findTaskCountByNativeQuery(parameterMap);
}
@Override
public List<Task> findTasksByParentTaskId(String parentTaskId) {
return taskDataManager.findTasksByParentTaskId(parentTaskId);
}
@Override
public void deleteTask(String taskId, String deleteReason, boolean cascade, boolean cancel) { | TaskEntity task = findById(taskId);
if (task != null) {
if (task.getExecutionId() != null) {
throw new ActivitiException("The task cannot be deleted because is part of a running process");
}
deleteTask(task, deleteReason, cascade, cancel);
} else if (cascade) {
getHistoricTaskInstanceEntityManager().delete(taskId);
}
}
@Override
public void deleteTask(String taskId, String deleteReason, boolean cascade) {
this.deleteTask(taskId, deleteReason, cascade, false);
}
@Override
public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) {
taskDataManager.updateTaskTenantIdForDeployment(deploymentId, newTenantId);
}
public TaskDataManager getTaskDataManager() {
return taskDataManager;
}
public void setTaskDataManager(TaskDataManager taskDataManager) {
this.taskDataManager = taskDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityManagerImpl.java | 1 |
请完成以下Java代码 | public Object run() {
RequestContext context = RequestContext.getCurrentContext();
context.getResponse().setCharacterEncoding("UTF-8");
String rewrittenResponse = rewriteBasePath(context);
if (context.getResponseGZipped()) {
try {
context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse)));
} catch (IOException e) {
log.error("Swagger-docs filter error", e);
}
} else {
context.setResponseBody(rewrittenResponse);
}
return null;
}
@SuppressWarnings("unchecked")
private String rewriteBasePath(RequestContext context) {
InputStream responseDataStream = context.getResponseDataStream();
String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();
try {
if (context.getResponseGZipped()) {
responseDataStream = new GZIPInputStream(context.getResponseDataStream());
}
String response = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
if (response != null) {
LinkedHashMap<String, Object> map = this.mapper.readValue(response, LinkedHashMap.class); | String basePath = requestUri.replace(Swagger2Controller.DEFAULT_URL, "");
map.put("basePath", basePath);
log.debug("Swagger-docs: rewritten Base URL with correct micro-service route: {}", basePath);
return mapper.writeValueAsString(map);
}
} catch (IOException e) {
log.error("Swagger-docs filter error", e);
}
return null;
}
public static byte[] gzipData(String content) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintWriter gzip = new PrintWriter(new GZIPOutputStream(bos));
gzip.print(content);
gzip.flush();
gzip.close();
return bos.toByteArray();
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\responserewriting\SwaggerBasePathRewritingFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FormModelResponse {
protected String id;
protected String name;
protected String description;
protected String key;
protected int version;
protected List<FormField> fields;
protected List<FormOutcome> outcomes;
protected String outcomeVariableName;
public FormModelResponse(FormInfo formInfo) {
this.id = formInfo.getId();
this.name = formInfo.getName();
this.description = formInfo.getDescription();
this.key = formInfo.getKey();
this.version = formInfo.getVersion();
}
public FormModelResponse(FormInfo formInfo, SimpleFormModel formModel) {
this(formInfo);
this.fields = formModel.getFields();
this.outcomes = formModel.getOutcomes();
this.outcomeVariableName = formModel.getOutcomeVariableName();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKey() {
return key;
} | public void setKey(String key) {
this.key = key;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public List<FormField> getFields() {
return fields;
}
public void setFields(List<FormField> fields) {
this.fields = fields;
}
public List<FormOutcome> getOutcomes() {
return outcomes;
}
public void setOutcomes(List<FormOutcome> outcomes) {
this.outcomes = outcomes;
}
public String getOutcomeVariableName() {
return outcomeVariableName;
}
public void setOutcomeVariableName(String outcomeVariableName) {
this.outcomeVariableName = outcomeVariableName;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\FormModelResponse.java | 2 |
请完成以下Java代码 | public class IpUtil {
private final static String UNKNOWN = "unknown";
private final static int MAX_LENGTH = 15;
/**
* 获取IP地址
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StrUtil.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
} | if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
log.error("IPUtils ERROR ", e);
}
// 使用代理,则获取第一个IP地址
if (!StrUtil.isEmpty(ip) && ip.length() > MAX_LENGTH) {
if (ip.indexOf(StrUtil.COMMA) > 0) {
ip = ip.substring(0, ip.indexOf(StrUtil.COMMA));
}
}
return ip;
}
} | repos\spring-boot-demo-master\demo-ratelimit-redis\src\main\java\com\xkcoding\ratelimit\redis\util\IpUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonQuery
{
@Nullable
@JsonProperty("field")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String field;
@NonNull
@JsonProperty("type")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
QueryType queryType;
@ApiModelProperty("Depending on the query-type, you can have either a `value` or `parameters`.")
@Nullable
@JsonProperty("parameters")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
Map<String, String> parameters;
@ApiModelProperty("Depending on the query-type, you can have either a `value` or `parameters`.")
@Nullable
@JsonProperty("value")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String value;
@Nullable
@JsonProperty("operator")
@JsonInclude(JsonInclude.Include.NON_EMPTY) | OperatorType operatorType;
@Nullable
@JsonProperty("queries")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
List<JsonQuery> jsonQueryList;
@Builder
public JsonQuery(
@JsonProperty("field") @Nullable final String field,
@JsonProperty("type") @NonNull final QueryType queryType,
@JsonProperty("parameters") @Nullable final Map<String, String> parameters,
@JsonProperty("value") @Nullable final String value,
@JsonProperty("operator") @Nullable final OperatorType operatorType,
@JsonProperty("queries") @Nullable @Singular final List<JsonQuery> jsonQueries)
{
this.field = field;
this.queryType = queryType;
this.parameters = parameters;
this.value = value;
this.operatorType = operatorType;
this.jsonQueryList = jsonQueries;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\model\JsonQuery.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public long getDateTimeIntervalStartTs(ZonedDateTime dateTime) {
long offset = getOffsetSafe();
ZonedDateTime shiftedNow = dateTime.minusSeconds(offset);
ZonedDateTime alignedStart = getAlignedBoundary(shiftedNow, false);
ZonedDateTime actualStart = alignedStart.plusSeconds(offset);
return actualStart.toInstant().toEpochMilli();
}
@Override
public long getCurrentIntervalEndTs() {
ZoneId zoneId = getZoneId();
ZonedDateTime now = ZonedDateTime.now(zoneId);
return getDateTimeIntervalEndTs(now);
}
@Override
public long getDateTimeIntervalEndTs(ZonedDateTime dateTime) {
long offset = getOffsetSafe();
ZonedDateTime shiftedNow = dateTime.minusSeconds(offset);
ZonedDateTime alignedEnd = getAlignedBoundary(shiftedNow, true);
ZonedDateTime actualEnd = alignedEnd.plusSeconds(offset);
return actualEnd.toInstant().toEpochMilli();
}
protected abstract ZonedDateTime alignToIntervalStart(ZonedDateTime reference);
protected ZonedDateTime getAlignedBoundary(ZonedDateTime reference, boolean next) { | ZonedDateTime base = alignToIntervalStart(reference);
return next ? getNextIntervalStart(base) : base;
}
@Override
public void validate() {
try {
getZoneId();
} catch (Exception ex) {
throw new IllegalArgumentException("Invalid timezone in interval: " + ex.getMessage());
}
if (offsetSec != null) {
if (offsetSec < 0) {
throw new IllegalArgumentException("Offset cannot be negative.");
}
if (TimeUnit.SECONDS.toMillis(offsetSec) >= getCurrentIntervalDurationMillis()) {
throw new IllegalArgumentException("Offset must be greater than interval duration.");
}
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\aggregation\single\interval\BaseAggInterval.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static class ImmutablesJdbcConfiguration extends AbstractJdbcConfiguration {
private final ResourceLoader resourceLoader;
public ImmutablesJdbcConfiguration(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* {@link JdbcConverter} that redirects entities to be instantiated towards the implementation. See
* {@link #IMMUTABLE_IMPLEMENTATION_CLASS} and
* {@link #getImplementationEntity(JdbcMappingContext, RelationalPersistentEntity)}.
*
* @param mappingContext
* @param operations
* @param relationResolver
* @param conversions
* @param dialect
* @return
*/
@Override
public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations,
@Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, Dialect dialect) {
var jdbcTypeFactory = new DefaultJdbcTypeFactory(operations.getJdbcOperations());
return new MappingJdbcConverter(mappingContext, relationResolver, conversions, jdbcTypeFactory) {
@Override
@SuppressWarnings("all")
protected <S> S readAggregate(ConversionContext context, RowDocumentAccessor documentAccessor,
TypeInformation<? extends S> typeHint) {
RelationalPersistentEntity<?> implementationEntity = getImplementationEntity(mappingContext,
mappingContext.getRequiredPersistentEntity(typeHint));
return (S) super.readAggregate(context, documentAccessor, implementationEntity.getTypeInformation());
} | };
}
/**
* Returns if the entity passed as an argument is an interface the implementation provided by Immutable is provided
* instead. In all other cases the entity passed as an argument is returned.
*/
@SuppressWarnings("unchecked")
private <T> RelationalPersistentEntity<T> getImplementationEntity(JdbcMappingContext mappingContext,
RelationalPersistentEntity<T> entity) {
Class<T> type = entity.getType();
if (type.isInterface()) {
var immutableClass = String.format(IMMUTABLE_IMPLEMENTATION_CLASS, type.getPackageName(), type.getSimpleName());
if (ClassUtils.isPresent(immutableClass, resourceLoader.getClassLoader())) {
return (RelationalPersistentEntity<T>) mappingContext
.getPersistentEntity(ClassUtils.resolveClassName(immutableClass, resourceLoader.getClassLoader()));
}
}
return entity;
}
}
} | repos\spring-data-examples-main\jdbc\immutables\src\main\java\example\springdata\jdbc\immutables\Application.java | 2 |
请完成以下Java代码 | public boolean hasResponseToken() {
return this.ticketValidation != null && this.ticketValidation.responseToken() != null;
}
/**
* Gets the (Base64) encoded response token assuming one is available.
* @return encoded response token
*/
public String getEncodedResponseToken() {
if (!hasResponseToken()) {
throw new IllegalStateException("Unauthenticated or no response token");
}
return Base64.getEncoder().encodeToString(this.ticketValidation.responseToken());
}
/**
* Unwraps an encrypted message using the gss context
* @param data the data
* @param offset data offset
* @param length data length
* @return the decrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] decrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException {
return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() {
public byte[] run() throws Exception {
final GSSContext context = getTicketValidation().getGssContext();
return context.unwrap(data, offset, length, new MessageProp(true));
}
});
}
/**
* Unwraps an encrypted message using the gss context
* @param data the data
* @return the decrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] decrypt(final byte[] data) throws PrivilegedActionException {
return decrypt(data, 0, data.length);
} | /**
* Wraps an message using the gss context
* @param data the data
* @param offset data offset
* @param length data length
* @return the encrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] encrypt(final byte[] data, final int offset, final int length) throws PrivilegedActionException {
return Subject.doAs(getTicketValidation().subject(), new PrivilegedExceptionAction<byte[]>() {
public byte[] run() throws Exception {
final GSSContext context = getTicketValidation().getGssContext();
return context.wrap(data, offset, length, new MessageProp(true));
}
});
}
/**
* Wraps an message using the gss context
* @param data the data
* @return the encrypted message
* @throws PrivilegedActionException if jaas throws and error
*/
public byte[] encrypt(final byte[] data) throws PrivilegedActionException {
return encrypt(data, 0, data.length);
}
@Override
public JaasSubjectHolder getJaasSubjectHolder() {
return this.jaasSubjectHolder;
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceRequestToken.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class ExecutorOneConfiguration {
@Bean(name = EXECUTOR_ONE_BEAN_NAME + "-properties")
@Primary
@ConfigurationProperties(prefix = "spring.task.execution-one") // 读取 spring.task.execution-one 配置到 TaskExecutionProperties 对象
public TaskExecutionProperties taskExecutionProperties() {
return new TaskExecutionProperties();
}
@Bean(name = EXECUTOR_ONE_BEAN_NAME)
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
// 创建 TaskExecutorBuilder 对象
TaskExecutorBuilder builder = createTskExecutorBuilder(this.taskExecutionProperties());
// 创建 ThreadPoolTaskExecutor 对象
return builder.build();
}
}
@Configuration
public static class ExecutorTwoConfiguration {
@Bean(name = EXECUTOR_TWO_BEAN_NAME + "-properties")
@ConfigurationProperties(prefix = "spring.task.execution-two") // 读取 spring.task.execution-two 配置到 TaskExecutionProperties 对象
public TaskExecutionProperties taskExecutionProperties() {
return new TaskExecutionProperties();
}
@Bean(name = EXECUTOR_TWO_BEAN_NAME)
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
// 创建 TaskExecutorBuilder 对象
TaskExecutorBuilder builder = createTskExecutorBuilder(this.taskExecutionProperties());
// 创建 ThreadPoolTaskExecutor 对象
return builder.build();
} | }
private static TaskExecutorBuilder createTskExecutorBuilder(TaskExecutionProperties properties) {
// Pool 属性
TaskExecutionProperties.Pool pool = properties.getPool();
TaskExecutorBuilder builder = new TaskExecutorBuilder();
builder = builder.queueCapacity(pool.getQueueCapacity());
builder = builder.corePoolSize(pool.getCoreSize());
builder = builder.maxPoolSize(pool.getMaxSize());
builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout());
builder = builder.keepAlive(pool.getKeepAlive());
// Shutdown 属性
TaskExecutionProperties.Shutdown shutdown = properties.getShutdown();
builder = builder.awaitTermination(shutdown.isAwaitTermination());
builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
// 其它基本属性
builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
// builder = builder.customizers(taskExecutorCustomizers.orderedStream()::iterator);
// builder = builder.taskDecorator(taskDecorator.getIfUnique());
return builder;
}
} | repos\SpringBoot-Labs-master\lab-29\lab-29-async-two\src\main\java\cn\iocoder\springboot\lab29\asynctask\config\AsyncConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | ServerHttpMessageConvertersCustomizer serverConvertersCustomizer(
ObjectProvider<HttpMessageConverters> legacyConverters,
ObjectProvider<HttpMessageConverter<?>> converters) {
return new DefaultServerHttpMessageConvertersCustomizer(legacyConverters.getIfAvailable(),
converters.orderedStream().toList());
}
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(HttpMessageConvertersProperties.class)
protected static class StringHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(StringHttpMessageConverter.class)
StringHttpMessageConvertersCustomizer stringHttpMessageConvertersCustomizer(
HttpMessageConvertersProperties properties) {
return new StringHttpMessageConvertersCustomizer(properties);
}
}
static class StringHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
StringHttpMessageConverter converter;
StringHttpMessageConvertersCustomizer(HttpMessageConvertersProperties properties) {
this.converter = new StringHttpMessageConverter(properties.getStringEncodingCharset());
this.converter.setWriteAcceptCharset(false);
}
@Override
public void customize(ClientBuilder builder) {
builder.withStringConverter(this.converter);
}
@Override
public void customize(ServerBuilder builder) { | builder.withStringConverter(this.converter);
}
}
static class NotReactiveWebApplicationCondition extends NoneNestedConditions {
NotReactiveWebApplicationCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnWebApplication(type = Type.REACTIVE)
private static final class ReactiveWebApplication {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\HttpMessageConvertersAutoConfiguration.java | 2 |
请完成以下Java代码 | 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 |
请在Spring Boot框架中完成以下Java代码 | public boolean isReloadOnUpdate() {
return this.reloadOnUpdate;
}
public void setReloadOnUpdate(boolean reloadOnUpdate) {
this.reloadOnUpdate = reloadOnUpdate;
}
public static class Options {
/**
* Supported SSL ciphers.
*/
private @Nullable Set<String> ciphers;
/**
* Enabled SSL protocols.
*/
private @Nullable Set<String> enabledProtocols;
public @Nullable Set<String> getCiphers() {
return this.ciphers;
}
public void setCiphers(@Nullable Set<String> ciphers) {
this.ciphers = ciphers;
}
public @Nullable Set<String> getEnabledProtocols() {
return this.enabledProtocols;
}
public void setEnabledProtocols(@Nullable Set<String> enabledProtocols) {
this.enabledProtocols = enabledProtocols;
}
}
public static class Key {
/**
* The password used to access the key in the key store.
*/
private @Nullable String password; | /**
* The alias that identifies the key in the key store.
*/
private @Nullable String alias;
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getAlias() {
return this.alias;
}
public void setAlias(@Nullable String alias) {
this.alias = alias;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslBundleProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getLogLevel() {
return this.logLevel;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public OffHeapProperties getOffHeap() {
return this.offHeap;
}
public PeerCacheProperties getPeer() {
return this.peer;
}
public CacheServerProperties getServer() {
return this.server;
}
public static class CompressionProperties {
private String compressorBeanName;
private String[] regionNames = {};
public String getCompressorBeanName() {
return this.compressorBeanName;
}
public void setCompressorBeanName(String compressorBeanName) {
this.compressorBeanName = compressorBeanName;
} | public String[] getRegionNames() {
return this.regionNames;
}
public void setRegionNames(String[] regionNames) {
this.regionNames = regionNames;
}
}
public static class OffHeapProperties {
private String memorySize;
private String[] regionNames = {};
public String getMemorySize() {
return this.memorySize;
}
public void setMemorySize(String memorySize) {
this.memorySize = memorySize;
}
public String[] getRegionNames() {
return this.regionNames;
}
public void setRegionNames(String[] regionNames) {
this.regionNames = regionNames;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java | 2 |
请完成以下Java代码 | private AccountDimension newMinimalAccountDimension(final I_I_GLJournal importRecord, final int accountId)
{
return AccountDimension.builder()
.setAcctSchemaId(AcctSchemaId.ofRepoIdOrNull(importRecord.getC_AcctSchema_ID()))
.setAD_Client_ID(importRecord.getAD_Client_ID())
.setAD_Org_ID(importRecord.getAD_Org_ID())
.setC_ElementValue_ID(accountId)
.build();
}
@Override
public Class<I_I_GLJournal> getImportModelClass()
{
return I_I_GLJournal.class;
}
@Override
public String getImportTableName()
{
return I_I_GLJournal.Table_Name;
} | @Override
protected String getTargetTableName()
{
return I_GL_Journal.Table_Name;
}
@Override
protected String getImportOrderBySql()
{
return "COALESCE(BatchDocumentNo, I_GLJournal_ID ||' '), COALESCE(JournalDocumentNo, " +
"I_GLJournal_ID ||' '), C_AcctSchema_ID, PostingType, C_DocType_ID, GL_Category_ID, " +
"C_Currency_ID, TRUNC(DateAcct), Line, I_GLJournal_ID";
}
@Override
public I_I_GLJournal retrieveImportRecord(Properties ctx, ResultSet rs)
{
return new X_I_GLJournal(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\impexp\GLJournalImportProcess.java | 1 |
请完成以下Java代码 | public class LifecycleEventEntity extends EventEntity<LifecycleEvent> implements BaseEntity<LifecycleEvent> {
@Column(name = EVENT_TYPE_COLUMN_NAME)
private String eventType;
@Column(name = EVENT_SUCCESS_COLUMN_NAME)
private boolean success;
@Column(name = EVENT_ERROR_COLUMN_NAME)
private String error;
public LifecycleEventEntity(LifecycleEvent event) {
super(event);
this.eventType = event.getLcEventType();
this.success = event.isSuccess();
this.error = event.getError();
} | @Override
public LifecycleEvent toData() {
return LifecycleEvent.builder()
.tenantId(TenantId.fromUUID(tenantId))
.entityId(entityId)
.serviceId(serviceId)
.id(id)
.ts(ts)
.lcEventType(eventType)
.success(success)
.error(error)
.build();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\LifecycleEventEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EventSubscriptionResource {
@Autowired
protected CmmnRestResponseFactory restResponseFactory;
@Autowired
protected CmmnRuntimeService runtimeService;
@Autowired(required=false)
protected CmmnRestApiInterceptor restApiInterceptor;
@ApiOperation(value = "Get a single event subscription", tags = { "Event subscriptions" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the event subscription exists and is returned."),
@ApiResponse(code = 404, message = "Indicates the requested event subscription does not exist.") | })
@GetMapping(value = "/cmmn-runtime/event-subscriptions/{eventSubscriptionId}", produces = "application/json")
public EventSubscriptionResponse getEventSubscription(@ApiParam(name = "eventSubscriptionId") @PathVariable String eventSubscriptionId) {
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery().id(eventSubscriptionId).singleResult();
if (eventSubscription == null) {
throw new FlowableObjectNotFoundException("Could not find a event subscription with id '" + eventSubscriptionId + "'.", EventSubscription.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessEventSubscriptionById(eventSubscription);
}
return restResponseFactory.createEventSubscriptionResponse(eventSubscription);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\EventSubscriptionResource.java | 2 |
请完成以下Java代码 | public OAuth2AccessTokenResponse build() {
Instant issuedAt = getIssuedAt();
Instant expiresAt = getExpiresAt();
OAuth2AccessTokenResponse accessTokenResponse = new OAuth2AccessTokenResponse();
accessTokenResponse.accessToken = new OAuth2AccessToken(this.tokenType, this.tokenValue, issuedAt,
expiresAt, this.scopes);
if (StringUtils.hasText(this.refreshToken)) {
accessTokenResponse.refreshToken = new OAuth2RefreshToken(this.refreshToken, issuedAt);
}
accessTokenResponse.additionalParameters = Collections
.unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap()
: this.additionalParameters);
return accessTokenResponse;
}
private Instant getIssuedAt() {
if (this.issuedAt == null) {
this.issuedAt = Instant.now();
}
return this.issuedAt;
}
/**
* expires_in is RECOMMENDED, as per spec
* https://tools.ietf.org/html/rfc6749#section-5.1 Therefore, expires_in may not
* be returned in the Access Token response which would result in the default | * value of 0. For these instances, default the expiresAt to +1 second from
* issuedAt time.
* @return
*/
private Instant getExpiresAt() {
if (this.expiresAt == null) {
Instant issuedAt = getIssuedAt();
this.expiresAt = (this.expiresIn > 0) ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1);
}
return this.expiresAt;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AccessTokenResponse.java | 1 |
请完成以下Java代码 | private I_AD_Column getAD_Column()
{
I_AD_Column column = data.getAD_Column();
if (column != null && column.getAD_Table_ID() != adTableId)
{
logger.warn("Column '" + column.getColumnName()
+ "' (ID=" + column.getAD_Column_ID() + ") does not match AD_Table_ID from parent. Attempting to retrieve column by name and tableId.");
column = null;
}
final String dataColumnName = data.getColumnName();
if (column != null && !dataColumnName.equalsIgnoreCase(column.getColumnName()))
{
logger.warn("Column ID collision '" + dataColumnName + "' with existing '" + column.getColumnName()
+ "' (ID=" + column.getAD_Column_ID() + "). Attempting to retrieve column by name and tableId.");
column = null;
} | if (column == null)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(data);
final String trxName = InterfaceWrapperHelper.getTrxName(data);
final String whereClause = I_AD_Column.COLUMNNAME_AD_Table_ID + "=?"
+ " AND " + I_AD_Column.COLUMNNAME_ColumnName + "=?";
column = new TypedSqlQuery<I_AD_Column>(ctx, I_AD_Column.class, whereClause, trxName)
.setParameters(adTableId, dataColumnName)
.firstOnly(I_AD_Column.class);
}
return column;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationDataExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JXlsExporter setLoader(final ClassLoader loader)
{
this._loader = loader;
return this;
}
public ClassLoader getLoader()
{
return _loader == null ? getClass().getClassLoader() : _loader;
}
public JXlsExporter setAD_Language(final String adLanguage)
{
this._adLanguage = adLanguage;
return this;
}
private Language getLanguage()
{
if (!Check.isEmpty(_adLanguage, true))
{
return Language.getLanguage(_adLanguage);
}
return Env.getLanguage(getContext());
}
public Locale getLocale()
{
final Language language = getLanguage();
if (language != null)
{
return language.getLocale();
}
return Locale.getDefault();
}
public JXlsExporter setTemplateResourceName(final String templateResourceName)
{
this._templateResourceName = templateResourceName;
return this;
}
private InputStream getTemplate()
{
if (_template != null)
{
return _template;
}
if (!Check.isEmpty(_templateResourceName, true))
{
final ClassLoader loader = getLoader();
final InputStream template = loader.getResourceAsStream(_templateResourceName);
if (template == null)
{
throw new JXlsExporterException("Could not find template for name: " + _templateResourceName + " using " + loader);
}
return template;
}
throw new JXlsExporterException("Template is not configured");
}
public JXlsExporter setTemplate(final InputStream template)
{
this._template = template;
return this;
}
private IXlsDataSource getDataSource()
{
Check.assumeNotNull(_dataSource, "dataSource not null");
return _dataSource;
} | public JXlsExporter setDataSource(final IXlsDataSource dataSource)
{
this._dataSource = dataSource;
return this;
}
public JXlsExporter setResourceBundle(final ResourceBundle resourceBundle)
{
this._resourceBundle = resourceBundle;
return this;
}
private ResourceBundle getResourceBundle()
{
if (_resourceBundle != null)
{
return _resourceBundle;
}
if (!Check.isEmpty(_templateResourceName, true))
{
String baseName = null;
try
{
final int dotIndex = _templateResourceName.lastIndexOf('.');
baseName = dotIndex <= 0 ? _templateResourceName : _templateResourceName.substring(0, dotIndex);
return ResourceBundle.getBundle(baseName, getLocale(), getLoader());
}
catch (final MissingResourceException e)
{
logger.debug("No resource found for {}", baseName);
}
}
return null;
}
public Map<String, String> getResourceBundleAsMap()
{
final ResourceBundle bundle = getResourceBundle();
if (bundle == null)
{
return ImmutableMap.of();
}
return ResourceBundleMapWrapper.of(bundle);
}
public JXlsExporter setProperty(@NonNull final String name, @NonNull final Object value)
{
Check.assumeNotEmpty(name, "name not empty");
_properties.put(name, value);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JXlsExporter.java | 2 |
请完成以下Java代码 | public void setJSONPathShopwareID (final @Nullable java.lang.String JSONPathShopwareID)
{
set_Value (COLUMNNAME_JSONPathShopwareID, JSONPathShopwareID);
}
@Override
public java.lang.String getJSONPathShopwareID()
{
return get_ValueAsString(COLUMNNAME_JSONPathShopwareID);
}
@Override
public void setM_FreightCost_NormalVAT_Product_ID (final int M_FreightCost_NormalVAT_Product_ID)
{
if (M_FreightCost_NormalVAT_Product_ID < 1)
set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, null);
else
set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, M_FreightCost_NormalVAT_Product_ID);
}
@Override
public int getM_FreightCost_NormalVAT_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCost_NormalVAT_Product_ID);
}
@Override
public void setM_FreightCost_ReducedVAT_Product_ID (final int M_FreightCost_ReducedVAT_Product_ID)
{
if (M_FreightCost_ReducedVAT_Product_ID < 1)
set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, null);
else
set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, M_FreightCost_ReducedVAT_Product_ID);
}
@Override
public int getM_FreightCost_ReducedVAT_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID() | {
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
/**
* ProductLookup AD_Reference_ID=541499
* Reference name: _ProductLookup
*/
public static final int PRODUCTLOOKUP_AD_Reference_ID=541499;
/** Product Id = ProductId */
public static final String PRODUCTLOOKUP_ProductId = "ProductId";
/** Product Number = ProductNumber */
public static final String PRODUCTLOOKUP_ProductNumber = "ProductNumber";
@Override
public void setProductLookup (final java.lang.String ProductLookup)
{
set_Value (COLUMNNAME_ProductLookup, ProductLookup);
}
@Override
public java.lang.String getProductLookup()
{
return get_ValueAsString(COLUMNNAME_ProductLookup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FacebookService {
@Autowired
private FacebookClient facebookClient;
@Value("${facebook.app.secret}")
private String appSecret;
private static final Logger logger = Logger.getLogger(FacebookService.class.getName());
public User getUserProfile() {
try {
return facebookClient.fetchObject("me", User.class, Parameter.with("fields", "id,name,email"));
} catch (FacebookOAuthException e) {
// Handle expired/invalid token
logger.log(Level.SEVERE,"Authentication failed: " + e.getMessage());
return null;
} catch (FacebookResponseContentException e) {
// General API errors
logger.log(Level.SEVERE,"API error: " + e.getMessage());
return null;
}
}
public List<User> getFriendList() {
try {
Connection<User> friendsConnection = facebookClient.fetchConnection("me/friends", User.class);
return friendsConnection.getData();
} catch (Exception e) {
logger.log(Level.SEVERE,"Error fetching friends list: " + e.getMessage());
return null;
}
}
public String postStatusUpdate(String message) {
try {
FacebookType response = facebookClient.publish("me/feed", FacebookType.class, Parameter.with("message", message));
return "Post ID: " + response.getId(); | } catch (Exception e) {
logger.log(Level.SEVERE,"Failed to post status: " + e.getMessage());
return null;
}
}
public void uploadPhotoToFeed() {
try (InputStream imageStream = getClass().getResourceAsStream("/static/image.jpg")) {
FacebookType response = facebookClient.publish("me/photos", FacebookType.class, BinaryAttachment.with("image.jpg", imageStream),
Parameter.with("message", "Uploaded with RestFB"));
logger.log(Level.INFO,"Photo uploaded. ID: " + response.getId());
} catch (IOException e) {
logger.log(Level.SEVERE,"Failed to read image file: " + e.getMessage());
}
}
public String postToPage(String pageId, String message) {
try {
Page page = facebookClient.fetchObject(pageId, Page.class, Parameter.with("fields", "access_token"));
FacebookClient pageClient = new DefaultFacebookClient(page.getAccessToken(), appSecret, Version.LATEST);
FacebookType response = pageClient.publish(pageId + "/feed", FacebookType.class, Parameter.with("message", message));
return "Page Post ID: " + response.getId();
} catch (Exception e) {
logger.log(Level.SEVERE,"Failed to post to page: " + e.getMessage());
return null;
}
}
} | repos\tutorials-master\libraries-http-3\src\main\java\com\baeldung\facebook\FacebookService.java | 2 |
请完成以下Java代码 | public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the gender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGender() {
return gender;
}
/** | * Sets the value of the gender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGender(String value) {
this.gender = value;
}
/**
* Gets the value of the created property.
*
* @return
* possible object is
* {@link String }
*
*/
public Calendar getCreated() {
return created;
}
/**
* Sets the value of the created property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreated(Calendar value) {
this.created = value;
}
} | repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\gen\UserResponse.java | 1 |
请完成以下Java代码 | public abstract class AbstractValidatingPasswordEncoder implements PasswordEncoder {
@Override
public final @Nullable String encode(@Nullable CharSequence rawPassword) {
if (rawPassword == null) {
return null;
}
return encodeNonNullPassword(rawPassword.toString());
}
protected abstract String encodeNonNullPassword(String rawPassword);
@Override
public final boolean matches(@Nullable CharSequence rawPassword, @Nullable String encodedPassword) {
if (rawPassword == null || rawPassword.length() == 0 || encodedPassword == null
|| encodedPassword.length() == 0) {
return false;
} | return matchesNonNull(rawPassword.toString(), encodedPassword);
}
protected abstract boolean matchesNonNull(String rawPassword, String encodedPassword);
@Override
public final boolean upgradeEncoding(@Nullable String encodedPassword) {
if (encodedPassword == null || encodedPassword.length() == 0) {
return false;
}
return upgradeEncodingNonNull(encodedPassword);
}
protected boolean upgradeEncodingNonNull(String encodedPassword) {
return false;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\AbstractValidatingPasswordEncoder.java | 1 |
请完成以下Java代码 | public class X_AD_Ref_List_Trl extends org.compiere.model.PO implements I_AD_Ref_List_Trl, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1050923734L;
/** Standard Constructor */
public X_AD_Ref_List_Trl (final Properties ctx, final int AD_Ref_List_Trl_ID, @Nullable final String trxName)
{
super (ctx, AD_Ref_List_Trl_ID, trxName);
}
/** Load Constructor */
public X_AD_Ref_List_Trl (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_Language AD_Reference_ID=106
* Reference name: AD_Language
*/
public static final int AD_LANGUAGE_AD_Reference_ID=106;
@Override
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public org.compiere.model.I_AD_Ref_List getAD_Ref_List()
{
return get_ValueAsPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class);
}
@Override
public void setAD_Ref_List(final org.compiere.model.I_AD_Ref_List AD_Ref_List)
{
set_ValueFromPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class, AD_Ref_List);
}
@Override
public void setAD_Ref_List_ID (final int AD_Ref_List_ID)
{
if (AD_Ref_List_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID);
}
@Override
public int getAD_Ref_List_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Ref_List_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description) | {
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List_Trl.java | 1 |
请完成以下Java代码 | public boolean matches(HttpServletRequest request) {
for (RequestMatcher matcher : this.requestMatchers) {
if (matcher.matches(request)) {
return true;
}
}
return false;
}
/**
* Returns a {@link MatchResult} for this {@link HttpServletRequest}. In the case of a
* match, request variables are any request variables from the first underlying
* matcher.
* @param request the HTTP request
* @return a {@link MatchResult} based on the given HTTP request
* @since 6.1
*/
@Override
public MatchResult matcher(HttpServletRequest request) {
for (RequestMatcher matcher : this.requestMatchers) {
MatchResult result = matcher.matcher(request);
if (result.isMatch()) {
return result;
}
}
return MatchResult.notMatch();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) { | return false;
}
OrRequestMatcher that = (OrRequestMatcher) o;
return Objects.equals(this.requestMatchers, that.requestMatchers);
}
@Override
public int hashCode() {
return Objects.hash(this.requestMatchers);
}
@Override
public String toString() {
return "Or " + this.requestMatchers;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\OrRequestMatcher.java | 1 |
请完成以下Java代码 | public class IntermediateThrowEventParseHandler extends AbstractActivityBpmnParseHandler<ThrowEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(IntermediateThrowEventParseHandler.class);
@Override
public Class<? extends BaseElement> getHandledType() {
return ThrowEvent.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, ThrowEvent intermediateEvent) {
ActivityImpl nestedActivityImpl = createActivityOnCurrentScope(bpmnParse, intermediateEvent, BpmnXMLConstants.ELEMENT_EVENT_THROW);
EventDefinition eventDefinition = null;
if (!intermediateEvent.getEventDefinitions().isEmpty()) {
eventDefinition = intermediateEvent.getEventDefinitions().get(0);
}
nestedActivityImpl.setAsync(intermediateEvent.isAsynchronous());
nestedActivityImpl.setExclusive(!intermediateEvent.isNotExclusive());
if (eventDefinition instanceof SignalEventDefinition) {
bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition);
} else if (eventDefinition instanceof org.flowable.bpmn.model.CompensateEventDefinition) {
bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition);
} else if (eventDefinition == null) {
nestedActivityImpl.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createIntermediateThrowNoneEventActivityBehavior(intermediateEvent));
} else {
LOGGER.warn("Unsupported intermediate throw event type for throw event {}", intermediateEvent.getId());
}
} | //
// Seems not to be used anymore?
//
// protected CompensateEventDefinition createCompensateEventDefinition(BpmnParse bpmnParse, org.activiti.bpmn.model.CompensateEventDefinition eventDefinition, ScopeImpl scopeElement) {
// if (StringUtils.isNotEmpty(eventDefinition.getActivityRef())) {
// if (scopeElement.findActivity(eventDefinition.getActivityRef()) == null) {
// bpmnParse.getBpmnModel().addProblem("Invalid attribute value for 'activityRef': no activity with id '" + eventDefinition.getActivityRef() +
// "' in current scope " + scopeElement.getId(), eventDefinition);
// }
// }
//
// CompensateEventDefinition compensateEventDefinition = new CompensateEventDefinition();
// compensateEventDefinition.setActivityRef(eventDefinition.getActivityRef());
// compensateEventDefinition.setWaitForCompletion(eventDefinition.isWaitForCompletion());
//
// return compensateEventDefinition;
// }
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\IntermediateThrowEventParseHandler.java | 1 |
请完成以下Java代码 | public List<Object> provideLineGroupingValues(final OLCand cand)
{
return ImmutableList.of();
}
}
@ToString
private static final class CompositeOLCandGroupingProvider implements IOLCandGroupingProvider
{
private final ImmutableList<IOLCandGroupingProvider> providers;
private CompositeOLCandGroupingProvider(final List<IOLCandGroupingProvider> providers)
{
this.providers = ImmutableList.copyOf(providers);
}
@Override
public List<Object> provideLineGroupingValues(final OLCand cand)
{
return providers.stream()
.flatMap(provider -> provider.provideLineGroupingValues(cand).stream())
.collect(Collectors.toList());
}
}
private static final class NullOLCandValidator implements IOLCandValidator
{
public static final transient NullOLCandValidator instance = new NullOLCandValidator();
/** @return {@code 0} */
@Override
public int getSeqNo()
{
return 0;
}
@Override
public void validate(final I_C_OLCand olCand)
{
// nothing to do
}
}
private static final class CompositeOLCandValidator implements IOLCandValidator
{
private final ImmutableList<IOLCandValidator> validators;
private final IErrorManager errorManager;
private CompositeOLCandValidator(@NonNull final List<IOLCandValidator> validators, @NonNull final IErrorManager errorManager)
{ | this.validators = ImmutableList.copyOf(validators);
this.errorManager = errorManager;
}
/** @return {@code 0}. Actually, it doesn't matte for this validator. */
@Override
public int getSeqNo()
{
return 0;
}
/**
* Change {@link I_C_OLCand#COLUMN_IsError IsError}, {@link I_C_OLCand#COLUMN_ErrorMsg ErrorMsg},
* {@link I_C_OLCand#COLUMNNAME_AD_Issue_ID ADIssueID} accordingly, but <b>do not</b> save.
*/
@Override
public void validate(@NonNull final I_C_OLCand olCand)
{
for (final IOLCandValidator olCandValdiator : validators)
{
try
{
olCandValdiator.validate(olCand);
}
catch (final Exception e)
{
final AdempiereException me = AdempiereException
.wrapIfNeeded(e)
.appendParametersToMessage()
.setParameter("OLCandValidator", olCandValdiator.getClass().getSimpleName());
olCand.setIsError(true);
olCand.setErrorMsg(me.getLocalizedMessage());
final AdIssueId issueId = errorManager.createIssue(e);
olCand.setAD_Issue_ID(issueId.getRepoId());
olCand.setErrorMsgJSON(JsonObjectMapperHolder.toJsonNonNull(JsonErrorItem.builder()
.message(me.getLocalizedMessage())
.errorCode(AdempiereException.extractErrorCodeOrNull(me))
.stackTrace(Trace.toOneLineStackTraceString(me.getStackTrace()))
.adIssueId(JsonMetasfreshId.of(issueId.getRepoId()))
.errorCode(AdempiereException.extractErrorCodeOrNull(me))
.throwable(me)
.build()));
break;
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandSPIRegistry.java | 1 |
请完成以下Java代码 | private String getDescriptionPrefix(final I_C_Invoice_Candidate candidate)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final int bpartnerId = candidate.getBill_BPartner_ID();
String descriptionPrefix = bpartnerId2descriptionPrefix.get(bpartnerId);
// Build descriptionPrefix if not already built
if (descriptionPrefix == null)
{
final I_C_BPartner billBPartner = bpartnerDAO.getById(BPartnerId.ofRepoId(candidate.getBill_BPartner_ID()));
final String adLanguage = billBPartner.getAD_Language();
descriptionPrefix = msgBL.getMsg(adLanguage, MSG_QualityDiscount, new Object[] {});
bpartnerId2descriptionPrefix.put(bpartnerId, descriptionPrefix);
} | return descriptionPrefix;
}
private void setNetLineAmt(final IInvoiceLineRW invoiceLine)
{
final Quantity stockQty = invoiceLine.getQtysToInvoice().getStockQty();
final Quantity uomQty = invoiceLine.getQtysToInvoice().getUOMQtyOpt().orElse(stockQty);
final ProductPrice priceActual = invoiceLine.getPriceActual();
final Money lineNetAmt = computeLineNetAmt(priceActual, uomQty);
invoiceLine.setNetLineAmt(lineNetAmt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\invoicecandidate\spi\impl\FreshQuantityDiscountAggregator.java | 1 |
请完成以下Java代码 | public class Reservation {
private LocalDate begin;
private LocalDate end;
@Valid
private Customer customer;
@Positive
private int room;
@ConsistentDateParameters
@ValidReservation
public Reservation(LocalDate begin, LocalDate end, Customer customer, int room) {
this.begin = begin;
this.end = end;
this.customer = customer;
this.room = room;
}
public LocalDate getBegin() {
return begin;
}
public void setBegin(LocalDate begin) {
this.begin = begin;
} | public LocalDate getEnd() {
return end;
}
public void setEnd(LocalDate end) {
this.end = end;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getRoom() {
return room;
}
public void setRoom(int room) {
this.room = room;
}
} | repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\methodvalidation\model\Reservation.java | 1 |
请完成以下Java代码 | public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Occupation_Job_ID (final int AD_User_Occupation_Job_ID)
{
if (AD_User_Occupation_Job_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Job_ID, AD_User_Occupation_Job_ID);
}
@Override
public int getAD_User_Occupation_Job_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_Job_ID);
}
@Override
public org.compiere.model.I_CRM_Occupation getCRM_Occupation()
{
return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); | }
@Override
public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation)
{
set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation);
}
@Override
public void setCRM_Occupation_ID (final int CRM_Occupation_ID)
{
if (CRM_Occupation_ID < 1)
set_Value (COLUMNNAME_CRM_Occupation_ID, null);
else
set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID);
}
@Override
public int getCRM_Occupation_ID()
{
return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_Job.java | 1 |
请完成以下Java代码 | public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException {
return new JcaExecutorServiceConnectionFactoryImpl(this, cxManager);
}
public Object createConnectionFactory() throws ResourceException {
throw new ResourceException("This resource adapter doesn't support non-managed environments");
}
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
return new JcaExecutorServiceManagedConnection(this);
}
@SuppressWarnings("rawtypes")
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
ManagedConnection result = null;
Iterator it = connectionSet.iterator();
while (result == null && it.hasNext()) {
ManagedConnection mc = (ManagedConnection) it.next();
if (mc instanceof JcaExecutorServiceManagedConnection) {
result = mc;
}
}
return result;
}
public PrintWriter getLogWriter() throws ResourceException {
return logwriter;
}
public void setLogWriter(PrintWriter out) throws ResourceException {
logwriter = out; | }
public ResourceAdapter getResourceAdapter() {
return ra;
}
public void setResourceAdapter(ResourceAdapter ra) {
this.ra = ra;
}
@Override
public int hashCode() {
return 31;
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof JcaExecutorServiceManagedConnectionFactory))
return false;
return true;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\outbound\JcaExecutorServiceManagedConnectionFactory.java | 1 |
请完成以下Java代码 | public void setJSONPathSalesRepID (final @Nullable java.lang.String JSONPathSalesRepID)
{
set_Value (COLUMNNAME_JSONPathSalesRepID, JSONPathSalesRepID);
}
@Override
public java.lang.String getJSONPathSalesRepID()
{
return get_ValueAsString(COLUMNNAME_JSONPathSalesRepID);
}
@Override
public void setJSONPathShopwareID (final @Nullable java.lang.String JSONPathShopwareID)
{
set_Value (COLUMNNAME_JSONPathShopwareID, JSONPathShopwareID);
}
@Override
public java.lang.String getJSONPathShopwareID()
{
return get_ValueAsString(COLUMNNAME_JSONPathShopwareID);
}
@Override
public void setM_FreightCost_NormalVAT_Product_ID (final int M_FreightCost_NormalVAT_Product_ID)
{
if (M_FreightCost_NormalVAT_Product_ID < 1)
set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, null);
else
set_Value (COLUMNNAME_M_FreightCost_NormalVAT_Product_ID, M_FreightCost_NormalVAT_Product_ID);
}
@Override
public int getM_FreightCost_NormalVAT_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCost_NormalVAT_Product_ID);
}
@Override
public void setM_FreightCost_ReducedVAT_Product_ID (final int M_FreightCost_ReducedVAT_Product_ID)
{
if (M_FreightCost_ReducedVAT_Product_ID < 1)
set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, null);
else
set_Value (COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID, M_FreightCost_ReducedVAT_Product_ID);
}
@Override
public int getM_FreightCost_ReducedVAT_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_FreightCost_ReducedVAT_Product_ID);
}
@Override
public void setM_PriceList_ID (final int M_PriceList_ID)
{ | if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, M_PriceList_ID);
}
@Override
public int getM_PriceList_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PriceList_ID);
}
/**
* ProductLookup AD_Reference_ID=541499
* Reference name: _ProductLookup
*/
public static final int PRODUCTLOOKUP_AD_Reference_ID=541499;
/** Product Id = ProductId */
public static final String PRODUCTLOOKUP_ProductId = "ProductId";
/** Product Number = ProductNumber */
public static final String PRODUCTLOOKUP_ProductNumber = "ProductNumber";
@Override
public void setProductLookup (final java.lang.String ProductLookup)
{
set_Value (COLUMNNAME_ProductLookup, ProductLookup);
}
@Override
public java.lang.String getProductLookup()
{
return get_ValueAsString(COLUMNNAME_ProductLookup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean lockEventSubscription(String eventSubscriptionId) {
return getEventSubscriptionEntityManager().lockEventSubscription(eventSubscriptionId);
}
@Override
public void unlockEventSubscription(String eventSubscriptionId) {
getEventSubscriptionEntityManager().unlockEventSubscription(eventSubscriptionId);
}
@Override
public void deleteEventSubscription(EventSubscriptionEntity eventSubscription) {
getEventSubscriptionEntityManager().delete(eventSubscription);
}
@Override
public void deleteEventSubscriptionsByExecutionId(String executionId) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsByExecutionId(executionId);
}
@Override
public void deleteEventSubscriptionsForScopeIdAndType(String scopeId, String scopeType) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeIdAndType(scopeId, scopeType);
}
@Override
public void deleteEventSubscriptionsForProcessDefinition(String processDefinitionId) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForProcessDefinition(processDefinitionId);
}
@Override | public void deleteEventSubscriptionsForScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionIdAndType(scopeDefinitionId, scopeType);
}
@Override
public void deleteEventSubscriptionsForScopeDefinitionIdAndTypeAndNullScopeId(String scopeDefinitionId, String scopeType) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionIdAndTypeAndNullScopeId(scopeDefinitionId, scopeType);
}
@Override
public void deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(String processDefinitionId, String eventType, String activityId, String configuration) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForProcessDefinitionAndProcessStartEvent(processDefinitionId, eventType, activityId, configuration);
}
@Override
public void deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(String scopeDefinitionId, String eventType, String configuration) {
getEventSubscriptionEntityManager().deleteEventSubscriptionsForScopeDefinitionAndScopeStartEvent(scopeDefinitionId, eventType, configuration);
}
public EventSubscription createEventSubscription(EventSubscriptionBuilder builder) {
return getEventSubscriptionEntityManager().createEventSubscription(builder);
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return configuration.getEventSubscriptionEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void updateDashboardAssignments(TenantId tenantId, CustomerId edgeCustomerId, Dashboard dashboardById, Dashboard savedDashboard, Set<ShortCustomerInfo> newAssignedCustomers) {
Set<ShortCustomerInfo> currentAssignedCustomers = new HashSet<>();
if (dashboardById != null) {
if (dashboardById.getAssignedCustomers() != null) {
currentAssignedCustomers.addAll(dashboardById.getAssignedCustomers());
}
}
newAssignedCustomers = filterNonExistingCustomers(tenantId, edgeCustomerId, currentAssignedCustomers, newAssignedCustomers);
Set<CustomerId> addedCustomerIds = new HashSet<>();
Set<CustomerId> removedCustomerIds = new HashSet<>();
for (ShortCustomerInfo newAssignedCustomer : newAssignedCustomers) {
if (!savedDashboard.isAssignedToCustomer(newAssignedCustomer.getCustomerId())) {
addedCustomerIds.add(newAssignedCustomer.getCustomerId());
}
}
for (ShortCustomerInfo currentAssignedCustomer : currentAssignedCustomers) {
if (!newAssignedCustomers.contains(currentAssignedCustomer)) {
removedCustomerIds.add(currentAssignedCustomer.getCustomerId());
}
}
for (CustomerId customerIdToAdd : addedCustomerIds) {
edgeCtx.getDashboardService().assignDashboardToCustomer(tenantId, savedDashboard.getId(), customerIdToAdd);
}
for (CustomerId customerIdToRemove : removedCustomerIds) {
edgeCtx.getDashboardService().unassignDashboardFromCustomer(tenantId, savedDashboard.getId(), customerIdToRemove);
} | }
protected void deleteDashboard(TenantId tenantId, DashboardId dashboardId) {
deleteDashboard(tenantId, null, dashboardId);
}
protected void deleteDashboard(TenantId tenantId, Edge edge, DashboardId dashboardId) {
Dashboard dashboardById = edgeCtx.getDashboardService().findDashboardById(tenantId, dashboardId);
if (dashboardById != null) {
edgeCtx.getDashboardService().deleteDashboard(tenantId, dashboardId);
pushEntityEventToRuleEngine(tenantId, edge, dashboardById, TbMsgType.ENTITY_DELETED);
}
}
protected abstract Set<ShortCustomerInfo> filterNonExistingCustomers(TenantId tenantId, CustomerId customerId, Set<ShortCustomerInfo> currentAssignedCustomers, Set<ShortCustomerInfo> newAssignedCustomers);
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\dashboard\BaseDashboardProcessor.java | 2 |
请完成以下Java代码 | public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<FormValue> getFormValues() {
return formValues;
}
public void setFormValues(List<FormValue> formValues) {
this.formValues = formValues;
}
public FormProperty clone() {
FormProperty clone = new FormProperty();
clone.setValues(this);
return clone;
} | public void setValues(FormProperty otherProperty) {
super.setValues(otherProperty);
setName(otherProperty.getName());
setExpression(otherProperty.getExpression());
setVariable(otherProperty.getVariable());
setType(otherProperty.getType());
setDefaultExpression(otherProperty.getDefaultExpression());
setDatePattern(otherProperty.getDatePattern());
setReadable(otherProperty.isReadable());
setWriteable(otherProperty.isWriteable());
setRequired(otherProperty.isRequired());
formValues = new ArrayList<FormValue>();
if (otherProperty.getFormValues() != null && !otherProperty.getFormValues().isEmpty()) {
for (FormValue formValue : otherProperty.getFormValues()) {
formValues.add(formValue.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FormProperty.java | 1 |
请完成以下Java代码 | public ProjectTypeId getFirstIdByProjectCategoryAndOrgOrNull(
@NonNull final ProjectCategory projectCategory,
@NonNull final OrgId orgId,
final boolean onlyCurrentOrg)
{
final IQueryBuilder<I_C_ProjectType> builder = queryBL.createQueryBuilderOutOfTrx(I_C_ProjectType.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_ProjectType.COLUMNNAME_ProjectCategory, projectCategory.getCode())
.orderByDescending(I_C_ProjectType.COLUMNNAME_AD_Org_ID)
.orderBy(I_C_ProjectType.COLUMNNAME_C_ProjectType_ID);
if (onlyCurrentOrg)
{
builder.addInArrayFilter(I_C_ProjectType.COLUMNNAME_AD_Org_ID, orgId);
}
else | {
builder.addInArrayFilter(I_C_ProjectType.COLUMNNAME_AD_Org_ID, OrgId.ANY, orgId);
}
return builder
.create()
.firstId(ProjectTypeId::ofRepoIdOrNull);
}
public I_C_ProjectType getByName(final @NonNull String projectTypeValue)
{
return queryBL.createQueryBuilderOutOfTrx(I_C_ProjectType.class)
.addEqualsFilter(I_C_ProjectType.COLUMNNAME_Name, projectTypeValue)
.create()
.firstOnlyNotNull(I_C_ProjectType.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectTypeRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
/*@Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addAdditionalTomcatConnectors(createStandardConnector());
return tomcat;
}
private Connector createStandardConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setPort(80);
return connector;
}*/
@Bean
public TomcatServletWebServerFactory servletContainer() {
// 对http请求添加安全性约束,将其转换为https请求
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) { | SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(connector());
return tomcat;
}
@Bean
public Connector connector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
// 捕获http请求,并将其重定向到443端口
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(443);
return connector;
}
} | repos\springboot-demo-master\https\src\main\java\com\et\https\DemoApplication.java | 2 |
请完成以下Java代码 | public boolean contains(String m) {
String text = this.value;
if (text.length() < m.length()) {
return false;
}
return text.toLowerCase().contains(m.toLowerCase());
}
/**
* 任意一个包含返回true
* <pre>
* containsAny("abcdef", "a", "b)
* 等价
* "abcdef".contains("a") || "abcdef".contains("b")
* </pre>
*
* @param matchers 多个要判断的被包含项
*/
public boolean containsAny(String... matchers) {
for (String matcher : matchers) {
if (contains(matcher)) {
return true;
}
}
return false;
}
/**
* 所有都包含才返回true
*
* @param matchers 多个要判断的被包含项
*/
public boolean containsAllIgnoreCase(String... matchers) {
for (String matcher : matchers) {
if (contains(matcher) == false) {
return false;
}
}
return true;
}
public NonCaseString trim() {
return NonCaseString.of(this.value.trim());
}
public NonCaseString replace(char oldChar, char newChar) {
return NonCaseString.of(this.value.replace(oldChar, newChar));
}
public NonCaseString replaceAll(String regex, String replacement) {
return NonCaseString.of(this.value.replaceAll(regex, replacement));
}
public NonCaseString substring(int beginIndex) {
return NonCaseString.of(this.value.substring(beginIndex));
}
public NonCaseString substring(int beginIndex, int endIndex) {
return NonCaseString.of(this.value.substring(beginIndex, endIndex));
}
public boolean isNotEmpty() { | return !this.value.isEmpty();
}
@Override
public int length() {
return this.value.length();
}
@Override
public char charAt(int index) {
return this.value.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return this.value.subSequence(start, end);
}
public String[] split(String regex) {
return this.value.split(regex);
}
/**
* @return 原始字符串
*/
public String get() {
return this.value;
}
@Override
public String toString() {
return this.value;
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java | 1 |
请完成以下Java代码 | public class TbFetchDeviceCredentialsNode extends TbAbstractNodeWithFetchTo<TbFetchDeviceCredentialsNodeConfiguration> {
private static final String CREDENTIALS = "credentials";
private static final String CREDENTIALS_TYPE = "credentialsType";
@Override
protected TbFetchDeviceCredentialsNodeConfiguration loadNodeConfiguration(TbNodeConfiguration configuration) throws TbNodeException {
return TbNodeUtils.convert(configuration, TbFetchDeviceCredentialsNodeConfiguration.class);
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
var originator = msg.getOriginator();
var msgDataAsObjectNode = TbMsgSource.DATA.equals(fetchTo) ? getMsgDataAsObjectNode(msg) : null;
if (!EntityType.DEVICE.equals(originator.getEntityType())) {
ctx.tellFailure(msg, new RuntimeException("Unsupported originator type: " + originator.getEntityType() + "!"));
return;
}
var deviceId = new DeviceId(msg.getOriginator().getId());
var deviceCredentials = ctx.getDeviceCredentialsService().findDeviceCredentialsByDeviceId(ctx.getTenantId(), deviceId);
if (deviceCredentials == null) {
ctx.tellFailure(msg, new RuntimeException("Failed to get Device Credentials for device: " + deviceId + "!"));
return;
}
var credentialsType = deviceCredentials.getCredentialsType();
var credentialsInfo = ctx.getDeviceCredentialsService().toCredentialsInfo(deviceCredentials);
var metaData = msg.getMetaData().copy();
if (TbMsgSource.METADATA.equals(fetchTo)) {
metaData.putValue(CREDENTIALS_TYPE, credentialsType.name());
if (credentialsType.equals(DeviceCredentialsType.ACCESS_TOKEN) || credentialsType.equals(DeviceCredentialsType.X509_CERTIFICATE)) {
metaData.putValue(CREDENTIALS, credentialsInfo.asText());
} else {
metaData.putValue(CREDENTIALS, JacksonUtil.toString(credentialsInfo));
} | } else if (TbMsgSource.DATA.equals(fetchTo)) {
msgDataAsObjectNode.put(CREDENTIALS_TYPE, credentialsType.name());
msgDataAsObjectNode.set(CREDENTIALS, credentialsInfo);
}
TbMsg transformedMsg = transformMessage(msg, msgDataAsObjectNode, metaData);
ctx.tellSuccess(transformedMsg);
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
return fromVersion == 0 ?
upgradeRuleNodesWithOldPropertyToUseFetchTo(
oldConfiguration,
"fetchToMetadata",
TbMsgSource.METADATA.name(),
TbMsgSource.DATA.name()) :
new TbPair<>(false, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbFetchDeviceCredentialsNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
} | public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\EventSubscriptionResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static class ProxyDataSourceInterceptor implements MethodInterceptor {
private final DataSource dataSource;
public ProxyDataSourceInterceptor(final DataSource dataSource) {
super();
SLF4JQueryLoggingListener listener = new SLF4JQueryLoggingListener() {
@Override
public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
// call query logging logic only when it took more than threshold
if (THRESHOLD_MILLIS <= execInfo.getElapsedTime()) {
logger.info("Slow SQL detected ...");
super.afterQuery(execInfo, queryInfoList);
}
}
};
listener.setLogLevel(SLF4JLogLevel.WARN);
this.dataSource = ProxyDataSourceBuilder.create(dataSource)
.name("DATA_SOURCE_PROXY") | .multiline()
.listener(listener)
.build();
}
@Override
public Object invoke(final MethodInvocation invocation) throws Throwable {
final Method proxyMethod = ReflectionUtils.
findMethod(this.dataSource.getClass(),
invocation.getMethod().getName());
if (proxyMethod != null) {
return proxyMethod.invoke(this.dataSource, invocation.getArguments());
}
return invocation.proceed();
}
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootLogSlowQueries\src\main\java\com\bookstore\config\DatasourceProxyBeanPostProcessor.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.