instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class OrderCheckupDAO implements IOrderCheckupDAO { private final IQueryBL queryBL = Services.get(IQueryBL.class); @Override public List<I_C_Order_MFGWarehouse_Report> retrieveAllReports(final I_C_Order order) { return queryBL .createQueryBuilder(I_C_Order_MFGWarehouse_Report.class, order) // .addOnlyActiveRecordsFilter() // return all of them .addEqualsFilter(I_C_Order_MFGWarehouse_Report.COLUMN_C_Order_ID, order.getC_Order_ID()) .orderBy() .addColumn(I_C_Order_MFGWarehouse_Report.COLUMN_C_Order_MFGWarehouse_Report_ID) .endOrderBy() .create() .list(I_C_Order_MFGWarehouse_Report.class);
} @Override public List<I_C_Order_MFGWarehouse_ReportLine> retrieveAllReportLines(final I_C_Order_MFGWarehouse_Report report) { return queryBL .createQueryBuilder(I_C_Order_MFGWarehouse_ReportLine.class, report) // .addOnlyActiveRecordsFilter() // return all of them .addEqualsFilter(I_C_Order_MFGWarehouse_ReportLine.COLUMN_C_Order_MFGWarehouse_Report_ID, report.getC_Order_MFGWarehouse_Report_ID()) .orderBy() .addColumn(I_C_Order_MFGWarehouse_ReportLine.COLUMN_C_Order_MFGWarehouse_ReportLine_ID) .endOrderBy() .create() .list(I_C_Order_MFGWarehouse_ReportLine.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\impl\OrderCheckupDAO.java
1
请完成以下Java代码
public String getTreeType() { return m_TreeType; } // getTreeType /** * Get Tree * @return tree */ public MTree getTree() { return m_tree; } // getTreeType /** * Get Where Clause * @param ID start node * @return ColumnName = 1 or ( ColumnName = 1 OR ColumnName = 2 OR ColumnName = 3) */ public String getWhereClause (int ID) { String ColumnName = getElementType().getColumnName(); // MTreeNode node = m_tree.getRoot().findNode(ID); log.trace("Root=" + node); // StringBuilder result = null; if (node != null && node.isSummary ()) { Enumeration<TreeNode> en = node.preorderEnumeration (); StringBuilder sb = new StringBuilder (); while (en.hasMoreElements ()) { MTreeNode nn = (MTreeNode)en.nextElement (); if (!nn.isSummary ()) { if (sb.length () > 0) { sb.append (" OR "); } sb.append (ColumnName); sb.append ('='); sb.append (nn.getNode_ID ()); log.trace("- " + nn); } else log.trace("- skipped parent (" + nn + ")"); } result = new StringBuilder (" ( "); result.append (sb); result.append (" ) "); } else // not found or not summary result = new StringBuilder (ColumnName).append("=").append(ID); // log.trace(result.toString()); return result.toString(); } // getWhereClause /** * Get Child IDs * @param ID start node * @return array if IDs */ public Integer[] getChildIDs (int ID) { ArrayList<Integer> list = new ArrayList<Integer>(); // MTreeNode node = m_tree.getRoot().findNode(ID); log.trace("Root=" + node); // if (node != null && node.isSummary()) { Enumeration en = node.preorderEnumeration(); while (en.hasMoreElements())
{ MTreeNode nn = (MTreeNode)en.nextElement(); if (!nn.isSummary()) { list.add(new Integer(nn.getNode_ID())); log.trace("- " + nn); } else log.trace("- skipped parent (" + nn + ")"); } } else // not found or not summary list.add(new Integer(ID)); // Integer[] retValue = new Integer[list.size()]; list.toArray(retValue); return retValue; } // getWhereClause /** * String Representation * @return info */ @Override public String toString() { StringBuilder sb = new StringBuilder("MReportTree[ElementType="); sb.append(elementType).append(",TreeType=").append(m_TreeType) .append(",").append(m_tree) .append("]"); return sb.toString(); } // toString } // MReportTree
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportTree.java
1
请完成以下Java代码
public class Library { public static final int MAX_BOOKS = 10000; private static final Logger LOGGER = Logger.getLogger(Library.class.getName()); public static int totalBooks; public static List<String> lines; static { totalBooks = 0; } static { try { lines = Files.readAllLines(Paths.get("file.txt")); } catch (IOException e) { throw new RuntimeException(e); } } private final String name; private final int books; public Library(String name, int books) { this.name = name; this.books = books; totalBooks += books; } public static int getTotalBooks() { return totalBooks; } public static void printLibraryDetails(Library library) { LOGGER.info("Library Name: " + library.name); LOGGER.info("Number of Books: " + library.books); } public static String getLibraryInformation(Library library) { return library.getName() + " has " + library.getBooks() + " books."; } public static synchronized void addBooks(int count) { totalBooks += count; } public String getName() { return name; } public int getBooks() { return books; } public static class LibraryStatistics {
public static int getAverageBooks(Library[] libraries) { int total = 0; for (Library library : libraries) { total += library.books; } return libraries.length > 0 ? total / libraries.length : 0; } } public static class Book { private final String title; private final String author; public Book(String title, String author) { this.title = title; this.author = author; } public void displayBookDetails() { LOGGER.info("Book Title: " + title); LOGGER.info("Book Author: " + author); } } public record BookRecord(String title, String author) { } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\statickeyword\Library.java
1
请完成以下Java代码
public void setI_Pharma_BPartner_ID (int I_Pharma_BPartner_ID) { if (I_Pharma_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_I_Pharma_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_I_Pharma_BPartner_ID, Integer.valueOf(I_Pharma_BPartner_ID)); } /** Get Import Pharma BPartners. @return Import Pharma BPartners */ @Override public int getI_Pharma_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_Pharma_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
} /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_BPartner.java
1
请完成以下Java代码
public final class ALoginRes_vi extends ListResourceBundle { // TODO Run native2ascii to convert everything to plain ASCII !! /** Translation Content */ static final Object[][] contents = new String[][] { { "Connection", "K\u1EBFt n\u1ED1i" }, { "Defaults", "M\u1EB7c nhi�n" }, { "Login", "\u0110\u0103ng nh\u1EADp" }, { "File", "H\u1EC7 th\u1ED1ng" }, { "Exit", "Tho�t" }, { "Help", "Gi�p \u0111\u1EE1" }, { "About", "Gi\u1EDBi thi\u1EC7u" }, { "Host", "M�y ch\u1EE7" }, { "Database", "C\u01A1 s\u1EDF d\u1EEF li\u1EC7u" }, { "User", "T�n ng\u01B0\u1EDDi d�ng" }, { "EnterUser", "H�y nh\u1EADp t�n ng\u01B0\u1EDDi d�ng" }, { "Password", "M\u1EADt kh\u1EA9u" }, { "EnterPassword", "H�y nh\u1EADp m\u1EADt kh\u1EA9u" }, { "Language", "Ng�n ng\u1EEF" }, { "SelectLanguage", "H�y ch\u1ECDn ng�n ng\u1EEF" }, { "Role", "Vai tr�" }, { "Client", "C�ng ty" }, { "Organization", "\u0110\u01A1n v\u1ECB" }, { "Date", "Ng�y" }, { "Warehouse", "Kho h�ng" }, { "Printer", "M�y in" }, { "Connected", "\u0110� k\u1EBFt n\u1ED1i" }, { "NotConnected", "Ch\u01B0a k\u1EBFt n\u1ED1i \u0111\u01B0\u1EE3c" }, { "DatabaseNotFound", "Kh�ng t�m th\u1EA5y CSDL" }, { "UserPwdError", "Ng\u01B0\u1EDDi d�ng v� m\u1EADt kh\u1EA9u kh�ng kh\u1EDBp nhau" },
{ "RoleNotFound", "Kh�ng t�m th\u1EA5y vai tr� n�y" }, { "Authorized", "\u0110� \u0111\u01B0\u1EE3c ph�p" }, { "Ok", "\u0110\u1ED3ng �" }, { "Cancel", "H\u1EE7y" }, { "VersionConflict", "X\u1EA3y ra tranh ch\u1EA5p phi�n b\u1EA3n:" }, { "VersionInfo", "Th�ng tin v\u1EC1 phi�n b\u1EA3n" }, { "PleaseUpgrade", "Vui l�ng n�ng c\u1EA5p ch\u01B0\u01A1ng tr�nh" } }; /** * Get Contents * @return context */ public Object[][] getContents() { return contents; } // getContents } // ALoginRes
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_vi.java
1
请完成以下Java代码
protected void onRefresh() { super.onRefresh(); ConfigurableListableBeanFactory currentBeanFactory = getBeanFactory(); if (this.beanFactory != null) { Arrays.stream(ArrayUtils.nullSafeArray(this.beanFactory.getSingletonNames(), String.class)) .filter(singletonBeanName -> !currentBeanFactory.containsSingleton(singletonBeanName)) .forEach(singletonBeanName -> currentBeanFactory .registerSingleton(singletonBeanName, this.beanFactory.getSingleton(singletonBeanName))); if (isCopyConfigurationEnabled()) { currentBeanFactory.copyConfigurationFrom(this.beanFactory); } } } /** * Stores a reference to the previous {@link ConfigurableListableBeanFactory} in order to copy its configuration * and state on {@link ApplicationContext} refresh invocations. * * @see #getBeanFactory() */ @Override
protected void prepareRefresh() { this.beanFactory = (DefaultListableBeanFactory) SpringExtensions.safeGetValue(this::getBeanFactory); super.prepareRefresh(); } /** * @inheritDoc */ @Override public void register(Class<?>... componentClasses) { Arrays.stream(ArrayUtils.nullSafeArray(componentClasses, Class.class)) .filter(Objects::nonNull) .forEach(this.componentClasses::add); } /** * @inheritDoc */ @Override public void scan(String... basePackages) { Arrays.stream(ArrayUtils.nullSafeArray(basePackages, String.class)) .filter(StringUtils::hasText) .forEach(this.basePackages::add); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\annotation\RefreshableAnnotationConfigApplicationContext.java
1
请在Spring Boot框架中完成以下Java代码
public class PersonDaoImpl implements PersonDao { @PersistenceContext private EntityManager em; @Override public Person save(final Person person) { em.persist(person); return person; } @Override public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).where(person.firstname.eq(firstname)).fetch(); } @Override public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch(); } @Override public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person;
return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch(); } @Override public int findMaxAge() { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).select(person.age.max()).fetchFirst(); } @Override public Map<String, Integer> findMaxAgeByName() { final JPAQueryFactory query = new JPAQueryFactory(JPQLTemplates.DEFAULT, em); final QPerson person = QPerson.person; return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age))); } }
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\dao\PersonDaoImpl.java
2
请完成以下Java代码
public IfPart getIfPart() { return ifPartChild.getChild(this); } public void setIfPart(IfPart ifPart) { ifPartChild.setChild(this, ifPart); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Sentry.class, CMMN_ELEMENT_SENTRY) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Sentry>() { public Sentry newInstance(ModelTypeInstanceContext instanceContext) { return new SentryImpl(instanceContext); } });
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); onPartCollection = sequenceBuilder.elementCollection(OnPart.class) .build(); ifPartChild = sequenceBuilder.element(IfPart.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\SentryImpl.java
1
请完成以下Java代码
public RequestId getRequestIdForMessageId(@NonNull final String messageId) { final List<Integer> requestIds = Services.get(IQueryBL.class).createQueryBuilder(I_C_Mail.class) .addEqualsFilter(I_C_Mail.COLUMN_InitialMessageID, messageId) .addNotNull(I_C_Mail.COLUMN_R_Request_ID) .orderBy(I_C_Mail.COLUMN_R_Request_ID) .create() .listDistinct(I_C_Mail.COLUMNNAME_R_Request_ID, Integer.class); if (requestIds.isEmpty()) { return null; } return RequestId.ofRepoId(requestIds.get(0)); } private static final class InboundEMailAttachmentDataSource implements DataSource { private InboundEMailAttachment attachment; private InboundEMailAttachmentDataSource(@NonNull final InboundEMailAttachment attachment) { this.attachment = attachment; } @Override
public String getName() { return attachment.getFilename(); } @Override public String getContentType() { return attachment.getContentType(); } @Override public InputStream getInputStream() throws IOException { return Files.newInputStream(attachment.getTempFile()); } @Override public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailRepository.java
1
请完成以下Java代码
public class SequenceflowValidator extends ProcessLevelValidator { @Override protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) { List<SequenceFlow> sequenceFlows = process.findFlowElementsOfType(SequenceFlow.class); for (SequenceFlow sequenceFlow : sequenceFlows) { String sourceRef = sequenceFlow.getSourceRef(); String targetRef = sequenceFlow.getTargetRef(); if (StringUtils.isEmpty(sourceRef)) { addError(errors, Problems.SEQ_FLOW_INVALID_SRC, process, sequenceFlow); } if (StringUtils.isEmpty(targetRef)) { addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow); } // Implicit check: sequence flow cannot cross (sub) process // boundaries, hence we check the parent and not the process // (could be subprocess for example) FlowElement source = process.getFlowElement(sourceRef, true); FlowElement target = process.getFlowElement(targetRef, true); // Src and target validation if (source == null) { addError(errors, Problems.SEQ_FLOW_INVALID_SRC, process, sequenceFlow); } if (target == null) { addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow); } if (source != null && target != null) { FlowElementsContainer sourceContainer = process.getFlowElementsContainer(source.getId()); FlowElementsContainer targetContainer = process.getFlowElementsContainer(target.getId()); if (sourceContainer == null) { addError(errors, Problems.SEQ_FLOW_INVALID_SRC, process, sequenceFlow); } if (targetContainer == null) {
addError(errors, Problems.SEQ_FLOW_INVALID_TARGET, process, sequenceFlow); } if (sourceContainer != null && targetContainer != null && !sourceContainer.equals(targetContainer)) { addError(errors, Problems.SEQ_FLOW_INVALID_TARGET_DIFFERENT_SCOPE, process, sequenceFlow); } } String conditionExpression = sequenceFlow.getConditionExpression(); if (conditionExpression != null) { try { ExpressionFactory.newInstance().createValueExpression( new SimpleContext(), conditionExpression.trim(), Object.class ); } catch (Exception e) { addError(errors, Problems.SEQ_FLOW_INVALID_CONDITIONAL_EXPRESSION, process, sequenceFlow); } } } } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\SequenceflowValidator.java
1
请完成以下Java代码
private Mono<Authentication> flatMapAuthentication(ServerWebExchange exchange) { return exchange.getPrincipal().cast(Authentication.class).defaultIfEmpty(this.anonymousAuthenticationToken); } private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) { logger.debug(LogMessage.format("Logging out user '%s' and transferring to logout destination", authentication)); return this.logoutHandler.logout(webFilterExchange, authentication) .then(this.logoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.clearContext()); } /** * Sets the {@link ServerLogoutSuccessHandler}. The default is * {@link RedirectServerLogoutSuccessHandler}. * @param logoutSuccessHandler the handler to use */ public void setLogoutSuccessHandler(ServerLogoutSuccessHandler logoutSuccessHandler) { Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null");
this.logoutSuccessHandler = logoutSuccessHandler; } /** * Sets the {@link ServerLogoutHandler}. The default is * {@link SecurityContextServerLogoutHandler}. * @param logoutHandler The handler to use */ public void setLogoutHandler(ServerLogoutHandler logoutHandler) { Assert.notNull(logoutHandler, "logoutHandler must not be null"); this.logoutHandler = logoutHandler; } public void setRequiresLogoutMatcher(ServerWebExchangeMatcher requiresLogoutMatcher) { Assert.notNull(requiresLogoutMatcher, "requiresLogoutMatcher must not be null"); this.requiresLogout = requiresLogoutMatcher; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\logout\LogoutWebFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue private Long id; @Column(nullable = false, unique = true) private String userName; @Column(nullable = false) private String passWord; @Column(nullable = false, unique = true) private String email; @Column(nullable = true, unique = true) private String nickName; @Column(nullable = false) private String regTime; public User() { } public User(String userName, String passWord, String email, String nickName, String regTime) { this.userName = userName; this.passWord = passWord; this.email = email; this.nickName = nickName; this.regTime = regTime; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord;
} public void setPassWord(String passWord) { this.passWord = passWord; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getRegTime() { return regTime; } public void setRegTime(String regTime) { this.regTime = regTime; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\model\User.java
2
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setMedicalAidPositionNumber (final @Nullable String MedicalAidPositionNumber) { set_Value (COLUMNNAME_MedicalAidPositionNumber, MedicalAidPositionNumber); } @Override public String getMedicalAidPositionNumber() { return get_ValueAsString(COLUMNNAME_MedicalAidPositionNumber); } /** * PurchaseRating AD_Reference_ID=541279 * Reference name: PurchaseRating */ public static final int PURCHASERATING_AD_Reference_ID=541279; /** A = A */ public static final String PURCHASERATING_A = "A"; /** B = B */ public static final String PURCHASERATING_B = "B"; /** C = C */ public static final String PURCHASERATING_C = "C"; /** D = D */ public static final String PURCHASERATING_D = "D"; /** E = E */ public static final String PURCHASERATING_E = "E"; /** F = F */
public static final String PURCHASERATING_F = "F"; /** G = G */ public static final String PURCHASERATING_G = "G"; @Override public void setPurchaseRating (final @Nullable String PurchaseRating) { set_Value (COLUMNNAME_PurchaseRating, PurchaseRating); } @Override public String getPurchaseRating() { return get_ValueAsString(COLUMNNAME_PurchaseRating); } @Override public void setSize (final @Nullable String Size) { set_Value (COLUMNNAME_Size, Size); } @Override public String getSize() { return get_ValueAsString(COLUMNNAME_Size); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaArticle.java
1
请完成以下Java代码
public void setC_AcctSchema_ID (final int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID); } @Override public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public org.compiere.model.I_C_ElementValue getC_ElementValue() { return get_ValueAsPO(COLUMNNAME_C_ElementValue_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setC_ElementValue(final org.compiere.model.I_C_ElementValue C_ElementValue) { set_ValueFromPO(COLUMNNAME_C_ElementValue_ID, org.compiere.model.I_C_ElementValue.class, C_ElementValue); } @Override public void setC_ElementValue_ID (final int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_Value (COLUMNNAME_C_ElementValue_ID, null); else set_Value (COLUMNNAME_C_ElementValue_ID, C_ElementValue_ID); } @Override public int getC_ElementValue_ID() { return get_ValueAsInt(COLUMNNAME_C_ElementValue_ID); } @Override public void setC_Invoice_Acct_ID (final int C_Invoice_Acct_ID) { if (C_Invoice_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Acct_ID, C_Invoice_Acct_ID); } @Override public int getC_Invoice_Acct_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Acct_ID); } @Override public org.compiere.model.I_C_Invoice getC_Invoice() { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); }
@Override public void setC_Invoice(final org.compiere.model.I_C_Invoice C_Invoice) { set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice); } @Override public void setC_Invoice_ID (final int C_Invoice_ID) { if (C_Invoice_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_ID, C_Invoice_ID); } @Override public int getC_Invoice_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_ID); } @Override public org.compiere.model.I_C_InvoiceLine getC_InvoiceLine() { return get_ValueAsPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class); } @Override public void setC_InvoiceLine(final org.compiere.model.I_C_InvoiceLine C_InvoiceLine) { set_ValueFromPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class, C_InvoiceLine); } @Override public void setC_InvoiceLine_ID (final int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_InvoiceLine_ID, C_InvoiceLine_ID); } @Override public int getC_InvoiceLine_ID() { return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Acct.java
1
请完成以下Java代码
private @Nullable String extractMessage(@Nullable HttpEntity entity) { if (entity != null) { try { JSONObject error = getContentAsJson(entity); if (error.has("message")) { return error.getString("message"); } } catch (Exception ex) { // Ignore } } return null; } private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException { return new JSONObject(getContent(entity)); } private String getContent(HttpEntity entity) throws IOException { ContentType contentType = ContentType.create(entity.getContentType());
Charset charset = contentType.getCharset(); charset = (charset != null) ? charset : StandardCharsets.UTF_8; byte[] content = FileCopyUtils.copyToByteArray(entity.getContent()); return new String(content, charset); } private @Nullable String extractFileName(@Nullable Header header) { if (header != null) { String value = header.getValue(); int start = value.indexOf(FILENAME_HEADER_PREFIX); if (start != -1) { value = value.substring(start + FILENAME_HEADER_PREFIX.length()); int end = value.indexOf('\"'); if (end != -1) { return value.substring(0, end); } } } return null; } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\init\InitializrService.java
1
请在Spring Boot框架中完成以下Java代码
public String getActivityId() { return activityId; } public void setActivityId(String activityId) { this.activityId = activityId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionUrl() { return processDefinitionUrl; } public void setProcessDefinitionUrl(String processDefinitionUrl) { this.processDefinitionUrl = processDefinitionUrl; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getExecutionUrl() { return executionUrl; } public void setExecutionUrl(String executionUrl) { this.executionUrl = executionUrl; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getSubScopeId() {
return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\EventSubscriptionResponse.java
2
请在Spring Boot框架中完成以下Java代码
public class AnnotationUtil { /** * 获取指定类上的指定注解 * @param clazz 目标类 * @param annotationClazz 注解类的Class对象 * @param <T> 注解的类型 * @return 注解对象 */ public static <T> T getAnnotationValueByClass(Class clazz, Class annotationClazz) { return (T) clazz.getAnnotation(annotationClazz); } /** * 获取指定方法上的指定注解 * @param method 目标方法 * @param annotationClazz 注解类的Class对象 * @param <T> 注解类型
* @return 注解对象 */ public static <T> T getAnnotationValueByMethod(Method method, Class annotationClazz) { return (T) method.getAnnotation(annotationClazz); } /** * 获取指定Field上的指定注解 * @param field 目标 成员变量 * @param annotationClazz 注解类的Class对象 * @param <T> 注解类型 * @return 注解对象 */ public static <T> T getAnnotationValueByField(Field field, Class annotationClazz) { return (T) field.getAnnotation(annotationClazz); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\utils\AnnotationUtil.java
2
请完成以下Java代码
public class WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion extends ProductsProposalViewBasedProcess { private final IPriceListDAO pricesListsRepo = Services.get(IPriceListDAO.class); @Override public final ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!hasChangedRows()) { return ProcessPreconditionsResolution.rejectWithInternalReason("nothing to save"); } final ProductsProposalView view = getView(); if (!view.getSinglePriceListVersionId().isPresent()) { return ProcessPreconditionsResolution.rejectWithInternalReason("no base price list version"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { streamChangedRows() .forEach(this::save); return MSG_OK; } @Override protected void postProcess(final boolean success) { invalidateView(); } private boolean hasChangedRows() { return streamChangedRows() .findAny() .isPresent(); } private Stream<ProductsProposalRow> streamChangedRows() { return getSelectedRows() .stream() .filter(ProductsProposalRow::isChanged); } private void save(final ProductsProposalRow row) { if (!row.isChanged()) { return; } final BigDecimal userEnteredPriceValue = row.getPrice().getUserEnteredPriceValue(); final ProductPriceId productPriceId; // // Update existing product price if (row.getProductPriceId() != null) { productPriceId = row.getProductPriceId();
pricesListsRepo.updateProductPrice(UpdateProductPriceRequest.builder() .productPriceId(productPriceId) .priceStd(userEnteredPriceValue) .build()); } // // Save a new product price which was copied from some other price list version else if (row.getCopiedFromProductPriceId() != null) { productPriceId = pricesListsRepo.copyProductPrice(CopyProductPriceRequest.builder() .copyFromProductPriceId(row.getCopiedFromProductPriceId()) .copyToPriceListVersionId(getPriceListVersionId()) .priceStd(userEnteredPriceValue) .build()); } else { throw new AdempiereException("Cannot save row: " + row); } // // Refresh row getView().patchViewRow(row.getId(), RowSaved.builder() .productPriceId(productPriceId) .price(row.getPrice().withPriceListPriceValue(userEnteredPriceValue)) .build()); } private PriceListVersionId getPriceListVersionId() { return getView() .getSinglePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_PriceList_Version_ID@")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\process\WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.java
1
请完成以下Java代码
private Stream<IShipmentScheduleSegment> extractPickingBOMsStorageSegments(final OlAndSched olAndSched) { try (final MDCCloseable ignored = ShipmentSchedulesMDC.putShipmentScheduleId(olAndSched.getShipmentScheduleId())) { final PickingBOMsReversedIndex pickingBOMsReversedIndex = pickingBOMService.getPickingBOMsReversedIndex(); final ProductId componentId = olAndSched.getProductId(); final ImmutableSet<ProductId> pickingBOMProductIds = pickingBOMsReversedIndex.getBOMProductIdsByComponentId(componentId); if (pickingBOMProductIds.isEmpty()) { return Stream.empty(); } final Set<WarehouseId> warehouseIds = warehousesRepo.getWarehouseIdsOfSamePickingGroup(olAndSched.getWarehouseId()); final LinkedHashSet<IShipmentScheduleSegment> segments = new LinkedHashSet<>(); for (final WarehouseId warehouseId : warehouseIds) { final Set<Integer> locatorRepoIds = warehousesRepo.getLocatorIds(warehouseId) .stream() .map(LocatorId::getRepoId) .collect(ImmutableSet.toImmutableSet());
for (final ProductId pickingBOMProductId : pickingBOMProductIds) { final ImmutableShipmentScheduleSegment segment = ImmutableShipmentScheduleSegment.builder() .anyBPartner() .productId(pickingBOMProductId.getRepoId()) .locatorIds(locatorRepoIds) .build(); logger.debug("Add for pickingBOMProductId={} warehouseId={}: segment={}", pickingBOMProductId.getRepoId(), warehouseId.getRepoId(), segment); segments.add(segment); } } return segments.stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleUpdater.java
1
请完成以下Java代码
public Criteria andUserAgentNotIn(List<String> values) { addCriterion("user_agent not in", values, "userAgent"); return (Criteria) this; } public Criteria andUserAgentBetween(String value1, String value2) { addCriterion("user_agent between", value1, value2, "userAgent"); return (Criteria) this; } public Criteria andUserAgentNotBetween(String value1, String value2) { addCriterion("user_agent not between", value1, value2, "userAgent"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; }
public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminLoginLogExample.java
1
请完成以下Java代码
protected PricingConditionsRowData createPricingConditionsRowData(final CreateViewRequest request) { final Set<ProductId> productIds = ProductId.ofRepoIds(request.getFilterOnlyIds()); Check.assumeNotEmpty(productIds, "productIds is not empty"); final IProductDAO productsRepo = Services.get(IProductDAO.class); final Set<ProductAndCategoryAndManufacturerId> products = productsRepo.retrieveProductAndCategoryAndManufacturersByProductIds(productIds); return preparePricingConditionsRowData() .pricingConditionsBreaksExtractor(pricingConditions -> pricingConditions.streamBreaksMatchingAnyOfProducts(products)) .basePricingSystemPriceCalculator(this::calculateBasePricingSystemPrice) .load(); } private Money calculateBasePricingSystemPrice(final BasePricingSystemPriceCalculatorRequest request) { final IPricingConditionsService pricingConditionsService = Services.get(IPricingConditionsService.class); return pricingConditionsService.calculatePricingConditions(CalculatePricingConditionsRequest.builder() .forcePricingConditionsBreak(request.getPricingConditionsBreak()) .pricingCtx(createPricingContext(request)) .build()) .map(result -> Money.of(result.getPriceStdOverride(), result.getCurrencyId())) .orElse(null); } private IPricingContext createPricingContext(final BasePricingSystemPriceCalculatorRequest request) {
final IPricingBL pricingBL = Services.get(IPricingBL.class); final PricingConditionsBreak pricingConditionsBreak = request.getPricingConditionsBreak(); final IEditablePricingContext pricingCtx = pricingBL.createPricingContext(); final ProductId productId = pricingConditionsBreak.getMatchCriteria().getProductId(); pricingCtx.setProductId(productId); pricingCtx.setQty(BigDecimal.ONE); pricingCtx.setBPartnerId(request.getBpartnerId()); pricingCtx.setSOTrx(SOTrx.ofBoolean(request.isSOTrx())); return pricingCtx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\ProductPricingConditionsViewFactory.java
1
请完成以下Java代码
public class RecordMessagingMessageListenerAdapter<K, V> extends MessagingMessageListenerAdapter<K, V> implements AcknowledgingConsumerAwareMessageListener<K, V> { public RecordMessagingMessageListenerAdapter(@Nullable Object bean, @Nullable Method method) { this(bean, method, null); } public RecordMessagingMessageListenerAdapter(@Nullable Object bean, @Nullable Method method, @Nullable KafkaListenerErrorHandler errorHandler) { super(bean, method, errorHandler); } /** * Kafka {@link AcknowledgingConsumerAwareMessageListener} entry point. * <p> Delegate the message to the target listener method, * with appropriate conversion of the message argument. * @param record the incoming Kafka {@link ConsumerRecord}. * @param acknowledgment the acknowledgment. * @param consumer the consumer. */ @Override @SuppressWarnings("removal") public void onMessage(ConsumerRecord<K, V> record, @Nullable Acknowledgment acknowledgment, @Nullable Consumer<?, ?> consumer) {
Message<?> message; if (isConversionNeeded()) { message = toMessagingMessage(record, acknowledgment, consumer); } else { message = NULL_MESSAGE; } if (logger.isDebugEnabled()) { RecordMessageConverter messageConverter = getMessageConverter(); if (!(messageConverter instanceof JacksonProjectingMessageConverter || messageConverter instanceof ProjectingMessageConverter)) { this.logger.debug("Processing [" + message + "]"); } } invoke(record, acknowledgment, consumer, message); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\RecordMessagingMessageListenerAdapter.java
1
请完成以下Java代码
public class DeleteTaskPayload implements Payload { private String id; private String taskId; private String reason; public DeleteTaskPayload() { this.id = UUID.randomUUID().toString(); } public DeleteTaskPayload(String taskId, String reason) { this(); this.taskId = taskId; this.reason = reason; } @Override public String getId() { return id; } public String getTaskId() { return taskId; }
public void setTaskId(String taskId) { this.taskId = taskId; } public String getReason() { return reason; } public boolean hasReason() { return reason != null; } public void setReason(String reason) { this.reason = reason; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\DeleteTaskPayload.java
1
请完成以下Java代码
public void afterPropertiesSet() { checkIfValidList(this.providers); } @Override public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config, Object returnedObject) throws AccessDeniedException { Object result = returnedObject; for (AfterInvocationProvider provider : this.providers) { result = provider.decide(authentication, object, config, result); } return result; } public List<AfterInvocationProvider> getProviders() { return this.providers; } public void setProviders(List<?> newList) { checkIfValidList(newList); this.providers = new ArrayList<>(newList.size()); for (Object currentObject : newList) { Assert.isInstanceOf(AfterInvocationProvider.class, currentObject, () -> "AfterInvocationProvider " + currentObject.getClass().getName() + " must implement AfterInvocationProvider"); this.providers.add((AfterInvocationProvider) currentObject); } } private void checkIfValidList(List<?> listToCheck) { Assert.isTrue(!CollectionUtils.isEmpty(listToCheck), "A list of AfterInvocationProviders is required"); } @Override public boolean supports(ConfigAttribute attribute) { for (AfterInvocationProvider provider : this.providers) { logger.debug(LogMessage.format("Evaluating %s against %s", attribute, provider)); if (provider.supports(attribute)) { return true; } } return false;
} /** * Iterates through all <code>AfterInvocationProvider</code>s and ensures each can * support the presented class. * <p> * If one or more providers cannot support the presented class, <code>false</code> is * returned. * @param clazz the secure object class being queries * @return if the <code>AfterInvocationProviderManager</code> can support the secure * object class, which requires every one of its <code>AfterInvocationProvider</code>s * to support the secure object class */ @Override public boolean supports(Class<?> clazz) { for (AfterInvocationProvider provider : this.providers) { if (!provider.supports(clazz)) { return false; } } return true; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\AfterInvocationProviderManager.java
1
请完成以下Java代码
public class PlanItemUtil { /** * Returns all parent plan items, ordered from direct parent plan item to outermost. */ public static List<PlanItem> getAllParentPlanItems(PlanItem planItem) { List<PlanItem> parentPlanItems = new ArrayList<>(); internalGetParentPlanItems(planItem, parentPlanItems); return parentPlanItems; } protected static void internalGetParentPlanItems(PlanItem planItem, List<PlanItem> parentPlanItems) { Stage parentStage = planItem.getParentStage(); if (parentStage != null && !parentStage.isPlanModel()) { PlanItem parentPlanItem = parentStage.findPlanItemForPlanItemDefinitionInPlanFragmentOrUpwards(parentStage.getId()); if (parentPlanItem != null) { parentPlanItems.add(parentPlanItem); internalGetParentPlanItems(parentPlanItem, parentPlanItems); } } }
public static List<PlanItem> getAllChildPlanItems(PlanFragment planFragment) { List<PlanItem> planItems = new ArrayList<>(); internalGetAllChildPlanItems(planFragment, planItems); return planItems; } protected static void internalGetAllChildPlanItems(PlanFragment planFragment, List<PlanItem> planItems) { for (PlanItem planItem : planFragment.getPlanItems()) { planItems.add(planItem); PlanItemDefinition planItemDefinition = planItem.getPlanItemDefinition(); if (planItemDefinition instanceof PlanFragment) { internalGetAllChildPlanItems((PlanFragment) planItemDefinition, planItems); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\util\PlanItemUtil.java
1
请在Spring Boot框架中完成以下Java代码
public @NonNull String getHandledTableName() { return I_C_Invoice.Table_Name; } @Override public StandardDocumentReportType getStandardDocumentReportType() { return StandardDocumentReportType.INVOICE; } @Override public @NonNull DocumentReportInfo getDocumentReportInfo( @NonNull final TableRecordReference recordRef, @Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse) { final InvoiceId invoiceId = recordRef.getIdAssumingTableName(I_C_Invoice.Table_Name, InvoiceId::ofRepoId); final I_C_Invoice invoice = invoiceBL.getById(invoiceId); final BPartnerId bpartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID()); final I_C_BPartner bpartner = util.getBPartnerById(bpartnerId); final DocTypeId docTypeId = extractDocTypeId(invoice); final I_C_DocType docType = util.getDocTypeById(docTypeId); final ClientId clientId = ClientId.ofRepoId(invoice.getAD_Client_ID()); final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers( () -> adPrintFormatToUseId, () -> util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null), () -> PrintFormatId.ofRepoIdOrNull(bpartner.getInvoice_PrintFormat_ID()), () -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()), () -> util.getDefaultPrintFormats(clientId).getInvoicePrintFormatId()); if (printFormatId == null) { throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@"); } final Language language = util.getBPartnerLanguage(bpartner).orElse(null); final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder() .adTableId(recordRef.getAdTableId()) .bpartnerId(bpartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, invoice.getC_BPartner_Location_ID())) .docTypeId(docTypeId) .onlyCopiesGreaterZero(true) .build(); return DocumentReportInfo.builder() .recordRef(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId)) .reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId)) .copies(util.getDocumentCopies(docType, bpPrintFormatQuery)) .documentNo(invoice.getDocumentNo()) .bpartnerId(bpartnerId) .docTypeId(docTypeId) .language(language) .poReference(invoice.getPOReference()) .build(); } private DocTypeId extractDocTypeId(@NonNull final I_C_Invoice invoice) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(invoice.getC_DocType_ID()); if (docTypeId != null) { return docTypeId; } final DocTypeId docTypeTargetId = DocTypeId.ofRepoIdOrNull(invoice.getC_DocTypeTarget_ID()); if (docTypeTargetId != null) { return docTypeTargetId; } throw new AdempiereException("No document type set"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\InvoiceDocumentReportAdvisor.java
2
请在Spring Boot框架中完成以下Java代码
public class CachingProviderAutoConfiguration { protected static final Set<String> SPRING_CACHE_TYPES = asSet("gemfire", "geode"); protected static final String SPRING_CACHE_TYPE_PROPERTY = "spring.cache.type"; private final CacheManagerCustomizers cacheManagerCustomizers; private final CacheProperties cacheProperties; @Autowired private GemfireCacheManager cacheManager; CachingProviderAutoConfiguration( @Autowired(required = false) CacheProperties cacheProperties, @Autowired(required = false) CacheManagerCustomizers cacheManagerCustomizers) { this.cacheProperties = cacheProperties; this.cacheManagerCustomizers = cacheManagerCustomizers; } GemfireCacheManager getCacheManager() { Assert.state(this.cacheManager != null, "GemfireCacheManager was not properly configured"); return this.cacheManager;
} Optional<CacheManagerCustomizers> getCacheManagerCustomizers() { return Optional.ofNullable(this.cacheManagerCustomizers); } Optional<CacheProperties> getCacheProperties() { return Optional.ofNullable(this.cacheProperties); } @PostConstruct public void onGeodeCachingInitialization() { getCacheManagerCustomizers() .ifPresent(cacheManagerCustomizers -> cacheManagerCustomizers.customize(getCacheManager())); } public static class SpringCacheTypeCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String springCacheType = context.getEnvironment().getProperty(SPRING_CACHE_TYPE_PROPERTY); return !StringUtils.hasText(springCacheType) || SPRING_CACHE_TYPES.contains(springCacheType); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\CachingProviderAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void goodProcess(GoodListResponse goodListResponse){ for(GoodResponse goodResponse: goodListResponse.getGoodList()) { Retailer retailer = retailerRepository.findByInternalCode(goodResponse.getGoodId()).orElse(null); if(retailer == null) continue; List<Good> existGoods = goodsRepository.findByInternalCodeAndRetailer(goodResponse.getInternalCode(), retailer); if(!existGoods.isEmpty()) { existGoods.forEach( o -> { o.setIsOutdated(true); goodsRepository.save(o); }); // removeOutdatedGoodsFromBuckets(existGoods); } if(goodResponse.getIsOutdated() !=null && !goodResponse.getIsOutdated()) { Good good = new Good( goodResponse.getName(), goodResponse.getPrice(), goodResponse.getImage(), goodResponse.getIngredients(), retailerRepository.findByInternalCode(goodResponse.getRetailer()).orElse(null), goodResponse.getInternalCode()); goodsRepository.save(good); } } }
private void removeOutdatedGoodsFromBuckets(List<Good> outdatedGoods){ for(Good good: outdatedGoods) { for(User user: userRepository.findAll()) { orderRepository.findFirstByStatusAndUser(OrderStatus.NEW, user) .flatMap(orders -> orderDetailsRepository.findByGoodAndOrder(good, orders)) .ifPresent(orderDetails -> orderDetailsRepository.delete(orderDetails)); } } } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\GoodConsumeService.java
2
请完成以下Java代码
public BPartnerId getBPartnerId() { return bpartnerId; } public Builder setBPartnerId(final BPartnerId bpartnerId) { this.bpartnerId = bpartnerId; return this; } public @Nullable BankAccountId getBPartnerBankAccountId() { return bpBankAccountId; } public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId) { this.bpBankAccountId = bpBankAccountId; return this; } public BigDecimal getOpenAmt() { return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO); } public Builder setOpenAmt(final BigDecimal openAmt) { this._openAmt = openAmt; return this; }
public BigDecimal getPayAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(discountAmt); } public BigDecimal getDiscountAmt() { return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO); } public Builder setDiscountAmt(final BigDecimal discountAmt) { this._discountAmt = discountAmt; return this; } public BigDecimal getDifferenceAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal payAmt = getPayAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(payAmt).subtract(discountAmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java
1
请完成以下Java代码
public final void selectRowsByInvoiceCandidateIds(final Collection<Integer> invoiceCandidateIds) { if (invoiceCandidateIds == null || invoiceCandidateIds.isEmpty()) { return; } final List<IInvoiceCandidateRow> rowsChanged = new ArrayList<>(); for (final IInvoiceCandidateRow row : getRowsInnerList()) { // Skip if already selected if (row.isSelected()) { continue; } if (invoiceCandidateIds.contains(row.getC_Invoice_Candidate_ID())) { row.setSelected(true); rowsChanged.add(row); } } fireTableRowsUpdated(rowsChanged); } /** @return latest {@link IInvoiceCandidateRow#getDocumentDate()} of selected rows */ public final Date getLatestDocumentDateOfSelectedRows() { Date latestDocumentDate = null; for (final IInvoiceCandidateRow row : getRowsSelected()) { final Date documentDate = row.getDocumentDate(); latestDocumentDate = TimeUtil.max(latestDocumentDate, documentDate); } return latestDocumentDate; }
/** * @return latest {@link IInvoiceCandidateRow#getDateAcct()} of selected rows */ public final Date getLatestDateAcctOfSelectedRows() { Date latestDateAcct = null; for (final IInvoiceCandidateRow row : getRowsSelected()) { final Date dateAcct = row.getDateAcct(); latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct); } return latestDateAcct; } public final BigDecimal getTotalNetAmtToInvoiceOfSelectedRows() { BigDecimal totalNetAmtToInvoiced = BigDecimal.ZERO; for (final IInvoiceCandidateRow row : getRowsSelected()) { final BigDecimal netAmtToInvoice = row.getNetAmtToInvoice(); totalNetAmtToInvoiced = totalNetAmtToInvoiced.add(netAmtToInvoice); } return totalNetAmtToInvoiced; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidatesTableModel.java
1
请完成以下Java代码
public Id getOrderIdFromClientRequest(final Object soapRequestObj) { final BestellstatusAbfragen soapRequest = castToRequestFromClient(soapRequestObj); final Id orderId = Id.of(soapRequest.getBestellId()); return orderId; } @Override public ClientSoftwareId getClientSoftwareIdFromClientRequest(final Object soapRequestObj) { final BestellstatusAbfragen soapRequest = castToRequestFromClient(soapRequestObj); return ClientSoftwareId.of(soapRequest.getClientSoftwareKennung()); } private static BestellstatusAbfragen castToRequestFromClient(final Object soapRequestObj) { final BestellstatusAbfragen soapRequest = (BestellstatusAbfragen)soapRequestObj; return soapRequest; } @Override public JAXBElement<BestellstatusAbfragenResponse> encodeResponseToClient(final OrderStatusResponse response)
{ return toJAXB(response); } private JAXBElement<BestellstatusAbfragenResponse> toJAXB(final OrderStatusResponse response) { final BestellstatusAntwort soapResponseContent = jaxbObjectFactory.createBestellstatusAntwort(); soapResponseContent.setId(response.getOrderId().getValueAsString()); soapResponseContent.setBestellSupportId(response.getSupportId().getValueAsInt()); soapResponseContent.setStatus(response.getOrderStatus().getV1SoapCode()); soapResponseContent.getAuftraege().addAll(response.getOrderPackages().stream() .map(orderConverters::toJAXB) .collect(ImmutableList.toImmutableList())); final BestellstatusAbfragenResponse soapResponse = jaxbObjectFactory.createBestellstatusAbfragenResponse(); soapResponse.setReturn(soapResponseContent); return jaxbObjectFactory.createBestellstatusAbfragenResponse(soapResponse); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\v1\OrderStatusJAXBConvertersV1.java
1
请在Spring Boot框架中完成以下Java代码
private static Map<String, Object> request(SortedMap<String, String> paramMap, String requestUrl) { logger.info("鉴权请求地址:[{}],请求参数:[{}]", requestUrl, paramMap); HttpClient httpClient = new HttpClient(); HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams(); // 设置连接超时时间(单位毫秒) managerParams.setConnectionTimeout(9000); // 设置读数据超时时间(单位毫秒) managerParams.setSoTimeout(12000); PostMethod postMethod = new PostMethod(requestUrl); postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); NameValuePair[] pairs = new NameValuePair[paramMap.size()]; int i = 0; for (Map.Entry<String, String> entry : paramMap.entrySet()) { pairs[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } postMethod.setRequestBody(pairs); try { Integer code = httpClient.executeMethod(postMethod); if (code.compareTo(200) == 0) { String result = postMethod.getResponseBodyAsString(); logger.info("鉴权请求成功,同步返回数据:{}", result); return JSON.parseObject(result); } else { logger.error("鉴权请求失败,返回状态码:[{}]", code); } } catch (IOException e) { logger.info("鉴权请求异常:{}", e); return null; } return null; }
/** * 签名 * * @param paramMap 签名参数 * @param paySecret 签名秘钥 * @return */ private static String getSign(SortedMap<String, String> paramMap, String paySecret) { StringBuilder signBuilder = new StringBuilder(); for (Map.Entry<String, String> entry : paramMap.entrySet()) { if (!"sign".equals(entry.getKey()) && entry.getValue() != null && !StringUtil.isEmpty(entry.getValue())) { signBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } } signBuilder.append("paySecret=").append(paySecret); logger.info("鉴权签名原文:[{}]", signBuilder); String sign = MD5Util.encode(signBuilder.toString()).toUpperCase(); logger.info("鉴权签名结果:[{}]", sign); return sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\auth\AuthUtil.java
2
请完成以下Java代码
public void submitFormProperties(Map<String, String> properties, ExecutionEntity execution) { Map<String, String> propertiesCopy = new HashMap<>(properties); for (FormPropertyHandler formPropertyHandler : formPropertyHandlers) { // submitFormProperty will remove all the keys which it takes care // of formPropertyHandler.submitFormProperty(execution, propertiesCopy); } for (String propertyId : propertiesCopy.keySet()) { execution.setVariable(propertyId, propertiesCopy.get(propertyId)); } } // getters and setters // ////////////////////////////////////////////////////// public Expression getFormKey() { return formKey; } public void setFormKey(Expression formKey) { this.formKey = formKey; }
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public List<FormPropertyHandler> getFormPropertyHandlers() { return formPropertyHandlers; } public void setFormPropertyHandlers(List<FormPropertyHandler> formPropertyHandlers) { this.formPropertyHandlers = formPropertyHandlers; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\DefaultFormHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void setTokenUri(@Nullable String tokenUri) { this.tokenUri = tokenUri; } public @Nullable String getUserInfoUri() { return this.userInfoUri; } public void setUserInfoUri(@Nullable String userInfoUri) { this.userInfoUri = userInfoUri; } public @Nullable String getUserInfoAuthenticationMethod() { return this.userInfoAuthenticationMethod; } public void setUserInfoAuthenticationMethod(@Nullable String userInfoAuthenticationMethod) { this.userInfoAuthenticationMethod = userInfoAuthenticationMethod; } public @Nullable String getUserNameAttribute() { return this.userNameAttribute; }
public void setUserNameAttribute(@Nullable String userNameAttribute) { this.userNameAttribute = userNameAttribute; } public @Nullable String getJwkSetUri() { return this.jwkSetUri; } public void setJwkSetUri(@Nullable String jwkSetUri) { this.jwkSetUri = jwkSetUri; } public @Nullable String getIssuerUri() { return this.issuerUri; } public void setIssuerUri(@Nullable String issuerUri) { this.issuerUri = issuerUri; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-client\src\main\java\org\springframework\boot\security\oauth2\client\autoconfigure\OAuth2ClientProperties.java
2
请完成以下Java代码
public int read() throws IOException { int read = (this.headerStream != null) ? this.headerStream.read() : -1; if (read != -1) { this.position++; if (this.position >= this.headerLength) { this.headerStream = null; } return read; } return super.read(); } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int read = (this.headerStream != null) ? this.headerStream.read(b, off, len) : -1; if (read <= 0) { return readRemainder(b, off, len); } this.position += read; if (read < len) { int remainderRead = readRemainder(b, off + read, len - read); if (remainderRead > 0) { read += remainderRead;
} } if (this.position >= this.headerLength) { this.headerStream = null; } return read; } boolean hasZipHeader() { return Arrays.equals(this.header, ZIP_HEADER); } private int readRemainder(byte[] b, int off, int len) throws IOException { int read = super.read(b, off, len); if (read > 0) { this.position += read; } return read; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\ZipHeaderPeekInputStream.java
1
请在Spring Boot框架中完成以下Java代码
public String updateEmployee(@PathVariable("id") int id, @RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) { Employee employee = new Employee(); employee.setId( id ); employee.setLastName( lastName ); employee.setEmail( email ); employee.setGender( gender ); employee.setDId( dId ); Employee res = employeeService.updateEmployeeById( employee ); if (res != null) { return "update success"; } else { return "update fail"; } } @DeleteMapping(value = "/{id}") public String delete(@PathVariable(value = "id")int id) { boolean b = employeeService.removeById( id ); if(b) { return "delete success"; }else { return "delete fail"; } }
@PostMapping(value = "") public String postEmployee(@RequestParam(value = "lastName", required = true) String lastName, @RequestParam(value = "email", required = true) String email , @RequestParam(value = "gender", required = true) int gender , @RequestParam(value = "dId", required = true) int dId) { Employee employee = new Employee(); employee.setLastName( lastName ); employee.setEmail( email ); employee.setGender( gender ); employee.setDId( dId ); boolean b = employeeService.save( employee ); if(b) { return "sava success"; }else { return "sava fail"; } } }
repos\SpringBootLearning-master (1)\springboot-cache\src\main\java\com\gf\controller\EmployeeController.java
2
请在Spring Boot框架中完成以下Java代码
private void cloneWFNodeProductsForWFNode(@NonNull final I_AD_WF_Node toWFNode, @NonNull final I_AD_WF_Node fromWFNode) { getWFNodeProductsByWorkflowIdAndWFNodeId(WorkflowId.ofRepoId(fromWFNode.getAD_Workflow_ID()), WFNodeId.ofRepoId(fromWFNode.getAD_WF_Node_ID())) .forEach(wfNodeProduct -> cloneWFNodeProductAndSetNewWorkflowAndWFNode(wfNodeProduct, WFNodeId.ofRepoId(toWFNode.getAD_WF_Node_ID()), WorkflowId.ofRepoId(toWFNode.getAD_Workflow_ID()))); } public ImmutableList<I_PP_WF_Node_Product> getWFNodeProductsByWorkflowIdAndWFNodeId( @NonNull final WorkflowId fromWorkflowId, @NonNull final WFNodeId fromWFNodeId) { return queryBL.createQueryBuilder(I_PP_WF_Node_Product.class) .addEqualsFilter(I_PP_WF_Node_Product.COLUMNNAME_AD_Workflow_ID, fromWorkflowId.getRepoId()) .addEqualsFilter(I_PP_WF_Node_Product.COLUMNNAME_AD_WF_Node_ID, fromWFNodeId.getRepoId()) .create() .stream()
.collect(ImmutableList.toImmutableList()); } private void cloneWFNodeProductAndSetNewWorkflowAndWFNode( final @NonNull I_PP_WF_Node_Product wfNodeProduct, final @NonNull WFNodeId toWFNodeId, final @NonNull WorkflowId toWorkflowId) { final I_PP_WF_Node_Product newWFNodeProduct = InterfaceWrapperHelper.newInstance(I_PP_WF_Node_Product.class); InterfaceWrapperHelper.copyValues(wfNodeProduct, newWFNodeProduct); newWFNodeProduct.setAD_WF_Node_ID(toWFNodeId.getRepoId()); newWFNodeProduct.setAD_Workflow_ID(toWorkflowId.getRepoId()); InterfaceWrapperHelper.saveRecord(newWFNodeProduct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\service\impl\AD_WF_Node_CopyRecordSupport.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("elements", elements.isEmpty() ? null : elements) .toString(); } public List<DocumentLayoutElementDescriptor> getElements() { return elements; } public static final class Builder { private final List<DocumentLayoutElementDescriptor.Builder> elementBuilders = new ArrayList<>(); private Builder() { super(); } public AddressLayout build() { return new AddressLayout(this); } private List<DocumentLayoutElementDescriptor> buildElements() { return elementBuilders .stream() .map(elementBuilder -> elementBuilder.build()) .collect(GuavaCollectors.toImmutableList()); }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("elements-count", elementBuilders.size()) .toString(); } public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder) { Check.assumeNotNull(elementBuilder, "Parameter elementBuilder is not null"); elementBuilders.add(elementBuilder); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressLayout.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, CaseDefinitionDto> getDeployedCaseDefinitions() { return deployedCaseDefinitions; } public Map<String, DecisionDefinitionDto> getDeployedDecisionDefinitions() { return deployedDecisionDefinitions; } public Map<String, DecisionRequirementsDefinitionDto> getDeployedDecisionRequirementsDefinitions() { return deployedDecisionRequirementsDefinitions; } public static DeploymentWithDefinitionsDto fromDeployment(DeploymentWithDefinitions deployment) { DeploymentWithDefinitionsDto dto = new DeploymentWithDefinitionsDto(); dto.id = deployment.getId(); dto.name = deployment.getName(); dto.source = deployment.getSource(); dto.deploymentTime = deployment.getDeploymentTime(); dto.tenantId = deployment.getTenantId(); initDeployedResourceLists(deployment, dto); return dto; } private static void initDeployedResourceLists(DeploymentWithDefinitions deployment, DeploymentWithDefinitionsDto dto) { List<ProcessDefinition> deployedProcessDefinitions = deployment.getDeployedProcessDefinitions(); if (deployedProcessDefinitions != null) { dto.deployedProcessDefinitions = new HashMap<String, ProcessDefinitionDto>(); for (ProcessDefinition processDefinition : deployedProcessDefinitions) { dto.deployedProcessDefinitions .put(processDefinition.getId(), ProcessDefinitionDto.fromProcessDefinition(processDefinition)); } } List<CaseDefinition> deployedCaseDefinitions = deployment.getDeployedCaseDefinitions(); if (deployedCaseDefinitions != null) { dto.deployedCaseDefinitions = new HashMap<String, CaseDefinitionDto>();
for (CaseDefinition caseDefinition : deployedCaseDefinitions) { dto.deployedCaseDefinitions .put(caseDefinition.getId(), CaseDefinitionDto.fromCaseDefinition(caseDefinition)); } } List<DecisionDefinition> deployedDecisionDefinitions = deployment.getDeployedDecisionDefinitions(); if (deployedDecisionDefinitions != null) { dto.deployedDecisionDefinitions = new HashMap<String, DecisionDefinitionDto>(); for (DecisionDefinition decisionDefinition : deployedDecisionDefinitions) { dto.deployedDecisionDefinitions .put(decisionDefinition.getId(), DecisionDefinitionDto.fromDecisionDefinition(decisionDefinition)); } } List<DecisionRequirementsDefinition> deployedDecisionRequirementsDefinitions = deployment.getDeployedDecisionRequirementsDefinitions(); if (deployedDecisionRequirementsDefinitions != null) { dto.deployedDecisionRequirementsDefinitions = new HashMap<String, DecisionRequirementsDefinitionDto>(); for (DecisionRequirementsDefinition drd : deployedDecisionRequirementsDefinitions) { dto.deployedDecisionRequirementsDefinitions .put(drd.getId(), DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(drd)); } } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentWithDefinitionsDto.java
2
请完成以下Java代码
public static EAN13 ofNullableString(@Nullable final String barcode) { final String barcodeNorm = StringUtils.trimBlankToNull(barcode); return barcodeNorm != null ? EAN13Parser.parse(barcodeNorm).orElseThrow() : null; } @Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() {return barcode;} /** * @return true if standard/fixed code (i.e. not starting with prefix 28 nor 29) */ public boolean isFixed() {return prefix.isFixed();} public boolean isVariable() {return prefix.isFixed();} /** * @return true if variable weight EAN13 (i.e. starts with prefix 28) */ public boolean isVariableWeight() {return prefix.isVariableWeight();} /**
* @return true if internal or variable measure EAN13 (i.e. starts with prefix 29) */ public boolean isInternalUseOrVariableMeasure() {return prefix.isInternalUseOrVariableMeasure();} public Optional<BigDecimal> getWeightInKg() {return Optional.ofNullable(weightInKg);} public GTIN toGTIN() {return GTIN.ofEAN13(this);} public boolean isMatching(@NonNull final EAN13ProductCode expectedProductNo) { return EAN13ProductCode.equals(this.productNo, expectedProductNo); } public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode) { return this.productNo.endsWith(expectedProductCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\ean13\EAN13.java
1
请完成以下Java代码
public class ProcessInstanceDto extends LinkableDto { private String id; private String definitionId; private String businessKey; private String caseInstanceId; private boolean ended; private boolean suspended; private String tenantId; private String definitionKey; public ProcessInstanceDto() { } public ProcessInstanceDto(ProcessInstance instance) { this.id = instance.getId(); this.definitionId = instance.getProcessDefinitionId(); this.definitionKey = instance.getProcessDefinitionKey(); this.businessKey = instance.getBusinessKey(); this.caseInstanceId = instance.getCaseInstanceId(); this.ended = instance.isEnded(); this.suspended = instance.isSuspended(); this.tenantId = instance.getTenantId(); } public String getId() { return id; } public String getDefinitionId() { return definitionId; } public String getDefinitionKey() { return definitionKey; }
public String getBusinessKey() { return businessKey; } public String getCaseInstanceId() { return caseInstanceId; } public boolean isEnded() { return ended; } public boolean isSuspended() { return suspended; } public String getTenantId() { return tenantId; } public static ProcessInstanceDto fromProcessInstance(ProcessInstance instance) { return new ProcessInstanceDto(instance); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceDto.java
1
请完成以下Java代码
public Collection<I_M_ProductScalePrice> retrieveScalePrices(final int productPriceId, final String trxName) { return new Query(Env.getCtx(), I_M_ProductScalePrice.Table_Name, WHERE_PRODUCT_SCALE_PRICE, trxName) .setParameters(productPriceId) .setClient_ID() .setOnlyActiveRecords(true) .list(I_M_ProductScalePrice.class); } private I_M_ProductScalePrice createScalePrice(final String trxName) { return InterfaceWrapperHelper.newInstance(I_M_ProductScalePrice.class, PlainContextAware.newWithTrxName(Env.getCtx(), trxName)); } /** * Returns an existing scale price or (if <code>createNew</code> is true) creates a new one. */ @Nullable @Override public I_M_ProductScalePrice retrieveOrCreateScalePrices( final int productPriceId, final BigDecimal qty, final boolean createNew, final String trxName) { final PreparedStatement pstmt = DB.prepareStatement( SQL_SCALEPRICE_FOR_QTY, trxName); ResultSet rs = null; try { pstmt.setInt(1, productPriceId); pstmt.setBigDecimal(2, qty); pstmt.setMaxRows(1); rs = pstmt.executeQuery(); if (rs.next()) { logger.debug("Returning existing instance for M_ProductPrice " + productPriceId + " and quantity " + qty); return new X_M_ProductScalePrice(Env.getCtx(), rs, trxName); }
if (createNew) { logger.debug("Returning new instance for M_ProductPrice " + productPriceId + " and quantity " + qty); final I_M_ProductScalePrice newInstance = createScalePrice(trxName); newInstance.setM_ProductPrice_ID(productPriceId); newInstance.setQty(qty); return newInstance; } return null; } catch (final SQLException e) { throw new DBException(e, SQL_SCALEPRICE_FOR_QTY); } finally { DB.close(rs, pstmt); } } @Override public I_M_ProductScalePrice retrieveScalePrices(final int productPriceId, final BigDecimal qty, final String trxName) { return retrieveOrCreateScalePrices(productPriceId, qty, false, trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\ProductPA.java
1
请完成以下Java代码
public boolean isNullFieldValue () { Object oo = get_Value(COLUMNNAME_IsNullFieldValue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Operation AD_Reference_ID=205 */ public static final int OPERATION_AD_Reference_ID=205; /** = = == */ public static final String OPERATION_Eq = "=="; /** >= = >= */ public static final String OPERATION_GtEq = ">="; /** > = >> */ public static final String OPERATION_Gt = ">>"; /** < = << */ public static final String OPERATION_Le = "<<"; /** ~ = ~~ */ public static final String OPERATION_Like = "~~"; /** <= = <= */ public static final String OPERATION_LeEq = "<="; /** |<x>| = AB */ public static final String OPERATION_X = "AB"; /** sql = SQ */ public static final String OPERATION_Sql = "SQ"; /** != = != */ public static final String OPERATION_NotEq = "!="; /** Set Arbeitsvorgang . @param Operation Compare Operation */ public void setOperation (String Operation) { set_Value (COLUMNNAME_Operation, Operation);
} /** Get Arbeitsvorgang . @return Compare Operation */ public String getOperation () { return (String)get_Value(COLUMNNAME_Operation); } /** Type AD_Reference_ID=540202 */ public static final int TYPE_AD_Reference_ID=540202; /** Field Value = FV */ public static final String TYPE_FieldValue = "FV"; /** Context Value = CV */ public static final String TYPE_ContextValue = "CV"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Criteria.java
1
请在Spring Boot框架中完成以下Java代码
public R<List<RoleVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> role, BladeUser bladeUser) { QueryWrapper<Role> queryWrapper = Condition.getQueryWrapper(role, Role.class); List<Role> list = roleService.list((!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Role::getTenantId, bladeUser.getTenantId()) : queryWrapper); return R.data(RoleWrapper.build().listNodeVO(list)); } /** * 获取角色树形结构 */ @GetMapping("/tree") @ApiOperationSupport(order = 3) @Operation(summary = "树形结构", description = "树形结构") public R<List<RoleVO>> tree(String tenantId, BladeUser bladeUser) { List<RoleVO> tree = roleService.tree(Func.toStr(tenantId, bladeUser.getTenantId())); return R.data(tree); } /** * 获取指定角色树形结构 */ @GetMapping("/tree-by-id") @ApiOperationSupport(order = 4) @Operation(summary = "树形结构", description = "树形结构") public R<List<RoleVO>> treeById(Long roleId, BladeUser bladeUser) { Role role = roleService.getById(roleId); List<RoleVO> tree = roleService.tree(Func.notNull(role) ? role.getTenantId() : bladeUser.getTenantId()); return R.data(tree); } /** * 新增或修改 */ @PostMapping("/submit") @ApiOperationSupport(order = 5) @Operation(summary = "新增或修改", description = "传入role") public R submit(@Valid @RequestBody Role role, BladeUser user) { CacheUtil.clear(SYS_CACHE); if (Func.isEmpty(role.getId())) { role.setTenantId(user.getTenantId()); }
return R.status(roleService.saveOrUpdate(role)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 6) @Operation(summary = "删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { CacheUtil.clear(SYS_CACHE); return R.status(roleService.removeByIds(Func.toLongList(ids))); } /** * 设置菜单权限 */ @PostMapping("/grant") @ApiOperationSupport(order = 7) @Operation(summary = "权限设置", description = "传入roleId集合以及menuId集合") public R grant(@RequestBody GrantVO grantVO) { CacheUtil.clear(SYS_CACHE); boolean temp = roleService.grant(grantVO.getRoleIds(), grantVO.getMenuIds(), grantVO.getDataScopeIds()); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RoleController.java
2
请完成以下Java代码
public class RateLimitUtil { public static List<RateLimitEntry> parseConfig(String config) { if (config == null || config.isEmpty()) { return Collections.emptyList(); } return Arrays.stream(config.split(",")) .map(RateLimitEntry::parse) .toList(); } public static Function<DefaultTenantProfileConfiguration, String> merge( Function<DefaultTenantProfileConfiguration, String> configExtractor1, Function<DefaultTenantProfileConfiguration, String> configExtractor2) { return config -> { String config1 = configExtractor1.apply(config); String config2 = configExtractor2.apply(config); return RateLimitUtil.mergeStrConfigs(config1, config2); // merges the configs }; } private static String mergeStrConfigs(String firstConfig, String secondConfig) { List<RateLimitEntry> all = new ArrayList<>(); all.addAll(parseConfig(firstConfig)); all.addAll(parseConfig(secondConfig)); Map<Long, Long> merged = new HashMap<>(); for (RateLimitEntry entry : all) { merged.merge(entry.durationSeconds(), entry.capacity(), Long::sum); } return merged.entrySet().stream() .sorted(Map.Entry.comparingByKey()) // optional: sort by duration
.map(e -> e.getValue() + ":" + e.getKey()) .collect(Collectors.joining(",")); } public static boolean isValid(String configStr) { List<RateLimitEntry> limitedApiEntries = parseConfig(configStr); Set<Long> distinctDurations = new HashSet<>(); for (RateLimitEntry entry : limitedApiEntries) { if (!distinctDurations.add(entry.durationSeconds())) { return false; } } return true; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\limit\RateLimitUtil.java
1
请完成以下Java代码
public static InOutAndLineId ofRepoId(@NonNull final InOutId inOutId, final int inOutLineRepoId) { return new InOutAndLineId(inOutId, InOutLineId.ofRepoId(inOutLineRepoId)); } @Nullable public static InOutAndLineId ofRepoIdOrNull(final int inOutRepoId, final int inOutLineRepoId) { final InOutId inoutId = InOutId.ofRepoIdOrNull(inOutRepoId); if(inoutId == null) { return null; } final InOutLineId inoutLineId = InOutLineId.ofRepoIdOrNull(inOutLineRepoId); if(inoutLineId == null) { return null; } return new InOutAndLineId(inoutId, inoutLineId);
} @JsonProperty("inOutId") InOutId inOutId; @JsonProperty("inOutLineId") InOutLineId inOutLineId; @JsonCreator private InOutAndLineId( @JsonProperty("inOutId") @NonNull final InOutId inOutId, @JsonProperty("inOutLineId") @NonNull final InOutLineId inOutLineId) { this.inOutId = inOutId; this.inOutLineId = inOutLineId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\InOutAndLineId.java
1
请完成以下Java代码
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.info("[doGet][uri: {}]", req.getRequestURI()); } }); servletRegistrationBean.setUrlMappings(Collections.singleton("/test/01")); return servletRegistrationBean; } @Bean public FilterRegistrationBean testFilter01() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>(new Filter() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { logger.info("[doFilter]"); filterChain.doFilter(servletRequest, servletResponse); } }); filterRegistrationBean.setUrlPatterns(Collections.singleton("/test/*")); return filterRegistrationBean; } @Bean public ServletListenerRegistrationBean<?> testListener01() {
return new ServletListenerRegistrationBean<>(new ServletContextListener() { @Override public void contextInitialized(ServletContextEvent sce) { logger.info("[contextInitialized]"); } @Override public void contextDestroyed(ServletContextEvent sce) { } }); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-03\src\main\java\cn\iocoder\springboot\lab27\springwebflux\Application.java
1
请完成以下Java代码
public class ServletApplicationFactory extends DefaultApplicationFactory { private final ServletContext servletContext; private final ServerProperties server; private final ManagementServerProperties management; private final InstanceProperties instance; private final DispatcherServletPath dispatcherServletPath; public ServletApplicationFactory(InstanceProperties instance, ManagementServerProperties management, ServerProperties server, ServletContext servletContext, PathMappedEndpoints pathMappedEndpoints, WebEndpointProperties webEndpoint, MetadataContributor metadataContributor, DispatcherServletPath dispatcherServletPath) { super(instance, management, server, pathMappedEndpoints, webEndpoint, metadataContributor); this.servletContext = servletContext; this.server = server; this.management = management; this.instance = instance; this.dispatcherServletPath = dispatcherServletPath; } @Override protected String getServiceUrl() { if (instance.getServiceUrl() != null) { return instance.getServiceUrl(); } return UriComponentsBuilder.fromUriString(getServiceBaseUrl()) .path(getServicePath()) .path(getServerContextPath()) .toUriString(); } @Override protected String getManagementBaseUrl() { String baseUrl = instance.getManagementBaseUrl(); if (StringUtils.hasText(baseUrl)) { return baseUrl;
} if (isManagementPortEqual()) { return UriComponentsBuilder.fromUriString(getServiceUrl()) .path("/") .path(getDispatcherServletPrefix()) .path(getManagementContextPath()) .toUriString(); } Ssl ssl = (management.getSsl() != null) ? management.getSsl() : server.getSsl(); return UriComponentsBuilder.newInstance() .scheme(getScheme(ssl)) .host(getManagementHost()) .port(getLocalManagementPort()) .path(getManagementContextPath()) .toUriString(); } protected String getManagementContextPath() { return management.getBasePath(); } protected String getServerContextPath() { return servletContext.getContextPath(); } protected String getDispatcherServletPrefix() { return this.dispatcherServletPath.getPrefix(); } }
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\ServletApplicationFactory.java
1
请完成以下Java代码
static public <T> IterableDecorator<T, T> filter(Iterable<T> source, Predicate<T> filter) { return new IterableDecorator<>(source, Function.identity(), filter); } public static class IterableDecorator<U, T> implements Iterable<T> { private final Function<U, T> transform; private final Predicate<U> filter; private final Iterable<U> source; IterableDecorator(Iterable<U> source, Function<U, T> transform, Predicate<U> filter) { this.source = source; this.transform = transform; this.filter = filter; } @Override public Iterator<T> iterator() { return new IteratorDecorator<>(this.source.iterator(), this.transform, this.filter); } } public static class IteratorDecorator<U, T> implements Iterator<T> { private final Iterator<U> source; private final Function<U, T> transform; private final Predicate<U> filter; private T next = null; public IteratorDecorator(Iterator<U> source, Function<U, T> transform, Predicate<U> filter) { this.source = source; this.transform = transform; this.filter = filter; } public boolean hasNext() { this.maybeFetchNext(); return next != null; } public T next() {
if (next == null) { throw new NoSuchElementException(); } T val = next; next = null; return val; } private void maybeFetchNext() { if (next == null) { if (source.hasNext()) { U val = source.next(); if (filter.test(val)) { next = transform.apply(val); } } } } public void remove() { throw new UnsupportedOperationException(); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\Iterables.java
1
请完成以下Java代码
public class MainClass { public static final long MINUTES = 1000 * 60; public static void main(String[] args) throws IOException { SlackClientRuntimeConfig runtimeConfig = SlackClientRuntimeConfig.builder() .setTokenSupplier(() -> "<Your API Token>") .build(); SlackClient slackClient = SlackClientFactory.defaultFactory().build(runtimeConfig); ErrorReporter slackChannelErrorReporter = new SlackChannelErrorReporter(slackClient, "general"); ErrorReporter slackUserErrorReporter = new SlackUserErrorReporter(slackClient, "testuser@baeldung.com"); ErrorChecker diskSpaceErrorChecker10pct = new DiskSpaceErrorChecker(slackChannelErrorReporter, 0.1); ErrorChecker diskSpaceErrorChecker2pct = new DiskSpaceErrorChecker(slackUserErrorReporter, 0.02);
Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { diskSpaceErrorChecker10pct.check(); } }, 0, 5 * MINUTES); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { diskSpaceErrorChecker2pct.check(); } }, 0, 5 * MINUTES); } }
repos\tutorials-master\saas-modules\slack\src\main\java\com\baeldung\examples\slack\MainClass.java
1
请完成以下Java代码
public Mono<RSocket> accept(ConnectionSetupPayload setup, RSocket sendingSocket) { MimeType dataMimeType = parseMimeType(setup.dataMimeType(), this.defaultDataMimeType); Assert.notNull(dataMimeType, "No `dataMimeType` in ConnectionSetupPayload and no default value"); MimeType metadataMimeType = parseMimeType(setup.metadataMimeType(), this.defaultMetadataMimeType); Assert.notNull(metadataMimeType, "No `metadataMimeType` in ConnectionSetupPayload and no default value"); // FIXME do we want to make the sendingSocket available in the PayloadExchange return intercept(setup, dataMimeType, metadataMimeType) .flatMap((ctx) -> this.delegate.accept(setup, sendingSocket) .map((acceptingSocket) -> new PayloadInterceptorRSocket(acceptingSocket, this.interceptors, metadataMimeType, dataMimeType, ctx)) .contextWrite(ctx)); } private Mono<Context> intercept(Payload payload, MimeType dataMimeType, MimeType metadataMimeType) { return Mono.defer(() -> { ContextPayloadInterceptorChain chain = new ContextPayloadInterceptorChain(this.interceptors); DefaultPayloadExchange exchange = new DefaultPayloadExchange(PayloadExchangeType.SETUP, payload, metadataMimeType, dataMimeType); return chain.next(exchange).then(Mono.fromCallable(chain::getContext)).defaultIfEmpty(Context.empty()); }); }
private @Nullable MimeType parseMimeType(String str, @Nullable MimeType defaultMimeType) { return StringUtils.hasText(str) ? MimeTypeUtils.parseMimeType(str) : defaultMimeType; } void setDefaultDataMimeType(@Nullable MimeType defaultDataMimeType) { this.defaultDataMimeType = defaultDataMimeType; } void setDefaultMetadataMimeType(MimeType defaultMetadataMimeType) { Assert.notNull(defaultMetadataMimeType, "defaultMetadataMimeType cannot be null"); this.defaultMetadataMimeType = defaultMetadataMimeType; } }
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\core\PayloadSocketAcceptor.java
1
请完成以下Java代码
public static ShipmentAllocationBestBeforePolicy ofCode(@NonNull final String code) { final ShipmentAllocationBestBeforePolicy type = typesByCode.get(code); if (type == null) { throw new AdempiereException("No " + ShipmentAllocationBestBeforePolicy.class + " found for code: " + code); } return type; } private static final ImmutableMap<String, ShipmentAllocationBestBeforePolicy> typesByCode = Maps.uniqueIndex(Arrays.asList(values()), ShipmentAllocationBestBeforePolicy::getCode); public <T> Comparator<T> comparator(@NonNull final Function<T, LocalDate> bestBeforeDateExtractor) { return (value1, value2) -> { final LocalDate bestBefore1 = bestBeforeDateExtractor.apply(value1); final LocalDate bestBefore2 = bestBeforeDateExtractor.apply(value2); return compareBestBeforeDates(bestBefore1, bestBefore2); }; } private int compareBestBeforeDates(@Nullable final LocalDate bestBefore1, @Nullable final LocalDate bestBefore2) { if (this == Expiring_First)
{ final LocalDate bestBefore1Effective = CoalesceUtil.coalesceNotNull(bestBefore1, LocalDate.MAX); final LocalDate bestBefore2Effective = CoalesceUtil.coalesceNotNull(bestBefore2, LocalDate.MAX); return bestBefore1Effective.compareTo(bestBefore2Effective); } else if (this == Newest_First) { final LocalDate bestBefore1Effective = CoalesceUtil.coalesceNotNull(bestBefore1, LocalDate.MIN); final LocalDate bestBefore2Effective = CoalesceUtil.coalesceNotNull(bestBefore2, LocalDate.MIN); return -1 * bestBefore1Effective.compareTo(bestBefore2Effective); } else { throw new AdempiereException("Unknown policy: " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\ShipmentAllocationBestBeforePolicy.java
1
请在Spring Boot框架中完成以下Java代码
public class EdqsExecutors { private final EdqsConfig edqsConfig; private ExecutorService consumersExecutor; private ExecutorService consumerTaskExecutor; private ScheduledExecutorService scheduler; private ListeningExecutorService requestExecutor; @PostConstruct private void init() { consumersExecutor = Executors.newCachedThreadPool(ThingsBoardThreadFactory.forName("edqs-consumer")); consumerTaskExecutor = ThingsBoardExecutors.newWorkStealingPool(4, "edqs-consumer-task-executor"); scheduler = ThingsBoardExecutors.newSingleThreadScheduledExecutor("edqs-scheduler"); requestExecutor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(edqsConfig.getRequestExecutorSize(), "edqs-requests")); } @PreDestroy
private void destroy() { if (consumersExecutor != null) { consumersExecutor.shutdownNow(); } if (consumerTaskExecutor != null) { consumerTaskExecutor.shutdownNow(); } if (scheduler != null) { scheduler.shutdownNow(); } if (requestExecutor != null) { requestExecutor.shutdownNow(); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\edqs\EdqsExecutors.java
2
请完成以下Java代码
public void addAttributeStorageListener(final IAttributeStorageListener listener) { Check.assumeNotNull(listener, "listener not null"); if (attributeStorageListeners.contains(listener)) { // already added return; } attributeStorageListeners.add(listener); // // Update factory(the delegate) if is instantiated if (factory != null) { factory.addAttributeStorageListener(listener); } } @Override public void removeAttributeStorageListener(final IAttributeStorageListener listener) { if (listener == null) { return; } attributeStorageListeners.remove(listener); // Unregister the listner from factory(the delegate) if (factory != null) { factory.removeAttributeStorageListener(listener); } } @Override public boolean isHandled(final Object model) { final IAttributeStorageFactory delegate = getDelegate(); return delegate.isHandled(model); } @Override public IAttributeStorage getAttributeStorage(final Object model) { final IAttributeStorageFactory delegate = getDelegate(); return delegate.getAttributeStorage(model); } @Override public IAttributeStorage getAttributeStorageIfHandled(final Object model) { final IAttributeStorageFactory delegate = getDelegate(); return delegate.getAttributeStorageIfHandled(model); } @Override public final IHUAttributesDAO getHUAttributesDAO() { // TODO tbp: this exception is false: this.huAttributesDAO is NOT NULL! throw new HUException("No IHUAttributesDAO found on " + this); }
@Override public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO) { this.huAttributesDAO = huAttributesDAO; // // Update factory if is instantiated if (factory != null) { factory.setHUAttributesDAO(huAttributesDAO); } } @Override public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO(); } @Override public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory; // // Update factory if is instantiated if (factory != null) { factory.setHUStorageFactory(huStorageFactory); } } @Override public IHUStorageFactory getHUStorageFactory() { return huStorageFactory; } @Override public void flush() { final IHUAttributesDAO huAttributesDAO = this.huAttributesDAO; if (huAttributesDAO != null) { huAttributesDAO.flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ClassAttributeStorageFactory.java
1
请完成以下Java代码
void createBinaryTree() { int[] point = new int[VocabWord.MAX_CODE_LENGTH]; char[] code = new char[VocabWord.MAX_CODE_LENGTH]; int[] count = new int[vocabSize * 2 + 1]; char[] binary = new char[vocabSize * 2 + 1]; int[] parentNode = new int[vocabSize * 2 + 1]; for (int i = 0; i < vocabSize; i++) count[i] = vocab[i].cn; for (int i = vocabSize; i < vocabSize * 2; i++) count[i] = Integer.MAX_VALUE; int pos1 = vocabSize - 1; int pos2 = vocabSize; // Following algorithm constructs the Huffman tree by adding one node at a time int min1i, min2i; for (int i = 0; i < vocabSize - 1; i++) { // First, find two smallest nodes 'min1, min2' if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min1i = pos1; pos1--; } else { min1i = pos2; pos2++; } } else { min1i = pos2; pos2++; } if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min2i = pos1; pos1--; } else { min2i = pos2; pos2++; } } else { min2i = pos2; pos2++; } count[vocabSize + i] = count[min1i] + count[min2i]; parentNode[min1i] = vocabSize + i;
parentNode[min2i] = vocabSize + i; binary[min2i] = 1; } // Now assign binary code to each vocabulary word for (int j = 0; j < vocabSize; j++) { int k = j; int i = 0; while (true) { code[i] = binary[k]; point[i] = k; i++; k = parentNode[k]; if (k == vocabSize * 2 - 2) break; } vocab[j].codelen = i; vocab[j].point[0] = vocabSize - 2; for (k = 0; k < i; k++) { vocab[j].code[i - k - 1] = code[k]; vocab[j].point[i - k] = point[k] - vocabSize; } } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Corpus.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricTaskLogEntryBaseResource { private static Map<String, QueryProperty> allowedSortProperties = new HashMap<>(); static { allowedSortProperties.put("logNumber", HistoricTaskLogEntryQueryProperty.LOG_NUMBER); allowedSortProperties.put("timeStamp", HistoricTaskLogEntryQueryProperty.TIME_STAMP); } @Autowired protected RestResponseFactory restResponseFactory; @Autowired protected HistoryService historyService; @Autowired(required = false) protected BpmnRestApiInterceptor restApiInterceptor; protected DataResponse<HistoricTaskLogEntryResponse> getQueryResponse(HistoricTaskLogEntryQueryRequest request, Map<String, String> allRequestParams) { HistoricTaskLogEntryQuery query = this.historyService.createHistoricTaskLogEntryQuery(); if (request.getTaskId() != null) { query.taskId(allRequestParams.get("taskId")); } if (request.getType() != null) { query.type(allRequestParams.get("type")); } if (request.getUserId() != null) { query.userId(allRequestParams.get("userId")); } if (request.getProcessInstanceId() != null) { query.processInstanceId(allRequestParams.get("processInstanceId")); } if (request.getProcessDefinitionId() != null) { query.processDefinitionId(allRequestParams.get("processDefinitionId")); } if (request.getScopeId() != null) { query.scopeId(allRequestParams.get("scopeId")); } if (request.getScopeDefinitionId() != null) { query.scopeDefinitionId(allRequestParams.get("scopeDefinitionId")); } if (request.getSubScopeId() != null) { query.subScopeId(allRequestParams.get("subScopeId")); } if (request.getScopeType() != null) { query.scopeType(allRequestParams.get("scopeType")); }
if (request.getFrom() != null) { query.from(RequestUtil.getDate(allRequestParams, "from")); } if (request.getTo() != null) { query.to(RequestUtil.getDate(allRequestParams, "to")); } if (request.getTenantId() != null) { query.tenantId(allRequestParams.get("tenantId")); } if (request.getFromLogNumber() != null) { query.fromLogNumber(Long.parseLong(allRequestParams.get("fromLogNumber"))); } if (request.getToLogNumber() != null) { query.toLogNumber(Long.parseLong(allRequestParams.get("toLogNumber"))); } if (restApiInterceptor != null) { restApiInterceptor.accessHistoricTaskLogWithQuery(query, request); } return paginateList(allRequestParams, query, "logNumber", allowedSortProperties, restResponseFactory::createHistoricTaskLogEntryResponseList); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryBaseResource.java
2
请完成以下Java代码
public List<Quote> getQuotes(String baseCurrency, LocalDate date) { List<String> currencyQuery = new ArrayList<>(); Currency.getAvailableCurrencies().forEach(currency -> { if (!baseCurrency.equals(currency.getCurrencyCode())) { currencyQuery.add(String.format(URL_PROVIDER, baseCurrency + currency.getCurrencyCode())); } }); final List<Quote> quotes = new ArrayList<>(); for (String url: currencyQuery) { String response = doGetRequest(url); if (response != null) { final Quote map = map(response); if (map != null) { quotes.add(map); } } } return quotes; } private Quote map(String response) { try (final Jsonb jsonb = JsonbBuilder.create()) { final Map qrw = jsonb.fromJson(response, Map.class); return parseResult(qrw); } catch (Exception e) { System.out.println("Error while trying to read response"); return null; } } private static Quote parseResult(Map qrw) { Quote quote = null; if (qrw != null) { final Map quoteSummary = (Map) qrw.get("quoteSummary"); if (quoteSummary != null) { final List<Map> result = (List<Map>) quoteSummary.get("result"); if (result != null) { final Map resultArray = result.get(0); if (resultArray != null) { final Map summaryDetail = (Map) resultArray.get("summaryDetail"); if (summaryDetail != null) { quote = constructQuote(summaryDetail); } } } } } return quote;
} private static Quote constructQuote(Map summaryDetail) { final String currency = (String) summaryDetail.get("currency"); final Map ask = (Map) summaryDetail.get("ask"); final Map bid = (Map) summaryDetail.get("bid"); final BigDecimal askPrice = (BigDecimal) ask.get("raw"); final BigDecimal bidPrice = (BigDecimal) bid.get("raw"); if (askPrice != null && bidPrice != null) { return new Quote(currency, askPrice, bidPrice); } return null; } String doGetRequest(String url) { System.out.println(url); Request request = new Request.Builder() .url(url) .build(); Response response; try { response = client.newCall(request).execute(); return response.body().string(); } catch (IOException e) { return null; } } }
repos\tutorials-master\core-java-modules\java-spi\exchange-rate-impl\src\main\java\com\baeldung\rate\impl\YahooQuoteManagerImpl.java
1
请完成以下Java代码
public static PickingJobScheduleCollection ofCollection(@NonNull final Collection<PickingJobSchedule> list) { return list.isEmpty() ? EMPTY : new PickingJobScheduleCollection(ImmutableList.copyOf(list)); } public static Collector<PickingJobSchedule, ?, PickingJobScheduleCollection> collect() {return GuavaCollectors.collectUsingListAccumulator(PickingJobScheduleCollection::ofCollection);} public static Collector<PickingJobSchedule, ?, Map<ShipmentScheduleId, PickingJobScheduleCollection>> collectGroupedByShipmentScheduleId() { return Collectors.groupingBy(PickingJobSchedule::getShipmentScheduleId, collect()); } @Override public @NotNull Iterator<PickingJobSchedule> iterator() { return list.iterator(); } public boolean isEmpty() { return list.isEmpty(); } public void assertSingleShipmentScheduleId(final @NonNull ShipmentScheduleId expectedShipmentScheduleId) { final ShipmentScheduleId shipmentScheduleId = getSingleShipmentScheduleId(); if (!ShipmentScheduleId.equals(shipmentScheduleId, expectedShipmentScheduleId)) { throw new AdempiereException("Expected shipment schedule " + expectedShipmentScheduleId + " but found " + shipmentScheduleId) .setParameter("list", list); } } public Set<ShipmentScheduleId> getShipmentScheduleIds() { return byShipmentScheduleId.keySet(); } public ShipmentScheduleId getSingleShipmentScheduleId() { final Set<ShipmentScheduleId> shipmentScheduleIds = getShipmentScheduleIds(); if (shipmentScheduleIds.size() != 1) { throw new AdempiereException("Expected only one shipment schedule").setParameter("list", list); } return shipmentScheduleIds.iterator().next(); } public ShipmentScheduleAndJobScheduleIdSet toShipmentScheduleAndJobScheduleIdSet() { return list.stream()
.map(PickingJobSchedule::getShipmentScheduleAndJobScheduleId) .collect(ShipmentScheduleAndJobScheduleIdSet.collect()); } public boolean isAllProcessed() { return list.stream().allMatch(PickingJobSchedule::isProcessed); } public Optional<Quantity> getQtyToPick() { return list.stream() .map(PickingJobSchedule::getQtyToPick) .reduce(Quantity::add); } public Optional<PickingJobSchedule> getSingleScheduleByShipmentScheduleId(@NonNull ShipmentScheduleId shipmentScheduleId) { final ImmutableList<PickingJobSchedule> schedules = byShipmentScheduleId.get(shipmentScheduleId); if (schedules.isEmpty()) { return Optional.empty(); } else if (schedules.size() == 1) { return Optional.of(schedules.get(0)); } else { throw new AdempiereException("Only one schedule was expected for " + shipmentScheduleId + " but found " + schedules); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\model\PickingJobScheduleCollection.java
1
请完成以下Java代码
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU) { set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU); } @Override public void setM_HU_ID (final int M_HU_ID) { if (M_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID); } @Override public int getM_HU_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Storage getM_HU_Storage() { return get_ValueAsPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class); } @Override public void setM_HU_Storage(final de.metas.handlingunits.model.I_M_HU_Storage M_HU_Storage) { set_ValueFromPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class, M_HU_Storage); } @Override public void setM_HU_Storage_ID (final int M_HU_Storage_ID) { if (M_HU_Storage_ID < 1) set_Value (COLUMNNAME_M_HU_Storage_ID, null); else set_Value (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID); } @Override public int getM_HU_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID); } @Override public void setM_HU_Storage_Snapshot_ID (final int M_HU_Storage_Snapshot_ID) { if (M_HU_Storage_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Storage_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Storage_Snapshot_ID, M_HU_Storage_Snapshot_ID); } @Override public int getM_HU_Storage_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Storage_Snapshot_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Storage_Snapshot.java
1
请在Spring Boot框架中完成以下Java代码
public I_DD_Order getDDOrderById(final DDOrderId ddOrderId) { return ddOrderService.getById(ddOrderId); } public Map<DDOrderId, List<I_DD_OrderLine>> getLinesByDDOrderIds(final Set<DDOrderId> ddOrderIds) { return ddOrderService.streamLinesByDDOrderIds(ddOrderIds) .collect(Collectors.groupingBy(ddOrderLine -> DDOrderId.ofRepoId(ddOrderLine.getDD_Order_ID()), Collectors.toList())); } public Map<DDOrderLineId, List<DDOrderMoveSchedule>> getSchedulesByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds) { if (ddOrderLineIds.isEmpty()) {return ImmutableMap.of();} final Map<DDOrderLineId, List<DDOrderMoveSchedule>> map = ddOrderMoveScheduleService.getByDDOrderLineIds(ddOrderLineIds) .stream() .collect(Collectors.groupingBy(DDOrderMoveSchedule::getDdOrderLineId, Collectors.toList())); return CollectionUtils.fillMissingKeys(map, ddOrderLineIds, ImmutableList.of()); } public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId) { return ddOrderMoveScheduleService.hasInTransitSchedules(inTransitLocatorId); } public ZoneId getTimeZone(final OrgId orgId) { return orgDAO.getTimeZone(orgId);
} public HUInfo getHUInfo(final HuId huId) {return huService.getHUInfoById(huId);} @Nullable public SalesOrderRef getSalesOderRef(@NonNull final I_DD_Order ddOrder) { final OrderId salesOrderId = OrderId.ofRepoIdOrNull(ddOrder.getC_Order_ID()); return salesOrderId != null ? sourceDocService.getSalesOderRef(salesOrderId) : null; } @Nullable public ManufacturingOrderRef getManufacturingOrderRef(@NonNull final I_DD_Order ddOrder) { final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID()); return ppOrderId != null ? sourceDocService.getManufacturingOrderRef(ppOrderId) : null; } @NonNull public PlantInfo getPlantInfo(@NonNull final ResourceId plantId) { return sourceDocService.getPlantInfo(plantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoaderSupportingServices.java
2
请完成以下Java代码
public class SmsAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final Object principal; public SmsAuthenticationToken(String mobile) { super(null); this.principal = mobile; setAuthenticated(false); } public SmsAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; super.setAuthenticated(true); // must use super, as we override } @Override public Object getCredentials() {
return null; } public Object getPrincipal() { return this.principal; } public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { if (isAuthenticated) { throw new IllegalArgumentException( "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); } }
repos\SpringAll-master\38.Spring-Security-SmsCode\src\main\java\cc\mrbird\validate\smscode\SmsAuthenticationToken.java
1
请完成以下Java代码
public class MutableDocumentFieldChangedEvent implements IDocumentFieldChangedEvent { public static final MutableDocumentFieldChangedEvent of(final DocumentPath documentPath, final String fieldName, DocumentFieldWidgetType widgetType) { return new MutableDocumentFieldChangedEvent(documentPath, fieldName, widgetType); } private final DocumentPath documentPath; private final String fieldName; private final DocumentFieldWidgetType widgetType; private Object value; private boolean valueSet = false; private MutableDocumentFieldChangedEvent(final DocumentPath documentPath, final String fieldName, DocumentFieldWidgetType widgetType) { super(); Check.assumeNotNull(documentPath, "Parameter documentPath is not null"); this.documentPath = documentPath; Check.assumeNotEmpty(fieldName, "fieldName is not empty"); this.fieldName = fieldName; Check.assumeNotNull(widgetType, "Parameter widgetType is not null"); this.widgetType = widgetType; } @Override public String toString() { final ToStringHelper helper = MoreObjects.toStringHelper(this) .omitNullValues() .add("documentPath", documentPath) .add("fieldName", fieldName); if (valueSet) { helper.add("value", value == null ? "<NULL>" : value); } return helper.toString(); } @Override public DocumentPath getDocumentPath() { return documentPath; } @Override
public String getFieldName() { return fieldName; } @Override public DocumentFieldWidgetType getWidgetType() { return widgetType; } @Override public boolean isValueSet() { return valueSet; } @Override public Object getValue() { return value; } public MutableDocumentFieldChangedEvent setValue(final Object value) { this.value = value; valueSet = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\MutableDocumentFieldChangedEvent.java
1
请完成以下Java代码
public User getAuthor() { return author; } public void setAuthor(User author) { this.author = author; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() {
return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "title: " + this.title + "\npost: " + this.post + "\nauthor: " + this.author +"\ncreatetdAt: " + this.createdAt + "\nupdatedAt: " + this.updatedAt; } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\Post.java
1
请完成以下Java代码
protected void paintContentBorderTopEdge( Graphics g, int x, int y, int w, int h, boolean drawBroken, Rectangle selRect, boolean isContentBorderPainted) { int right = x + w - 1; int top = y; g.setColor(selectHighlight); if (drawBroken && selRect.x >= x && selRect.x <= x + w) { // Break line to show visual connection to selected tab g.fillRect(x, top, selRect.x - 2 - x, 1); if (selRect.x + selRect.width < x + w - 2) {
g.fillRect(selRect.x + selRect.width + 2, top, right - 2 - selRect.x - selRect.width, 1); } else { g.fillRect(x + w - 2, top, 1, 1); } } else { g.fillRect(x, top, w - 1, 1); } } @Override protected int getTabsOverlay() { return 6; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereTabbedPaneUI.java
1
请完成以下Spring Boot application配置
server: port: 8080 servlet: context-path: /demo spring: rabbitmq: host: localhost port: 5672 username: guest password: guest virtual-host: / # 手动提交消息 listener:
simple: acknowledge-mode: manual direct: acknowledge-mode: manual
repos\spring-boot-demo-master\demo-mq-rabbitmq\src\main\resources\application.yml
2
请完成以下Java代码
public PageData<Tenant> findTenants(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(tenantRepository .findTenantsNextPage( pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<TenantInfo> findTenantInfos(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(tenantRepository .findTenantInfosNextPage( pageLink.getTextSearch(), DaoUtil.toPageable(pageLink, TenantInfoEntity.tenantInfoColumnMap))); } @Override public PageData<TenantId> findTenantsIds(PageLink pageLink) { return DaoUtil.pageToPageData(tenantRepository.findTenantsIds(DaoUtil.toPageable(pageLink))).mapData(TenantId::fromUUID); } @Override public EntityType getEntityType() { return EntityType.TENANT; } @Override
public List<TenantId> findTenantIdsByTenantProfileId(TenantProfileId tenantProfileId) { return tenantRepository.findTenantIdsByTenantProfileId(tenantProfileId.getId()).stream() .map(TenantId::fromUUID) .collect(Collectors.toList()); } @Override public Tenant findTenantByName(TenantId tenantId, String name) { return DaoUtil.getData(tenantRepository.findFirstByTitle(name)); } @Override public List<Tenant> findTenantsByIds(UUID tenantId, List<UUID> tenantIds) { return DaoUtil.convertDataList(tenantRepository.findTenantsByIdIn(tenantIds)); } @Override public List<TenantFields> findNextBatch(UUID id, int batchSize) { return tenantRepository.findNextBatch(id, Limit.of(batchSize)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\tenant\JpaTenantDao.java
1
请完成以下Java代码
private void destroy() { if (queue != null) { queue.destroy(); } } @Override public ListenableFuture<Void> saveAsync(EdgeEvent edgeEvent) { log.debug("Saving EdgeEvent [{}] ", edgeEvent); if (edgeEvent.getId() == null) { UUID timeBased = Uuids.timeBased(); edgeEvent.setId(new EdgeEventId(timeBased)); edgeEvent.setCreatedTime(Uuids.unixTimestamp(timeBased)); } else if (edgeEvent.getCreatedTime() == 0L) { UUID eventId = edgeEvent.getId().getId(); if (eventId.version() == 1) { edgeEvent.setCreatedTime(Uuids.unixTimestamp(eventId)); } else { edgeEvent.setCreatedTime(System.currentTimeMillis()); } } if (StringUtils.isEmpty(edgeEvent.getUid())) { edgeEvent.setUid(edgeEvent.getId().toString()); } EdgeEventEntity entity = new EdgeEventEntity(edgeEvent); createPartition(entity); return save(entity); } private ListenableFuture<Void> save(EdgeEventEntity entity) { log.debug("Saving EdgeEventEntity [{}] ", entity); if (entity.getTenantId() == null) { log.trace("Save system edge event with predefined id {}", systemTenantId); entity.setTenantId(systemTenantId); } if (entity.getUuid() == null) { entity.setUuid(Uuids.timeBased()); } return addToQueue(entity); }
private ListenableFuture<Void> addToQueue(EdgeEventEntity entity) { return queue.add(entity); } @Override public PageData<EdgeEvent> findEdgeEvents(UUID tenantId, EdgeId edgeId, Long seqIdStart, Long seqIdEnd, TimePageLink pageLink) { return DaoUtil.toPageData( edgeEventRepository .findEdgeEventsByTenantIdAndEdgeId( tenantId, edgeId.getId(), pageLink.getTextSearch(), pageLink.getStartTime(), pageLink.getEndTime(), seqIdStart, seqIdEnd, DaoUtil.toPageable(pageLink, SORT_ORDERS))); } @Override public void cleanupEvents(long ttl) { partitioningRepository.dropPartitionsBefore(TABLE_NAME, ttl, TimeUnit.HOURS.toMillis(partitionSizeInHours)); } @Override public void createPartition(EdgeEventEntity entity) { partitioningRepository.createPartitionIfNotExists(TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\JpaBaseEdgeEventDao.java
1
请完成以下Java代码
public boolean isDoNotIncludeVariables() { return doNotIncludeVariables; } public void setDoNotIncludeVariables(boolean doNotIncludeVariables) { this.doNotIncludeVariables = doNotIncludeVariables; } @Override public List<IOParameter> getInParameters() { return inParameters; } @Override public void addInParameter(IOParameter inParameter) { if (inParameters == null) { inParameters = new ArrayList<>(); } inParameters.add(inParameter); } @Override public void setInParameters(List<IOParameter> inParameters) { this.inParameters = inParameters; } @Override public ScriptTask clone() { ScriptTask clone = new ScriptTask(); clone.setValues(this); return clone; } public void setValues(ScriptTask otherElement) { super.setValues(otherElement);
setScriptFormat(otherElement.getScriptFormat()); setScript(otherElement.getScript()); setResultVariable(otherElement.getResultVariable()); setSkipExpression(otherElement.getSkipExpression()); setAutoStoreVariables(otherElement.isAutoStoreVariables()); setDoNotIncludeVariables(otherElement.isDoNotIncludeVariables()); inParameters = null; if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) { inParameters = new ArrayList<>(); for (IOParameter parameter : otherElement.getInParameters()) { inParameters.add(parameter.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptTask.java
1
请完成以下Java代码
public CaseSentryPartQueryImpl standardEvent(String standardEvent) { ensureNotNull(NotValidException.class, "standardEvent", standardEvent); this.standardEvent = standardEvent; return this; } public CaseSentryPartQueryImpl variableEvent(String variableEvent) { ensureNotNull(NotValidException.class, "variableEvent", variableEvent); this.variableEvent = variableEvent; return this; } public CaseSentryPartQueryImpl variableName(String variableName) { ensureNotNull(NotValidException.class, "variableName", variableName); this.variableName = variableName; return this; } public CaseSentryPartQueryImpl satisfied() { this.satisfied = true; return this; } // order by /////////////////////////////////////////// public CaseSentryPartQueryImpl orderByCaseSentryId() { orderBy(CaseSentryPartQueryProperty.CASE_SENTRY_PART_ID); return this; } public CaseSentryPartQueryImpl orderByCaseInstanceId() { orderBy(CaseSentryPartQueryProperty.CASE_INSTANCE_ID); return this; } public CaseSentryPartQueryImpl orderByCaseExecutionId() { orderBy(CaseSentryPartQueryProperty.CASE_EXECUTION_ID); return this; } public CaseSentryPartQueryImpl orderBySentryId() { orderBy(CaseSentryPartQueryProperty.SENTRY_ID); return this; } public CaseSentryPartQueryImpl orderBySource() { orderBy(CaseSentryPartQueryProperty.SOURCE); return this; } // results //////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getCaseSentryPartManager() .findCaseSentryPartCountByQueryCriteria(this);
} public List<CaseSentryPartEntity> executeList(CommandContext commandContext, Page page) { checkQueryOk(); List<CaseSentryPartEntity> result = commandContext .getCaseSentryPartManager() .findCaseSentryPartByQueryCriteria(this, page); return result; } // getters ///////////////////////////////////////////// public String getId() { return id; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public String getSentryId() { return sentryId; } public String getType() { return type; } public String getSourceCaseExecutionId() { return sourceCaseExecutionId; } public String getStandardEvent() { return standardEvent; } public String getVariableEvent() { return variableEvent; } public String getVariableName() { return variableName; } public boolean isSatisfied() { return satisfied; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List < Employee > findAll() { return jdbcTemplate.query("select * from employees", new EmployeeRowMapper()); } public Optional < Employee > findById(long id) { return Optional.of(jdbcTemplate.queryForObject("select * from employees where id=?", new Object[] { id }, new BeanPropertyRowMapper < Employee > (Employee.class))); } public int deleteById(long id) { return jdbcTemplate.update("delete from employees where id=?", new Object[] { id }); }
public int insert(Employee employee) { return jdbcTemplate.update("insert into employees (id, first_name, last_name, email_address) " + "values(?, ?, ?, ?)", new Object[] { employee.getId(), employee.getFirstName(), employee.getLastName(), employee.getEmailId() }); } public int update(Employee employee) { return jdbcTemplate.update("update employees " + " set first_name = ?, last_name = ?, email_address = ? " + " where id = ?", new Object[] { employee.getFirstName(), employee.getLastName(), employee.getEmailId(), employee.getId() }); } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jdbc-crud-mysql-example\src\main\java\net\alanbinu\springboot2\jdbc\repository\EmployeeJDBCRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class RecordAccessRevokeRequest { TableRecordReference recordRef; Principal principal; PermissionIssuer issuer; boolean revokeAllPermissions; ImmutableSet<Access> permissions; final UserId requestedBy; @Builder private RecordAccessRevokeRequest( @NonNull final TableRecordReference recordRef, @NonNull Principal principal, @NonNull PermissionIssuer issuer, // final boolean revokeAllPermissions, @Singular final Set<Access> permissions, // @NonNull final UserId requestedBy)
{ this.recordRef = recordRef; this.principal = principal; this.issuer = issuer; if (revokeAllPermissions) { this.revokeAllPermissions = true; this.permissions = ImmutableSet.of(); } else { Check.assumeNotEmpty(permissions, "permissions is not empty"); this.revokeAllPermissions = false; this.permissions = ImmutableSet.copyOf(permissions); } this.requestedBy = requestedBy; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessRevokeRequest.java
2
请完成以下Java代码
private boolean isMSV3ServerProduct(final MSV3ServerConfig serverConfig, final I_M_Product product) { if (!serverConfig.hasProducts()) { return false; } if (!product.isActive()) { return false; } final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(product.getM_Product_Category_ID()); if (!serverConfig.getProductCategoryIds().contains(productCategoryId)) {
return false; } return true; } private MSV3ServerConfigService getServerConfigService() { return Adempiere.getBean(MSV3ServerConfigService.class); } private MSV3StockAvailabilityService getStockAvailabilityService() { return Adempiere.getBean(MSV3StockAvailabilityService.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\M_Product.java
1
请完成以下Java代码
public boolean isSnapshotsEnabled() { return this.snapshotsEnabled; } public void setSnapshotsEnabled(boolean snapshotsEnabled) { this.snapshotsEnabled = snapshotsEnabled; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Repository other = (Repository) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.releasesEnabled != other.releasesEnabled) { return false; } if (this.snapshotsEnabled != other.snapshotsEnabled) { return false; } if (this.url == null) { if (other.url != null) { return false; } } else if (!this.url.equals(other.url)) { return false; } return true; } @Override
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + (this.releasesEnabled ? 1231 : 1237); result = prime * result + (this.snapshotsEnabled ? 1231 : 1237); result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); return result; } @Override public String toString() { return new StringJoiner(", ", Repository.class.getSimpleName() + "[", "]").add("name='" + this.name + "'") .add("url=" + this.url) .add("releasesEnabled=" + this.releasesEnabled) .add("snapshotsEnabled=" + this.snapshotsEnabled) .toString(); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Repository.java
1
请完成以下Java代码
public byte[] decodeUsingBigInteger(String hexString) { byte[] byteArray = new BigInteger(hexString, 16).toByteArray(); if (byteArray[0] == 0) { byte[] output = new byte[byteArray.length - 1]; System.arraycopy(byteArray, 1, output, 0, output.length); return output; } return byteArray; } public String encodeUsingDataTypeConverter(byte[] bytes) { return DatatypeConverter.printHexBinary(bytes); } public byte[] decodeUsingDataTypeConverter(String hexString) { return DatatypeConverter.parseHexBinary(hexString); } public String encodeUsingApacheCommons(byte[] bytes) { return Hex.encodeHexString(bytes); } public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException { return Hex.decodeHex(hexString); } public String encodeUsingGuava(byte[] bytes) { return BaseEncoding.base16() .encode(bytes); }
public byte[] decodeUsingGuava(String hexString) { return BaseEncoding.base16() .decode(hexString.toUpperCase()); } public String encodeUsingHexFormat(byte[] bytes) { HexFormat hexFormat = HexFormat.of(); return hexFormat.formatHex(bytes); } public byte[] decodeUsingHexFormat(String hexString) { HexFormat hexFormat = HexFormat.of(); return hexFormat.parseHex(hexString); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\conversion\HexStringConverter.java
1
请完成以下Java代码
public boolean isDate() { return type == CellValueType.Date; } public java.util.Date dateValue() { return TimeUtil.asDate(valueObj); } public boolean isNumber() { return type == CellValueType.Number; } public double doubleValue() {
return ((Number)valueObj).doubleValue(); } public boolean isBoolean() { return type == CellValueType.Boolean; } public boolean booleanValue() { return (boolean)valueObj; } public String stringValue() { return valueObj.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\CellValue.java
1
请在Spring Boot框架中完成以下Java代码
public List<CommentAssembly> findAllAssemblyByArticleId(Long userId, long articleId) { return assemblyRepository.findAllByArticleId(articleId, userId).stream() .map(commentMapper::toDomain) .toList(); } @Override public Comment save(Comment comment) { var entity = commentMapper.fromDomain(comment); var saved = repository.save(entity); return commentMapper.toDomain(saved); } @Override public void deleteById(long id) { repository.deleteById(id); } @Override public void deleteAllByArticleId(long articleId) { repository.deleteAllByArticleId(articleId); } @Mapper(config = MappingConfig.class)
interface CommentMapper { Comment toDomain(CommentJdbcEntity source); CommentJdbcEntity fromDomain(Comment source); @Mapping(target = "author", source = "source") CommentAssembly toDomain(CommentAssemblyJdbcEntity source); default Profile profile(CommentAssemblyJdbcEntity source) { return new Profile(source.authorUsername(), source.authorBio(), source.authorImage(), source.authorFollowing()); } } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\CommentJdbcRepositoryAdapter.java
2
请完成以下Java代码
private void updateHeaderInNewTrx(final Collection<OrderId> orderIds) { final ITrxManager trxManager = get_TrxManager(); trxManager.runInNewTrx(() -> updateHeaderNow(ImmutableSet.copyOf(orderIds))); } private static void updateHeaderNow(final Set<OrderId> orderIds) { // shall not happen if (orderIds.isEmpty()) { return; } // Update Order Header: TotalLines { final ArrayList<Object> sqlParams = new ArrayList<>(); final String sql = "UPDATE C_Order o" + " SET TotalLines=" + "(SELECT COALESCE(SUM(ol.LineNetAmt),0) FROM C_OrderLine ol WHERE ol.C_Order_ID=o.C_Order_ID) " + "WHERE " + DB.buildSqlList("C_Order_ID", orderIds, sqlParams); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), ITrx.TRXNAME_ThreadInherited); if (no != 1) {
new AdempiereException("Updating TotalLines failed for C_Order_IDs=" + orderIds); } } // Update Order Header: GrandTotal { final ArrayList<Object> sqlParams = new ArrayList<>(); final String sql = "UPDATE C_Order o " + " SET GrandTotal=TotalLines+" // SUM up C_OrderTax.TaxAmt only for those lines which does not have Tax Included + "(SELECT COALESCE(SUM(TaxAmt),0) FROM C_OrderTax ot WHERE o.C_Order_ID=ot.C_Order_ID AND ot.IsActive='Y' AND ot.IsTaxIncluded='N') " + "WHERE " + DB.buildSqlList("C_Order_ID", orderIds, sqlParams); final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, sqlParams.toArray(), ITrx.TRXNAME_ThreadInherited); if (no != 1) { new AdempiereException("Updating GrandTotal failed for C_Order_IDs=" + orderIds); } } } } // MOrderLine
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MOrderLine.java
1
请完成以下Java代码
public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) { Assert.notNull(this.postAuthenticationChecks, "postAuthenticationChecks cannot be null"); this.postAuthenticationChecks = postAuthenticationChecks; } /** * @since 5.5 */ @Override public void setMessageSource(MessageSource messageSource) { Assert.notNull(messageSource, "messageSource cannot be null"); this.messages = new MessageSourceAccessor(messageSource); } /** * Sets the {@link ReactiveCompromisedPasswordChecker} to be used before creating a * successful authentication. Defaults to {@code null}. * @param compromisedPasswordChecker the {@link CompromisedPasswordChecker} to use
* @since 6.3 */ public void setCompromisedPasswordChecker(ReactiveCompromisedPasswordChecker compromisedPasswordChecker) { this.compromisedPasswordChecker = compromisedPasswordChecker; } /** * Allows subclasses to retrieve the <code>UserDetails</code> from an * implementation-specific location. * @param username The username to retrieve * @return the user information. If authentication fails, a Mono error is returned. */ protected abstract Mono<UserDetails> retrieveUser(String username); }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AbstractUserDetailsReactiveAuthenticationManager.java
1
请在Spring Boot框架中完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMessage() { return message; } public void setMessage(String message) {
this.message = message; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isSaveProcessInstanceId() { return saveProcessInstanceId; } public void setSaveProcessInstanceId(boolean saveProcessInstanceId) { this.saveProcessInstanceId = saveProcessInstanceId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentRequest.java
2
请完成以下Java代码
public void notTakingTranistion(PvmTransition outgoingTransition) { logDebug( "001", "Not taking transition '{}', outgoing execution has ended.", outgoingTransition); } public void debugExecutesActivity(PvmExecutionImpl execution, ActivityImpl activity, String name) { logDebug( "002", "{} executed activity {}: {}", execution, activity, name); } public void debugLeavesActivityInstance(PvmExecutionImpl execution, String activityInstanceId) { logDebug( "003", "Execution {} leaves activity instance {}", execution, activityInstanceId); } public void debugDestroyScope(PvmExecutionImpl execution, PvmExecutionImpl propagatingExecution) { logDebug( "004", "Execution {} leaves parent scope {}", execution, propagatingExecution); } public void destroying(PvmExecutionImpl pvmExecutionImpl) { logDebug( "005", "Detroying scope {}", pvmExecutionImpl); } public void removingEventScope(PvmExecutionImpl childExecution) { logDebug( "006", "Removeing event scope {}", childExecution); }
public void interruptingExecution(String reason, boolean skipCustomListeners) { logDebug( "007", "Interrupting execution execution {}, {}", reason, skipCustomListeners); } public void debugEnterActivityInstance(PvmExecutionImpl pvmExecutionImpl, String parentActivityInstanceId) { logDebug( "008", "Enter activity instance {} parent: {}", pvmExecutionImpl, parentActivityInstanceId); } public void exceptionWhileCompletingSupProcess(PvmExecutionImpl execution, Exception e) { logError( "009", "Exception while completing subprocess of execution {}", execution, e); } public void createScope(PvmExecutionImpl execution, PvmExecutionImpl propagatingExecution) { logDebug( "010", "Create scope: parent exection {} continues as {}", execution, propagatingExecution); } public ProcessEngineException scopeNotFoundException(String activityId, String executionId) { return new ProcessEngineException(exceptionMessage( "011", "Scope with specified activity Id {} and execution {} not found", activityId,executionId )); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\PvmLogger.java
1
请完成以下Spring Boot application配置
# # Copyright 2015-2023 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # logging.level.root=WARN logging.level.sample.mybatis.freemarker.mapper=TRACE mybatis.mapper-locations=classpath*:/mappers/*.xml mybatis.type-al
iases-package=sample.mybatis.freemarker.domain mybatis.scripting-language-driver.freemarker.template-file.base-dir=mappers/ mybatis.scripting-language-driver.freemarker.template-file.path-provider.includes-package-path=false mybatis.scripting-language-driver.freemarker.template-file.path-provider.separate-directory-per-mapper=false
repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-freemarker\src\main\resources\application.properties
2
请完成以下Java代码
public Deque<?> parse(String searchParam) { Deque<Object> output = new LinkedList<>(); Deque<String> stack = new LinkedList<>(); Arrays.stream(searchParam.split("\\s+")).forEach(token -> { if (ops.containsKey(token)) { while (!stack.isEmpty() && isHigerPrecedenceOperator(token, stack.peek())) output.push(stack.pop() .equalsIgnoreCase(SearchOperation.OR_OPERATOR) ? SearchOperation.OR_OPERATOR : SearchOperation.AND_OPERATOR); stack.push(token.equalsIgnoreCase(SearchOperation.OR_OPERATOR) ? SearchOperation.OR_OPERATOR : SearchOperation.AND_OPERATOR); } else if (token.equals(SearchOperation.LEFT_PARANTHESIS)) { stack.push(SearchOperation.LEFT_PARANTHESIS); } else if (token.equals(SearchOperation.RIGHT_PARANTHESIS)) { while (!stack.peek() .equals(SearchOperation.LEFT_PARANTHESIS)) output.push(stack.pop()); stack.pop(); } else {
Matcher matcher = SpecCriteraRegex.matcher(token); while (matcher.find()) { output.push(new SpecSearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5))); } } }); while (!stack.isEmpty()) output.push(stack.pop()); return output; } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\web\util\CriteriaParser.java
1
请完成以下Java代码
public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Override public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } @Override public String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } @Override public String getElementName() { return elementName; } public void setElementName(String elementName) { this.elementName = elementName; } @Override public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } @Override public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } @Override public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } @Override public String getJobHandlerType() { return jobHandlerType; } public void setJobHandlerType(String jobHandlerType) { this.jobHandlerType = jobHandlerType; } @Override public String getJobHandlerConfiguration() { return jobHandlerConfiguration;
} public void setJobHandlerConfiguration(String jobHandlerConfiguration) { this.jobHandlerConfiguration = jobHandlerConfiguration; } public String getRepeat() { return repeat; } public void setRepeat(String repeat) { this.repeat = repeat; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String getExceptionMessage() { return exceptionMessage; } public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH); } @Override public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getCorrelationId() { // v5 Jobs have no correlationId return null; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_M_PromotionGroupLine[") .append(get_ID()).append("]"); return sb.toString(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException { return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name) .getPO(getM_PromotionGroup_ID(), get_TrxName()); } /** Set Promotion Group.
@param M_PromotionGroup_ID Promotion Group */ public void setM_PromotionGroup_ID (int M_PromotionGroup_ID) { if (M_PromotionGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID)); } /** Get Promotion Group. @return Promotion Group */ public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Group Line. @param M_PromotionGroupLine_ID Promotion Group Line */ public void setM_PromotionGroupLine_ID (int M_PromotionGroupLine_ID) { if (M_PromotionGroupLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, Integer.valueOf(M_PromotionGroupLine_ID)); } /** Get Promotion Group Line. @return Promotion Group Line */ public int getM_PromotionGroupLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroupLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroupLine.java
1
请完成以下Java代码
public Boolean getIncludeEventSubscriptionsWithoutTenantId() { return includeEventSubscriptionsWithoutTenantId; } @CamundaQueryParam(value = "includeEventSubscriptionsWithoutTenantId", converter = BooleanConverter.class) public void setIncludeEventSubscriptionsWithoutTenantId(Boolean includeEventSubscriptionsWithoutTenantId) { this.includeEventSubscriptionsWithoutTenantId = includeEventSubscriptionsWithoutTenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected EventSubscriptionQuery createNewQuery(ProcessEngine engine) { return engine.getRuntimeService().createEventSubscriptionQuery(); } @Override protected void applyFilters(EventSubscriptionQuery query) { if (eventSubscriptionId != null) { query.eventSubscriptionId(eventSubscriptionId); } if (eventName != null) { query.eventName(eventName); } if (eventType != null) { query.eventType(eventType); } if (executionId != null) { query.executionId(executionId); } if (processInstanceId != null) { query.processInstanceId(processInstanceId); } if (activityId != null) { query.activityId(activityId); }
if (tenantIdIn != null && !tenantIdIn.isEmpty()) { query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) { query.includeEventSubscriptionsWithoutTenantId(); } } @Override protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_CREATED)) { query.orderByCreated(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionQueryDto.java
1
请完成以下Java代码
public Attribute getByCode(final AttributeCode attributeCode) { final Attribute attribute = getByCodeOrNull(attributeCode); if (attribute == null) { throw new AdempiereException("No active attribute found for `" + attributeCode + "`"); } return attribute; } public Attribute getByCodeOrNull(final AttributeCode attributeCode) { return attributesByCode.get(attributeCode); } @NonNull public Attribute getById(@NonNull final AttributeId id) { final Attribute attribute = getByIdOrNull(id); if (attribute == null) { throw new AdempiereException("No Attribute found for ID: " + id); } return attribute; } @Nullable public Attribute getByIdOrNull(final @NotNull AttributeId id) { return attributesById.get(id); } @NonNull public Set<Attribute> getByIds(@NonNull final Collection<AttributeId> ids) { if (ids.isEmpty()) {return ImmutableSet.of();} return ids.stream() .distinct() .map(this::getById) .collect(ImmutableSet.toImmutableSet()); } @NonNull public AttributeId getIdByCode(@NonNull final AttributeCode attributeCode) { return getByCode(attributeCode).getAttributeId(); }
public Set<Attribute> getByCodes(final Set<AttributeCode> attributeCodes) { if (attributeCodes.isEmpty()) {return ImmutableSet.of();} return attributeCodes.stream() .distinct() .map(this::getByCode) .collect(ImmutableSet.toImmutableSet()); } @NonNull public ImmutableList<AttributeCode> getOrderedAttributeCodesByIds(@NonNull final List<AttributeId> orderedAttributeIds) { if (orderedAttributeIds.isEmpty()) { return ImmutableList.of(); } return orderedAttributeIds.stream() .map(this::getById) .filter(Attribute::isActive) .map(Attribute::getAttributeCode) .collect(ImmutableList.toImmutableList()); } public Stream<Attribute> streamActive() { return attributesById.values().stream().filter(Attribute::isActive); } public boolean isActiveAttribute(final AttributeId id) { final Attribute attribute = getByIdOrNull(id); return attribute != null && attribute.isActive(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributesMap.java
1
请完成以下Java代码
public String getPermissionsPolicy() { return permissionsPolicy; } public void setPermissionsPolicy(String permissionsPolicy) { this.permissionsPolicy = permissionsPolicy; } /** * @return the default/opt-out header names to disable */ public List<String> getDisable() { return disabledHeaders.stream().toList(); } /** * Binds the list of default/opt-out header names to disable, transforms them into a * lowercase set. This is to ensure case-insensitive comparison. * @param disable - list of default/opt-out header names to disable */ public void setDisable(List<String> disable) { if (disable != null) { disabledHeaders = disable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet()); } } /** * @return the opt-in header names to enable */ public Set<String> getEnabledHeaders() { return enabledHeaders; } /** * Binds the list of default/opt-out header names to enable, transforms them into a * lowercase set. This is to ensure case-insensitive comparison. * @param enable - list of default/opt-out header enable */ public void setEnable(List<String> enable) { if (enable != null) { enabledHeaders = enable.stream().map(String::toLowerCase).collect(Collectors.toUnmodifiableSet()); } }
/** * @return the default/opt-out header names to disable */ public Set<String> getDisabledHeaders() { return disabledHeaders; } /** * @return the default/opt-out header names to apply */ public Set<String> getDefaultHeaders() { return defaultHeaders; } @Override public String toString() { return "SecureHeadersProperties{" + "xssProtectionHeader='" + xssProtectionHeader + '\'' + ", strictTransportSecurity='" + strictTransportSecurity + '\'' + ", frameOptions='" + frameOptions + '\'' + ", contentTypeOptions='" + contentTypeOptions + '\'' + ", referrerPolicy='" + referrerPolicy + '\'' + ", contentSecurityPolicy='" + contentSecurityPolicy + '\'' + ", downloadOptions='" + downloadOptions + '\'' + ", permittedCrossDomainPolicies='" + permittedCrossDomainPolicies + '\'' + ", permissionsPolicy='" + permissionsPolicy + '\'' + ", defaultHeaders=" + defaultHeaders + ", enable=" + enabledHeaders + ", disable=" + disabledHeaders + '}'; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersProperties.java
1
请在Spring Boot框架中完成以下Java代码
public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } @Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<ReactiveSessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<ReactiveSessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() { return this.sessionRepositoryCustomizers; } protected ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() { RedisSerializer<String> keySerializer = RedisSerializer.string(); RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer : new JdkSerializationRedisSerializer(); RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(defaultSerializer) .key(keySerializer) .hashKey(keySerializer) .build(); return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext); } public ReactiveRedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\AbstractRedisWebSessionConfiguration.java
2
请完成以下Java代码
public org.compiere.model.I_GL_JournalBatch getReversal() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_JournalBatch.class); } @Override public void setReversal(org.compiere.model.I_GL_JournalBatch Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_GL_JournalBatch.class, Reversal); } /** Set Reversal ID. @param Reversal_ID ID of document reversal */ @Override public void setReversal_ID (int Reversal_ID) { if (Reversal_ID < 1) set_Value (COLUMNNAME_Reversal_ID, null); else set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID)); } /** Get Reversal ID. @return ID of document reversal */ @Override public int getReversal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Total Credit. @param TotalCr Total Credit in document currency */ @Override public void setTotalCr (java.math.BigDecimal TotalCr) { set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr); }
/** Get Total Credit. @return Total Credit in document currency */ @Override public java.math.BigDecimal getTotalCr () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalCr); if (bd == null) return Env.ZERO; return bd; } /** Set Total Debit. @param TotalDr Total debit in document currency */ @Override public void setTotalDr (java.math.BigDecimal TotalDr) { set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr); } /** Get Total Debit. @return Total debit in document currency */ @Override public java.math.BigDecimal getTotalDr () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalDr); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalBatch.java
1
请完成以下Java代码
private Collection<EventLogId> getEventLogIdsUsingCacheOutOfTrx(@NonNull final Collection<UUID> uuids) { return uuid2eventLogId.getAllOrLoad(uuids, this::retrieveAllRecordIdOutOfTrx); } private ImmutableMap<UUID, EventLogId> retrieveAllRecordIdOutOfTrx(@NonNull final Collection<UUID> uuids) { if (uuids.isEmpty()) { return ImmutableMap.of(); } final ImmutableSet<String> uuidStrs = uuids.stream().map(UUID::toString).collect(ImmutableSet.toImmutableSet()); return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_EventLog.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_AD_EventLog.COLUMN_Event_UUID, uuidStrs) .orderBy(I_AD_EventLog.COLUMN_AD_EventLog_ID) // just to have a predictable order .create() .listColumns(I_AD_EventLog.COLUMNNAME_AD_EventLog_ID, I_AD_EventLog.COLUMNNAME_Event_UUID) .stream() .map(map -> { final int eventLogRepoId = NumberUtils.asInt(map.get(I_AD_EventLog.COLUMNNAME_AD_EventLog_ID), -1); final EventLogId eventLogId = EventLogId.ofRepoId(eventLogRepoId); final UUID uuid = UUID.fromString(map.get(I_AD_EventLog.COLUMNNAME_Event_UUID).toString()); return GuavaCollectors.entry(uuid, eventLogId); }) .collect(GuavaCollectors.toImmutableMap()); } private void updateUpdateEventLogErrorFlagFromEntries(@NonNull final Set<EventLogId> eventLogsWithError)
{ if (eventLogsWithError.isEmpty()) { return; } Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_EventLog.class) .addInArrayFilter(I_AD_EventLog.COLUMNNAME_AD_EventLog_ID, eventLogsWithError) .create() .updateDirectly() .addSetColumnValue(I_AD_EventLog.COLUMNNAME_IsError, true) .execute(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogsRepository.java
1
请完成以下Java代码
public void save(final I_M_HU_Storage storage) { final SaveDecoupledHUStorageDAO delegate = getDelegate(storage); delegate.save(storage); } @Override public List<I_M_HU_Storage> retrieveStorages(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.retrieveStorages(hu); } @Override public void save(final I_M_HU_Item_Storage storageLine) { final SaveDecoupledHUStorageDAO delegate = getDelegate(storageLine); delegate.save(storageLine); } @Override public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item item) { final SaveDecoupledHUStorageDAO delegate = getDelegate(item); return delegate.retrieveItemStorages(item); } @Override public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item item, @NonNull final ProductId productId) { final SaveDecoupledHUStorageDAO delegate = getDelegate(item); return delegate.retrieveItemStorage(item, productId); } @Override public void save(final I_M_HU_Item item) {
final SaveDecoupledHUStorageDAO delegate = getDelegate(item); delegate.save(item); } @Override public I_C_UOM getC_UOMOrNull(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.getC_UOMOrNull(hu); } @Override public UOMType getC_UOMTypeOrNull(final I_M_HU hu) { final SaveDecoupledHUStorageDAO delegate = getDelegate(hu); return delegate.getC_UOMTypeOrNull(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\SaveOnCommitHUStorageDAO.java
1
请完成以下Java代码
private ITranslatableString retrieveManufacturingOrderDocumentNo(final PPOrderId manufacturingOrderId) { return TranslatableStrings.anyLanguage(sourceDocService.getDocumentNoById(manufacturingOrderId)); } private ITranslatableString getProductName(final ProductId productId) { return productNames.computeIfAbsent(productId, this::retrieveProductName); } private ITranslatableString retrieveProductName(final ProductId productId) { return TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId)); } @NonNull public static Quantity extractQtyEntered(final I_DD_OrderLine ddOrderLine) { return Quantitys.of(ddOrderLine.getQtyEntered(), UomId.ofRepoId(ddOrderLine.getC_UOM_ID())); } private void processPendingRequests() { if (!pendingCollectProductsFromDDOrderIds.isEmpty()) { ddOrderService.getProductIdsByDDOrderIds(pendingCollectProductsFromDDOrderIds) .forEach(this::collectProduct);
pendingCollectProductsFromDDOrderIds.clear(); } if (!pendingCollectQuantitiesFromDDOrderIds.isEmpty()) { ddOrderService.streamLinesByDDOrderIds(pendingCollectQuantitiesFromDDOrderIds) .forEach(this::collectQuantity); pendingCollectQuantitiesFromDDOrderIds.clear(); } } private ITranslatableString getPlantName(final ResourceId resourceId) { return resourceNames.computeIfAbsent(resourceId, id -> TranslatableStrings.constant(sourceDocService.getPlantName(id))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetsCollector.java
1
请完成以下Java代码
public boolean canRead(ResolvableType type, @Nullable MediaType mediaType) { Class<?> clazz = type.resolve(); return (clazz != null) ? canRead(clazz, mediaType) : canRead(mediaType); } @Override public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) { return this.delegate.canRead(clazz, mediaType); } @Override public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) { return this.delegate.canWrite(clazz, mediaType); } @Override public List<MediaType> getSupportedMediaTypes() { return this.delegate.getSupportedMediaTypes(); } @Override public List<MediaType> getSupportedMediaTypes(Class<?> clazz) { return this.delegate.getSupportedMediaTypes(clazz);
} @Override protected void writeInternal(T t, ResolvableType type, HttpOutputMessage outputMessage, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotWritableException { this.delegate.write(t, null, outputMessage); } @Override public T read(ResolvableType type, HttpInputMessage inputMessage, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotReadableException { return this.delegate.read(type.getType(), null, inputMessage); } @Override public boolean canWrite(ResolvableType targetType, Class<?> valueClass, @Nullable MediaType mediaType) { return this.delegate.canWrite(targetType.getType(), valueClass, mediaType); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\authentication\WebAuthnAuthenticationFilter.java
1
请在Spring Boot框架中完成以下Java代码
public void create(Database resources) { resources.setId(IdUtil.simpleUUID()); databaseRepository.save(resources); } @Override @Transactional(rollbackFor = Exception.class) public void update(Database resources) { Database database = databaseRepository.findById(resources.getId()).orElseGet(Database::new); ValidationUtil.isNull(database.getId(),"Database","id",resources.getId()); database.copy(resources); databaseRepository.save(database); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Set<String> ids) { for (String id : ids) { databaseRepository.deleteById(id); } } @Override public boolean testConnection(Database resources) { try { return SqlUtils.testConnection(resources.getJdbcUrl(), resources.getUserName(), resources.getPwd()); } catch (Exception e) { log.error(e.getMessage()); return false; } }
@Override public void download(List<DatabaseDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (DatabaseDto databaseDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("数据库名称", databaseDto.getName()); map.put("数据库连接地址", databaseDto.getJdbcUrl()); map.put("用户名", databaseDto.getUserName()); map.put("创建日期", databaseDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DatabaseServiceImpl.java
2
请完成以下Java代码
public static DbSqlSession getDbSqlSession() { return getDbSqlSession(getCommandContext()); } public static DbSqlSession getDbSqlSession(CommandContext commandContext) { return commandContext.getSession(DbSqlSession.class); } public static EventResourceEntityManager getResourceEntityManager() { return getResourceEntityManager(getCommandContext()); } public static EventResourceEntityManager getResourceEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getResourceEntityManager(); } public static EventDeploymentEntityManager getDeploymentEntityManager() { return getDeploymentEntityManager(getCommandContext()); } public static EventDeploymentEntityManager getDeploymentEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getDeploymentEntityManager(); } public static EventDefinitionEntityManager getEventDefinitionEntityManager() { return getEventDefinitionEntityManager(getCommandContext()); } public static EventDefinitionEntityManager getEventDefinitionEntityManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getEventDefinitionEntityManager(); } public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager() { return getChannelDefinitionEntityManager(getCommandContext()); } public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager(CommandContext commandContext) {
return getEventRegistryConfiguration(commandContext).getChannelDefinitionEntityManager(); } public static TableDataManager getTableDataManager() { return getTableDataManager(getCommandContext()); } public static TableDataManager getTableDataManager(CommandContext commandContext) { return getEventRegistryConfiguration(commandContext).getTableDataManager(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\util\CommandContextUtil.java
1
请完成以下Java代码
public class HistoricCaseInstanceQueryProperty implements QueryProperty { private static final long serialVersionUID = 1L; private static final Map<String, HistoricCaseInstanceQueryProperty> properties = new HashMap<>(); public static final HistoricCaseInstanceQueryProperty CASE_INSTANCE_ID = new HistoricCaseInstanceQueryProperty("RES.ID_"); public static final HistoricCaseInstanceQueryProperty CASE_DEFINITION_KEY = new HistoricCaseInstanceQueryProperty("CASE_DEF.KEY_"); public static final HistoricCaseInstanceQueryProperty CASE_DEFINITION_ID = new HistoricCaseInstanceQueryProperty("RES.CASE_DEF_ID_"); public static final HistoricCaseInstanceQueryProperty CASE_INSTANCE_NAME = new HistoricCaseInstanceQueryProperty("RES.NAME_"); public static final HistoricCaseInstanceQueryProperty CASE_START_TIME = new HistoricCaseInstanceQueryProperty("RES.START_TIME_"); public static final HistoricCaseInstanceQueryProperty CASE_END_TIME = new HistoricCaseInstanceQueryProperty("RES.END_TIME_"); public static final HistoricCaseInstanceQueryProperty TENANT_ID = new HistoricCaseInstanceQueryProperty("RES.TENANT_ID_"); private String name;
public HistoricCaseInstanceQueryProperty(String name) { this.name = name; properties.put(name, this); } @Override public String getName() { return name; } public static HistoricCaseInstanceQueryProperty findByName(String propertyName) { return properties.get(propertyName); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricCaseInstanceQueryProperty.java
1
请完成以下Java代码
public EventModelBuilder resourceName(String resourceName) { this.resourceName = resourceName; return this; } @Override public EventModelBuilder category(String category) { this.category = category; return this; } @Override public EventModelBuilder parentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; return this; } @Override public EventModelBuilder deploymentTenantId(String deploymentTenantId) { this.deploymentTenantId = deploymentTenantId; return this; } @Override public EventModelBuilder header(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.header(name, type)); return this; } @Override public EventModelBuilder headerWithCorrelation(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.headerWithCorrelation(name, type)); return this; } @Override public EventModelBuilder correlationParameter(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.correlation(name, type)); return this; } @Override public EventModelBuilder payload(String name, String type) { eventPayloadDefinitions.put(name, new EventPayload(name, type)); return this; } @Override public EventModelBuilder metaParameter(String name, String type) { EventPayload payload = new EventPayload(name, type); payload.setMetaParameter(true); eventPayloadDefinitions.put(name, payload); return this; } @Override public EventModelBuilder fullPayload(String name) { eventPayloadDefinitions.put(name, EventPayload.fullPayload(name)); return this; } @Override public EventModel createEventModel() { return buildEventModel(); }
@Override public EventDeployment deploy() { if (resourceName == null) { throw new FlowableIllegalArgumentException("A resource name is mandatory"); } EventModel eventModel = buildEventModel(); return eventRepository.createDeployment() .name(deploymentName) .addEventDefinition(resourceName, eventJsonConverter.convertToJson(eventModel)) .category(category) .parentDeploymentId(parentDeploymentId) .tenantId(deploymentTenantId) .deploy(); } protected EventModel buildEventModel() { EventModel eventModel = new EventModel(); if (StringUtils.isNotEmpty(key)) { eventModel.setKey(key); } else { throw new FlowableIllegalArgumentException("An event definition key is mandatory"); } eventModel.setPayload(eventPayloadDefinitions.values()); return eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\EventModelBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // The memory user is not configured, but the UserService just created is configured into the AuthenticationManagerBuilder. auth.userDetailsService(userService); } @Order @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() /*.antMatchers("/admin/**").hasRole("ADMIN")//Indicates that the user accessing the URL in the "/admin/**" mode must have the role of ADMIN .antMatchers("/user/**").access("hasAnyRole('ADMIN','USER')") .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") .anyRequest().authenticated()//Indicates that in addition to the URL pattern defined previously, users must access other URLs after authentication (access after logging in) */ .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() { @Override public <O extends FilterSecurityInterceptor> O postProcess(O object) { object.setSecurityMetadataSource(cfisms()); object.setAccessDecisionManager(cadm());
return object; } }) .and() .formLogin() .loginProcessingUrl("/login").permitAll() .and() .csrf().disable(); } @Bean CustomFilterInvocationSecurityMetadataSource cfisms() { return new CustomFilterInvocationSecurityMetadataSource(); } @Bean CustomAccessDecisionManager cadm() { return new CustomAccessDecisionManager(); } }
repos\springboot-demo-master\security\src\main\java\com\et\security\config\WebSecurityConfig.java
2
请完成以下Java代码
public class IntroductionInline { public static void main(String[] args) { KnowledgeService service = new KnowledgeService(); Knowledge knowledge = service .newKnowledge() .newRule("Clear total sales") .forEach("$c", Customer.class) .execute(ctx -> { Customer c = ctx.get("$c"); c.setTotal(0.0); }) .newRule("Compute totals") .forEach( "$c", Customer.class, "$i", Invoice.class ) .where("$i.customer == $c") .execute(ctx -> { Customer c = ctx.get("$c"); Invoice i = ctx.get("$i"); c.addToTotal(i.getAmount()); }); List<Customer> customers = Arrays.asList( new Customer("Customer A"), new Customer("Customer B"), new Customer("Customer C") ); Random random = new Random(); Collection<Object> sessionData = new LinkedList<>(customers); for (int i = 0; i < 100_000; i++) { Customer randomCustomer = customers.get(random.nextInt(customers.size()));
Invoice invoice = new Invoice(randomCustomer, 100 * random.nextDouble()); sessionData.add(invoice); } knowledge .newStatelessSession() .insert(sessionData) .fire(); for (Customer c : customers) { System.out.printf("%s:\t$%,.2f%n", c.getName(), c.getTotal()); } service.shutdown(); } }
repos\tutorials-master\rule-engines-modules\evrete\src\main\java\com\baeldung\evrete\introduction\IntroductionInline.java
1
请完成以下Java代码
public applet setName (String name) { addAttribute ("name", name); return (this); } /** * Serialized applet file. * * @param object * Serialized applet file. */ // someone give me a better description of what this does. public applet setObject (String object) { addAttribute ("object", object); return (this); } /** * Breif description, alternate text for the applet. * * @param alt * alternat text. */ public applet setAlt (String alt) { addAttribute ("alt", alt); return (this); } /** * Sets the lang="" and xml:lang="" attributes * * @param lang * the lang="" and xml:lang="" attributes */ public Element setLang (String lang) { addAttribute ("lang", lang); addAttribute ("xml:lang", lang); return this; } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public applet addElement (String hashcode, Element element) { addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public applet addElement (String hashcode, String element) { addElementToRegistry (hashcode, element); return (this);
} /** * Add an element to the element * * @param element * a string representation of the element */ public applet addElement (String element) { addElementToRegistry (element); return (this); } /** * Add an element to the element * * @param element * an element to add */ public applet addElement (Element element) { addElementToRegistry (element); return (this); } /** * Removes an Element from the element. * * @param hashcode * the name of the element to be removed. */ public applet removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\applet.java
1