instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Spring Boot application配置
# configure datasource #quarkus.datasource.url=jdbc:h2:tcp://localhost/~/test quarkus.datasource.url=jdbc:h2:mem:testdb quarkus.datasource.driver=org.h2.Driver quarkus.datasource.username=sa quarkus.datas
ource.password= #quarkus quarkus.liquibase.change-log=db/liquibase-changelog-master.xml
repos\tutorials-master\quarkus-modules\quarkus-extension\quarkus-app\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public class MSV3ServerRequest { /** If you have 600K items on the metasfresh server, this request should be used with caution. */ public static MSV3ServerRequest requestAll() { return ALL; } public static MSV3ServerRequest requestConfig() { return CONFIG; } private static final MSV3ServerRequest ALL = MSV3ServerRequest.builder() .requestAllUsers(true) .requestAllStockAvailabilities(true) .build(); private static final MSV3ServerRequest CONFIG = MSV3ServerRequest.builder() .requestAllUsers(true) .requestAllStockAvailabilities(false)
.build(); boolean requestAllUsers; boolean requestAllStockAvailabilities; @JsonCreator private MSV3ServerRequest( @JsonProperty("requestAllUsers") final boolean requestAllUsers, @JsonProperty("requestAllStockAvailabilities") final boolean requestAllStockAvailabilities) { this.requestAllUsers = requestAllUsers; this.requestAllStockAvailabilities = requestAllStockAvailabilities; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\protocol\MSV3ServerRequest.java
2
请完成以下Java代码
public static String address(String address, int sensitiveSize) { if (oConvertUtils.isEmpty(address)) { return ""; } int len = address.length(); if(len<sensitiveSize){ return address; } return formatRight(address, sensitiveSize); } /** * [电子邮箱] 邮箱前缀仅显示第一个字母,前缀其他隐藏,用星号代替,@及后面的地址显示 * @param email 电子邮箱 * @return <例子:g**@163.com> */ public static String email(String email) { if (oConvertUtils.isEmpty(email)) { return ""; } int index = email.indexOf("@"); if (index <= 1){ return email; } String begin = email.substring(0, 1); String end = email.substring(index); String stars = "**"; return begin + stars + end; } /** * [银行卡号] 前六位,后四位,其他用星号隐藏每位1个星号 * @param cardNum 银行卡号 * @return <例子:6222600**********1234> */ public static String bankCard(String cardNum) { if (oConvertUtils.isEmpty(cardNum)) { return ""; } return formatBetween(cardNum, 6, 4); } /** * [公司开户银行联号] 公司开户银行联行号,显示前两位,其他用星号隐藏,每位1个星号 * @param code 公司开户银行联号 * @return <例子:12********> */ public static String cnapsCode(String code) { if (oConvertUtils.isEmpty(code)) { return ""; } return formatRight(code, 2); } /** * 将右边的格式化成* * @param str 字符串 * @param reservedLength 保留长度 * @return 格式化后的字符串 */ public static String formatRight(String str, int reservedLength){ String name = str.substring(0, reservedLength); String stars = String.join("", Collections.nCopies(str.length()-reservedLength, "*"));
return name + stars; } /** * 将左边的格式化成* * @param str 字符串 * @param reservedLength 保留长度 * @return 格式化后的字符串 */ public static String formatLeft(String str, int reservedLength){ int len = str.length(); String show = str.substring(len-reservedLength); String stars = String.join("", Collections.nCopies(len-reservedLength, "*")); return stars + show; } /** * 将中间的格式化成* * @param str 字符串 * @param beginLen 开始保留长度 * @param endLen 结尾保留长度 * @return 格式化后的字符串 */ public static String formatBetween(String str, int beginLen, int endLen){ int len = str.length(); String begin = str.substring(0, beginLen); String end = str.substring(len-endLen); String stars = String.join("", Collections.nCopies(len-beginLen-endLen, "*")); return begin + stars + end; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\util\SensitiveInfoUtil.java
1
请在Spring Boot框架中完成以下Java代码
public void sendEmailFromTemplate(User user, String templateName, String titleKey) { Mono.defer(() -> { this.sendEmailFromTemplateSync(user, templateName, titleKey); return Mono.empty(); }).subscribe(); } private void sendEmailFromTemplateSync(User user, String templateName, String titleKey) { if (user.getEmail() == null) { log.debug("Email doesn't exist for user '{}'", user.getLogin()); return; } Locale locale = Locale.forLanguageTag(user.getLangKey()); Context context = new Context(locale); context.setVariable(USER, user); context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl()); String content = templateEngine.process(templateName, context); String subject = messageSource.getMessage(titleKey, null, locale); this.sendEmailSync(user.getEmail(), subject, content, false, true); }
public void sendActivationEmail(User user) { log.debug("Sending activation email to '{}'", user.getEmail()); this.sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title"); } public void sendCreationEmail(User user) { log.debug("Sending creation email to '{}'", user.getEmail()); this.sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title"); } public void sendPasswordResetMail(User user) { log.debug("Sending password reset email to '{}'", user.getEmail()); this.sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title"); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\MailService.java
2
请完成以下Java代码
public static ResourceId ofRepoId(final int repoId) { if (repoId == NO_RESOURCE.repoId) { return NO_RESOURCE; } else { return new ResourceId(repoId); } } @Nullable public static ResourceId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<ResourceId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static ImmutableSet<ResourceId> ofRepoIds(@NonNull final Collection<Integer> repoIds) { if (repoIds.isEmpty()) { return ImmutableSet.of(); } return repoIds.stream().map(ResourceId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } public static int toRepoId(@Nullable final ResourceId ResourceId) { return ResourceId != null ? ResourceId.getRepoId() : -1; }
public static boolean equals(@Nullable final ResourceId o1, @Nullable final ResourceId o2) { return Objects.equals(o1, o2); } int repoId; private ResourceId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "S_Resource_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isNoResource() {return this.repoId == NO_RESOURCE.repoId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\product\ResourceId.java
1
请完成以下Java代码
public int getDLM_Partition_Record_V_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Record_V_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set DLM aktiviert. * * @param IsDLM * Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden */ @Override public void setIsDLM(final boolean IsDLM) { set_ValueNoCheck(COLUMNNAME_IsDLM, Boolean.valueOf(IsDLM)); } /** * Get DLM aktiviert. * * @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden */ @Override public boolean isDLM() { final Object oo = get_Value(COLUMNNAME_IsDLM); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** * Set Datensatz-ID. * * @param Record_ID * Direct internal record ID */ @Override public void setRecord_ID(final int Record_ID) { if (Record_ID < 0) { set_ValueNoCheck(COLUMNNAME_Record_ID, null); } else { set_ValueNoCheck(COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); }
} /** * Get Datensatz-ID. * * @return Direct internal record ID */ @Override public int getRecord_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override public void setTableName(final java.lang.String TableName) { set_ValueNoCheck(COLUMNNAME_TableName, TableName); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Record_V.java
1
请完成以下Java代码
public static boolean isNotNull(@Nullable final DocumentFilterDescriptorsProvider provider) { return !isNull(provider); } private NullDocumentFilterDescriptorsProvider() { } @Override public Collection<DocumentFilterDescriptor> getAll() { return ImmutableList.of(); }
@Override public DocumentFilterDescriptor getByFilterIdOrNull(final String filterId) { return null; } /** * NOTE: required for snapshot testing */ @JsonValue private Map<String, String> toJson() { return ImmutableMap.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\NullDocumentFilterDescriptorsProvider.java
1
请完成以下Java代码
public static boolean equals(@Nullable final LUPickingTarget o1, @Nullable final LUPickingTarget o2) { return Objects.equals(o1, o2); } public boolean isExistingLU() { return luId != null; } public boolean isNewLU() { return luId == null && luPIId != null; } public HuPackingInstructionsId getLuPIIdNotNull() { return Check.assumeNotNull(luPIId, "LU PI shall be set for {}", this); } public HuId getLuIdNotNull() { return Check.assumeNotNull(luId, "LU shall be set for {}", this); } public interface CaseConsumer { void noLU(); void newLU(final HuPackingInstructionsId luPackingInstructionsId); void existingLU(final HuId luId, final HUQRCode luQRCode); } public interface CaseMapper<T> { T noLU(); T newLU(final HuPackingInstructionsId luPackingInstructionsId); T existingLU(final HuId luId, final HUQRCode luQRCode); } public static void apply(@Nullable final LUPickingTarget target, @NonNull final CaseConsumer consumer) { if (target == null) { consumer.noLU(); } else if (target.isNewLU()) { consumer.newLU(target.getLuPIIdNotNull()); } else if (target.isExistingLU()) { consumer.existingLU(target.getLuIdNotNull(), target.getLuQRCode()); }
else { throw new AdempiereException("Unsupported target type: " + target); } } public static <T> T apply(@Nullable final LUPickingTarget target, @NonNull final CaseMapper<T> mapper) { if (target == null) { return mapper.noLU(); } else if (target.isNewLU()) { return mapper.newLU(target.getLuPIIdNotNull()); } else if (target.isExistingLU()) { return mapper.existingLU(target.getLuIdNotNull(), target.getLuQRCode()); } else { throw new AdempiereException("Unsupported target type: " + target); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\LUPickingTarget.java
1
请完成以下Java代码
public int getRowCount() { return m_tab.getRowCount(); } private CellValue getValueAt(final int row, final int col) { final GridField f = m_tab.getField(col); final Object key = m_tab.getValue(row, f.getColumnName()); Object value = key; Lookup lookup = f.getLookup(); if (lookup != null) { // nothing to do } else if (f.getDisplayType() == DisplayType.Button) { lookup = getButtonLookup(f); } if (lookup != null) { value = lookup.getDisplay(key); } final int displayType = f.getDisplayType(); return CellValues.toCellValue(value, displayType); } @Override public boolean isColumnPrinted(final int col) { final GridField f = m_tab.getField(col); // Hide not displayed fields if (!f.isDisplayed(GridTabLayoutMode.Grid)) { return false; } // Hide encrypted fields if (f.isEncrypted()) { return false; } // Hide simple button fields without a value if (f.getDisplayType() == DisplayType.Button && f.getAD_Reference_Value_ID() == null) { return false; } // Hide included tab fields (those are only placeholders for included tabs, always empty) if (f.getIncluded_Tab_ID() > 0) { return false; } // return true;
} @Override public boolean isFunctionRow(final int row) { return false; } @Override public boolean isPageBreak(final int row, final int col) { return false; } private final HashMap<String, MLookup> m_buttonLookups = new HashMap<>(); private MLookup getButtonLookup(final GridField mField) { MLookup lookup = m_buttonLookups.get(mField.getColumnName()); if (lookup != null) { return lookup; } // TODO: refactor with org.compiere.grid.ed.VButton.setField(GridField) if (mField.getColumnName().endsWith("_ID") && !IColumnBL.isRecordIdColumnName(mField.getColumnName())) { lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0, mField.getAD_Column_ID(), DisplayType.Search); } else if (mField.getAD_Reference_Value_ID() != null) { // Assuming List lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0, mField.getAD_Column_ID(), DisplayType.List); } // m_buttonLookups.put(mField.getColumnName(), lookup); return lookup; } @Override protected List<CellValue> getNextRow() { final ArrayList<CellValue> result = new ArrayList<>(); for (int i = 0; i < getColumnCount(); i++) { result.add(getValueAt(rowNumber, i)); } rowNumber++; return result; } @Override protected boolean hasNextRow() { return rowNumber < getRowCount(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\impexp\spreadsheet\excel\GridTabExcelExporter.java
1
请完成以下Java代码
public List<Element> elements() { return elements; } public String toString() { return "<"+tagName+"..."; } public String getUri() { return uri; } public String getTagName() { return tagName; } public int getLine() { return line; } public int getColumn() { return column; } /** * Due to the nature of SAX parsing, sometimes the characters of an element * are not processed at once. So instead of a setText operation, we need * to have an appendText operation. */
public void appendText(String text) { this.text.append(text); } public String getText() { return text.toString(); } /** * allows to recursively collect the ids of all elements in the tree. */ public void collectIds(List<String> ids) { ids.add(attribute("id")); for (Element child : elements) { child.collectIds(ids); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\xml\Element.java
1
请完成以下Java代码
public BigDecimal getMaxAllocation() { return m_maxAllocation; } // getMaxAllocation /** * Set Max Allocation if greater * @param max allocation * @param set set to max */ public void setMaxAllocation (BigDecimal max, boolean set) { if (set || max.compareTo(m_maxAllocation) > 0) m_maxAllocation = max; } // setMaxAllocation /** * Reset Calculations */ public void resetCalculations() { m_actualQty = Env.ZERO; m_actualMin = Env.ZERO; m_actualAllocation = Env.ZERO; // m_lastDifference = Env.ZERO; m_maxAllocation = Env.ZERO; } // resetCalculations /************************************************************************** * Get Product * @return product */ public MProduct getProduct() { if (m_product == null) m_product = MProduct.get(getCtx(), getM_Product_ID()); return m_product; } // getProduct /** * Get Product Standard Precision * @return standard precision */ public int getUOMPrecision() { return getProduct().getUOMPrecision(); } // getUOMPrecision
/************************************************************************** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("MDistributionRunLine[") .append(get_ID()).append("-") .append(getInfo()) .append ("]"); return sb.toString (); } // toString /** * Get Info * @return info */ public String getInfo() { StringBuffer sb = new StringBuffer (); sb.append("Line=").append(getLine()) .append (",TotalQty=").append(getTotalQty()) .append(",SumMin=").append(getActualMin()) .append(",SumQty=").append(getActualQty()) .append(",SumAllocation=").append(getActualAllocation()) .append(",MaxAllocation=").append(getMaxAllocation()) .append(",LastDiff=").append(getLastDifference()); return sb.toString (); } // getInfo } // MDistributionRunLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDistributionRunLine.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId(); addLog("Calling with params: externalSystemChildConfigId: {}", externalSystemChildConfigId); final Iterator<I_S_ExternalReference> externalRefIterator = getSelectedExternalReferenceRecords(); while (externalRefIterator.hasNext()) {
final TableRecordReference externalReferenceRecordRef = TableRecordReference.of(externalRefIterator.next()); getExportExternalReferenceToExternalSystem().exportToExternalSystem(externalSystemChildConfigId, externalReferenceRecordRef, getPinstanceId()); } return JavaProcess.MSG_OK; } @NonNull private Iterator<I_S_ExternalReference> getSelectedExternalReferenceRecords() { final IQueryBuilder<I_S_ExternalReference> externalReferenceQuery = retrieveSelectedRecordsQueryBuilder(I_S_ExternalReference.class); return externalReferenceQuery .create() .iterate(I_S_ExternalReference.class); } protected abstract ExternalSystemType getExternalSystemType(); protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId(); protected abstract String getExternalSystemParam(); protected abstract ExportToExternalSystemService getExportExternalReferenceToExternalSystem(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\externalreference\S_ExternalReference_SyncTo_ExternalSystem.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductionSimulationRowsRepository { private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); private final CandidateRepositoryRetrieval candidateRepositoryRetrieval; private final PPOrderCandidateDAO ppOrderCandidateDAO; private final LookupDataSource productLookup; private final LookupDataSource attributeSetInstanceLookup; private final LookupDataSource warehouseLookup; @Builder public ProductionSimulationRowsRepository( @NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval, @NonNull final PPOrderCandidateDAO ppOrderCandidateDAO, @NonNull final LookupDataSourceFactory lookupDataSourceFactory) { this.candidateRepositoryRetrieval = candidateRepositoryRetrieval; this.ppOrderCandidateDAO = ppOrderCandidateDAO; productLookup = lookupDataSourceFactory.searchInTableLookup(I_M_Product.Table_Name);
attributeSetInstanceLookup = lookupDataSourceFactory.searchInTableLookup(I_M_AttributeSetInstance.Table_Name); warehouseLookup = lookupDataSourceFactory.searchInTableLookup(I_M_Warehouse.Table_Name); } public ProductionSimulationRows getByOrderLineDescriptor(@NonNull final OrderLineDescriptor orderLineDescriptor) { return ProductionSimulationRowsLoader.builder() .candidateRepositoryRetrieval(candidateRepositoryRetrieval) .ppOrderCandidateDAO(ppOrderCandidateDAO) .productLookup(productLookup) .attributeSetInstanceLookup(attributeSetInstanceLookup) .warehouseLookup(warehouseLookup) .orderLineDescriptor(orderLineDescriptor) .orgDAO(orgDAO) .build() .load(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\ProductionSimulationRowsRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class UmsMemberReceiveAddressController { @Autowired private UmsMemberReceiveAddressService memberReceiveAddressService; @ApiOperation("添加收货地址") @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public CommonResult add(@RequestBody UmsMemberReceiveAddress address) { int count = memberReceiveAddressService.add(address); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除收货地址") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = memberReceiveAddressService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改收货地址") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsMemberReceiveAddress address) { int count = memberReceiveAddressService.update(id, address); if (count > 0) { return CommonResult.success(count);
} return CommonResult.failed(); } @ApiOperation("获取所有收货地址") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsMemberReceiveAddress>> list() { List<UmsMemberReceiveAddress> addressList = memberReceiveAddressService.list(); return CommonResult.success(addressList); } @ApiOperation("获取收货地址详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<UmsMemberReceiveAddress> getItem(@PathVariable Long id) { UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(id); return CommonResult.success(address); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\UmsMemberReceiveAddressController.java
2
请在Spring Boot框架中完成以下Java代码
public class ApplicationController extends RouterNanoHTTPD { ApplicationController() throws IOException { super(8072); addMappings(); start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } @Override public void addMappings() { addRoute("/", IndexHandler.class); addRoute("/users", UserHandler.class); } public static class UserHandler extends DefaultHandler {
@Override public String getText() { return "UserA, UserB, UserC"; } @Override public String getMimeType() { return MIME_PLAINTEXT; } @Override public Response.IStatus getStatus() { return Response.Status.OK; } } }
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\nanohttpd\ApplicationController.java
2
请完成以下Java代码
private Map<HuId, I_M_HU> retrieveHUs(final Collection<HuId> huIds) { return Maps.uniqueIndex(handlingUnitsBL.getByIds(huIds), HUsLoadingCache::extractHUId); } public HuId getTopLevelHUId(final HuId huId) { return topLevelHUIds.computeIfAbsent(huId, this::retrieveTopLevelHUId); } private HuId retrieveTopLevelHUId(final HuId huId) { final I_M_HU hu = getHUById(huId); final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParentAsLUTUCUPair(hu).getTopLevelHU(); addToCache(topLevelHU); return extractHUId(topLevelHU); } public ImmutableSet<HuId> getVHUIds(final HuId huId) {return vhuIds.computeIfAbsent(huId, this::retrieveVHUIds);} private ImmutableSet<HuId> retrieveVHUIds(final HuId huId) { final I_M_HU hu = getHUById(huId); final List<I_M_HU> vhus = handlingUnitsBL.getVHUs(hu); addToCache(vhus); return extractHUIds(vhus); } private static ImmutableSet<HuId> extractHUIds(final List<I_M_HU> hus) {return hus.stream().map(HUsLoadingCache::extractHUId).collect(ImmutableSet.toImmutableSet());} private static HuId extractHUId(final I_M_HU hu) {return HuId.ofRepoId(hu.getM_HU_ID());} public ImmutableAttributeSet getHUAttributes(final HuId huId) {
return huAttributesCache.computeIfAbsent(huId, this::retrieveHUAttributes); } private ImmutableAttributeSet retrieveHUAttributes(final HuId huId) { final I_M_HU hu = getHUById(huId); final IAttributeStorage attributes = attributesFactory.getAttributeStorage(hu); return ImmutableAttributeSet.createSubSet(attributes, a -> attributesToConsider.contains(AttributeCode.ofString(a.getValue()))); } public LocatorId getLocatorIdByHuId(final HuId huId) { final I_M_HU hu = getHUById(huId); return IHandlingUnitsBL.extractLocatorId(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\HUsLoadingCache.java
1
请完成以下Java代码
public GroupQuery orderByGroupId() { return orderBy(GroupQueryProperty.GROUP_ID); } @Override public GroupQuery orderByGroupName() { return orderBy(GroupQueryProperty.NAME); } @Override public GroupQuery orderByGroupType() { return orderBy(GroupQueryProperty.TYPE); } // results //////////////////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getGroupEntityManager(commandContext).findGroupCountByQueryCriteria(this); } @Override public List<Group> executeList(CommandContext commandContext) { return CommandContextUtil.getGroupEntityManager(commandContext).findGroupByQueryCriteria(this); } // getters //////////////////////////////////////////////////////// @Override public String getId() { return id; } public List<String> getIds() { return ids; } public String getName() { return name; }
public String getNameLike() { return nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getType() { return type; } public String getUserId() { return userId; } public List<String> getUserIds() { return userIds; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\GroupQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } /** * SwaggerUI information */ @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .deepLinking(true) .displayOperationId(false) .defaultModelsExpandDepth(1) .defaultModelExpandDepth(1)
.defaultModelRendering(ModelRendering.EXAMPLE) .displayRequestDuration(false) .docExpansion(DocExpansion.NONE) .filter(false) .maxDisplayedTags(null) .operationsSorter(OperationsSorter.ALPHA) .showExtensions(false) .tagsSorter(TagsSorter.ALPHA) .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) .validatorUrl(null) .build(); } @Bean public EmailAnnotationPlugin emailPlugin() { return new EmailAnnotationPlugin(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-legacy\src\main\java\com\baeldung\swagger2boot\configuration\SpringFoxConfig.java
2
请完成以下Java代码
public void setMark1Percent (int Mark1Percent) { set_Value (COLUMNNAME_Mark1Percent, Integer.valueOf(Mark1Percent)); } /** Get Mark 1 Percent. @return Percentage up to this color is used */ public int getMark1Percent () { Integer ii = (Integer)get_Value(COLUMNNAME_Mark1Percent); if (ii == null) return 0; return ii.intValue(); } /** Set Mark 2 Percent. @param Mark2Percent Percentage up to this color is used */ public void setMark2Percent (int Mark2Percent) { set_Value (COLUMNNAME_Mark2Percent, Integer.valueOf(Mark2Percent)); } /** Get Mark 2 Percent. @return Percentage up to this color is used */ public int getMark2Percent () { Integer ii = (Integer)get_Value(COLUMNNAME_Mark2Percent); if (ii == null) return 0; return ii.intValue(); } /** Set Mark 3 Percent. @param Mark3Percent Percentage up to this color is used */ public void setMark3Percent (int Mark3Percent) { set_Value (COLUMNNAME_Mark3Percent, Integer.valueOf(Mark3Percent)); } /** Get Mark 3 Percent. @return Percentage up to this color is used */ public int getMark3Percent () { Integer ii = (Integer)get_Value(COLUMNNAME_Mark3Percent); if (ii == null) return 0; return ii.intValue(); } /** Set Mark 4 Percent. @param Mark4Percent Percentage up to this color is used */ public void setMark4Percent (int Mark4Percent) { set_Value (COLUMNNAME_Mark4Percent, Integer.valueOf(Mark4Percent)); } /** Get Mark 4 Percent. @return Percentage up to this color is used */ public int getMark4Percent () { Integer ii = (Integer)get_Value(COLUMNNAME_Mark4Percent); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) {
set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Color Schema. @param PA_ColorSchema_ID Performance Color Schema */ public void setPA_ColorSchema_ID (int PA_ColorSchema_ID) { if (PA_ColorSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, Integer.valueOf(PA_ColorSchema_ID)); } /** Get Color Schema. @return Performance Color Schema */ public int getPA_ColorSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ColorSchema_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ColorSchema.java
1
请完成以下Java代码
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { config = loadNodeConfiguration(ctx, configuration); } @Override public void onMsg(TbContext ctx, TbMsg msg) { withCallback(transform(ctx, msg), m -> transformSuccess(ctx, msg, m), t -> transformFailure(ctx, msg, t), MoreExecutors.directExecutor()); } protected abstract C loadNodeConfiguration(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException; protected void transformFailure(TbContext ctx, TbMsg msg, Throwable t) { ctx.tellFailure(msg, t); } protected void transformSuccess(TbContext ctx, TbMsg msg, List<TbMsg> msgs) { if (msgs == null || msgs.isEmpty()) { ctx.tellFailure(msg, new RuntimeException("Message or messages list are empty!"));
} else if (msgs.size() == 1) { ctx.tellSuccess(msgs.get(0)); } else { TbMsgCallbackWrapper wrapper = new MultipleTbMsgsCallbackWrapper(msgs.size(), new TbMsgCallback() { @Override public void onSuccess() { ctx.ack(msg); } @Override public void onFailure(RuleEngineException e) { ctx.tellFailure(msg, e); } }); msgs.forEach(newMsg -> ctx.enqueueForTellNext(newMsg, TbNodeConnectionType.SUCCESS, wrapper::onSuccess, wrapper::onFailure)); } } protected abstract ListenableFuture<List<TbMsg>> transform(TbContext ctx, TbMsg msg); }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\transform\TbAbstractTransformNode.java
1
请完成以下Java代码
public Map<String, Long> getTableCount() { return commandExecutor.execute(new GetTableCountCmd(configuration.getEngineCfgKey())); } @Override public String getTableName(Class<?> entityClass) { return commandExecutor.execute(new GetTableNameCmd(entityClass)); } @Override public TableMetaData getTableMetaData(String tableName) { return commandExecutor.execute(new GetTableMetaDataCmd(tableName, configuration.getEngineCfgKey())); } @Override public TablePageQuery createTablePageQuery() { return new TablePageQueryImpl(commandExecutor, configuration); }
public <MapperType, ResultType> ResultType executeCustomSql(CustomSqlExecution<MapperType, ResultType> customSqlExecution) { Class<MapperType> mapperClass = customSqlExecution.getMapperClass(); return commandExecutor.execute(new ExecuteCustomSqlCmd<>(mapperClass, customSqlExecution)); } @Override public ChangeTenantIdBuilder createChangeTenantIdBuilder(String fromTenantId, String toTenantId) { return new ChangeTenantIdBuilderImpl(fromTenantId, toTenantId, configuration.getChangeTenantIdManager()); } @Override public LockManager getLockManager(String lockName) { return new LockManagerImpl(commandExecutor, lockName, getConfiguration().getLockPollRate(), configuration.getEngineCfgKey()); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnManagementServiceImpl.java
1
请完成以下Java代码
private Optional<I_M_HU_LUTU_Configuration> getM_HU_LUTU_Configuration() { //noinspection OptionalAssignedToNull if (_lutuConfiguration == null) { _lutuConfiguration = retrieveM_HU_LUTU_Configuration(); } return _lutuConfiguration; } private Optional<I_M_HU_LUTU_Configuration> retrieveM_HU_LUTU_Configuration() { final I_M_ShipmentSchedule shipmentSchedule = getM_ShipmentSchedule().orElse(null); if (shipmentSchedule == null) { return Optional.empty(); } final I_M_HU_LUTU_Configuration lutuConfiguration = huShipmentScheduleBL.deriveM_HU_LUTU_Configuration(shipmentSchedule); if (lutuConfiguration == null) // shall not happen { logger.warn("No LU/TU configuration found for {}", shipmentSchedule); return Optional.empty(); } if (lutuConfigurationFactory.isNoLU(lutuConfiguration)) { logger.warn("No LU PI found for {}", shipmentSchedule); return Optional.empty();
} return Optional.of(lutuConfiguration); } @Nullable public I_M_HU_PI_Item_Product getTuPIItemProduct() { return getM_HU_LUTU_Configuration() .map(I_M_HU_LUTU_Configuration::getM_HU_PI_Item_Product_ID) .map(id->InterfaceWrapperHelper.load(id, I_M_HU_PI_Item_Product.class)) .orElse(null); } } // Builder }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\sscc18\PrintableDesadvLineSSCC18Labels.java
1
请完成以下Java代码
public class PMM_CreatePurchaseOrders_Action extends ExecutableSideAction { // services private final transient IMsgBL msgBL = Services.get(IMsgBL.class); private final transient IClientUI clientUI = Services.get(IClientUI.class); // messages private static final String MSG_Root = "PMM_PurchaseCandidate.SideActions.CreatePurchaseOrders."; private static final String MSG_DisplayName = MSG_Root + "title"; private static final String MSG_DoYouWantToUpdate_1P = MSG_Root + "DoYouWantToUpdate"; // parameters private final GridTab gridTab; private final int windowNo; private final String displayName; private boolean running = false; public PMM_CreatePurchaseOrders_Action(final GridTab gridTab) { super(); Check.assumeNotNull(gridTab, "gridTab not null"); this.gridTab = gridTab; windowNo = gridTab.getWindowNo(); displayName = msgBL.translate(Env.getCtx(), MSG_DisplayName); } @Override public String getDisplayName() { return displayName; } /** * @return true if this action is currently running */ public final boolean isRunning() { return running; } @Override public void execute() { running = true;
try { execute0(); } finally { running = false; } } private void execute0() { final int countEnqueued = PMM_GenerateOrders.prepareEnqueuing() .filter(gridTab.createCurrentRecordsQueryFilter(I_PMM_PurchaseCandidate.class)) .confirmRecordsToProcess(this::confirmRecordsToProcess) .enqueue(); // // Refresh rows, because they were updated if (countEnqueued > 0) { gridTab.dataRefreshAll(); } // // Inform the user clientUI.info(windowNo, "Updated", "#" + countEnqueued); } private final boolean confirmRecordsToProcess(final int countToProcess) { return clientUI.ask() .setParentWindowNo(windowNo) .setAdditionalMessage(msgBL.getMsg(Env.getCtx(), MSG_DoYouWantToUpdate_1P, new Object[] { countToProcess })) .setDefaultAnswer(false) .getAnswer(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\callout\PMM_CreatePurchaseOrders_Action.java
1
请完成以下Java代码
public CorrelationPropertyBinding newInstance(ModelTypeInstanceContext instanceContext) { return new CorrelationPropertyBindingImpl(instanceContext); } }); correlationPropertyRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_CORRELATION_PROPERTY_REF) .required() .qNameAttributeReference(CorrelationProperty.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); dataPathChild = sequenceBuilder.element(DataPath.class) .required() .build(); typeBuilder.build(); } public CorrelationPropertyBindingImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext); } public CorrelationProperty getCorrelationProperty() { return correlationPropertyRefAttribute.getReferenceTargetElement(this); } public void setCorrelationProperty(CorrelationProperty correlationProperty) { correlationPropertyRefAttribute.setReferenceTargetElement(this, correlationProperty); } public DataPath getDataPath() { return dataPathChild.getChild(this); } public void setDataPath(DataPath dataPath) { dataPathChild.setChild(this, dataPath); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CorrelationPropertyBindingImpl.java
1
请完成以下Java代码
public class UseFoo { private String value = "Enclosing scope value"; public String add(final String string, final Foo foo) { return foo.method(string); } public String addWithStandardFI(final String string, final Function<String, String> fn) { return fn.apply(string); } public String scopeExperiment() { final Foo fooIC = new Foo() { String value = "Inner class value";
@Override public String method(final String string) { return value; } }; final String resultIC = fooIC.method(""); final Foo fooLambda = parameter -> { final String value = "Lambda value"; return this.value; }; final String resultLambda = fooLambda.method(""); return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda; } }
repos\tutorials-master\core-java-modules\core-java-lambdas\src\main\java\com\baeldung\java8\lambda\tips\UseFoo.java
1
请完成以下Java代码
public int getHUPIProductItemId() { final HUPIItemProductId packingInstructions = olCandEffectiveValuesBL.getEffectivePackingInstructions(olCandRecord); return HUPIItemProductId.toRepoId(packingInstructions); } public InvoicableQtyBasedOn getInvoicableQtyBasedOn() { return InvoicableQtyBasedOn.ofNullableCodeOrNominal(olCandRecord.getInvoicableQtyBasedOn()); } public BPartnerInfo getBPartnerInfo() { return bpartnerInfo; }
public boolean isAssignToBatch(@NonNull final AsyncBatchId asyncBatchIdCandidate) { if (this.asyncBatchId == null) { return false; } return asyncBatchId.getRepoId() == asyncBatchIdCandidate.getRepoId(); } public void setHeaderAggregationKey(@NonNull final String headerAggregationKey) { olCandRecord.setHeaderAggregationKey(headerAggregationKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCand.java
1
请在Spring Boot框架中完成以下Java代码
public class ServletEncodingProperties { /** * Default HTTP encoding for Servlet applications. */ public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; /** * Charset of HTTP requests and responses. Added to the "Content-Type" header if not * set explicitly. */ private Charset charset = DEFAULT_CHARSET; /** * Whether to force the encoding to the configured charset on HTTP requests and * responses. */ private @Nullable Boolean force; /** * Whether to force the encoding to the configured charset on HTTP requests. Defaults * to true when "force" has not been specified. */ private @Nullable Boolean forceRequest; /** * Whether to force the encoding to the configured charset on HTTP responses. */ private @Nullable Boolean forceResponse; public Charset getCharset() { return this.charset; } public void setCharset(Charset charset) { this.charset = charset; } public boolean isForce() { return Boolean.TRUE.equals(this.force); } public void setForce(boolean force) { this.force = force; } public boolean isForceRequest() { return Boolean.TRUE.equals(this.forceRequest); } public void setForceRequest(boolean forceRequest) { this.forceRequest = forceRequest;
} public boolean isForceResponse() { return Boolean.TRUE.equals(this.forceResponse); } public void setForceResponse(boolean forceResponse) { this.forceResponse = forceResponse; } public boolean shouldForce(HttpMessageType type) { Boolean force = (type != HttpMessageType.REQUEST) ? this.forceResponse : this.forceRequest; if (force == null) { force = this.force; } if (force == null) { force = (type == HttpMessageType.REQUEST); } return force; } /** * Type of HTTP message to consider for encoding configuration. */ public enum HttpMessageType { /** * HTTP request message. */ REQUEST, /** * HTTP response message. */ RESPONSE } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\ServletEncodingProperties.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; }
public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getUsersAccess() { return usersAccess; } public void setUsersAccess(String usersAccess) { this.usersAccess = usersAccess; } public String getGroupsAccess() { return groupsAccess; } public void setGroupsAccess(String groupsAccess) { this.groupsAccess = groupsAccess; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\BaseAppModel.java
1
请在Spring Boot框架中完成以下Java代码
public Object execute(CommandContext commandContext) { JobEntity jobToDelete = getJobToDelete(commandContext); InternalJobCompatibilityManager internalJobCompatibilityManager = jobServiceConfiguration.getInternalJobCompatibilityManager(); if (internalJobCompatibilityManager != null && internalJobCompatibilityManager.isFlowable5Job(jobToDelete)) { internalJobCompatibilityManager.deleteV5Job(jobToDelete.getId()); return null; } sendCancelEvent(jobToDelete); jobServiceConfiguration.getJobEntityManager().delete(jobToDelete); return null; } protected void sendCancelEvent(JobEntity jobToDelete) { FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete), jobServiceConfiguration.getEngineName()); } } protected JobEntity getJobToDelete(CommandContext commandContext) {
if (jobId == null) { throw new FlowableIllegalArgumentException("jobId is null"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Deleting job {}", jobId); } JobEntity job = jobServiceConfiguration.getJobEntityManager().findById(jobId); if (job == null) { throw new FlowableObjectNotFoundException("No job found with id '" + jobId + "'", Job.class); } // We need to check if the job was locked, ie acquired by the job acquisition thread // This happens if the job was already acquired, but not yet executed. // In that case, we can't allow to delete the job. if (job.getLockOwner() != null) { throw new FlowableException("Cannot delete " + job + " when the job is being executed. Try again later."); } return job; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteJobCmd.java
2
请完成以下Java代码
public int getColumnWidth(final String columnName) { final Cell cell = getCell(columnName); return cell.getWidth(); } public String getCellValue(@NonNull final String columnName) { final Cell cell = getCell(columnName); return cell.getAsString(); } public void put(@NonNull final String columnName, @NonNull final Cell value) { map.put(columnName, value); }
public void put(@NonNull final String columnName, @Nullable final Object valueObj) { map.put(columnName, Cell.ofNullable(valueObj)); } public void putAll(@NonNull final Map<String, ?> map) { map.forEach((columnName, value) -> this.map.put(columnName, Cell.ofNullable(value))); } public boolean containsColumn(final String columnName) { return map.containsKey(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Row.java
1
请完成以下Java代码
public int getM_CostType_ID() { return get_ValueAsInt(COLUMNNAME_M_CostType_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 setPeriod_OpenFuture (final int Period_OpenFuture) { set_Value (COLUMNNAME_Period_OpenFuture, Period_OpenFuture); } @Override public int getPeriod_OpenFuture() { return get_ValueAsInt(COLUMNNAME_Period_OpenFuture); } @Override public void setPeriod_OpenHistory (final int Period_OpenHistory) { set_Value (COLUMNNAME_Period_OpenHistory, Period_OpenHistory); } @Override public int getPeriod_OpenHistory() { return get_ValueAsInt(COLUMNNAME_Period_OpenHistory); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override
public void setSeparator (final java.lang.String Separator) { set_Value (COLUMNNAME_Separator, Separator); } @Override public java.lang.String getSeparator() { return get_ValueAsString(COLUMNNAME_Separator); } /** * TaxCorrectionType AD_Reference_ID=392 * Reference name: C_AcctSchema TaxCorrectionType */ public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392; /** None = N */ public static final String TAXCORRECTIONTYPE_None = "N"; /** Write_OffOnly = W */ public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W"; /** DiscountOnly = D */ public static final String TAXCORRECTIONTYPE_DiscountOnly = "D"; /** Write_OffAndDiscount = B */ public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B"; @Override public void setTaxCorrectionType (final java.lang.String TaxCorrectionType) { set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType); } @Override public java.lang.String getTaxCorrectionType() { return get_ValueAsString(COLUMNNAME_TaxCorrectionType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } public org.eevolution.model.I_HR_Job getNext_Job() throws RuntimeException { return (org.eevolution.model.I_HR_Job)MTable.get(getCtx(), org.eevolution.model.I_HR_Job.Table_Name) .getPO(getNext_Job_ID(), get_TrxName()); } /** Set Next Job. @param Next_Job_ID Next Job */ public void setNext_Job_ID (int Next_Job_ID) { if (Next_Job_ID < 1) set_Value (COLUMNNAME_Next_Job_ID, null); else set_Value (COLUMNNAME_Next_Job_ID, Integer.valueOf(Next_Job_ID)); } /** Get Next Job. @return Next Job */ public int getNext_Job_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Next_Job_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Job.java
1
请完成以下Java代码
public void addFocusListener (FocusListener l) { if (m_textPane == null) // during init super.addFocusListener(l); else m_textPane.addFocusListener(l); } /** * Add Mouse Listener * @param l listner */ @Override public void addMouseListener (MouseListener l) { m_textPane.addMouseListener(l); } /** * Add Key Listener * @param l listner */ @Override public void addKeyListener (KeyListener l) { m_textPane.addKeyListener(l); } /** * Add Input Method Listener * @param l listener */ @Override public void addInputMethodListener (InputMethodListener l) { m_textPane.addInputMethodListener(l); } /** * Get Input Method Requests * @return requests */ @Override public InputMethodRequests getInputMethodRequests() { return m_textPane.getInputMethodRequests(); } /** * Set Input Verifier * @param l verifyer */ @Override public void setInputVerifier (InputVerifier l) { m_textPane.setInputVerifier(l); } // metas: begin public String getContentType() { if (m_textPane != null) return m_textPane.getContentType(); return null; } private void setHyperlinkListener() { if (hyperlinkListenerClass == null) { return;
} try { final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance(); m_textPane.addHyperlinkListener(listener); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e); } } private static Class<?> hyperlinkListenerClass; static { final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler"; try { hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e); } } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } // metas: end } // CTextPane
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java
1
请完成以下Java代码
public BigDecimal getTotalQtyAvailable() { return list.stream() .map(ShipmentScheduleAvailableStockDetail::getQtyAvailable) .reduce(BigDecimal.ZERO, BigDecimal::add); } public boolean isEmpty() { return list.isEmpty(); } public int size() { return list.size(); }
public BigDecimal getQtyAvailable(final int storageIndex) { return getStorageDetail(storageIndex).getQtyAvailable(); } public void subtractQtyOnHand(final int storageIndex, @NonNull final BigDecimal qtyOnHandToRemove) { getStorageDetail(storageIndex).subtractQtyOnHand(qtyOnHandToRemove); } public ShipmentScheduleAvailableStockDetail getStorageDetail(final int storageIndex) { return list.get(storageIndex); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentScheduleAvailableStock.java
1
请在Spring Boot框架中完成以下Java代码
public final class InMemoryClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> { private final Map<String, ClientRegistration> registrations; /** * Constructs an {@code InMemoryClientRegistrationRepository} using the provided * parameters. * @param registrations the client registration(s) */ public InMemoryClientRegistrationRepository(ClientRegistration... registrations) { this(Arrays.asList(registrations)); } /** * Constructs an {@code InMemoryClientRegistrationRepository} using the provided * parameters. * @param registrations the client registration(s) */ public InMemoryClientRegistrationRepository(List<ClientRegistration> registrations) { this(createRegistrationsMap(registrations)); } private static Map<String, ClientRegistration> createRegistrationsMap(List<ClientRegistration> registrations) { Assert.notEmpty(registrations, "registrations cannot be empty"); return toUnmodifiableConcurrentMap(registrations); } private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) { ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>(); for (ClientRegistration registration : registrations) { Assert.state(!result.containsKey(registration.getRegistrationId()), () -> String.format("Duplicate key %s", registration.getRegistrationId())); result.put(registration.getRegistrationId(), registration); } return Collections.unmodifiableMap(result); }
/** * Constructs an {@code InMemoryClientRegistrationRepository} using the provided * {@code Map} of {@link ClientRegistration#getRegistrationId() registration id} to * {@link ClientRegistration}. * @param registrations the {@code Map} of client registration(s) * @since 5.2 */ public InMemoryClientRegistrationRepository(Map<String, ClientRegistration> registrations) { Assert.notNull(registrations, "registrations cannot be null"); this.registrations = registrations; } @Override public ClientRegistration findByRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return this.registrations.get(registrationId); } /** * Returns an {@code Iterator} of {@link ClientRegistration}. * @return an {@code Iterator<ClientRegistration>} */ @Override public Iterator<ClientRegistration> iterator() { return this.registrations.values().iterator(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\registration\InMemoryClientRegistrationRepository.java
2
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (handleExcludeURL(req, resp)) { chain.doFilter(request, response); return; } XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(xssRequest, response); } private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { if (!enabled) { return true; } if (excludes == null || excludes.isEmpty()) {
return false; } String url = request.getServletPath(); for (String pattern : excludes) { Pattern p = Pattern.compile("^" + pattern); Matcher m = p.matcher(url); if (m.find()) { return true; } } return false; } @Override public void destroy() { } }
repos\springboot-demo-master\xss\src\main\java\com\et\filter\XssFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hilopooledlo") @GenericGenerator(name = "hilopooledlo", strategy = "com.bookstore.generator.id.StringPrefixedSequenceIdGenerator", parameters = { @Parameter(name = CustomSequenceIdGenerator.SEQUENCE_PARAM, value = "hilo_sequence"), @Parameter(name = CustomSequenceIdGenerator.INITIAL_PARAM, value = "1"), @Parameter(name = CustomSequenceIdGenerator.OPT_PARAM, value = "pooled-lo"), @Parameter(name = CustomSequenceIdGenerator.INCREMENT_PARAM, value = "100"), @Parameter(name = CustomSequenceIdGenerator.PREFIX_PARAM, value = "A-"), @Parameter(name = CustomSequenceIdGenerator.NUMBER_FORMAT_PARAM, value = "%010d") } ) private String id; private String name; public String getId() {
return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCustomSequenceGenerator\src\main\java\com\bookstore\entity\Author.java
2
请在Spring Boot框架中完成以下Java代码
public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } public boolean isUnassigned() { return unassigned; } public boolean isNoDelegationState() { return noDelegationState; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionKeyLike() { return caseDefinitionKeyLike; } public String getCaseDefinitionKeyLikeIgnoreCase() { return caseDefinitionKeyLikeIgnoreCase; } public Collection<String> getCaseDefinitionKeys() { return caseDefinitionKeys; } public boolean isExcludeSubtasks() { return excludeSubtasks; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } @Override public List<Task> list() { cachedCandidateGroups = null; return super.list(); } @Override public List<Task> listPage(int firstResult, int maxResults) { cachedCandidateGroups = null; return super.listPage(firstResult, maxResults);
} @Override public long count() { cachedCandidateGroups = null; return super.count(); } public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups; } public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java
2
请完成以下Java代码
public DhlCustomDeliveryDataDetail getDetailByPackageId(final PackageId packageId) { //noinspection OptionalGetWithoutIsPresent return details.stream() .filter(it -> Objects.equals(it.getPackageId(), packageId)) .findFirst() .get(); } @NonNull public DhlCustomDeliveryDataDetail getDetailBySequenceNumber(@NonNull final DhlSequenceNumber sequenceNumber) { //noinspection OptionalGetWithoutIsPresent return details.stream() .filter(it -> it.getSequenceNumber().equals(sequenceNumber)) .findFirst()
.get(); } @NonNull public DhlCustomDeliveryData withDhlCustomDeliveryDataDetails(@Nullable final ImmutableList<DhlCustomDeliveryDataDetail> details) { if (details == null) { return this; } return toBuilder() .clearDetails() .details(details) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\model\DhlCustomDeliveryData.java
1
请完成以下Java代码
public static final PickingSlotRowId fromStringPartsList(final List<String> parts) { final int partsCount = parts.size(); if (partsCount < 1) { throw new IllegalArgumentException("Invalid id: " + parts); } final PickingSlotId pickingSlotId = !Check.isEmpty(parts.get(0), true) ? PickingSlotId.ofRepoIdOrNull(Integer.parseInt(parts.get(0))) : null; final HuId huId = partsCount >= 2 ? HuId.ofRepoIdOrNull(Integer.parseInt(parts.get(1))) : null; final int huStorageProductId = partsCount >= 3 ? Integer.parseInt(parts.get(2)) : 0; return new PickingSlotRowId(pickingSlotId, huId, huStorageProductId); } @Getter private final PickingSlotId pickingSlotId; @Getter private final HuId huId; @Getter private final int huStorageProductId; private transient DocumentId _documentId; // lazy private static final String SEPARATOR = "-"; private static final Joiner DOCUMENT_ID_JOINER = Joiner.on(SEPARATOR).skipNulls(); private static final Splitter DOCUMENT_ID_SPLITTER = Splitter.on(SEPARATOR); @Builder private PickingSlotRowId(final PickingSlotId pickingSlotId, final HuId huId, final int huStorageProductId) { this.pickingSlotId = pickingSlotId; this.huId = huId; this.huStorageProductId = huStorageProductId > 0 ? huStorageProductId : 0; } @Override public String toString() { return toDocumentId().toJson(); } public DocumentId toDocumentId() { DocumentId id = _documentId; if (id == null) {
final String idStr = DOCUMENT_ID_JOINER.join( pickingSlotId != null ? pickingSlotId.getRepoId() : 0, huId != null ? huId.getRepoId() : null, huStorageProductId > 0 ? huStorageProductId : null); id = _documentId = DocumentId.ofString(idStr); } return id; } /** @return {@code true} if this row ID represents an actual picking slot and not any sort of HU that is also shown in this view. */ public boolean isPickingSlotRow() { return getPickingSlotId() != null && getHuId() == null; } /** @return {@code true} is this row ID represents an HU that is assigned to a picking slot */ public boolean isPickedHURow() { return getPickingSlotId() != null && getHuId() != null; } /** @return {@code true} if this row ID represents an HU that is a source-HU for fine-picking. */ public boolean isPickingSourceHURow() { return getPickingSlotId() == null && getHuId() != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRowId.java
1
请完成以下Java代码
protected DmnDecisionTableResult doEvaluateDecision(DecisionDefinition decisionDefinition, VariableMap variables) { try { return evaluateDecisionTable(decisionDefinition, variables); } catch (Exception e) { throw new ProcessEngineException("Exception while evaluating decision with key '"+decisionDefinitionKey+"'", e); } } protected DecisionDefinition getDecisionDefinition(CommandContext commandContext) { DeploymentCache deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentCache(); if (decisionDefinitionId != null) { return findById(deploymentCache); } else { return findByKey(deploymentCache); } } protected DecisionDefinition findById(DeploymentCache deploymentCache) { return deploymentCache.findDeployedDecisionDefinitionById(decisionDefinitionId); } protected DecisionDefinition findByKey(DeploymentCache deploymentCache) { DecisionDefinition decisionDefinition = null;
if (version == null && !isTenandIdSet) { decisionDefinition = deploymentCache.findDeployedLatestDecisionDefinitionByKey(decisionDefinitionKey); } else if (version == null && isTenandIdSet) { decisionDefinition = deploymentCache.findDeployedLatestDecisionDefinitionByKeyAndTenantId(decisionDefinitionKey, decisionDefinitionTenantId); } else if (version != null && !isTenandIdSet) { decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByKeyAndVersion(decisionDefinitionKey, version); } else if (version != null && isTenandIdSet) { decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByKeyVersionAndTenantId(decisionDefinitionKey, version, decisionDefinitionTenantId); } return decisionDefinition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\cmd\EvaluateDecisionTableCmd.java
1
请完成以下Java代码
protected boolean isNukeAndPaveEnabled() { return getEnvironment() .map(env -> env.getProperty(NUKE_AND_PAVE_PROPERTY, Boolean.class)) .orElse(Boolean.getBoolean(NUKE_AND_PAVE_PROPERTY)); } @Override public void setEnvironment(@Nullable Environment environment) { this.environment = environment; } protected Optional<Environment> getEnvironment() { return Optional.ofNullable(this.environment); } public @NonNull CrudRepository<T, ID> getRepository() { return this.repository; } protected <S, R> R doRepositoryOp(S entity, Function<S, R> repositoryOperation) { try { return repositoryOperation.apply(entity); } catch (Throwable cause) { throw newCacheRuntimeException(() -> String.format(DATA_ACCESS_ERROR, entity), cause); } } @Override
public T load(LoaderHelper<ID, T> helper) throws CacheLoaderException { return null; } protected abstract CacheRuntimeException newCacheRuntimeException( Supplier<String> messageSupplier, Throwable cause); @SuppressWarnings("unchecked") public <U extends RepositoryCacheLoaderWriterSupport<T, ID>> U with(Environment environment) { setEnvironment(environment); return (U) this; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\support\RepositoryCacheLoaderWriterSupport.java
1
请完成以下Java代码
public CaseExecutionEntity findCaseExecutionById(String caseExecutionId) { return getDbEntityManager().selectById(CaseExecutionEntity.class, caseExecutionId); } public CaseExecutionEntity findSubCaseInstanceBySuperCaseExecutionId(String superCaseExecutionId) { return (CaseExecutionEntity) getDbEntityManager().selectOne("selectSubCaseInstanceBySuperCaseExecutionId", superCaseExecutionId); } public CaseExecutionEntity findSubCaseInstanceBySuperExecutionId(String superExecutionId) { return (CaseExecutionEntity) getDbEntityManager().selectOne("selectSubCaseInstanceBySuperExecutionId", superExecutionId); } public long findCaseExecutionCountByQueryCriteria(CaseExecutionQueryImpl caseExecutionQuery) { configureTenantCheck(caseExecutionQuery); return (Long) getDbEntityManager().selectOne("selectCaseExecutionCountByQueryCriteria", caseExecutionQuery); } @SuppressWarnings("unchecked") public List<CaseExecution> findCaseExecutionsByQueryCriteria(CaseExecutionQueryImpl caseExecutionQuery, Page page) { configureTenantCheck(caseExecutionQuery); return getDbEntityManager().selectList("selectCaseExecutionsByQueryCriteria", caseExecutionQuery, page); } public long findCaseInstanceCountByQueryCriteria(CaseInstanceQueryImpl caseInstanceQuery) { configureTenantCheck(caseInstanceQuery); return (Long) getDbEntityManager().selectOne("selectCaseInstanceCountByQueryCriteria", caseInstanceQuery); } @SuppressWarnings("unchecked") public List<CaseInstance> findCaseInstanceByQueryCriteria(CaseInstanceQueryImpl caseInstanceQuery, Page page) { configureTenantCheck(caseInstanceQuery); return getDbEntityManager().selectList("selectCaseInstanceByQueryCriteria", caseInstanceQuery, page); }
@SuppressWarnings("unchecked") public List<CaseExecutionEntity> findChildCaseExecutionsByParentCaseExecutionId(String parentCaseExecutionId) { return getDbEntityManager().selectList("selectCaseExecutionsByParentCaseExecutionId", parentCaseExecutionId); } @SuppressWarnings("unchecked") public List<CaseExecutionEntity> findChildCaseExecutionsByCaseInstanceId(String caseInstanceId) { return getDbEntityManager().selectList("selectCaseExecutionsByCaseInstanceId", caseInstanceId); } protected void configureTenantCheck(AbstractQuery<?, ?> query) { getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionManager.java
1
请完成以下Java代码
private String quoteCsvValue(String valueStr) { return fieldQuote + valueStr.replace(fieldQuote, fieldQuote + fieldQuote) + fieldQuote; } @Override public void close() throws IOException { if (writer == null) { return; } try { writer.flush(); } finally {
if (writer != null) { try { writer.close(); } catch (IOException e) { // shall not happen e.printStackTrace(); // NOPMD by tsa on 3/13/13 1:46 PM } writer = null; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\CSVWriter.java
1
请完成以下Java代码
public static TenderType ofNullableCode(final String code) { return code != null ? ofCode(code) : null; } public static TenderType ofCode(@NonNull final String code) { TenderType type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + TenderType.class + " found for code: " + code); } return type; } private static final ImmutableMap<String, TenderType> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), TenderType::getCode);
public boolean isCash() { return this == Cash; } public boolean isCheck() { return this == Check; } public boolean isCreditCard() { return this == CreditCard; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\TenderType.java
1
请完成以下Java代码
public void setC_Period_ID (int C_Period_ID) { if (C_Period_ID < 1) set_Value (COLUMNNAME_C_Period_ID, null); else set_Value (COLUMNNAME_C_Period_ID, Integer.valueOf(C_Period_ID)); } /** Get Periode. @return Periode des Kalenders */ @Override public int getC_Period_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Period_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_Year getC_Year() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Year_ID, org.compiere.model.I_C_Year.class); } @Override public void setC_Year(org.compiere.model.I_C_Year C_Year) { set_ValueFromPO(COLUMNNAME_C_Year_ID, org.compiere.model.I_C_Year.class, C_Year); } /** Set Jahr. @param C_Year_ID Kalenderjahr */ @Override public void setC_Year_ID (int C_Year_ID) { if (C_Year_ID < 1) set_Value (COLUMNNAME_C_Year_ID, null); else set_Value (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID)); } /** Get Jahr. @return Kalenderjahr */ @Override public int getC_Year_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Belegdatum. @param DateDoc Datum des Belegs */ @Override public void setDateDoc (java.sql.Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Belegdatum. @return Datum des Belegs */ @Override public java.sql.Timestamp getDateDoc () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateDoc);
} /** Set M_Material_Tracking_Report. @param M_Material_Tracking_Report_ID M_Material_Tracking_Report */ @Override public void setM_Material_Tracking_Report_ID (int M_Material_Tracking_Report_ID) { if (M_Material_Tracking_Report_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_ID, Integer.valueOf(M_Material_Tracking_Report_ID)); } /** Get M_Material_Tracking_Report. @return M_Material_Tracking_Report */ @Override public int getM_Material_Tracking_Report_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report.java
1
请完成以下Java代码
public String getTableName() { return I_C_Location.Table_Name; } @Override public String getColumnName() { return I_C_Location.Table_Name + "." + I_C_Location.COLUMNNAME_C_Location_ID; } // getColumnName @Override public String getColumnNameNotFQ() { return I_C_Location.COLUMNNAME_C_Location_ID; } /**
* Return data as sorted Array - not implemented * @param mandatory mandatory * @param onlyValidated only validated * @param onlyActive only active * @param temporary force load for temporary display * @return null */ @Override public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { log.error("not implemented"); return null; } // getArray } // MLocation
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocationLookup.java
1
请完成以下Java代码
public class MSLACriteria extends X_PA_SLA_Criteria { /** * */ private static final long serialVersionUID = -3295590987540402184L; /** * Get MSLACriteria from Cache * @param ctx context * @param PA_SLA_Criteria_ID id * @param trxName transaction * @return MSLACriteria */ public static MSLACriteria get (Properties ctx, int PA_SLA_Criteria_ID, String trxName) { Integer key = new Integer (PA_SLA_Criteria_ID); MSLACriteria retValue = (MSLACriteria) s_cache.get (key); if (retValue != null) return retValue; retValue = new MSLACriteria (ctx, PA_SLA_Criteria_ID, trxName); if (retValue.get_ID () != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer,MSLACriteria> s_cache = new CCache<Integer,MSLACriteria>("PA_SLA_Criteria", 20); /** * Standard Constructor * @param ctx context * @param PA_SLA_Criteria_ID id * @param trxName transaction */ public MSLACriteria (Properties ctx, int PA_SLA_Criteria_ID, String trxName) { super (ctx, PA_SLA_Criteria_ID, trxName); } // MSLACriteria /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MSLACriteria (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MSLACriteria /** * Get Goals of Criteria * @return array of Goals */ public MSLAGoal[] getGoals()
{ String sql = "SELECT * FROM PA_SLA_Goal " + "WHERE PA_SLA_Criteria_ID=?"; ArrayList<MSLAGoal> list = new ArrayList<MSLAGoal>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt.setInt (1, getPA_SLA_Criteria_ID()); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add(new MSLAGoal(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; } MSLAGoal[] retValue = new MSLAGoal[list.size ()]; list.toArray (retValue); return retValue; } // getGoals /** * Create New Instance of SLA Criteria * @return instanciated class * @throws Exception */ public SLACriteria newSLACriteriaInstance() throws Exception { if (getClassname() == null || getClassname().length() == 0) throw new AdempiereSystemError("No SLA Criteria Classname"); try { Class clazz = Class.forName(getClassname()); SLACriteria retValue = (SLACriteria)clazz.newInstance(); return retValue; } catch (Exception e) { throw new AdempiereSystemError("Could not intsnciate SLA Criteria", e); } } // newInstance } // MSLACriteria
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSLACriteria.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @PrePersist private void prePersist() { logger.info("@PrePersist callback ..."); } @PreUpdate private void preUpdate() { logger.info("@PreUpdate callback ..."); } @PreRemove private void preRemove() { logger.info("@PreRemove callback ..."); }
@PostLoad private void postLoad() { logger.info("@PostLoad callback ..."); } @PostPersist private void postPersist() { logger.info("@PostPersist callback ..."); } @PostUpdate private void postUpdate() { logger.info("@PostUpdate callback ..."); } @PostRemove private void postRemove() { logger.info("@PostRemove callback ..."); } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJpaCallbacks\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public String toString() { return (include ? "InSelection-" : "NotInSelection-") + selectionId.getRepoId(); } @Override public boolean accept(final T model) { if (model == null) { return false; } final int id = InterfaceWrapperHelper.getId(model); final boolean isInSelection = POJOLookupMap.get().isInSelection(selectionId, id);
if (include) { return isInSelection; } else // exclude { return !isInSelection; } } public PInstanceId getSelectionId() { return selectionId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\POJOInSelectionQueryFilter.java
1
请完成以下Java代码
public abstract class CoreActivity extends CoreModelElement { private static final long serialVersionUID = 1L; protected IoMapping ioMapping; public CoreActivity(String id) { super(id); } /** searches for the activity recursively */ public CoreActivity findActivity(String activityId) { CoreActivity localActivity = getChildActivity(activityId); if (localActivity!=null) { return localActivity; } for (CoreActivity activity: getActivities()) { CoreActivity nestedActivity = activity.findActivity(activityId); if (nestedActivity!=null) { return nestedActivity; } } return null; } public CoreActivity createActivity() { return createActivity(null); } /** searches for the activity locally */ public abstract CoreActivity getChildActivity(String activityId); public abstract CoreActivity createActivity(String activityId); public abstract List<? extends CoreActivity> getActivities();
public abstract CoreActivityBehavior<? extends BaseDelegateExecution> getActivityBehavior(); public IoMapping getIoMapping() { return ioMapping; } public void setIoMapping(IoMapping ioMapping) { this.ioMapping = ioMapping; } public String toString() { return "Activity("+id+")"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CoreActivity.java
1
请完成以下Java代码
public <T extends I_M_ShipmentSchedule> T getShipmentScheduleOrNull( @Nullable final IDeliveryDayAllocable deliveryDayAllocable, @NonNull final Class<T> modelClass) { if (deliveryDayAllocable == null) { return null; } else if (deliveryDayAllocable instanceof ShipmentScheduleDeliveryDayAllocable) { final ShipmentScheduleDeliveryDayAllocable shipmentScheduleDeliveryDayAllocable = (ShipmentScheduleDeliveryDayAllocable)deliveryDayAllocable; final I_M_ShipmentSchedule shipmentSchedule = shipmentScheduleDeliveryDayAllocable.getM_ShipmentSchedule(); return InterfaceWrapperHelper.create(shipmentSchedule, modelClass); } else { return null; } } @Override public final void updateDeliveryDayInfo(@NonNull final I_M_ShipmentSchedule sched) { // Get Delivery Day Allocation final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class); final IContextAware context = InterfaceWrapperHelper.getContextAware(sched); final IDeliveryDayAllocable deliveryDayAllocable = asDeliveryDayAllocable(sched);
final I_M_DeliveryDay_Alloc deliveryDayAlloc = deliveryDayBL.getCreateDeliveryDayAlloc(context, deliveryDayAllocable); if (deliveryDayAlloc == null) { return; } InterfaceWrapperHelper.save(deliveryDayAlloc); // make sure is saved } @Override public ZonedDateTime getDeliveryDateCurrent(final I_M_ShipmentSchedule sched) { return Services.get(IShipmentScheduleEffectiveBL.class).getDeliveryDate(sched); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\ShipmentScheduleDeliveryDayBL.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getCouponId() { return couponId; } public void setCouponId(Long couponId) { this.couponId = couponId; } public Long getProductCategoryId() { return productCategoryId; } public void setProductCategoryId(Long productCategoryId) { this.productCategoryId = productCategoryId; } public String getProductCategoryName() { return productCategoryName; } public void setProductCategoryName(String productCategoryName) { this.productCategoryName = productCategoryName; } public String getParentCategoryName() { return parentCategoryName; } public void setParentCategoryName(String parentCategoryName) {
this.parentCategoryName = parentCategoryName; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", couponId=").append(couponId); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", productCategoryName=").append(productCategoryName); sb.append(", parentCategoryName=").append(parentCategoryName); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponProductCategoryRelation.java
1
请完成以下Java代码
public class ArrayDistance { public static Long computeMinimumDistance(TreeSet<Long> setA, TreeSet<Long> setB) { Long[] arrayA = setA.toArray(new Long[0]); Long[] arrayB = setB.toArray(new Long[0]); return computeMinimumDistance(arrayA, arrayB); } public static Long computeMinimumDistance(Long[] arrayA, Long[] arrayB) { int aIndex = 0; int bIndex = 0; long min = Math.abs(arrayA[0] - arrayB[0]); while (true) { if (arrayA[aIndex] > arrayB[bIndex]) { bIndex++; } else { aIndex++; } if (aIndex >= arrayA.length || bIndex >= arrayB.length) { break; } if (Math.abs(arrayA[aIndex] - arrayB[bIndex]) < min)
{ min = Math.abs(arrayA[aIndex] - arrayB[bIndex]); } } return min; } public static Long computeAverageDistance(Long[] arrayA, Long[] arrayB) { Long totalA = 0L; Long totalB = 0L; for (Long a : arrayA) totalA += a; for (Long b : arrayB) totalB += b; return Math.abs(totalA / arrayA.length - totalB / arrayB.length); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ArrayDistance.java
1
请在Spring Boot框架中完成以下Java代码
public void delCaches(Long id){ List<User> users = userRepository.findByMenuId(id); redisUtils.del(CacheKey.MENU_ID + id); redisUtils.delByKeys(CacheKey.MENU_USER, users.stream().map(User::getId).collect(Collectors.toSet())); // 清除 Role 缓存 List<Role> roles = roleService.findInMenuId(new ArrayList<Long>(){{ add(id); }}); redisUtils.delByKeys(CacheKey.ROLE_ID, roles.stream().map(Role::getId).collect(Collectors.toSet())); } /** * 构建前端路由 * @param menuDTO / * @param menuVo / * @return /
*/ private static MenuVo getMenuVo(MenuDto menuDTO, MenuVo menuVo) { MenuVo menuVo1 = new MenuVo(); menuVo1.setMeta(menuVo.getMeta()); // 非外链 if(!menuDTO.getIFrame()){ menuVo1.setPath("index"); menuVo1.setName(menuVo.getName()); menuVo1.setComponent(menuVo.getComponent()); } else { menuVo1.setPath(menuDTO.getPath()); } return menuVo1; } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\MenuServiceImpl.java
2
请完成以下Java代码
public void setIsSmtpAuthorization (final boolean IsSmtpAuthorization) { set_Value (COLUMNNAME_IsSmtpAuthorization, IsSmtpAuthorization); } @Override public boolean isSmtpAuthorization() { return get_ValueAsBoolean(COLUMNNAME_IsSmtpAuthorization); } @Override public void setIsStartTLS (final boolean IsStartTLS) { set_Value (COLUMNNAME_IsStartTLS, IsStartTLS); } @Override public boolean isStartTLS() { return get_ValueAsBoolean(COLUMNNAME_IsStartTLS); } @Override public void setMSGRAPH_ClientId (final @Nullable java.lang.String MSGRAPH_ClientId) { set_Value (COLUMNNAME_MSGRAPH_ClientId, MSGRAPH_ClientId); } @Override public java.lang.String getMSGRAPH_ClientId() { return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientId); } @Override public void setMSGRAPH_ClientSecret (final @Nullable java.lang.String MSGRAPH_ClientSecret) { set_Value (COLUMNNAME_MSGRAPH_ClientSecret, MSGRAPH_ClientSecret); } @Override public java.lang.String getMSGRAPH_ClientSecret() { return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientSecret); } @Override public void setMSGRAPH_TenantId (final @Nullable java.lang.String MSGRAPH_TenantId) { set_Value (COLUMNNAME_MSGRAPH_TenantId, MSGRAPH_TenantId); } @Override public java.lang.String getMSGRAPH_TenantId() { return get_ValueAsString(COLUMNNAME_MSGRAPH_TenantId); } @Override public void setPassword (final @Nullable java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } @Override public java.lang.String getPassword() { return get_ValueAsString(COLUMNNAME_Password); }
@Override public void setSMTPHost (final @Nullable java.lang.String SMTPHost) { set_Value (COLUMNNAME_SMTPHost, SMTPHost); } @Override public java.lang.String getSMTPHost() { return get_ValueAsString(COLUMNNAME_SMTPHost); } @Override public void setSMTPPort (final int SMTPPort) { set_Value (COLUMNNAME_SMTPPort, SMTPPort); } @Override public int getSMTPPort() { return get_ValueAsInt(COLUMNNAME_SMTPPort); } /** * Type AD_Reference_ID=541904 * Reference name: AD_MailBox_Type */ public static final int TYPE_AD_Reference_ID=541904; /** SMTP = smtp */ public static final String TYPE_SMTP = "smtp"; /** MSGraph = msgraph */ public static final String TYPE_MSGraph = "msgraph"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java
1
请完成以下Java代码
public class ThingsboardErrorResponse { // HTTP Response Status Code private final HttpStatus status; // General Error message private final String message; // Error code private final ThingsboardErrorCode errorCode; private final long timestamp; protected ThingsboardErrorResponse(final String message, final ThingsboardErrorCode errorCode, HttpStatus status) { this.message = message; this.errorCode = errorCode; this.status = status; this.timestamp = System.currentTimeMillis(); } public static ThingsboardErrorResponse of(final String message, final ThingsboardErrorCode errorCode, HttpStatus status) { return new ThingsboardErrorResponse(message, errorCode, status); } @Schema(description = "HTTP Response Status Code", example = "401", accessMode = Schema.AccessMode.READ_ONLY) public Integer getStatus() { return status.value(); } @Schema(description = "Error message", example = "Authentication failed", accessMode = Schema.AccessMode.READ_ONLY) public String getMessage() { return message; } @Schema(description = "Platform error code:" + "\n* `2` - General error (HTTP: 500 - Internal Server Error)" +
"\n\n* `10` - Authentication failed (HTTP: 401 - Unauthorized)" + "\n\n* `11` - JWT token expired (HTTP: 401 - Unauthorized)" + "\n\n* `15` - Credentials expired (HTTP: 401 - Unauthorized)" + "\n\n* `20` - Permission denied (HTTP: 403 - Forbidden)" + "\n\n* `30` - Invalid arguments (HTTP: 400 - Bad Request)" + "\n\n* `31` - Bad request params (HTTP: 400 - Bad Request)" + "\n\n* `32` - Item not found (HTTP: 404 - Not Found)" + "\n\n* `33` - Too many requests (HTTP: 429 - Too Many Requests)" + "\n\n* `34` - Too many updates (Too many updates over Websocket session)" + "\n\n* `40` - Subscription violation (HTTP: 403 - Forbidden)" + "\n\n* `41` - Entities limit exceeded (HTTP: 403 - Forbidden)", example = "10", type = "integer", accessMode = Schema.AccessMode.READ_ONLY) public ThingsboardErrorCode getErrorCode() { return errorCode; } @Schema(description = "Timestamp", accessMode = Schema.AccessMode.READ_ONLY) public long getTimestamp() { return timestamp; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\exception\ThingsboardErrorResponse.java
1
请完成以下Java代码
public final class SanitizableData { /** * Represents a sanitized value. */ public static final String SANITIZED_VALUE = "******"; private final @Nullable PropertySource<?> propertySource; private final String key; private @Nullable String lowerCaseKey; private final @Nullable Object value; /** * Create a new {@link SanitizableData} instance. * @param propertySource the property source that provided the data or {@code null}. * @param key the data key * @param value the data value */ public SanitizableData(@Nullable PropertySource<?> propertySource, String key, @Nullable Object value) { Assert.notNull(key, "'key' must not be null"); this.propertySource = propertySource; this.key = key; this.value = value; } /** * Return the property source that provided the data or {@code null} If the data was * not from a {@link PropertySource}. * @return the property source that provided the data */ public @Nullable PropertySource<?> getPropertySource() { return this.propertySource; } /** * Return the key of the data. * @return the data key */ public String getKey() { return this.key; } /** * Return the key as a lowercase value. * @return the key as a lowercase value * @since 3.5.0 */ public String getLowerCaseKey() { String result = this.lowerCaseKey;
if (result == null) { result = this.key.toLowerCase(Locale.getDefault()); this.lowerCaseKey = result; } return result; } /** * Return the value of the data. * @return the data value */ public @Nullable Object getValue() { return this.value; } /** * Return a new {@link SanitizableData} instance with sanitized value. * @return a new sanitizable data instance. * @since 3.1.0 */ public SanitizableData withSanitizedValue() { return withValue(SANITIZED_VALUE); } /** * Return a new {@link SanitizableData} instance with a different value. * @param value the new value (often {@link #SANITIZED_VALUE} * @return a new sanitizable data instance */ public SanitizableData withValue(@Nullable Object value) { return new SanitizableData(this.propertySource, this.key, value); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\SanitizableData.java
1
请完成以下Java代码
protected final BigDecimal toBigDecimalOrZero(final Object valueObj) { if (valueObj == null) { return BigDecimal.ZERO; } else if (valueObj instanceof BigDecimal) { return (BigDecimal)valueObj; } else { try { return new BigDecimal(valueObj.toString()); } catch (Exception e) { logger.warn("Failed converting " + valueObj + " (class " + valueObj.getClass() + ")" + " to BigDecimal. Returning ZERO.", e); } return BigDecimal.ZERO; } } protected final boolean setRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Object value) { final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return false; } if (columnIndex >= row.size()) { return false; } row.set(columnIndex, value); return true; } protected final Object getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName) { if (row == null) { return null; } final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return null; } if (columnIndex >= row.size()) { return null; } final Object value = row.get(columnIndex);
return value; } protected final <T> T getRowValueOrNull(final IRModelMetadata metadata, final List<Object> row, final String columnName, final Class<T> valueClass) { final Object valueObj = getRowValueOrNull(metadata, row, columnName); if (valueObj == null) { return null; } if (!valueClass.isAssignableFrom(valueObj.getClass())) { return null; } final T value = valueClass.cast(valueObj); return value; } /** * * @param calculationCtx * @param columnName * @return true if the status of current calculation is about calculating the row for "columnName" group (subtotals) */ protected final boolean isGroupBy(final RModelCalculationContext calculationCtx, final String columnName) { final int groupColumnIndex = calculationCtx.getGroupColumnIndex(); if (groupColumnIndex < 0) { // no grouping return false; } final IRModelMetadata metadata = calculationCtx.getMetadata(); final int columnIndex = metadata.getRColumnIndex(columnName); if (columnIndex < 0) { return false; } return columnIndex == groupColumnIndex; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\AbstractRModelAggregatedValue.java
1
请完成以下Java代码
public static int toRepoIdOrAny(@Nullable final OrgId orgId) { return orgId != null ? orgId.getRepoId() : ANY.repoId; } @Override @JsonValue public int getRepoId() { return repoId; } public boolean isAny() { return repoId == Env.CTXVALUE_AD_Org_ID_Any; } /** * @return {@code true} if the org in question is not {@code *} (i.e. "ANY"), but a specific organisation's ID */ public boolean isRegular() { return !isAny(); } public void ifRegular(@NonNull final Consumer<OrgId> consumer)
{ if (isRegular()) { consumer.accept(this); } } @Nullable public OrgId asRegularOrNull() {return isRegular() ? this : null;} public static boolean equals(@Nullable final OrgId id1, @Nullable final OrgId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgId.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isNameStartsWith(@NonNull final String prefix) { if (Check.isBlank(prefix)) { throw new AdempiereException("Blank prefix is not allowed"); } return name.startsWith(prefix); } public boolean isClientAndOrgMatching(@NonNull final ClientAndOrgId clientAndOrgId) { for (ClientAndOrgId currentClientAndOrgId = clientAndOrgId; currentClientAndOrgId != null; currentClientAndOrgId = getFallbackClientAndOrgId(currentClientAndOrgId)) { if (entryValues.containsKey(currentClientAndOrgId)) { return true; } } return false; } @Nullable private ClientAndOrgId getFallbackClientAndOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { if (!clientAndOrgId.getOrgId().isAny()) { return clientAndOrgId.withAnyOrgId(); } else if (!clientAndOrgId.getClientId().isSystem()) { return clientAndOrgId.withSystemClientId(); }
else { return null; } } public Optional<String> getValueAsString(@NonNull final ClientAndOrgId clientAndOrgId) { for (ClientAndOrgId currentClientAndOrgId = clientAndOrgId; currentClientAndOrgId != null; currentClientAndOrgId = getFallbackClientAndOrgId(currentClientAndOrgId)) { final SysConfigEntryValue entryValue = entryValues.get(currentClientAndOrgId); if (entryValue != null) { return Optional.of(entryValue.getValue()); } } return Optional.empty(); } // // // ------------------------------- // // public static class SysConfigEntryBuilder { public String getName() { return name; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigEntry.java
2
请完成以下Java代码
public class User { @Expose @SerializedName(value = "firstName", alternate = { "fullName", "name" }) String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } 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; } @Expose int age; @Expose(serialize = true, deserialize = false) public long id; @Expose(serialize = false, deserialize = false) private String email; public User(String name, int age, String email) { this.name = name; this.age = age; this.email = email; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", id=" + id + ", email='" + email + '\'' + '}'; } }
repos\tutorials-master\json-modules\gson-3\src\main\java\com\baeldung\gson\entities\User.java
1
请完成以下Java代码
public class EndSubscriber<T> implements Subscriber<T> { private final AtomicInteger howMuchMessagesToConsume; private Subscription subscription; public List<T> consumedElements = new LinkedList<>(); public EndSubscriber(Integer howMuchMessagesToConsume) { this.howMuchMessagesToConsume = new AtomicInteger(howMuchMessagesToConsume); } @Override public void onSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(1); } @Override public void onNext(T item) { howMuchMessagesToConsume.decrementAndGet(); System.out.println("Got : " + item); consumedElements.add(item);
if (howMuchMessagesToConsume.get() > 0) { subscription.request(1); } } @Override public void onError(Throwable t) { t.printStackTrace(); } @Override public void onComplete() { System.out.println("Done"); } }
repos\tutorials-master\core-java-modules\core-java-9-new-features\src\main\java\com\baeldung\java9\streams.reactive\EndSubscriber.java
1
请完成以下Java代码
private void logUpload(ClassPathChangedEvent event) { logger.info(LogMessage.format("Uploading %s", event.overview())); } private byte[] serialize(ClassLoaderFiles classLoaderFiles) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(classLoaderFiles); objectOutputStream.close(); return outputStream.toByteArray(); } private ClassLoaderFiles getClassLoaderFiles(ClassPathChangedEvent event) throws IOException { ClassLoaderFiles files = new ClassLoaderFiles(); for (ChangedFiles changedFiles : event.getChangeSet()) { String sourceDirectory = changedFiles.getSourceDirectory().getAbsolutePath(); for (ChangedFile changedFile : changedFiles) {
files.addFile(sourceDirectory, changedFile.getRelativeName(), asClassLoaderFile(changedFile)); } } return files; } private ClassLoaderFile asClassLoaderFile(ChangedFile changedFile) throws IOException { ClassLoaderFile.Kind kind = TYPE_MAPPINGS.get(changedFile.getType()); Assert.state(kind != null, "'kind' must not be null"); byte[] bytes = (kind != Kind.DELETED) ? FileCopyUtils.copyToByteArray(changedFile.getFile()) : null; long lastModified = (kind != Kind.DELETED) ? changedFile.getFile().lastModified() : System.currentTimeMillis(); return new ClassLoaderFile(kind, lastModified, bytes); } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\ClassPathChangeUploader.java
1
请完成以下Java代码
public void setIsAutoSendVendors (final boolean IsAutoSendVendors) { set_Value (COLUMNNAME_IsAutoSendVendors, IsAutoSendVendors); } @Override public boolean isAutoSendVendors() { return get_ValueAsBoolean(COLUMNNAME_IsAutoSendVendors); } @Override public void setIsCreateBPartnerFolders (final boolean IsCreateBPartnerFolders) { set_Value (COLUMNNAME_IsCreateBPartnerFolders, IsCreateBPartnerFolders); } @Override public boolean isCreateBPartnerFolders() { return get_ValueAsBoolean(COLUMNNAME_IsCreateBPartnerFolders); } @Override public void setIsSyncBPartnersToRestEndpoint (final boolean IsSyncBPartnersToRestEndpoint) { set_Value (COLUMNNAME_IsSyncBPartnersToRestEndpoint, IsSyncBPartnersToRestEndpoint); } @Override public boolean isSyncBPartnersToRestEndpoint() { return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRestEndpoint); } @Override public void setIsSyncHUsOnMaterialReceipt (final boolean IsSyncHUsOnMaterialReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnMaterialReceipt, IsSyncHUsOnMaterialReceipt); } @Override public boolean isSyncHUsOnMaterialReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnMaterialReceipt); } @Override public void setIsSyncHUsOnProductionReceipt (final boolean IsSyncHUsOnProductionReceipt) { set_Value (COLUMNNAME_IsSyncHUsOnProductionReceipt, IsSyncHUsOnProductionReceipt);
} @Override public boolean isSyncHUsOnProductionReceipt() { return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnProductionReceipt); } /** * TenantId AD_Reference_ID=276 * Reference name: AD_Org (all) */ public static final int TENANTID_AD_Reference_ID=276; @Override public void setTenantId (final java.lang.String TenantId) { set_Value (COLUMNNAME_TenantId, TenantId); } @Override public java.lang.String getTenantId() { return get_ValueAsString(COLUMNNAME_TenantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_GRSSignum.java
1
请完成以下Java代码
public int getMSV3_Customer_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Customer_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); }
/** Set Nutzerkennung. @param UserID Nutzerkennung */ @Override public void setUserID (java.lang.String UserID) { set_Value (COLUMNNAME_UserID, UserID); } /** Get Nutzerkennung. @return Nutzerkennung */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Customer_Config.java
1
请在Spring Boot框架中完成以下Java代码
public class TransactionEventHandlerForCockpitRecords implements MaterialEventHandler<AbstractTransactionEvent> { private final MainDataRequestHandler dataUpdateRequestHandler; private final IOrgDAO orgDAO = Services.get(IOrgDAO.class); public TransactionEventHandlerForCockpitRecords( @NonNull final MainDataRequestHandler dataUpdateRequestHandler) { this.dataUpdateRequestHandler = dataUpdateRequestHandler; } @Override public Collection<Class<? extends AbstractTransactionEvent>> getHandledEventType() { return ImmutableList.of( TransactionCreatedEvent.class, TransactionDeletedEvent.class); } @Override public void handleEvent(@NonNull final AbstractTransactionEvent event) { final UpdateMainDataRequest dataUpdateRequest = createDataUpdateRequestForEvent(event); dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); } private UpdateMainDataRequest createDataUpdateRequestForEvent(@NonNull final AbstractTransactionEvent event) { final OrgId orgId = event.getOrgId();
final ZoneId timeZone = orgDAO.getTimeZone(orgId); final MainDataRecordIdentifier identifier = MainDataRecordIdentifier .createForMaterial(event.getMaterialDescriptor(), timeZone); final BigDecimal eventQuantity = event.getQuantityDelta(); final UpdateMainDataRequestBuilder dataRequestBuilder = UpdateMainDataRequest.builder() .identifier(identifier) .onHandQtyChange(eventQuantity); if (event.isDirectMovementWarehouse()) { dataRequestBuilder.directMovementQty(eventQuantity); } if (event.getInventoryLineId() > 0) { dataRequestBuilder.qtyInventoryCount(eventQuantity); dataRequestBuilder.qtyInventoryTime(event.getMaterialDescriptor().getDate()); } return dataRequestBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\TransactionEventHandlerForCockpitRecords.java
2
请完成以下Java代码
public static EventRepositoryService getEventRepositoryService() { return getEventRegistryConfiguration().getEventRepositoryService(); } public static DbSqlSession getDbSqlSession() { return getDbSqlSession(getCommandContext()); } public static DbSqlSession getDbSqlSession(CommandContext commandContext) { return commandContext.getSession(DbSqlSession.class); } public static EventResourceEntityManager getResourceEntityManager() { return getResourceEntityManager(getCommandContext()); } public static EventResourceEntityManager getResourceEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getResourceEntityManager(); } public static EventDeploymentEntityManager getDeploymentEntityManager() { return getDeploymentEntityManager(getCommandContext()); } public static EventDeploymentEntityManager getDeploymentEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getDeploymentEntityManager(); } public static EventDefinitionEntityManager getEventDefinitionEntityManager() { return getEventDefinitionEntityManager(getCommandContext()); } public static EventDefinitionEntityManager getEventDefinitionEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getEventDefinitionEntityManager(); }
public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager() { return getChannelDefinitionEntityManager(getCommandContext()); } public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getChannelDefinitionEntityManager(); } public static TableDataManager getTableDataManager() { return getTableDataManager(getCommandContext()); } public static TableDataManager getTableDataManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getTableDataManager(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\util\CommandContextUtil.java
1
请完成以下Java代码
public Command<?> getCommand() { return command; } public Map<Class<?>, Session> getSessions() { return sessions; } public Throwable getException() { return exception; } public boolean isReused() { return reused; }
public void setReused(boolean reused) { this.reused = reused; } public Object getResult() { return resultStack.pollLast(); } public void setResult(Object result) { resultStack.add(result); } public long getStartTime() { return startTime; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\CommandContext.java
1
请完成以下Java代码
protected void configure(HttpSecurity http) throws Exception { // Disable CSRF (cross site request forgery) http.csrf().disable(); // No session will be created or used by spring security http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Entry points http.authorizeRequests()//0 .antMatchers("/users/signin").permitAll()// .antMatchers("/users/signup").permitAll()// .antMatchers("/h2-console/**/**").permitAll() // Disallow everything else.. .anyRequest().authenticated(); // If a user try to access a resource without having enough permissions http.exceptionHandling().accessDeniedPage("/login"); // Apply JWT http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider)); // Optional, if you want to test the API from a browser // http.httpBasic(); }
@Override public void configure(WebSecurity web) throws Exception { // Allow swagger to be accessed without authentication web.ignoring().antMatchers("/v2/api-docs")// .antMatchers("/swagger-resources/**")// .antMatchers("/swagger-ui.html")// .antMatchers("/configuration/**")// .antMatchers("/webjars/**")// .antMatchers("/public") // Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production) .and().ignoring().antMatchers("/h2-console/**/**"); ; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); } }
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\security\WebSecurityConfig.java
1
请完成以下Java代码
public abstract class SaveContextOnUpdateOrErrorResponseWrapper extends OnCommittedResponseWrapper { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private boolean contextSaved = false; // See SEC-1052 private final boolean disableUrlRewriting; /** * @param response the response to be wrapped * @param disableUrlRewriting turns the URL encoding methods into null operations, * preventing the use of URL rewriting to add the session identifier as a URL * parameter. */ public SaveContextOnUpdateOrErrorResponseWrapper(HttpServletResponse response, boolean disableUrlRewriting) { super(response); this.disableUrlRewriting = disableUrlRewriting; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Invoke this method to disable automatic saving of the {@link SecurityContext} when * the {@link HttpServletResponse} is committed. This can be useful in the event that * Async Web Requests are made which may no longer contain the {@link SecurityContext} * on it. */ public void disableSaveOnResponseCommitted() { disableOnResponseCommitted(); } /** * Implements the logic for storing the security context. * @param context the <tt>SecurityContext</tt> instance to store */ protected abstract void saveContext(SecurityContext context); /** * Calls <code>saveContext()</code> with the current contents of the * <tt>SecurityContextHolder</tt> as long as {@link #disableSaveOnResponseCommitted()
* ()} was not invoked. */ @Override protected void onResponseCommitted() { saveContext(this.securityContextHolderStrategy.getContext()); this.contextSaved = true; } @Override public final String encodeRedirectURL(String url) { if (this.disableUrlRewriting) { return url; } return super.encodeRedirectURL(url); } @Override public final String encodeURL(String url) { if (this.disableUrlRewriting) { return url; } return super.encodeURL(url); } /** * Tells if the response wrapper has called <code>saveContext()</code> because of this * wrapper. */ public final boolean isContextSaved() { return this.contextSaved; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\SaveContextOnUpdateOrErrorResponseWrapper.java
1
请完成以下Java代码
private void fillProcessDefinitionData(HistoryEvent event, ExecutionEntity execution) { String processDefinitionId = execution.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(execution.getProcessDefinitionId()); event.setProcessDefinitionKey(execution.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoricIncidentEventEntity event, Incident incident) { String processDefinitionId = incident.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(incident.getProcessDefinitionId()); } } private void fillProcessDefinitionData(HistoryEvent event, UserOperationLogContextEntry userOperationLogContextEntry) { String processDefinitionId = userOperationLogContextEntry.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(userOperationLogContextEntry.getProcessDefinitionId()); event.setProcessDefinitionKey(userOperationLogContextEntry.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoryEvent event, String processDefinitionId) { ProcessDefinitionEntity entity = this.getProcessDefinitionEntity(processDefinitionId);
if (entity != null) { event.setProcessDefinitionId(entity.getId()); event.setProcessDefinitionKey(entity.getKey()); event.setProcessDefinitionVersion(entity.getVersion()); event.setProcessDefinitionName(entity.getName()); } } protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) { DbEntityManager dbEntityManager = (Context.getCommandContext() != null) ? Context.getCommandContext().getDbEntityManager() : null; if (dbEntityManager != null) { return dbEntityManager .selectById(ProcessDefinitionEntity.class, processDefinitionId); } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultHistoryEventProducer.java
1
请在Spring Boot框架中完成以下Java代码
private @Nullable Path getWorkingDirectory(RunningService runningService) { DockerComposeFile composeFile = runningService.composeFile(); if (composeFile == null || CollectionUtils.isEmpty(composeFile.getFiles())) { return Path.of("."); } return composeFile.getFiles().get(0).toPath().getParent(); } 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
请在Spring Boot框架中完成以下Java代码
public boolean isChange() { if (!newValuesSet) { return false; } if (newSequence) { return true; } if (!Objects.equals(this.sequenceName, this.sequenceNameNew)) { return true; } if (currentNext != currentNextNew) { return true; } if (currentNextSys != currentNextSysNew) { return true; } return false; } @Override public String toString() { final StringBuilder changes = new StringBuilder(); if (newValuesSet && !Objects.equals(sequenceName, sequenceNameNew)) { if (changes.length() > 0) { changes.append(", "); } changes.append("Name(new)=").append(sequenceNameNew); } if (newValuesSet && currentNext != currentNextNew) {
if (changes.length() > 0) { changes.append(", "); } changes.append("CurrentNext=").append(currentNext).append("->").append(currentNextNew); } if (newValuesSet && currentNextSys != currentNextSysNew) { if (changes.length() > 0) { changes.append(", "); } changes.append("CurrentNextSys=").append(currentNextSys).append("->").append(currentNextSysNew); } final StringBuilder sb = new StringBuilder(); sb.append("Sequence ").append(sequenceName); if (newSequence) { sb.append(" (new)"); } sb.append(": "); if (changes.length() > 0) { sb.append(changes); } else if (newSequence) { sb.append("just created"); } else { sb.append("no changes"); } return sb.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\TableSequenceChecker.java
2
请在Spring Boot框架中完成以下Java代码
class JmsAnnotationDrivenConfiguration { private final ObjectProvider<DestinationResolver> destinationResolver; private final ObjectProvider<JtaTransactionManager> transactionManager; private final ObjectProvider<MessageConverter> messageConverter; private final ObjectProvider<ExceptionListener> exceptionListener; private final ObjectProvider<ObservationRegistry> observationRegistry; private final JmsProperties properties; JmsAnnotationDrivenConfiguration(ObjectProvider<DestinationResolver> destinationResolver, ObjectProvider<JtaTransactionManager> transactionManager, ObjectProvider<MessageConverter> messageConverter, ObjectProvider<ExceptionListener> exceptionListener, ObjectProvider<ObservationRegistry> observationRegistry, JmsProperties properties) { this.destinationResolver = destinationResolver; this.transactionManager = transactionManager; this.messageConverter = messageConverter; this.exceptionListener = exceptionListener; this.observationRegistry = observationRegistry; this.properties = properties; } @Bean @ConditionalOnMissingBean @SuppressWarnings("removal") DefaultJmsListenerContainerFactoryConfigurer jmsListenerContainerFactoryConfigurer() { DefaultJmsListenerContainerFactoryConfigurer configurer = new DefaultJmsListenerContainerFactoryConfigurer(); configurer.setDestinationResolver(this.destinationResolver.getIfUnique()); configurer.setTransactionManager(this.transactionManager.getIfUnique()); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setExceptionListener(this.exceptionListener.getIfUnique()); configurer.setObservationRegistry(this.observationRegistry.getIfUnique()); configurer.setJmsProperties(this.properties); return configurer; } @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnMissingBean(name = "jmsListenerContainerFactory") DefaultJmsListenerContainerFactory jmsListenerContainerFactory( DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); configurer.configure(factory, ConnectionFactoryUnwrapper.unwrapCaching(connectionFactory)); return factory; } @Configuration(proxyBeanMethods = false) @EnableJms @ConditionalOnMissingBean(name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) static class EnableJmsConfiguration { } @Configuration(proxyBeanMethods = false) @ConditionalOnJndi static class JndiConfiguration { @Bean @ConditionalOnMissingBean(DestinationResolver.class) JndiDestinationResolver destinationResolver() { JndiDestinationResolver resolver = new JndiDestinationResolver(); resolver.setFallbackToDynamicDestination(true); return resolver; } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsAnnotationDrivenConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { this.loaded.clear(); } @Override public boolean containsValue(Object value) { return this.loaded.containsValue(value); } @Override public Collection<V> values() { return this.loaded.values(); } @Override public Set<Entry<K, V>> entrySet() { return this.loaded.entrySet(); }
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoadingMap<?, ?> that = (LoadingMap<?, ?>) o; return this.loaded.equals(that.loaded); } @Override public int hashCode() { return this.loaded.hashCode(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java
2
请完成以下Java代码
private static List<HUQRCodeGenerateRequest.Attribute> toHUQRCodeGenerateRequestAttributesList(@NonNull final ImmutableAttributeSet attributes) { return attributes .getAttributeCodes() .stream() .map(attributeCode -> toHUQRCodeGenerateRequestAttribute(attributes, attributeCode)) .collect(ImmutableList.toImmutableList()); } private static HUQRCodeGenerateRequest.Attribute toHUQRCodeGenerateRequestAttribute(final ImmutableAttributeSet attributes, AttributeCode attributeCode) { final AttributeId attributeId = attributes.getAttributeIdByCode(attributeCode); final HUQRCodeGenerateRequest.Attribute.AttributeBuilder resultBuilder = HUQRCodeGenerateRequest.Attribute.builder() .attributeId(attributeId); return attributes.getAttributeValueType(attributeCode) .map(new AttributeValueType.CaseMapper<HUQRCodeGenerateRequest.Attribute>() { @Override public HUQRCodeGenerateRequest.Attribute string() { return resultBuilder.valueString(attributes.getValueAsString(attributeCode)).build(); } @Override
public HUQRCodeGenerateRequest.Attribute number() { return resultBuilder.valueNumber(attributes.getValueAsBigDecimal(attributeCode)).build(); } @Override public HUQRCodeGenerateRequest.Attribute date() { return resultBuilder.valueDate(attributes.getValueAsLocalDate(attributeCode)).build(); } @Override public HUQRCodeGenerateRequest.Attribute list() { return resultBuilder.valueListId(attributes.getAttributeValueIdOrNull(attributeCode)).build(); } }); } @Override public void logout(final @NonNull UserId userId) { abortAll(userId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\ManufacturingMobileApplication.java
1
请完成以下Java代码
public boolean isValidateSchema() { return validateSchema; } public void setValidateSchema(boolean validateSchema) { this.validateSchema = validateSchema; } public List<DecisionEntity> getDecisions() { return decisions; } public String getTargetNamespace() { return targetNamespace; }
public DmnDeploymentEntity getDeployment() { return deployment; } public void setDeployment(DmnDeploymentEntity deployment) { this.deployment = deployment; } public DmnDefinition getDmnDefinition() { return dmnDefinition; } public void setDmnDefinition(DmnDefinition dmnDefinition) { this.dmnDefinition = dmnDefinition; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\parser\DmnParse.java
1
请完成以下Java代码
protected ExitStatus run(OptionSet options) throws Exception { return ExitStatus.OK; } public String getHelp() { if (this.help == null) { getParser().formatHelpWith(new BuiltinHelpFormatter(80, 2)); OutputStream out = new ByteArrayOutputStream(); try { getParser().printHelpOn(out); } catch (IOException ex) { return "Help not available"; } this.help = out.toString().replace(" --cp ", " -cp "); } return this.help; } public Collection<OptionHelp> getOptionsHelp() { if (this.optionHelp == null) { OptionHelpFormatter formatter = new OptionHelpFormatter(); getParser().formatHelpWith(formatter); try { getParser().printHelpOn(new ByteArrayOutputStream()); } catch (Exception ex) { // Ignore and provide no hints } this.optionHelp = formatter.getOptionHelp(); } return this.optionHelp; } private static final class OptionHelpFormatter implements HelpFormatter { private final List<OptionHelp> help = new ArrayList<>(); @Override public String format(Map<String, ? extends OptionDescriptor> options) { Comparator<OptionDescriptor> comparator = Comparator .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set<OptionDescriptor> sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor)); } } return ""; } Collection<OptionHelp> getOptionHelp() { return Collections.unmodifiableList(this.help); } }
private static class OptionHelpAdapter implements OptionHelp { private final Set<String> options; private final String description; OptionHelpAdapter(OptionDescriptor descriptor) { this.options = new LinkedHashSet<>(); for (String option : descriptor.options()) { String prefix = (option.length() != 1) ? "--" : "-"; this.options.add(prefix + option); } if (this.options.contains("--cp")) { this.options.remove("--cp"); this.options.add("-cp"); } this.description = descriptor.description(); } @Override public Set<String> getOptions() { return this.options; } @Override public String getUsageHelp() { return this.description; } } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\options\OptionHandler.java
1
请完成以下Java代码
public void setReference (String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference); } /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary ()
{ return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessorLog.java
1
请完成以下Java代码
public ProductInfo getByProductId(@NonNull final ProductId productId) { return productInfos.computeIfAbsent(productId, this::retrieveProductInfo); } private ProductInfo retrieveProductInfo(@NonNull final ProductId productId) { final I_M_Product productRecord = productsRepo.getById(productId); final UomId packageUOMId = UomId.ofRepoIdOrNull(productRecord.getPackage_UOM_ID()); final String packageSizeUOM; if (packageUOMId != null) { final I_C_UOM packageUOM = uomsRepo.getById(packageUOMId); packageSizeUOM = packageUOM.getUOMSymbol(); } else { packageSizeUOM = null;
} final String stockUOM = uomsRepo.getName(UomId.ofRepoId(productRecord.getC_UOM_ID())).translate(Env.getAD_Language()); final ITranslatableString productName = InterfaceWrapperHelper.getModelTranslationMap(productRecord) .getColumnTrl(I_M_Product.COLUMNNAME_Name, productRecord.getName()); return ProductInfo.builder() .productId(productId) .code(productRecord.getValue()) .name(productName) .packageSize(productRecord.getPackageSize()) .packageSizeUOM(packageSizeUOM) .stockUOM(stockUOM) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\factory\ProductInfoSupplier.java
1
请完成以下Java代码
public DeviceId getDeviceId() { return deviceId; } public void setDeviceId(DeviceId deviceId) { this.deviceId = deviceId; } @Schema(description = "Type of the credentials", allowableValues = {"ACCESS_TOKEN", "X509_CERTIFICATE", "MQTT_BASIC", "LWM2M_CREDENTIALS"}) @Override public DeviceCredentialsType getCredentialsType() { return credentialsType; } public void setCredentialsType(DeviceCredentialsType credentialsType) { this.credentialsType = credentialsType; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Credentials Id per platform instance. " + "Used to lookup credentials from the database. " + "By default, new access token for your device. " + "Depends on the type of the credentials." , example = "Access token or other value that depends on the credentials type") @Override public String getCredentialsId() { return credentialsId; } public void setCredentialsId(String credentialsId) { this.credentialsId = credentialsId;
} @Schema(description = "Value of the credentials. " + "Null in case of ACCESS_TOKEN credentials type. Base64 value in case of X509_CERTIFICATE. " + "Complex object in case of MQTT_BASIC and LWM2M_CREDENTIALS", example = "Null in case of ACCESS_TOKEN. See model definition.") public String getCredentialsValue() { return credentialsValue; } public void setCredentialsValue(String credentialsValue) { this.credentialsValue = credentialsValue; } @Override public String toString() { return "DeviceCredentials [deviceId=" + deviceId + ", credentialsType=" + credentialsType + ", credentialsId=" + credentialsId + ", credentialsValue=" + credentialsValue + ", createdTime=" + createdTime + ", id=" + id + "]"; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\security\DeviceCredentials.java
1
请完成以下Java代码
public Params toParams() { return Params.builder() .value("bpartnerId", bpartnerLocationId.getBpartnerId().getRepoId()) .value("bpartnerLocationId", bpartnerLocationId.getRepoId()) .value("pickingSlotIds", RepoIdAwares.toCommaSeparatedString(pickingSlotIds)) .value("countHUs", countHUs) .value("startedJobId", startedJobId != null ? startedJobId.getRepoId() : null) .build(); } public boolean isStatsMissing() { return countHUs == null; } public OptionalInt getCountHUs() { return countHUs != null ? OptionalInt.of(countHUs) : OptionalInt.empty(); }
public HUConsolidationJobReference withUpdatedStats(@NonNull final PickingSlotQueuesSummary summary) { final OptionalInt optionalCountHUs = summary.getCountHUs(pickingSlotIds); if (optionalCountHUs.isPresent()) { final int countHUsNew = optionalCountHUs.getAsInt(); if (this.countHUs == null || this.countHUs != countHUsNew) { return toBuilder().countHUs(countHUsNew).build(); } else { return this; } } else { return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobReference.java
1
请在Spring Boot框架中完成以下Java代码
GitAttributesContributor gitAttributesContributor(GitAttributes gitAttributes) { return new GitAttributesContributor(gitAttributes); } @Bean GitAttributes gitAttributes(ObjectProvider<GitAttributesCustomizer> gitAttributesCustomizers) { GitAttributes gitAttributes = new GitAttributes(); gitAttributesCustomizers.orderedStream().forEach((customizer) -> customizer.customize(gitAttributes)); return gitAttributes; } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public GitIgnoreCustomizer mavenGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add("target/", ".mvn/wrapper/maven-wrapper.jar", "!**/src/main/**/target/", "!**/src/test/**/target/"); gitIgnore.getNetBeans().add("build/", "!**/src/main/**/build/", "!**/src/test/**/build/"); }; } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitIgnoreCustomizer gradleGitIgnoreCustomizer() { return (gitIgnore) -> { gitIgnore.getGeneral() .add(".gradle", "build/", "!gradle/wrapper/gradle-wrapper.jar", "!**/src/main/**/build/", "!**/src/test/**/build/"); gitIgnore.getIntellijIdea().add("out/", "!**/src/main/**/out/", "!**/src/test/**/out/"); gitIgnore.getSts().add("bin/", "!**/src/main/**/bin/", "!**/src/test/**/bin/"); }; } @Bean @ConditionalOnBuildSystem(MavenBuildSystem.ID) public GitAttributesCustomizer mavenGitAttributesCustomizer() {
return (gitAttributes) -> { gitAttributes.add("/mvnw", "text", "eol=lf"); gitAttributes.add("*.cmd", "text", "eol=crlf"); }; } @Bean @ConditionalOnBuildSystem(GradleBuildSystem.ID) public GitAttributesCustomizer gradleGitAttributesCustomizer() { return (gitAttributes) -> { gitAttributes.add("/gradlew", "text", "eol=lf"); gitAttributes.add("*.bat", "text", "eol=crlf"); gitAttributes.add("*.jar", "binary"); }; } private GitIgnore createGitIgnore() { GitIgnore gitIgnore = new GitIgnore(); gitIgnore.getSts() .add(".apt_generated", ".classpath", ".factorypath", ".project", ".settings", ".springBeans", ".sts4-cache"); gitIgnore.getIntellijIdea().add(".idea", "*.iws", "*.iml", "*.ipr"); gitIgnore.getNetBeans().add("/nbproject/private/", "/nbbuild/", "/dist/", "/nbdist/", "/.nb-gradle/"); gitIgnore.getVscode().add(".vscode/"); return gitIgnore; } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitProjectGenerationConfiguration.java
2
请完成以下Java代码
public Date getHandleTime() { return handleTime; } public void setHandleTime(Date handleTime) { this.handleTime = handleTime; } public int getHandleCode() { return handleCode; } public void setHandleCode(int handleCode) { this.handleCode = handleCode; }
public String getHandleMsg() { return handleMsg; } public void setHandleMsg(String handleMsg) { this.handleMsg = handleMsg; } public int getAlarmStatus() { return alarmStatus; } public void setAlarmStatus(int alarmStatus) { this.alarmStatus = alarmStatus; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java
1
请完成以下Java代码
public void setAD_Language (final java.lang.String AD_Language) { set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language); } @Override public java.lang.String getAD_Language() { return get_ValueAsString(COLUMNNAME_AD_Language); } @Override public org.compiere.model.I_AD_Ref_List getAD_Ref_List() { return get_ValueAsPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class); } @Override public void setAD_Ref_List(final org.compiere.model.I_AD_Ref_List AD_Ref_List) { set_ValueFromPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class, AD_Ref_List); } @Override public void setAD_Ref_List_ID (final int AD_Ref_List_ID) { if (AD_Ref_List_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID); } @Override public int getAD_Ref_List_ID() { return get_ValueAsInt(COLUMNNAME_AD_Ref_List_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() {
return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List_Trl.java
1
请完成以下Java代码
protected DecisionDefinition findDecisionDefinitionById(String decisionDefinitionId, CommandContext commandContext) { return commandContext.getProcessEngineConfiguration() .getDeploymentCache() .findDeployedDecisionDefinitionById(decisionDefinitionId); } protected boolean isDmnEnabled(CommandContext commandContext) { return commandContext.getProcessEngineConfiguration().isDmnEnabled(); } protected Date calculateRemovalTime(HistoricDecisionInstanceEntity decisionInstance, CommandContext commandContext) { DecisionDefinition decisionDefinition = findDecisionDefinitionById(decisionInstance.getDecisionDefinitionId(), commandContext); return commandContext.getProcessEngineConfiguration() .getHistoryRemovalTimeProvider() .calculateRemovalTime(decisionInstance, decisionDefinition); } protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) { return commandContext.getDbEntityManager() .selectById(ByteArrayEntity.class, byteArrayId); } protected HistoricDecisionInstanceEntity findDecisionInstanceById(String instanceId, CommandContext commandContext) {
return commandContext.getHistoricDecisionInstanceManager() .findHistoricDecisionInstance(instanceId); } public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; } protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration, List<String> decisionInstanceIds) { return new SetRemovalTimeBatchConfiguration(decisionInstanceIds) .setRemovalTime(configuration.getRemovalTime()) .setHasRemovalTime(configuration.hasRemovalTime()) .setHierarchical(configuration.isHierarchical()); } protected SetRemovalTimeJsonConverter getJsonConverterInstance() { return SetRemovalTimeJsonConverter.INSTANCE; } public String getType() { return Batch.TYPE_DECISION_SET_REMOVAL_TIME; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\DecisionSetRemovalTimeJobHandler.java
1
请完成以下Java代码
public AttachmentEntry toAttachmentEntry(@NonNull final I_AD_AttachmentEntry entryRecord) { final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoIdOrAny(entryRecord.getAD_Org_ID())); return AttachmentEntry.builder() .id(AttachmentEntryId.ofRepoIdOrNull(entryRecord.getAD_AttachmentEntry_ID())) .name(entryRecord.getFileName()) .type(AttachmentEntryType.ofCode(entryRecord.getType())) .filename(entryRecord.getFileName()) .mimeType(entryRecord.getContentType()) .url(extractUriOrNull(entryRecord)) .tags(AttachmentTags.ofString(entryRecord.getTags())) .createdUpdatedInfo(CreatedUpdatedInfo.of( TimeUtil.asZonedDateTime(entryRecord.getCreated(), timeZone), UserId.ofRepoId(entryRecord.getCreatedBy()), TimeUtil.asZonedDateTime(entryRecord.getUpdated(), timeZone), UserId.ofRepoId(entryRecord.getUpdatedBy()))) .build(); } @Nullable private static URI extractUriOrNull(final I_AD_AttachmentEntry entryRecord) { final String url = entryRecord.getURL(); if (Check.isEmpty(url, true)) { return null; } try { return new URI(url); } catch (final URISyntaxException ex) { throw new AdempiereException("Invalid URL: " + url, ex) .setParameter("entryRecord", entryRecord); }
} public void syncToRecord( @NonNull final AttachmentEntry attachmentEntry, @NonNull final I_AD_AttachmentEntry attachmentEntryRecord) { attachmentEntryRecord.setFileName(attachmentEntry.getFilename()); attachmentEntryRecord.setType(attachmentEntry.getType().getCode()); attachmentEntryRecord.setFileName(attachmentEntry.getFilename()); if (attachmentEntry.getUrl() != null) { attachmentEntryRecord.setURL(attachmentEntry.getUrl().toString()); } else { attachmentEntryRecord.setURL(null); } attachmentEntryRecord.setTags(attachmentEntry.getTags().getTagsAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryFactory.java
1
请完成以下Java代码
private static float clamp(float value) { return Math.max(0, Math.min(1, value)); } @Data @AllArgsConstructor @NoArgsConstructor public static class ProcessedImage { private String mediaType; private int width; private int height; @With private byte[] data; private long size; private ProcessedImage preview; } @Data public static class ScadaSymbolMetadataInfo { private String title; private String description; private String[] searchTags; private int widgetSizeX; private int widgetSizeY; public ScadaSymbolMetadataInfo(String fileName, JsonNode metaData) { if (metaData != null && metaData.has("title")) { title = metaData.get("title").asText(); } else { title = fileName; } if (metaData != null && metaData.has("description")) { description = metaData.get("description").asText(); } else { description = ""; }
if (metaData != null && metaData.has("searchTags") && metaData.get("searchTags").isArray()) { var tagsNode = (ArrayNode) metaData.get("searchTags"); searchTags = new String[tagsNode.size()]; for (int i = 0; i < tagsNode.size(); i++) { searchTags[i] = tagsNode.get(i).asText(); } } else { searchTags = new String[0]; } if (metaData != null && metaData.has("widgetSizeX")) { widgetSizeX = metaData.get("widgetSizeX").asInt(); } else { widgetSizeX = 3; } if (metaData != null && metaData.has("widgetSizeY")) { widgetSizeY = metaData.get("widgetSizeY").asInt(); } else { widgetSizeY = 3; } } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\util\ImageUtils.java
1
请在Spring Boot框架中完成以下Java代码
public class UserService implements IUserService, UserDetailsService { @Autowired private UserRepo userRepo; @Override public User save(User entity) throws Exception { return userRepo.save(entity); } @Override public void delete(Long id) throws Exception { userRepo.delete(id); } @Override public void delete(User entity) throws Exception { userRepo.delete(entity); } @Override public User findById(Long id) { return userRepo.findOne(id); } @Override public User findBySample(User sample) { return userRepo.findOne(whereSpec(sample)); } @Override public List<User> findAll() { return userRepo.findAll(); } @Override public List<User> findAll(User sample) { return userRepo.findAll(whereSpec(sample)); } @Override public Page<User> findAll(PageRequest pageRequest) { return userRepo.findAll(pageRequest); }
@Override public Page<User> findAll(User sample, PageRequest pageRequest) { return userRepo.findAll(whereSpec(sample), pageRequest); } private Specification<User> whereSpec(final User sample){ return (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(); if (sample.getId()!=null){ predicates.add(cb.equal(root.<Long>get("id"), sample.getId())); } if (StringUtils.hasLength(sample.getUsername())){ predicates.add(cb.equal(root.<String>get("username"),sample.getUsername())); } return cb.and(predicates.toArray(new Predicate[predicates.size()])); }; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User sample = new User(); sample.setUsername(username); User user = findBySample(sample); if( user == null ){ throw new UsernameNotFoundException(String.format("User with username=%s was not found", username)); } return user; } }
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\UserService.java
2
请完成以下Java代码
public class ControllerEndpointDiscoverer extends EndpointDiscoverer<ExposableControllerEndpoint, Operation> implements ControllerEndpointsSupplier { private final @Nullable List<PathMapper> endpointPathMappers; /** * Create a new {@link ControllerEndpointDiscoverer} instance. * @param applicationContext the source application context * @param endpointPathMappers the endpoint path mappers * @param filters filters to apply */ public ControllerEndpointDiscoverer(ApplicationContext applicationContext, @Nullable List<PathMapper> endpointPathMappers, Collection<EndpointFilter<ExposableControllerEndpoint>> filters) { super(applicationContext, ParameterValueMapper.NONE, Collections.emptyList(), filters, Collections.emptyList()); this.endpointPathMappers = endpointPathMappers; } @Override protected boolean isEndpointTypeExposed(Class<?> beanType) { MergedAnnotations annotations = MergedAnnotations.from(beanType, SearchStrategy.SUPERCLASS); return annotations.isPresent(ControllerEndpoint.class) || annotations.isPresent(RestControllerEndpoint.class); } @Override protected ExposableControllerEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess, Collection<Operation> operations) { String rootPath = PathMapper.getRootPath(this.endpointPathMappers, id); return new DiscoveredControllerEndpoint(this, endpointBean, id, rootPath, defaultAccess); } @Override protected Operation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker) { throw new IllegalStateException("ControllerEndpoints must not declare operations"); } @Override protected OperationKey createOperationKey(Operation operation) { throw new IllegalStateException("ControllerEndpoints must not declare operations"); } @Override protected boolean isInvocable(ExposableControllerEndpoint endpoint) { return true; } static class ControllerEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection() .registerType(ControllerEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\ControllerEndpointDiscoverer.java
1
请在Spring Boot框架中完成以下Java代码
public class SelectionSize { int size; boolean allSelected; public static SelectionSize ofSize(int size) { return new SelectionSize(size, false); } public static SelectionSize ofAll() { return new SelectionSize(-1, true); } private SelectionSize(final int size, final boolean allSelected) { this.size = size; this.allSelected = allSelected; } /** @return true if there is no selected rows */ public boolean isNoSelection() { return !isAllSelected() && getSize() <= 0; } /** @return true if only one row is selected */ public boolean isSingleSelection() {
return !isAllSelected() && getSize() == 1; } /** @return true if there are more then one selected row */ public boolean isMoreThanOneSelected() { return isAllSelected() || getSize() > 1; } public int getSize() { if (allSelected) { throw new AdempiereException("It's illegal to call getSize() if isAllSelected()==true"); } return size; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\SelectionSize.java
2
请完成以下Java代码
public int[] getWords() { return words; } public int[] getTags() { return tags; } public int[] getBrownCluster4thPrefix() { return brownCluster4thPrefix; } public int[] getBrownCluster6thPrefix() { return brownCluster6thPrefix; } public int[] getBrownClusterFullString() { return brownClusterFullString; } @Override public boolean equals(Object obj) { if (obj instanceof Sentence) { Sentence sentence = (Sentence) obj; if (sentence.words.length != words.length) return false; for (int i = 0; i < sentence.words.length; i++)
{ if (sentence.words[i] != words[i]) return false; if (sentence.tags[i] != tags[i]) return false; } return true; } return false; } @Override public int compareTo(Object o) { if (equals(o)) return 0; return hashCode() - o.hashCode(); } @Override public int hashCode() { int hash = 0; for (int tokenId = 0; tokenId < words.length; tokenId++) { hash ^= (words[tokenId] * tags[tokenId]); } return hash; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\structures\Sentence.java
1
请完成以下Java代码
public static final IncludedHUsLocalCache getCreate(final I_M_HU_Item huItem) { IncludedHUsLocalCache cache = InterfaceWrapperHelper.getDynAttribute(huItem, DYNATTR_Instance); if (cache == null) { cache = new IncludedHUsLocalCache(huItem); // FIXME: this is making de.metas.customer.picking.service.impl.PackingServiceTest to fail cache.setCacheDisabled(HUConstants.DEBUG_07504_Disable_IncludedHUsLocalCache); InterfaceWrapperHelper.setDynAttribute(huItem, DYNATTR_Instance, cache); } return cache; } public IncludedHUsLocalCache(final I_M_HU_Item parentItem) { super(parentItem); } @Override protected Comparator<I_M_HU> createItemsComparator() { return queryOrderBy.getComparator(I_M_HU.class); } @Override protected List<I_M_HU> retrieveItems(final IContextAware ctx, final I_M_HU_Item parentItem) { final IQueryBuilder<I_M_HU> queryBuilder = queryBL .createQueryBuilder(I_M_HU.class, ctx) .addEqualsFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, parentItem.getM_HU_Item_ID())
// Retrieve all HUs, even if they are not active. // We need this because in case of shipped HUs (HUStatus=E) those are also inactivated (IsActive=N). // see https://github.com/metasfresh/metasfresh-webui-api/issues/567. // .addOnlyActiveRecordsFilter() ; final List<I_M_HU> hus = queryBuilder .create() .setOrderBy(queryOrderBy) .list(); // Make sure hu.getM_HU_Item_Parent() returns our parentItem for (final I_M_HU hu : hus) { hu.setM_HU_Item_Parent(parentItem); } return hus; } @Override protected final Object mkKey(final I_M_HU item) { return item.getM_HU_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\IncludedHUsLocalCache.java
1
请完成以下Java代码
public CircuitBreakerConfig setFallbackPath(String fallbackPath) { this.fallbackPath = fallbackPath; return this; } public Set<String> getStatusCodes() { return statusCodes; } public CircuitBreakerConfig setStatusCodes(String... statusCodes) { return setStatusCodes(new LinkedHashSet<>(Arrays.asList(statusCodes))); } public CircuitBreakerConfig setStatusCodes(Set<String> statusCodes) { this.statusCodes = statusCodes; return this; } public boolean isResumeWithoutError() { return resumeWithoutError; } public CircuitBreakerConfig setResumeWithoutError(boolean resumeWithoutError) { this.resumeWithoutError = resumeWithoutError;
return this; } } public static class CircuitBreakerStatusCodeException extends ResponseStatusException { public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) { super(statusCode); } } public static class FilterSupplier extends SimpleFilterSupplier { public FilterSupplier() { super(CircuitBreakerFilterFunctions.class); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\CircuitBreakerFilterFunctions.java
1
请完成以下Java代码
public MessageFlowAssociation newInstance(ModelTypeInstanceContext instanceContext) { return new MessageFlowAssociationImpl(instanceContext); } }); innerMessageFlowRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_INNER_MESSAGE_FLOW_REF) .required() .qNameAttributeReference(MessageFlow.class) .build(); outerMessageFlowRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OUTER_MESSAGE_FLOW_REF) .required() .qNameAttributeReference(MessageFlow.class) .build(); typeBuilder.build(); } public MessageFlowAssociationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext); } public MessageFlow getInnerMessageFlow() { return innerMessageFlowRefAttribute.getReferenceTargetElement(this); } public void setInnerMessageFlow(MessageFlow innerMessageFlow) { innerMessageFlowRefAttribute.setReferenceTargetElement(this, innerMessageFlow); } public MessageFlow getOuterMessageFlow() { return outerMessageFlowRefAttribute.getReferenceTargetElement(this); } public void setOuterMessageFlow(MessageFlow outerMessageFlow) { outerMessageFlowRefAttribute.setReferenceTargetElement(this, outerMessageFlow); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MessageFlowAssociationImpl.java
1
请完成以下Java代码
public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public @Nullable String getRouteIdPrefix() { return routeIdPrefix; } public void setRouteIdPrefix(String routeIdPrefix) { this.routeIdPrefix = routeIdPrefix; } public String getIncludeExpression() { return includeExpression; } public void setIncludeExpression(String includeExpression) { this.includeExpression = includeExpression; } public String getUrlExpression() { return urlExpression; } public void setUrlExpression(String urlExpression) { this.urlExpression = urlExpression; } public boolean isLowerCaseServiceId() { return lowerCaseServiceId; } public void setLowerCaseServiceId(boolean lowerCaseServiceId) { this.lowerCaseServiceId = lowerCaseServiceId;
} public List<PredicateDefinition> getPredicates() { return predicates; } public void setPredicates(List<PredicateDefinition> predicates) { this.predicates = predicates; } public List<FilterDefinition> getFilters() { return filters; } public void setFilters(List<FilterDefinition> filters) { this.filters = filters; } @Override public String toString() { return new ToStringCreator(this).append("enabled", enabled) .append("routeIdPrefix", routeIdPrefix) .append("includeExpression", includeExpression) .append("urlExpression", urlExpression) .append("lowerCaseServiceId", lowerCaseServiceId) .append("predicates", predicates) .append("filters", filters) .toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryLocatorProperties.java
1
请在Spring Boot框架中完成以下Java代码
public String getComment() { return comment; } /** * @param comment * the comment to set */ public void setComment(String comment) { this.comment = comment; } /** * @return the posted */ @JsonProperty(JP_POSTED) @JsonSerialize(using = CustomDateToStringSerializer.class) public Date getPosted() { return posted; } /** * @param posted * the posted to set */ public void setPosted(Date posted) { this.posted = posted; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((posted == null) ? 0 : posted.hashCode()); result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommentResource other = (CommentResource) obj; if (comment == null) { if (other.comment != null) return false; } else if (!comment.equals(other.comment)) return false; if (posted == null) { if (other.posted != null) return false; } else if (!posted.equals(other.posted)) return false; if (taskId == null) { if (other.taskId != null)
return false; } else if (!taskId.equals(other.taskId)) return false; return true; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "CommentResource [taskId=" + taskId + ", comment=" + comment + ", posted=" + posted + "]"; } } /** * Custom date serializer that converts the date to String before sending it out * * @author anilallewar * */ class CustomDateToStringSerializer extends JsonSerializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { String dateString = dateFormat.format(value); jgen.writeString(dateString); } }
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\model\CommentResource.java
2
请在Spring Boot框架中完成以下Java代码
public Result<List<SysGatewayRoute>> deleteList(HttpServletRequest request) { Result<List<SysGatewayRoute>> result = new Result<>(); List<SysGatewayRoute> list = sysGatewayRouteService.getDeletelist(); result.setSuccess(true); result.setResult(list); return result; } /** * 还原被逻辑删除的路由 * * @param jsonObject * @return */ @RequiresPermissions("system:gateway:putRecycleBin") @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT) public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) { try { String ids = jsonObject.getString("ids"); if (StringUtils.isNotBlank(ids)) { sysGatewayRouteService.revertLogicDeleted(Arrays.asList(ids.split(","))); return Result.ok("操作成功!"); } } catch (Exception e) { e.printStackTrace(); return Result.error("操作失败!"); } return Result.ok("还原成功"); } /** * 彻底删除路由 * * @param ids 被删除的路由ID,多个id用半角逗号分割 * @return */ @RequiresPermissions("system:gateway:deleteRecycleBin") @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE) public Result deleteRecycleBin(@RequestParam("ids") String ids) { try { if (StringUtils.isNotBlank(ids)) { sysGatewayRouteService.deleteLogicDeleted(Arrays.asList(ids.split(","))); } return Result.ok("删除成功!");
} catch (Exception e) { e.printStackTrace(); return Result.error("删除失败!"); } } /** * 复制路由 * * @param id 路由id * @return */ @RequiresPermissions("system:gateway:copyRoute") @RequestMapping(value = "/copyRoute", method = RequestMethod.GET) public Result<SysGatewayRoute> copyRoute(@RequestParam(name = "id", required = true) String id, HttpServletRequest req) { Result<SysGatewayRoute> result = new Result<>(); SysGatewayRoute sysGatewayRoute= sysGatewayRouteService.copyRoute(id); result.setResult(sysGatewayRoute); result.setSuccess(true); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysGatewayRouteController.java
2
请完成以下Java代码
public class RedirectUrlBuilder { private @Nullable String scheme; private @Nullable String serverName; private int port; private @Nullable String contextPath; private @Nullable String servletPath; private @Nullable String pathInfo; private @Nullable String query; public void setScheme(String scheme) { Assert.isTrue("http".equals(scheme) || "https".equals(scheme), () -> "Unsupported scheme '" + scheme + "'"); this.scheme = scheme; } public void setServerName(String serverName) { this.serverName = serverName; } public void setPort(int port) { this.port = port; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public void setServletPath(String servletPath) { this.servletPath = servletPath; } public void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } public void setQuery(String query) { this.query = query; } public String getUrl() { StringBuilder sb = new StringBuilder(); Assert.notNull(this.scheme, "scheme cannot be null"); Assert.notNull(this.serverName, "serverName cannot be null");
sb.append(this.scheme).append("://").append(this.serverName); // Append the port number if it's not standard for the scheme if (this.port != (this.scheme.equals("http") ? 80 : 443)) { sb.append(":").append(this.port); } if (this.contextPath != null) { sb.append(this.contextPath); } if (this.servletPath != null) { sb.append(this.servletPath); } if (this.pathInfo != null) { sb.append(this.pathInfo); } if (this.query != null) { sb.append("?").append(this.query); } return sb.toString(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\RedirectUrlBuilder.java
1