instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class CarrierGoodsTypeRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
final CCache<String, CarrierGoodsType> carrierGoodsTypesByExternalId = CCache.newLRUCache(I_Carrier_Goods_Type.Table_Name + "#by#M_Shipper_ID#ExternalId", 100, 0);
final CCache<String, CarrierGoodsType> carrierGoodsTypesById = CCache.newLRUCache(I_Carrier_Goods_Type.Table_Name + "#byId", 100, 0);
@NonNull
public CarrierGoodsType getOrCreateGoodsType(@NonNull final ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final CarrierGoodsType cachedGoodsTypeByExternalId = getCachedGoodsTypeByShipperExternalId(shipperId, externalId);
if (cachedGoodsTypeByExternalId != null)
{
return cachedGoodsTypeByExternalId;
}
return createGoodsType(shipperId, externalId, name);
}
private CarrierGoodsType createGoodsType(final @NonNull ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final I_Carrier_Goods_Type po = InterfaceWrapperHelper.newInstance(I_Carrier_Goods_Type.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(externalId);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromRecord(po);
}
@Nullable
private CarrierGoodsType getCachedGoodsTypeByShipperExternalId(@NonNull final ShipperId shipperId, @Nullable final String externalId)
{
if (externalId == null)
{
return null;
}
return carrierGoodsTypesByExternalId.getOrLoad(shipperId + externalId, () ->
queryBL.createQueryBuilder(I_Carrier_Goods_Type.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_ExternalId, externalId)
.firstOptional()
.map(CarrierGoodsTypeRepository::fromRecord)
.orElse(null));
}
@Nullable
public CarrierGoodsType getCachedGoodsTypeById(@Nullable final CarrierGoodsTypeId goodsTypeId)
|
{
if (goodsTypeId == null)
{
return null;
}
return carrierGoodsTypesById.getOrLoad(goodsTypeId.toString(), () ->
queryBL.createQueryBuilder(I_Carrier_Goods_Type.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_Carrier_Goods_Type_ID, goodsTypeId)
.firstOptional()
.map(CarrierGoodsTypeRepository::fromRecord)
.orElse(null));
}
private static CarrierGoodsType fromRecord(@NotNull final I_Carrier_Goods_Type goodsType)
{
return CarrierGoodsType.builder()
.id(CarrierGoodsTypeId.ofRepoId(goodsType.getCarrier_Goods_Type_ID()))
.externalId(goodsType.getExternalId())
.name(goodsType.getName())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierGoodsTypeRepository.java
| 2
|
请完成以下Java代码
|
public boolean hasParameters()
{
return true; // yes, we will need some params like AD_Language, Filter, Limit etc
}
@Override
public Set<String> getDependsOnFieldNames()
{
// there are no other fields on which we depend
return ImmutableSet.of();
}
@Override
public boolean isNumericKey()
{
return true;
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builder(CONTEXT_LookupTableName)
.requiresAD_Language()
.putFilterById(IdsToFilter.ofSingleValue(id));
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final Object id = evalCtx.getSingleIdToFilterAsObject();
if (id == null)
{
throw new IllegalStateException("No ID provided in " + evalCtx);
}
return getLookupValueById(id);
}
public LookupValue getLookupValueById(final Object idObj)
{
final LookupValue country = getAllCountriesById().getById(idObj);
return CoalesceUtil.coalesce(country, LOOKUPVALUE_NULL);
}
@Override
public Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(CONTEXT_LookupTableName)
.requiresFilterAndLimit()
.requiresAD_Language();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
//
// Determine what we will filter
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int offset = evalCtx.getOffset(0);
final int limit = evalCtx.getLimit(filter.isMatchAll() ? Integer.MAX_VALUE : 100);
|
//
// Get, filter, return
return getAllCountriesById()
.getValues()
.stream()
.filter(filter)
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
private LookupValuesList getAllCountriesById()
{
final Object cacheKey = "ALL";
return allCountriesCache.getOrLoad(cacheKey, this::retriveAllCountriesById);
}
private LookupValuesList retriveAllCountriesById()
{
return Services.get(ICountryDAO.class)
.getCountries(Env.getCtx())
.stream()
.map(this::createLookupValue)
.collect(LookupValuesList.collect());
}
private IntegerLookupValue createLookupValue(final I_C_Country countryRecord)
{
final int countryId = countryRecord.getC_Country_ID();
final IModelTranslationMap modelTranslationMap = InterfaceWrapperHelper.getModelTranslationMap(countryRecord);
final ITranslatableString countryName = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Name, countryRecord.getName());
final ITranslatableString countryDescription = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Description, countryRecord.getName());
return IntegerLookupValue.of(countryId, countryName, countryDescription);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressCountryLookupDescriptor.java
| 1
|
请完成以下Java代码
|
public class DateHelper {
static final Date findMaxDateOf(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(Event::getDate)
.max(Date::compareTo)
.get();
}
static final Date findMaxDateOfWithComparator(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(Event::getDate)
.max(Comparator.naturalOrder())
.get();
}
static final Date findMinDateOf(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(Event::getDate)
.min(Date::compareTo)
.get();
}
static final Date findMinDateOfWithComparator(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(Event::getDate)
.min(Comparator.naturalOrder())
.get();
}
static final LocalDate findMaxDateOfLocalEvents(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(LocalEvent::getDate)
.max(LocalDate::compareTo)
.get();
}
static final LocalDate findMaxDateOfLocalEventsWithComparator(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(LocalEvent::getDate)
.max(Comparator.naturalOrder())
.get();
}
static final LocalDate findMinDateOfLocalEvents(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
|
}
return events.stream()
.map(LocalEvent::getDate)
.min(LocalDate::compareTo)
.get();
}
static final LocalDate findMinDateOfLocalEventsWithComparator(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(LocalEvent::getDate)
.min(Comparator.naturalOrder())
.get();
}
static Date findMaxDateWithCollections(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return Collections.max(events.stream()
.map(Event::getDate)
.collect(Collectors.toList()));
}
static LocalDate findMaxLocalDateWithCollections(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return Collections.max(events.stream()
.map(LocalEvent::getDate)
.collect(Collectors.toList()));
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-4\src\main\java\com\baeldung\streams\maxdate\DateHelper.java
| 1
|
请完成以下Java代码
|
public String[] getCaseDefinitionIdIn() {
return caseDefinitionIdIn;
}
public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) {
this.caseDefinitionIdIn = caseDefinitionIdIn;
}
public String[] getCaseDefinitionKeyIn() {
return caseDefinitionKeyIn;
}
public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) {
this.caseDefinitionKeyIn = caseDefinitionKeyIn;
}
public Date getCurrentTimestamp() {
return currentTimestamp;
}
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
public String[] getTenantIdIn() {
|
return tenantIdIn;
}
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isCompact() {
return isCompact;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricCaseInstanceReportImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JSONFileItemReaderDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Job jsonFileItemReaderJob() {
return jobBuilderFactory.get("jsonFileItemReaderJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(jsonItemReader())
|
.writer(list -> list.forEach(System.out::println))
.build();
}
private ItemReader<TestData> jsonItemReader() {
// 设置json文件地址
ClassPathResource resource = new ClassPathResource("file.json");
// 设置json文件转换的目标对象类型
JacksonJsonObjectReader<TestData> jacksonJsonObjectReader = new JacksonJsonObjectReader<>(TestData.class);
JsonItemReader<TestData> reader = new JsonItemReader<>(resource, jacksonJsonObjectReader);
// 给reader设置一个别名
reader.setName("testDataJsonItemReader");
return reader;
}
}
|
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\JSONFileItemReaderDemo.java
| 2
|
请完成以下Java代码
|
public void setAttributesKey (final @Nullable java.lang.String AttributesKey)
{
set_ValueNoCheck (COLUMNNAME_AttributesKey, AttributesKey);
}
@Override
public java.lang.String getAttributesKey()
{
return get_ValueAsString(COLUMNNAME_AttributesKey);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
|
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOnHandChange (final @Nullable BigDecimal QtyOnHandChange)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHandChange, QtyOnHandChange);
}
@Override
public BigDecimal getQtyOnHandChange()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandChange);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock_From_HUs_V.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public XMLGregorianCalendar getMovementDate() {
return movementDate;
}
/**
* Sets the value of the movementDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setMovementDate(XMLGregorianCalendar value) {
this.movementDate = value;
}
/**
* Gets the value of the poReference property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPOReference() {
return poReference;
}
/**
* Sets the value of the poReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPOReference(String value) {
this.poReference = value;
}
|
/**
* Gets the value of the shipmentDocumentno property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShipmentDocumentno() {
return shipmentDocumentno;
}
/**
* Sets the value of the shipmentDocumentno property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShipmentDocumentno(String value) {
this.shipmentDocumentno = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop111VType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<ExternalSystemServiceInstance> getByConfigAndServiceId(@NonNull final ExternalSystemParentConfigId configId, @NonNull final ExternalSystemServiceId serviceId)
{
return queryBL.createQueryBuilder(I_ExternalSystem_Service_Instance.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_Service_Instance.COLUMN_ExternalSystem_Config_ID, configId)
.addEqualsFilter(I_ExternalSystem_Service_Instance.COLUMN_ExternalSystem_Service_ID, serviceId)
.create()
.firstOnlyOptional(I_ExternalSystem_Service_Instance.class)
.map(this::ofRecord);
}
@NonNull
public Stream<ExternalSystemServiceInstance> streamByConfigIds(@NonNull final Set<ExternalSystemParentConfigId> configIds)
{
return queryBL.createQueryBuilder(I_ExternalSystem_Service_Instance.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_ExternalSystem_Service_Instance.COLUMNNAME_ExternalSystem_Config_ID, configIds)
.create()
.stream()
|
.map(this::ofRecord);
}
@NonNull
private ExternalSystemServiceInstance ofRecord(@NonNull final I_ExternalSystem_Service_Instance record)
{
final ExternalSystemServiceModel service = serviceRepository.getById(ExternalSystemServiceId.ofRepoId(record.getExternalSystem_Service_ID()));
return ExternalSystemServiceInstance.builder()
.id(ExternalSystemServiceInstanceId.ofRepoId(record.getExternalSystem_Service_Instance_ID()))
.service(service)
.configId(ExternalSystemParentConfigId.ofRepoId(record.getExternalSystem_Config_ID()))
.expectedStatus(ExternalStatus.ofCode(record.getExpectedStatus()))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\externalserviceinstance\ExternalSystemServiceInstanceRepository.java
| 2
|
请完成以下Java代码
|
public void configurePolymorphicTypeValidator(BasicPolymorphicTypeValidator.Builder builder) {
builder.allowIfSubType(Instant.class)
.allowIfSubType(Duration.class)
.allowIfSubType(SimpleGrantedAuthority.class)
.allowIfSubType(FactorGrantedAuthority.class)
.allowIfSubType(UsernamePasswordAuthenticationToken.class)
.allowIfSubType(RememberMeAuthenticationToken.class)
.allowIfSubType(AnonymousAuthenticationToken.class)
.allowIfSubType(User.class)
.allowIfSubType(BadCredentialsException.class)
.allowIfSubType(SecurityContextImpl.class)
.allowIfSubType(TestingAuthenticationToken.class)
.allowIfSubType("java.util.Collections$UnmodifiableSet")
.allowIfSubType("java.util.Collections$UnmodifiableRandomAccessList")
.allowIfSubType("java.util.Collections$EmptyList")
.allowIfSubType("java.util.ArrayList")
.allowIfSubType("java.util.HashMap")
.allowIfSubType("java.util.Collections$EmptyMap")
.allowIfSubType("java.util.Date")
.allowIfSubType("java.util.Arrays$ArrayList")
.allowIfSubType("java.util.Collections$UnmodifiableMap")
|
.allowIfSubType("java.util.LinkedHashMap")
.allowIfSubType("java.util.Collections$SingletonList")
.allowIfSubType("java.util.TreeMap")
.allowIfSubType("java.util.HashSet")
.allowIfSubType("java.util.LinkedHashSet");
}
@Override
public void setupModule(SetupContext context) {
((MapperBuilder<?, ?>) context.getOwner()).enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS);
context.setMixIn(AnonymousAuthenticationToken.class, AnonymousAuthenticationTokenMixin.class);
context.setMixIn(RememberMeAuthenticationToken.class, RememberMeAuthenticationTokenMixin.class);
context.setMixIn(SimpleGrantedAuthority.class, SimpleGrantedAuthorityMixin.class);
context.setMixIn(FactorGrantedAuthority.class, FactorGrantedAuthorityMixin.class);
context.setMixIn(User.class, UserMixin.class);
context.setMixIn(UsernamePasswordAuthenticationToken.class, UsernamePasswordAuthenticationTokenMixin.class);
context.setMixIn(TestingAuthenticationToken.class, TestingAuthenticationTokenMixin.class);
context.setMixIn(BadCredentialsException.class, BadCredentialsExceptionMixin.class);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\jackson\CoreJacksonModule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void saveBPartnerBankAccount(@NonNull final BPartnerBankAccountsSaveRequest request)
{
final BPartnerBankAccount bankAccount = request.getBankAccount();
final OrgId orgId = request.getOrgId();
final BPartnerId bpartnerId = request.getBpartnerId();
final boolean validatePermissions = request.isValidatePermissions();
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_C_BP_BankAccount.Table_Name, bankAccount.getId()))
{
final I_C_BP_BankAccount record = loadOrNew(bankAccount.getId(), I_C_BP_BankAccount.class);
if (orgId != null)
{
record.setAD_Org_ID(orgId.getRepoId());
}
record.setC_BPartner_ID(bpartnerId.getRepoId());
record.setIBAN(bankAccount.getIban());
record.setC_Currency_ID(bankAccount.getCurrencyId().getRepoId());
record.setIsActive(bankAccount.isActive());
record.setAD_Org_Mapping_ID(OrgMappingId.toRepoId(bankAccount.getOrgMappingId()));
record.setA_Name(bankAccount.getAccountName());
record.setA_Street(bankAccount.getAccountStreet());
record.setA_Zip(bankAccount.getAccountZip());
record.setA_City(bankAccount.getAccountCity());
record.setA_Country(bankAccount.getAccountCountry());
if (validatePermissions)
{
assertCanCreateOrUpdate(record);
}
saveRecord(record);
final BPartnerBankAccountId id = BPartnerBankAccountId.ofRepoId(bpartnerId, record.getC_BP_BankAccount_ID());
|
bankAccount.setId(id);
}
}
private void assertCanCreateOrUpdate(@NonNull final Object record)
{
if (Adempiere.isUnitTestMode())
{
return;
}
PermissionServiceFactories
.currentContext()
.createPermissionService()
.assertCanCreateOrUpdate(record);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\BPartnerCompositeSaver.java
| 2
|
请完成以下Java代码
|
private Set<String> getAttributeNames() {
return this.attributeNames;
}
/**
* Sets the attribute names to retrieve for each ldap groups. Null means retrieve all
* @param attributeNames - the names of the LDAP attributes to retrieve
*/
public void setAttributeNames(Set<String> attributeNames) {
this.attributeNames = attributeNames;
}
/**
* How far should a nested search go. Depth is calculated in the number of levels we
* search up for parent groups.
|
* @return the max search depth, default is 10
*/
private int getMaxSearchDepth() {
return this.maxSearchDepth;
}
/**
* How far should a nested search go. Depth is calculated in the number of levels we
* search up for parent groups.
* @param maxSearchDepth the max search depth
*/
public void setMaxSearchDepth(int maxSearchDepth) {
this.maxSearchDepth = maxSearchDepth;
}
}
|
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\NestedLdapAuthoritiesPopulator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
modelAndView.setViewName("pdfPreviewIframe");
return modelAndView;
}
/**
* 把指定URL后的字符串全部截断当成参数
* 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
* @param request
* @return
*/
private static String extractPathFromPattern(final HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}
/**
* 根据网路图片地址上传到服务器
* @param jsonObject
* @param request
* @return
*/
@PostMapping("/uploadImgByHttp")
public Result<String> uploadImgByHttp(@RequestBody JSONObject jsonObject, HttpServletRequest request){
String fileUrl = oConvertUtils.getString(jsonObject.get("fileUrl"));
String filename = oConvertUtils.getString(jsonObject.get("filename"));
String bizPath = oConvertUtils.getString(jsonObject.get("bizPath"));
try {
String savePath = "";
MultipartFile file = HttpFileToMultipartFileUtil.httpFileToMultipartFile(fileUrl, filename);
// 文件安全校验,防止上传漏洞文件
SsrfFileTypeFilter.checkUploadFileType(file, bizPath);
if (oConvertUtils.isEmpty(bizPath)) {
|
bizPath = CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType) ? "upload" : "";
}
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
savePath = this.uploadLocal(file,bizPath);
}else{
savePath = CommonUtils.upload(file, bizPath, uploadType);
}
return Result.OK(savePath);
} catch (Exception e) {
log.error(e.getMessage(), e);
return Result.error(e.getMessage());
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\CommonController.java
| 2
|
请完成以下Java代码
|
public class ServiceTaskJavaDelegateActivityBehavior extends TaskActivityBehavior implements ActivityBehavior, ExecutionListener {
protected JavaDelegate javaDelegate;
protected Expression skipExpression;
protected ServiceTaskJavaDelegateActivityBehavior() {
}
public ServiceTaskJavaDelegateActivityBehavior(JavaDelegate javaDelegate, Expression skipExpression) {
this.javaDelegate = javaDelegate;
this.skipExpression = skipExpression;
}
@Override
public void execute(DelegateExecution execution) {
boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression);
if (!isSkipExpressionEnabled ||
|
(isSkipExpressionEnabled && !SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression))) {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new JavaDelegateInvocation(javaDelegate, execution));
}
leave((ActivityExecution) execution);
}
@Override
public void notify(DelegateExecution execution) {
execute(execution);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\ServiceTaskJavaDelegateActivityBehavior.java
| 1
|
请完成以下Java代码
|
public class GetExecutionVariableInstancesCmd implements Command<Map<String, VariableInstance>>, Serializable {
private static final long serialVersionUID = 1L;
protected String executionId;
protected Collection<String> variableNames;
protected boolean isLocal;
public GetExecutionVariableInstancesCmd(String executionId, Collection<String> variableNames, boolean isLocal) {
this.executionId = executionId;
this.variableNames = variableNames;
this.isLocal = isLocal;
}
@Override
public Map<String, VariableInstance> execute(CommandContext commandContext) {
// Verify existence of execution
if (executionId == null) {
throw new FlowableIllegalArgumentException("executionId is null");
}
ExecutionEntity execution = commandContext.getExecutionEntityManager().findExecutionById(executionId);
if (execution == null) {
throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class);
}
Map<String, VariableInstance> variables = null;
if (variableNames == null || variableNames.isEmpty()) {
// Fetch all
if (isLocal) {
variables = execution.getVariableInstancesLocal();
|
} else {
variables = execution.getVariableInstances();
}
} else {
// Fetch specific collection of variables
if (isLocal) {
variables = execution.getVariableInstancesLocal(variableNames, false);
} else {
variables = execution.getVariableInstances(variableNames, false);
}
}
return variables;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\GetExecutionVariableInstancesCmd.java
| 1
|
请完成以下Java代码
|
public static boolean canDo(Action action, State state)
{
if (action == Action.Shift)
{ //shift
return !(!state.bufferEmpty() && state.bufferHead() == state.rootIndex && !state.stackEmpty()) && !state.bufferEmpty() && !state.isEmptyFlag();
}
else if (action == Action.RightArc)
{ //right arc
if (state.stackEmpty())
return false;
return !(!state.bufferEmpty() && state.bufferHead() == state.rootIndex) && !state.bufferEmpty() && !state.stackEmpty();
}
else if (action == Action.LeftArc)
{ //left arc
if (state.stackEmpty() || state.bufferEmpty())
return false;
if (!state.stackEmpty() && state.stackTop() == state.rootIndex)
return false;
return state.stackTop() != state.rootIndex && !state.hasHead(state.stackTop()) && !state.stackEmpty();
}
else if (action == Action.Reduce)
{ //reduce
return !state.stackEmpty() && state.hasHead(state.stackTop()) || !state.stackEmpty() && state.stackSize() == 1 && state.bufferSize() == 0 && state.stackTop() == state.rootIndex;
}
else if (action == Action.Unshift)
{ //unshift
return !state.stackEmpty() && !state.hasHead(state.stackTop()) && state.isEmptyFlag();
}
return false;
}
/**
* Shows true if all of the configurations in the beam are in the terminal state
*
* @param beam the current beam
* @return true if all of the configurations in the beam are in the terminal state
*/
public static boolean isTerminal(ArrayList<Configuration> beam)
{
for (Configuration configuration : beam)
if (!configuration.state.isTerminalState())
return false;
return true;
}
|
public static void commitAction(int action, int label, float score, ArrayList<Integer> dependencyRelations, Configuration newConfig)
{
if (action == 0)
{
shift(newConfig.state);
newConfig.addAction(0);
}
else if (action == 1)
{
reduce(newConfig.state);
newConfig.addAction(1);
}
else if (action == 2)
{
rightArc(newConfig.state, label);
newConfig.addAction(3 + label);
}
else if (action == 3)
{
leftArc(newConfig.state, label);
newConfig.addAction(3 + dependencyRelations.size() + label);
}
else if (action == 4)
{
unShift(newConfig.state);
newConfig.addAction(2);
}
newConfig.setScore(score);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\parser\ArcEager.java
| 1
|
请完成以下Java代码
|
public class EventInstanceImpl implements EventInstance {
protected String eventKey;
protected Collection<EventPayloadInstance> payloadInstances;
protected Collection<EventPayloadInstance> headerInstances;
protected Collection<EventPayloadInstance> correlationPayloadInstances;
protected String tenantId;
public EventInstanceImpl(String eventKey, Collection<EventPayloadInstance> payloadInstances) {
this(eventKey, payloadInstances, EventRegistryEngineConfiguration.NO_TENANT_ID);
}
public EventInstanceImpl(String eventKey, Collection<EventPayloadInstance> payloadInstances, String tenantId) {
this.eventKey = eventKey;
this.payloadInstances = payloadInstances;
this.headerInstances = this.payloadInstances.stream()
.filter(eventPayloadInstance -> eventPayloadInstance.getEventPayloadDefinition().isHeader())
.collect(Collectors.toList());
this.correlationPayloadInstances = this.payloadInstances.stream()
.filter(eventPayloadInstance -> eventPayloadInstance.getEventPayloadDefinition().isCorrelationParameter())
.collect(Collectors.toList());
this.tenantId = tenantId;
}
@Override
public String getEventKey() {
return eventKey;
}
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
@Override
public Collection<EventPayloadInstance> getPayloadInstances() {
return payloadInstances;
}
public void setPayloadInstances(Collection<EventPayloadInstance> payloadInstances) {
this.payloadInstances = payloadInstances;
}
@Override
public Collection<EventPayloadInstance> getHeaderInstances() {
return headerInstances;
}
public void setHeaderInstances(Collection<EventPayloadInstance> headerInstances) {
this.headerInstances = headerInstances;
}
@Override
public Collection<EventPayloadInstance> getCorrelationParameterInstances() {
|
return correlationPayloadInstances;
}
public void setCorrelationParameterInstances(Collection<EventPayloadInstance> correlationParameterInstances) {
this.correlationPayloadInstances = correlationParameterInstances;
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("EventInstance[eventKey=").append(eventKey);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\runtime\EventInstanceImpl.java
| 1
|
请完成以下Java代码
|
public static JSch setUpJsch() throws JSchException {
JSch jsch = new JSch();
jsch.addIdentity(PRIVATE_KEY);
return jsch;
}
public static Session createSession(JSch jsch) throws JSchException {
Session session = jsch.getSession(USER, HOST, PORT);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
}
public static ChannelSftp createSftpChannel(Session session) throws JSchException {
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
return channelSftp;
}
|
public static void readFileLineByLine(ChannelSftp channelSftp, String filePath) throws SftpException, IOException {
InputStream stream = channelSftp.get(filePath);
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
LOGGER.info(line);
}
}
}
public static void disconnect(ChannelSftp channelSftp, Session session) {
channelSftp.disconnect();
session.disconnect();
}
}
|
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\readfileremotely\RemoteServerJsch.java
| 1
|
请完成以下Java代码
|
public Collection<IDocumentFieldView> getFieldViews()
{
return data.getFieldViews();
}
public JSONASIDocument toJSONASIDocument(
final JSONDocumentOptions docOpts,
final JSONDocumentLayoutOptions layoutOpts)
{
return JSONASIDocument.builder()
.id(data.getDocumentId())
.layout(JSONASILayout.of(getLayout(), layoutOpts))
.fieldsByName(JSONDocument.ofDocument(data, docOpts).getFieldsByName())
.build();
}
public LookupValuesPage getFieldLookupValuesForQuery(final String attributeName, final String query)
{
return data.getFieldLookupValuesForQuery(attributeName, query);
}
public LookupValuesList getFieldLookupValues(final String attributeName)
{
return data.getFieldLookupValues(attributeName);
}
public boolean isCompleted()
{
return completed;
}
IntegerLookupValue complete()
{
assertNotCompleted();
final I_M_AttributeSetInstance asiRecord = createM_AttributeSetInstance(this);
final IntegerLookupValue lookupValue = IntegerLookupValue.of(asiRecord.getM_AttributeSetInstance_ID(), asiRecord.getDescription());
completed = true;
return lookupValue;
}
|
private static I_M_AttributeSetInstance createM_AttributeSetInstance(final ASIDocument asiDoc)
{
//
// Create M_AttributeSetInstance
final AttributeSetId attributeSetId = asiDoc.getAttributeSetId();
final I_M_AttributeSetInstance asiRecord = InterfaceWrapperHelper.newInstance(I_M_AttributeSetInstance.class);
asiRecord.setM_AttributeSet_ID(attributeSetId.getRepoId());
InterfaceWrapperHelper.save(asiRecord);
//
// Create M_AttributeInstances
asiDoc.getFieldViews()
.forEach(asiField -> asiField
.getDescriptor()
.getDataBindingNotNull(ASIAttributeFieldBinding.class)
.createAndSaveM_AttributeInstance(asiRecord, asiField));
//
// Update the ASI description
Services.get(IAttributeSetInstanceBL.class).setDescription(asiRecord);
InterfaceWrapperHelper.save(asiRecord);
return asiRecord;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIDocument.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
@ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case")
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
@ApiModelProperty(example = "123")
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@ApiModelProperty(example = "event-to-cmmn-1.1-case")
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
|
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceResponse.java
| 2
|
请完成以下Java代码
|
public static void addToSetOperation() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = database.getCollection(testCollectionName);
Document item = new Document().append("itemName", "PIZZA MANIA")
.append("quantity", 1)
.append("price", 800);
UpdateResult updateResult = collection.updateOne(Filters.eq("customerId", 1023), Updates.addToSet("items", item));
System.out.println("updateResult:- " + updateResult);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Push document into the array using DBObject
//
|
pushOperationUsingDBObject();
//
// Push document into the array using Document.
//
pushOperationUsingDocument();
//
// Push document into the array using addToSet operator.
//
addToSetOperation();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\PushOperations.java
| 1
|
请完成以下Java代码
|
public class CompositePredicate<T> implements Predicate<T>
{
private final CopyOnWriteArrayList<Predicate<T>> predicates = new CopyOnWriteArrayList<>();
private boolean and = true;
public CompositePredicate<T> addPredicate(@NonNull final Predicate<T> predicate)
{
predicates.addIfAbsent(predicate);
return this;
}
@Override
public boolean test(@Nullable final T value)
{
Check.assume(!predicates.isEmpty(), "There is at least one child predicate in this composite predicate");
for (final Predicate<T> predicate : predicates)
{
final boolean accepted = predicate.test(value);
if (and && !accepted)
{
return false;
}
else if (!and && accepted)
{
return true;
}
}
|
return and;
}
/**
* @return true if this composite contains no predicates
*/
public boolean isEmpty()
{
return predicates.isEmpty();
}
/**
* @param and true if there shall be a logical AND between predicates; false if there shall be a logical OR between predicates
*/
public void setAnd(final boolean and)
{
this.and = and;
}
/**
* @return true if a logical AND is applied between predicates; false if a logical OR is applied between predicates
*/
public boolean isAnd()
{
return this.and;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\CompositePredicate.java
| 1
|
请完成以下Java代码
|
public class PrefixPathGatewayFilterFactory
extends AbstractGatewayFilterFactory<PrefixPathGatewayFilterFactory.Config> {
/**
* Prefix key.
*/
public static final String PREFIX_KEY = "prefix";
private static final Log log = LogFactory.getLog(PrefixPathGatewayFilterFactory.class);
public PrefixPathGatewayFilterFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(PREFIX_KEY);
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
final UriTemplate uriTemplate = new UriTemplate(
Objects.requireNonNull(config.prefix, "prefix must not be null"));
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
boolean alreadyPrefixed = exchange.getAttributeOrDefault(GATEWAY_ALREADY_PREFIXED_ATTR, false);
if (alreadyPrefixed) {
return chain.filter(exchange);
}
exchange.getAttributes().put(GATEWAY_ALREADY_PREFIXED_ATTR, true);
ServerHttpRequest req = exchange.getRequest();
addOriginalRequestUrl(exchange, req.getURI());
Map<String, String> uriVariables = getUriTemplateVariables(exchange);
URI uri = uriTemplate.expand(uriVariables);
String newPath = uri.getRawPath() + req.getURI().getRawPath();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);
ServerHttpRequest request = req.mutate().path(newPath).build();
if (log.isTraceEnabled()) {
log.trace("Prefixed URI with: " + config.prefix + " -> " + request.getURI());
}
return chain.filter(exchange.mutate().request(request).build());
}
|
@Override
public String toString() {
return filterToStringCreator(PrefixPathGatewayFilterFactory.this).append("prefix", config.getPrefix())
.toString();
}
};
}
public static class Config {
private @Nullable String prefix;
public @Nullable String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\PrefixPathGatewayFilterFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Map<String, String> getNotificationData(MobileAppDeliveryMethodNotificationTemplate processedTemplate, NotificationProcessingContext ctx) {
Map<String, String> data = Optional.ofNullable(processedTemplate.getAdditionalConfig())
.filter(JsonNode::isObject).map(JacksonUtil::toFlatMap).orElseGet(HashMap::new);
NotificationInfo info = ctx.getRequest().getInfo();
if (info == null) {
return data;
}
Optional.ofNullable(info.getStateEntityId()).ifPresent(stateEntityId -> {
data.put("stateEntityId", stateEntityId.getId().toString());
data.put("stateEntityType", stateEntityId.getEntityType().name());
});
data.put("notificationType", ctx.getNotificationType().name());
switch (ctx.getNotificationType()) {
case ALARM:
case ALARM_ASSIGNMENT:
case ALARM_COMMENT:
info.getTemplateData().forEach((key, value) -> {
data.put("info." + key, value);
});
break;
}
data.replaceAll((key, value) -> Strings.nullToEmpty(value));
return data;
|
}
@Override
public void check(TenantId tenantId) throws Exception {
NotificationSettings systemSettings = notificationSettingsService.findNotificationSettings(TenantId.SYS_TENANT_ID);
if (!systemSettings.getDeliveryMethodsConfigs().containsKey(MOBILE_APP)) {
throw new RuntimeException("Push-notifications to mobile are not configured");
}
}
@Override
public NotificationDeliveryMethod getDeliveryMethod() {
return MOBILE_APP;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\MobileAppNotificationChannel.java
| 2
|
请完成以下Java代码
|
public JsonHU withIsDisposalPending(@Nullable final Boolean isDisposalPending)
{
return Objects.equals(this.isDisposalPending, isDisposalPending)
? this
: toBuilder().isDisposalPending(isDisposalPending).build();
}
public JsonHU withDisplayedAttributesOnly(@Nullable final List<String> displayedAttributeCodesOnly)
{
if (displayedAttributeCodesOnly == null || displayedAttributeCodesOnly.isEmpty())
{
return this;
}
final JsonHUAttributes attributes2New = attributes2.retainOnlyAttributesInOrder(displayedAttributeCodesOnly);
if (Objects.equals(attributes2New, this.attributes2))
{
return this;
}
return toBuilder()
.attributes2(attributes2New)
|
.attributes(attributes2New.toJsonHUAttributeCodeAndValues())
.build();
}
public JsonHU withLayoutSections(@Nullable List<String> layoutSections)
{
final ImmutableList<String> layoutSectionsNorm = layoutSections == null || layoutSections.isEmpty()
? null
: ImmutableList.copyOf(layoutSections);
if (Objects.equals(layoutSectionsNorm, this.layoutSections))
{
return this;
}
else
{
return toBuilder()
.layoutSections(layoutSectionsNorm)
.build();
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonHU.java
| 1
|
请完成以下Java代码
|
public void setProcessDef(ProcessDefinitionEntity processDef) {
this.processDef = processDef;
this.processDefId = processDef.getId();
}
@Override
public String getProcessDefinitionId() {
return this.processDefId;
}
@Override
public String getScopeId() {
return null;
}
@Override
public String getSubScopeId() {
return null;
}
@Override
public String getScopeType() {
return null;
}
@Override
public String getScopeDefinitionId() {
return null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type);
|
if (userId != null) {
sb.append(", userId=").append(userId);
}
if (groupId != null) {
sb.append(", groupId=").append(groupId);
}
if (taskId != null) {
sb.append(", taskId=").append(taskId);
}
if (processInstanceId != null) {
sb.append(", processInstanceId=").append(processInstanceId);
}
if (processDefId != null) {
sb.append(", processDefId=").append(processDefId);
}
sb.append("]");
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntity.java
| 1
|
请完成以下Java代码
|
private static AvailableToPromiseQuery createSingleQuery(
@NonNull final ZonedDateTime preparationDate,
@NonNull final OrderLineKey orderLineKey)
{
final AvailableToPromiseQuery query = AvailableToPromiseQuery
.builder()
.productId(orderLineKey.getProductId())
.storageAttributesKeyPattern(AttributesKeyPatternsUtil.ofAttributeKey(orderLineKey.getAttributesKey()))
.bpartner(orderLineKey.getBpartner())
.date(preparationDate)
.build();
return query;
}
private OrderLineKey createOrderKeyForOrderLineRecord(@NonNull final I_C_OrderLine orderLineRecord)
{
final ProductDescriptor productDescriptor = productDescriptorFactory.createProductDescriptor(orderLineRecord, AttributesKey.ALL);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(orderLineRecord.getC_BPartner_ID()); // this column is mandatory and always > 0
return new OrderLineKey(
productDescriptor.getProductId(),
productDescriptor.getStorageAttributesKey(),
BPartnerClassifier.specific(bpartnerId));
}
@Value
private static class OrderLineKey
{
int productId;
|
AttributesKey attributesKey;
BPartnerClassifier bpartner;
private static OrderLineKey forResultGroup(@NonNull final AvailableToPromiseResultGroup resultGroup)
{
return new OrderLineKey(
resultGroup.getProductId().getRepoId(),
resultGroup.getStorageAttributesKey(),
resultGroup.getBpartner());
}
private OrderLineKey(
final int productId,
@NonNull final AttributesKey attributesKey,
@NonNull final BPartnerClassifier bpartner)
{
this.productId = productId;
this.attributesKey = attributesKey;
this.bpartner = bpartner;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\interceptor\OrderAvailableToPromiseTool.java
| 1
|
请完成以下Java代码
|
public Flux<Instance> findAll() {
return Mono.fromSupplier(this.snapshots::values).flatMapIterable(Function.identity());
}
@Override
public Mono<Instance> find(InstanceId id) {
return Mono.defer(() -> {
if (!this.outdatedSnapshots.contains(id)) {
return Mono.justOrEmpty(this.snapshots.get(id));
}
else {
return rehydrateSnapshot(id).doOnSuccess((v) -> this.outdatedSnapshots.remove(v.getId()));
}
});
}
@Override
public Mono<Instance> save(Instance instance) {
return super.save(instance).doOnError(OptimisticLockingException.class,
(e) -> this.outdatedSnapshots.add(instance.getId()));
}
public void start() {
this.subscription = this.eventStore.findAll().concatWith(this.eventStore).subscribe(this::updateSnapshot);
}
public void stop() {
if (this.subscription != null) {
this.subscription.dispose();
this.subscription = null;
}
}
protected Mono<Instance> rehydrateSnapshot(InstanceId id) {
return super.find(id).map((instance) -> this.snapshots.compute(id, (key, snapshot) -> {
// check if the loaded version hasn't been already outdated by a snapshot
if (snapshot == null || instance.getVersion() >= snapshot.getVersion()) {
return instance;
}
else {
|
return snapshot;
}
}));
}
protected void updateSnapshot(InstanceEvent event) {
try {
this.snapshots.compute(event.getInstance(), (key, old) -> {
Instance instance = (old != null) ? old : Instance.create(key);
if (event.getVersion() > instance.getVersion()) {
return instance.apply(event);
}
return instance;
});
}
catch (Exception ex) {
log.warn("Error while updating the snapshot with event {}", event, ex);
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\SnapshottingInstanceRepository.java
| 1
|
请完成以下Java代码
|
private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row += SUBSECTION_SIZE) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column += SUBSECTION_SIZE) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int rowDelta = 0; rowDelta < SUBSECTION_SIZE; rowDelta++) {
for (int columnDelta = 0; columnDelta < SUBSECTION_SIZE; columnDelta++) {
int index = getIndex(row + rowDelta, column + columnDelta, n);
coverBoard[index][hBase] = true;
}
}
}
}
}
return hBase;
}
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private int checkRowConstraint(boolean[][] coverBoard, int hBase) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private int checkCellConstraint(boolean[][] coverBoard, int hBase) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
int index = getIndex(row, column, n);
|
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private boolean[][] initializeExactCoverBoard(int[][] board) {
boolean[][] coverBoard = createExactCoverBoard();
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
int n = board[row - 1][column - 1];
if (n != NO_VALUE) {
for (int num = MIN_VALUE; num <= MAX_VALUE; num++) {
if (num != n) {
Arrays.fill(coverBoard[getIndex(row, column, num)], false);
}
}
}
}
}
return coverBoard;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\sudoku\DancingLinksAlgorithm.java
| 1
|
请完成以下Java代码
|
public MDistributionRunLine[] getLines (boolean reload)
{
if (!reload && m_lines != null) {
set_TrxName(m_lines, get_TrxName());
return m_lines;
}
//
String sql = "SELECT * FROM M_DistributionRunLine "
+ "WHERE M_DistributionRun_ID=? AND IsActive='Y' AND TotalQty IS NOT NULL AND TotalQty<> 0 ORDER BY Line";
ArrayList<MDistributionRunLine> list = new ArrayList<MDistributionRunLine>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getM_DistributionRun_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MDistributionRunLine(getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
|
{
log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
m_lines = new MDistributionRunLine[list.size()];
list.toArray (m_lines);
return m_lines;
} // getLines
} // MDistributionRun
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDistributionRun.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static final class DispatcherServletRegistrationCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
Assert.state(beanFactory != null, "'beanFactory' must not be null");
ConditionOutcome outcome = checkDefaultDispatcherName(beanFactory);
if (!outcome.isMatch()) {
return outcome;
}
return checkServletRegistration(beanFactory);
}
private ConditionOutcome checkDefaultDispatcherName(ConfigurableListableBeanFactory beanFactory) {
boolean containsDispatcherBean = beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
if (!containsDispatcherBean) {
return ConditionOutcome.match();
}
List<String> servlets = Arrays
.asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false));
if (!servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {
return ConditionOutcome.noMatch(
startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));
}
return ConditionOutcome.match();
}
private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) {
ConditionMessage.Builder message = startMessage();
List<String> registrations = Arrays
.asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false));
boolean containsDispatcherRegistrationBean = beanFactory
.containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
if (registrations.isEmpty()) {
if (containsDispatcherRegistrationBean) {
return ConditionOutcome.noMatch(message.found("non servlet registration bean")
|
.items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll());
}
if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) {
return ConditionOutcome.noMatch(message.found("servlet registration bean")
.items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
if (containsDispatcherRegistrationBean) {
return ConditionOutcome.noMatch(message.found("non servlet registration bean")
.items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
return ConditionOutcome.match(message.found("servlet registration beans")
.items(Style.QUOTE, registrations)
.append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
private ConditionMessage.Builder startMessage() {
return ConditionMessage.forCondition("DispatcherServlet Registration");
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\DispatcherServletAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void setKerberosLoginFile(SQLServerConfigurationExtension configuration, String file) {
configuration.getKerberos().getLogin().setFile(file);
}
}
/**
* Helper class used to map properties to a {@link ConfigurationExtension}.
*
* @param <E> the extension type
*/
static class Extension<E extends ConfigurationExtension> {
private final Supplier<E> extension;
|
Extension(FluentConfiguration configuration, Class<E> type, String name) {
this.extension = SingletonSupplier.of(() -> {
E extension = configuration.getPluginRegister().getExact(type);
Assert.state(extension != null, () -> "Flyway %s extension missing".formatted(name));
return extension;
});
}
<T> Consumer<T> via(BiConsumer<E, T> action) {
return (value) -> action.accept(this.extension.get(), value);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\FlywayAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public ProductionMaterialType getType()
{
return ProductionMaterialType.PRODUCED;
}
@Override
public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw)
{
ppOrder.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw);
}
@Override
public BigDecimal getQM_QtyDeliveredPercOfRaw()
{
return ppOrder.getQM_QtyDeliveredPercOfRaw();
}
@Override
public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg)
{
ppOrder.setQM_QtyDeliveredAvg(qtyDeliveredAvg);
}
@Override
public BigDecimal getQM_QtyDeliveredAvg()
{
return ppOrder.getQM_QtyDeliveredAvg();
}
@Override
public Object getModel()
{
return ppOrder;
}
@Override
public String getVariantGroup()
{
return null;
}
@Override
public BOMComponentType getComponentType()
{
return null;
|
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
if (!_handlingUnitsInfoLoaded)
{
_handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder);
_handlingUnitsInfoLoaded = true;
}
return _handlingUnitsInfo;
}
@Override
public I_M_Product getMainComponentProduct()
{
// there is no substitute for a produced material
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java
| 1
|
请完成以下Java代码
|
protected void checkQueryOk() {
super.checkQueryOk();
ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId);
if (includeIncidents && includeIncidentsForType != null) {
throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query.");
}
}
// getter/setter for authorization check
public List<PermissionCheck> getProcessInstancePermissionChecks() {
return processInstancePermissionChecks;
}
public void setProcessInstancePermissionChecks(List<PermissionCheck> processInstancePermissionChecks) {
this.processInstancePermissionChecks = processInstancePermissionChecks;
}
public void addProcessInstancePermissionCheck(List<PermissionCheck> permissionChecks) {
processInstancePermissionChecks.addAll(permissionChecks);
}
public List<PermissionCheck> getJobPermissionChecks() {
return jobPermissionChecks;
}
public void setJobPermissionChecks(List<PermissionCheck> jobPermissionChecks) {
this.jobPermissionChecks = jobPermissionChecks;
}
|
public void addJobPermissionCheck(List<PermissionCheck> permissionChecks) {
jobPermissionChecks.addAll(permissionChecks);
}
public List<PermissionCheck> getIncidentPermissionChecks() {
return incidentPermissionChecks;
}
public void setIncidentPermissionChecks(List<PermissionCheck> incidentPermissionChecks) {
this.incidentPermissionChecks = incidentPermissionChecks;
}
public void addIncidentPermissionCheck(List<PermissionCheck> permissionChecks) {
incidentPermissionChecks.addAll(permissionChecks);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ActivityStatisticsQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<InstanceId> register(Registration registration) {
Assert.notNull(registration, "'registration' must not be null");
InstanceId id = generator.generateId(registration);
Assert.notNull(id, "'id' must not be null");
return repository.compute(id, (key, instance) -> {
if (instance == null) {
instance = Instance.create(key);
}
return Mono.just(instance.register(registration));
}).map(Instance::getId);
}
/**
* Get a list of all registered instances that satisfy the filter.
* @return list of all instances satisfying the filter.
*/
public Flux<Instance> getInstances() {
return repository.findAll().filter(filter::filter);
}
/**
* Get a list of all registered application instances that satisfy the filter.
* @param name the name to search for.
* @return list of instances for the given application that satisfy the filter.
*/
public Flux<Instance> getInstances(String name) {
return repository.findByName(name).filter(filter::filter);
}
|
/**
* Get a specific instance
* @param id the id
* @return a Mono with the Instance.
*/
public Mono<Instance> getInstance(InstanceId id) {
return repository.find(id).filter(filter::filter);
}
/**
* Remove a specific instance from services
* @param id the instances id to unregister
* @return the id of the unregistered instance
*/
public Mono<InstanceId> deregister(InstanceId id) {
return repository.computeIfPresent(id, (key, instance) -> Mono.just(instance.deregister()))
.map(Instance::getId);
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\InstanceRegistry.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public AuditLog save(TenantId tenantId, AuditLog domain) {
return super.save(tenantId, domain);
}
@Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER)
@Override
public AuditLog saveAndFlush(TenantId tenantId, AuditLog domain) {
return super.saveAndFlush(tenantId, domain);
}
@Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER)
@Override
public void removeById(TenantId tenantId, UUID id) {
super.removeById(tenantId, id);
}
@Transactional(transactionManager = EVENTS_TRANSACTION_MANAGER)
|
@Override
public void removeAllByIds(Collection<UUID> ids) {
super.removeAllByIds(ids);
}
@Override
protected EntityManager getEntityManager() {
return entityManager;
}
@Override
protected JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\audit\DedicatedJpaAuditLogDao.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AcctDocRegistry
{
@NonNull private static final Logger logger = LogManager.getLogger(AcctDocRegistry.class);
@NonNull private final AggregatedAcctDocProvider docProviders;
@NonNull private final AcctDocRequiredServicesFacade acctDocRequiredServices;
public AcctDocRegistry(
@NonNull final List<IAcctDocProvider> acctDocProviders,
@NonNull final AcctDocRequiredServicesFacade acctDocRequiredServices)
{
docProviders = new AggregatedAcctDocProvider(acctDocProviders);
logger.info("Using: {}", docProviders);
this.acctDocRequiredServices = acctDocRequiredServices;
}
@NonNull
public Doc<?> get(@NonNull final List<AcctSchema> acctSchemas, @NonNull final TableRecordReference documentRef)
{
final Doc<?> doc = docProviders.getOrNull(acctDocRequiredServices, acctSchemas, documentRef);
if (doc == null)
{
throw new PostingExecutionException("No accountable document found: " + documentRef);
}
return doc;
}
public Set<String> getDocTableNames()
{
return docProviders.getDocTableNames();
}
public boolean isAccountingTable(final String docTableName)
{
return docProviders.isAccountingTable(docTableName);
}
//
//
//
// ------------------------------------------------------------------------
//
//
//
@ToString
private static class AggregatedAcctDocProvider implements IAcctDocProvider
{
private final ImmutableMap<String, IAcctDocProvider> providersByDocTableName;
private AggregatedAcctDocProvider(final List<IAcctDocProvider> providers)
{
final ImmutableMap.Builder<String, IAcctDocProvider> mapBuilder = ImmutableMap.builder();
for (final IAcctDocProvider provider : providers)
{
for (final String docTableName : provider.getDocTableNames())
{
mapBuilder.put(docTableName, provider);
|
}
}
this.providersByDocTableName = mapBuilder.build();
}
public boolean isAccountingTable(final String docTableName)
{
return getDocTableNames().contains(docTableName);
}
@Override
public Set<String> getDocTableNames()
{
return providersByDocTableName.keySet();
}
@Override
public Doc<?> getOrNull(
@NonNull final AcctDocRequiredServicesFacade services,
@NonNull final List<AcctSchema> acctSchemas,
@NonNull final TableRecordReference documentRef)
{
try
{
final String docTableName = documentRef.getTableName();
final IAcctDocProvider provider = providersByDocTableName.get(docTableName);
if (provider == null)
{
return null;
}
return provider.getOrNull(services, acctSchemas, documentRef);
}
catch (final AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw PostingExecutionException.wrapIfNeeded(ex);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\AcctDocRegistry.java
| 2
|
请完成以下Java代码
|
public class Dest2 {
private int id;
private int points;
public Dest2() {
}
public Dest2(int id, int points) {
super();
this.id = id;
this.points = points;
}
public int getId() {
return id;
}
public void setId(int id) {
|
this.id = id;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
@Override
public String toString() {
return "Dest2 [id=" + id + ", points=" + points + "]";
}
}
|
repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\Dest2.java
| 1
|
请完成以下Java代码
|
private I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
Check.assumeNotNull(_workpackage, "workpackage not null");
return _workpackage;
}
@Override
public IWorkPackageParamsBuilder setParameter(final String parameterName, final Object parameterValue)
{
assertNotBuilt();
Check.assumeNotEmpty(parameterName, "parameterName not empty");
parameterName2valueMap.put(parameterName, parameterValue);
return this;
}
@Override
public IWorkPackageParamsBuilder setParameters(final Map<String, ?> parameters)
{
assertNotBuilt();
if (parameters == null || parameters.isEmpty())
{
return this;
}
for (final Map.Entry<String, ?> param : parameters.entrySet())
{
final String parameterName = param.getKey();
Check.assumeNotEmpty(parameterName, "parameterName not empty");
final Object parameterValue = param.getValue();
|
parameterName2valueMap.put(parameterName, parameterValue);
}
return this;
}
@Override
public IWorkPackageParamsBuilder setParameters(@Nullable final IParams parameters)
{
assertNotBuilt();
if (parameters == null)
{
return this;
}
final Collection<String> parameterNames = parameters.getParameterNames();
if(parameterNames.isEmpty())
{
return this;
}
for (final String parameterName : parameterNames)
{
Check.assumeNotEmpty(parameterName, "parameterName not empty");
final Object parameterValue = parameters.getParameterAsObject(parameterName);
parameterName2valueMap.put(parameterName, parameterValue);
}
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageParamsBuilder.java
| 1
|
请完成以下Java代码
|
public class UserApplication {
private static JpaUserDao jpaUserDao;
public static void main(String[] args) {
User user1 = getUser(1);
System.out.println(user1);
updateUser(user1, new String[]{"John", "john@domain.com"});
saveUser(new User("Monica", "monica@domain.com"));
deleteUser(getUser(2));
getAllUsers().forEach(user -> System.out.println(user.getName()));
}
private static class JpaUserDaoHolder {
private static final JpaUserDao jpaUserDao = new JpaUserDao(new JpaEntityManagerFactory().getEntityManager());
}
public static Dao getJpaUserDao() {
return JpaUserDaoHolder.jpaUserDao;
}
|
public static User getUser(long id) {
Optional<User> user = getJpaUserDao().get(id);
return user.orElseGet(()-> {return new User("non-existing user", "no-email");});
}
public static List<User> getAllUsers() {
return getJpaUserDao().getAll();
}
public static void updateUser(User user, String[] params){
getJpaUserDao().update(user, params);
}
public static void saveUser(User user) {
getJpaUserDao().save(user);
}
public static void deleteUser(User user) {
getJpaUserDao().delete(user);
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\application\UserApplication.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class Dbcp2 {
@Bean
static Dbcp2JdbcConnectionDetailsBeanPostProcessor dbcp2JdbcConnectionDetailsBeanPostProcessor(
ObjectProvider<JdbcConnectionDetails> connectionDetailsProvider) {
return new Dbcp2JdbcConnectionDetailsBeanPostProcessor(connectionDetailsProvider);
}
@Bean
@ConfigurationProperties("spring.datasource.dbcp2")
org.apache.commons.dbcp2.BasicDataSource dataSource(DataSourceProperties properties,
JdbcConnectionDetails connectionDetails) {
Class<? extends DataSource> dataSourceType = org.apache.commons.dbcp2.BasicDataSource.class;
return createDataSource(connectionDetails, dataSourceType, properties.getClassLoader());
}
}
/**
* Oracle UCP DataSource configuration.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ PoolDataSourceImpl.class, OracleConnection.class })
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "oracle.ucp.jdbc.PoolDataSource",
matchIfMissing = true)
static class OracleUcp {
@Bean
static OracleUcpJdbcConnectionDetailsBeanPostProcessor oracleUcpJdbcConnectionDetailsBeanPostProcessor(
ObjectProvider<JdbcConnectionDetails> connectionDetailsProvider) {
return new OracleUcpJdbcConnectionDetailsBeanPostProcessor(connectionDetailsProvider);
}
@Bean
@ConfigurationProperties("spring.datasource.oracleucp")
PoolDataSourceImpl dataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails)
throws SQLException {
PoolDataSourceImpl dataSource = createDataSource(connectionDetails, PoolDataSourceImpl.class,
|
properties.getClassLoader());
if (StringUtils.hasText(properties.getName())) {
dataSource.setConnectionPoolName(properties.getName());
}
return dataSource;
}
}
/**
* Generic DataSource configuration.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {
@Bean
DataSource dataSource(DataSourceProperties properties, JdbcConnectionDetails connectionDetails) {
return createDataSource(connectionDetails, properties.getType(), properties.getClassLoader());
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceConfiguration.java
| 2
|
请完成以下Java代码
|
public <E extends Throwable> V getOrElseThrow(final K key, final Supplier<E> exceptionSupplier) throws E
{
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
final V value = get(key);
if (value == null)
{
throw exceptionSupplier.get();
}
return value;
}
}
public void put(final K key, final V value)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
m_justReset = false;
if (value == null)
{
cache.invalidate(key);
}
else
{
cache.put(key, value);
fireAdditionListener(key, value);
}
}
}
private void fireAdditionListener(final K key, final V value)
{
logger.debug("fireAdditionListener - Item added; key={}; value={}", key, value);
if (additionListener != null)
{
additionListener.itemAdded(key, value);
}
}
/**
* Add all key/value pairs to this cache.
*
* @param map key/value pairs
*/
public void putAll(final Map<? extends K, ? extends V> map)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
cache.putAll(map);
for (final Entry<? extends K, ? extends V> entry : map.entrySet())
{
fireAdditionListener(entry.getKey(), entry.getValue());
}
}
}
/**
* @see java.util.Map#isEmpty()
*/
public boolean isEmpty()
{
return cache.size() == 0;
} // isEmpty
/**
* @see java.util.Map#keySet()
*/
public Set<K> keySet()
{
return cache.asMap().keySet();
} // keySet
/**
|
* @see java.util.Map#size()
*/
@Override
public long size()
{
return cache.size();
} // size
/**
* @see java.util.Map#values()
*/
public Collection<V> values()
{
return cache.asMap().values();
} // values
@Override
protected final void finalize() throws Throwable
{
// NOTE: to avoid memory leaks we need to programatically clear our internal state
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
logger.debug("Running finalize");
cache.invalidateAll();
}
}
public CCacheStats stats()
{
final CacheStats guavaStats = cache.stats();
return CCacheStats.builder()
.cacheId(cacheId)
.name(cacheName)
.labels(labels)
.config(config)
.debugAcquireStacktrace(debugAcquireStacktrace)
//
.size(cache.size())
.hitCount(guavaStats.hitCount())
.missCount(guavaStats.missCount())
.build();
}
private boolean isNoCache()
{
return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SeExecutorService implements ExecutorService {
private final static ContainerIntegrationLogger LOG = ProcessEngineLogger.CONTAINER_INTEGRATION_LOGGER;
protected ThreadPoolExecutor threadPoolExecutor;
public SeExecutorService(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return executeLongRunning(runnable);
} else {
return executeShortRunning(runnable);
}
}
protected boolean executeLongRunning(Runnable runnable) {
new Thread(runnable).start();
return true;
|
}
protected boolean executeShortRunning(Runnable runnable) {
try {
threadPoolExecutor.execute(runnable);
return true;
}
catch (RejectedExecutionException e) {
LOG.debugRejectedExecutionException(e);
return false;
}
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new ExecuteJobsRunnable(jobIds, processEngine);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\threading\se\SeExecutorService.java
| 2
|
请完成以下Java代码
|
public static FactLineMatchKey ofNullableString(final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
return stringNorm != null ? new FactLineMatchKey(stringNorm) : null;
}
public static FactLineMatchKey ofString(final String string)
{
return new FactLineMatchKey(string);
}
public static FactLineMatchKey ofFactLine(@NonNull final FactLine factLine)
{
return ofString(
Util.ArrayKey.builder()
// no need to include AD_Table_ID/Record_ID because we always match on document level
.append(Math.max(factLine.getLine_ID(), 0))
.append(factLine.getAccountConceptualName())
.append(CostElementId.toRepoId(factLine.getCostElementId()))
|
.append(TaxId.toRepoId(factLine.getTaxId()))
.append(Math.max(factLine.getM_Locator_ID(), 0))
.build()
.toString()
);
}
@Deprecated
@Override
public String toString() {return getAsString();}
public String getAsString()
{
return string;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactLineMatchKey.java
| 1
|
请完成以下Java代码
|
protected void registerChannelModel(OutboundChannelModel outboundChannelModel) {
if (outboundChannelModel.getOutboundEventProcessingPipeline() == null) {
OutboundEventProcessingPipeline eventProcessingPipeline;
if (StringUtils.isNotEmpty(outboundChannelModel.getPipelineDelegateExpression())) {
eventProcessingPipeline = resolveExpression(outboundChannelModel.getPipelineDelegateExpression(), OutboundEventProcessingPipeline.class);
} else if ("json".equals(outboundChannelModel.getSerializerType())) {
OutboundEventSerializer eventSerializer = new EventPayloadToJsonStringSerializer(objectMapper);
eventProcessingPipeline = new DefaultOutboundEventProcessingPipeline(eventSerializer);
} else if ("xml".equals(outboundChannelModel.getSerializerType())) {
OutboundEventSerializer eventSerializer = new EventPayloadToXmlStringSerializer();
eventProcessingPipeline = new DefaultOutboundEventProcessingPipeline(eventSerializer);
} else if ("expression".equals(outboundChannelModel.getSerializerType())) {
if (StringUtils.isNotEmpty(outboundChannelModel.getSerializerDelegateExpression())) {
OutboundEventSerializer outboundEventSerializer = resolveExpression(
outboundChannelModel.getSerializerDelegateExpression(), OutboundEventSerializer.class);
eventProcessingPipeline = new DefaultOutboundEventProcessingPipeline(outboundEventSerializer);
} else {
throw new FlowableException(
"The channel key " + outboundChannelModel.getKey()
+ " is using expression deserialization, but pipelineDelegateExpression was not set.");
}
} else {
eventProcessingPipeline = null;
}
if (eventProcessingPipeline != null) {
|
outboundChannelModel.setOutboundEventProcessingPipeline(eventProcessingPipeline);
}
}
}
protected <T> T resolveExpression(String expression, Class<T> type) {
Object value = CommandContextUtil.getEventRegistryConfiguration().getExpressionManager()
.createExpression(expression)
.getValue(new VariableContainerWrapper(Collections.emptyMap()));
if (type.isInstance(value)) {
return type.cast(value);
}
throw new FlowableException("expected expression " + expression + " to resolve to " + type + " but it did not. Resolved value is " + value);
}
@Override
public void unregisterChannelModel(ChannelModel channelModel, String tenantId, EventRepositoryService eventRepositoryService) {
// nothing to do
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\pipeline\OutboundChannelModelProcessor.java
| 1
|
请完成以下Java代码
|
protected String getName(CmmnElement element) {
String name = null;
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
name = planItem.getName();
}
if (name == null || name.isEmpty()) {
PlanItemDefinition definition = getDefinition(element);
if (definition != null) {
name = definition.getName();
}
}
return name;
}
protected PlanItemDefinition getDefinition(CmmnElement element) {
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
return planItem.getDefinition();
} else
if (isDiscretionaryItem(element)) {
DiscretionaryItem discretionaryItem = (DiscretionaryItem) element;
return discretionaryItem.getDefinition();
}
return null;
}
protected Collection<Sentry> getEntryCriterias(CmmnElement element) {
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
return planItem.getEntryCriteria();
}
return new ArrayList<Sentry>();
}
protected Collection<Sentry> getExitCriterias(CmmnElement element) {
if (isPlanItem(element)) {
PlanItem planItem = (PlanItem) element;
return planItem.getExitCriteria();
}
return new ArrayList<Sentry>();
}
protected String getDesciption(CmmnElement element) {
String description = element.getDescription();
if (description == null) {
PlanItemDefinition definition = getDefinition(element);
description = definition.getDescription();
}
return description;
}
protected String getDocumentation(CmmnElement element) {
|
Collection<Documentation> documentations = element.getDocumentations();
if (documentations.isEmpty()) {
PlanItemDefinition definition = getDefinition(element);
documentations = definition.getDocumentations();
}
if (documentations.isEmpty()) {
return null;
}
StringBuilder builder = new StringBuilder();
for (Documentation doc : documentations) {
String content = doc.getTextContent();
if (content == null || content.isEmpty()) {
continue;
}
if (builder.length() != 0) {
builder.append("\n\n");
}
builder.append(content.trim());
}
return builder.toString();
}
protected boolean isPlanItem(CmmnElement element) {
return element instanceof PlanItem;
}
protected boolean isDiscretionaryItem(CmmnElement element) {
return element instanceof DiscretionaryItem;
}
protected abstract List<String> getStandardEvents(CmmnElement element);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\ItemHandler.java
| 1
|
请完成以下Java代码
|
public class JsonConverterV1
{
public static final GlobalQRCodeVersion GLOBAL_QRCODE_VERSION = GlobalQRCodeVersion.ofInt(1);
public static GlobalQRCode toGlobalQRCode(@NonNull final WorkplaceQRCode qrCode)
{
return GlobalQRCode.of(WorkplaceQRCodeJsonConverter.GLOBAL_QRCODE_TYPE, GLOBAL_QRCODE_VERSION, toJson(qrCode));
}
private static JsonWorkspaceQRCodePayloadV1 toJson(@NonNull final WorkplaceQRCode qrCode)
{
return JsonWorkspaceQRCodePayloadV1.builder()
.workplaceId(qrCode.getWorkplaceId().getRepoId())
.caption(qrCode.getCaption())
.build();
}
|
public static WorkplaceQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
Check.assumeEquals(globalQRCode.getVersion(), GLOBAL_QRCODE_VERSION, "QR Code version");
final JsonWorkspaceQRCodePayloadV1 payload = globalQRCode.getPayloadAs(JsonWorkspaceQRCodePayloadV1.class);
return fromJson(payload);
}
private static WorkplaceQRCode fromJson(@NonNull final JsonWorkspaceQRCodePayloadV1 json)
{
return WorkplaceQRCode.builder()
.workplaceId(WorkplaceId.ofRepoId(json.getWorkplaceId()))
.caption(json.getCaption())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\qrcode\v1\JsonConverterV1.java
| 1
|
请完成以下Java代码
|
public DDOrderId getDDOrderId() {return ddOrderId;}
public DDOrderLineId getDDOrderLineId() {return ddOrderLineId;}
public int getDDOrderLineAlternativeId() {return ddOrderLineAlternativeId;}
public ImmutableList<PickFromHU> getPickFromHUs() {return ImmutableList.copyOf(pickFromHUs);}
public boolean isFullyShipped()
{
return qtyToShipRemaining.signum() <= 0;
}
public void addPickFromHU(@NonNull final PickFromHU pickFromHU)
{
this.pickFromHUs.add(pickFromHU);
|
qtyToShipRemaining = qtyToShipRemaining.subtract(pickFromHU.getQty());
qtyToShipScheduled = qtyToShipScheduled.add(pickFromHU.getQty());
}
//
//
//
@Value
@Builder
public static class PickFromHU
{
@NonNull I_M_HU hu;
@NonNull Quantity qty;
public HuId getHuId() {return HuId.ofRepoId(hu.getM_HU_ID());}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\generate_from_hu\DDOrderLineToAllocate.java
| 1
|
请完成以下Java代码
|
public I_C_Flatrate_Term retrieveLatestFlatrateTermForBPartnerId(@NonNull final BPartnerId bpartnerId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_C_Flatrate_Term.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bpartnerId.getRepoId())
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMNNAME_MasterEndDate, Direction.Descending, Nulls.Last)
.addColumn(I_C_Flatrate_Term.COLUMNNAME_EndDate, Direction.Descending, Nulls.Last)
.endOrderBy()
.create()
.first();
}
@Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#BPartnerId")
@Override
@Nullable
public I_C_Flatrate_Term retrieveFirstFlatrateTermForBPartnerId(@NonNull final BPartnerId bpartnerId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_C_Flatrate_Term.class)
.addOnlyActiveRecordsFilter()
|
.addOnlyContextClient()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bpartnerId)
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMNNAME_MasterStartDate, Direction.Ascending, Nulls.Last)
.addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate, Direction.Ascending, Nulls.Last)
.endOrderBy()
.create()
.first();
}
@Override
@NonNull
public <T extends I_C_Flatrate_Conditions> T getConditionsById(@NonNull final ConditionsId conditionsId, @NonNull final Class<T> modelClass)
{
return InterfaceWrapperHelper.load(conditionsId, modelClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractsDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static PickingLineGroupBy ofCode(@NonNull final String code)
{
return index.ofCode(code);
}
@Nullable
public static PickingLineGroupBy ofNullableCode(@Nullable final String code)
{
return index.ofNullableCode(code);
}
private final String code;
@NonNull
public Map<String, List<PickingJobLine>> groupLines(@NonNull final List<PickingJobLine> pickingJobLines, @NonNull final PickingLineSortBy sortBy)
{
return pickingJobLines.stream()
.collect(Collectors.groupingBy(
this::getGroupKey,
Collectors.collectingAndThen(Collectors.toList(), sortBy::sort)
));
}
|
@NonNull
private String getGroupKey(@NonNull final PickingJobLine pickingJobLine)
{
switch (this)
{
case PRODUCT_CATEGORY:
return pickingJobLine.getProductCategoryId().toString();
case NONE:
return NONE.getCode();
default:
throw new RuntimeException("Value not supported! this=" + this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\PickingLineGroupBy.java
| 2
|
请完成以下Java代码
|
public class ProcessMDC
{
public static final String NAME_AD_Process_ID = "AD_Process_ID";
public static final String NAME_AD_PInstance_ID = "AD_PInstance_ID";
public static IAutoCloseable putProcessAndInstanceId(
@Nullable final AdProcessId adProcessId,
@Nullable final PInstanceId pInstanceId)
{
final ImmutableList<MDCCloseable> closeables = ImmutableList.of(
putAdProcessId(adProcessId),
putPInstanceId(pInstanceId));
return () -> closeables.forEach(MDCCloseable::close);
}
|
public static MDCCloseable putAdProcessId(@Nullable final AdProcessId adProcessId)
{
return MDC.putCloseable(
NAME_AD_Process_ID,
adProcessId != null ? String.valueOf(adProcessId.getRepoId()) : null);
}
public static MDCCloseable putPInstanceId(@Nullable final PInstanceId pinstanceId)
{
return MDC.putCloseable(
NAME_AD_PInstance_ID,
pinstanceId != null ? String.valueOf(pinstanceId.getRepoId()) : null);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessMDC.java
| 1
|
请完成以下Java代码
|
public I_W_CounterCount getW_CounterCount() throws RuntimeException
{
return (I_W_CounterCount)MTable.get(getCtx(), I_W_CounterCount.Table_Name)
.getPO(getW_CounterCount_ID(), get_TrxName()); }
/** Set Counter Count.
@param W_CounterCount_ID
Web Counter Count Management
*/
public void setW_CounterCount_ID (int W_CounterCount_ID)
{
if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID));
}
/** Get Counter Count.
@return Web Counter Count Management
*/
public int getW_CounterCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Web Counter.
@param W_Counter_ID
Individual Count hit
*/
public void setW_Counter_ID (int W_Counter_ID)
{
if (W_Counter_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_W_Counter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Counter_ID, Integer.valueOf(W_Counter_ID));
}
/** Get Web Counter.
@return Individual Count hit
*/
public int getW_Counter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Counter_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Counter.java
| 1
|
请完成以下Java代码
|
protected void setOnBatchUpdateValues(PreparedStatement ps, int i, List<AttributeKvEntity> entities) throws SQLException {
AttributeKvEntity kvEntity = entities.get(i);
ps.setString(1, replaceNullChars(kvEntity.getStrValue()));
if (kvEntity.getLongValue() != null) {
ps.setLong(2, kvEntity.getLongValue());
} else {
ps.setNull(2, Types.BIGINT);
}
if (kvEntity.getDoubleValue() != null) {
ps.setDouble(3, kvEntity.getDoubleValue());
} else {
ps.setNull(3, Types.DOUBLE);
}
if (kvEntity.getBooleanValue() != null) {
ps.setBoolean(4, kvEntity.getBooleanValue());
} else {
ps.setNull(4, Types.BOOLEAN);
}
ps.setString(5, replaceNullChars(kvEntity.getJsonValue()));
ps.setLong(6, kvEntity.getLastUpdateTs());
ps.setObject(7, kvEntity.getId().getEntityId());
ps.setInt(8, kvEntity.getId().getAttributeType());
ps.setInt(9, kvEntity.getId().getAttributeKey());
}
@Override
protected void setOnInsertOrUpdateValues(PreparedStatement ps, int i, List<AttributeKvEntity> insertEntities) throws SQLException {
AttributeKvEntity kvEntity = insertEntities.get(i);
ps.setObject(1, kvEntity.getId().getEntityId());
ps.setInt(2, kvEntity.getId().getAttributeType());
ps.setInt(3, kvEntity.getId().getAttributeKey());
ps.setString(4, replaceNullChars(kvEntity.getStrValue()));
ps.setString(10, replaceNullChars(kvEntity.getStrValue()));
if (kvEntity.getLongValue() != null) {
ps.setLong(5, kvEntity.getLongValue());
|
ps.setLong(11, kvEntity.getLongValue());
} else {
ps.setNull(5, Types.BIGINT);
ps.setNull(11, Types.BIGINT);
}
if (kvEntity.getDoubleValue() != null) {
ps.setDouble(6, kvEntity.getDoubleValue());
ps.setDouble(12, kvEntity.getDoubleValue());
} else {
ps.setNull(6, Types.DOUBLE);
ps.setNull(12, Types.DOUBLE);
}
if (kvEntity.getBooleanValue() != null) {
ps.setBoolean(7, kvEntity.getBooleanValue());
ps.setBoolean(13, kvEntity.getBooleanValue());
} else {
ps.setNull(7, Types.BOOLEAN);
ps.setNull(13, Types.BOOLEAN);
}
ps.setString(8, replaceNullChars(kvEntity.getJsonValue()));
ps.setString(14, replaceNullChars(kvEntity.getJsonValue()));
ps.setLong(9, kvEntity.getLastUpdateTs());
ps.setLong(15, kvEntity.getLastUpdateTs());
}
@Override
protected String getBatchUpdateQuery() {
return BATCH_UPDATE;
}
@Override
protected String getInsertOrUpdateQuery() {
return INSERT_OR_UPDATE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\attributes\AttributeKvInsertRepository.java
| 1
|
请完成以下Java代码
|
public void setMainTable(String mainTable)
{
if (mainTable == null || mainTable.length() == 0)
return;
m_mainTable = mainTable;
if (m_mainAlias.equals(mainTable))
m_mainAlias = "";
} // setMainTable
/**
* Get Main Table Name
* @return Main Table Name
*/
public String getMainTable()
{
return m_mainTable;
} // getMainTable
/**
* Set Main Table Name.
* If table name equals alias, the alias is set to ""
* @param joinTable
*/
public void setJoinTable(String joinTable)
{
if (joinTable == null || joinTable.length() == 0)
return;
m_joinTable = joinTable;
if (m_joinAlias.equals(joinTable))
m_joinAlias = "";
} // setJoinTable
/**
* Get Join Table Name
* @return Join Table Name
*/
public String getJoinTable()
{
return m_joinTable;
|
} // getJoinTable
/*************************************************************************/
/**
* This Join is a condition of the first Join.
* e.g. tb.AD_User_ID(+)=? or tb.AD_User_ID(+)='123'
* @param first
* @return true if condition
*/
public boolean isConditionOf (Join first)
{
if (m_mainTable == null // did not find Table from "Alias"
&& (first.getJoinTable().equals(m_joinTable) // same join table
|| first.getMainAlias().equals(m_joinTable))) // same main table
return true;
return false;
} // isConditionOf
/**
* String representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer ("Join[");
sb.append(m_joinClause)
.append(" - Main=").append(m_mainTable).append("/").append(m_mainAlias)
.append(", Join=").append(m_joinTable).append("/").append(m_joinAlias)
.append(", Left=").append(m_left)
.append(", Condition=").append(m_condition)
.append("]");
return sb.toString();
} // toString
} // Join
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\Join.java
| 1
|
请完成以下Java代码
|
public int getM_PackagingTree_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackagingTree_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_M_Warehouse getM_Warehouse_Dest() throws RuntimeException
{
return (org.compiere.model.I_M_Warehouse)MTable.get(getCtx(), org.compiere.model.I_M_Warehouse.Table_Name)
.getPO(getM_Warehouse_Dest_ID(), get_TrxName()); }
/** Set Ziel-Lager.
@param M_Warehouse_Dest_ID Ziel-Lager */
public void setM_Warehouse_Dest_ID (int M_Warehouse_Dest_ID)
{
if (M_Warehouse_Dest_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_Dest_ID, Integer.valueOf(M_Warehouse_Dest_ID));
}
/** Get Ziel-Lager.
@return Ziel-Lager */
public int getM_Warehouse_Dest_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_Dest_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Set Verarbeitet.
*
* @param Processed
* Checkbox sagt aus, ob der Beleg verarbeitet wurde.
|
*/
public void setProcessed(boolean Processed)
{
set_Value(COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/**
* Get Verarbeitet.
*
* @return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
public boolean isProcessed()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTree.java
| 1
|
请完成以下Java代码
|
public void resetNewRecordWhereClause()
{
m_whereClauseNewRecords = null;
}
private List<String> m_whereClauseNewRecords = null;
// end: c.ghita@metas.ro : US1207
/**
*
* @return true if values of current row were changed
*/
// metas
public boolean isChanged()
{
return m_changed;
}
private DataNewCopyMode _dataNewCopyMode = null;
/** variable for retaining the old po'ID for copy with details */
private int m_oldPO_id = -1;
private void setDataNewCopyMode(final DataNewCopyMode copyMode)
{
Check.assumeNotNull(copyMode, "copyMode not null");
this._dataNewCopyMode = copyMode;
}
public void resetDataNewCopyMode()
|
{
this._dataNewCopyMode = null;
// // Make sure the suggested child tables to be copied list is reset
// if (m_gridTab != null)
// {
// m_gridTab.resetSuggestedCopyWithDetailsList();
// }
}
/**
* Checks if we are currenty copying the current row <b>with details</b>.
* <p>
* NOTE: this information will be available even after {@link #dataNew(int, DataNewCopyMode)} until the record is saved or discarded.
*
* @return true if we are currenty copying the current row <b>with details</b>
*/
public boolean isCopyWithDetails()
{
return DataNewCopyMode.isCopyWithDetails(_dataNewCopyMode);
}
/**
* @return true if we are currenty copying the current row (with or without details)
*/
public boolean isRecordCopyingMode()
{
return DataNewCopyMode.isCopy(_dataNewCopyMode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTable.java
| 1
|
请完成以下Java代码
|
public CaseInstanceBuilder caseDefinitionWithoutTenantId() {
this.caseDefinitionTenantId = null;
isTenantIdSet = true;
return this;
}
public CaseInstanceBuilder setVariable(String variableName, Object variableValue) {
ensureNotNull(NotValidException.class, "variableName", variableName);
if (variables == null) {
variables = Variables.createVariables();
}
variables.putValue(variableName, variableValue);
return this;
}
public CaseInstanceBuilder setVariables(Map<String, Object> variables) {
if (variables != null) {
if (this.variables == null) {
this.variables = Variables.fromMap(variables);
}
else {
this.variables.putAll(variables);
}
}
return this;
}
public CaseInstance create() {
if (isTenantIdSet && caseDefinitionId != null) {
throw LOG.exceptionCreateCaseInstanceByIdAndTenantId();
}
try {
CreateCaseInstanceCmd command = new CreateCaseInstanceCmd(this);
if(commandExecutor != null) {
return commandExecutor.execute(command);
} else {
return command.execute(commandContext);
}
} catch (CaseDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (CaseIllegalStateTransitionException e) {
throw new NotAllowedException(e.getMessage(), e);
}
}
// getters ////////////////////////////////////
public String getCaseDefinitionKey() {
|
return caseDefinitionKey;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getBusinessKey() {
return businessKey;
}
public VariableMap getVariables() {
return variables;
}
public String getCaseDefinitionTenantId() {
return caseDefinitionTenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseInstanceBuilderImpl.java
| 1
|
请完成以下Java代码
|
public de.metas.procurement.base.model.I_PMM_PurchaseCandidate getPMM_PurchaseCandidate() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_PMM_PurchaseCandidate_ID, de.metas.procurement.base.model.I_PMM_PurchaseCandidate.class);
}
@Override
public void setPMM_PurchaseCandidate(de.metas.procurement.base.model.I_PMM_PurchaseCandidate PMM_PurchaseCandidate)
{
set_ValueFromPO(COLUMNNAME_PMM_PurchaseCandidate_ID, de.metas.procurement.base.model.I_PMM_PurchaseCandidate.class, PMM_PurchaseCandidate);
}
/** Set Bestellkandidat.
@param PMM_PurchaseCandidate_ID Bestellkandidat */
@Override
public void setPMM_PurchaseCandidate_ID (int PMM_PurchaseCandidate_ID)
{
if (PMM_PurchaseCandidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_PurchaseCandidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PMM_PurchaseCandidate_ID, Integer.valueOf(PMM_PurchaseCandidate_ID));
}
/** Get Bestellkandidat.
@return Bestellkandidat */
@Override
public int getPMM_PurchaseCandidate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_PurchaseCandidate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Purchase order candidate - order line.
@param PMM_PurchaseCandidate_OrderLine_ID Purchase order candidate - order line */
@Override
public void setPMM_PurchaseCandidate_OrderLine_ID (int PMM_PurchaseCandidate_OrderLine_ID)
{
if (PMM_PurchaseCandidate_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_PurchaseCandidate_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PMM_PurchaseCandidate_OrderLine_ID, Integer.valueOf(PMM_PurchaseCandidate_OrderLine_ID));
}
/** Get Purchase order candidate - order line.
@return Purchase order candidate - order line */
@Override
public int getPMM_PurchaseCandidate_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_PurchaseCandidate_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Bestellte Menge.
@param QtyOrdered
Bestellte Menge
*/
@Override
public void setQtyOrdered (java.math.BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
/** Get Bestellte Menge.
@return Bestellte Menge
*/
@Override
public java.math.BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Bestellte Menge (TU).
@param QtyOrdered_TU
Bestellte Menge (TU)
*/
@Override
public void setQtyOrdered_TU (java.math.BigDecimal QtyOrdered_TU)
{
set_Value (COLUMNNAME_QtyOrdered_TU, QtyOrdered_TU);
}
/** Get Bestellte Menge (TU).
@return Bestellte Menge (TU)
*/
@Override
public java.math.BigDecimal getQtyOrdered_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_TU);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_PurchaseCandidate_OrderLine.java
| 1
|
请完成以下Java代码
|
private final boolean isValidURL()
{
final String urlString = m_text.getText();
if (Check.isEmpty(urlString, true))
{
return false;
}
return true;
}
/**
* Action button pressed - show URL
*/
private void action_button()
{
String urlString = m_text.getText();
if (!Check.isEmpty(urlString, true))
{
urlString = urlString.trim();
try
{
// validate the URL
new URL(urlString);
Env.startBrowser(urlString);
return;
}
catch (Exception e)
{
final String message = e.getLocalizedMessage();
ADialog.warn(0, this, "URLnotValid", message);
}
}
} // action button
/**
* Set Field/WindowNo for ValuePreference
* @param mField field
*/
@Override
public void setField (GridField mField)
{
this.m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
/**
* Set Text
* @param text text
*/
public void setText (String text)
{
m_text.setText (text);
validateOnTextChanged();
} // setText
/**
* Get Text (clear)
* @return text
*/
public String getText ()
{
String text = m_text.getText();
return text;
} // getText
|
/**
* Focus Gained.
* Enabled with Obscure
* @param e event
*/
public void focusGained (FocusEvent e)
{
m_infocus = true;
setText(getText()); // clear
} // focusGained
/**
* Focus Lost
* Enabled with Obscure
* @param e event
*/
public void focusLost (FocusEvent e)
{
m_infocus = false;
setText(getText()); // obscure
} // focus Lost
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VURL
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java
| 1
|
请完成以下Java代码
|
private int getPaymentIndexById(final @NonNull POSPaymentId posPaymentId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentId.equals(payments.get(i).getLocalId(), posPaymentId))
{
return i;
}
}
throw new AdempiereException("No payment found for " + posPaymentId + " in " + payments);
}
private OptionalInt getPaymentIndexByExternalId(final @NonNull POSPaymentExternalId externalId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentExternalId.equals(payments.get(i).getExternalId(), externalId))
{
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
public void removePaymentsIf(@NonNull final Predicate<POSPayment> predicate)
{
|
updateAllPayments(payment -> {
// skip payments marked as DELETED
if (payment.isDeleted())
{
return payment;
}
if (!predicate.test(payment))
{
return payment;
}
if (payment.isAllowDeleteFromDB())
{
payment.assertAllowDelete();
return null;
}
else
{
return payment.changingStatusToDeleted();
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrder.java
| 1
|
请完成以下Java代码
|
public void setChecked (Timestamp Checked)
{
set_Value (COLUMNNAME_Checked, Checked);
}
/** Get Last Checked.
@return Info when we did the last check
*/
public Timestamp getChecked ()
{
return (Timestamp)get_Value(COLUMNNAME_Checked);
}
public I_CM_Container getCM_Container() throws RuntimeException
{
return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name)
.getPO(getCM_Container_ID(), get_TrxName()); }
/** Set Web Container.
@param CM_Container_ID
Web Container contains content like images, text etc.
*/
public void setCM_Container_ID (int CM_Container_ID)
{
if (CM_Container_ID < 1)
set_Value (COLUMNNAME_CM_Container_ID, null);
else
set_Value (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID));
}
/** Get Web Container.
@return Web Container contains content like images, text etc.
*/
public int getCM_Container_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Container URL.
@param CM_Container_URL_ID
Contains info on used URLs
*/
public void setCM_Container_URL_ID (int CM_Container_URL_ID)
{
if (CM_Container_URL_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, Integer.valueOf(CM_Container_URL_ID));
}
/** Get Container URL.
@return Contains info on used URLs
*/
public int getCM_Container_URL_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_URL_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Last Result.
@param Last_Result
Contains data on the last check result
*/
public void setLast_Result (String Last_Result)
{
set_Value (COLUMNNAME_Last_Result, Last_Result);
}
/** Get Last Result.
@return Contains data on the last check result
*/
public String getLast_Result ()
{
return (String)get_Value(COLUMNNAME_Last_Result);
}
/** Set Status.
@param Status
Status of the currently running check
*/
public void setStatus (String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
public String getStatus ()
{
return (String)get_Value(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_URL.java
| 1
|
请完成以下Java代码
|
private void postDependingMatchInvsIfNeeded()
{
if (!services.getSysConfigBooleanValue(SYSCONFIG_PostMatchInvs, DEFAULT_PostMatchInvs))
{
return;
}
final ImmutableSet<InOutLineId> inoutLineIds = getDocLines()
.stream()
.map(DocLine_InOut::getInOutLineId)
.collect(ImmutableSet.toImmutableSet());
if (inoutLineIds.isEmpty())
{
return;
}
final Set<MatchInvId> matchInvIds = matchInvoiceService.getIdsProcessedButNotPostedByInOutLineIds(inoutLineIds);
postDependingDocuments(I_M_MatchInv.Table_Name, matchInvIds);
}
@NonNull
private CostAmount roundToStdPrecision(@NonNull final CostAmount costs)
{
return costs.round(services::getCurrencyStandardPrecision);
}
public CurrencyConversionContext getCurrencyConversionContext(final AcctSchema ignoredAcctSchema)
{
final I_M_InOut inout = getModel(I_M_InOut.class);
return inOutBL.getCurrencyConversionContext(inout);
}
@Nullable
@Override
protected OrderId getSalesOrderId()
{
final Optional<OrderId> optionalSalesOrderId = CollectionUtils.extractSingleElementOrDefault(
getDocLines(),
docLine -> Optional.ofNullable(docLine.getSalesOrderId()),
Optional.empty());
|
//noinspection DataFlowIssue
return optionalSalesOrderId.orElse(null);
}
//
//
//
//
//
@Value
static class InOutDocBaseType
{
@NonNull DocBaseType docBaseType;
boolean isSOTrx;
public boolean isCustomerShipment() {return isSOTrx && docBaseType.isShipment();}
public boolean isCustomerReturn() {return isSOTrx && docBaseType.isReceipt();}
public boolean isVendorReceipt() {return !isSOTrx && docBaseType.isReceipt();}
public boolean isVendorReturn() {return !isSOTrx && docBaseType.isShipment();}
public boolean isReturn() {return isCustomerReturn() || isVendorReturn();}
}
} // Doc_InOut
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_InOut.java
| 1
|
请完成以下Java代码
|
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 setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class);
}
@Override
public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
|
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setWriteAudit (final boolean WriteAudit)
{
set_Value (COLUMNNAME_WriteAudit, WriteAudit);
}
@Override
public boolean isWriteAudit()
{
return get_ValueAsBoolean(COLUMNNAME_WriteAudit);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<String> computeExchangeHeadersToString(@NonNull final Exchange exchange)
{
return getHeaders(exchange).map(AuditFileTrailUtil::auditHeaders);
}
@NonNull
private Optional<Map<String, Object>> getHeaders(@NonNull final Exchange exchange)
{
if (exchange.getIn().getHeaders() == null)
{
return Optional.empty();
}
final Map<String, Object> headers = exchange.getIn().getHeaders().entrySet()
.stream()
.filter(entry -> !Exchange.HTTP_SERVLET_REQUEST.equals(entry.getKey()))
.collect(ImmutableMap.toImmutableMap(
Map.Entry::getKey,
entry -> CoalesceUtil.coalesceNotNull(entry.getValue(), "<null>")) // ImmutableMap doesn't allow null values
);
if (headers.isEmpty())
{
return Optional.empty();
}
return Optional.of(headers);
}
@NonNull
private String auditHeaders(@NonNull final Map<String, Object> headers)
{
final StringBuilder headersStringCollector = new StringBuilder(" ========================= Headers ======================== \n");
try
{
final ObjectMapper objectMapper = JsonObjectMapperHolder.newJsonObjectMapper();
|
return headersStringCollector
.append(objectMapper.writeValueAsString(headers))
.append("\n")
.toString();
}
catch (final Exception e)
{
return headersStringCollector.append(getHeadersErrorMessage(e, headers)).toString();
}
}
@NonNull
private String getHeadersErrorMessage(@NonNull final Exception exception, @NonNull final Map<String, Object> headers)
{
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
return "\n Got exception while parsing request headers \n"
+ ";\n ========================= blindly converting headers toString(); headers: ======================== \n"
+ headers.toString()
+ ";\n ========================= error stack trace - start ======================== \n"
+ exception.getLocalizedMessage()
+ ";\n ========================= error stack trace - end ======================== \n";
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AuditFileTrailUtil.java
| 2
|
请完成以下Java代码
|
public class PropertiesHttpMessageConverter extends AbstractGenericHttpMessageConverter<Properties> {
public PropertiesHttpMessageConverter() {
super(new MediaType("text", "properties"));
}
@Override
protected void writeInternal(Properties properties, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
// 获取请求头
HttpHeaders headers = outputMessage.getHeaders();
// 获取 content-type
MediaType contentType = headers.getContentType();
// 获取编码
Charset charset = null;
if (contentType != null) {
charset = contentType.getCharset();
}
charset = charset == null ? Charset.forName("UTF-8") : charset;
// 获取请求体
OutputStream body = outputMessage.getBody();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body, charset);
properties.store(outputStreamWriter, "Serialized by PropertiesHttpMessageConverter#writeInternal");
}
@Override
protected Properties readInternal(Class<? extends Properties> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
Properties properties = new Properties();
// 获取请求头
HttpHeaders headers = inputMessage.getHeaders();
// 获取 content-type
|
MediaType contentType = headers.getContentType();
// 获取编码
Charset charset = null;
if (contentType != null) {
charset = contentType.getCharset();
}
charset = charset == null ? Charset.forName("UTF-8") : charset;
// 获取请求体
InputStream body = inputMessage.getBody();
InputStreamReader inputStreamReader = new InputStreamReader(body, charset);
properties.load(inputStreamReader);
return properties;
}
@Override
public Properties read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return readInternal(null, inputMessage);
}
}
|
repos\SpringAll-master\47.Spring-Boot-Content-Negotiation\src\main\java\com\example\demo\converter\PropertiesHttpMessageConverter.java
| 1
|
请完成以下Java代码
|
public static InputDataSourceId ofRepoId(final int repoId)
{
return new InputDataSourceId(repoId);
}
@Nullable
public static InputDataSourceId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new InputDataSourceId(repoId) : null;
}
public static Optional<InputDataSourceId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final InputDataSourceId inputDataSourceId)
{
|
return toRepoIdOr(inputDataSourceId, -1);
}
public static int toRepoIdOr(@Nullable final InputDataSourceId inputDataSourceId, final int defaultValue)
{
return inputDataSourceId != null ? inputDataSourceId.getRepoId() : defaultValue;
}
private InputDataSourceId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\InputDataSourceId.java
| 1
|
请完成以下Java代码
|
public void clear()
{
termFrequencyMap.clear();
}
/**
* 提取关键词(非线程安全)
*
* @param termList
* @param size
* @return
*/
@Override
public List<String> getKeywords(List<Term> termList, int size)
{
clear();
add(termList);
Collection<TermFrequency> topN = top(size);
List<String> r = new ArrayList<String>(topN.size());
for (TermFrequency termFrequency : topN)
{
r.add(termFrequency.getTerm());
}
|
return r;
}
/**
* 提取关键词(线程安全)
*
* @param document 文档内容
* @param size 希望提取几个关键词
* @return 一个列表
*/
public static List<String> getKeywordList(String document, int size)
{
return new TermFrequencyCounter().getKeywords(document, size);
}
@Override
public String toString()
{
final int max = 100;
return top(Math.min(max, size())).toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\TermFrequencyCounter.java
| 1
|
请完成以下Java代码
|
public static Result success() {
Result result = new Result<>();
result.setCode("200");
result.setStatus(Status.SUCCESS);
result.setMessage(Status.SUCCESS.name());
return result;
}
public static <T> Result success(T data) {
Result<T> result = new Result<>();
result.setCode("200");
result.setStatus(Status.SUCCESS);
result.setMessage(Status.SUCCESS.name());
result.setData(data);
return result;
}
public static <T> Result error(String msg) {
Result<T> result = new Result<>();
result.setCode("500");
result.setStatus(Status.ERROR);
result.setMessage(msg);
return result;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getCode() {
return code;
}
|
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public static enum Status {
SUCCESS("OK"),
ERROR("ERROR");
private String code;
private Status(String code) {
this.code = code;
}
public String code() {
return this.code;
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-hystrix\src\main\java\com\xiaolyuh\entity\Result.java
| 1
|
请完成以下Java代码
|
public final class DocumentApprovalConstraint extends Constraint
{
public static final DocumentApprovalConstraint of(
final boolean canApproveOwnDoc,
@NonNull final BigDecimal amtApproval,
@Nullable final CurrencyId currencyId)
{
return new DocumentApprovalConstraint(canApproveOwnDoc, amtApproval, currencyId);
}
public static final DocumentApprovalConstraint DEFAULT = new DocumentApprovalConstraint(false, BigDecimal.ZERO, null);
private final boolean canApproveOwnDoc;
private final BigDecimal amtApproval;
private final CurrencyId currencyId;
private DocumentApprovalConstraint(
boolean canApproveOwnDoc,
@NonNull BigDecimal amtApproval,
@Nullable CurrencyId currencyId)
{
this.canApproveOwnDoc = canApproveOwnDoc;
this.amtApproval = amtApproval;
this.currencyId = currencyId;
}
@Override
public String toString()
{
// NOTE: we are making it translateable friendly because it's displayed in Prefereces->Info->Rollen
final StringBuilder sb = new StringBuilder()
.append("DocumentApproval[")
.append("@IsCanApproveOwnDoc@: @" + (canApproveOwnDoc ? "Y" : "N") + "@");
if (!canApproveOwnDoc)
{
sb.append(", @AmtApproval@: " + amtApproval);
sb.append(", @C_Currency_ID@: " + currencyId);
}
sb.append("]");
|
return sb.toString();
}
@Override
public boolean isInheritable()
{
return false;
}
public boolean canApproveOwnDoc()
{
return canApproveOwnDoc;
}
@NonNull
public Money getAmtApproval(@NonNull final CurrencyId fallbackCurrencyId)
{
return currencyId != null
? Money.of(amtApproval, currencyId)
: Money.of(amtApproval, fallbackCurrencyId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\DocumentApprovalConstraint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EqualByJavaDefault implements Cloneable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
public EqualByJavaDefault() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
|
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\equality\EqualByJavaDefault.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected Tuple2<String, Flux<Instance>> getApplicationForInstance(Instance instance) {
String name = instance.getRegistration().getName();
return Tuples.of(name, this.instanceRegistry.getInstances(name).filter(Instance::isRegistered));
}
protected Mono<Application> toApplication(String name, Flux<Instance> instances) {
return instances.collectList().map((instanceList) -> {
Tuple2<String, Instant> status = getStatus(instanceList);
return Application.create(name)
.instances(instanceList)
.buildVersion(getBuildVersion(instanceList))
.status(status.getT1())
.statusTimestamp(status.getT2())
.build();
});
}
@Nullable
protected BuildVersion getBuildVersion(List<Instance> instances) {
List<BuildVersion> versions = instances.stream()
.map(Instance::getBuildVersion)
.filter(Objects::nonNull)
.distinct()
.sorted()
.toList();
if (versions.isEmpty()) {
return null;
}
else if (versions.size() == 1) {
return versions.get(0);
}
else {
return BuildVersion.valueOf(versions.get(0) + " ... " + versions.get(versions.size() - 1));
}
}
protected Tuple2<String, Instant> getStatus(List<Instance> instances) {
// TODO: Correct is just a second readmodel for groups
Map<String, Instant> statusWithTime = instances.stream()
.collect(toMap((instance) -> instance.getStatusInfo().getStatus(), Instance::getStatusTimestamp,
this::getMax));
if (statusWithTime.size() == 1) {
|
Map.Entry<String, Instant> e = statusWithTime.entrySet().iterator().next();
return Tuples.of(e.getKey(), e.getValue());
}
if (statusWithTime.containsKey(StatusInfo.STATUS_UP)) {
Instant oldestNonUp = statusWithTime.entrySet()
.stream()
.filter((e) -> !StatusInfo.STATUS_UP.equals(e.getKey()))
.map(Map.Entry::getValue)
.min(naturalOrder())
.orElse(Instant.EPOCH);
Instant latest = getMax(oldestNonUp, statusWithTime.getOrDefault(StatusInfo.STATUS_UP, Instant.EPOCH));
return Tuples.of(StatusInfo.STATUS_RESTRICTED, latest);
}
return statusWithTime.entrySet()
.stream()
.min(Map.Entry.comparingByKey(StatusInfo.severity()))
.map((e) -> Tuples.of(e.getKey(), e.getValue()))
.orElse(Tuples.of(STATUS_UNKNOWN, Instant.EPOCH));
}
protected Instant getMax(Instant t1, Instant t2) {
return (t1.compareTo(t2) >= 0) ? t1 : t2;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\ApplicationRegistry.java
| 2
|
请完成以下Java代码
|
public void setAcctSvcrTxId(String value) {
this.acctSvcrTxId = value;
}
/**
* Gets the value of the mktInfrstrctrTxId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMktInfrstrctrTxId() {
return mktInfrstrctrTxId;
}
/**
* Sets the value of the mktInfrstrctrTxId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMktInfrstrctrTxId(String value) {
this.mktInfrstrctrTxId = value;
}
/**
* Gets the value of the prcgId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPrcgId() {
return prcgId;
}
/**
* Sets the value of the prcgId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrcgId(String value) {
this.prcgId = value;
}
/**
* Gets the value of the prtry 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 prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryReference1 }
*
*
*/
public List<ProprietaryReference1> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryReference1>();
}
return this.prtry;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionReferences3.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MSV3_Customer_Config
{
private MSV3CustomerConfigService getMSV3CustomerConfigService()
{
return Adempiere.getBean(MSV3CustomerConfigService.class);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void onCreated(final I_MSV3_Customer_Config configRecord)
{
if (configRecord.isActive())
{
final MSV3CustomerConfigService service = getMSV3CustomerConfigService();
service.publishConfigChanged(configRecord);
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE)
public void onUpdated(final I_MSV3_Customer_Config configRecord)
|
{
final MSV3CustomerConfigService service = getMSV3CustomerConfigService();
if (configRecord.isActive())
{
service.publishConfigChanged(configRecord);
}
else
{
service.publishConfigDeleted(configRecord.getMSV3_Customer_Config_ID());
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void onDeleted(final I_MSV3_Customer_Config configRecord)
{
final MSV3CustomerConfigService service = getMSV3CustomerConfigService();
service.publishConfigDeleted(configRecord.getMSV3_Customer_Config_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\MSV3_Customer_Config.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
@Column(length = 3)
private String firstName;
@Size(min = 3, max = 15)
private String middleName;
@Length(min = 3, max = 15)
private String lastName;
@Column(length = 5)
@Size(min = 3, max = 5)
private String city;
public User(String firstName, String middleName, String lastName, String city) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.city = city;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
|
public void setMiddleName(String middletName) {
this.middleName = middletName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkey\User.java
| 2
|
请完成以下Java代码
|
public class ShortValueSerializer extends PrimitiveValueSerializer<ShortValue> {
public ShortValueSerializer() {
super(ValueType.SHORT);
}
public ShortValue convertToTypedValue(UntypedValueImpl untypedValue) {
return Variables.shortValue((Short) untypedValue.getValue(), untypedValue.isTransient());
}
public ShortValue readValue(ValueFields valueFields, boolean asTransientValue) {
Long longValue = valueFields.getLongValue();
Short shortValue = null;
if(longValue != null) {
shortValue = longValue.shortValue();
}
return Variables.shortValue(shortValue, asTransientValue);
}
|
public void writeValue(ShortValue value, ValueFields valueFields) {
Short shortValue = value.getValue();
if (shortValue != null) {
valueFields.setLongValue(shortValue.longValue());
valueFields.setTextValue(value.toString());
} else {
valueFields.setLongValue(null);
valueFields.setTextValue(null);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\ShortValueSerializer.java
| 1
|
请完成以下Java代码
|
public boolean isAllowDifferentCapacities()
{
return allowDifferentCapacities;
}
@Override
public void setAllowDifferentCapacities(final boolean allowDifferentCapacities)
{
this.allowDifferentCapacities = allowDifferentCapacities;
}
@Override
public boolean isAllowInfiniteCapacity()
{
return allowInfiniteCapacity;
}
@Override
public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity)
{
this.allowInfiniteCapacity = allowInfiniteCapacity;
}
@Override
public boolean isAllowAnyPartner()
|
{
return allowAnyPartner;
}
@Override
public void setAllowAnyPartner(final boolean allowAnyPartner)
{
this.allowAnyPartner = allowAnyPartner;
}
@Override
public int getM_Product_Packaging_ID()
{
return packagingProductId;
}
@Override
public void setM_Product_Packaging_ID(final int packagingProductId)
{
this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
| 1
|
请完成以下Java代码
|
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getCreatedDate() {
return createdDate;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
return new Date();
}
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
return new Date();
}
}
@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
class UserIgnoreCase {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
public UserIgnoreCase() {
}
public UserIgnoreCase(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.createdDate = new Date();
}
public String getFirstName() {
return firstName;
}
|
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getCreatedDate() {
return createdDate;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
return new Date();
}
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
return new Date();
}
}
|
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\format\User.java
| 1
|
请完成以下Java代码
|
public static String getStringFromReader(Reader reader, boolean trim) throws IOException {
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (trim) {
stringBuilder.append(line.trim());
} else {
stringBuilder.append(line).append("\n");
}
}
} finally {
closeSilently(bufferedReader);
}
return stringBuilder.toString();
|
}
public static Reader classpathResourceAsReader(String fileName) {
try {
File classpathFile = getClasspathFile(fileName);
return new FileReader(classpathFile);
} catch (FileNotFoundException e) {
throw LOG.fileNotFoundException(fileName, e);
}
}
public static Reader stringAsReader(String string) {
return new StringReader(string);
}
}
|
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\SpinIoUtil.java
| 1
|
请完成以下Java代码
|
public String toString() {return getCode();}
@JsonValue
@NonNull
public String getCode() {return code;}
public static boolean equals(@Nullable final EventStatus status1, @Nullable final EventStatus status2) {return Objects.equals(status1, status2);}
}
//
//
//
//
//
@Value
@Builder
@Jacksonized
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Event
{
String id;
EventType type;
EventStatus status;
/**
* e.g. 2024-10-05T12:48:34.312Z
*/
String timestamp;
BigDecimal amount;
@JsonProperty("fee_amount") BigDecimal fee_amount;
// other fields:
// "deducted_amount": 0.0,
// "deducted_fee_amount": 0.0,
// "transaction_id": "1a434bf8-bd5c-44a6-8576-37bc9aedc912",
// "installment_number": 1,
// "payout_reference": "SUMUP PID",
|
@JsonIgnore
public boolean isRefunded()
{
return EventType.equals(type, EventType.REFUND)
&& EventStatus.equals(status, EventStatus.REFUNDED);
}
@JsonIgnore
public BigDecimal getAmountPlusFee()
{
BigDecimal result = BigDecimal.ZERO;
if (amount != null)
{
result = result.add(amount);
}
if (amount != null)
{
result = result.add(fee_amount);
}
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\json\JsonGetTransactionResponse.java
| 1
|
请完成以下Java代码
|
public void mergeFrom(final WindowId windowId, final DocumentId documentId, final JSONIncludedTabInfo tabInfo)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.addIncludedTabInfo(tabInfo);
}
public void mergeFrom(final JSONDocumentChangedWebSocketEventCollector from)
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> fromEvents = from._events;
if (fromEvents == null || fromEvents.isEmpty())
{
return;
}
fromEvents.forEach(this::mergeFrom);
}
private void mergeFrom(final EventKey key, final JSONDocumentChangedWebSocketEvent from)
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events;
|
if (events == null)
{
throw new AdempiereException("already closed: " + this);
}
events.compute(key, (k, existingEvent) -> {
if (existingEvent == null)
{
return from.copy();
}
else
{
existingEvent.mergeFrom(from);
return existingEvent;
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEventCollector.java
| 1
|
请完成以下Java代码
|
public LongestSearcher getLongestSearcher(String text, int offset)
{
return getLongestSearcher(text.toCharArray(), offset);
}
public LongestSearcher getLongestSearcher(char[] text, int offset)
{
return new LongestSearcher(offset, text);
}
/**
* 最长匹配
*
* @param text 文本
* @param processor 处理器
*/
public void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<V> processor)
{
LongestSearcher searcher = getLongestSearcher(text, 0);
while (searcher.next())
{
processor.hit(searcher.begin, searcher.begin + searcher.length, searcher.value);
}
}
/**
* 转移状态
*
* @param current
* @param c
* @return
*/
protected int transition(int current, char c)
{
int b = base[current];
int p;
p = b + c + 1;
if (b == check[p])
b = base[p];
else
return -1;
p = b;
return p;
}
/**
* 更新某个键对应的值
*
* @param key 键
* @param value 值
* @return 是否成功(失败的原因是没有这个键)
*/
public boolean set(String key, V value)
{
int index = exactMatchSearch(key);
if (index >= 0)
{
v[index] = value;
return true;
}
return false;
}
|
/**
* 从值数组中提取下标为index的值<br>
* 注意为了效率,此处不进行参数校验
*
* @param index 下标
* @return 值
*/
public V get(int index)
{
return v[index];
}
/**
* 释放空闲的内存
*/
private void shrink()
{
// if (HanLP.Config.DEBUG)
// {
// System.err.printf("释放内存 %d bytes\n", base.length - size - 65535);
// }
int nbase[] = new int[size + 65535];
System.arraycopy(base, 0, nbase, 0, size);
base = nbase;
int ncheck[] = new int[size + 65535];
System.arraycopy(check, 0, ncheck, 0, size);
check = ncheck;
}
/**
* 打印统计信息
*/
// public void report()
// {
// System.out.println("size: " + size);
// int nonZeroIndex = 0;
// for (int i = 0; i < base.length; i++)
// {
// if (base[i] != 0) nonZeroIndex = i;
// }
// System.out.println("BaseUsed: " + nonZeroIndex);
// nonZeroIndex = 0;
// for (int i = 0; i < check.length; i++)
// {
// if (check[i] != 0) nonZeroIndex = i;
// }
// System.out.println("CheckUsed: " + nonZeroIndex);
// }
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\DoubleArrayTrie.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DataMongoProperties {
/**
* Whether to enable auto-index creation.
*/
private @Nullable Boolean autoIndexCreation;
/**
* Fully qualified name of the FieldNamingStrategy to use.
*/
private @Nullable Class<?> fieldNamingStrategy;
private final Gridfs gridfs = new Gridfs();
private final Representation representation = new Representation();
public @Nullable Boolean isAutoIndexCreation() {
return this.autoIndexCreation;
}
public void setAutoIndexCreation(@Nullable Boolean autoIndexCreation) {
this.autoIndexCreation = autoIndexCreation;
}
public @Nullable Class<?> getFieldNamingStrategy() {
return this.fieldNamingStrategy;
}
public void setFieldNamingStrategy(@Nullable Class<?> fieldNamingStrategy) {
this.fieldNamingStrategy = fieldNamingStrategy;
}
public Gridfs getGridfs() {
return this.gridfs;
}
public Representation getRepresentation() {
return this.representation;
}
public static class Gridfs {
/**
* GridFS database name.
*/
private @Nullable String database;
/**
* GridFS bucket name.
*/
private @Nullable String bucket;
public @Nullable String getDatabase() {
return this.database;
}
public void setDatabase(@Nullable String database) {
this.database = database;
}
|
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
}
public static class Representation {
/**
* Representation to use when converting a BigDecimal.
*/
private @Nullable BigDecimalRepresentation bigDecimal = BigDecimalRepresentation.UNSPECIFIED;
public @Nullable BigDecimalRepresentation getBigDecimal() {
return this.bigDecimal;
}
public void setBigDecimal(@Nullable BigDecimalRepresentation bigDecimal) {
this.bigDecimal = bigDecimal;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-mongodb\src\main\java\org\springframework\boot\data\mongodb\autoconfigure\DataMongoProperties.java
| 2
|
请完成以下Java代码
|
public void validate(@NonNull final I_C_OLCand olCand)
{
// If there is a PIIP, then verify that there is pricing info for the packing material. Otherwise, completing the order will fail later on.
final I_M_HU_PI_Item_Product huPIItemProduct = OLCandPIIPUtil.extractHUPIItemProductOrNull(olCand);
if (huPIItemProduct != null)
{
final IHUPackingMaterialDAO packingMaterialDAO = Services.get(IHUPackingMaterialDAO.class);
final List<I_M_HU_PackingMaterial> packingMaterials = packingMaterialDAO.retrievePackingMaterials(huPIItemProduct);
for (final I_M_HU_PackingMaterial pm : packingMaterials)
{
final ProductId packingMaterialProductId = ProductId.ofRepoIdOrNull(pm.getM_Product_ID());
checkForPrice(olCand, packingMaterialProductId);
}
if (huPIItemProduct.isOrderInTuUomWhenMatched())
{
olCand.setC_UOM_Internal_ID(uomDAO.getUomIdByX12DE355(X12DE355.COLI).getRepoId());
}
}
}
private void checkForPrice(@NonNull final I_C_OLCand olCand, @Nullable final ProductId packingMaterialProductId)
{
final PricingSystemId pricingSystemId = PricingSystemId.ofRepoIdOrNull(olCand.getM_PricingSystem_ID());
final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class);
final LocalDate datePromisedEffective = TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olCand));
final BPartnerLocationAndCaptureId billBPLocationId = olCandEffectiveValuesBL.getBillLocationAndCaptureEffectiveId(olCand);
final PriceListId plId = Services.get(IPriceListDAO.class).retrievePriceListIdByPricingSyst(pricingSystemId, billBPLocationId, SOTrx.SALES);
if (plId == null)
{
throw new AdempiereException("@PriceList@ @NotFound@: @M_PricingSystem@ " + pricingSystemId + ", @Bill_Location@ " + billBPLocationId);
}
|
final IPricingBL pricingBL = Services.get(IPricingBL.class);
final IEditablePricingContext pricingCtx = pricingBL.createPricingContext();
pricingCtx.setBPartnerId(BPartnerId.ofRepoIdOrNull(olCand.getBill_BPartner_ID()));
pricingCtx.setSOTrx(SOTrx.SALES);
pricingCtx.setQty(BigDecimal.ONE); // we don't care for the actual quantity we just want to verify that there is a price
pricingCtx.setPricingSystemId(pricingSystemId);
pricingCtx.setPriceListId(plId);
pricingCtx.setProductId(packingMaterialProductId);
pricingCtx.setPriceDate(datePromisedEffective);
pricingCtx.setCurrencyId(CurrencyId.ofRepoId(olCand.getC_Currency_ID()));
pricingCtx.setFailIfNotCalculated();
Services.get(IPricingBL.class).calculatePrice(pricingCtx);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\ordercandidate\spi\impl\OLCandPIIPPriceValidator.java
| 1
|
请完成以下Java代码
|
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
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<ResponseEntity<JWTToken>> authorize(@Valid @RequestBody Mono<LoginVM> loginVM) {
return loginVM
.flatMap(
login ->
authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()))
.flatMap(auth -> Mono.fromCallable(() -> this.createToken(auth, login.isRememberMe())))
)
.map(jwt -> {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setBearerAuth(jwt);
return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
});
}
/**
* {@code GET /authenticate} : check if the user is authenticated, and return its login.
*
* @param request the HTTP request.
* @return the login if the user is authenticated.
*/
@GetMapping("/authenticate")
public Mono<String> isAuthenticated(ServerWebExchange request) {
log.debug("REST request to check if the current user is authenticated");
return request.getPrincipal().map(Principal::getName);
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" "));
Instant now = Instant.now();
Instant validity;
if (rememberMe) {
validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS);
} else {
validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS);
}
|
// @formatter:off
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(validity)
.subject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken {
private String idToken;
JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\rest\AuthenticateController.java
| 2
|
请完成以下Java代码
|
public abstract class AbstractAtomicOperationCaseExecutionComplete extends AbstractCmmnEventAtomicOperation {
protected static final CmmnOperationLogger LOG = ProcessEngineLogger.CMMN_OPERATION_LOGGER;
protected String getEventName() {
return COMPLETE;
}
protected CmmnExecution eventNotificationsStarted(CmmnExecution execution) {
CmmnActivityBehavior behavior = getActivityBehavior(execution);
triggerBehavior(behavior, execution);
execution.setCurrentState(COMPLETED);
return execution;
}
protected void postTransitionNotification(CmmnExecution execution) {
if (!execution.isCaseInstanceExecution()) {
execution.remove();
} else {
CmmnExecution superCaseExecution = execution.getSuperCaseExecution();
PvmExecutionImpl superExecution = execution.getSuperExecution();
if (superCaseExecution != null) {
TransferVariablesActivityBehavior behavior = (TransferVariablesActivityBehavior) getActivityBehavior(superCaseExecution);
behavior.transferVariables(execution, superCaseExecution);
superCaseExecution.complete();
} else if (superExecution != null) {
SubProcessActivityBehavior behavior = (SubProcessActivityBehavior) getActivityBehavior(superExecution);
try {
behavior.passOutputVariables(superExecution, execution);
} catch (RuntimeException e) {
LOG.completingSubCaseError(execution, e);
throw e;
} catch (Exception e) {
LOG.completingSubCaseError(execution, e);
throw LOG.completingSubCaseErrorException(execution, e);
}
// set sub case instance to null
superExecution.setSubCaseInstance(null);
try {
behavior.completed(superExecution);
} catch (RuntimeException e) {
LOG.completingSubCaseError(execution, e);
|
throw e;
} catch (Exception e) {
LOG.completingSubCaseError(execution, e);
throw LOG.completingSubCaseErrorException(execution, e);
}
}
execution.setSuperCaseExecution(null);
execution.setSuperExecution(null);
}
CmmnExecution parent = execution.getParent();
if (parent != null) {
CmmnActivityBehavior behavior = getActivityBehavior(parent);
if (behavior instanceof CmmnCompositeActivityBehavior) {
CmmnCompositeActivityBehavior compositeBehavior = (CmmnCompositeActivityBehavior) behavior;
compositeBehavior.handleChildCompletion(parent, execution);
}
}
}
protected abstract void triggerBehavior(CmmnActivityBehavior behavior, CmmnExecution execution);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\operation\AbstractAtomicOperationCaseExecutionComplete.java
| 1
|
请完成以下Java代码
|
public void setLabelCertificationAuthority (java.lang.String LabelCertificationAuthority)
{
set_Value (COLUMNNAME_LabelCertificationAuthority, LabelCertificationAuthority);
}
/** Get Label-Zerti-Stelle.
@return Zertifizierungsstelle
*/
@Override
public java.lang.String getLabelCertificationAuthority ()
{
return (java.lang.String)get_Value(COLUMNNAME_LabelCertificationAuthority);
}
@Override
public org.compiere.model.I_M_Label getM_Label() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Label_ID, org.compiere.model.I_M_Label.class);
}
@Override
public void setM_Label(org.compiere.model.I_M_Label M_Label)
{
set_ValueFromPO(COLUMNNAME_M_Label_ID, org.compiere.model.I_M_Label.class, M_Label);
}
/** Set Label List.
@param M_Label_ID Label List */
@Override
public void setM_Label_ID (int M_Label_ID)
{
if (M_Label_ID < 1)
set_Value (COLUMNNAME_M_Label_ID, null);
else
set_Value (COLUMNNAME_M_Label_ID, Integer.valueOf(M_Label_ID));
}
/** Get Label List.
@return Label List */
@Override
public int getM_Label_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Label_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Label_ID.
@param M_Product_Certificate_ID Label_ID */
@Override
public void setM_Product_Certificate_ID (int M_Product_Certificate_ID)
{
if (M_Product_Certificate_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_Certificate_ID, Integer.valueOf(M_Product_Certificate_ID));
}
/** Get Label_ID.
@return Label_ID */
@Override
|
public int getM_Product_Certificate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Certificate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Certificate.java
| 1
|
请完成以下Java代码
|
public int getAD_UserQuery_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserQuery_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validierungscode.
@param Code
Validation Code
*/
@Override
public void setCode (java.lang.String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validierungscode.
@return Validation Code
*/
@Override
public java.lang.String getCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Code);
}
/** 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 Mandatory Parameters.
@param IsManadatoryParams Mandatory Parameters */
@Override
public void setIsManadatoryParams (boolean IsManadatoryParams)
{
set_Value (COLUMNNAME_IsManadatoryParams, Boolean.valueOf(IsManadatoryParams));
}
/** Get Mandatory Parameters.
@return Mandatory Parameters */
@Override
public boolean isManadatoryParams ()
{
|
Object oo = get_Value(COLUMNNAME_IsManadatoryParams);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Display All Parameters.
@param IsShowAllParams Display All Parameters */
@Override
public void setIsShowAllParams (boolean IsShowAllParams)
{
set_Value (COLUMNNAME_IsShowAllParams, Boolean.valueOf(IsShowAllParams));
}
/** Get Display All Parameters.
@return Display All Parameters */
@Override
public boolean isShowAllParams ()
{
Object oo = get_Value(COLUMNNAME_IsShowAllParams);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserQuery.java
| 1
|
请完成以下Java代码
|
public int getAD_Client_ID() {
return po.getAD_Client_ID(); // getAD_Client_ID
}
/**
* Get AD_Org
* @return AD_Org_ID
*/
public int getAD_Org_ID() {
return po.getAD_Org_ID(); // getAD_Org_ID
}
/**
* Set Active
* @param active active
*/
public void setIsActive(boolean active) {
po.setIsActive(active); // setActive
}
/**
* Is Active
* @return is active
*/
public boolean isActive() {
return po.isActive(); // isActive
}
/**
* Get Created
* @return created
*/
public Timestamp getCreated() {
return po.getCreated(); // getCreated
}
/**
* Get Updated
* @return updated
*/
public Timestamp getUpdated() {
return po.getUpdated(); // getUpdated
}
/**
* Get CreatedBy
* @return AD_User_ID
*/
public int getCreatedBy() {
return po.getCreatedBy(); // getCreateddBy
}
/**
* Get UpdatedBy
* @return AD_User_ID
*/
public int getUpdatedBy() {
return po.getUpdatedBy(); // getUpdatedBy
}
/**************************************************************************
* Update Value or create new record.
* To reload call load() - not updated
* @return true if saved
*/
public boolean save() {
return po.save(); // save
}
/**
* Update Value or create new record.
* To reload call load() - not updated
* @param trxName transaction
* @return true if saved
*/
public boolean save(String trxName) {
return po.save(trxName); // save
}
/**
* Is there a Change to be saved?
* @return true if record changed
*/
public boolean is_Changed() {
return po.is_Changed(); // is_Change
}
/**
* Create Single/Multi Key Where Clause
* @param withValues if true uses actual values otherwise ?
* @return where clause
*/
public String get_WhereClause(boolean withValues) {
return po.get_WhereClause(withValues); // getWhereClause
}
/**************************************************************************
* Delete Current Record
* @param force delete also processed records
* @return true if deleted
|
*/
public boolean delete(boolean force) {
return po.delete(force); // delete
}
/**
* Delete Current Record
* @param force delete also processed records
* @param trxName transaction
*/
public boolean delete(boolean force, String trxName) {
return po.delete(force, trxName); // delete
}
/**************************************************************************
* Lock it.
* @return true if locked
*/
public boolean lock() {
return po.lock(); // lock
}
/**
* UnLock it
* @return true if unlocked (false only if unlock fails)
*/
public boolean unlock(String trxName) {
return po.unlock(trxName); // unlock
}
/**
* Set Trx
* @param trxName transaction
*/
public void set_TrxName(String trxName) {
po.set_TrxName(trxName); // setTrx
}
/**
* Get Trx
* @return transaction
*/
public String get_TrxName() {
return po.get_TrxName(); // getTrx
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java
| 1
|
请完成以下Java代码
|
public class Person {
@JsonElement
private String firstName;
@JsonElement
private String lastName;
@JsonElement(key = "personAge")
private String age;
private String address;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public Person(String firstName, String lastName, String age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Init
private void initNames() {
this.firstName = this.firstName.substring(0, 1)
.toUpperCase() + this.firstName.substring(1);
this.lastName = this.lastName.substring(0, 1)
.toUpperCase() + this.lastName.substring(1);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
|
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
|
repos\tutorials-master\core-java-modules\core-java-annotations\src\main\java\com\baeldung\customannotations\Person.java
| 1
|
请完成以下Java代码
|
protected void initializeTaskListeners(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, TaskDefinition taskDefinition) {
HumanTask humanTask = getDefinition(element);
List<CamundaTaskListener> listeners = queryExtensionElementsByClass(humanTask, CamundaTaskListener.class);
for (CamundaTaskListener listener : listeners) {
TaskListener taskListener = initializeTaskListener(element, activity, context, listener);
String eventName = listener.getCamundaEvent();
if (eventName != null) {
taskDefinition.addTaskListener(eventName, taskListener);
} else {
taskDefinition.addTaskListener(TaskListener.EVENTNAME_CREATE, taskListener);
taskDefinition.addTaskListener(TaskListener.EVENTNAME_ASSIGNMENT, taskListener);
taskDefinition.addTaskListener(TaskListener.EVENTNAME_COMPLETE, taskListener);
taskDefinition.addTaskListener(TaskListener.EVENTNAME_UPDATE, taskListener);
taskDefinition.addTaskListener(TaskListener.EVENTNAME_DELETE, taskListener);
}
}
}
protected TaskListener initializeTaskListener(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, CamundaTaskListener listener) {
Collection<CamundaField> fields = listener.getCamundaFields();
List<FieldDeclaration> fieldDeclarations = initializeFieldDeclarations(element, activity, context, fields);
ExpressionManager expressionManager = context.getExpressionManager();
TaskListener taskListener = null;
String className = listener.getCamundaClass();
String expression = listener.getCamundaExpression();
String delegateExpression = listener.getCamundaDelegateExpression();
CamundaScript scriptElement = listener.getCamundaScript();
if (className != null) {
taskListener = new ClassDelegateTaskListener(className, fieldDeclarations);
} else if (expression != null) {
Expression expressionExp = expressionManager.createExpression(expression);
taskListener = new ExpressionTaskListener(expressionExp);
|
} else if (delegateExpression != null) {
Expression delegateExp = expressionManager.createExpression(delegateExpression);
taskListener = new DelegateExpressionTaskListener(delegateExp, fieldDeclarations);
} else if (scriptElement != null) {
ExecutableScript executableScript = initializeScript(element, activity, context, scriptElement);
if (executableScript != null) {
taskListener = new ScriptTaskListener(executableScript);
}
}
return taskListener;
}
protected HumanTask getDefinition(CmmnElement element) {
return (HumanTask) super.getDefinition(element);
}
@Override
protected CmmnActivityBehavior getActivityBehavior() {
return new HumanTaskActivityBehavior();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\HumanTaskItemHandler.java
| 1
|
请完成以下Java代码
|
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public int getHorsePower() {
return horsePower;
}
public void setHorsePower(int horsePower) {
this.horsePower = horsePower;
}
|
public int getNumberOfCylinders() {
return numberOfCylinders;
}
public void setNumberOfCylinders(int numberOfCylinders) {
this.numberOfCylinders = numberOfCylinders;
}
@Override
public String toString() {
return "Engine{" +
"capacity=" + capacity +
", horsePower=" + horsePower +
", numberOfCylinders=" + numberOfCylinders +
'}';
}
}
|
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\entity\Engine.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Greeting_ID (final int C_Greeting_ID)
{
if (C_Greeting_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Greeting_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Greeting_ID, C_Greeting_ID);
}
@Override
public int getC_Greeting_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Greeting_ID);
}
@Override
public void setGreeting (final @Nullable java.lang.String Greeting)
{
set_Value (COLUMNNAME_Greeting, Greeting);
}
@Override
public java.lang.String getGreeting()
{
return get_ValueAsString(COLUMNNAME_Greeting);
}
/**
* GreetingStandardType AD_Reference_ID=541326
* Reference name: GreetingStandardType
*/
public static final int GREETINGSTANDARDTYPE_AD_Reference_ID=541326;
/** MR = MR */
public static final String GREETINGSTANDARDTYPE_MR = "MR";
/** MRS = MRS */
public static final String GREETINGSTANDARDTYPE_MRS = "MRS";
/** MR+MRS = MR+MRS */
public static final String GREETINGSTANDARDTYPE_MRPlusMRS = "MR+MRS";
/** MRS+MR = MRS+MR */
public static final String GREETINGSTANDARDTYPE_MRSPlusMR = "MRS+MR";
@Override
public void setGreetingStandardType (final @Nullable java.lang.String GreetingStandardType)
{
set_Value (COLUMNNAME_GreetingStandardType, GreetingStandardType);
}
@Override
public java.lang.String getGreetingStandardType()
{
return get_ValueAsString(COLUMNNAME_GreetingStandardType);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
|
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setIsFirstNameOnly (final boolean IsFirstNameOnly)
{
set_Value (COLUMNNAME_IsFirstNameOnly, IsFirstNameOnly);
}
@Override
public boolean isFirstNameOnly()
{
return get_ValueAsBoolean(COLUMNNAME_IsFirstNameOnly);
}
@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_C_Greeting.java
| 1
|
请完成以下Java代码
|
public class ResourceCheckFilter extends AccessControlFilter {
private String errorUrl;
public String getErrorUrl() {
return errorUrl;
}
public void setErrorUrl(String errorUrl) {
this.errorUrl = errorUrl;
}
/**
* 表示是否允许访问 ,如果允许访问返回true,否则false;
*
* @param servletRequest
* @param servletResponse
* @param o 表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分
* @return
* @throws Exception
*/
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
Subject subject = getSubject(servletRequest, servletResponse);
String url = getPathWithinApplication(servletRequest);
log.info("当前用户正在访问的 url => " + url);
return subject.isPermitted(url);
}
/**
* onAccessDenied:表示当访问拒绝时是否已经处理了; 如果返回 true 表示需要继续处理; 如果返回 false
* 表示该拦截器实例已经处理了,将直接返回即可。
*
|
* @param servletRequest
* @param servletResponse
* @return
* @throws Exception
*/
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
log.info("当 isAccessAllowed 返回 false 的时候,才会执行 method onAccessDenied ");
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.sendRedirect(request.getContextPath() + this.errorUrl);
// 返回 false 表示已经处理,例如页面跳转啥的,表示不在走以下的拦截器了(如果还有配置的话)
return false;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\filters\ResourceCheckFilter.java
| 1
|
请完成以下Java代码
|
public void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic)
{
HandlerTools.setDeliveredData(ic);
}
@Override
public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(ic);
final ConditionTypeSpecificInvoiceCandidateHandler handler = getSpecificHandler(term);
return handler.calculatePriceAndTax(ic);
}
@Override
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
HandlerTools.setBPartnerData(ic);
}
@Override
public void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_Flatrate_Term term = HandlerTools.retrieveTerm(ic);
final ConditionTypeSpecificInvoiceCandidateHandler handler = getSpecificHandler(term);
final Consumer<I_C_Invoice_Candidate> defaultImplementation = super::setInvoiceScheduleAndDateToInvoice;
|
handler.getInvoiceScheduleSetterFunction(defaultImplementation)
.accept(ic);
}
private ConditionTypeSpecificInvoiceCandidateHandler getSpecificHandler(@NonNull final I_C_Flatrate_Term term)
{
final ConditionTypeSpecificInvoiceCandidateHandler handlerOrNull = conditionTypeSpecificInvoiceCandidateHandlers.get(term.getType_Conditions());
return Check.assumeNotNull(handlerOrNull,
"The given term's condition-type={} has a not-null ConditionTypeSpecificInvoiceCandidateHandler; term={}",
term.getType_Conditions(), term);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoicecandidate\FlatrateTerm_Handler.java
| 1
|
请完成以下Java代码
|
public class IOParameter extends BaseElement {
protected String source;
protected String sourceExpression;
protected String target;
protected String targetExpression;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getSourceExpression() {
return sourceExpression;
}
|
public void setSourceExpression(String sourceExpression) {
this.sourceExpression = sourceExpression;
}
public String getTargetExpression() {
return targetExpression;
}
public void setTargetExpression(String targetExpression) {
this.targetExpression = targetExpression;
}
public IOParameter clone() {
IOParameter clone = new IOParameter();
clone.setValues(this);
return clone;
}
public void setValues(IOParameter otherElement) {
super.setValues(otherElement);
setSource(otherElement.getSource());
setSourceExpression(otherElement.getSourceExpression());
setTarget(otherElement.getTarget());
setTargetExpression(otherElement.getTargetExpression());
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\IOParameter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private SslOptions createSslOptions(@Nullable String ciphers, @Nullable String enabledProtocols) {
Set<String> ciphersSet = null;
if (StringUtils.hasLength(ciphers)) {
ciphersSet = StringUtils.commaDelimitedListToSet(ciphers);
}
Set<String> enabledProtocolsSet = null;
if (StringUtils.hasLength(enabledProtocols)) {
enabledProtocolsSet = StringUtils.commaDelimitedListToSet(enabledProtocols);
}
return SslOptions.of(ciphersSet, enabledProtocolsSet);
}
private @Nullable SslBundle getPemSslBundle(RunningService service) {
PemSslStoreDetails keyStoreDetails = getPemSslStoreDetails(service, "keystore");
PemSslStoreDetails trustStoreDetails = getPemSslStoreDetails(service, "truststore");
if (keyStoreDetails == null && trustStoreDetails == null) {
return null;
}
SslBundleKey key = SslBundleKey.of(service.labels().get("org.springframework.boot.sslbundle.pem.key.alias"),
service.labels().get("org.springframework.boot.sslbundle.pem.key.password"));
SslOptions options = createSslOptions(
service.labels().get("org.springframework.boot.sslbundle.pem.options.ciphers"),
service.labels().get("org.springframework.boot.sslbundle.pem.options.enabled-protocols"));
String protocol = service.labels().get("org.springframework.boot.sslbundle.pem.protocol");
Path workingDirectory = getWorkingDirectory(service);
ResourceLoader resourceLoader = getResourceLoader(workingDirectory);
return SslBundle.of(new PemSslStoreBundle(PemSslStore.load(keyStoreDetails, resourceLoader),
PemSslStore.load(trustStoreDetails, resourceLoader)), key, options, protocol);
}
private @Nullable PemSslStoreDetails getPemSslStoreDetails(RunningService service, String storeType) {
|
String type = service.labels().get("org.springframework.boot.sslbundle.pem.%s.type".formatted(storeType));
String certificate = service.labels()
.get("org.springframework.boot.sslbundle.pem.%s.certificate".formatted(storeType));
String privateKey = service.labels()
.get("org.springframework.boot.sslbundle.pem.%s.private-key".formatted(storeType));
String privateKeyPassword = service.labels()
.get("org.springframework.boot.sslbundle.pem.%s.private-key-password".formatted(storeType));
if (certificate == null && privateKey == null) {
return null;
}
return new PemSslStoreDetails(type, certificate, privateKey, privateKeyPassword);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\service\connection\DockerComposeConnectionDetailsFactory.java
| 2
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Page URL.
@param PageURL Page URL */
public void setPageURL (String PageURL)
{
set_Value (COLUMNNAME_PageURL, PageURL);
}
/** Get Page URL.
@return Page URL */
public String getPageURL ()
{
return (String)get_Value(COLUMNNAME_PageURL);
}
|
/** Set Counter Count.
@param W_CounterCount_ID
Web Counter Count Management
*/
public void setW_CounterCount_ID (int W_CounterCount_ID)
{
if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID));
}
/** Get Counter Count.
@return Web Counter Count Management
*/
public int getW_CounterCount_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_CounterCount.java
| 1
|
请完成以下Java代码
|
public Map<String, ProtocolConfig> getProtocols() {
return this.protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
}
public Map<String, MonitorConfig> getMonitors() {
return this.monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return this.providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return this.consumers;
}
|
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
@Override
public String toString() {
return "DubboProperties [server=" + this.server + ", application=" + this.application
+ ", module=" + this.module + ", registry=" + this.registry + ", protocol=" + this.protocol
+ ", monitor=" + this.monitor + ", provider=" + this.provider + ", consumer="
+ this.consumer + ", applications=" + this.applications + ", modules=" + this.modules
+ ", registries=" + this.registries + ", protocols=" + this.protocols + ", monitors="
+ this.monitors + ", providers=" + this.providers + ", consumers=" + this.consumers + "]";
}
}
|
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboProperties.java
| 1
|
请完成以下Java代码
|
private static class HUStack
{
private final ArrayList<HuId> huIds = new ArrayList<>();
private final HashMap<HuId, HUBuilder> hus = new HashMap<>();
void push(@NonNull final IPair<HuId, HUBuilder> idWithHuBuilder)
{
this.huIds.add(idWithHuBuilder.getLeft());
this.hus.put(idWithHuBuilder.getLeft(), idWithHuBuilder.getRight());
}
public boolean isEmpty()
{
return huIds.isEmpty();
}
public IPair<HuId, HUBuilder> peek()
{
|
final HuId huId = this.huIds.get(huIds.size() - 1);
final HUBuilder huBuilder = this.hus.get(huId);
return ImmutablePair.of(huId, huBuilder);
}
final IPair<HuId, HUBuilder> pop()
{
final HuId huId = this.huIds.remove(huIds.size() - 1);
final HUBuilder huBuilder = this.hus.remove(huId);
return ImmutablePair.of(huId, huBuilder);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\HURepository.java
| 1
|
请完成以下Java代码
|
public IVendorInvoicingInfo getVendorInvoicingInfoForPLV(final I_M_PriceList_Version plv)
{
final MaterialTrackingAsVendorInvoicingInfo materialTrackingAsVendorInvoicingInfo = new MaterialTrackingAsVendorInvoicingInfo(getM_Material_Tracking());
materialTrackingAsVendorInvoicingInfo.setM_PriceList_Version(plv);
return materialTrackingAsVendorInvoicingInfo;
}
private MaterialTrackingDocumentsPricingInfo getPricingInfo()
{
if (pricingInfo == null)
{
final I_M_Material_Tracking materialTracking = getM_Material_Tracking();
final I_C_Flatrate_Term flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID());
final I_M_PricingSystem pricingSystem = priceListsRepo.getPricingSystemById(PricingSystemId.ofRepoIdOrNull(flatrateTerm
.getC_Flatrate_Conditions()
.getM_PricingSystem_ID()));
pricingInfo = MaterialTrackingDocumentsPricingInfo
.builder()
.setM_Material_Tracking(materialTracking)
// note that we give to the builder also those that were already processed into invoice candidates,
// because it needs that information to distinguish InOutLines that were not yet issued
// from those that were issued and whose issue-PP_Order already have IsInvoiceCanidate='Y'
.setAllProductionOrders(getAllProductionOrders())
.setNotYetInvoicedProductionOrders(getNotInvoicedProductionOrders())
.setM_PricingSystem(pricingSystem)
.build();
}
return pricingInfo;
}
@Override
public List<IQualityInspectionOrder> getProductionOrdersForPLV(final I_M_PriceList_Version plv)
{
return getPricingInfo().getQualityInspectionOrdersForPLV(plv);
}
@Override
public IVendorReceipt<I_M_InOutLine> getVendorReceiptForPLV(final I_M_PriceList_Version plv)
{
return getPricingInfo().getVendorReceiptForPLV(plv);
}
|
@Override
public IQualityInspectionOrder getQualityInspectionOrderOrNull()
{
final List<IQualityInspectionOrder> qualityInspectionOrders = getQualityInspectionOrders();
if (qualityInspectionOrders.isEmpty())
{
return null;
}
// as of now, return the last one
// TODO: consider returning an aggregated/averaged one
return qualityInspectionOrders.get(qualityInspectionOrders.size() - 1);
}
@Override
public void linkModelToMaterialTracking(final Object model)
{
final I_M_Material_Tracking materialTracking = getM_Material_Tracking();
materialTrackingBL.linkModelToMaterialTracking(
MTLinkRequest.builder()
.model(model)
.materialTrackingRecord(materialTracking)
.build());
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingDocuments.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.