instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public ITranslatableString translatable(final String text) { return TranslatableStrings.constant(text); } @Override public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return TranslatableStrings.constant(adMessage.toAD_Message()); } else { return TranslatableStrings.constant(adMessage.toAD_Message() + " - " + Joiner.on(", ").useForNull("-").join(msgParameters)); } } @Override public void cacheReset() { // nothing } @Override public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters) { return TranslatableStrings.adMessage(adMessage, msgParameters) .translate(Language.getBaseAD_Language()); } @Override public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey value) { return Optional.empty();
} @Override public boolean isMessageExists(final AdMessageKey adMessage) { return false; } @Override public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId) { return Optional.empty(); } @Nullable @Override public String getErrorCode(final @NonNull AdMessageKey messageKey) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\PlainMsgBL.java
1
请完成以下Java代码
public static MobileApplicationPermissions merge( @NonNull final MobileApplicationPermissions permissions1, @NonNull final MobileApplicationPermissions permissions2, @NonNull final PermissionsBuilder.CollisionPolicy collisionPolicy) { return merge(Arrays.asList(permissions1, permissions2), collisionPolicy); } public static MobileApplicationPermissions merge( @NonNull final List<MobileApplicationPermissions> permissionsList, @NonNull final PermissionsBuilder.CollisionPolicy collisionPolicy) { final HashedMap<MobileApplicationRepoId, MobileApplicationPermission> resultMap = new HashedMap<>(); for (final MobileApplicationPermissions permissions : permissionsList) { if (permissions == null) { continue; } if (resultMap.isEmpty()) { resultMap.putAll(permissions.byMobileApplicationId); } else { for (final MobileApplicationPermission permission : permissions.byMobileApplicationId.values()) { final MobileApplicationRepoId mobileApplicationId = permission.getMobileApplicationId(); final MobileApplicationPermission existingPermission = resultMap.get(mobileApplicationId); final MobileApplicationPermission newPermission = MobileApplicationPermission.merge(existingPermission, permission, collisionPolicy); resultMap.put(mobileApplicationId, newPermission); } } } return MobileApplicationPermissions.ofCollection(resultMap.values()); } @Override
public String toString() { final String permissionsName = getClass().getSimpleName(); final Collection<MobileApplicationPermission> permissionsList = byMobileApplicationId.values(); final StringBuilder sb = new StringBuilder(); sb.append(permissionsName).append(": "); if (permissionsList.isEmpty()) { sb.append("@NoRestrictions@"); } else { sb.append(Env.NL); } Joiner.on(Env.NL) .skipNulls() .appendTo(sb, permissionsList); return sb.toString(); } public boolean isAllowAccess(@NonNull final MobileApplicationRepoId mobileApplicationId) { final MobileApplicationPermission permission = byMobileApplicationId.get(mobileApplicationId); return permission != null && permission.isAllowAccess(); } public boolean isAllowAction(@NonNull final MobileApplicationRepoId mobileApplicationId, @NonNull final MobileApplicationActionId actionId) { final MobileApplicationPermission permission = byMobileApplicationId.get(mobileApplicationId); return permission != null && permission.isAllowAction(actionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\mobile_application\MobileApplicationPermissions.java
1
请完成以下Java代码
protected void createAssociation(BpmnParse bpmnParse, Association association) { BpmnModel bpmnModel = bpmnParse.getBpmnModel(); if ( bpmnModel.getArtifact(association.getSourceRef()) != null || bpmnModel.getArtifact(association.getTargetRef()) != null ) { // connected to a text annotation so skipping it return; } // ActivityImpl sourceActivity = // parentScope.findActivity(association.getSourceRef()); // ActivityImpl targetActivity = // parentScope.findActivity(association.getTargetRef()); // an association may reference elements that are not parsed as // activities (like for instance // text annotations so do not throw an exception if sourceActivity or // targetActivity are null) // However, we make sure they reference 'something':
// if (sourceActivity == null) { // bpmnModel.addProblem("Invalid reference sourceRef '" + // association.getSourceRef() + "' of association element ", // association.getId()); // } else if (targetActivity == null) { // bpmnModel.addProblem("Invalid reference targetRef '" + // association.getTargetRef() + "' of association element ", // association.getId()); /* * } else { if (sourceActivity.getProperty("type").equals("compensationBoundaryCatch" )) { Object isForCompensation = targetActivity.getProperty(PROPERTYNAME_IS_FOR_COMPENSATION); if * (isForCompensation == null || !(Boolean) isForCompensation) { logger.warn( "compensation boundary catch must be connected to element with isForCompensation=true" ); } else { ActivityImpl * compensatedActivity = sourceActivity.getParentActivity(); compensatedActivity.setProperty(BpmnParse .PROPERTYNAME_COMPENSATION_HANDLER_ID, targetActivity.getId()); } } } */ } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\AbstractBpmnParseHandler.java
1
请完成以下Java代码
public MultipleArticleModel getFeed(@AuthenticationPrincipal UserJWTPayload jwtPayload, Pageable pageable) { final var articles = articleService.getFeedByUserId(jwtPayload.getUserId(), pageable); return MultipleArticleModel.fromArticles(articles); } @GetMapping("/articles/{slug}") public ResponseEntity<ArticleModel> getArticleBySlug(@PathVariable String slug) { return of(articleService.getArticleBySlug(slug) .map(ArticleModel::fromArticle)); } @PutMapping("/articles/{slug}") public ArticleModel putArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug, @RequestBody ArticlePutRequestDTO dto) { final var articleUpdated = articleService.updateArticle(jwtPayload.getUserId(), slug, dto.toUpdateRequest()); return ArticleModel.fromArticle(articleUpdated); } @PostMapping("/articles/{slug}/favorite") public ArticleModel favoriteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug) { var articleFavorited = articleService.favoriteArticle(jwtPayload.getUserId(), slug);
return ArticleModel.fromArticle(articleFavorited); } @DeleteMapping("/articles/{slug}/favorite") public ArticleModel unfavoriteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug) { var articleUnfavored = articleService.unfavoriteArticle(jwtPayload.getUserId(), slug); return ArticleModel.fromArticle(articleUnfavored); } @ResponseStatus(NO_CONTENT) @DeleteMapping("/articles/{slug}") public void deleteArticleBySlug(@AuthenticationPrincipal UserJWTPayload jwtPayload, @PathVariable String slug) { articleService.deleteArticleBySlug(jwtPayload.getUserId(), slug); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\article\ArticleRestController.java
1
请完成以下Java代码
public boolean retainAll(Collection<?> c) { return pipeList.retainAll(c); } @Override public void clear() { pipeList.clear(); } @Override public boolean equals(Object o) { return pipeList.equals(o); } @Override public int hashCode() { return pipeList.hashCode(); } @Override public Pipe<List<IWord>, List<IWord>> get(int index) { return pipeList.get(index); } @Override public Pipe<List<IWord>, List<IWord>> set(int index, Pipe<List<IWord>, List<IWord>> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<List<IWord>, List<IWord>> element) { pipeList.add(index, element); } @Override public Pipe<List<IWord>, List<IWord>> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); }
@Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<List<IWord>, List<IWord>>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\SegmentPipeline.java
1
请完成以下Java代码
public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID()
{ return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java
1
请完成以下Java代码
public class PPOrderLinesViewDataSupplier { private final ASIViewRowAttributesProvider asiAttributesProvider; private final ExtendedMemorizingSupplier<PPOrderLinesViewData> dataSupplier; @Builder private PPOrderLinesViewDataSupplier( @NonNull final WindowId viewWindowId, @NonNull final PPOrderId ppOrderId, @Nullable final ASIViewRowAttributesProvider asiAttributesProvider, @NonNull final SqlViewBinding huSQLViewBinding, @NonNull final HUReservationService huReservationService, @NonNull final ADReferenceService adReferenceService) { this.asiAttributesProvider = asiAttributesProvider; dataSupplier = ExtendedMemorizingSupplier .of(() -> PPOrderLinesViewDataLoader .builder(viewWindowId) .asiAttributesProvider(asiAttributesProvider) .huSQLViewBinding(huSQLViewBinding)
.huReservationService(huReservationService) .adReferenceService(adReferenceService) .build() .retrieveData(ppOrderId)); } public PPOrderLinesViewData getData() { return dataSupplier.get(); } public void invalidate() { dataSupplier.forget(); if (asiAttributesProvider != null) { asiAttributesProvider.invalidateAll(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesViewDataSupplier.java
1
请在Spring Boot框架中完成以下Java代码
public static class AdminUiWebMvcConfig implements WebMvcConfigurer { private final AdminServerUiProperties adminUi; private final AdminServerProperties adminServer; private final ApplicationContext applicationContext; public AdminUiWebMvcConfig(AdminServerUiProperties adminUi, AdminServerProperties adminServer, ApplicationContext applicationContext) { this.adminUi = adminUi; this.adminServer = adminServer; this.applicationContext = applicationContext; } @Bean public HomepageForwardingFilterConfig homepageForwardingFilterConfig() throws IOException { String homepage = normalizeHomepageUrl(this.adminServer.path("/")); List<String> extensionRoutes = new UiRoutesScanner(this.applicationContext) .scan(this.adminUi.getExtensionResourceLocations()); List<String> routesIncludes = Stream .concat(DEFAULT_UI_ROUTES.stream(), Stream.concat(extensionRoutes.stream(), Stream.of("/"))) .map(this.adminServer::path) .toList(); List<String> routesExcludes = Stream .concat(DEFAULT_UI_ROUTE_EXCLUDES.stream(), this.adminUi.getAdditionalRouteExcludes().stream()) .map(this.adminServer::path) .toList(); return new HomepageForwardingFilterConfig(homepage, routesIncludes, routesExcludes);
} @Override public void addResourceHandlers( org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry registry) { registry.addResourceHandler(this.adminServer.path("/**")) .addResourceLocations(this.adminUi.getResourceLocations()) .setCacheControl(this.adminUi.getCache().toCacheControl()); registry.addResourceHandler(this.adminServer.path("/extensions/**")) .addResourceLocations(this.adminUi.getExtensionResourceLocations()) .setCacheControl(this.adminUi.getCache().toCacheControl()); } @Bean @ConditionalOnMissingBean public de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter homepageForwardFilter( HomepageForwardingFilterConfig homepageForwardingFilterConfig) { return new de.codecentric.boot.admin.server.ui.web.servlet.HomepageForwardingFilter( homepageForwardingFilterConfig); } } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\config\AdminServerUiAutoConfiguration.java
2
请完成以下Java代码
public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Inventur-Position. @return Unique line in an Inventory document */ @Override public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_InventoryLineMA. @param M_InventoryLineMA_ID M_InventoryLineMA */ @Override public void setM_InventoryLineMA_ID (int M_InventoryLineMA_ID) { if (M_InventoryLineMA_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLineMA_ID, Integer.valueOf(M_InventoryLineMA_ID)); } /** Get M_InventoryLineMA. @return M_InventoryLineMA */ @Override public int getM_InventoryLineMA_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLineMA_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bewegungs-Menge. @param MovementQty Quantity of a product moved. */ @Override public void setMovementQty (java.math.BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Bewegungs-Menge. @return Quantity of a product moved. */ @Override public java.math.BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLineMA.java
1
请在Spring Boot框架中完成以下Java代码
public class DroolsBeanFactory { private static final String RULES_PATH = "com/baeldung/drools/rules/"; private KieServices kieServices = KieServices.Factory.get(); private KieFileSystem getKieFileSystem() { KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); List<String> rules = Arrays.asList("com/baeldung/drools/rules/BackwardChaining.drl", "com/baeldung/drools/rules/SuggestApplicant.drl", "com/baeldung/drools/rules/Product_rules.drl.xls", "com/baeldung/drools/rules/eligibility_rules_event.drl", "com/baeldung/drools/rules/eligibility_rules_context.drl"); for (String rule : rules) { kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); } return kieFileSystem; } private void getKieRepository() { final KieRepository kieRepository = kieServices.getRepository(); kieRepository.addKieModule(kieRepository::getDefaultReleaseId); } public KieSession getKieSession() { KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem()); kb.buildAll(); KieRepository kieRepository = kieServices.getRepository(); ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId(); KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId); return kieContainer.newKieSession(); } public KieSession getKieSession(Resource dt) { KieFileSystem kieFileSystem = kieServices.newKieFileSystem() .write(dt); KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem) .buildAll(); KieRepository kieRepository = kieServices.getRepository(); ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();
KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId); KieSession ksession = kieContainer.newKieSession(); return ksession; } /* * Can be used for debugging * Input excelFile example: com/baeldung/drools/rules/Discount.drl.xls */ public String getDrlFromExcel(String excelFile) { DecisionTableConfiguration configuration = KnowledgeBuilderFactory.newDecisionTableConfiguration(); configuration.setInputType(DecisionTableInputType.XLS); Resource dt = ResourceFactory.newClassPathResource(excelFile, getClass()); DecisionTableProviderImpl decisionTableProvider = new DecisionTableProviderImpl(); String drl = decisionTableProvider.loadFromResource(dt, null); return drl; } }
repos\tutorials-master\drools\src\main\java\com\baeldung\drools\config\DroolsBeanFactory.java
2
请完成以下Java代码
public class DataLoaderMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterType().equals(DataLoader.class); } @Override public Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) { DataLoader<Object, Object> dataLoader = null; Class<?> valueType = getValueType(parameter); if (valueType != null) { dataLoader = environment.getDataLoader(valueType.getName()); } String parameterName = null; if (dataLoader == null) { parameterName = parameter.getParameterName(); if (parameterName != null) { dataLoader = environment.getDataLoader(parameterName); } } if (dataLoader == null) { String message = getErrorMessage(parameter, environment, valueType, parameterName); throw new IllegalArgumentException(message); } return dataLoader; } private @Nullable Class<?> getValueType(MethodParameter param) { Assert.isAssignable(DataLoader.class, param.getParameterType()); Type genericType = param.getGenericParameterType(); if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; if (parameterizedType.getActualTypeArguments().length == 2) { Type valueType = parameterizedType.getActualTypeArguments()[1]; return (valueType instanceof Class) ? (Class<?>) valueType : ResolvableType.forType(valueType).resolve(); } } return null; } private String getErrorMessage( MethodParameter parameter, DataFetchingEnvironment environment, @Nullable Class<?> valueType, @Nullable String parameterName) { StringBuilder builder = new StringBuilder("Cannot resolve DataLoader for parameter"); if (parameterName != null) {
builder.append(" '").append(parameterName).append("'"); } else { builder.append("[").append(parameter.getParameterIndex()).append("]"); } if (parameter.getMethod() != null) { builder.append(" in method ").append(parameter.getMethod().toGenericString()); } builder.append(". "); if (valueType == null) { builder.append("If the batch loader was registered without a name, " + "then declaring the DataLoader argument with generic types should help " + "to look up the DataLoader based on the value type name."); } else if (parameterName == null) { builder.append("If the batch loader was registered with a name, " + "then compiling with \"-parameters\" should help " + "to look up the DataLoader based on the parameter name."); } else { builder.append("Neither the name of the declared value type '").append(valueType) .append("' nor the method parameter name '").append(parameterName) .append("' match to any DataLoader. The DataLoaderRegistry contains: ") .append(environment.getDataLoaderRegistry().getKeys()); } return builder.toString(); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\DataLoaderMethodArgumentResolver.java
1
请完成以下Java代码
class HTMLEditor_MenuAction { public HTMLEditor_MenuAction(String name, HTMLEditor_MenuAction[] subMenus) { m_name = name; m_subMenus = subMenus; } public HTMLEditor_MenuAction(String name, String actionName) { m_name = name; m_actionName = actionName; } public HTMLEditor_MenuAction(String name, Action action) { m_name = name; m_action = action; } private String m_name; private String m_actionName; private Action m_action; private HTMLEditor_MenuAction[] m_subMenus; public boolean isSubMenu() { return m_subMenus != null; } public boolean isAction() { return m_action != null;
} public String getName() { return m_name; } public HTMLEditor_MenuAction[] getSubMenus() { return m_subMenus; } public String getActionName() { return m_actionName; } public Action getAction() { return m_action; } } // MenuAction
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\HTMLEditor.java
1
请完成以下Java代码
public PartyIdentification43 getInvcee() { return invcee; } /** * Sets the value of the invcee property. * * @param value * allowed object is * {@link PartyIdentification43 } * */ public void setInvcee(PartyIdentification43 value) { this.invcee = value; } /** * Gets the value of the taxRmt property. * * @return * possible object is * {@link TaxInformation4 } * */ public TaxInformation4 getTaxRmt() { return taxRmt; } /** * Sets the value of the taxRmt property. * * @param value * allowed object is * {@link TaxInformation4 } * */ public void setTaxRmt(TaxInformation4 value) { this.taxRmt = value; } /** * Gets the value of the grnshmtRmt property. * * @return * possible object is * {@link Garnishment1 } * */ public Garnishment1 getGrnshmtRmt() { return grnshmtRmt; } /** * Sets the value of the grnshmtRmt property. * * @param value * allowed object is * {@link Garnishment1 } * */ public void setGrnshmtRmt(Garnishment1 value) {
this.grnshmtRmt = value; } /** * Gets the value of the addtlRmtInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addtlRmtInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddtlRmtInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAddtlRmtInf() { if (addtlRmtInf == null) { addtlRmtInf = new ArrayList<String>(); } return this.addtlRmtInf; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\StructuredRemittanceInformation13.java
1
请完成以下Java代码
private final List<I_M_InOut> getReceiptsToReverse(final Stream<Integer> huIds) { return huIds .map(huId -> getReceiptOrNull(huId)) // skip if no receipt found because // * it could be that user selected not a top level HU.... skip it for now // * or we were really asked to as much as we can .filter(receipt -> receipt != null) .collect(GuavaCollectors.toImmutableList()); } /** * Get all HUs which are assigned to given receipts. * * @param receipts * @return HUs */ public Set<I_M_HU> getHUsForReceipts(final Collection<? extends I_M_InOut> receipts) { final Set<I_M_HU> hus = new TreeSet<>(HUByIdComparator.instance); for (final I_M_InOut receipt : receipts) { final int inoutId = receipt.getM_InOut_ID(); final Collection<I_M_HU> husForReceipt = inoutId2hus.get(inoutId); if (Check.isEmpty(husForReceipt)) { continue; } hus.addAll(husForReceipt); } return hus; } public static final class Builder
{ private I_M_ReceiptSchedule receiptSchedule; private boolean tolerateNoHUsFound = false; private Builder() { super(); } public ReceiptCorrectHUsProcessor build() { return new ReceiptCorrectHUsProcessor(this); } public Builder setM_ReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule) { this.receiptSchedule = receiptSchedule; return this; } private I_M_ReceiptSchedule getM_ReceiptSchedule() { Check.assumeNotNull(receiptSchedule, "Parameter receiptSchedule is not null"); return receiptSchedule; } public Builder tolerateNoHUsFound() { tolerateNoHUsFound = true; return this; } private boolean isFailOnNoHUsFound() { return !tolerateNoHUsFound; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\ReceiptCorrectHUsProcessor.java
1
请完成以下Spring Boot application配置
logging: level: org: springframework: cloud: task: DEBUG spring: application: name: helloWorld datasource: url: jdbc:mysql://localhost:3306/springcloud?useSSL=false username: root password: jpa: hibernate: ddl-auto: cre
ate-drop properties: hibernate: dialect: org.hibernate.dialect.MySQL5Dialect batch: initialize-schema: always
repos\tutorials-master\spring-cloud-modules\spring-cloud-task\springcloudtaskbatch\src\main\resources\application.yml
2
请完成以下Java代码
public GroupQuery memberOfTenant(String tenantId) { ensureNotNull("Provided tenantId", tenantId); this.tenantId = tenantId; return this; } //sorting //////////////////////////////////////////////////////// public GroupQuery orderByGroupId() { return orderBy(GroupQueryProperty.GROUP_ID); } public GroupQuery orderByGroupName() { return orderBy(GroupQueryProperty.NAME); } public GroupQuery orderByGroupType() { return orderBy(GroupQueryProperty.TYPE); } //getters //////////////////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() {
return nameLike; } public String getType() { return type; } public String getUserId() { return userId; } public String getTenantId() { return tenantId; } public String[] getIds() { return ids; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\GroupQueryImpl.java
1
请完成以下Java代码
public List<IWord> flow(String input) { List<IWord> output = new LinkedList<IWord>(); output.add(new Word(input, null)); return output; } }, new Pipe<List<IWord>, List<IWord>>() { @Override public List<IWord> flow(List<IWord> input) { return input; } } ); add(analyzer); } /** * 获取代理的词法分析器 * * @return */ public LexicalAnalyzer getAnalyzer() { for (Pipe<List<IWord>, List<IWord>> pipe : this) { if (pipe instanceof LexicalAnalyzerPipe) { return ((LexicalAnalyzerPipe) pipe).analyzer; } } return null; } @Override public void segment(String sentence, String normalized, List<String> wordList) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); analyzer.segment(sentence, normalized, wordList); } @Override public List<String> segment(String sentence) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.segment(sentence); } @Override public String[] recognize(String[] wordArray, String[] posArray) { LexicalAnalyzer analyzer = getAnalyzer();
if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.recognize(wordArray, posArray); } @Override public String[] tag(String... words) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.tag(words); } @Override public String[] tag(List<String> wordList) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.tag(wordList); } @Override public NERTagSet getNERTagSet() { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.getNERTagSet(); } @Override public Sentence analyze(String sentence) { return new Sentence(flow(sentence)); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\LexicalAnalyzerPipeline.java
1
请在Spring Boot框架中完成以下Java代码
public class PHAND1 { @XmlElement(name = "DOCUMENTID", required = true) protected String documentid; @XmlElement(name = "HANDLINGINSTRCODE") protected String handlinginstrcode; @XmlElement(name = "HANDLINGINSTRDESC") protected String handlinginstrdesc; @XmlElement(name = "HAZARDOUSMATCODE") protected String hazardousmatcode; @XmlElement(name = "HAZARDOUSMATNAME") protected String hazardousmatname; /** * Gets the value of the documentid property. * * @return * possible object is * {@link String } * */ public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the handlinginstrcode property. * * @return * possible object is * {@link String } * */ public String getHANDLINGINSTRCODE() { return handlinginstrcode; } /** * Sets the value of the handlinginstrcode property. * * @param value * allowed object is * {@link String } * */ public void setHANDLINGINSTRCODE(String value) { this.handlinginstrcode = value; } /** * Gets the value of the handlinginstrdesc property. * * @return * possible object is * {@link String } * */ public String getHANDLINGINSTRDESC() { return handlinginstrdesc; } /**
* Sets the value of the handlinginstrdesc property. * * @param value * allowed object is * {@link String } * */ public void setHANDLINGINSTRDESC(String value) { this.handlinginstrdesc = value; } /** * Gets the value of the hazardousmatcode property. * * @return * possible object is * {@link String } * */ public String getHAZARDOUSMATCODE() { return hazardousmatcode; } /** * Sets the value of the hazardousmatcode property. * * @param value * allowed object is * {@link String } * */ public void setHAZARDOUSMATCODE(String value) { this.hazardousmatcode = value; } /** * Gets the value of the hazardousmatname property. * * @return * possible object is * {@link String } * */ public String getHAZARDOUSMATNAME() { return hazardousmatname; } /** * Sets the value of the hazardousmatname property. * * @param value * allowed object is * {@link String } * */ public void setHAZARDOUSMATNAME(String value) { this.hazardousmatname = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PHAND1.java
2
请在Spring Boot框架中完成以下Java代码
public Object getVariableValue() { return variableValue; } public void setVariableValue(Object variableValue) { this.variableValue = variableValue; } @Override public VariableType getVariableType() { return variableType; } public void setVariableType(VariableType variableType) { this.variableType = variableType; } @Override public String getTaskId() {
return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getVariableInstanceId() { return variableInstanceId; } public void setVariableInstanceId(String variableInstanceId) { this.variableInstanceId = variableInstanceId; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\event\impl\FlowableVariableEventImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class PaymentLinkResult { @NonNull BankStatementId bankStatementId; @NonNull BankStatementLineId bankStatementLineId; @Nullable BankStatementLineRefId bankStatementLineRefId; @NonNull PaymentId paymentId; @NonNull Money statementTrxAmt; boolean paymentMarkedAsReconciled; public boolean isBankStatementLineReferenceLink() {
return bankStatementLineRefId != null; } public BankStatementAndLineAndRefId getBankStatementAndLineAndRefId() { if (bankStatementLineRefId == null) { throw new AdempiereException("Payment wasn't link on a bank statement line reference: " + this); } return BankStatementAndLineAndRefId.of( bankStatementId, bankStatementLineId, bankStatementLineRefId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\PaymentLinkResult.java
2
请完成以下Java代码
private void injectEngineConfig(ProcessDefinitionQueryDto parameter) { ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) getProcessEngine()).getProcessEngineConfiguration(); if (processEngineConfiguration.getHistoryLevel().equals(HistoryLevel.HISTORY_LEVEL_NONE)) { parameter.setHistoryEnabled(false); } parameter.initQueryVariableValues(processEngineConfiguration.getVariableSerializers(), processEngineConfiguration.getDatabaseType()); } protected void configureExecutionQuery(ProcessDefinitionQueryDto query) { configureAuthorizationCheck(query); configureTenantCheck(query); addPermissionCheck(query, PROCESS_INSTANCE, "EXEC2.PROC_INST_ID_", READ); addPermissionCheck(query, PROCESS_DEFINITION, "PROCDEF.KEY_", READ_INSTANCE); }
protected class QueryCalledProcessDefinitionsCmd implements Command<List<ProcessDefinitionDto>> { protected ProcessDefinitionQueryDto queryParameter; public QueryCalledProcessDefinitionsCmd(ProcessDefinitionQueryDto queryParameter) { this.queryParameter = queryParameter; } @Override public List<ProcessDefinitionDto> execute(CommandContext commandContext) { queryParameter.setParentProcessDefinitionId(id); injectEngineConfig(queryParameter); configureExecutionQuery(queryParameter); queryParameter.disableMaxResultsLimit(); return getQueryService().executeQuery("selectCalledProcessDefinitions", queryParameter); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\sub\resources\ProcessDefinitionResource.java
1
请完成以下Java代码
private Map<String, Object> getConfigInfo() { return ImmutableMap.<String, Object>builder() .put("enabled", DummyDeviceConfigPool.isEnabled()) .put("responseMinValue", DummyDeviceConfigPool.getResponseMinValue().doubleValue()) .put("responseMaxValue", DummyDeviceConfigPool.getResponseMaxValue().doubleValue()) .build(); } @GetMapping("/addOrUpdate") public void addScale( @RequestParam("deviceName") final String deviceName, @RequestParam("attributes") final String attributesStr, @RequestParam(name = "onlyForWarehouseIds", required = false) final String onlyForWarehouseIdsStr) { assertLoggedIn(); final List<AttributeCode> attributes = CollectionUtils.ofCommaSeparatedList(attributesStr, AttributeCode::ofString); final List<WarehouseId> onlyForWarehouseIds = RepoIdAwares.ofCommaSeparatedList(onlyForWarehouseIdsStr, WarehouseId.class); DummyDeviceConfigPool.addDevice(DummyDeviceAddRequest.builder() .deviceName(deviceName) .assignedAttributeCodes(attributes)
.onlyWarehouseIds(onlyForWarehouseIds) .build()); setEnabled(true); } @GetMapping("/removeDevice") public void addScale( @RequestParam("deviceName") final String deviceName) { assertLoggedIn(); DummyDeviceConfigPool.removeDeviceByName(deviceName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.webui\src\main\java\de\metas\device\rest\DummyDevicesRestControllerTemplate.java
1
请在Spring Boot框架中完成以下Java代码
private RfqQty getOrCreateQty(@NonNull final LocalDate date) { final RfqQty existingRfqQty = getRfqQtyByDate(date); if (existingRfqQty != null) { return existingRfqQty; } else { final RfqQty rfqQty = RfqQty.builder() .rfq(this) .datePromised(date) .build(); addRfqQty(rfqQty); return rfqQty; } } private void addRfqQty(final RfqQty rfqQty) { rfqQty.setRfq(this); quantities.add(rfqQty); } @Nullable public RfqQty getRfqQtyByDate(@NonNull final LocalDate date) { for (final RfqQty rfqQty : quantities) { if (date.equals(rfqQty.getDatePromised())) { return rfqQty; } } return null; } private void updateConfirmedByUser()
{ this.confirmedByUser = computeConfirmedByUser(); } private boolean computeConfirmedByUser() { if (pricePromised.compareTo(pricePromisedUserEntered) != 0) { return false; } for (final RfqQty rfqQty : quantities) { if (!rfqQty.isConfirmedByUser()) { return false; } } return true; } public void closeIt() { this.closed = true; } public void confirmByUser() { this.pricePromised = getPricePromisedUserEntered(); quantities.forEach(RfqQty::confirmByUser); updateConfirmedByUser(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
2
请在Spring Boot框架中完成以下Java代码
public ServerDeployDto findByIp(String ip) { ServerDeploy deploy = serverDeployRepository.findByIp(ip); return serverDeployMapper.toDto(deploy); } @Override public Boolean testConnect(ServerDeploy resources) { ExecuteShellUtil executeShellUtil = null; try { executeShellUtil = new ExecuteShellUtil(resources.getIp(), resources.getAccount(), resources.getPassword(),resources.getPort()); return executeShellUtil.execute("ls")==0; } catch (Exception e) { return false; }finally { if (executeShellUtil != null) { executeShellUtil.close(); } } } @Override @Transactional(rollbackFor = Exception.class) public void create(ServerDeploy resources) { serverDeployRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(ServerDeploy resources) { ServerDeploy serverDeploy = serverDeployRepository.findById(resources.getId()).orElseGet(ServerDeploy::new); ValidationUtil.isNull( serverDeploy.getId(),"ServerDeploy","id",resources.getId()); serverDeploy.copy(resources);
serverDeployRepository.save(serverDeploy); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<Long> ids) { for (Long id : ids) { serverDeployRepository.deleteById(id); } } @Override public void download(List<ServerDeployDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (ServerDeployDto deployDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("服务器名称", deployDto.getName()); map.put("服务器IP", deployDto.getIp()); map.put("端口", deployDto.getPort()); map.put("账号", deployDto.getAccount()); map.put("创建日期", deployDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\ServerDeployServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Users timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Users users = (Users) o; return Objects.equals(this._id, users._id) && Objects.equals(this.firstName, users.firstName) && Objects.equals(this.lastName, users.lastName) && Objects.equals(this.email, users.email) && Objects.equals(this.timestamp, users.timestamp); } @Override public int hashCode() { return Objects.hash(_id, firstName, lastName, email, timestamp);
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Users {\n"); sb.append(" _id: ").append(toIndentedString(_id)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Users.java
2
请完成以下Java代码
void transit(State source, Action act, State target) { int deprel = 0; int[] deprel_inference = new int[]{deprel}; if (ActionUtils.is_shift(act)) { target.shift(source); } else if (ActionUtils.is_left_arc(act, deprel_inference)) { deprel = deprel_inference[0]; target.left_arc(source, deprel); } else if (ActionUtils.is_right_arc(act, deprel_inference)) { deprel = deprel_inference[0]; target.right_arc(source, deprel); } else { System.err.printf("unknown transition in transit: %d-%d", act.name(), act.rel()); } } List<Integer> transform(List<Action> actions) { List<Integer> classes = new ArrayList<Integer>(); transform(actions, classes); return classes; } void transform(List<Action> actions, List<Integer> classes) { classes.clear(); for (int i = 0; i < actions.size(); ++i) { classes.add(transform(actions.get(i))); } } /** * 转换动作为动作id * @param act 动作 * @return 动作类型的依存关系id */ int transform(Action act) { int deprel = 0; int[] deprel_inference = new int[]{deprel}; if (ActionUtils.is_shift(act)) { return 0; } else if (ActionUtils.is_left_arc(act, deprel_inference)) { deprel = deprel_inference[0]; return 1 + deprel; } else if (ActionUtils.is_right_arc(act, deprel_inference))
{ deprel = deprel_inference[0]; return L + 1 + deprel; } else { System.err.printf("unknown transition in transform(Action): %d-%d", act.name(), act.rel()); } return -1; } /** * 转换动作id为动作 * @param act 动作类型的依存关系id * @return 动作 */ Action transform(int act) { if (act == 0) { return ActionFactory.make_shift(); } else if (act < 1 + L) { return ActionFactory.make_left_arc(act - 1); } else if (act < 1 + 2 * L) { return ActionFactory.make_right_arc(act - 1 - L); } else { System.err.printf("unknown transition in transform(int): %d", act); } return new Action(); } int number_of_transitions() { return L * 2 + 1; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\TransitionSystem.java
1
请完成以下Java代码
public AlarmComment findAlarmCommentById(TenantId tenantId, AlarmCommentId alarmCommentId) { log.trace("Executing findAlarmCommentByIdAsync by alarmCommentId [{}]", alarmCommentId); validateId(alarmCommentId, id -> "Incorrect alarmCommentId " + id); return alarmCommentDao.findById(tenantId, alarmCommentId.getId()); } private AlarmComment createAlarmComment(TenantId tenantId, AlarmComment alarmComment) { log.debug("New Alarm comment : {}", alarmComment); if (alarmComment.getType() == null) { alarmComment.setType(AlarmCommentType.OTHER); } return alarmCommentDao.save(tenantId, alarmComment); } private AlarmComment updateAlarmComment(TenantId tenantId, AlarmComment newAlarmComment) {
log.debug("Update Alarm comment : {}", newAlarmComment); AlarmComment existing = alarmCommentDao.findAlarmCommentById(tenantId, newAlarmComment.getId().getId()); if (existing != null) { if (newAlarmComment.getComment() != null) { JsonNode comment = newAlarmComment.getComment(); ((ObjectNode) comment).put("edited", "true"); ((ObjectNode) comment).put("editedOn", System.currentTimeMillis()); existing.setComment(comment); } return alarmCommentDao.save(tenantId, existing); } return null; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\alarm\BaseAlarmCommentService.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Image getAD_Image() { return get_ValueAsPO(COLUMNNAME_AD_Image_ID, org.compiere.model.I_AD_Image.class); } @Override public void setAD_Image(final org.compiere.model.I_AD_Image AD_Image) { set_ValueFromPO(COLUMNNAME_AD_Image_ID, org.compiere.model.I_AD_Image.class, AD_Image); } @Override public void setAD_Image_ID (final int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, AD_Image_ID); } @Override public int getAD_Image_ID() { return get_ValueAsInt(COLUMNNAME_AD_Image_ID); } @Override public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID) { if (M_HazardSymbol_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID); } @Override public int getM_HazardSymbol_ID() { return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_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 setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_HazardSymbol.java
1
请完成以下Java代码
public IHUAllocations getHUAllocations() { // TODO Auto-generated method stub throw new UnsupportedOperationException("not implemented"); } public void setSuggestedPackingMaterial(final I_M_HU_PackingMaterial suggestedPackingMaterial) { this.suggestedPackingMaterial = suggestedPackingMaterial; } public void setSuggestedItemProduct(final I_M_HU_PI_Item_Product suggestedItemProduct) { this.suggestedItemProduct = suggestedItemProduct; } public I_M_HU_PackingMaterial getSuggestedPackingMaterial() { return suggestedPackingMaterial; } public I_M_HU_PI_Item_Product getSuggestedItemProduct() { return suggestedItemProduct; }
public I_M_HU_PI getSuggestedPI() { return suggestedPI; } public void setSuggestedPI(final I_M_HU_PI suggestedPI) { this.suggestedPI = suggestedPI; } @Override public int getC_BPartner_Location_ID() { return -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\PlainHUDocumentLine.java
1
请完成以下Java代码
public abstract class ServiceCapability<T> implements Cloneable { private final String id; private final ServiceCapabilityType type; /** * A title of the capability, used as a header text or label. */ private String title; /** * A description of the capability, used in help usage or UI tooltips. */ private String description; protected ServiceCapability(String id, ServiceCapabilityType type, String title, String description) { this.id = id; this.type = type; this.title = title; this.description = description; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getId() { return this.id; } public ServiceCapabilityType getType() { return this.type; } /** * Return the "content" of this capability. The structure of the content vastly * depends on the {@link ServiceCapability type} of the capability.
* @return the content */ public abstract T getContent(); /** * Merge the content of this instance with the specified content. * @param otherContent the content to merge * @see #merge(io.spring.initializr.metadata.ServiceCapability) */ public abstract void merge(T otherContent); /** * Merge this capability with the specified argument. The service capabilities should * match (i.e have the same {@code id} and {@code type}). Sub-classes may merge * additional content. * @param other the content to merge */ public void merge(ServiceCapability<T> other) { Assert.notNull(other, "Other must not be null"); Assert.isTrue(this.id.equals(other.id), "Ids must be equals"); Assert.isTrue(this.type.equals(other.type), "Types must be equals"); if (StringUtils.hasText(other.title)) { this.title = other.title; } if (StringUtils.hasText(other.description)) { this.description = other.description; } merge(other.getContent()); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\ServiceCapability.java
1
请在Spring Boot框架中完成以下Java代码
public class BeanValidatingItemProcessorDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private ListItemReader<TestData> simpleReader; @Bean public Job beanValidatingItemProcessorJob() throws Exception { return jobBuilderFactory.get("beanValidatingItemProcessorJob") .start(step()) .build(); }
private Step step() throws Exception { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(simpleReader) .processor(beanValidatingItemProcessor()) .writer(list -> list.forEach(System.out::println)) .build(); } private BeanValidatingItemProcessor<TestData> beanValidatingItemProcessor() throws Exception { BeanValidatingItemProcessor<TestData> beanValidatingItemProcessor = new BeanValidatingItemProcessor<>(); // 开启过滤,不符合规则的数据被过滤掉; beanValidatingItemProcessor.setFilter(true); beanValidatingItemProcessor.afterPropertiesSet(); return beanValidatingItemProcessor; } }
repos\SpringAll-master\70.spring-batch-itemprocessor\src\main\java\cc\mrbird\batch\entity\job\BeanValidatingItemProcessorDemo.java
2
请在Spring Boot框架中完成以下Java代码
public KafkaTracing kafkaTracing(Tracing tracing) { return KafkaTracing.newBuilder(tracing) .remoteServiceName("demo-mq-kafka") // 远程 Kafka 服务名,可自定义 .build(); } @Bean public ProducerFactory<?, ?> kafkaProducerFactory(KafkaProperties properties, KafkaTracing kafkaTracing) { // 创建 DefaultKafkaProducerFactory 对象 DefaultKafkaProducerFactory<?, ?> factory = new DefaultKafkaProducerFactory(properties.buildProducerProperties()) { @Override public Producer createProducer() { // 创建默认的 Producer Producer<?, ?> producer = super.createProducer(); // 创建可链路追踪的 Producer return kafkaTracing.producer(producer); } }; // 设置事务前缀 String transactionIdPrefix = properties.getProducer().getTransactionIdPrefix(); if (transactionIdPrefix != null) { factory.setTransactionIdPrefix(transactionIdPrefix); } return factory; }
@Bean public ConsumerFactory<?, ?> kafkaConsumerFactory(KafkaProperties properties, KafkaTracing kafkaTracing) { // 创建 DefaultKafkaConsumerFactory 对象 return new DefaultKafkaConsumerFactory(properties.buildConsumerProperties()) { @Override public Consumer<?, ?> createConsumer(String groupId, String clientIdPrefix, String clientIdSuffix) { return this.createConsumer(groupId, clientIdPrefix, clientIdSuffix, null); } @Override public Consumer<?, ?> createConsumer(String groupId, String clientIdPrefix, final String clientIdSuffixArg, Properties properties) { // 创建默认的 Consumer Consumer<?, ?> consumer = super.createConsumer(groupId, clientIdPrefix, clientIdSuffixArg, properties); // 创建可链路追踪的 Consumer return kafkaTracing.consumer(consumer); } }; } }
repos\SpringBoot-Labs-master\lab-40\lab-40-kafka\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public <C extends NotificationDeliveryMethodConfig> C getDeliveryMethodConfig(NotificationDeliveryMethod deliveryMethod) { NotificationSettings settings; if (deliveryMethod == NotificationDeliveryMethod.MOBILE_APP) { settings = this.systemSettings; } else { settings = this.settings; } return (C) settings.getDeliveryMethodsConfigs().get(deliveryMethod); } public <T extends DeliveryMethodNotificationTemplate> T getProcessedTemplate(NotificationDeliveryMethod deliveryMethod, NotificationRecipient recipient) { T template = (T) templates.get(deliveryMethod); if (recipient != null) { Map<String, String> additionalTemplateContext = createTemplateContextForRecipient(recipient); if (template.getTemplatableValues().stream().anyMatch(value -> value.containsParams(additionalTemplateContext.keySet()))) { template = processTemplate(template, additionalTemplateContext); } } return template; } private <T extends DeliveryMethodNotificationTemplate> T processTemplate(T template, Map<String, String> additionalTemplateContext) { Map<String, String> templateContext = new HashMap<>(); if (request.getInfo() != null) { templateContext.putAll(request.getInfo().getTemplateData()); } if (additionalTemplateContext != null) { templateContext.putAll(additionalTemplateContext); }
if (templateContext.isEmpty()) return template; template = (T) template.copy(); template.getTemplatableValues().forEach(templatableValue -> { String value = templatableValue.get(); if (StringUtils.isNotEmpty(value)) { value = TemplateUtils.processTemplate(value, templateContext); templatableValue.set(value); } }); return template; } private Map<String, String> createTemplateContextForRecipient(NotificationRecipient recipient) { return Map.of( "recipientTitle", recipient.getTitle(), "recipientEmail", Strings.nullToEmpty(recipient.getEmail()), "recipientFirstName", Strings.nullToEmpty(recipient.getFirstName()), "recipientLastName", Strings.nullToEmpty(recipient.getLastName()) ); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\NotificationProcessingContext.java
2
请完成以下Java代码
public Attribute<String> getReferenceTargetAttribute() { return referenceTargetAttribute; } /** * Set the reference target model element type * * @param referenceTargetElementType the referenceTargetElementType to set */ public void setReferenceTargetElementType(ModelElementTypeImpl referenceTargetElementType) { this.referenceTargetElementType = referenceTargetElementType; } public Collection<ModelElementInstance> findReferenceSourceElements(ModelElementInstance referenceTargetElement) { if(referenceTargetElementType.isBaseTypeOf(referenceTargetElement.getElementType())) { ModelElementType owningElementType = getReferenceSourceElementType(); return referenceTargetElement.getModelInstance().getModelElementsByType(owningElementType); } else { return Collections.emptyList(); } } /** * Update the reference identifier of the reference source model element instance * * @param referenceSourceElement the reference source model element instance * @param oldIdentifier the old reference identifier * @param newIdentifier the new reference identifier */ protected abstract void updateReference(ModelElementInstance referenceSourceElement, String oldIdentifier, String newIdentifier); /** * Update the reference identifier * * @param referenceTargetElement the reference target model element instance * @param oldIdentifier the old reference identifier * @param newIdentifier the new reference identifier */ public void referencedElementUpdated(ModelElementInstance referenceTargetElement, String oldIdentifier, String newIdentifier) { for (ModelElementInstance referenceSourceElement : findReferenceSourceElements(referenceTargetElement)) { updateReference(referenceSourceElement, oldIdentifier, newIdentifier);
} } /** * Remove the reference in the reference source model element instance * * @param referenceSourceElement the reference source model element instance */ protected abstract void removeReference(ModelElementInstance referenceSourceElement, ModelElementInstance referenceTargetElement); /** * Remove the reference if the target element is removed * * @param referenceTargetElement the reference target model element instance, which is removed * @param referenceIdentifier the identifier of the reference to filter reference source elements */ public void referencedElementRemoved(ModelElementInstance referenceTargetElement, Object referenceIdentifier) { for (ModelElementInstance referenceSourceElement : findReferenceSourceElements(referenceTargetElement)) { if (referenceIdentifier.equals(getReferenceIdentifier(referenceSourceElement))) { removeReference(referenceSourceElement, referenceTargetElement); } } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ReferenceImpl.java
1
请完成以下Java代码
public void setRequestMatcher(RequestMatcher requestMatcher) { this.requestMatcher = requestMatcher; } /** * If <code>true</code>, indicates that it is permitted to store the target URL and * exception information in a new <code>HttpSession</code> (the default). In * situations where you do not wish to unnecessarily create <code>HttpSession</code>s * - because the user agent will know the failed URL, such as with BASIC or Digest * authentication - you may wish to set this property to <code>false</code>. */ public void setCreateSessionAllowed(boolean createSessionAllowed) { this.createSessionAllowed = createSessionAllowed; } /** * If the {@code sessionAttrName} property is set, the request is stored in the * session using this attribute name. Default is "SPRING_SECURITY_SAVED_REQUEST". * @param sessionAttrName a new session attribute name. * @since 4.2.1
*/ public void setSessionAttrName(String sessionAttrName) { this.sessionAttrName = sessionAttrName; } /** * Specify the name of a query parameter that is added to the URL that specifies the * request cache should be checked in * {@link #getMatchingRequest(HttpServletRequest, HttpServletResponse)} * @param matchingRequestParameterName the parameter name that must be in the request * for {@link #getMatchingRequest(HttpServletRequest, HttpServletResponse)} to check * the session. Default is "continue". */ public void setMatchingRequestParameterName(String matchingRequestParameterName) { this.matchingRequestParameterName = matchingRequestParameterName; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\HttpSessionRequestCache.java
1
请完成以下Java代码
public double getTargetValue () { return m_targetValue; } // getTargetValue /** * @param targetValue The targetValue to set. */ public void setTargetValue (double targetValue) { m_targetValue = targetValue; } // setTargetValue /** * @return Returns the data value. */ public double getValue () { return m_value; } // getValue /** * @param value The data value to set. */ public void setValue (double value) { m_value = value; if (m_label != null) m_labelValue = s_format.format(m_value) + " - " + m_label; else m_labelValue = s_format.format(m_value); } // setValue /** * @return Returns the column width in pixels. */ public double getColWidth () { return m_width; } // getColWidth /** * @param width The column width in pixels. */ public void setColWidth (double width) { m_width = width; } // getColWidth /** * @return Returns the height in pixels. */ public double getColHeight() { return m_height; } // getHeight
/** * @param height The height in pixels. */ public void setColHeight (double height) { m_height = height; } // setHeight public MQuery getMQuery(MGoal mGoal) { MQuery query = null; if (getAchievement() != null) // Single Achievement { MAchievement a = getAchievement(); query = MQuery.getEqualQuery("PA_Measure_ID", a.getPA_Measure_ID()); } else if (getGoal() != null) // Multiple Achievements { MGoal goal = getGoal(); query = MQuery.getEqualQuery("PA_Measure_ID", goal.getPA_Measure_ID()); } else if (getMeasureCalc() != null) // Document { MMeasureCalc mc = getMeasureCalc(); query = mc.getQuery(mGoal.getRestrictions(false), getMeasureDisplay(), getDate(), Env.getUserRolePermissions()); // logged in role } else if (getProjectType() != null) // Document { ProjectType pt = getProjectType(); query = MMeasure.getQuery(pt, mGoal.getRestrictions(false), getMeasureDisplay(), getDate(), getID(), Env.getUserRolePermissions()); // logged in role } else if (getRequestType() != null) // Document { MRequestType rt = getRequestType(); query = rt.getQuery(mGoal.getRestrictions(false), getMeasureDisplay(), getDate(), getID(), Env.getUserRolePermissions()); // logged in role } return query; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\apps\graph\GraphColumn.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskId() { return taskId; } /** * Sets the task id. * * @param taskId the new task id */ public void setTaskId(String taskId) { this.taskId = taskId; } /** * Gets the description. * * @return the description */ public String getDescription() { return description; } /** * Sets the description. * * @param description the new description */ public void setDescription(String description) { this.description = description; } /** * Checks if is completed. * * @return true, if is completed */ public boolean isCompleted() { return completed; } /** * Sets the completed. * * @param completed the new completed */ public void setCompleted(boolean completed) { this.completed = completed; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the comments */ public CommentCollectionResource getComments() { return comments; } /** * @param comments the comments to set */ public void setComments(CommentCollectionResource comments) {
this.comments = comments; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((comments == null) ? 0 : comments.hashCode()); result = prime * result + (completed ? 1231 : 1237); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((taskId == null) ? 0 : taskId.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.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; TaskDTO other = (TaskDTO) obj; if (comments == null) { if (other.comments != null) return false; } else if (!comments.equals(other.comments)) return false; if (completed != other.completed) return false; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (taskId == null) { if (other.taskId != null) return false; } else if (!taskId.equals(other.taskId)) return false; if (userName == null) { if (other.userName != null) return false; } else if (!userName.equals(other.userName)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "TaskDTO [taskId=" + taskId + ", description=" + description + ", completed=" + completed + ", userName=" + userName + ", comments=" + comments + "]"; } }
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\dtos\TaskDTO.java
2
请完成以下Java代码
public ListenableFuture<AttributesSaveResult> save(TenantId tenantId, EntityId entityId, AttributeScope scope, List<AttributeKvEntry> attributes) { validate(entityId, scope); AttributeUtils.validate(attributes, valueNoXssValidation); return doSave(tenantId, entityId, scope, attributes); } private ListenableFuture<AttributesSaveResult> doSave(TenantId tenantId, EntityId entityId, AttributeScope scope, List<AttributeKvEntry> attributes) { List<ListenableFuture<Long>> futures = new ArrayList<>(attributes.size()); for (AttributeKvEntry attribute : attributes) { ListenableFuture<Long> future = Futures.transform(attributesDao.save(tenantId, entityId, scope, attribute), version -> { TenantId edqsTenantId = entityId.getEntityType() == EntityType.TENANT ? (TenantId) entityId : tenantId; edqsService.onUpdate(edqsTenantId, ObjectType.ATTRIBUTE_KV, new AttributeKv(entityId, scope, attribute, version)); return version; }, MoreExecutors.directExecutor()); futures.add(future); } return Futures.transform(Futures.allAsList(futures), AttributesSaveResult::of, MoreExecutors.directExecutor()); } @Override public ListenableFuture<List<String>> removeAll(TenantId tenantId, EntityId entityId, AttributeScope scope, List<String> attributeKeys) { validate(entityId, scope); List<ListenableFuture<TbPair<String, Long>>> futures = attributesDao.removeAllWithVersions(tenantId, entityId, scope, attributeKeys); return Futures.transform(Futures.allAsList(futures), result -> { List<String> keys = new ArrayList<>(); for (TbPair<String, Long> keyVersionPair : result) {
String key = keyVersionPair.getFirst(); Long version = keyVersionPair.getSecond(); if (version != null) { TenantId edqsTenantId = entityId.getEntityType() == EntityType.TENANT ? (TenantId) entityId : tenantId; edqsService.onDelete(edqsTenantId, ObjectType.ATTRIBUTE_KV, new AttributeKv(entityId, scope, key, version)); } keys.add(key); } return keys; }, MoreExecutors.directExecutor()); } @Override public int removeAllByEntityId(TenantId tenantId, EntityId entityId) { List<Pair<AttributeScope, String>> deleted = attributesDao.removeAllByEntityId(tenantId, entityId); deleted.forEach(attribute -> { AttributeScope scope = attribute.getKey(); String key = attribute.getValue(); if (scope != null && key != null) { edqsService.onDelete(tenantId, ObjectType.ATTRIBUTE_KV, new AttributeKv(entityId, scope, key, Long.MAX_VALUE)); } }); return deleted.size(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\attributes\BaseAttributesService.java
1
请完成以下Java代码
public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public void setIsUseCustomization (final boolean IsUseCustomization) { set_Value (COLUMNNAME_IsUseCustomization, IsUseCustomization); } @Override public boolean isUseCustomization() { return get_ValueAsBoolean(COLUMNNAME_IsUseCustomization); } @Override public void setMobile_Application_ID (final int Mobile_Application_ID) { if (Mobile_Application_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID); }
@Override public int getMobile_Application_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_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 setName_Customized (final @Nullable java.lang.String Name_Customized) { set_Value (COLUMNNAME_Name_Customized, Name_Customized); } @Override public java.lang.String getName_Customized() { return get_ValueAsString(COLUMNNAME_Name_Customized); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Trl.java
1
请在Spring Boot框架中完成以下Java代码
class AutoConfiguredRestClientSsl implements RestClientSsl { private final ClientHttpRequestFactoryBuilder<?> builder; private final HttpClientSettings settings; private final SslBundles sslBundles; AutoConfiguredRestClientSsl(ClientHttpRequestFactoryBuilder<?> clientHttpRequestFactoryBuilder, HttpClientSettings settings, SslBundles sslBundles) { this.builder = clientHttpRequestFactoryBuilder; this.settings = settings; this.sslBundles = sslBundles; }
@Override public Consumer<RestClient.Builder> fromBundle(String bundleName) { return fromBundle(this.sslBundles.getBundle(bundleName)); } @Override public Consumer<RestClient.Builder> fromBundle(SslBundle bundle) { return (builder) -> builder.requestFactory(requestFactory(bundle)); } private ClientHttpRequestFactory requestFactory(SslBundle bundle) { return this.builder.build(this.settings.withSslBundle(bundle)); } }
repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\AutoConfiguredRestClientSsl.java
2
请完成以下Java代码
public int getM_PricingSystem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); }
/** Set Preis Präzision. @param PricePrecision Precision (number of decimals) for the Price */ @Override public void setPricePrecision (int PricePrecision) { set_Value (COLUMNNAME_PricePrecision, Integer.valueOf(PricePrecision)); } /** Get Preis Präzision. @return Precision (number of decimals) for the Price */ @Override public int getPricePrecision () { Integer ii = (Integer)get_Value(COLUMNNAME_PricePrecision); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PriceList.java
1
请完成以下Java代码
public class CreateCmmnExternalWorkerJobBeforeContext { protected final ExternalWorkerServiceTask externalWorkerServiceTask; protected final PlanItemInstanceEntity planItemInstance; protected String jobCategory; protected String jobTopicExpression; public CreateCmmnExternalWorkerJobBeforeContext(ExternalWorkerServiceTask externalWorkerServiceTask, PlanItemInstanceEntity planItemInstance, String jobCategory, String jobTopicExpression) { this.externalWorkerServiceTask = externalWorkerServiceTask; this.planItemInstance = planItemInstance; this.jobCategory = jobCategory; this.jobTopicExpression = jobTopicExpression; } public ExternalWorkerServiceTask getExternalWorkerServiceTask() { return externalWorkerServiceTask; } public PlanItemInstanceEntity getPlanItemInstance() { return planItemInstance; }
public String getJobCategory() { return jobCategory; } public void setJobCategory(String jobCategory) { this.jobCategory = jobCategory; } public String getJobTopicExpression() { return jobTopicExpression; } public void setJobTopicExpression(String jobTopicExpression) { this.jobTopicExpression = jobTopicExpression; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateCmmnExternalWorkerJobBeforeContext.java
1
请完成以下Java代码
public List<String> getDeploymentResourceNames(String deploymentId) { return dataManager.getDeploymentResourceNames(deploymentId); } @Override public List<Deployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentsByNativeQuery(parameterMap); } @Override public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) { return dataManager.findDeploymentCountByNativeQuery(parameterMap); } protected ResourceEntityManager getResourceEntityManager() { return engineConfiguration.getResourceEntityManager(); } protected ModelEntityManager getModelEntityManager() {
return engineConfiguration.getModelEntityManager(); } protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() { return engineConfiguration.getProcessDefinitionEntityManager(); } protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() { return engineConfiguration.getProcessDefinitionInfoEntityManager(); } protected ExecutionEntityManager getExecutionEntityManager() { return engineConfiguration.getExecutionEntityManager(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityManagerImpl.java
1
请完成以下Java代码
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public boolean getIsLeaf() { return isLeaf; }
public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public String getPermsType() { return permsType; } public void setPermsType(String permsType) { this.permsType = permsType; } public java.lang.String getStatus() { return status; } public void setStatus(java.lang.String status) { this.status = status; } /*update_begin author:wuxianquan date:20190908 for:get set方法 */ public boolean isInternalOrExternal() { return internalOrExternal; } public void setInternalOrExternal(boolean internalOrExternal) { this.internalOrExternal = internalOrExternal; } /*update_end author:wuxianquan date:20190908 for:get set 方法 */ public boolean isHideTab() { return hideTab; } public void setHideTab(boolean hideTab) { this.hideTab = hideTab; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
1
请完成以下Java代码
public String asString() { return "graphql.error.type"; } }, /** * {@link DataLoader#getName()} of the data loader. */ LOADER_NAME { @Override public String asString() { return "graphql.loader.name"; } }, /** * Outcome of the GraphQL data fetching operation. */ OUTCOME { @Override public String asString() { return "graphql.outcome"; } }
} public enum DataLoaderHighCardinalityKeyNames implements KeyName { /** * Size of the list of elements returned by the data loading operation. */ LOADER_SIZE { @Override public String asString() { return "graphql.loader.size"; } } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\GraphQlObservationDocumentation.java
1
请完成以下Java代码
public void validateQtyAvailableForSale(@NonNull final I_C_OrderLine orderLineRecord) { if (!availableForSalesUtil.isOrderLineEligibleForFeature(orderLineRecord)) { return; // nothing to do } if (!availableForSalesUtil.isOrderEligibleForFeature(orderLineRecord.getC_Order())) { return; // nothing to do } final OrgId orgId = OrgId.ofRepoId(orderLineRecord.getAD_Org_ID()); final AvailableForSalesConfig config = availableForSalesConfigRepo.getConfig( ConfigQuery.builder() .clientId(ClientId.ofRepoId(orderLineRecord.getAD_Client_ID())) .orgId(orgId) .build()); if (!config.isFeatureEnabled()) { return; // nothing to do } // has to contain everything that the method to be invoked after commit needs final CheckAvailableForSalesRequest checkAvailableForSalesRequest = availableForSalesUtil.createRequest(orderLineRecord); availableForSalesUtil.checkAndUpdateOrderLineRecords(ImmutableList.of(checkAvailableForSalesRequest), config, orgId); } @ModelChange( // timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, // ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_QtyOrdered, I_C_OrderLine.COLUMNNAME_M_Product_ID, I_C_OrderLine.COLUMNNAME_M_AttributeSetInstance_ID, I_C_OrderLine.COLUMNNAME_AD_Org_ID, I_C_OrderLine.COLUMNNAME_M_Warehouse_ID }) public void triggerSyncAvailableForSales(@NonNull final I_C_OrderLine orderLineRecord) { syncOrderLineWithAvailableForSales(orderLineRecord); if (!InterfaceWrapperHelper.isNew(orderLineRecord))
{ final I_C_OrderLine orderLineOld = InterfaceWrapperHelper.createOld(orderLineRecord, I_C_OrderLine.class); syncOrderLineWithAvailableForSales(orderLineOld); } } private void syncOrderLineWithAvailableForSales(@NonNull final I_C_OrderLine orderLineRecord) { if (!availableForSalesUtil.isOrderLineEligibleForFeature(orderLineRecord)) { return; } final boolean isOrderEligibleForFeature = availableForSalesUtil.isOrderEligibleForFeature(OrderId.ofRepoId(orderLineRecord.getC_Order_ID())); if (!isOrderEligibleForFeature) { return; } final AvailableForSalesConfig config = getAvailableForSalesConfig(orderLineRecord); if (!config.isFeatureEnabled()) { return; // nothing to do } availableForSalesUtil.syncAvailableForSalesForOrderLine(orderLineRecord, config); } @NonNull private AvailableForSalesConfig getAvailableForSalesConfig(@NonNull final I_C_OrderLine orderLineRecord) { return availableForSalesConfigRepo.getConfig( AvailableForSalesConfigRepo.ConfigQuery.builder() .clientId(ClientId.ofRepoId(orderLineRecord.getAD_Client_ID())) .orgId(OrgId.ofRepoId(orderLineRecord.getAD_Org_ID())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\availableforsales\interceptor\C_OrderLine.java
1
请完成以下Java代码
private static LocalDate extractDate(final I_C_Order order) { return order.getDateOrdered().toLocalDateTime().toLocalDate(); } private ImmutableSet<ProductId> getProductIds(final I_C_Order order) { final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID()); return orderDAO.retrieveOrderLines(orderId) .stream() .map(orderLine -> ProductId.ofRepoId(orderLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); } public void invalidateByProducts(@NonNull Set<ProductId> productIds, @NonNull LocalDate date) { if (productIds.isEmpty()) { return; } final ArrayList<Object> sqlValuesParams = new ArrayList<>(); final StringBuilder sqlValues = new StringBuilder();
for (final ProductId productId : productIds) { if (sqlValues.length() > 0) { sqlValues.append(","); } sqlValues.append("(?,?)"); sqlValuesParams.add(productId); sqlValuesParams.add(date); } final String sql = "INSERT INTO " + TABLENAME_Recompute + " (m_product_id, date)" + "VALUES " + sqlValues; DB.executeUpdateAndThrowExceptionOnFail(sql, sqlValuesParams.toArray(), ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\stats\purchase_max_price\PurchaseLastMaxPriceService.java
1
请完成以下Java代码
public MetricsQuery limit(int maxResults) { setMaxResults(maxResults); return this; } @Override public MetricsQuery aggregateByReporter() { aggregateByReporter = true; return this; } @Override public void setMaxResults(int maxResults) { if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) { throw new ProcessEngineException("Metrics interval query row limit can't be set larger than " + DEFAULT_LIMIT_SELECT_INTERVAL + '.'); } this.maxResults = maxResults; } public Date getStartDate() { return startDate; } public Date getEndDate() { return endDate; } public Long getStartDateMilliseconds() { return startDateMilliseconds; } public Long getEndDateMilliseconds() { return endDateMilliseconds; } public String getName() { return name; } public String getReporter() { return reporter; } public Long getInterval() { if (interval == null) { return DEFAULT_SELECT_INTERVAL; } return interval; } @Override public int getMaxResults() { if (maxResults > DEFAULT_LIMIT_SELECT_INTERVAL) { return DEFAULT_LIMIT_SELECT_INTERVAL; } return super.getMaxResults(); }
protected class MetricsQueryIntervalCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQueryIntervalCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectInterval(metricsQuery); } } protected class MetricsQuerySumCmd implements Command<Object> { protected MetricsQueryImpl metricsQuery; public MetricsQuerySumCmd(MetricsQueryImpl metricsQuery) { this.metricsQuery = metricsQuery; } @Override public Object execute(CommandContext commandContext) { return commandContext.getMeterLogManager() .executeSelectSum(metricsQuery); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\MetricsQueryImpl.java
1
请完成以下Java代码
public void onParameterChanged(final String parameterName) { if (!PARAM_fullPaymentString.equals(parameterName) && !PARAM_C_BPartner_ID.equals(parameterName)) { // only update on magic payment string or bpartner return; } if (Check.isEmpty(fullPaymentStringParam, true)) { // do nothing if it's empty return; } final IPaymentStringDataProvider dataProvider; try { dataProvider = getDataProvider(); } catch (final PaymentStringParseException pspe) { final String adMessage = pspe.getLocalizedMessage() + " (\"" + fullPaymentStringParam + "\")"; throw new AdempiereException(adMessage); } final PaymentString paymentString = dataProvider.getPaymentString(); final I_C_Invoice actualInvoice = getActualInvoice(); final I_C_BP_BankAccount bpBankAccountExisting = paymentStringProcessService.getAndVerifyBPartnerAccountOrNull(dataProvider, actualInvoice.getC_BPartner_ID()); if (bpBankAccountExisting != null) { bPartnerParam = bPartnerDAO.getById(bpBankAccountExisting.getC_BPartner_ID()); bankAccountParam = bpBankAccountExisting; } else { /*
* If the C_BPartner is set from the field (manually by the user), * C_BP_BankAccount will be created by this process when the user presses "Start". * * If the C_BPartner is NOT set, show error and ask the user to set the partner before adding the magic payment string. * */ if (bPartnerParam == null) { throw new AdempiereException(MSG_CouldNotFindOrCreateBPBankAccount, paymentString.getPostAccountNo()); } else { bankAccountNumberParam = paymentString.getPostAccountNo(); willCreateANewBandAccountParam = true; } } amountParam = paymentString.getAmount(); } private IPaymentStringDataProvider getDataProvider() { return paymentStringProcessService.parsePaymentString(getCtx(), fullPaymentStringParam); } private I_C_Invoice getActualInvoice() { return invoiceDAO.getByIdInTrx(InvoiceId.ofRepoId(getRecord_ID())); } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { return paymentStringProcessService.checkPreconditionsApplicable(context); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\paymentdocumentform\WEBUI_Import_Payment_Request_For_Purchase_Invoice.java
1
请完成以下Java代码
public static LocatorId ofRepoIdOrNull(@Nullable final WarehouseId warehouseId, final int repoId) { if (repoId <= 0) { return null; } if (warehouseId == null) { throw new IllegalArgumentException("Inconsistent state: warehouseId is null but locator's repoId=" + repoId); } return ofRepoId(warehouseId, repoId); } @Nullable public static LocatorId ofRepoIdOrNull(final int warehouseRepoId, final int repoId) { if (repoId <= 0) { return null; } final WarehouseId warehouseId = WarehouseId.ofRepoIdOrNull(warehouseRepoId); if (warehouseId == null) { throw new IllegalArgumentException("Inconsistent state: warehouseId is null but locator's repoId=" + repoId); } return ofRepoId(warehouseId, repoId); } @Nullable public static LocatorId ofRecordOrNull(@Nullable final I_M_Locator locatorRecord) { if (locatorRecord == null) { return null; } return ofRecord(locatorRecord); } public static LocatorId ofRecord(@NonNull final I_M_Locator locatorRecord) { return ofRepoId( WarehouseId.ofRepoId(locatorRecord.getM_Warehouse_ID()), locatorRecord.getM_Locator_ID()); } public static int toRepoId(@Nullable final LocatorId locatorId) { return locatorId != null ? locatorId.getRepoId() : -1; } public static Set<Integer> toRepoIds(final Collection<LocatorId> locatorIds) { if (locatorIds.isEmpty()) { return ImmutableSet.of(); } return locatorIds.stream().map(LocatorId::getRepoId).collect(ImmutableSet.toImmutableSet()); } public static boolean equals(@Nullable final LocatorId id1, @Nullable final LocatorId id2) { return Objects.equals(id1, id2); } @SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean equalsByRepoId(final int repoId1, final int repoId2) { final int repoId1Norm = repoId1 > 0 ? repoId1 : -1; final int repoId2Norm = repoId2 > 0 ? repoId2 : -1; return repoId1Norm == repoId2Norm; } private LocatorId(final int repoId, @NonNull final WarehouseId warehouseId) { Check.assumeGreaterThanZero(repoId, "M_Locator_ID"); this.repoId = repoId; this.warehouseId = warehouseId; } @JsonValue public String toJson() { return warehouseId.getRepoId() + "_" + repoId; } @JsonCreator public static LocatorId fromJson(final String json) { final String[] parts = json.split("_"); if (parts.length != 2) { throw new IllegalArgumentException("Invalid json: " + json); } final int warehouseId = Integer.parseInt(parts[0]); final int locatorId = Integer.parseInt(parts[1]); return ofRepoId(warehouseId, locatorId); } public void assetWarehouseId(@NonNull final WarehouseId expectedWarehouseId) { if (!WarehouseId.equals(this.warehouseId, expectedWarehouseId)) { throw new AdempiereException("Expected " + expectedWarehouseId + " for " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\LocatorId.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerExportFilterDescriptionProviderFactory implements DocumentFilterDescriptorsProviderFactory { private static final String C_BPARTNER_EXPORT_TABLE = I_C_BPartner_Export.Table_Name; private final transient IMsgBL msgBL = Services.get(IMsgBL.class); public BPartnerExportFilterDescriptionProviderFactory() { } @Override @NonNull public DocumentFilterDescriptorsProvider createFiltersProvider(@NonNull final CreateFiltersProviderContext context) { if (!isValidTable(context.getTableName())) { return NullDocumentFilterDescriptorsProvider.instance; } return ImmutableDocumentFilterDescriptorsProvider.of( DocumentFilterDescriptor.builder() .setFilterId(BPartnerExportFilterConverter.FILTER_ID) .setFrequentUsed(true) // TODO ??? .setDisplayName(msgBL.translatable("Postal")) //
.addParameter(DocumentFilterParamDescriptor.builder() .mandatory(true) .fieldName(BPartnerExportFilterConverter.PARAM_POSTAL_FROM) .displayName(msgBL.translatable(BPartnerExportFilterConverter.PARAM_POSTAL_FROM)) .widgetType(DocumentFieldWidgetType.Text) ) .addParameter(DocumentFilterParamDescriptor.builder() .mandatory(true) .fieldName(BPartnerExportFilterConverter.PARAM_POSTAL_TO) .displayName(msgBL.translatable(BPartnerExportFilterConverter.PARAM_POSTAL_TO)) .widgetType(DocumentFieldWidgetType.Text) ) // .build() ); } private boolean isValidTable(@Nullable final String tableName) { return C_BPARTNER_EXPORT_TABLE.equals(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bpartner\filter\BPartnerExportFilterDescriptionProviderFactory.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String get(String s) { return null; } @Override public String prefix() { return "management.statsd.metrics.export"; } @Override public StatsdFlavor flavor() { return obtain(StatsdProperties::getFlavor, StatsdConfig.super::flavor); } @Override public boolean enabled() { return obtain(StatsdProperties::isEnabled, StatsdConfig.super::enabled); } @Override public String host() { return obtain(StatsdProperties::getHost, StatsdConfig.super::host); } @Override public int port() { return obtain(StatsdProperties::getPort, StatsdConfig.super::port); } @Override public StatsdProtocol protocol() { return obtain(StatsdProperties::getProtocol, StatsdConfig.super::protocol); }
@Override public int maxPacketLength() { return obtain(StatsdProperties::getMaxPacketLength, StatsdConfig.super::maxPacketLength); } @Override public Duration pollingFrequency() { return obtain(StatsdProperties::getPollingFrequency, StatsdConfig.super::pollingFrequency); } @Override public Duration step() { return obtain(StatsdProperties::getStep, StatsdConfig.super::step); } @Override public boolean publishUnchangedMeters() { return obtain(StatsdProperties::isPublishUnchangedMeters, StatsdConfig.super::publishUnchangedMeters); } @Override public boolean buffered() { return obtain(StatsdProperties::isBuffered, StatsdConfig.super::buffered); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\statsd\StatsdPropertiesConfigAdapter.java
2
请完成以下Java代码
public Money getInvoiceLineOpenAmt(I_C_InvoiceLine invoiceLine) { final InvoiceId invoiceId = InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID()); final I_C_Invoice invoice = invoiceBL.getById(invoiceId); Money openAmt = Money.of(invoiceLine.getLineNetAmt(), CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final Money matchedAmt = matchInvoiceService.getCostAmountMatched(InvoiceAndLineId.ofRepoId(invoiceId, invoiceLine.getC_InvoiceLine_ID())).orElse(null); if (matchedAmt != null) { openAmt = openAmt.subtract(matchedAmt); } return openAmt; } public void cloneAllByOrderId( @NonNull final OrderId orderId, @NonNull final OrderCostCloneMapper mapper) { final List<OrderCost> originalOrderCosts = orderCostRepository.getByOrderId(orderId); final ImmutableList<OrderCost> clonedOrderCosts = originalOrderCosts.stream() .map(originalOrderCost -> originalOrderCost.copy(mapper)) .collect(ImmutableList.toImmutableList()); orderCostRepository.saveAll(clonedOrderCosts); } public void updateOrderCostsOnOrderLineChanged(final OrderCostDetailOrderLinePart orderLineInfo) { orderCostRepository.changeByOrderLineId( orderLineInfo.getOrderLineId(), orderCost -> { orderCost.updateOrderLineInfoIfApplies(orderLineInfo, moneyService::getStdPrecision, uomConversionBL); updateCreatedOrderLineIfAny(orderCost); }); }
private void updateCreatedOrderLineIfAny(@NonNull final OrderCost orderCost) { if (orderCost.getCreatedOrderLineId() == null) { return; } CreateOrUpdateOrderLineFromOrderCostCommand.builder() .orderBL(orderBL) .moneyService(moneyService) .orderCost(orderCost) .build() .execute(); } public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId) { orderCostRepository.deleteByCreatedOrderLineId(createdOrderLineId); } public boolean isCostGeneratedOrderLine(@NonNull final OrderLineId orderLineId) { return orderCostRepository.hasCostsByCreatedOrderLineIds(ImmutableSet.of(orderLineId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostService.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName;
} public void setLastName(String lastName) { this.lastName = lastName; } public List<BookAuthorEntity> getBookAuthorEntities() { return bookAuthorEntities; } public void setBookAuthorEntities(List<BookAuthorEntity> bookAuthorEntities) { this.bookAuthorEntities = bookAuthorEntities; } @Override public String toString() { return "Author{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", books=" + bookAuthorEntities + '}'; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\specifications\join\Author.java
1
请在Spring Boot框架中完成以下Java代码
public void setInvoiceSettlementDate(ExtendedDateType value) { this.invoiceSettlementDate = value; } /** * Date/time which describes the last allowed payment date of the invoice. * * @return * possible object is * {@link ExtendedDateType } * */ public ExtendedDateType getPaymentDueDate() { return paymentDueDate; } /** * Sets the value of the paymentDueDate property. * * @param value * allowed object is * {@link ExtendedDateType } * */ public void setPaymentDueDate(ExtendedDateType value) { this.paymentDueDate = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}AdditionalReference" maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "additionalReference" }) public static class RelatedReferences {
@XmlElement(name = "AdditionalReference") protected List<ReferenceType> additionalReference; /** * Other references if no dedicated field is available.Gets the value of the additionalReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the additionalReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdditionalReference().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getAdditionalReference() { if (additionalReference == null) { additionalReference = new ArrayList<ReferenceType>(); } return this.additionalReference; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\REMADVListLineItemExtensionType.java
2
请完成以下Java代码
public ClientRegistration getClientRegistration() { return this.clientRegistration; } /** * Returns the {@link OAuth2AuthorizationExchange authorization exchange}. * @return the {@link OAuth2AuthorizationExchange} */ public OAuth2AuthorizationExchange getAuthorizationExchange() { return this.authorizationExchange; } /** * Returns the {@link OAuth2AccessToken access token}. * @return the {@link OAuth2AccessToken} */ public OAuth2AccessToken getAccessToken() { return this.accessToken; }
/** * Returns the {@link OAuth2RefreshToken refresh token}. * @return the {@link OAuth2RefreshToken} */ public @Nullable OAuth2RefreshToken getRefreshToken() { return this.refreshToken; } /** * Returns the additional parameters * @return the additional parameters */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2AuthorizationCodeAuthenticationToken.java
1
请完成以下Java代码
public static void parseDepends (List<String> list, String parseString) { final IStringExpression expression = Services.get(IExpressionFactory.class).compile(parseString, IStringExpression.class); parseDepends(list, expression); } // parseDepends // metas: private static String getValue(Evaluatee source, String variable) { return CtxNames.parse(variable).getValueAsString(source); } public static String parseContext(Evaluatee source, String expression) { if (expression == null || expression.length() == 0) return null; // int pos = 0; String finalExpression = expression; while (pos < expression.length()) { int first = expression.indexOf('@', pos); if (first == -1) return expression; int second = expression.indexOf('@', first+1); if (second == -1) { s_log.error("No second @ in Logic: {}", expression); return null; } String variable = expression.substring(first+1, second); String eval = getValue(source, variable); s_log.trace("{}={}", variable, eval); if (Check.isEmpty(eval, true)) { eval = Env.getContext(Env.getCtx(), variable); } finalExpression = finalExpression.replaceFirst("@"+variable+"@", eval); //
pos = second + 1; } return finalExpression; } public static boolean hasVariable(Evaluatee source, String variableName) { if (source instanceof Evaluatee2) { final Evaluatee2 source2 = (Evaluatee2)source; return source2.has_Variable(variableName); } else { return !Check.isEmpty(source.get_ValueAsString(variableName)); } } public static void parseDepends (final List<String> list, final IExpression<?> expr) { if (expr == null) { return; } list.addAll(expr.getParameterNames()); } } // Evaluator
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Evaluator.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Program program = (Program)o; return Objects.equals(this.authenticityVerification, program.authenticityVerification) && Objects.equals(this.fulfillmentProgram, program.fulfillmentProgram); } @Override public int hashCode() { return Objects.hash(authenticityVerification, fulfillmentProgram); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Program {\n"); sb.append(" authenticityVerification: ").append(toIndentedString(authenticityVerification)).append("\n");
sb.append(" fulfillmentProgram: ").append(toIndentedString(fulfillmentProgram)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Program.java
2
请完成以下Java代码
private static class DelegatingServiceInstance implements ServiceInstance { final ServiceInstance delegate; private final DiscoveryLocatorProperties properties; private DelegatingServiceInstance(ServiceInstance delegate, DiscoveryLocatorProperties properties) { this.delegate = delegate; this.properties = properties; } @Override public String getServiceId() { if (properties.isLowerCaseServiceId()) { return delegate.getServiceId().toLowerCase(Locale.ROOT); } return delegate.getServiceId(); } @Override public String getHost() { return delegate.getHost(); } @Override public int getPort() { return delegate.getPort(); } @Override public boolean isSecure() { return delegate.isSecure(); }
@Override public URI getUri() { return delegate.getUri(); } @Override public @Nullable Map<String, String> getMetadata() { return delegate.getMetadata(); } @Override public @Nullable String getScheme() { return delegate.getScheme(); } @Override public String toString() { return new ToStringCreator(this).append("delegate", delegate).append("properties", properties).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryClientRouteDefinitionLocator.java
1
请完成以下Java代码
public IStringExpression toStringExpressionWithColumnNameAlias() { return IStringExpression.composer() .append("(").append(toStringExpression()).append(") AS ").append(columnNameAlias) .build(); } public IStringExpression toStringExpression() { final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias) ? joinOnTableNameOrAlias + "." + joinOnColumnName : joinOnColumnName; if (sqlExpression == null) { return ConstantStringExpression.of(joinOnColumnNameFQ); } else { return sqlExpression.toStringExpression(joinOnColumnNameFQ); } } public IStringExpression toOrderByStringExpression() { final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias) ? joinOnTableNameOrAlias + "." + joinOnColumnName : joinOnColumnName; if (sqlExpression == null) { return ConstantStringExpression.of(joinOnColumnNameFQ); } else
{ return sqlExpression.toOrderByStringExpression(joinOnColumnNameFQ); } } public SqlSelectDisplayValue withJoinOnTableNameOrAlias(@Nullable final String joinOnTableNameOrAlias) { return !Objects.equals(this.joinOnTableNameOrAlias, joinOnTableNameOrAlias) ? toBuilder().joinOnTableNameOrAlias(joinOnTableNameOrAlias).build() : this; } public String toSqlOrderByUsingColumnNameAlias() { final String columnNameAliasFQ = joinOnTableNameOrAlias != null ? joinOnTableNameOrAlias + "." + columnNameAlias : columnNameAlias; if (sqlExpression != null) { return columnNameAliasFQ + "[" + sqlExpression.getNameSqlArrayIndex() + "]"; } else { return columnNameAliasFQ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlSelectDisplayValue.java
1
请完成以下Java代码
public void setCpblties(PointOfInteractionCapabilities1 value) { this.cpblties = value; } /** * Gets the value of the cmpnt property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the cmpnt property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCmpnt().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link PointOfInteractionComponent1 } * * */ public List<PointOfInteractionComponent1> getCmpnt() { if (cmpnt == null) { cmpnt = new ArrayList<PointOfInteractionComponent1>(); } return this.cmpnt; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PointOfInteraction1.java
1
请完成以下Java代码
public DBFunctions retrieveByTableName(@NonNull final String tableName) { final ImmutableList<DBFunction> functions = retrieveAvailableImportFunctionsByTableName(tableName); final List<DBFunction> availableAfterRowFunctions = new ArrayList<>(); final List<DBFunction> availableAfterAllFunctions = new ArrayList<>(); for (final DBFunction function : functions) { if (isEligibleAfterRowFunction(function)) { availableAfterRowFunctions.add(function); } else if (isEligibleAfterAllFunction(function)) { availableAfterAllFunctions.add(function); } else { log.warn("Function {} from schema {} is not eliglible for importing process!", function.getName(), function.getSchema()); } } return DBFunctions.builder() .tableName(tableName) .availableAfterRowFunctions(ImmutableList.copyOf(availableAfterRowFunctions)) .availableAfterAllFunctions(ImmutableList.copyOf(availableAfterAllFunctions)) .build(); } private ImmutableList<DBFunction> retrieveAvailableImportFunctionsByTableName(@NonNull final String tableName) { final StringBuilder sql = new StringBuilder("SELECT routines.specific_schema, routines.routine_name FROM information_schema.routines ") .append(" WHERE routines.routine_name ILIKE ? ") .append(" ORDER BY routines.routine_name "); final List<Object> sqlParams = Arrays.<Object> asList(tableName + "_%"); return ImmutableList.copyOf(DB.retrieveRowsOutOfTrx(sql.toString(), sqlParams, rs -> retrieveDBFunction(rs))); }
private DBFunction retrieveDBFunction(@NonNull final ResultSet rs) throws SQLException { final String specific_schema = rs.getString("specific_schema"); final String routine_name = rs.getString("routine_name"); return DBFunction.builder() .schema(specific_schema) .name(routine_name) .build(); } private boolean isEligibleAfterRowFunction(@NonNull final DBFunction function) { final String routine_name = function.getName(); return StringUtils.containsIgnoreCase(routine_name, IMPORT_AFTER_ROW); } private boolean isEligibleAfterAllFunction(@NonNull final DBFunction function) { final String routine_name = function.getName(); return StringUtils.containsIgnoreCase(routine_name, IMPORT_AFTER_ALL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\DBFunctionsRepository.java
1
请完成以下Java代码
public String getFillValue() { return "#585858"; } @Override public String getDValue() { return " M20.820839 9.171502 L17.36734 22.58992 L11.54138 12.281818999999999 L7.3386512 18.071607 L11.048949 4.832305699999999 L16.996148 14.132659 L20.820839 9.171502 z"; } public void drawIcon(final int imageX, final int imageY, final int iconPadding, final SVGGraphics2D svgGenerator) { Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG); gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 4) + "," + (imageY - 4) + ")"); Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG); pathTag.setAttributeNS(null, "d", this.getDValue()); pathTag.setAttributeNS(null, "style", this.getStyleValue()); pathTag.setAttributeNS(null, "fill", this.getFillValue()); pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); gTag.appendChild(pathTag); svgGenerator.getDOMTreeManager().appendGroup(gTag, null); }
@Override public String getAnchorValue() { return null; } @Override public String getStyleValue() { return "stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10"; } @Override public String getStrokeWidth() { return null; } }
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\ErrorThrowIconType.java
1
请完成以下Java代码
public DecisionTask newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionTaskImpl(instanceContext); } }); decisionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DECISION_REF) .build(); /** Camunda extensions */ camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE) .namespace(CAMUNDA_NS) .build(); camundaDecisionBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_BINDING) .namespace(CAMUNDA_NS) .build(); camundaDecisionVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_VERSION) .namespace(CAMUNDA_NS) .build();
camundaDecisionTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_TENANT_ID) .namespace(CAMUNDA_NS) .build(); camundaMapDecisionResultAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_MAP_DECISION_RESULT) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class) .build(); decisionRefExpressionChild = sequenceBuilder.element(DecisionRefExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class CompleteWFActivityHandler implements WFActivityHandler, UserConfirmationSupport { public static final WFActivityType HANDLED_ACTIVITY_TYPE = WFActivityType.ofString("huConsolidation.complete"); @NonNull private final IMsgBL msgBL = Services.get(IMsgBL.class); @NonNull private final HUConsolidationJobService jobService; @Override public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(msgBL.getMsg(jsonOpts.getAdLanguage(), ARE_YOU_SURE)) .build());
} @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity) { final HUConsolidationJob job = getHUConsolidationJob(wfProcess); return computeActivityState(job); } public static WFActivityStatus computeActivityState(final HUConsolidationJob job) { // TODO return WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.assertActivityType(HANDLED_ACTIVITY_TYPE); return HUConsolidationApplication.mapJob(request.getWfProcess(), jobService::complete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\CompleteWFActivityHandler.java
2
请完成以下Java代码
public void actionPerformed(ActionEvent e) { String newText = String.valueOf(getPassword()); // Data Binding try { fireVetoableChange(m_columnName, m_oldText, newText); } catch (PropertyVetoException pve) {} } // actionPerformed /** * Set Field/WindowNo for ValuePreference * @param mField field */ public void setField (GridField mField) { m_mField = mField;
} // setField @Override public GridField getField() { return m_mField; } // metas: Ticket#2011062310000013 public boolean isAutoCommit() { return false; } } // VPassword
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPassword.java
1
请在Spring Boot框架中完成以下Java代码
final class PropertiesJdbcConnectionDetails implements JdbcConnectionDetails { private final DataSourceProperties properties; PropertiesJdbcConnectionDetails(DataSourceProperties properties) { this.properties = properties; } @Override public @Nullable String getUsername() { return this.properties.determineUsername(); } @Override public @Nullable String getPassword() { return this.properties.determinePassword(); }
@Override public String getJdbcUrl() { return this.properties.determineUrl(); } @Override public String getDriverClassName() { return this.properties.determineDriverClassName(); } @Override public @Nullable String getXaDataSourceClassName() { return (this.properties.getXa().getDataSourceClassName() != null) ? this.properties.getXa().getDataSourceClassName() : JdbcConnectionDetails.super.getXaDataSourceClassName(); } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\PropertiesJdbcConnectionDetails.java
2
请完成以下Java代码
public Enumeration<URL> run() throws IOException { return bundle.getResources(name); } }); } catch (PrivilegedActionException e) { Exception cause = e.getException(); if (cause instanceof IOException) throw (IOException) cause; else throw (RuntimeException) cause; } if (urls == null) { urls = Collections.enumeration(new ArrayList<>()); } return urls; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class clazz; try { clazz = findClass(name); } catch (ClassNotFoundException cnfe) { if (classLoader != null) { try { clazz = classLoader.loadClass(name); } catch (ClassNotFoundException e) { throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId() + " (" + bundle.getSymbolicName() + ")", cnfe); } } else { throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId() + " (" + bundle.getSymbolicName() + ")", cnfe); } } if (resolve) { resolveClass(clazz); } return clazz; } public Bundle getBundle() { return bundle; } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\BundleDelegatingClassLoader.java
1
请完成以下Java代码
public void put(@NonNull final ADRefList adRefList) { map.put(adRefList.getReferenceId(), adRefList); } @Override public void createRefListItem(@NonNull final ADRefListItemCreateRequest request) { final ADRefList refList = getById(request.getReferenceId()); final ADRefList refListChanged = refList.toBuilder() .items(ImmutableList.<ADRefListItem>builder() .addAll(refList.getItems()) .add(ADRefListItem.builder() .referenceId(request.getReferenceId()) .refListId(ADRefListId.ofRepoId(nextAD_Ref_List_ID.getAndIncrement())) .value(request.getValue()) .valueName(request.getValue()) .name(request.getName()) .build()) .build()) .build(); map.put(refListChanged.getReferenceId(), refListChanged); } @Override public ADRefList getById(@NonNull final ReferenceId adReferenceId) {
final ADRefList adRefList = autoCreateOnDemand ? map.computeIfAbsent(adReferenceId, AdRefListRepositoryMocked::newDummyADRefList) : map.get(adReferenceId); if (adRefList == null) { throw new AdempiereException("No List Reference found for " + adReferenceId); } return adRefList; } private static ADRefList newDummyADRefList(@NonNull final ReferenceId referenceId) { return ADRefList.builder() .referenceId(referenceId) .name("Auto generated for " + referenceId) .items(ImmutableList.of()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ad_reference\AdRefListRepositoryMocked.java
1
请完成以下Java代码
public List<I_M_DeliveryDay> retrieveDeliveryDaysForTourInstance(final I_M_Tour_Instance tourInstance) { Check.assumeNotNull(tourInstance, "tourInstance not null"); final IQueryBuilder<I_M_DeliveryDay> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_M_DeliveryDay.class, tourInstance) // .addOnlyActiveRecordsFilter() // get all .addEqualsFilter(I_M_DeliveryDay.COLUMN_M_Tour_Instance_ID, tourInstance.getM_Tour_Instance_ID()); queryBuilder.orderBy() .addColumn(I_M_DeliveryDay.COLUMN_SeqNo, Direction.Ascending, Nulls.Last); return queryBuilder .create() .list(); } @Override public boolean isDeliveryDayMatches(final I_M_DeliveryDay deliveryDay, final IDeliveryDayQueryParams params) { if (deliveryDay == null) { return false; } return createDeliveryDayMatcher(params) .accept(deliveryDay); } @Override public List<I_M_DeliveryDay> retrieveDeliveryDays(final I_M_Tour tour, final Timestamp deliveryDate) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_M_DeliveryDay> queryBuilder = queryBL.createQueryBuilder(I_M_DeliveryDay.class, tour) .addEqualsFilter(I_M_DeliveryDay.COLUMN_M_Tour_ID, tour.getM_Tour_ID()) .addEqualsFilter(I_M_DeliveryDay.COLUMN_DeliveryDate, deliveryDate, DateTruncQueryFilterModifier.DAY) .addOnlyActiveRecordsFilter(); queryBuilder.orderBy() .addColumn(I_M_DeliveryDay.COLUMN_DeliveryDate, Direction.Ascending, Nulls.Last); return queryBuilder .create()
.list(); } @Override public I_M_DeliveryDay_Alloc retrieveDeliveryDayAllocForModel(final IContextAware context, final IDeliveryDayAllocable deliveryDayAllocable) { Check.assumeNotNull(deliveryDayAllocable, "deliveryDayAllocable not null"); final String tableName = deliveryDayAllocable.getTableName(); final int adTableId = Services.get(IADTableDAO.class).retrieveTableId(tableName); final int recordId = deliveryDayAllocable.getRecord_ID(); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_DeliveryDay_Alloc.class, context) .addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_AD_Table_ID, adTableId) .addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_Record_ID, recordId) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_M_DeliveryDay_Alloc.class); } @Override public boolean hasAllocations(final I_M_DeliveryDay deliveryDay) { Check.assumeNotNull(deliveryDay, "deliveryDay not null"); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_DeliveryDay_Alloc.class, deliveryDay) .addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_M_DeliveryDay_ID, deliveryDay.getM_DeliveryDay_ID()) .addOnlyActiveRecordsFilter() .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\DeliveryDayDAO.java
1
请完成以下Java代码
public static ReportResultData ofFile(final @NotNull File file, @NotNull final String reportFilename) { return ReportResultData.builder() .reportData(new FileSystemResource(file)) .reportFilename(reportFilename) .reportContentType(MimeType.getMimeType(reportFilename)) .build(); } @JsonIgnore public boolean isEmpty() { try { return reportData.contentLength() <= 0; } catch (final IOException e) { return true; // reportdata couldn't be resolved, so we say it's empty } } public File writeToTemporaryFile(@NonNull final String filenamePrefix) { final File file = createTemporaryFile(filenamePrefix); try { FileUtils.copyInputStreamToFile(reportData.getInputStream(), file); return file; }
catch (final IOException ex) { throw new AdempiereException("Failed writing " + file.getAbsolutePath(), ex); } } @NonNull private File createTemporaryFile(@NonNull final String filenamePrefix) { try { final String ext = MimeType.getExtensionByType(reportContentType); final String suffix = Check.isNotBlank(ext) ? "." + ext : ""; return File.createTempFile(filenamePrefix, suffix); } catch (final IOException ex) { throw new AdempiereException("Failed creating temporary file with `" + filenamePrefix + "` prefix", ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ReportResultData.java
1
请完成以下Java代码
public class Foo { private long id; private String name; public Foo() { super(); } public Foo(final String name) { super(); this.name = name; } public Foo(final long id, final String name) { super(); this.id = id; this.name = name; } // API
public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } }
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\dto\Foo.java
1
请完成以下Java代码
protected String getDbVersion() { return getProperty(getSchemaVersionPropertyName(), false); } protected int getChangeLogVersionOrder(String changeLogVersion) { return Integer.parseInt(changeLogVersion); } protected ChangeLogVersion getChangeLogVersion() { String changeLogTableName = getChangeLogTableName(); if (changeLogTableName != null && isTablePresent(changeLogTableName)) { SchemaManagerDatabaseConfiguration databaseConfiguration = getDatabaseConfiguration(); if (!databaseConfiguration.isTablePrefixIsSchema()) { changeLogTableName = prependDatabaseTablePrefix(changeLogTableName); } try (PreparedStatement statement = databaseConfiguration.getConnection() .prepareStatement("select ID from " + changeLogTableName + " order by DATEEXECUTED")) { int latestChangeLogVersionOrder = 0; String changeLogVersion = null; try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { String changeLogVersionId = resultSet.getString(1); int changeLogVersionOrder = getChangeLogVersionOrder(changeLogVersionId); if (changeLogVersionOrder > latestChangeLogVersionOrder) {
// Even though we are ordering by DATEEXECUTED, and the last ID should be the last executed one. // It is still possible that there are multiple entries with the same DATEEXECUTED value and the order might not be correct. // e.g. MySQL 8.0 sometimes does not return the correct order. changeLogVersion = changeLogVersionId; latestChangeLogVersionOrder = changeLogVersionOrder; } } } if (changeLogVersion != null) { return new ChangeLogVersion(changeLogVersion, getDbVersionForChangelogVersion(changeLogVersion)); } } catch (SQLException e) { throw new RuntimeException("Failed to get change log version from " + changeLogTableName, e); } } return new ChangeLogVersion(null, getDbVersionForChangelogVersion(null)); } public record ChangeLogVersion(String version, String dbVersion) { } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\EngineSqlScriptBasedDbSchemaManager.java
1
请完成以下Java代码
public class ReferenceType { @XmlAnyElement(lax = true) protected List<Object> any; @XmlAttribute(name = "URI", required = true) @XmlSchemaType(name = "anyURI") protected String uri; /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Object } * * */ public List<Object> getAny() { if (any == null) {
any = new ArrayList<Object>(); } return this.any; } /** * Gets the value of the uri property. * * @return * possible object is * {@link String } * */ public String getURI() { return uri; } /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setURI(String value) { this.uri = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\ReferenceType.java
1
请完成以下Java代码
public class BoilerPlateMenuAction extends AbstractContextMenuAction implements IEditorContextPopupMenuComposer { @Override public String getName() { return null; } @Override public String getIcon() { return null; } @Override public boolean isAvailable() { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); if (gridField == null) { return false; } final int displayType = gridField.getDisplayType(); if (displayType == DisplayType.String || displayType == DisplayType.Text || displayType == DisplayType.TextLong) { return true; } return false; } @Override public boolean isRunnable() { return true; } @Override public void run() { throw new UnsupportedOperationException(); }
@Override public boolean createUI(java.awt.Container parent) { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); final Container textComponent = (Container)editor; final List<JMenuItem> items = BoilerPlateMenu.createMenuElements(textComponent, gridField); if (items == null || items.isEmpty()) { return false; } for (JMenuItem item : items) { parent.add(item); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\BoilerPlateMenuAction.java
1
请完成以下Java代码
public boolean accept(final IValidationContext evalCtx, final NamePair item) { final String valueType = evalCtx.get_ValueAsString(I_M_Attribute.COLUMNNAME_AttributeValueType); // AttributeValueType not set yet => don't accept any JavaClass if (Check.isEmpty(valueType)) { return false; } // If AttributeValueType is List we accept this JavaClass right away // because attribute's handler supported value type can only be Number or String so we cannot validate if (X_M_Attribute.ATTRIBUTEVALUETYPE_List.equals(valueType)) { return true; } // // Get I_AD_JavaClass final int adJavaClassId = Integer.parseInt(item.getID()); final I_AD_JavaClass javaClass = Services.get(IJavaClassDAO.class).retriveJavaClassOrNull(Env.getCtx(), adJavaClassId); if (null == javaClass) { return false; } // // Create Attribute Handler's instance
final IJavaClassBL javaClassBL = Services.get(IJavaClassBL.class); final IAttributeValueHandler handler = javaClassBL.newInstance(javaClass); if (null == handler) { return false; } if (handler instanceof IAttributeValueGenerator) { // // generator shall have the same type as our attribute final IAttributeValueGenerator generator = (IAttributeValueGenerator)handler; final String generatorAcceptsValueType = generator.getAttributeValueType(); return generatorAcceptsValueType == null || valueType.equals(generatorAcceptsValueType); } // // Default: accept return true; } @Override public Set<String> getParameters(@Nullable final String contextTableName) { return PARAMETERS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\AttributeGeneratorValidationRule.java
1
请在Spring Boot框架中完成以下Java代码
public static Builder withResponseValue(String responseValue) { return new Builder(responseValue); } @Override public String getNameId() { return this.nameId; } @Override public List<String> getSessionIndexes() { return this.sessionIndexes; } @Override public Map<String, List<Object>> getAttributes() { return this.attributes; } @Override public String getResponseValue() { return this.responseValue; } public static final class Builder { private final String responseValue; private String nameId; private List<String> sessionIndexes = List.of(); private Map<String, List<Object>> attributes = Map.of(); Builder(String responseValue) { this.responseValue = responseValue; } public Builder nameId(String nameId) {
this.nameId = nameId; return this; } public Builder sessionIndexes(List<String> sessionIndexes) { this.sessionIndexes = sessionIndexes; return this; } public Builder attributes(Map<String, List<Object>> attributes) { this.attributes = attributes; return this; } public Saml2ResponseAssertion build() { return new Saml2ResponseAssertion(this.responseValue, this.nameId, this.sessionIndexes, this.attributes); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2ResponseAssertion.java
2
请完成以下Java代码
public final class GlobalQRCodeVersion { public static GlobalQRCodeVersion ofInt(final int value) { if (value <= 0) { throw Check.mkEx("Invalid global QR code version: " + value); } return interner.intern(new GlobalQRCodeVersion(value)); } @JsonCreator public static GlobalQRCodeVersion ofString(final String string) { try { return ofInt(Integer.parseInt(string)); } catch (final NumberFormatException e) { throw Check.mkEx("Invalid global QR code version: `" + string + "`", e); } } private static final Interner<GlobalQRCodeVersion> interner = Interners.newStrongInterner(); private final int value; private GlobalQRCodeVersion(final int value) { this.value = value;
} @Override @Deprecated public String toString() { return String.valueOf(toJson()); } @JsonValue public int toJson() { return value; } public static boolean equals(@Nullable final GlobalQRCodeVersion o1, @Nullable final GlobalQRCodeVersion o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCodeVersion.java
1
请完成以下Java代码
public boolean startsWith(char prefix) { return name.charAt(0) == prefix; } /** * 词性的首字母<br> * 词性根据开头的几个字母可以判断大的类别 * * @return */ public char firstChar() { return name.charAt(0); } /** * 安全地将字符串类型的词性转为Enum类型,如果未定义该词性,则返回null * * @param name 字符串词性 * @return Enum词性 */ public static final Nature fromString(String name) { Integer id = idMap.get(name); if (id == null) return null; return values[id]; } /**
* 创建自定义词性,如果已有该对应词性,则直接返回已有的词性 * * @param name 字符串词性 * @return Enum词性 */ public static final Nature create(String name) { Nature nature = fromString(name); if (nature == null) return new Nature(name); return nature; } @Override public String toString() { return name; } public int ordinal() { return ordinal; } public static Nature[] values() { return values; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\tag\Nature.java
1
请完成以下Java代码
public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getTenantId() { return tenantId; }
public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public Set<String> getVariableNames() { return variables.keySet(); } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("instanceId='" + instanceId + "'") .add("scopeType='" + scopeType + "'") .add("tenantId='" + tenantId + "'") .toString(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\VariableContainerWrapper.java
1
请在Spring Boot框架中完成以下Java代码
static abstract class AbstractDisableGemFireShutdownHookSupport { boolean shouldDisableGemFireShutdownHook(@Nullable Environment environment) { return disableGemFireShutdownHookPredicate.test(environment); } /** * If we do not disable Apache Geode's {@link org.apache.geode.distributed.DistributedSystem} JRE/JVM runtime * shutdown hook then the {@link org.apache.geode.cache.Region} is prematurely closed by the JRE/JVM shutdown hook * before Spring's {@link org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor}s can do * their work of exporting data from the {@link org.apache.geode.cache.Region} as JSON. */ void disableGemFireShutdownHook(@Nullable Environment environment) { System.setProperty(GEMFIRE_DISABLE_SHUTDOWN_HOOK, Boolean.TRUE.toString()); } } static abstract class CacheDataImporterExporterReference extends AbstractCacheDataImporterExporter { static final String EXPORT_ENABLED_PROPERTY_NAME = AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME; } static class DisableGemFireShutdownHookCondition extends AbstractDisableGemFireShutdownHookSupport
implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return shouldDisableGemFireShutdownHook(context.getEnvironment()); } } public static class DisableGemFireShutdownHookEnvironmentPostProcessor extends AbstractDisableGemFireShutdownHookSupport implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { if (shouldDisableGemFireShutdownHook(environment)) { disableGemFireShutdownHook(environment); } } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\DataImportExportAutoConfiguration.java
2
请完成以下Java代码
private SqlAndParams toSql(@NonNull final IHUQueryBuilder huQuery) { final ISqlQueryFilter sqlQueryFilter = ISqlQueryFilter.cast(huQuery.createQueryFilter()); return SqlAndParams.of( sqlQueryFilter.getSql(), sqlQueryFilter.getSqlParams(Env.getCtx())); } @Override public FilterSql acceptAll() {return FilterSql.ALLOW_ALL;} @Override public FilterSql acceptAllBut(@NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds) { final SqlAndParams whereClause = !excludeHUIds.isEmpty() ? toSql(newHUQuery().addHUIdsToExclude(excludeHUIds)) : null; return FilterSql.builder() .whereClause(whereClause) .alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds)) .build(); } @Override public FilterSql acceptNone() {return FilterSql.ALLOW_NONE;} @Override public FilterSql acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds) { final SqlAndParams whereClause = fixedHUIds.isNone()
? FilterSql.ALLOW_NONE.getWhereClause() : toSql(newHUQuery().addOnlyHUIds(fixedHUIds.toSet())); return FilterSql.builder() .whereClause(whereClause) .alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds)) .build(); } @Override public FilterSql huQuery(final @NonNull IHUQueryBuilder initialHUQueryCopy, final @NonNull Set<HuId> alwaysIncludeHUIds, final @NonNull Set<HuId> excludeHUIds) { initialHUQueryCopy.setContext(PlainContextAware.newOutOfTrx()); initialHUQueryCopy.addHUIdsToAlwaysInclude(alwaysIncludeHUIds); initialHUQueryCopy.addHUIdsToExclude(excludeHUIds); return FilterSql.builder() .whereClause(toSql(initialHUQueryCopy)) .alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterDataToSqlCaseConverter.java
1
请在Spring Boot框架中完成以下Java代码
public void setUsePrettyPrint(boolean usePrettyPrint) { this.delegate.setUsePrettyPrint(usePrettyPrint); } /** * Configure whether to sign the metadata, defaults to {@code false}. * * @since 6.4 */ public void setSignMetadata(boolean signMetadata) { this.delegate.setSignMetadata(signMetadata); } /** * A tuple containing an OpenSAML {@link EntityDescriptor} and its associated * {@link RelyingPartyRegistration} * * @since 5.7 */ public static final class EntityDescriptorParameters { private final EntityDescriptor entityDescriptor; private final RelyingPartyRegistration registration; public EntityDescriptorParameters(EntityDescriptor entityDescriptor, RelyingPartyRegistration registration) { this.entityDescriptor = entityDescriptor;
this.registration = registration; } EntityDescriptorParameters(BaseOpenSamlMetadataResolver.EntityDescriptorParameters parameters) { this.entityDescriptor = parameters.getEntityDescriptor(); this.registration = parameters.getRelyingPartyRegistration(); } public EntityDescriptor getEntityDescriptor() { return this.entityDescriptor; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\metadata\OpenSaml5MetadataResolver.java
2
请在Spring Boot框架中完成以下Java代码
public void process(final Exchange exchange) throws Exception { final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class); exchange.getIn().setHeader(GetPatientsRouteConstants.HEADER_ORG_CODE, request.getOrgCode()); if (request.getAdPInstanceId() != null) { exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue()); } final String apiKey = request.getParameters().get(ExternalSystemConstants.PARAM_API_KEY); final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH); final String tenant = request.getParameters().get(ExternalSystemConstants.PARAM_TENANT); final String updatedAfter = CoalesceUtil.coalesceNotNull( request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER_OVERRIDE), request.getParameters().get(ExternalSystemConstants.PARAM_UPDATED_AFTER), Instant.ofEpochMilli(0).toString()); final AlbertaConnectionDetails albertaConnectionDetails = AlbertaConnectionDetails.builder() .apiKey(apiKey) .basePath(basePath) .tenant(tenant) .build(); final ApiClient apiClient = new ApiClient(); apiClient.setBasePath(basePath); final OrderApi orderApi = new OrderApi(apiClient); final ArrayOfOrders createdOrders = orderApi.getCreatedOrders(apiKey, GetOrdersRouteConstants.OrderStatus.CREATED.getValue(), updatedAfter); final @NonNull List<Order> ordersToImport = createdOrders == null || createdOrders.isEmpty() ? new ArrayList<>() : createdOrders; final Set<String> createOrderIds = ordersToImport.stream() .map(Order::getId) .filter(Objects::nonNull) .collect(Collectors.toSet());
final List<Order> updatedOrders = orderApi.getCreatedOrders(apiKey, GetOrdersRouteConstants.OrderStatus.UPDATED.getValue(), updatedAfter); if (updatedOrders != null && !updatedOrders.isEmpty()) { updatedOrders.stream() .filter(order -> order.getId() != null && !createOrderIds.contains(order.getId())) .forEach(ordersToImport::add); } exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_ORG_CODE, request.getOrgCode()); exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_ALBERTA_CONN_DETAILS, albertaConnectionDetails); exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_ALBERTA_PHARMACY_API, new PharmacyApi(apiClient)); exchange.setProperty(GetPatientsRouteConstants.ROUTE_PROPERTY_DOCTOR_API, new DoctorApi(apiClient)); exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_UPDATED_AFTER, new NextImportSinceTimestamp(Instant.parse(updatedAfter))); exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_COMMAND, request.getCommand()); exchange.setProperty(GetOrdersRouteConstants.ROUTE_PROPERTY_EXTERNAL_SYSTEM_CONFIG_ID, request.getExternalSystemConfigId()); exchange.getIn().setBody(ordersToImport.isEmpty() ? null : ordersToImport); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\RetrieveOrdersProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public class BuyerReceivingChangeStateComponent extends BaseChangeStateComponent { @Autowired private OrderDAO orderDAO; @Override protected void preHandle(OrderProcessContext orderProcessContext) { super.preHandle(orderProcessContext); // 插入物流单号 insertExpressNo(orderProcessContext); } /** * 插入物流单号 * @param orderProcessContext */ private void insertExpressNo(OrderProcessContext orderProcessContext) { // 获取物流单号 String expressNo = (String) orderProcessContext.getOrderProcessReq().getReqData(); // 获取订单ID String orderId = orderProcessContext.getOrderProcessReq().getOrderId();
// 构造插入请求 OrdersEntity ordersEntity = new OrdersEntity(); ordersEntity.setId(orderId); ordersEntity.setExpressNo(expressNo); // 插入物流单号 orderDAO.updateOrder(ordersEntity); } @Override public void setTargetOrderState() { this.targetOrderState = OrderStateEnum.BUYER_RECEIVING; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\changestate\BuyerReceivingChangeStateComponent.java
2
请完成以下Java代码
public void pointcut() { } @Around("pointcut()") public void around(ProceedingJoinPoint point) { long beginTime = System.currentTimeMillis(); try { // 执行方法 point.proceed(); } catch (Throwable e) { e.printStackTrace(); } // 执行时长(毫秒) long time = System.currentTimeMillis() - beginTime; // 保存日志 saveLog(point, time); } private void saveLog(ProceedingJoinPoint joinPoint, long time) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLog sysLog = new SysLog(); Log logAnnotation = method.getAnnotation(Log.class); if (logAnnotation != null) { // 注解上的描述 sysLog.setOperation(logAnnotation.value()); } // 请求的方法名 String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); // 请求的方法参数值 Object[] args = joinPoint.getArgs(); // 请求的方法参数名称 LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] paramNames = u.getParameterNames(method); if (args != null && paramNames != null) { String params = ""; for (int i = 0; i < args.length; i++) { params += " " + paramNames[i] + ": " + args[i]; } sysLog.setParams(params); } // 获取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); // 设置IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); // 模拟一个用户名 sysLog.setUsername("mrbird"); sysLog.setTime((int) time); Date date = new Date(); sysLog.setCreateTime(date); // 保存系统日志 sysLogDao.saveSysLog(sysLog); } }
repos\SpringAll-master\07.Spring-Boot-AOP-Log\src\main\java\com\springboot\aspect\LogAspect.java
1
请完成以下Java代码
public void setIsCanReport (boolean IsCanReport) { set_Value (COLUMNNAME_IsCanReport, Boolean.valueOf(IsCanReport)); } /** Get Kann Berichte erstellen. @return Users with this role can create reports */ @Override public boolean isCanReport () { Object oo = get_Value(COLUMNNAME_IsCanReport); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Ausschluß. @param IsExclude Exclude access to the data - if not selected Include access to the data */ @Override public void setIsExclude (boolean IsExclude) { set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude)); } /** Get Ausschluß. @return Exclude access to the data - if not selected Include access to the data */ @Override public boolean isExclude () { Object oo = get_Value(COLUMNNAME_IsExclude); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Schreibgeschützt. @param IsReadOnly Field is read only */
@Override public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Schreibgeschützt. @return Field is read only */ @Override public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); 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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Access.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } final OrgPermission other = EqualsBuilder.getOther(this, obj); if (other == null) { return false; } return new EqualsBuilder() .append(resource, other.resource) .append(accesses, other.accesses) .isEqual(); } @Override public String toString() { return resource + ", " + accesses; } @Override public boolean hasAccess(Access access) { return accesses.contains(access); } public boolean isReadOnly() { return hasAccess(Access.READ) && !hasAccess(Access.WRITE); } public boolean isReadWrite() { return hasAccess(Access.WRITE); } public ClientId getClientId() { return resource.getClientId(); } public OrgId getOrgId() { return resource.getOrgId(); } @Override public OrgResource getResource()
{ return resource; } @Override public Permission mergeWith(final Permission permissionFrom) { final OrgPermission orgPermissionFrom = checkCompatibleAndCast(permissionFrom); final ImmutableSet<Access> accesses = ImmutableSet.<Access> builder() .addAll(this.accesses) .addAll(orgPermissionFrom.accesses) .build(); return new OrgPermission(resource, accesses); } /** * Creates a copy of this permission but it will use the given resource. * * @return copy of this permission but having the given resource */ public OrgPermission copyWithResource(final OrgResource resource) { return new OrgPermission(resource, this.accesses); } } // OrgAccess
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermission.java
1
请在Spring Boot框架中完成以下Java代码
public void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) { super.setAccessDecisionManager(myAccessDecisionManager); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain); invoke(fi); } public void invoke(FilterInvocation fi) throws IOException, ServletException { InterceptorStatusToken token = super.beforeInvocation(fi); try { //执行下一个拦截器 fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.afterInvocation(token, null);
} } @Override public Class<?> getSecureObjectClass() { return FilterInvocation.class; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } }
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyFilterSecurityInterceptor.java
2
请完成以下Java代码
boolean isSameLastLineCommentPrefix() { return this.lastLineCommentPrefixCharacter == this.character; } boolean isCommentPrefixCharacter() { return this.character == '#' || this.character == '!'; } boolean isHyphenCharacter() { return this.character == '-'; } } /** * A single document within the properties file. */ static class Document { private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
void put(String key, OriginTrackedValue value) { if (!key.isEmpty()) { this.values.put(key, value); } } boolean isEmpty() { return this.values.isEmpty(); } Map<String, OriginTrackedValue> asMap() { return this.values; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
1
请完成以下Java代码
private void loadAndSetAlbertaRelatedInfo( @NonNull final ImmutableList.Builder<I_M_Product> productRecordsBuilder, @NonNull final HashSet<ProductId> loadedProductIds) { if (externalSystemType == null || !externalSystemType.isAlberta()) { return; } final Instant since = isSingleExport() ? Instant.now().plus(1, ChronoUnit.YEARS) //dev-note: lazy way of saying we are interested only in our product : this.since; final GetAlbertaProductsInfoRequest getAlbertaProductsInfoRequest = GetAlbertaProductsInfoRequest.builder() .since(since) .productIdSet(loadedProductIds) .pharmacyPriceListId(getPharmacyPriceListIdOrNull()) .build(); productId2AlbertaInfo = albertaProductService.getAlbertaInfoByProductId(getAlbertaProductsInfoRequest); final ImmutableSet<ProductId> productIdsLeftToLoaded = productId2AlbertaInfo .keySet() .stream() .filter(productId -> !loadedProductIds.contains(productId)) .collect(ImmutableSet.toImmutableSet()); servicesFacade.getProductsById(productIdsLeftToLoaded).forEach(productRecordsBuilder::add);
} @NonNull private Stream<I_M_Product> streamProductsToExport() { if (isSingleExport()) { Check.assumeNotNull(productIdentifier, "ProductIdentifier must be set in case of single export!"); final ProductId productId = productLookupService.resolveProductExternalIdentifier(productIdentifier, RestUtils.retrieveOrgIdOrDefault(orgCode)) .map(ProductAndHUPIItemProductId::getProductId) .orElseThrow(() -> new AdempiereException("Fail to resolve product external identifier") .appendParametersToMessage() .setParameter("ExternalIdentifier", productIdentifier)); return Stream.of(servicesFacade.getProductById(productId)); } else { return servicesFacade.streamAllProducts(since); } } private boolean isSingleExport() { return productIdentifier != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\command\GetProductsCommand.java
1
请在Spring Boot框架中完成以下Java代码
public Long sRemove(String key, Object... values) { return redisTemplate.opsForSet().remove(key, values); } @Override public List<Object> lRange(String key, long start, long end) { return redisTemplate.opsForList().range(key, start, end); } @Override public Long lSize(String key) { return redisTemplate.opsForList().size(key); } @Override public Object lIndex(String key, long index) { return redisTemplate.opsForList().index(key, index); } @Override public Long lPush(String key, Object value) { return redisTemplate.opsForList().rightPush(key, value); } @Override public Long lPush(String key, Object value, long time) { Long index = redisTemplate.opsForList().rightPush(key, value); expire(key, time); return index; }
@Override public Long lPushAll(String key, Object... values) { return redisTemplate.opsForList().rightPushAll(key, values); } @Override public Long lPushAll(String key, Long time, Object... values) { Long count = redisTemplate.opsForList().rightPushAll(key, values); expire(key, time); return count; } @Override public Long lRemove(String key, long count, Object value) { return redisTemplate.opsForList().remove(key, count, value); } }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\service\impl\RedisServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
private BigDecimal getQtyPending() {return ddOrderLine.getQtyToMove();} @NonNull private WarehouseId getWarehouseIdForType(@NonNull final CandidateType candidateType) { return computeWarehouseId(abstractDDOrderEvent, candidateType); } @NonNull private Instant getDate(@NonNull final CandidateType candidateType) { return TimeUtil.getDay(computeDate(abstractDDOrderEvent, ddOrderLine, candidateType), orgZone); } @NonNull private MainDataRecordIdentifier getMainRecordIdentifier(@NonNull final CandidateType candidateType) { return MainDataRecordIdentifier.builder() .date(getDate(candidateType)) .warehouseId(getWarehouseIdForType(candidateType)) .productDescriptor(ddOrderLine.getProductDescriptor()) .build(); } @NonNull private UpdateMainDataRequest buildUpdateMainDataRequest( @NonNull final MainDataRecordIdentifier mainDataRecordIdentifier, @NonNull final CandidateType candidateType,
@NonNull final BigDecimal qtyPending) { final UpdateMainDataRequest.UpdateMainDataRequestBuilder updateMainDataRequestBuilder = UpdateMainDataRequest.builder() .identifier(mainDataRecordIdentifier); switch (candidateType) { case DEMAND: return updateMainDataRequestBuilder.qtyDemandDDOrder(qtyPending).build(); case SUPPLY: return updateMainDataRequestBuilder.qtySupplyDDOrder(qtyPending).build(); default: throw new AdempiereException("CandidateType not supported! CandidateType = " + candidateType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderMainDataHandler.java
2
请在Spring Boot框架中完成以下Java代码
public TaskEntity createTask() { return getTaskEntityManager().create(); } @Override public void insertTask(TaskEntity taskEntity, boolean fireCreateEvent) { getTaskEntityManager().insert(taskEntity, fireCreateEvent); } @Override public void deleteTask(TaskEntity task, boolean fireEvents) { getTaskEntityManager().delete(task, fireEvents); } @Override public void deleteTasksByExecutionId(String executionId) {
getTaskEntityManager().deleteTasksByExecutionId(executionId); } public TaskEntityManager getTaskEntityManager() { return configuration.getTaskEntityManager(); } @Override public TaskEntity createTask(TaskBuilder taskBuilder) { return getTaskEntityManager().createTask(taskBuilder); } protected VariableServiceConfiguration getVariableServiceConfiguration(AbstractEngineConfiguration engineConfiguration) { return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskServiceImpl.java
2
请完成以下Java代码
private SocketConfig createSocketConfig() { SocketConfig.Builder builder = SocketConfig.custom(); this.socketConfigCustomizer.accept(builder); return builder.build(); } private ConnectionConfig createConnectionConfig(HttpClientSettings settings) { ConnectionConfig.Builder builder = ConnectionConfig.custom(); PropertyMapper map = PropertyMapper.get(); map.from(settings::connectTimeout) .as(Duration::toMillis) .to((timeout) -> builder.setConnectTimeout(timeout, TimeUnit.MILLISECONDS)); map.from(settings::readTimeout) .asInt(Duration::toMillis) .to((timeout) -> builder.setSocketTimeout(timeout, TimeUnit.MILLISECONDS)); this.connectionConfigCustomizer.accept(builder); return builder.build(); } private RequestConfig createDefaultRequestConfig() { RequestConfig.Builder builder = RequestConfig.custom(); this.defaultRequestConfigCustomizer.accept(builder); return builder.build(); } /** * Factory that can be used to optionally create a {@link TlsSocketStrategy} given an * {@link SslBundle}.
* * @since 4.0.0 */ public interface TlsSocketStrategyFactory { /** * Return the {@link TlsSocketStrategy} to use for the given bundle. * @param sslBundle the SSL bundle or {@code null} * @return the {@link TlsSocketStrategy} to use or {@code null} */ @Nullable TlsSocketStrategy getTlsSocketStrategy(@Nullable SslBundle sslBundle); } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\HttpComponentsHttpClientBuilder.java
1
请完成以下Java代码
public WebClient readWriteTimeoutClient() { HttpClient httpClient = HttpClient.create() .doOnConnected(conn -> conn .addHandler(new ReadTimeoutHandler(5, TimeUnit.SECONDS)) .addHandler(new WriteTimeoutHandler(5))); return buildWebClient(httpClient); } public WebClient sslTimeoutClient() { HttpClient httpClient = HttpClient.create() .secure(spec -> spec .sslContext(SslContextBuilder.forClient()) .defaultConfiguration(SslProvider.DefaultConfigurationType.TCP) .handshakeTimeout(Duration.ofSeconds(30)) .closeNotifyFlushTimeout(Duration.ofSeconds(10)) .closeNotifyReadTimeout(Duration.ofSeconds(10))); return buildWebClient(httpClient);
} public WebClient proxyTimeoutClient() { HttpClient httpClient = HttpClient.create() .proxy(spec -> spec .type(ProxyProvider.Proxy.HTTP) .host("http://proxy") .port(8080) .connectTimeoutMillis(3000)); return buildWebClient(httpClient); } private WebClient buildWebClient(HttpClient httpClient) { return WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\timeout\WebClientTimeoutProvider.java
1
请完成以下Java代码
public static double withMathRound(double value, int places) { double scale = Math.pow(10, places); return Math.round(value * scale) / scale; } public static double withDecimalFormatPattern(double value, int places) { DecimalFormat df2 = new DecimalFormat("#,###,###,##0.00"); DecimalFormat df3 = new DecimalFormat("#,###,###,##0.000"); if (places == 2) return Double.valueOf(df2.format(value)); else if (places == 3) return Double.valueOf(df3.format(value)); else throw new IllegalArgumentException(); } public static double withDecimalFormatLocal(double value) { DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault()); return Double.valueOf(df.format(value)); } public static String withStringFormat(double value, int places) { return String.format("%." + places + "f", value); } public static String byPaddingZeros(int value, int paddingLength) { return String.format("%0" + paddingLength + "d", value); } public static double withTwoDecimalPlaces(double value) { DecimalFormat df = new DecimalFormat("#.00"); return Double.valueOf(df.format(value)); } public static String withLargeIntegers(double value) { DecimalFormat df = new DecimalFormat("###,###,###"); return df.format(value); } public static String forPercentages(double value, Locale localisation) {
NumberFormat nf = NumberFormat.getPercentInstance(localisation); return nf.format(value); } public static String currencyWithChosenLocalisation(double value, Locale localisation) { NumberFormat nf = NumberFormat.getCurrencyInstance(localisation); return nf.format(value); } public static String currencyWithDefaultLocalisation(double value) { NumberFormat nf = NumberFormat.getCurrencyInstance(); return nf.format(value); } public static String formatScientificNotation(double value, Locale localisation) { return String.format(localisation, "%.3E", value); } public static String formatScientificNotationWithMinChars(double value, Locale localisation) { return String.format(localisation, "%12.4E", value); } }
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\formatNumber\FormatNumber.java
1
请完成以下Java代码
private static TableRecordReference extractRootRecordReference(final Document includedDocument) { if (includedDocument.isRootDocument()) { return null; } final Document rootDocument = includedDocument.getRootDocument(); final String rootTableName = rootDocument.getEntityDescriptor().getTableNameOrNull(); if (rootTableName == null) { return null; } final int rootRecordId = rootDocument.getDocumentId().toIntOr(-1); if (rootRecordId < 0) { return null; } return TableRecordReference.of(rootTableName, rootRecordId); } private static DocumentId extractDocumentId(final PO po, SqlDocumentEntityDataBindingDescriptor dataBinding) { if (dataBinding.isSingleKey())
{ return DocumentId.of(InterfaceWrapperHelper.getId(po)); } else { final List<SqlDocumentFieldDataBindingDescriptor> keyFields = dataBinding.getKeyFields(); if (keyFields.isEmpty()) { throw new AdempiereException("No primary key defined for " + dataBinding.getTableName()); } final List<Object> keyParts = keyFields.stream() .map(keyField -> po.get_Value(keyField.getColumnName())) .collect(ImmutableList.toImmutableList()); return DocumentId.ofComposedKeyParts(keyParts); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\save\DefaultSaveHandler.java
1
请完成以下Java代码
public Double getSortNo() { return sortNo; } public void setSortNo(Double sortNo) { this.sortNo = sortNo; } public Integer getMenuType() { return menuType; } public void setMenuType(Integer menuType) { this.menuType = menuType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isRoute() { return route; } public void setRoute(boolean route) { this.route = route; } public Integer getDelFlag() { return delFlag; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; }
public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public boolean getIsLeaf() { return isLeaf; } public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; } public String getPermsType() { return permsType; } public void setPermsType(String permsType) { this.permsType = permsType; } public java.lang.String getStatus() { return status; } public void setStatus(java.lang.String status) { this.status = status; } /*update_begin author:wuxianquan date:20190908 for:get set方法 */ public boolean isInternalOrExternal() { return internalOrExternal; } public void setInternalOrExternal(boolean internalOrExternal) { this.internalOrExternal = internalOrExternal; } /*update_end author:wuxianquan date:20190908 for:get set 方法 */ public boolean isHideTab() { return hideTab; } public void setHideTab(boolean hideTab) { this.hideTab = hideTab; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\SysPermissionTree.java
1
请完成以下Java代码
public I_AD_InfoColumn getAD_InfoColumn() { return _infoColumn; } public IInfoSimple getParent() { return _parent; } @Override public String toString() { final I_AD_InfoColumn infoColumn = getAD_InfoColumn(); if (infoColumn != null) { return getClass().getSimpleName() + "[" + infoColumn.getName() + "]"; } else { return super.toString(); } } @Override public final String getText() { if (editor == null) { return null; } final Object value = editor.getValue(); if (value == null) { return null; } return value.toString(); } @Override public Object getParameterValue(final int index, final boolean returnValueTo) { final Object field; if (returnValueTo) { field = getParameterToComponent(index); }
else { field = getParameterComponent(index); } if (field instanceof CEditor) { final CEditor editor = (CEditor)field; return editor.getValue(); } else { throw new AdempiereException("Component type not supported - " + field); } } /** * Method called when one of the parameter fields changed */ protected void onFieldChanged() { // parent.executeQuery(); we don't want to query each time, because we might block the search } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\AbstractInfoQueryCriteriaGeneral.java
1