instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static void ifPortBindingException(Exception ex, Consumer<BindException> action) { ifCausedBy(ex, BindException.class, (bindException) -> { // bind exception can be also thrown because an address can't be assigned String message = bindException.getMessage(); if (message != null && message.toLowerCase(Locale.ROOT).contains("in use")) { action.accept(bindException); } }); } /** * Perform an action if the given exception was caused by a specific exception type. * @param <E> the cause exception type * @param ex the source exception * @param causedBy the required cause type * @param action the action to perform
* @since 2.2.7 */ @SuppressWarnings("unchecked") public static <E extends Exception> void ifCausedBy(Exception ex, Class<E> causedBy, Consumer<E> action) { Throwable candidate = ex; while (candidate != null) { if (causedBy.isInstance(candidate)) { action.accept((E) candidate); return; } candidate = candidate.getCause(); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\PortInUseException.java
1
请完成以下Java代码
public String getReportMemberName() { return reportMemberName; } public void setReportMemberName(String reportMemberName) { this.reportMemberName = reportMemberName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getReportObject() { return reportObject; } public void setReportObject(String reportObject) { this.reportObject = reportObject; } public Integer getReportStatus() { return reportStatus; } public void setReportStatus(Integer reportStatus) { this.reportStatus = reportStatus; } public Integer getHandleStatus() { return handleStatus; } public void setHandleStatus(Integer handleStatus) { this.handleStatus = handleStatus; } public String getNote() { return note; }
public void setNote(String note) { this.note = note; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", reportType=").append(reportType); sb.append(", reportMemberName=").append(reportMemberName); sb.append(", createTime=").append(createTime); sb.append(", reportObject=").append(reportObject); sb.append(", reportStatus=").append(reportStatus); sb.append(", handleStatus=").append(handleStatus); sb.append(", note=").append(note); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsMemberReport.java
1
请完成以下Java代码
public class ConsumerApp { public static void main(String[] args) throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.digest(new byte[256]); byte[] dummy = digest.digest(); int hashLen = dummy.length; System.out.println("Starting consumer iterations..."); long size = Long.parseLong(args[1]); MappedByteBuffer shm = createSharedMemory(args[0], size + hashLen); long start = System.currentTimeMillis(); long iterations = 0; int capacity = shm.capacity(); long matchCount = 0; long mismatchCount = 0; byte[] expectedHash = new byte[hashLen]; while (System.currentTimeMillis() - start < 30_000) { for (int i = 0; i < capacity - hashLen; i++) { byte value = shm.get(i); digest.update(value); } byte[] hash = digest.digest(); shm.position(capacity-hashLen); shm.get(expectedHash); if (Arrays.equals(hash, expectedHash)) { matchCount++; } else { mismatchCount++; } iterations++; } System.out.printf("%d iterations run. matches=%d, mismatches=%d\n", iterations, matchCount, mismatchCount); System.out.println("Press <enter> to exit"); System.console() .readLine(); } private static MappedByteBuffer createSharedMemory(String path, long size) {
try (FileChannel fc = (FileChannel) Files.newByteChannel( new File(path).toPath(), EnumSet.of( StandardOpenOption.CREATE, StandardOpenOption.SPARSE, StandardOpenOption.WRITE, StandardOpenOption.READ))) { return fc.map(FileChannel.MapMode.READ_WRITE, 0, size); } catch (IOException ioe) { throw new RuntimeException(ioe); } } private static long getBufferAddress(MappedByteBuffer shm) { try { Class<?> cls = shm.getClass(); Method maddr = cls.getMethod("address"); maddr.setAccessible(true); Long addr = (Long) maddr.invoke(shm); if (addr == null) { throw new RuntimeException("Unable to retrieve buffer's address"); } return addr; } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } } }
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\sharedmem\ConsumerApp.java
1
请完成以下Java代码
public String getCamundaFormRef() { return camundaFormRefAttribute.getValue(this); } public void setCamundaFormRef(String camundaFormRef) { camundaFormRefAttribute.setValue(this, camundaFormRef); } public String getCamundaFormRefBinding() { return camundaFormRefBindingAttribute.getValue(this); } public void setCamundaFormRefBinding(String camundaFormRefBinding) { camundaFormRefBindingAttribute.setValue(this, camundaFormRefBinding); }
public String getCamundaFormRefVersion() { return camundaFormRefVersionAttribute.getValue(this); } public void setCamundaFormRefVersion(String camundaFormRefVersion) { camundaFormRefVersionAttribute.setValue(this, camundaFormRefVersion); } public String getCamundaInitiator() { return camundaInitiatorAttribute.getValue(this); } public void setCamundaInitiator(String camundaInitiator) { camundaInitiatorAttribute.setValue(this, camundaInitiator); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\StartEventImpl.java
1
请在Spring Boot框架中完成以下Java代码
public static class RewriteLocationResponseHeaderConfig { private StripVersion stripVersion = StripVersion.AS_IN_REQUEST; private String locationHeaderName = HttpHeaders.LOCATION; private @Nullable String hostValue; private String protocolsRegex = DEFAULT_PROTOCOLS; private Pattern hostPortPattern = DEFAULT_HOST_PORT; private Pattern hostPortVersionPattern = DEFAULT_HOST_PORT_VERSION; public StripVersion getStripVersion() { return stripVersion; } public RewriteLocationResponseHeaderConfig setStripVersion(String stripVersion) { this.stripVersion = StripVersion.valueOf(stripVersion); return this; } public RewriteLocationResponseHeaderConfig setStripVersion(StripVersion stripVersion) { this.stripVersion = stripVersion; return this; } public String getLocationHeaderName() { return locationHeaderName; } public RewriteLocationResponseHeaderConfig setLocationHeaderName(String locationHeaderName) { this.locationHeaderName = locationHeaderName; return this; } public @Nullable String getHostValue() { return hostValue; } public RewriteLocationResponseHeaderConfig setHostValue(String hostValue) { this.hostValue = hostValue; return this;
} public String getProtocolsRegex() { return protocolsRegex; } public RewriteLocationResponseHeaderConfig setProtocolsRegex(String protocolsRegex) { this.protocolsRegex = protocolsRegex; this.hostPortPattern = compileHostPortPattern(protocolsRegex); this.hostPortVersionPattern = compileHostPortVersionPattern(protocolsRegex); return this; } public Pattern getHostPortPattern() { return hostPortPattern; } public Pattern getHostPortVersionPattern() { return hostPortVersionPattern; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RewriteLocationResponseHeaderFilterFunctions.java
2
请完成以下Java代码
public int getAD_Color_ID (int index) { if (index < 0 || index > m_windows.size()) { throw new IllegalArgumentException ("Index invalid: " + index); } WBWindow win = m_windows.get(index); int retValue = -1; // if (win.mWindow != null && win.Type == TYPE_WINDOW) // return win.mWindow.getAD_Color_ID(); if (retValue == -1) { return getAD_Color_ID(); } return retValue; } // getAD_Color_ID /** * Set WindowNo of Window * @param index index in workbench * @param windowNo window no */ public void setWindowNo (int index, int windowNo) { if (index < 0 || index > m_windows.size()) { throw new IllegalArgumentException ("Index invalid: " + index); } WBWindow win = m_windows.get(index); win.WindowNo = windowNo; } // getWindowNo /** * Get WindowNo of Window * @param index index in workbench * @return WindowNo of Window if previously set, otherwise -1; */ public int getWindowNo (int index) { if (index < 0 || index > m_windows.size()) { throw new IllegalArgumentException ("Index invalid: " + index); } WBWindow win = m_windows.get(index); return win.WindowNo; } // getWindowNo /** * Dispose of Window * @param index index in workbench */ public void dispose (int index) { if (index < 0 || index > m_windows.size()) { throw new IllegalArgumentException ("Index invalid: " + index); } WBWindow win = m_windows.get(index); if (win.mWindow != null) { win.mWindow.dispose(); } win.mWindow = null; } // dispose /** * Get Window Size * @return window size or null if not set */ public Dimension getWindowSize() { return null; } // getWindowSize /************************************************************************** * Window Type */ class WBWindow { /** * WBWindow * @param type * @param id
*/ public WBWindow (int type, int id) { Type = type; ID = id; } /** Type */ public int Type = 0; /** ID */ public int ID = 0; /** Window No */ public int WindowNo = -1; /** Window Model */ public GridWindow mWindow = null; // public MFrame mFrame = null; // public MProcess mProcess = null; } // WBWindow // metas: begin public GridWindow getMWindowById(AdWindowId adWindowId) { if (adWindowId == null) { return null; } for (WBWindow win : m_windows) { if (win.Type == TYPE_WINDOW && AdWindowId.equals(adWindowId, win.mWindow.getAdWindowId())) { return win.mWindow; } } return null; } // metas: end } // Workbench
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWorkbench.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_R_Category[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } 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(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Category. @param R_Category_ID Request Category */ public void setR_Category_ID (int R_Category_ID) { if (R_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_R_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Category_ID, Integer.valueOf(R_Category_ID)); } /** Get Category. @return Request Category */ public int getR_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Category_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_R_Category.java
1
请完成以下Java代码
public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getRole() { return role; } public void setRole(Integer role) { this.role = role; }
public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
repos\springBoot-master\springboot-elasticsearch\src\main\java\cn\abel\bean\User.java
1
请在Spring Boot框架中完成以下Java代码
public List<Tag> findAll() { return repository.findAll().stream() .map(tagMapper::toDomain) .toList(); } @Override public Tag save(Tag tag) { var entity = tagMapper.fromDomain(tag); var saved = repository.save(entity); return tagMapper.toDomain(saved); } @Override public List<Tag> saveAll(Collection<Tag> tags) {
var entities = tags.stream().map(tagMapper::fromDomain).toList(); var saved = repository.saveAll(entities); return saved.stream().map(tagMapper::toDomain).toList(); } @Mapper(config = MappingConfig.class) interface TagMapper { Tag toDomain(TagJdbcEntity source); TagJdbcEntity fromDomain(Tag source); } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\TagJdbcRepositoryAdapter.java
2
请完成以下Java代码
public void setC_OrderPO(final org.compiere.model.I_C_Order C_OrderPO) { set_ValueFromPO(COLUMNNAME_C_OrderPO_ID, org.compiere.model.I_C_Order.class, C_OrderPO); } @Override public void setC_OrderPO_ID (final int C_OrderPO_ID) { if (C_OrderPO_ID < 1) set_Value (COLUMNNAME_C_OrderPO_ID, null); else set_Value (COLUMNNAME_C_OrderPO_ID, C_OrderPO_ID); } @Override public int getC_OrderPO_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderPO_ID); } @Override public void setC_PurchaseCandidate_Alloc_ID (final int C_PurchaseCandidate_Alloc_ID) { if (C_PurchaseCandidate_Alloc_ID < 1) set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_Alloc_ID, null); else set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_Alloc_ID, C_PurchaseCandidate_Alloc_ID); } @Override public int getC_PurchaseCandidate_Alloc_ID() { return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_Alloc_ID); } @Override public de.metas.purchasecandidate.model.I_C_PurchaseCandidate getC_PurchaseCandidate() { return get_ValueAsPO(COLUMNNAME_C_PurchaseCandidate_ID, de.metas.purchasecandidate.model.I_C_PurchaseCandidate.class); } @Override public void setC_PurchaseCandidate(final de.metas.purchasecandidate.model.I_C_PurchaseCandidate C_PurchaseCandidate) { set_ValueFromPO(COLUMNNAME_C_PurchaseCandidate_ID, de.metas.purchasecandidate.model.I_C_PurchaseCandidate.class, C_PurchaseCandidate); } @Override public void setC_PurchaseCandidate_ID (final int C_PurchaseCandidate_ID) { if (C_PurchaseCandidate_ID < 1) set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_ID, null); else set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_ID, C_PurchaseCandidate_ID); } @Override public int getC_PurchaseCandidate_ID() { return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_ID); } @Override public void setDateOrdered (final @Nullable java.sql.Timestamp DateOrdered) { set_Value (COLUMNNAME_DateOrdered, DateOrdered); } @Override public java.sql.Timestamp getDateOrdered() { return get_ValueAsTimestamp(COLUMNNAME_DateOrdered); }
@Override public void setDatePromised (final @Nullable java.sql.Timestamp DatePromised) { set_Value (COLUMNNAME_DatePromised, DatePromised); } @Override public java.sql.Timestamp getDatePromised() { return get_ValueAsTimestamp(COLUMNNAME_DatePromised); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRemotePurchaseOrderId (final @Nullable java.lang.String RemotePurchaseOrderId) { set_Value (COLUMNNAME_RemotePurchaseOrderId, RemotePurchaseOrderId); } @Override public java.lang.String getRemotePurchaseOrderId() { return get_ValueAsString(COLUMNNAME_RemotePurchaseOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate_Alloc.java
1
请完成以下Java代码
public DTO getResource(@QueryParam(VariableResource.DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValue) { U variableInstance = baseQueryForVariable(deserializeObjectValue).singleResult(); if (variableInstance != null) { return transformToDto(variableInstance); } else { throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); } } @GET @Path("/data") public Response getResourceBinary() { U queryResult = baseQueryForBinaryVariable().singleResult(); if (queryResult != null) { TypedValue variableInstance = transformQueryResultIntoTypedValue(queryResult); return new VariableResponseProvider().getResponseForTypedVariable(variableInstance, id); } else { throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); } } protected String getId() { return id; } protected ProcessEngine getEngine() { return engine; }
/** * Create the query we need for fetching the desired result. Setting * properties in the query like disableCustomObjectDeserialization() or * disableBinaryFetching() should be done in this method. */ protected abstract Query<T, U> baseQueryForBinaryVariable(); /** * TODO change comment Create the query we need for fetching the desired * result. Setting properties in the query like * disableCustomObjectDeserialization() or disableBinaryFetching() should be * done in this method. * * @param deserializeObjectValue */ protected abstract Query<T, U> baseQueryForVariable(boolean deserializeObjectValue); protected abstract TypedValue transformQueryResultIntoTypedValue(U queryResult); protected abstract DTO transformToDto(U queryResult); protected abstract String getResourceNameForErrorMessage(); }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\AbstractResourceProvider.java
1
请完成以下Java代码
public List<VariableInstanceEntity> findVariableInstancesByCaseExecutionId(String caseExecutionId) { return findVariableInstancesByCaseExecutionIdAndVariableNames(caseExecutionId, null); } @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByCaseExecutionIdAndVariableNames(String caseExecutionId, Collection<String> variableNames) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("caseExecutionId", caseExecutionId); parameter.put("variableNames", variableNames); return getDbEntityManager().selectList("selectVariablesByCaseExecutionId", parameter); } public void deleteVariableInstanceByTask(TaskEntity task) { List<VariableInstanceEntity> variableInstances = task.variableStore.getVariables(); for (VariableInstanceEntity variableInstance: variableInstances) { variableInstance.delete(); } } public long findVariableInstanceCountByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery) { configureQuery(variableInstanceQuery); return (Long) getDbEntityManager().selectOne("selectVariableInstanceCountByQueryCriteria", variableInstanceQuery); } @SuppressWarnings("unchecked")
public List<VariableInstance> findVariableInstanceByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery, Page page) { configureQuery(variableInstanceQuery); return getDbEntityManager().selectList("selectVariableInstanceByQueryCriteria", variableInstanceQuery, page); } protected void configureQuery(VariableInstanceQueryImpl query) { getAuthorizationManager().configureVariableInstanceQuery(query); getTenantManager().configureQuery(query); } @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByBatchId(String batchId) { Map<String, String> parameters = Collections.singletonMap("batchId", batchId); return getDbEntityManager().selectList("selectVariableInstancesByBatchId", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceManager.java
1
请完成以下Java代码
public Object put(String key, Object value) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException("decision output is immutable"); } @Override public void clear() { throw new UnsupportedOperationException("decision output is immutable"); } @Override public Set<Entry<String, Object>> entrySet() { Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) { DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue()); entrySet.add(entry); } return entrySet; } protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> { protected final String key; protected final TypedValue typedValue; public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) { this.key = key; this.typedValue = typedValue; } @Override
public String getKey() { return key; } @Override public Object getValue() { if (typedValue != null) { return typedValue.getValue(); } else { return null; } } @Override public Object setValue(Object value) { throw new UnsupportedOperationException("decision output entry is immutable"); } } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java
1
请完成以下Java代码
public <ID extends RepoIdAware, ET extends T> Map<ID, ET> mapByRepoIdAware(@NonNull final IntFunction<ID> idMapper, @NonNull final Class<ET> clazz) throws DBException { final Function<ET, ID> record2RepoIdAware = (record) -> { final int recordId = InterfaceWrapperHelper.getId(record); return idMapper.apply(recordId); }; return stream(clazz) .collect(ImmutableMap.toImmutableMap(record2RepoIdAware, Function.identity())); } @Override public final List<Map<String, Object>> listColumns(final String... columnNames) { final boolean distinct = false; return listColumns(distinct, columnNames); } @Override public final List<Map<String, Object>> listDistinct(final String... columnNames) { final boolean distinct = true; return listColumns(distinct, columnNames); } /** * Selects given columns and return the result as a list of ColumnName to Value map. * * @param distinct true if the value rows shall be district * @return a list of rows, where each row is a {@link Map} having the required columns as keys. */ protected abstract List<Map<String, Object>> listColumns(final boolean distinct, final String... columnNames); @Override public <K, ET extends T> ImmutableMap<K, ET> map(final Class<ET> modelClass, final Function<ET, K> keyFunction) { final List<ET> list = list(modelClass); return Maps.uniqueIndex(list, keyFunction::apply); } @Override public <K> ImmutableMap<K, T> map(@NonNull final Function<T, K> keyFunction) { final List<T> list = list(); return Maps.uniqueIndex(list, keyFunction::apply); } @Override public <K, ET extends T> ListMultimap<K, ET> listMultimap(final Class<ET> modelClass, final Function<ET, K> keyFunction) { final ListMultimap<K, ET> map = LinkedListMultimap.create(); final List<ET> list = list(modelClass); for (final ET item : list) {
final K key = keyFunction.apply(item); map.put(key, item); } return map; } @Override public <K, ET extends T> Collection<List<ET>> listAndSplit(final Class<ET> modelClass, final Function<ET, K> keyFunction) { final ListMultimap<K, ET> map = listMultimap(modelClass, keyFunction); return Multimaps.asMap(map).values(); } @Override public ICompositeQueryUpdaterExecutor<T> updateDirectly() { return new CompositeQueryUpdaterExecutor<>(this); } @Override public <ToModelType> IQueryInsertExecutor<ToModelType, T> insertDirectlyInto(final Class<ToModelType> toModelClass) { return new QueryInsertExecutor<>(toModelClass, this); } /** * Convenience method that evaluates {@link IQuery#OPTION_ReturnReadOnlyRecords}. */ protected boolean isReadOnlyRecords() { return Boolean.TRUE.equals(getOption(OPTION_ReturnReadOnlyRecords)); } abstract <ToModelType> QueryInsertExecutorResult executeInsert(final QueryInsertExecutor<ToModelType, T> queryInserter); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AbstractTypedQuery.java
1
请完成以下Java代码
public static void addInvolvedCaseInstanceId(CommandContext commandContext, String caseInstanceId) { if (caseInstanceId != null) { Set<String> involvedCaseInstanceIds = null; Object obj = commandContext.getAttribute(ATTRIBUTE_INVOLVED_CASE_INSTANCE_IDS); if (obj != null) { involvedCaseInstanceIds = (Set<String>) obj; } else { involvedCaseInstanceIds = new HashSet<>(1); // typically will be only 1 entry commandContext.addAttribute(ATTRIBUTE_INVOLVED_CASE_INSTANCE_IDS, involvedCaseInstanceIds); } involvedCaseInstanceIds.add(caseInstanceId); } } @SuppressWarnings("unchecked") public static Set<String> getInvolvedCaseInstanceIds(CommandContext commandContext) { Object obj = commandContext.getAttribute(ATTRIBUTE_INVOLVED_CASE_INSTANCE_IDS); if (obj != null) { return (Set<String>) obj; } return null; } public static CaseInstanceHelper getCaseInstanceHelper() { return getCaseInstanceHelper(getCommandContext()); } public static CaseInstanceHelper getCaseInstanceHelper(CommandContext commandContext) { return getCmmnEngineConfiguration(commandContext).getCaseInstanceHelper(); }
public static CommandContext getCommandContext() { return Context.getCommandContext(); } public static DmnEngineConfigurationApi getDmnEngineConfiguration(CommandContext commandContext) { return (DmnEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_DMN_ENGINE_CONFIG); } public static DmnDecisionService getDmnRuleService(CommandContext commandContext) { DmnEngineConfigurationApi dmnEngineConfiguration = getDmnEngineConfiguration(commandContext); if (dmnEngineConfiguration == null) { throw new FlowableException("Dmn engine is not configured"); } return dmnEngineConfiguration.getDmnDecisionService(); } public static InternalTaskAssignmentManager getInternalTaskAssignmentManager(CommandContext commandContext) { return getCmmnEngineConfiguration(commandContext).getTaskServiceConfiguration().getInternalTaskAssignmentManager(); } public static InternalTaskAssignmentManager getInternalTaskAssignmentManager() { return getInternalTaskAssignmentManager(getCommandContext()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\CommandContextUtil.java
1
请完成以下Java代码
public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public Date getRemovalTime() {
return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", name=" + name + ", deploymentId=" + deploymentId + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
1
请完成以下Java代码
public final V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { final Object valueObj = extractParameterValue(ctx); if (valueObj == null) { if (onVariableNotFound == OnVariableNotFound.ReturnNoResult) // i.e. !ignoreUnparsable { return noResultValue; } else if (onVariableNotFound == OnVariableNotFound.Fail) { throw ExpressionEvaluationException.newWithTranslatableMessage("@NotFound@: " + parameter); } else { throw new IllegalArgumentException("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound); } } return valueConverter.convertFrom(valueObj, options); } } protected abstract static class GeneralExpressionTemplate<V, ET extends IExpression<V>> extends ExpressionTemplateBase<V, ET> { private final StringExpression stringExpression; /* package */ GeneralExpressionTemplate(final ExpressionContext context, final Compiler<V, ET> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler); stringExpression = new StringExpression(expressionStr, expressionChunks); } @Override public String getExpressionString() { return stringExpression.getExpressionString(); }
@Override public String getFormatedExpressionString() { return stringExpression.getFormatedExpressionString(); } @Override public Set<String> getParameterNames() { return stringExpression.getParameterNames(); } @Override public Set<CtxName> getParameters() { return stringExpression.getParameters(); } @Override public V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { final String resultStr = stringExpression.evaluate(ctx, onVariableNotFound); if (stringExpression.isNoResult(resultStr)) { if (onVariableNotFound == OnVariableNotFound.ReturnNoResult) // i.e. !ignoreUnparsable { return noResultValue; } // else if (onVariableNotFound == OnVariableNotFound.Fail) // no need to handle this case because we expect an exception to be already thrown else { throw new IllegalArgumentException("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound); } } return valueConverter.convertFrom(resultStr, options); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\StringExpressionSupportTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public void createDatabaseSchema() throws Exception { this.createDatabaseSchema(true); } @Override public void createDatabaseSchema(boolean createIndexes) throws Exception { log.info("Installing SQL DataBase schema part: " + schemaSql); executeQueryFromFile(schemaSql); if (createIndexes) { this.createDatabaseIndexes(); } } @Override public void createDatabaseIndexes() throws Exception { if (schemaIdxSql != null) { log.info("Installing SQL DataBase schema indexes part: " + schemaIdxSql); executeQueryFromFile(schemaIdxSql); } } void executeQueryFromFile(String schemaIdxSql) throws SQLException, IOException { Path schemaIdxFile = Paths.get(installScripts.getDataDir(), SQL_DIR, schemaIdxSql); String sql = Files.readString(schemaIdxFile);
try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) { conn.createStatement().execute(sql); //NOSONAR, ignoring because method used to load initial thingsboard database schema } } protected void executeQuery(String query) { executeQuery(query, null); } protected void executeQuery(String query, String logQuery) { logQuery = logQuery != null ? logQuery : query; try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) { conn.createStatement().execute(query); //NOSONAR, ignoring because method used to execute thingsboard database upgrade script log.info("Successfully executed query: {}", logQuery); Thread.sleep(5000); } catch (InterruptedException | SQLException e) { throw new RuntimeException("Failed to execute query: " + logQuery, e); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\SqlAbstractDatabaseSchemaService.java
2
请完成以下Java代码
public void doBefore(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); // 排除不可切换数据源的方法 DefaultDatasource annotation = method.getAnnotation(DefaultDatasource.class); if (null != annotation) { DatasourceConfigContextHolder.setDefaultDatasource(); } else { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes; HttpServletRequest request = attributes.getRequest(); String configIdInHeader = request.getHeader("Datasource-Config-Id"); if (StringUtils.hasText(configIdInHeader)) { long configId = Long.parseLong(configIdInHeader); DatasourceConfigContextHolder.setCurrentDatasourceConfig(configId);
} else { DatasourceConfigContextHolder.setDefaultDatasource(); } } } /** * 后置操作,设置回默认的数据源id */ @AfterReturning("datasourcePointcut()") public void doAfter() { DatasourceConfigContextHolder.setDefaultDatasource(); } }
repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\aspect\DatasourceSelectorAspect.java
1
请完成以下Java代码
public void propertyChange (PropertyChangeEvent evt) { if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) setValue(evt.getNewValue()); } // propertyChange /** * Return Editor value * @return value */ @Override public Object getValue() { return isSelected(); } // getValue /** * Return Display Value * @return value */ @Override public String getDisplay() { String value = isSelected() ? "Y" : "N"; return Msg.translate(Env.getCtx(), value); } // getDisplay /** * Set Background (nop) */ public void setBackground() { } // setBackground /** * Action Listener - data binding * @param e */ @Override public void actionPerformed(ActionEvent e) { try { fireVetoableChange(m_columnName, null, getValue()); } catch (PropertyVetoException pve) {
} } // actionPerformed /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField */ @Override public void setField (org.compiere.model.GridField mField) { m_mField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_mField; } /** * @return Returns the savedMnemonic. */ public char getSavedMnemonic () { return m_savedMnemonic; } // getSavedMnemonic /** * @param savedMnemonic The savedMnemonic to set. */ public void setSavedMnemonic (char savedMnemonic) { m_savedMnemonic = savedMnemonic; } // getSavedMnemonic @Override public boolean isAutoCommit() { return true; } } // VCheckBox
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCheckBox.java
1
请完成以下Java代码
public class InputClause extends DmnElement { protected LiteralExpression inputExpression; protected UnaryTests inputValues; protected int inputNumber; public LiteralExpression getInputExpression() { return inputExpression; } public void setInputExpression(LiteralExpression inputExpression) { this.inputExpression = inputExpression; }
public UnaryTests getInputValues() { return inputValues; } public void setInputValues(UnaryTests inputValues) { this.inputValues = inputValues; } public int getInputNumber() { return inputNumber; } public void setInputNumber(int inputNumber) { this.inputNumber = inputNumber; } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\InputClause.java
1
请完成以下Java代码
public class DocumentProcessingException extends AdempiereException { public DocumentProcessingException(final IDocument document, final String docAction) { super(buildMsg(null, document, docAction)); } public DocumentProcessingException(final String message, final Object documentObj, final String docAction) { super(buildMsg(message, documentObj, docAction)); } private static ITranslatableString buildMsg( @Nullable final String message, @Nullable final Object documentObj, @Nullable final String docAction) { final TranslatableStringBuilder msg = TranslatableStrings.builder(); if (message == null || Check.isBlank(message)) { msg.append("Error Processing Document"); } else { msg.append(message.trim()); } final String documentInfo; final String processMsg; if (documentObj == null) { // shall not happen documentInfo = "no document"; processMsg = null; } else { final IDocument document = Services.get(IDocumentBL.class).getDocumentOrNull(documentObj); if (document != null) { documentInfo = document.getDocumentInfo();
processMsg = document.getProcessMsg(); } else { documentInfo = documentObj.toString(); processMsg = null; } } msg.append("\n").appendADElement("Document").append(": ").append(documentInfo); msg.append("\n").appendADElement("DocAction").append(": ").append(docAction); if (!Check.isEmpty(processMsg, true)) { msg.append("\n").appendADElement("ProcessMsg").append(": ").append(processMsg); } return msg.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\exceptions\DocumentProcessingException.java
1
请在Spring Boot框架中完成以下Java代码
public void editDictByLowAppId(SysDictVo sysDictVo) { String id = sysDictVo.getId(); SysDict dict = baseMapper.selectById(id); if(null == dict){ throw new JeecgBootException("字典数据不存在"); } //判断应用id和数据库中的是否一致,不一致不让修改 if(!dict.getLowAppId().equals(sysDictVo.getLowAppId())){ throw new JeecgBootException("字典数据不存在"); } SysDict sysDict = new SysDict(); sysDict.setDictName(sysDictVo.getDictName()); sysDict.setId(id); baseMapper.updateById(sysDict); this.updateDictItem(id,sysDictVo.getDictItemsList()); // 删除字典缓存 redisUtil.removeAll(CacheConstant.SYS_DICT_CACHE + "::" + dict.getDictCode()); } /** * 还原逻辑删除 * @param ids */ @Override public boolean revertLogicDeleted(List<String> ids) { return baseMapper.revertLogicDeleted(ids) > 0; } /** * 彻底删除 * @param ids * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean removeLogicDeleted(List<String> ids) { // 1. 删除字典 int line = this.baseMapper.removeLogicDeleted(ids); // 2. 删除字典选项配置 line += this.sysDictItemMapper.delete(new LambdaQueryWrapper<SysDictItem>().in(SysDictItem::getDictId, ids)); return line > 0; } /** * 添加字典 * @param dictName */ private String[] addDict(String dictName,String lowAppId, Integer tenantId) { SysDict dict = new SysDict(); dict.setDictName(dictName); dict.setDictCode(RandomUtil.randomString(10)); dict.setDelFlag(Integer.valueOf(CommonConstant.STATUS_0)); dict.setLowAppId(lowAppId); dict.setTenantId(tenantId); baseMapper.insert(dict);
String[] dictResult = new String[]{dict.getId(), dict.getDictCode()}; return dictResult; } /** * 添加字典子项 * @param id * @param dictItemList */ private void addDictItem(String id,List<SysDictItem> dictItemList) { if(null!=dictItemList && dictItemList.size()>0){ for (SysDictItem dictItem:dictItemList) { SysDictItem sysDictItem = new SysDictItem(); BeanUtils.copyProperties(dictItem,sysDictItem); sysDictItem.setDictId(id); sysDictItem.setId(""); sysDictItem.setStatus(Integer.valueOf(CommonConstant.STATUS_1)); sysDictItemMapper.insert(sysDictItem); } } } /** * 更新字典子项 * @param id * @param dictItemList */ private void updateDictItem(String id,List<SysDictItem> dictItemList){ //先删除在新增 因为排序可能不一致 LambdaQueryWrapper<SysDictItem> query = new LambdaQueryWrapper<>(); query.eq(SysDictItem::getDictId,id); sysDictItemMapper.delete(query); //新增子项 this.addDictItem(id,dictItemList); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDictServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public static class DirectExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo12Queue() { return new Queue(Demo12Message.QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Direct Exchange @Bean public DirectExchange demo12Exchange() { return new DirectExchange(Demo12Message.EXCHANGE,
true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo12Message.EXCHANGE // Routing key:Demo12Message.ROUTING_KEY // Queue:Demo12Message.QUEUE @Bean public Binding demo12Binding() { return BindingBuilder.bind(demo12Queue()).to(demo12Exchange()).with(Demo12Message.ROUTING_KEY); } } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-ack\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the schmeNm property. * * @return * possible object is * {@link FinancialIdentificationSchemeName1Choice } * */ public FinancialIdentificationSchemeName1Choice getSchmeNm() { return schmeNm; } /** * Sets the value of the schmeNm property. * * @param value * allowed object is * {@link FinancialIdentificationSchemeName1Choice } * */ public void setSchmeNm(FinancialIdentificationSchemeName1Choice value) {
this.schmeNm = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String } * */ public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\GenericFinancialIdentification1.java
1
请完成以下Java代码
public String getUnstructuredRemittanceInfo() { return getUnstructuredRemittanceInfo("\n"); } @Override @NonNull public String getLineDescription() { return getLineDescription("\n"); } @Override @NonNull public Amount getStatementAmount() { final BigDecimal value = getStatementAmountValue(); final CurrencyCode currencyCode = CurrencyCode.ofThreeLetterCode(getCcy()); return Amount.of(value, currencyCode); } @NonNull protected CurrencyId getCurrencyIdByCurrencyCode(@NonNull final CurrencyCode currencyCode) { return currencyRepository.getCurrencyIdByCurrencyCode(currencyCode); } @NonNull private BigDecimal getStatementAmountValue() { return Optional.ofNullable(getAmtValue()) .map(value -> isCRDT() ? value
: value.negate()) .orElse(BigDecimal.ZERO); } @NonNull protected abstract String getUnstructuredRemittanceInfo(@NonNull final String delimiter); @NonNull protected abstract List<String> getUnstructuredRemittanceInfoList(); @NonNull protected abstract String getLineDescription(@NonNull final String delimiter); @NonNull protected abstract List<String> getLineDescriptionList(); @Nullable protected abstract String getCcy(); @Nullable protected abstract BigDecimal getAmtValue(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\BatchReportEntryWrapper.java
1
请完成以下Java代码
public void setUserElementString7 (final java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setC_Flatrate_Term_ID (final int C_Flatrate_Term_ID) { if (C_Flatrate_Term_ID < 1) set_Value (COLUMNNAME_C_Flatrate_Term_ID, null); else set_Value (COLUMNNAME_C_Flatrate_Term_ID, C_Flatrate_Term_ID); }
@Override public int getC_Flatrate_Term_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_Term_ID); } @Override public void setExternalId (final @Nullable java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLine.java
1
请在Spring Boot框架中完成以下Java代码
public class Book implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long id; private String title; private String isbn; private double price; @Formula("price - price * 0.25") private double discounted; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; }
public void setIsbn(String isbn) { this.isbn = isbn; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Transient public double getDiscounted() { return discounted; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + ", price=" + price + ", discounted=" + discounted + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCalculatePropertyFormula\src\main\java\com\bookstore\entity\Book.java
2
请完成以下Java代码
public abstract class AbstractReceiptScheduleEvent implements MaterialEvent { private final EventDescriptor eventDescriptor; private final MaterialDescriptor materialDescriptor; private final OldReceiptScheduleData oldReceiptScheduleData; private final BigDecimal reservedQuantity; @JsonInclude(NON_NULL) private final MinMaxDescriptor minMaxDescriptor; private final int receiptScheduleId; public AbstractReceiptScheduleEvent( @NonNull final EventDescriptor eventDescriptor, @NonNull final MaterialDescriptor materialDescriptor, @Nullable final OldReceiptScheduleData oldReceiptScheduleData, @Nullable final MinMaxDescriptor minMaxDescriptor, final BigDecimal reservedQuantity, final int receiptScheduleId) { this.minMaxDescriptor = minMaxDescriptor; this.receiptScheduleId = receiptScheduleId; this.eventDescriptor = eventDescriptor; this.materialDescriptor = materialDescriptor; this.oldReceiptScheduleData = oldReceiptScheduleData; this.reservedQuantity = reservedQuantity; } public abstract BigDecimal getOrderedQuantityDelta(); public abstract BigDecimal getReservedQuantityDelta();
@OverridingMethodsMustInvokeSuper public AbstractReceiptScheduleEvent validate() { checkIdGreaterThanZero("receiptScheduleId", receiptScheduleId); Check.errorIf(reservedQuantity == null, "reservedQuantity may not be null"); return this; } @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.of(M_RECEIPTSCHEDULE_TABLE_NAME, receiptScheduleId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\receiptschedule\AbstractReceiptScheduleEvent.java
1
请完成以下Java代码
public Assignment newInstance(ModelTypeInstanceContext instanceContext) { return new AssignmentImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); fromChild = sequenceBuilder.element(From.class) .required() .build(); toChild = sequenceBuilder.element(To.class) .required() .build(); typeBuilder.build(); } public AssignmentImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public From getFrom() {
return fromChild.getChild(this); } public void setFrom(From from) { fromChild.setChild(this, from); } public To getTo() { return toChild.getChild(this); } public void setTo(To to) { toChild.setChild(this, to); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\AssignmentImpl.java
1
请完成以下Java代码
public int getRevisionNext() { return revision + 1; } // getters and setters ////////////////////////////////////////////////////// @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } public Date getDuedate() { return duedate; } public void setDuedate(Date duedate) { this.duedate = duedate; } public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { this.isExclusive = isExclusive; } @Override public int hashCode() {
final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AcquirableJobEntity other = (AcquirableJobEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", duedate=" + duedate + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java
1
请完成以下Java代码
static class ArgumentValueSerializer extends ReferenceTypeSerializer<ArgumentValue<?>> { ArgumentValueSerializer(ReferenceType fullType, boolean staticTyping, @Nullable TypeSerializer vts, ValueSerializer<Object> ser) { super(fullType, staticTyping, vts, ser); } ArgumentValueSerializer(ReferenceTypeSerializer<?> base, BeanProperty property, TypeSerializer vts, ValueSerializer<?> valueSer, NameTransformer unwrapper, Object suppressableValue, boolean suppressNulls) { super(base, property, vts, valueSer, unwrapper, suppressableValue, suppressNulls); } @Override protected ReferenceTypeSerializer<ArgumentValue<?>> withResolved(BeanProperty prop, TypeSerializer vts, ValueSerializer<?> valueSer, NameTransformer unwrapper) { return new ArgumentValueSerializer(this, prop, vts, valueSer, unwrapper, _suppressableValue, _suppressNulls); } @Override public ReferenceTypeSerializer<ArgumentValue<?>> withContentInclusion(final Object suppressableValue, final boolean suppressNulls) { return new ArgumentValueSerializer(this, _property, _valueTypeSerializer, _valueSerializer, _unwrapper, suppressableValue, suppressNulls); } @Override
protected boolean _isValuePresent(final ArgumentValue<?> value) { return !value.isOmitted(); } @Override protected @Nullable Object _getReferenced(final ArgumentValue<?> value) { return value.value(); } @Override protected @Nullable Object _getReferencedIfPresent(final ArgumentValue<?> value) { return value.value(); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\json\GraphQlJacksonModule.java
1
请完成以下Java代码
public int getIMP_ProcessorLog_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_IMP_ProcessorLog_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Error. @param IsError An Error occurred in the execution */ public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Error. @return An Error occurred in the execution */ public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reference. @param Reference Reference for this record */ public void setReference (String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Reference. @return Reference for this record */ public String getReference () { return (String)get_Value(COLUMNNAME_Reference);
} /** Set Summary. @param Summary Textual summary of this request */ public void setSummary (String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ public String getSummary () { return (String)get_Value(COLUMNNAME_Summary); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_ProcessorLog.java
1
请完成以下Java代码
public class BarDeploymentListener implements ArtifactUrlTransformer { private static final Logger LOGGER = LoggerFactory.getLogger(BarDeploymentListener.class); @Override public URL transform(URL artifact) throws Exception { try { return new URL("bar", null, artifact.toString()); } catch (Exception e) { LOGGER.error("Unable to build bar bundle", e); return null; } } @Override public boolean canHandle(File artifact) { JarFile jar = null; try { if (!artifact.getName().endsWith(".bar")) { return false; } jar = new JarFile(artifact);
// Only handle non OSGi bundles Manifest m = jar.getManifest(); if (m != null && m.getMainAttributes().getValue(new Attributes.Name(BUNDLE_SYMBOLICNAME)) != null && m.getMainAttributes().getValue(new Attributes.Name(BUNDLE_VERSION)) != null) { return false; } return true; } catch (Exception e) { return false; } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { LOGGER.error("Unable to close jar", e); } } } } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BarDeploymentListener.java
1
请完成以下Java代码
public Mono<Void> invalidate() { return Mono.fromRunnable(() -> this.expired = true); } public Mono<Void> refreshLastRequest() { this.lastAccessTime = Instant.now(); return Mono.empty(); } public Instant getLastAccessTime() { return this.lastAccessTime; } public Object getPrincipal() { return this.principal;
} public String getSessionId() { return this.sessionId; } public boolean isExpired() { return this.expired; } public void setLastAccessTime(Instant lastAccessTime) { this.lastAccessTime = lastAccessTime; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\session\ReactiveSessionInformation.java
1
请完成以下Java代码
public Builder rowCustomizer(final ViewRowCustomizer rowCustomizer) { this.rowCustomizer = rowCustomizer; return this; } private ViewRowCustomizer getRowCustomizer() { return rowCustomizer; } public Builder viewInvalidationAdvisor(@NonNull final IViewInvalidationAdvisor viewInvalidationAdvisor) { this.viewInvalidationAdvisor = viewInvalidationAdvisor; return this; } private IViewInvalidationAdvisor getViewInvalidationAdvisor() { return viewInvalidationAdvisor; } public Builder refreshViewOnChangeEvents(final boolean refreshViewOnChangeEvents) { this.refreshViewOnChangeEvents = refreshViewOnChangeEvents; return this;
} public Builder queryIfNoFilters(final boolean queryIfNoFilters) { this.queryIfNoFilters = queryIfNoFilters; return this; } public Builder includedEntitiesDescriptors(final Map<DetailId, SqlDocumentEntityDataBindingDescriptor> includedEntitiesDescriptors) { this.includedEntitiesDescriptors = includedEntitiesDescriptors; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBinding.java
1
请完成以下Java代码
public String getContentType() { return MimeType.getMimeType(getName()); } /** * Get Data * * @return data */ public byte[] getData() { byte[] data = super.getBinaryData(); if (data != null) { return data; } // From URL final String str = getImageURL(); if (str == null || str.length() == 0) { log.info("No Image URL"); return null; } // Get from URL final URL url = getURL(); if (url == null) { log.info("No URL"); return null; } try { final URLConnection conn = url.openConnection(); conn.setUseCaches(false); final InputStream is = conn.getInputStream(); final byte[] buffer = new byte[1024 * 8]; // 8kB final ByteArrayOutputStream os = new ByteArrayOutputStream(); int length;
while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } is.close(); data = os.toByteArray(); os.close(); } catch (final Exception e) { log.info(e.toString()); } return data; } // getData @Override public String toString() { return "MImage[ID=" + get_ID() + ",Name=" + getName() + "]"; } // toString @Override protected boolean beforeSave(final boolean newRecord) { if (getAD_Org_ID() != OrgId.ANY.getRepoId()) { setAD_Org_ID(OrgId.ANY.getRepoId()); } return true; } } // MImage
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MImage.java
1
请完成以下Java代码
class FootballPlayer { private String name; private Club club; public FootballPlayer(String name, Club club) { this.name = name; this.club = club; } public String getName() { return name; } public Club getClub() { return club; }
} class Club { private String name; public Club(String name) { this.name = name; } public String getName() { return name; } }
repos\tutorials-master\core-java-modules\core-java-compiler\src\main\java\com\baeldung\filenameandclassname\FootballGame.java
1
请完成以下Java代码
public int size() { return recordRefs.size(); } @NonNull public AdTableId getSingleTableId() { final ImmutableSet<AdTableId> tableIds = getTableIds(); if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() == 1) { return tableIds.iterator().next(); } else { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public void assertSingleTableName() { final ImmutableSet<AdTableId> tableIds = getTableIds();
if (tableIds.isEmpty()) { throw new AdempiereException("No AD_Table_ID"); } else if (tableIds.size() != 1) { throw new AdempiereException("More than one AD_Table_ID found: " + tableIds); } } public Stream<TableRecordReference> streamReferences() { return recordRefs.stream(); } @NonNull private ImmutableSet<AdTableId> getTableIds() { return recordRefs.stream() .map(TableRecordReference::getAD_Table_ID) .map(AdTableId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReferenceSet.java
1
请在Spring Boot框架中完成以下Java代码
public class TrendzController extends BaseController { private final TrendzSettingsService trendzSettingsService; @ApiOperation(value = "Save Trendz settings (saveTrendzSettings)", notes = "Saves Trendz settings for this tenant.\n" + NEW_LINE + "Here is an example of the Trendz settings:\n" + MARKDOWN_CODE_BLOCK_START + "{\n" + " \"enabled\": true,\n" + " \"baseUrl\": \"https://some.domain.com:18888/also_necessary_prefix\"\n" + "}" + MARKDOWN_CODE_BLOCK_END + TENANT_AUTHORITY_PARAGRAPH) @PostMapping("/trendz/settings") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')") public TrendzSettings saveTrendzSettings(@RequestBody TrendzSettings trendzSettings, @AuthenticationPrincipal SecurityUser user) throws ThingsboardException { accessControlService.checkPermission(user, Resource.ADMIN_SETTINGS, Operation.WRITE); TenantId tenantId = user.getTenantId();
trendzSettingsService.saveTrendzSettings(tenantId, trendzSettings); return trendzSettings; } @ApiOperation(value = "Get Trendz Settings (getTrendzSettings)", notes = "Retrieves Trendz settings for this tenant." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) @GetMapping("/trendz/settings") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") public TrendzSettings getTrendzSettings(@AuthenticationPrincipal SecurityUser user) { TenantId tenantId = user.getTenantId(); return trendzSettingsService.findTrendzSettings(tenantId); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\TrendzController.java
2
请完成以下Java代码
public void reverseReceiptScheduleAllocs(final I_M_InOut receipt) { // Only if it's a receipt if (receipt.isSOTrx()) { return; } for (final I_M_InOutLine line : Services.get(IInOutDAO.class).retrieveLines(receipt)) { final List<I_M_ReceiptSchedule_Alloc> lineAllocs = Services.get(IReceiptScheduleDAO.class).retrieveRsaForInOutLine(line); if (lineAllocs.isEmpty()) { continue; } final I_M_InOutLine reversalLine = line.getReversalLine(); Check.assumeNotNull(reversalLine, "reversalLine not null (original line: {})", line); Check.assume(reversalLine.getM_InOutLine_ID() > 0, "reversalLine not null (original line: {})", line); reverseAllocations(lineAllocs, reversalLine); } } private void reverseAllocations(final List<I_M_ReceiptSchedule_Alloc> lineAllocs, final I_M_InOutLine reversalLine) { for (final I_M_ReceiptSchedule_Alloc lineAlloc : lineAllocs) { reverseAllocation(lineAlloc, reversalLine); } } private void reverseAllocation(I_M_ReceiptSchedule_Alloc lineAlloc, I_M_InOutLine reversalLine) {
final I_M_ReceiptSchedule_Alloc reversalLineAlloc = Services.get(IReceiptScheduleBL.class).reverseAllocation(lineAlloc); reversalLineAlloc.setM_InOutLine(reversalLine); InterfaceWrapperHelper.save(reversalLineAlloc); } @DocValidate(timings = { ModelValidator.TIMING_AFTER_VOID }) public void deleteReceiptScheduleAllocs(final I_M_InOut receipt) { // Only if it's a receipt if (receipt.isSOTrx()) { return; } Services.get(IReceiptScheduleDAO.class) .retrieveRsaForInOut(receipt) .forEach(rsa -> InterfaceWrapperHelper.delete(rsa)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_InOut_Receipt.java
1
请完成以下Java代码
public class EmployerAddressType { @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") protected CompanyType company; @XmlElement(namespace = "http://www.forum-datenaustausch.ch/invoice") protected PersonType person; @XmlAttribute(name = "ean_party") protected String eanParty; @XmlAttribute(name = "reg_number") protected String regNumber; /** * Gets the value of the company property. * * @return * possible object is * {@link CompanyType } * */ public CompanyType getCompany() { return company; } /** * Sets the value of the company property. * * @param value * allowed object is * {@link CompanyType } * */ public void setCompany(CompanyType value) { this.company = value; } /** * Gets the value of the person property. * * @return * possible object is * {@link PersonType } * */ public PersonType getPerson() { return person; } /** * Sets the value of the person property. * * @param value * allowed object is * {@link PersonType } * */ public void setPerson(PersonType value) { this.person = value; } /** * Gets the value of the eanParty property. * * @return * possible object is * {@link String } * */ public String getEanParty() { return eanParty; } /** * Sets the value of the eanParty property.
* * @param value * allowed object is * {@link String } * */ public void setEanParty(String value) { this.eanParty = value; } /** * Gets the value of the regNumber property. * * @return * possible object is * {@link String } * */ public String getRegNumber() { return regNumber; } /** * Sets the value of the regNumber property. * * @param value * allowed object is * {@link String } * */ public void setRegNumber(String value) { this.regNumber = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EmployerAddressType.java
1
请完成以下Java代码
private static final class NullExpression extends NullExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { public NullExpression(final Compiler<Boolean, BooleanStringExpression> compiler) { super(compiler); } } private static final class ConstantExpression extends ConstantExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private ConstantExpression(final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final Boolean constantValue) { super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue); } } private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private SingleParameterExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final CtxName parameter)
{ super(context, compiler, expressionStr, parameter); } @Override protected Boolean extractParameterValue(Evaluatee ctx) { return parameter.getValueAsBoolean(ctx); } } private static final class GeneralExpression extends GeneralExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression { private GeneralExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler, expressionStr, expressionChunks); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\BooleanStringExpressionSupport.java
1
请完成以下Java代码
public final class TimedAnnotations { private static final Map<AnnotatedElement, Set<Timed>> cache = new ConcurrentReferenceHashMap<>(); private TimedAnnotations() { } /** * Return {@link Timed} annotations that should be used for the given {@code method} * and {@code type}. * @param method the source method * @param type the source type * @return the {@link Timed} annotations to use or an empty set */ public static Set<Timed> get(Method method, Class<?> type) { Set<Timed> methodAnnotations = findTimedAnnotations(method); if (!methodAnnotations.isEmpty()) { return methodAnnotations; } return findTimedAnnotations(type); }
private static Set<Timed> findTimedAnnotations(@Nullable AnnotatedElement element) { if (element == null) { return Collections.emptySet(); } Set<Timed> result = cache.get(element); if (result != null) { return result; } MergedAnnotations annotations = MergedAnnotations.from(element); result = (!annotations.isPresent(Timed.class)) ? Collections.emptySet() : annotations.stream(Timed.class).collect(MergedAnnotationCollectors.toAnnotationSet()); cache.put(element, result); return result; } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\metrics\TimedAnnotations.java
1
请完成以下Java代码
public class PvmLogger extends ProcessEngineLogger { 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框架中完成以下Java代码
public static void parseDeclarationControls(Element element, BeanDefinitionBuilder builder) { NamespaceUtils.setValueIfAttributeDefined(builder, element, "auto-declare", "shouldDeclare"); String admins = element.getAttribute("declared-by"); if (StringUtils.hasText(admins)) { String[] adminBeanNames = admins.split(","); ManagedList<BeanReference> adminBeanRefs = new ManagedList<>(); for (String adminBeanName : adminBeanNames) { adminBeanRefs.add(new RuntimeBeanReference(adminBeanName.trim())); } builder.addPropertyValue("adminsThatShouldDeclare", adminBeanRefs); } NamespaceUtils.setValueIfAttributeDefined(builder, element, "ignore-declaration-exceptions"); } public static @Nullable BeanDefinition createExpressionDefinitionFromValueOrExpression(String valueElementName, String expressionElementName, ParserContext parserContext, Element element, boolean oneRequired) { Assert.hasText(valueElementName, "'valueElementName' must not be empty"); Assert.hasText(expressionElementName, "'expressionElementName' must not be empty"); String valueElementValue = element.getAttribute(valueElementName); String expressionElementValue = element.getAttribute(expressionElementName); boolean hasAttributeValue = StringUtils.hasText(valueElementValue); boolean hasAttributeExpression = StringUtils.hasText(expressionElementValue); if (hasAttributeValue && hasAttributeExpression) { parserContext.getReaderContext().error("Only one of '" + valueElementName + "' or '" + expressionElementName + "' is allowed", element); } if (oneRequired && (!hasAttributeValue && !hasAttributeExpression)) { parserContext.getReaderContext().error("One of '" + valueElementName + "' or '" + expressionElementName + "' is required", element); } BeanDefinition expressionDef; if (hasAttributeValue) { expressionDef = new RootBeanDefinition(LiteralExpression.class); expressionDef.getConstructorArgumentValues().addGenericArgumentValue(valueElementValue); }
else { expressionDef = createExpressionDefIfAttributeDefined(expressionElementName, element); } return expressionDef; } public static @Nullable BeanDefinition createExpressionDefIfAttributeDefined( String expressionElementName, Element element) { Assert.hasText(expressionElementName, "'expressionElementName' must no be empty"); String expressionElementValue = element.getAttribute(expressionElementName); if (StringUtils.hasText(expressionElementValue)) { BeanDefinitionBuilder expressionDefBuilder = BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class); expressionDefBuilder.addConstructorArgValue(expressionElementValue); return expressionDefBuilder.getRawBeanDefinition(); } return null; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\NamespaceUtils.java
2
请完成以下Java代码
private static void configureLUTUConfigLU( @NonNull final I_M_HU_LUTU_Configuration lutuConfigNew, final int lu_PI_Item_ID, final BigDecimal qtyLU) { if (lu_PI_Item_ID > 0) { if (qtyLU == null || qtyLU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyLU); } final I_M_HU_PI_Item luPI_Item = loadOutOfTrx(lu_PI_Item_ID, I_M_HU_PI_Item.class); lutuConfigNew.setM_LU_HU_PI_Item(luPI_Item); lutuConfigNew.setM_LU_HU_PI(luPI_Item.getM_HU_PI_Version().getM_HU_PI()); lutuConfigNew.setQtyLU(qtyLU); lutuConfigNew.setIsInfiniteQtyLU(false); } else { lutuConfigNew.setM_LU_HU_PI(null); lutuConfigNew.setM_LU_HU_PI_Item(null); lutuConfigNew.setQtyLU(BigDecimal.ZERO); } } public int getLuPiItemId() { return lu_PI_Item_ID; } public void setLuPiItemId(final int lu_PI_Item_ID) { this.lu_PI_Item_ID = lu_PI_Item_ID; } private HUPIItemProductId getTU_HU_PI_Item_Product_ID() { if (tu_HU_PI_Item_Product_ID <= 0) { throw new FillMandatoryException(PARAM_M_HU_PI_Item_Product_ID); } return HUPIItemProductId.ofRepoId(tu_HU_PI_Item_Product_ID); } public void setTU_HU_PI_Item_Product_ID(final int tu_HU_PI_Item_Product_ID) { this.tu_HU_PI_Item_Product_ID = tu_HU_PI_Item_Product_ID; } public BigDecimal getQtyCUsPerTU() { return qtyCUsPerTU; }
public void setQtyCUsPerTU(final BigDecimal qtyCU) { this.qtyCUsPerTU = qtyCU; } /** * Called from the process class to set the TU qty from the process parameter. */ public void setQtyTU(final BigDecimal qtyTU) { this.qtyTU = qtyTU; } public void setQtyLU(final BigDecimal qtyLU) { this.qtyLU = qtyLU; } private boolean getIsReceiveIndividualCUs() { if (isReceiveIndividualCUs == null) { isReceiveIndividualCUs = computeIsReceiveIndividualCUs(); } return isReceiveIndividualCUs; } private boolean computeIsReceiveIndividualCUs() { if (selectedRow.getType() != PPOrderLineType.MainProduct || selectedRow.getUomId() == null || !selectedRow.getUomId().isEach()) { return false; } return Optional.ofNullable(selectedRow.getOrderId()) .flatMap(ppOrderBOMBL::getSerialNoSequenceId) .isPresent(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\PackingInfoProcessParams.java
1
请完成以下Java代码
public int getC_PrintJob_Line_To_ID() { return get_ValueAsInt(COLUMNNAME_C_PrintJob_Line_To_ID); } @Override public void setErrorMsg (java.lang.String ErrorMsg) { set_Value (COLUMNNAME_ErrorMsg, ErrorMsg); } @Override public java.lang.String getErrorMsg() { return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg); } @Override public void setHostKey (java.lang.String HostKey) { set_Value (COLUMNNAME_HostKey, HostKey); } @Override public java.lang.String getHostKey() { return (java.lang.String)get_Value(COLUMNNAME_HostKey); } /** * Status AD_Reference_ID=540384 * Reference name: C_Print_Job_Instructions_Status */
public static final int STATUS_AD_Reference_ID=540384; /** Pending = P */ public static final String STATUS_Pending = "P"; /** Send = S */ public static final String STATUS_Send = "S"; /** Done = D */ public static final String STATUS_Done = "D"; /** Error = E */ public static final String STATUS_Error = "E"; @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions.java
1
请完成以下Java代码
public void mouseReleased(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == mRefresh) { if (m_goals != null) { for (MGoal m_goal : m_goals) { m_goal.updateGoal(true); } } htmlUpdate(lastUrl); Container parent = getParent(); if (parent != null) { parent.invalidate(); } invalidate(); if (parent != null) { parent.repaint(); } else { repaint(); } } } class PageLoader implements Runnable { private JEditorPane html; private URL url; private Cursor cursor; PageLoader( JEditorPane html, URL url, Cursor cursor ) { this.html = html; this.url = url; this.cursor = cursor;
} @Override public void run() { if( url == null ) { // restore the original cursor html.setCursor( cursor ); // PENDING(prinz) remove this hack when // automatic validation is activated. Container parent = html.getParent(); parent.repaint(); } else { Document doc = html.getDocument(); try { html.setPage( url ); } catch( IOException ioe ) { html.setDocument( doc ); } finally { // schedule the cursor to revert after // the paint has happended. url = null; SwingUtilities.invokeLater( this ); } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java
1
请在Spring Boot框架中完成以下Java代码
public int[][] batchInsert(List<Book> books, int batchSize) { int[][] updateCounts = jdbcTemplate.batchUpdate( "insert into books (name, price) values(?,?)", books, batchSize, new ParameterizedPreparedStatementSetter<Book>() { public void setValues(PreparedStatement ps, Book argument) throws SQLException { ps.setString(1, argument.getName()); ps.setBigDecimal(2, argument.getPrice()); } }); return updateCounts; } // https://www.postgresql.org/docs/7.3/jdbc-binary-data.html // https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#jdbc-lob @Override public void saveImage(Long bookId, File image) { try (InputStream imageInStream = new FileInputStream(image)) { jdbcTemplate.execute( "INSERT INTO book_image (book_id, filename, blob_image) VALUES (?, ?, ?)", new AbstractLobCreatingPreparedStatementCallback(lobHandler) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setLong(1, 1L); ps.setString(2, image.getName()); lobCreator.setBlobAsBinaryStream(ps, 3, imageInStream, (int) image.length()); } } ); } catch (IOException e) { e.printStackTrace();
} } @Override public List<Map<String, InputStream>> findImageByBookId(Long bookId) { List<Map<String, InputStream>> result = jdbcTemplate.query( "select id, book_id, filename, blob_image from book_image where book_id = ?", new Object[]{bookId}, new RowMapper<Map<String, InputStream>>() { public Map<String, InputStream> mapRow(ResultSet rs, int i) throws SQLException { String fileName = rs.getString("filename"); InputStream blob_image_stream = lobHandler.getBlobAsBinaryStream(rs, "blob_image"); // byte array //Map<String, Object> results = new HashMap<>(); //byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "blob_image"); //results.put("BLOB", blobBytes); Map<String, InputStream> results = new HashMap<>(); results.put(fileName, blob_image_stream); return results; } }); return result; } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\repository\JdbcBookRepository.java
2
请完成以下Java代码
public static void updateSetOnInsertOperations() { UpdateOptions options = new UpdateOptions().upsert(true); UpdateResult updateSetOnInsertResult = collection.updateOne(Filters.eq("modelName", "GTPR"), Updates.combine(Updates.set("companyName", "Hero Honda"), Updates.setOnInsert("launchYear", 2022), Updates.setOnInsert("type", "Bike"), Updates.setOnInsert("registeredNo", "EPS 5562")), options); System.out.println("updateSetOnInsertResult:- " + updateSetOnInsertResult); } public static void findOneAndUpdateOperations() { FindOneAndUpdateOptions upsertOptions = new FindOneAndUpdateOptions(); upsertOptions.returnDocument(ReturnDocument.AFTER); upsertOptions.upsert(true); Document resultDocument = collection.findOneAndUpdate(Filters.eq("modelName", "X7"), Updates.set("companyName", "Hero Honda"), upsertOptions); System.out.println("resultDocument:- " + resultDocument); } public static void replaceOneOperations() { UpdateOptions options = new UpdateOptions().upsert(true); Document replaceDocument = new Document(); replaceDocument.append("modelName", "GTPP") .append("companyName", "Hero Honda") .append("launchYear", 2022) .append("type", "Bike") .append("registeredNo", "EPS 5562"); UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options); System.out.println("updateReplaceResult:- " + updateReplaceResult); } public static void main(String args[]) { // // Connect to cluster (default is localhost:27017) // setUp(); // // Update with upsert operation
// updateOperations(); // // Update with upsert operation using setOnInsert // updateSetOnInsertOperations(); // // Update with upsert operation using findOneAndUpdate // findOneAndUpdateOperations(); // // Update with upsert operation using replaceOneOperations // replaceOneOperations(); } }
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\UpsertOperations.java
1
请完成以下Java代码
public class InvoiceAccountProviderExtension implements AccountProviderExtension { @NonNull private final IAccountDAO accountDAO; @NonNull private final InvoiceAcct invoiceAccounts; @NonNull final ClientId clientId; @Nullable private final InvoiceAndLineId invoiceAndLineId; @Builder private InvoiceAccountProviderExtension( @NonNull final IAccountDAO accountDAO, // @NonNull final InvoiceAcct invoiceAccounts, @NonNull final ClientId clientId, @Nullable final InvoiceAndLineId invoiceAndLineId) { this.accountDAO = accountDAO; if (invoiceAndLineId != null) { invoiceAndLineId.assertInvoiceId(invoiceAccounts.getInvoiceId()); } this.invoiceAccounts = invoiceAccounts; this.clientId = clientId; this.invoiceAndLineId = invoiceAndLineId; } @Override @NonNull public Optional<Account> getProductAccount(@NonNull final AcctSchemaId acctSchemaId, @Nullable final ProductId productId, @NonNull final ProductAcctType acctType) { return getProductAccount(acctSchemaId, acctType); } @Override @NonNull public Optional<Account> getProductCategoryAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final ProductCategoryId productCategoryId, @NonNull final ProductAcctType acctType) { return getProductAccount(acctSchemaId, acctType); } @NonNull private Optional<Account> getProductAccount(final @NonNull AcctSchemaId acctSchemaId, final @NonNull ProductAcctType acctType) { return invoiceAccounts.getElementValueId(acctSchemaId, acctType.getAccountConceptualName(), invoiceAndLineId) .map(elementValueId -> getOrCreateAccount(elementValueId, acctSchemaId)) .map(id -> Account.of(id, acctType)); } @Override @NonNull public Optional<Account> getBPartnerCustomerAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final BPartnerId bpartnerId, @NonNull final BPartnerCustomerAccountType acctType) { return Optional.empty();
} @Override @NonNull public Optional<Account> getBPartnerVendorAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final BPartnerId bpartnerId, @NonNull final BPartnerVendorAccountType acctType) { return Optional.empty(); } @Override @NonNull public Optional<Account> getBPGroupAccount(@NonNull final AcctSchemaId acctSchemaId, @NonNull final BPGroupId bpGroupId, @NonNull final BPartnerGroupAccountType acctType) { return Optional.empty(); } @NonNull private AccountId getOrCreateAccount( @NonNull final ElementValueId elementValueId, @NonNull final AcctSchemaId acctSchemaId) { return accountDAO.getOrCreateOutOfTrx( AccountDimension.builder() .setAcctSchemaId(acctSchemaId) .setC_ElementValue_ID(elementValueId.getRepoId()) .setAD_Client_ID(clientId.getRepoId()) .setAD_Org_ID(OrgId.ANY.getRepoId()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\InvoiceAccountProviderExtension.java
1
请完成以下Java代码
protected boolean beforeDelete () { log.info("***"); return true; } /** * After Delete * @param success * @return success */ protected boolean afterDelete (boolean success) { log.info("*** Success=" + success); return success; } /** * Before Save * @param newRecord * @return true */ protected boolean beforeSave (boolean newRecord) { log.info("New=" + newRecord + " ***"); return true; } /** * After Save * @param newRecord * @param success * @return success */ protected boolean afterSave (boolean newRecord, boolean success) { log.info("New=" + newRecord + ", Seccess=" + success + " ***"); return success; } // afterSave /************************************************************************* * Test
* @param args */ public static void main(String[] args) { Adempiere.startup(true); Properties ctx = Env.getCtx(); /** Test CLOB */ MTest t1 = new MTest (ctx, 0, null); t1.setName("Test1"); System.out.println("->" + t1.getCharacterData() + "<-"); t1.save(); t1.setCharacterData("Long Text JJ"); t1.save(); int Test_ID = t1.getTest_ID(); // MTest t2 = new MTest (Env.getCtx(), Test_ID, null); System.out.println("->" + t2.getCharacterData() + "<-"); t2.delete(true); /** Volume Test for (int i = 1; i < 20000; i++) { new MTest (ctx, "test", i).save(); } /** */ } // main } // MTest
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTest.java
1
请完成以下Java代码
public void setHospitalIdentifier(@Nullable final String hospitalIdentifier) { this.hospitalIdentifier = hospitalIdentifier; this.hospitalIdentifierSet = true; } public void setDischargeDate(@Nullable final LocalDate dischargeDate) { this.dischargeDate = dischargeDate; this.dischargeDateSet = true; } public void setPayerIdentifier(@Nullable final String payerIdentifier) { this.payerIdentifier = payerIdentifier; this.payerIdentifierSet = true; } public void setPayerType(@Nullable final String payerType) { this.payerType = payerType; this.payerTypeSet = true; } public void setNumberOfInsured(@Nullable final String numberOfInsured) { this.numberOfInsured = numberOfInsured; this.numberOfInsuredSet = true; } public void setCopaymentFrom(@Nullable final LocalDate copaymentFrom) { this.copaymentFrom = copaymentFrom; this.copaymentFromSet = true; } public void setCopaymentTo(@Nullable final LocalDate copaymentTo) { this.copaymentTo = copaymentTo; this.copaymentToSet = true; } public void setIsTransferPatient(@Nullable final Boolean isTransferPatient) { this.isTransferPatient = isTransferPatient; this.transferPatientSet = true; } public void setIVTherapy(@Nullable final Boolean IVTherapy) { this.isIVTherapy = IVTherapy; this.ivTherapySet = true; } public void setFieldNurseIdentifier(@Nullable final String fieldNurseIdentifier) { this.fieldNurseIdentifier = fieldNurseIdentifier; this.fieldNurseIdentifierSet = true; } public void setDeactivationReason(@Nullable final String deactivationReason) { this.deactivationReason = deactivationReason; this.deactivationReasonSet = true; } public void setDeactivationDate(@Nullable final LocalDate deactivationDate) { this.deactivationDate = deactivationDate; this.deactivationDateSet = true; } public void setDeactivationComment(@Nullable final String deactivationComment) { this.deactivationComment = deactivationComment; this.deactivationCommentSet = true; }
public void setClassification(@Nullable final String classification) { this.classification = classification; this.classificationSet = true; } public void setCareDegree(@Nullable final BigDecimal careDegree) { this.careDegree = careDegree; this.careDegreeSet = true; } public void setCreatedAt(@Nullable final Instant createdAt) { this.createdAt = createdAt; this.createdAtSet = true; } public void setCreatedByIdentifier(@Nullable final String createdByIdentifier) { this.createdByIdentifier = createdByIdentifier; this.createdByIdentifierSet = true; } public void setUpdatedAt(@Nullable final Instant updatedAt) { this.updatedAt = updatedAt; this.updatedAtSet = true; } public void setUpdateByIdentifier(@Nullable final String updateByIdentifier) { this.updateByIdentifier = updateByIdentifier; this.updateByIdentifierSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaPatient.java
1
请完成以下Java代码
public AsyncInlineCachingRegionConfigurer<T, ID> withQueueEventSubstitutionFilter( @Nullable GatewayEventSubstitutionFilter<ID, T> eventSubstitutionFilter) { this.gatewayEventSubstitutionFilter = eventSubstitutionFilter; return this; } /** * Builder method used to configure whether cache {@link Region} entry destroyed events due to expiration * are forwarded to the {@link AsyncEventQueue}. * * @return this {@link AsyncInlineCachingRegionConfigurer}. */ public AsyncInlineCachingRegionConfigurer<T, ID> withQueueForwardedExpirationDestroyEvents() { this.forwardExpirationDestroy = true; return this; } /** * Builder method used to configure the maximum JVM Heap memory in megabytes used by the {@link AsyncEventQueue}. * * After the maximum memory threshold is reached then the AEQ overflows cache events to disk. * * Default to {@literal 100 MB}. * * @param maximumMemory {@link Integer} value specifying the maximum amount of memory in megabytes used by the AEQ * to capture cache events. * @return this {@link AsyncInlineCachingRegionConfigurer}. */ public AsyncInlineCachingRegionConfigurer<T, ID> withQueueMaxMemory(int maximumMemory) { this.maximumQueueMemory = maximumMemory; return this; }
/** * Builder method used to configure the {@link AsyncEventQueue} order of processing for cache events when the AEQ * is serial and the AEQ is using multiple dispatcher threads. * * @param orderPolicy {@link GatewaySender} {@link OrderPolicy} used to determine the order of processing * for cache events when the AEQ is serial and uses multiple dispatcher threads. * @return this {@link AsyncInlineCachingRegionConfigurer}. * @see org.apache.geode.cache.wan.GatewaySender.OrderPolicy */ public AsyncInlineCachingRegionConfigurer<T, ID> withQueueOrderPolicy( @Nullable GatewaySender.OrderPolicy orderPolicy) { this.orderPolicy = orderPolicy; return this; } /** * Builder method used to enable a single {@link AsyncEventQueue AEQ} attached to a {@link Region Region} * (possibly) hosted and distributed across the cache cluster to process cache events. * * Default is {@literal false}, or {@literal serial}. * * @return this {@link AsyncInlineCachingRegionConfigurer}. * @see #withParallelQueue() */ public AsyncInlineCachingRegionConfigurer<T, ID> withSerialQueue() { this.parallel = false; return this; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\AsyncInlineCachingRegionConfigurer.java
1
请完成以下Java代码
public String get_ValueOldAsString(final String variableName) { return get_ValueAsString(variableName); } private String getAttributeLabel() { return attribute.getDisplayName().getDefaultValue(); } private String getAttributeUOM() { final UomId uomId = attribute.getUomId(); if (uomId == null) { return null; } final I_C_UOM uom = uomsRepo.getById(uomId); if (uom == null) { return null; } return uom.getUOMSymbol(); } private ITranslatableString getAttributeValueAsDisplayString() { final AttributeValueType valueType = attribute.getValueType(); if (AttributeValueType.STRING.equals(valueType)) { final String valueStr = attributeValue != null ? attributeValue.toString() : null; return ASIDescriptionBuilderCommand.formatStringValue(valueStr); } else if (AttributeValueType.NUMBER.equals(valueType)) { final BigDecimal valueBD = attributeValue != null ? NumberUtils.asBigDecimal(attributeValue, null) : null; if (valueBD == null && !verboseDescription) { return null; } else { return ASIDescriptionBuilderCommand.formatNumber(valueBD, attribute.getNumberDisplayType()); } }
else if (AttributeValueType.DATE.equals(valueType)) { final Date valueDate = attributeValue != null ? TimeUtil.asDate(attributeValue) : null; if (valueDate == null && !verboseDescription) { return null; } else { return ASIDescriptionBuilderCommand.formatDateValue(valueDate); } } else if (AttributeValueType.LIST.equals(valueType)) { final AttributeListValue attributeValue = attributeValueId != null ? attributesRepo.retrieveAttributeValueOrNull(attribute, attributeValueId) : null; if (attributeValue != null) { return ASIDescriptionBuilderCommand.formatStringValue(attributeValue.getName()); } else { return ASIDescriptionBuilderCommand.formatStringValue(null); } } else { // Unknown attributeValueType final String valueStr = attributeValue != null ? attributeValue.toString() : null; return ASIDescriptionBuilderCommand.formatStringValue(valueStr); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeDescriptionPatternEvalCtx.java
1
请完成以下Java代码
public @NonNull IssuingToleranceValueType getValueType() {return valueType;} private void assertValueType(@NonNull IssuingToleranceValueType expectedValueType) { if (this.valueType != expectedValueType) { throw new AdempiereException("Expected " + this + " to be of type: " + expectedValueType); } } @NonNull public Percent getPercent() { assertValueType(IssuingToleranceValueType.PERCENTAGE); return Check.assumeNotNull(percent, "percent not null"); } @NonNull public Quantity getQty() { assertValueType(IssuingToleranceValueType.QUANTITY); return Check.assumeNotNull(qty, "qty not null"); } public ITranslatableString toTranslatableString() { if (valueType == IssuingToleranceValueType.PERCENTAGE) { final Percent percent = getPercent(); return TranslatableStrings.builder().appendPercent(percent).build(); } else if (valueType == IssuingToleranceValueType.QUANTITY) { final Quantity qty = getQty(); return TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build(); } else { // shall not happen return TranslatableStrings.empty(); } } public Quantity addTo(@NonNull final Quantity qtyBase) { if (valueType == IssuingToleranceValueType.PERCENTAGE) { final Percent percent = getPercent(); return qtyBase.add(percent); } else if (valueType == IssuingToleranceValueType.QUANTITY) { final Quantity qty = getQty(); return qtyBase.add(qty); } else { // shall not happen throw new AdempiereException("Unknown valueType: " + valueType); }
} public Quantity subtractFrom(@NonNull final Quantity qtyBase) { if (valueType == IssuingToleranceValueType.PERCENTAGE) { final Percent percent = getPercent(); return qtyBase.subtract(percent); } else if (valueType == IssuingToleranceValueType.QUANTITY) { final Quantity qty = getQty(); return qtyBase.subtract(qty); } else { // shall not happen throw new AdempiereException("Unknown valueType: " + valueType); } } public IssuingToleranceSpec convertQty(@NonNull final UnaryOperator<Quantity> qtyConverter) { if (valueType == IssuingToleranceValueType.QUANTITY) { final Quantity qtyConv = qtyConverter.apply(qty); if (qtyConv.equals(qty)) { return this; } return toBuilder().qty(qtyConv).build(); } else { return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\IssuingToleranceSpec.java
1
请在Spring Boot框架中完成以下Java代码
private static class StagingRecordKey { @Nullable InvoiceId invoiceId; @Nullable InvoiceAndLineId invoiceAndLineId; @NonNull String label; public static StagingRecordKey forRecordOrNull(@NonNull final I_C_Invoice_Detail detailRecord) { final InvoiceAndLineId invoiceAndLineId = InvoiceAndLineId.ofRepoIdOrNull(detailRecord.getC_Invoice_ID(), detailRecord.getC_InvoiceLine_ID()); if (invoiceAndLineId != null) { return new StagingRecordKey(null, invoiceAndLineId, detailRecord.getLabel()); } final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(detailRecord.getC_Invoice_ID()); if (invoiceId != null) { return new StagingRecordKey(invoiceId, null, detailRecord.getLabel()); } return null; } public static StagingRecordKey forItemOrNull(@NonNull final InvoiceId invoiceId, @NonNull final InvoiceDetailItem detailItem)
{ return new StagingRecordKey(invoiceId, null, detailItem.getLabel()); } public static StagingRecordKey forItemOrNull(@NonNull final InvoiceAndLineId invoiceAndLineId, @NonNull final InvoiceDetailItem detailItem) { return new StagingRecordKey(null, invoiceAndLineId, detailItem.getLabel()); } } // also used by InvoiceWithDetailsService List<I_C_Invoice_Detail> getInvoiceDetailsListForInvoiceId(@NonNull final InvoiceId invoiceId) { return queryBL .createQueryBuilder(I_C_Invoice_Detail.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice_Detail.COLUMNNAME_C_Invoice_ID, invoiceId) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\detail\InvoiceWithDetailsRepository.java
2
请完成以下Java代码
public void setParentProcessInstanceId(String parentProcessInstanceId) { this.parentProcessInstanceId = parentProcessInstanceId; } public String[] getActivityIdIn() { return activityIdIn; } @CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class) public void setActivityIdIn(String[] activityIdIn) { this.activityIdIn = activityIdIn; } public String[] getActivityInstanceIdIn() { return activityInstanceIdIn; } @CamundaQueryParam(value="activityInstanceIdIn", converter = StringArrayConverter.class) public void setActivityInstanceIdIn(String[] activityInstanceIdIn) { this.activityInstanceIdIn = activityInstanceIdIn; } public String getBusinessKey() { return businessKey; } @CamundaQueryParam(value="businessKey") public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public Date getStartedBefore() { return startedBefore; } @CamundaQueryParam(value="startedBefore", converter = DateConverter.class) public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } @CamundaQueryParam(value="startedAfter", converter = DateConverter.class) public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public Boolean getWithIncident() { return withIncident; } @CamundaQueryParam(value="withIncident", converter = BooleanConverter.class) public void setWithIncident(Boolean withIncident) { this.withIncident = withIncident; } @Override protected String getOrderByValue(String sortBy) { return ORDER_BY_VALUES.get(sortBy); }
@Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } public String getOuterOrderBy() { String outerOrderBy = getOrderBy(); if (outerOrderBy == null || outerOrderBy.isEmpty()) { return "ID_ asc"; } else if (outerOrderBy.contains(".")) { return outerOrderBy.substring(outerOrderBy.lastIndexOf(".") + 1); } else { return outerOrderBy; } } private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) { List<QueryVariableValue> values = new ArrayList<QueryVariableValue>(); if (variables == null) { return values; } for (VariableQueryParameterDto variable : variables) { QueryVariableValue value = new QueryVariableValue( variable.getName(), resolveVariableValue(variable.getValue()), ConditionQueryParameterDto.getQueryOperator(variable.getOperator()), false); value.initialize(variableTypes, dbType); values.add(value); } return values; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\AbstractProcessInstanceQueryDto.java
1
请完成以下Java代码
private static Map<String, AttributeKvEntry> mapAttributes(List<AttributeKvEntry> attributes) { Map<String, AttributeKvEntry> result = new HashMap<>(); for (AttributeKvEntry attribute : attributes) { result.put(attribute.getKey(), attribute); } return result; } public Collection<AttributeKvEntry> getClientSideAttributes() { return clientSideAttributesMap.values(); } public Collection<AttributeKvEntry> getServerSideAttributes() { return serverPrivateAttributesMap.values(); } public Collection<AttributeKvEntry> getServerSidePublicAttributes() { return serverPublicAttributesMap.values(); } public Optional<AttributeKvEntry> getClientSideAttribute(String attribute) { return Optional.ofNullable(clientSideAttributesMap.get(attribute)); } public Optional<AttributeKvEntry> getServerPrivateAttribute(String attribute) { return Optional.ofNullable(serverPrivateAttributesMap.get(attribute)); } public Optional<AttributeKvEntry> getServerPublicAttribute(String attribute) { return Optional.ofNullable(serverPublicAttributesMap.get(attribute)); } public void remove(AttributeKey key) { Map<String, AttributeKvEntry> map = getMapByScope(key.getScope()); if (map != null) { map.remove(key.getAttributeKey()); }
} public void update(String scope, List<AttributeKvEntry> values) { Map<String, AttributeKvEntry> map = getMapByScope(scope); values.forEach(v -> map.put(v.getKey(), v)); } private Map<String, AttributeKvEntry> getMapByScope(String scope) { Map<String, AttributeKvEntry> map = null; if (scope.equalsIgnoreCase(DataConstants.CLIENT_SCOPE)) { map = clientSideAttributesMap; } else if (scope.equalsIgnoreCase(DataConstants.SHARED_SCOPE)) { map = serverPublicAttributesMap; } else if (scope.equalsIgnoreCase(DataConstants.SERVER_SCOPE)) { map = serverPrivateAttributesMap; } return map; } @Override public String toString() { return "DeviceAttributes{" + "clientSideAttributesMap=" + clientSideAttributesMap + ", serverPrivateAttributesMap=" + serverPrivateAttributesMap + ", serverPublicAttributesMap=" + serverPublicAttributesMap + '}'; } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\rule\engine\DeviceAttributes.java
1
请完成以下Java代码
final class RepositoryDeferredCsrfToken implements DeferredCsrfToken { private final CsrfTokenRepository csrfTokenRepository; private final HttpServletRequest request; private final HttpServletResponse response; private @Nullable CsrfToken csrfToken; private boolean missingToken; RepositoryDeferredCsrfToken(CsrfTokenRepository csrfTokenRepository, HttpServletRequest request, HttpServletResponse response) { this.csrfTokenRepository = csrfTokenRepository; this.request = request; this.response = response; } @Override public CsrfToken get() { init(); return Objects.requireNonNull(this.csrfToken); } @Override public boolean isGenerated() {
init(); return this.missingToken; } private void init() { if (this.csrfToken != null) { return; } this.csrfToken = this.csrfTokenRepository.loadToken(this.request); this.missingToken = (this.csrfToken == null); if (this.missingToken) { this.csrfToken = this.csrfTokenRepository.generateToken(this.request); this.csrfTokenRepository.saveToken(this.csrfToken, this.request, this.response); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\RepositoryDeferredCsrfToken.java
1
请完成以下Java代码
public byte[] serialize(String topic, Headers headers, Object data) { if (data == null) { return null; } byte[] value = null; String selectorKey = selectorKey(); Header header = headers.lastHeader(selectorKey); if (header != null) { value = header.value(); } if (value == null) { value = trySerdes(data); if (value == null) { throw new IllegalStateException("No '" + selectorKey + "' header present and type (" + data.getClass().getName() + ") is not supported by Serdes"); } try { headers.add(new RecordHeader(selectorKey, value)); } catch (IllegalStateException e) { LOGGER.debug(e, () -> "Could not set header for type " + data.getClass()); } } String selector = new String(value).replaceAll("\"", ""); @SuppressWarnings("unchecked") Serializer<Object> serializer = (Serializer<Object>) this.delegates.get(selector); if (serializer == null) { throw new IllegalStateException( "No serializer found for '" + selectorKey + "' header with value '" + selector + "'"); } return serializer.serialize(topic, headers, data); } private String selectorKey() { return this.forKeys ? KEY_SERIALIZATION_SELECTOR : VALUE_SERIALIZATION_SELECTOR;
} /* * Package for testing. */ @SuppressWarnings("NullAway") // Dataflow analysis limitation byte[] trySerdes(Object data) { try { Serde<? extends Object> serdeFrom = Serdes.serdeFrom(data.getClass()); Serializer<?> serializer = serdeFrom.serializer(); serializer.configure(this.autoConfigs, this.forKeys); String key = data.getClass().getName(); this.delegates.put(key, serializer); return key.getBytes(); } catch (IllegalStateException e) { return null; } } @Override public void close() { this.delegates.values().forEach(Serializer::close); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingSerializer.java
1
请完成以下Java代码
private Boolean isConnectionValid(Connection connection) throws SQLException { return connection.isValid(0); } /** * Set the {@link DataSource} to use. * @param dataSource the data source */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); } /** * Set a specific validation query to use to validate a connection. If none is set, a * validation based on {@link Connection#isValid(int)} is used. * @param query the validation query to use */ public void setQuery(String query) { this.query = query; } /** * Return the validation query or {@code null}. * @return the query */ public @Nullable String getQuery() { return this.query; } /**
* {@link RowMapper} that expects and returns results from a single column. */ private static final class SingleColumnRowMapper implements RowMapper<Object> { @Override public Object mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columns = metaData.getColumnCount(); if (columns != 1) { throw new IncorrectResultSetColumnCountException(1, columns); } Object result = JdbcUtils.getResultSetValue(rs, 1); Assert.state(result != null, "'result' must not be null"); return result; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\health\DataSourceHealthIndicator.java
1
请在Spring Boot框架中完成以下Java代码
public Result confirmDelivery(String orderId, String expressNo, HttpServletRequest httpReq) { // 获取卖家ID String sellerId = getUserId(httpReq); // 确认收货 orderService.confirmDelivery(orderId, expressNo, sellerId); // 成功 return Result.newSuccessResult(); } @Override public Result confirmReceive(String orderId, HttpServletRequest httpReq) { // 获取买家ID String buyerId = getUserId(httpReq); // 确认收货 orderService.confirmReceive(orderId, buyerId); // 成功 return Result.newSuccessResult(); }
/** * 获取用户ID * @param httpReq HTTP请求 * @return 用户ID */ private String getUserId(HttpServletRequest httpReq) { UserEntity userEntity = userUtil.getUser(httpReq); if (userEntity == null) { throw new CommonBizException(ExpCodeEnum.UNLOGIN); } return userEntity.getId(); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\order\OrderControllerImpl.java
2
请在Spring Boot框架中完成以下Java代码
public ApplicationRunner init() { return args -> { System.out.println("\n ------------------ N+1 ----------------- \n"); System.out.println("-----------------displayBooksCausingNPlus1-------------------- \n"); bookstoreService.displayBooksCausingNPlus1(); System.out.println("-----------------displayBooksByAgeGt45CausingNPlus1-------------------- \n"); bookstoreService.displayBooksByAgeGt45CausingNPlus1(); System.out.println("\n ----------------- LEFT JOIN ----------------- \n"); System.out.println("-----------------displayBookById-------------------- \n"); bookstoreService.displayBookById(); System.out.println("-----------------displayBookByIdViaJoinFetch-------------------- \n"); bookstoreService.displayBookByIdViaJoinFetch();
System.out.println("-----------------displayBookByIdViaEntityGraph-------------------- \n"); bookstoreService.displayBookByIdViaEntityGraph(); System.out.println("------------------displayBooksViaEntityGraph------------------- \n"); bookstoreService.displayBooksViaEntityGraph(); System.out.println("-------------------displayBooksByAgeGt45ViaEntityGraph------------------ \n"); bookstoreService.displayBooksByAgeGt45ViaEntityGraph(); System.out.println("------------------displayBooksViaJoinfetch------------------- \n"); bookstoreService.displayBooksViaJoinFetch(); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFetchJoinAndQueries\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
private DocumentFieldDescriptor.Builder createProductFieldDescriptor() { return DocumentFieldDescriptor .builder(IInvoiceLineQuickInput.COLUMNNAME_M_Product_ID) .setCaption(msgBL.translatable(IInvoiceLineQuickInput.COLUMNNAME_M_Product_ID)) .setWidgetType(DocumentFieldWidgetType.Lookup) .setLookupDescriptorProvider( ProductLookupDescriptor .builderWithoutStockInfo() .bpartnerParamName(I_C_Invoice.COLUMNNAME_C_BPartner_ID) .pricingDateParamName(I_C_Invoice.COLUMNNAME_DateInvoiced) .build()) .setMandatoryLogic(true) .setDisplayLogic(ConstantLogicExpression.TRUE) .addCallout(invoiceLineQuickInputCallout::onProductChange) .addCharacteristic(Characteristic.PublicField); } private DocumentFieldDescriptor.Builder createQtyFieldDescriptor() { return DocumentFieldDescriptor.builder(IInvoiceLineQuickInput.COLUMNNAME_Qty) .setCaption(msgBL.translatable(IInvoiceLineQuickInput.COLUMNNAME_Qty)) .setWidgetType(DocumentFieldWidgetType.Quantity) .setMandatoryLogic(true) .addCharacteristic(Characteristic.PublicField); }
private DocumentFieldDescriptor.Builder createPackingItemFieldDescriptor() { return DocumentFieldDescriptor.builder(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID) .setCaption(msgBL.translatable(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID)) .setWidgetType(DocumentFieldWidgetType.Lookup) .setLookupDescriptorProvider(lookupDescriptorProviders.sql() .setCtxTableName(null) // ctxTableName .setCtxColumnName(IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID) .setDisplayType(DisplayType.TableDir) .setAD_Val_Rule_ID(AdValRuleId.ofRepoId(540480)) // FIXME: hardcoded "M_HU_PI_Item_Product_For_Org_Product_And_DateInvoiced" .build()) .setValueClass(LookupValue.IntegerLookupValue.class) .setReadonlyLogic(ConstantLogicExpression.FALSE) .setAlwaysUpdateable(true) .setMandatoryLogic(ConstantLogicExpression.FALSE) .setDisplayLogic(ConstantLogicExpression.TRUE) .addCharacteristic(Characteristic.PublicField); } private QuickInputLayoutDescriptor createLayout(final DocumentEntityDescriptor entityDescriptor) { return QuickInputLayoutDescriptor.onlyFields(entityDescriptor, new String[][] { { IInvoiceLineQuickInput.COLUMNNAME_M_Product_ID, IInvoiceLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID }, { IInvoiceLineQuickInput.COLUMNNAME_Qty } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\invoiceline\InvoiceLineQuickInputDescriptorFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getTaskAssigneeLikeIgnoreCase() { return taskAssigneeLikeIgnoreCase; } public boolean isWithoutDeleteReason() { return withoutDeleteReason; } public String getLocale() { return locale; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionKeyLike() { return caseDefinitionKeyLike; } public String getCaseDefinitionKeyLikeIgnoreCase() { return caseDefinitionKeyLikeIgnoreCase; } public Collection<String> getCaseDefinitionKeys() { return caseDefinitionKeys; } public boolean isWithLocalizationFallback() { return withLocalizationFallback; } public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCandidateGroups() { return safeCandidateGroups;
} public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) { this.safeCandidateGroups = safeCandidateGroups; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } public Set<String> getScopeIds() { return scopeIds; } public List<List<String>> getSafeScopeIds() { return safeScopeIds; } public void setSafeScopeIds(List<List<String>> safeScopeIds) { this.safeScopeIds = safeScopeIds; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskInstanceQueryImpl.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } // toString /** * Value Has Key * @return true if value has a key */ public boolean hasKey() { return m_value instanceof NamePair; } // hasKey /** * String representation with key info * @return info */ public String toStringX() { if (m_value instanceof NamePair)
{ NamePair pp = (NamePair)m_value; StringBuffer sb = new StringBuffer(m_columnName); sb.append("(").append(pp.getID()).append(")") .append("=").append(pp.getName()); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } else return toString(); } // toStringX public String getM_formatPattern() { return m_formatPattern; } public void setM_formatPattern(String pattern) { m_formatPattern = pattern; } } // PrintDataElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java
1
请完成以下Java代码
public HistoricTaskInstanceReport completedBefore(Date completedBefore) { ensureNotNull(NotValidException.class, "completedBefore", completedBefore); this.completedBefore = completedBefore; return this; } public TenantCheck getTenantCheck() { return tenantCheck; } public String getReportPeriodUnitName() { return durationPeriodUnit.name(); } protected class ExecuteDurationCmd implements Command<List<DurationReportResult>> { @Override public List<DurationReportResult> execute(CommandContext commandContext) { return executeDuration(commandContext);
} } protected class HistoricTaskInstanceCountByNameCmd implements Command<List<HistoricTaskInstanceReportResult>> { @Override public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) { return executeCountByTaskName(commandContext); } } protected class HistoricTaskInstanceCountByProcessDefinitionKey implements Command<List<HistoricTaskInstanceReportResult>> { @Override public List<HistoricTaskInstanceReportResult> execute(CommandContext commandContext) { return executeCountByProcessDefinitionKey(commandContext); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceReportImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Chapter implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String content; @Version private short version; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; } public short getVersion() { return version; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOptimisticForceIncrement\src\main\java\com\bookstore\entity\Chapter.java
2
请完成以下Java代码
public class JobAcquisitionAdd extends AbstractAddStepHandler { public static final JobAcquisitionAdd INSTANCE = new JobAcquisitionAdd(); protected JobAcquisitionAdd() { super(SubsystemAttributeDefinitons.JOB_ACQUISITION_ATTRIBUTES); } @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { String acquisitionName = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); // start new service for job executor ServiceName serviceName = ServiceNames.forMscRuntimeContainerJobExecutorService(acquisitionName); ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(serviceName); serviceBuilder.requires(ServiceNames.forMscRuntimeContainerDelegate()); serviceBuilder.requires(ServiceNames.forMscExecutorService()); Consumer<RuntimeContainerJobExecutor> provider = serviceBuilder.provides(serviceName);
MscRuntimeContainerJobExecutor mscRuntimeContainerJobExecutor = new MscRuntimeContainerJobExecutor(provider); if (model.hasDefined(SubsystemAttributeDefinitons.PROPERTIES.getName())) { List<Property> properties = SubsystemAttributeDefinitons.PROPERTIES.resolveModelAttribute(context, model).asPropertyList(); for (Property property : properties) { PropertyHelper.applyProperty(mscRuntimeContainerJobExecutor, property.getName(), property.getValue().asString()); } } serviceBuilder.setInitialMode(Mode.ACTIVE); serviceBuilder.setInstance(mscRuntimeContainerJobExecutor); serviceBuilder.install(); } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\JobAcquisitionAdd.java
1
请完成以下Java代码
public void fireDataStatusEEvent(final ValueNamePair errorLog) { final boolean isError = true; fireDataStatusEEvent(errorLog.getValue(), errorLog.getName(), isError); } @Override public void putContext(final String name, final boolean value) { getDocument().setDynAttribute(name, value); } @Override public void putContext(final String name, final java.util.Date value) { getDocument().setDynAttribute(name, value); } @Override public void putContext(final String name, final int value) { getDocument().setDynAttribute(name, value); } @Override public boolean getContextAsBoolean(final String name) { final Object valueObj = getDocument().getDynAttribute(name); return DisplayType.toBoolean(valueObj); } @Override public int getContextAsInt(final String name) { final Object valueObj = getDocument().getDynAttribute(name);
if (valueObj == null) { return -1; } else if (valueObj instanceof Number) { return ((Number)valueObj).intValue(); } else { return Integer.parseInt(valueObj.toString()); } } @Override public ICalloutRecord getCalloutRecord() { return getDocument().asCalloutRecord(); } @Override public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id) { return documentField.getLookupValueById(id) != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldAsCalloutField.java
1
请完成以下Java代码
private static InboundEMail toInboundEMail(final Message<?> message) { final MessageHeaders messageHeaders = message.getHeaders(); @SuppressWarnings("unchecked") final MultiValueMap<String, Object> messageRawHeaders = messageHeaders.get(MailHeaders.RAW_HEADERS, MultiValueMap.class); final MailContent mailContent = MailContentCollector.toMailContent(messageHeaders.get(InboundEMailHeaderAndContentMapper.CONTENT)); final String messageId = toMessageId(messageRawHeaders.getFirst("Message-ID")); final String firstMessageIdReference = toMessageId(messageRawHeaders.getFirst("References")); final String initialMessageId = CoalesceUtil.coalesce(firstMessageIdReference, messageId); return InboundEMail.builder() .from(messageHeaders.get(MailHeaders.FROM, String.class)) .to(ImmutableList.copyOf(messageHeaders.get(MailHeaders.TO, String[].class))) .cc(ImmutableList.copyOf(messageHeaders.get(MailHeaders.CC, String[].class))) .bcc(ImmutableList.copyOf(messageHeaders.get(MailHeaders.BCC, String[].class))) .subject(messageHeaders.get(MailHeaders.SUBJECT, String.class)) .content(mailContent.getText()) .contentType(messageHeaders.get(MailHeaders.CONTENT_TYPE, String.class)) .receivedDate(toZonedDateTime(messageHeaders.get(MailHeaders.RECEIVED_DATE))) .messageId(messageId) .initialMessageId(initialMessageId) .headers(convertMailHeadersToJson(messageRawHeaders)) .attachments(mailContent.getAttachments()) .build(); } private static final String toMessageId(final Object messageIdObj) { if (messageIdObj == null) { return null; } return messageIdObj.toString(); } private static ZonedDateTime toZonedDateTime(final Object dateObj) { return TimeUtil.asZonedDateTime(dateObj); } private static final ImmutableMap<String, Object> convertMailHeadersToJson(final MultiValueMap<String, Object> mailRawHeaders) { return mailRawHeaders.entrySet() .stream() .map(entry -> GuavaCollectors.entry(entry.getKey(), convertListToJson(entry.getValue()))) .filter(entry -> entry.getValue() != null) .collect(GuavaCollectors.toImmutableMap()); } private static final Object convertListToJson(final List<Object> values) { if (values == null || values.isEmpty()) {
return ImmutableList.of(); } else if (values.size() == 1) { return convertValueToJson(values.get(0)); } else { return values.stream() .map(v -> convertValueToJson(v)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } } private static final Object convertValueToJson(final Object value) { if (value == null) { return null; } return value.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailMessageHandler.java
1
请完成以下Java代码
public static void readAllEntriesByZipFile(SourceState sourceState, Blackhole blackhole) throws IOException { try (ZipFile zipFile = new ZipFile(sourceState.compressedFile)) { Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { blackhole.consume(ZipSampleFileStore.getString(inputStream)); } } } } @Benchmark public static void readAllEntriesByZipInputStream(SourceState sourceState, Blackhole blackhole) throws IOException { try ( BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceState.compressedFile)); ZipInputStream zipInputStream = new ZipInputStream(bis) ) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { blackhole.consume(ZipSampleFileStore.getString(zipInputStream)); } } } @Benchmark public static void readLastEntryByZipFile(SourceState sourceState, Blackhole blackhole) throws IOException { try (ZipFile zipFile = new ZipFile(sourceState.compressedFile)) { ZipEntry zipEntry = zipFile.getEntry(getLastEntryName()); try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { blackhole.consume(ZipSampleFileStore.getString(inputStream)); } }
} @Benchmark public static void readLastEntryByZipInputStream(SourceState sourceState, Blackhole blackhole) throws IOException { try ( BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceState.compressedFile)); ZipInputStream zipInputStream = new ZipInputStream(bis) ) { ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (Objects.equals(entry.getName(), getLastEntryName())){ blackhole.consume(ZipSampleFileStore.getString(zipInputStream)); } } } } private static String getLastEntryName() { return String.format(ZipSampleFileStore.ENTRY_NAME_PATTERN, NUM_OF_FILES); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(ZipBenchmark.class.getSimpleName()).threads(1) .shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\zip\ZipBenchmark.java
1
请完成以下Java代码
public void setM_ShipmentSchedule_ExportAudit_ID (final int M_ShipmentSchedule_ExportAudit_ID) { if (M_ShipmentSchedule_ExportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID, M_ShipmentSchedule_ExportAudit_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_ID); } @Override public void setM_ShipmentSchedule_ExportAudit_Item_ID (final int M_ShipmentSchedule_ExportAudit_Item_ID) { if (M_ShipmentSchedule_ExportAudit_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID, M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public int getM_ShipmentSchedule_ExportAudit_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ExportAudit_Item_ID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setTransactionIdAPI (final @Nullable java.lang.String TransactionIdAPI) { throw new IllegalArgumentException ("TransactionIdAPI is virtual column"); } @Override public java.lang.String getTransactionIdAPI() { return get_ValueAsString(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_ExportAudit_Item.java
1
请完成以下Java代码
public class QualityBasedInvoicingDAO implements IQualityBasedInvoicingDAO { @Override public IProductionMaterialQuery createInitialQuery() { return new ProductionMaterialQuery(); } @Override public List<IProductionMaterial> retriveProductionMaterials(final IProductionMaterialQuery query) { final ProductionMaterialQueryExecutor queryExecutor = new ProductionMaterialQueryExecutor(query); return queryExecutor.retriveProductionMaterials(); } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocuments(final I_M_Material_Tracking materialTracking) { return new MaterialTrackingDocuments(materialTracking); } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocumentsFor(@NonNull final I_PP_Order model) { final IMaterialTrackingDocuments materialTrackingDocuments = retrieveMaterialTrackingDocumentsOrNullFor(model); if (materialTrackingDocuments == null) { throw new AdempiereException("@NotFound@ @M_Material_Tracking_ID@" + "\n model: " + model); }
return materialTrackingDocuments; } @Override public IMaterialTrackingDocuments retrieveMaterialTrackingDocumentsOrNullFor(@NonNull final I_PP_Order model) { // Retrieve Material Tracking via material_tracklin final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final I_M_Material_Tracking materialTracking = materialTrackingDAO.retrieveSingleMaterialTrackingForModel(model); if (materialTracking == null) { return null; } return retrieveMaterialTrackingDocuments(materialTracking); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityBasedInvoicingDAO.java
1
请完成以下Java代码
public IQueryBuilder<I_M_ShipmentSchedule_QtyPicked> retrieveSchedsQtyPickedForVHUQuery(@NonNull final I_M_HU vhu) { return queryBL.createQueryBuilder(I_M_ShipmentSchedule_QtyPicked.class, vhu) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_VHU_ID, vhu.getM_HU_ID()) .orderBy(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_M_ShipmentSchedule_QtyPicked_ID); } @Override public List<ShipmentScheduleWithHU> retrieveShipmentSchedulesWithHUsFromHUs(@NonNull final List<I_M_HU> hus) { final IMutableHUContext huContext = huContextFactory.createMutableHUContext(); // // Iterate HUs and collect candidates from them final IHandlingUnitsBL handlingUnitsBL = handlingUnitsBL(); final ArrayList<ShipmentScheduleWithHU> result = new ArrayList<>(); for (final I_M_HU hu : hus) { // Make sure we are dealing with an top level HU if (!handlingUnitsBL.isTopLevel(hu)) { throw new HUException("HU " + hu + " shall be top level"); } // // Retrieve and create candidates from shipment schedule QtyPicked assignments final List<ShipmentScheduleWithHU> candidatesForHU = new ArrayList<>(); final List<I_M_ShipmentSchedule_QtyPicked> shipmentSchedulesQtyPicked = retrieveQtyPickedNotDeliveredForTopLevelHU(hu); for (final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked : shipmentSchedulesQtyPicked) { if (!shipmentScheduleQtyPicked.isActive()) { continue; } // NOTE: we allow negative Qtys too because they shall be part of a bigger transfer and overall qty can be positive // if (ssQtyPicked.getQtyPicked().signum() <= 0) // {
// continue; // } final ShipmentScheduleWithHU candidate = ShipmentScheduleWithHU.ofShipmentScheduleQtyPickedWithHuContext(shipmentScheduleQtyPicked, huContext); candidatesForHU.add(candidate); } // // Add the candidates for current HU to the list of all collected candidates result.addAll(candidatesForHU); // Log if there were no candidates created for current HU. if (candidatesForHU.isEmpty()) { Loggables.addLog("No eligible {} records found for hu {}", I_M_ShipmentSchedule_QtyPicked.Table_Name, handlingUnitsBL().getDisplayName(hu)); } } // // Sort result result.sort(new ShipmentScheduleWithHUComparator()); // TODO: make sure all shipment schedules are valid return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\HUShipmentScheduleDAO.java
1
请在Spring Boot框架中完成以下Java代码
public String getDelegationState() { return delegationState; } public void setDelegationState(String delegationState) { this.delegationState = delegationState; delegationStateSet = true; } public String getName() { return name; } public void setName(String name) { this.name = name; nameSet = true; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; descriptionSet = true; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; duedateSet = true; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; prioritySet = true; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; parentTaskIdSet = true; } public void setCategory(String category) { this.category = category; categorySet = true; } public String getCategory() { return category; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; tenantIdSet = true; } public String getFormKey() { return formKey; }
public void setFormKey(String formKey) { this.formKey = formKey; formKeySet = true; } public boolean isOwnerSet() { return ownerSet; } public boolean isAssigneeSet() { return assigneeSet; } public boolean isDelegationStateSet() { return delegationStateSet; } public boolean isNameSet() { return nameSet; } public boolean isDescriptionSet() { return descriptionSet; } public boolean isDuedateSet() { return duedateSet; } public boolean isPrioritySet() { return prioritySet; } public boolean isParentTaskIdSet() { return parentTaskIdSet; } public boolean isCategorySet() { return categorySet; } public boolean isTenantIdSet() { return tenantIdSet; } public boolean isFormKeySet() { return formKeySet; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java
2
请完成以下Java代码
public Set<DocumentStandardAction> getStandardActions(@NonNull final Document document) { final HashSet<DocumentStandardAction> standardActions = new HashSet<>(document.getStandardActions()); Boolean allowWindowEdit = null; Boolean allowDocumentEdit = null; for (final Iterator<DocumentStandardAction> it = standardActions.iterator(); it.hasNext(); ) { final DocumentStandardAction action = it.next(); if (action.isDocumentWriteAccessRequired()) { if (allowDocumentEdit == null) { allowDocumentEdit = DocumentPermissionsHelper.canEdit(document, permissions); } if (!allowDocumentEdit) { it.remove(); continue; } } if (action.isWindowWriteAccessRequired()) { if (allowWindowEdit == null) { final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();
final AdWindowId adWindowId = entityDescriptor.getDocumentType().isWindow() ? entityDescriptor.getWindowId().toAdWindowId() : null; allowWindowEdit = adWindowId != null && permissions.checkWindowPermission(adWindowId).hasWriteAccess(); } if (!allowWindowEdit) { it.remove(); //noinspection UnnecessaryContinue continue; } } } return ImmutableSet.copyOf(standardActions); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPermissions.java
1
请完成以下Java代码
public void installKeyboardActions (JComponent c) { super.installKeyboardActions (c); updateMnemonicBindingX ((AbstractButton)c); } // installKeyboardActions /** * Property Change * @param e event */ public void propertyChange (PropertyChangeEvent e) { String prop = e.getPropertyName(); if (prop.equals(AbstractButton.MNEMONIC_CHANGED_PROPERTY)) updateMnemonicBindingX ((AbstractButton)e.getSource()); else super.propertyChange (e); } // propertyChange /** * Update Mnemonic Binding * @param b button */ void updateMnemonicBindingX (AbstractButton b) { int m = b.getMnemonic(); if (m != 0) { InputMap map = SwingUtilities.getUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map == null) { map = new ComponentInputMapUIResource(b); SwingUtilities.replaceUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW, map); } map.clear(); String className = b.getClass().getName(); int mask = InputEvent.ALT_MASK; // Default Buttons if (b instanceof JCheckBox // In Tab || className.indexOf("VButton") != -1) mask = InputEvent.SHIFT_MASK + InputEvent.CTRL_MASK; map.put(KeyStroke.getKeyStroke(m, mask, false), "pressed"); map.put(KeyStroke.getKeyStroke(m, mask, true), "released"); map.put(KeyStroke.getKeyStroke(m, 0, true), "released"); } else { InputMap map = SwingUtilities.getUIInputMap(b, JComponent.WHEN_IN_FOCUSED_WINDOW); if (map != null) map.clear(); } } // updateMnemonicBindingX } // AdempiereButtonListener
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereButtonListener.java
1
请完成以下Java代码
static String encode(String path) { byte[] bytes = path.getBytes(StandardCharsets.UTF_8); for (byte b : bytes) { if (!isAllowed(b)) { return encode(bytes); } } return path; } private static String encode(byte[] bytes) { ByteArrayOutputStream result = new ByteArrayOutputStream(bytes.length); for (byte b : bytes) { if (isAllowed(b)) { result.write(b); } else { result.write('%'); result.write(Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16))); result.write(Character.toUpperCase(Character.forDigit(b & 0xF, 16))); }
} return result.toString(StandardCharsets.UTF_8); } private static boolean isAllowed(int ch) { for (char allowed : ALLOWED) { if (ch == allowed) { return true; } } return isAlpha(ch) || isDigit(ch); } private static boolean isAlpha(int ch) { return (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'); } private static boolean isDigit(int ch) { return (ch >= '0' && ch <= '9'); } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\UriPathEncoder.java
1
请完成以下Java代码
public boolean setValue(final String propertyName, final Object value) { pojoWrapper.setValue(propertyName, value); return true; } @Override public boolean setValueNoCheck(String columnName, Object value) { pojoWrapper.setValue(columnName, value); return true; } @Override public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception { return pojoWrapper.getReferencedObject(propertyName, interfaceMethod); } @Override public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value) { final String propertyName; if (idPropertyName.endsWith("_ID")) { propertyName = idPropertyName.substring(0, idPropertyName.length() - 3); } else { throw new AdempiereException("Invalid idPropertyName: " + idPropertyName); } pojoWrapper.setReferencedObject(propertyName, value); }
@Override public boolean invokeEquals(final Object[] methodArgs) { return pojoWrapper.invokeEquals(methodArgs); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { throw new IllegalStateException("Invoking parent method is not supported"); } @Override public boolean isKeyColumnName(final String columnName) { return pojoWrapper.isKeyColumnName(columnName); } @Override public boolean isCalculated(final String columnName) { return pojoWrapper.isCalculated(columnName); } @Override public boolean hasColumnName(String columnName) { return pojoWrapper.hasColumnName(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOModelInternalAccessor.java
1
请完成以下Java代码
public void parse( XMLStreamReader xtr, List<SubProcess> activeSubProcessList, Process activeProcess, BpmnModel model ) throws Exception { BaseElement parentElement = null; if (!activeSubProcessList.isEmpty()) { parentElement = activeSubProcessList.get(activeSubProcessList.size() - 1); } else { parentElement = activeProcess; } boolean readyWithChildElements = false; while (readyWithChildElements == false && xtr.hasNext()) { xtr.next(); if (xtr.isStartElement()) { if (ELEMENT_EXECUTION_LISTENER.equals(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, parentElement, model); } else if (ELEMENT_EVENT_LISTENER.equals(xtr.getLocalName())) { new ActivitiEventListenerParser().parseChildElement(xtr, parentElement, model);
} else if (ELEMENT_POTENTIAL_STARTER.equals(xtr.getLocalName())) { new PotentialStarterParser().parse(xtr, activeProcess); } else { ExtensionElement extensionElement = BpmnXMLUtil.parseExtensionElement(xtr); if (parentElement != null) { parentElement.addExtensionElement(extensionElement); } } } else if (xtr.isEndElement()) { if (ELEMENT_EXTENSIONS.equals(xtr.getLocalName())) { readyWithChildElements = true; } } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\ExtensionElementsParser.java
1
请完成以下Java代码
protected MessageCorrelationBuilder createMessageCorrelationBuilder(CorrelationMessageDto messageDto) { ProcessEngine processEngine = getProcessEngine(); RuntimeService runtimeService = processEngine.getRuntimeService(); ObjectMapper objectMapper = getObjectMapper(); Map<String, Object> correlationKeys = VariableValueDto.toMap(messageDto.getCorrelationKeys(), processEngine, objectMapper); Map<String, Object> localCorrelationKeys = VariableValueDto.toMap(messageDto.getLocalCorrelationKeys(), processEngine, objectMapper); Map<String, Object> processVariables = VariableValueDto.toMap(messageDto.getProcessVariables(), processEngine, objectMapper); Map<String, Object> processVariablesLocal = VariableValueDto.toMap(messageDto.getProcessVariablesLocal(), processEngine, objectMapper); Map<String, Object> processVariablesToTriggeredScope = VariableValueDto.toMap(messageDto.getProcessVariablesToTriggeredScope(), processEngine, objectMapper); MessageCorrelationBuilder builder = runtimeService .createMessageCorrelation(messageDto.getMessageName()); if (processVariables != null) { builder.setVariables(processVariables); } if (processVariablesLocal != null) { builder.setVariablesLocal(processVariablesLocal); } if (processVariablesToTriggeredScope != null) { builder.setVariablesToTriggeredScope(processVariablesToTriggeredScope); } if (messageDto.getBusinessKey() != null) { builder.processInstanceBusinessKey(messageDto.getBusinessKey()); } if (correlationKeys != null && !correlationKeys.isEmpty()) { for (Entry<String, Object> correlationKey : correlationKeys.entrySet()) { String name = correlationKey.getKey(); Object value = correlationKey.getValue(); builder.processInstanceVariableEquals(name, value); } } if (localCorrelationKeys != null && !localCorrelationKeys.isEmpty()) { for (Entry<String, Object> correlationKey : localCorrelationKeys.entrySet()) {
String name = correlationKey.getKey(); Object value = correlationKey.getValue(); builder.localVariableEquals(name, value); } } if (messageDto.getTenantId() != null) { builder.tenantId(messageDto.getTenantId()); } else if (messageDto.isWithoutTenantId()) { builder.withoutTenantId(); } String processInstanceId = messageDto.getProcessInstanceId(); if (processInstanceId != null) { builder.processInstanceId(processInstanceId); } return builder; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MessageRestServiceImpl.java
1
请完成以下Java代码
public abstract class AbstractRateLimiter<C> extends AbstractStatefulConfigurable<C> implements RateLimiter<C>, ApplicationListener<FilterArgsEvent> { private String configurationPropertyName; private @Nullable ConfigurationService configurationService; protected AbstractRateLimiter(Class<C> configClass, String configurationPropertyName, @Nullable ConfigurationService configurationService) { super(configClass); this.configurationPropertyName = configurationPropertyName; this.configurationService = configurationService; } protected String getConfigurationPropertyName() { return configurationPropertyName; } protected void setConfigurationService(ConfigurationService configurationService) { this.configurationService = configurationService; } @Override public void onApplicationEvent(FilterArgsEvent event) { Map<String, Object> args = event.getArgs(); if (args.isEmpty() || !hasRelevantKey(args)) { return; }
String routeId = event.getRouteId(); C routeConfig = newConfig(); if (this.configurationService != null) { this.configurationService.with(routeConfig) .name(this.configurationPropertyName) .normalizedProperties(args) .bind(); } getConfig().put(routeId, routeConfig); } private boolean hasRelevantKey(Map<String, Object> args) { return args.keySet().stream().anyMatch(key -> key.startsWith(configurationPropertyName + ".")); } @Override public String toString() { return new ToStringCreator(this).append("configurationPropertyName", configurationPropertyName) .append("config", getConfig()) .append("configClass", getConfigClass()) .toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\ratelimit\AbstractRateLimiter.java
1
请完成以下Java代码
public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } @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 getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\event\FlowableEngineEventImpl.java
1
请完成以下Java代码
public RefundContract save(@NonNull final RefundContract contract) { final I_C_Flatrate_Term contractRecord; if (contract.getId() == null) { contractRecord = newInstance(I_C_Flatrate_Term.class); } else { contractRecord = load(contract.getId().getRepoId(), I_C_Flatrate_Term.class); } // contractRecord.setM_Product_ID(contract.getProductId().getRepoId()); contractRecord.setType_Conditions(X_C_Flatrate_Term.TYPE_CONDITIONS_Refund); contractRecord.setDocStatus(IDocument.STATUS_Completed); contractRecord.setStartDate(TimeUtil.asTimestamp(contract.getStartDate())); contractRecord.setEndDate(TimeUtil.asTimestamp(contract.getEndDate())); contractRecord.setBill_BPartner_ID(contract.getBPartnerId().getRepoId());
final List<RefundConfig> refundConfigs = contract.getRefundConfigs(); final ConditionsId conditionsId = CollectionUtils.extractSingleElement(refundConfigs, RefundConfig::getConditionsId); contractRecord.setC_Flatrate_Conditions_ID(conditionsId.getRepoId()); final List<RefundConfig> savedConfigs = refundConfigRepository.saveAll(refundConfigs); saveRecord(contractRecord); return contract .toBuilder() .id(FlatrateTermId.ofRepoId(contractRecord.getC_Flatrate_Term_ID())) .clearRefundConfigs() .refundConfigs(savedConfigs) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundContractRepository.java
1
请完成以下Java代码
public static InstanceWebClient.Builder builder() { return new InstanceWebClient.Builder(); } public static InstanceWebClient.Builder builder(WebClient.Builder webClient) { return new InstanceWebClient.Builder(webClient); } private static ExchangeFilterFunction setInstance(Mono<Instance> instance) { return (request, next) -> instance .map((i) -> ClientRequest.from(request).attribute(ATTRIBUTE_INSTANCE, i).build()) .switchIfEmpty(Mono.error(() -> new ResolveInstanceException("Could not resolve Instance"))) .flatMap(next::exchange); } private static ExchangeFilterFunction toExchangeFilterFunction(InstanceExchangeFilterFunction filter) { return (request, next) -> request.attribute(ATTRIBUTE_INSTANCE) .filter(Instance.class::isInstance) .map(Instance.class::cast) .map((instance) -> filter.filter(instance, request, next)) .orElseGet(() -> next.exchange(request)); } public static class Builder { private List<InstanceExchangeFilterFunction> filters = new ArrayList<>(); private WebClient.Builder webClientBuilder; public Builder() { this(WebClient.builder()); } public Builder(WebClient.Builder webClientBuilder) { this.webClientBuilder = webClientBuilder; } protected Builder(Builder other) { this.filters = new ArrayList<>(other.filters); this.webClientBuilder = other.webClientBuilder.clone(); } public Builder filter(InstanceExchangeFilterFunction filter) { this.filters.add(filter); return this;
} public Builder filters(Consumer<List<InstanceExchangeFilterFunction>> filtersConsumer) { filtersConsumer.accept(this.filters); return this; } public Builder webClient(WebClient.Builder builder) { this.webClientBuilder = builder; return this; } public Builder clone() { return new Builder(this); } public InstanceWebClient build() { this.filters.stream() .map(InstanceWebClient::toExchangeFilterFunction) .forEach(this.webClientBuilder::filter); return new InstanceWebClient(this.webClientBuilder.build()); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\InstanceWebClient.java
1
请完成以下Java代码
public class ContactPhoneNo { private final int AD_User_ID; private final String phoneNo; private final String contactName; public ContactPhoneNo(String phoneNo, String contactName, int AD_User_ID) { super(); this.phoneNo = phoneNo; this.contactName = contactName; this.AD_User_ID = AD_User_ID; } public String getPhoneNo() { return phoneNo; } public String getContactName() { return contactName;
} public int getAD_User_ID() { return AD_User_ID; } @Override public String toString() { return phoneNo + " ("+contactName+")"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\ContactPhoneNo.java
1
请在Spring Boot框架中完成以下Java代码
public DTAXI1 getDTAXI1() { return dtaxi1; } /** * Sets the value of the dtaxi1 property. * * @param value * allowed object is * {@link DTAXI1 } * */ public void setDTAXI1(DTAXI1 value) { this.dtaxi1 = value; } /** * Gets the value of the dalch1 property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dalch1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDALCH1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DALCH1 } * * */ public List<DALCH1> getDALCH1() { if (dalch1 == null) { dalch1 = new ArrayList<DALCH1>(); } return this.dalch1; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\DETAILXrech.java
2
请完成以下Java代码
public String getDetailInfo () { return (String)get_Value(COLUMNNAME_DetailInfo); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Approved. @param IsApproved Indicates if this document requires approval */ public void setIsApproved (boolean IsApproved) { set_Value (COLUMNNAME_IsApproved, Boolean.valueOf(IsApproved)); } /** Get Approved. @return Indicates if this document requires approval */ public boolean isApproved () { Object oo = get_Value(COLUMNNAME_IsApproved); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Change Notice. @param M_ChangeNotice_ID Bill of Materials (Engineering) Change Notice (Version) */ public void setM_ChangeNotice_ID (int M_ChangeNotice_ID) { if (M_ChangeNotice_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID)); } /** Get Change Notice. @return Bill of Materials (Engineering) Change Notice (Version) */ public int getM_ChangeNotice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ 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; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeNotice.java
1
请在Spring Boot框架中完成以下Java代码
public class M_ProductPrice { private static final AdMessageKey MSG_NO_C_TAX_CATEGORY_FOR_PRODUCT_PRICE = AdMessageKey.of("MissingTaxCategoryForProductPrice"); private final ProductTaxCategoryService productTaxCategoryService; private final IMsgBL msgBL = Services.get(IMsgBL.class); public M_ProductPrice(@NonNull final ProductTaxCategoryService productTaxCategoryService) { this.productTaxCategoryService = productTaxCategoryService; } @Init public void init(final IModelValidationEngine engine) { CopyRecordFactory.enableForTableName(I_M_ProductPrice.Table_Name); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }) public void assertMainProductPriceIsNotDuplicate(@NonNull final I_M_ProductPrice productPrice) { ProductPrices.assertMainProductPriceIsNotDuplicate(productPrice); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_ProductPrice.COLUMNNAME_C_UOM_ID, I_M_ProductPrice.COLUMNNAME_IsInvalidPrice, I_M_ProductPrice.COLUMNNAME_IsActive }) public void assertUomConversionExists(@NonNull final I_M_ProductPrice productPrice) { ProductPrices.assertUomConversionExists(productPrice); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_M_ProductPrice.COLUMNNAME_C_TaxCategory_ID }) public void assertProductTaxCategoryExists(@NonNull final I_M_ProductPrice productPrice) { if (productPrice.getC_TaxCategory_ID() <= 0) { final Optional<TaxCategoryId> taxCategoryId = productTaxCategoryService.getTaxCategoryIdOptional(productPrice); if (!taxCategoryId.isPresent()) { final ITranslatableString message = msgBL.getTranslatableMsgText(MSG_NO_C_TAX_CATEGORY_FOR_PRODUCT_PRICE); throw new AdempiereException(message).markAsUserValidationError(); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\interceptor\M_ProductPrice.java
2
请完成以下Java代码
public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.lt(converter, o1, o2); } @Override public String toString() { return "<"; } }; public static final Operator MOD = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mod(converter, o1, o2); } @Override public String toString() { return "%"; } }; public static final Operator MUL = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.mul(converter, o1, o2); } @Override public String toString() { return "*"; } }; public static final Operator NE = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return BooleanOperations.ne(converter, o1, o2); } @Override public String toString() { return "!="; } }; public static final Operator OR = new Operator() { public Object eval(Bindings bindings, ELContext context, AstNode left, AstNode right) { Boolean l = bindings.convert(left.eval(bindings, context), Boolean.class); return Boolean.TRUE.equals(l) ? Boolean.TRUE : bindings.convert(right.eval(bindings, context), Boolean.class); } @Override public String toString() { return "||"; } }; public static final Operator SUB = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.sub(converter, o1, o2); } @Override public String toString() { return "-";
} }; private final Operator operator; private final AstNode left, right; public AstBinary(AstNode left, AstNode right, Operator operator) { this.left = left; this.right = right; this.operator = operator; } public Operator getOperator() { return operator; } @Override public Object eval(Bindings bindings, ELContext context) { return operator.eval(bindings, context, left, right); } @Override public String toString() { return "'" + operator.toString() + "'"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { left.appendStructure(b, bindings); b.append(' '); b.append(operator); b.append(' '); right.appendStructure(b, bindings); } public int getCardinality() { return 2; } public AstNode getChild(int i) { return i == 0 ? left : i == 1 ? right : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstBinary.java
1
请完成以下Java代码
public void setC_DirectDebit_ID (int C_DirectDebit_ID) { if (C_DirectDebit_ID < 1) throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory."); set_ValueNoCheck (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID)); } /** Get C_DirectDebit_ID. @return C_DirectDebit_ID */ public int getC_DirectDebit_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Dtafile. @param Dtafile Copy of the *.dta stored as plain text */ public void setDtafile (String Dtafile) { set_Value (COLUMNNAME_Dtafile, Dtafile); } /** Get Dtafile. @return Copy of the *.dta stored as plain text */ public String getDtafile () { return (String)get_Value(COLUMNNAME_Dtafile); } /** Set IsRemittance. @param IsRemittance IsRemittance */
public void setIsRemittance (boolean IsRemittance) { set_Value (COLUMNNAME_IsRemittance, Boolean.valueOf(IsRemittance)); } /** Get IsRemittance. @return IsRemittance */ public boolean isRemittance () { Object oo = get_Value(COLUMNNAME_IsRemittance); 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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebit.java
1
请完成以下Java代码
private static String cmdString(String[] cmd) { StringBuilder cmdText = new StringBuilder(); for(String cmdPart: cmd) { cmdText.append(cmdPart); cmdText.append(" "); } return cmdText.toString(); } public void run() { task.log("launching cmd '"+cmdString(cmd)+"' in dir '"+dir+"'"); if (msg!=null) { task.log("waiting for launch completion msg '"+msg+"'..."); } else { task.log("not waiting for a launch completion msg."); } ProcessBuilder processBuilder = new ProcessBuilder(cmd) .redirectErrorStream(true) .directory(dir); InputStream consoleStream = null; try { Process process = processBuilder.start(); consoleStream = process.getInputStream(); BufferedReader consoleReader = new BufferedReader(new InputStreamReader(consoleStream)); String consoleLine = ""; while ( (consoleLine!=null) && (msg==null || consoleLine.indexOf(msg)==-1) ) {
consoleLine = consoleReader.readLine(); if (consoleLine!=null) { task.log(" " + consoleLine); } else { task.log("launched process completed"); } } } catch (Exception e) { throw new BuildException("couldn't launch "+cmdString(cmd), e); } finally { IoUtil.closeSilently(consoleStream); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ant\LaunchThread.java
1
请完成以下Java代码
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) { ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); if (response.isCommitted()) { return Mono.error(ex); } response.getHeaders().setContentType(MediaType.APPLICATION_JSON); if (ex instanceof ResponseStatusException) { response.setStatusCode(((ResponseStatusException) ex).getStatusCode()); } return response.writeWith(Mono.fromSupplier(() -> { DataBufferFactory bufferFactory = response.bufferFactory(); try { int status = 500; if (response.getStatusCode() != null) { status = response.getStatusCode().value(); } Map<String, Object> result = ResponseProvider.response(status, this.buildMessage(request, ex)); return bufferFactory.wrap(objectMapper.writeValueAsBytes(result)); } catch (JsonProcessingException e) {
return bufferFactory.wrap(new byte[0]); } })); } /** * 构建异常信息 */ private String buildMessage(ServerHttpRequest request, Throwable ex) { StringBuilder message = new StringBuilder("Failed to handle request ["); message.append(request.getMethod().name()); message.append(" "); message.append(request.getURI()); message.append("]"); if (ex != null) { message.append(": "); message.append(ex.getMessage()); } return message.toString(); } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\handler\ErrorExceptionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class GrpcServiceDefinition { private final String beanName; private final Class<?> beanClazz; private final ServerServiceDefinition definition; /** * Creates a new GrpcServiceDefinition. * * @param beanName The name of the grpc service bean in the spring context. * @param beanClazz The class of the grpc service bean. * @param definition The grpc service definition. */ public GrpcServiceDefinition(final String beanName, final Class<?> beanClazz, final ServerServiceDefinition definition) { this.beanName = beanName; this.beanClazz = beanClazz; this.definition = definition; } /** * Gets the name of the grpc service bean. * * @return The name of the bean.
*/ public String getBeanName() { return this.beanName; } /** * Gets the class of the grpc service bean. * * @return The class of the grpc service bean. */ public Class<?> getBeanClazz() { return this.beanClazz; } /** * Gets the grpc service definition. * * @return The grpc service definition. */ public ServerServiceDefinition getDefinition() { return this.definition; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\service\GrpcServiceDefinition.java
2
请完成以下Java代码
public PickingJobCandidateProducts updatingEachProduct(@NonNull UnaryOperator<PickingJobCandidateProduct> updater) { if (byProductId.isEmpty()) { return this; } final ImmutableMap<ProductId, PickingJobCandidateProduct> byProductIdNew = byProductId.values() .stream() .map(updater) .collect(ImmutableMap.toImmutableMap(PickingJobCandidateProduct::getProductId, product -> product)); return Objects.equals(this.byProductId, byProductIdNew) ? this : new PickingJobCandidateProducts(byProductIdNew); } @Nullable public ProductId getSingleProductIdOrNull() { return singleProduct != null ? singleProduct.getProductId() : null; }
@Nullable public Quantity getSingleQtyToDeliverOrNull() { return singleProduct != null ? singleProduct.getQtyToDeliver() : null; } @Nullable public Quantity getSingleQtyAvailableToPickOrNull() { return singleProduct != null ? singleProduct.getQtyAvailableToPick() : null; } @Nullable public ITranslatableString getSingleProductNameOrNull() { return singleProduct != null ? singleProduct.getProductName() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidateProducts.java
1
请完成以下Java代码
public class SetTaskVariablesCmd extends NeedsActiveTaskCmd<Object> { private static final long serialVersionUID = 1L; protected Map<String, ? extends Object> variables; protected boolean isLocal; public SetTaskVariablesCmd(String taskId, Map<String, ? extends Object> variables, boolean isLocal) { super(taskId); this.taskId = taskId; this.variables = variables; this.isLocal = isLocal; } protected Object execute(CommandContext commandContext, TaskEntity task) { if (isLocal) { if (variables != null) { for (String variableName : variables.keySet()) { task.setVariableLocal(variableName, variables.get(variableName), false); } } } else {
if (variables != null) { for (String variableName : variables.keySet()) { task.setVariable(variableName, variables.get(variableName), false); } } } // ACT-1887: Force an update of the task's revision to prevent // simultaneous inserts of the same variable. If not, duplicate variables may occur since optimistic // locking doesn't work on inserts task.forceUpdate(); return null; } @Override protected String getSuspendedTaskException() { return "Cannot add variables to a suspended task"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetTaskVariablesCmd.java
1
请完成以下Java代码
public List<IUserRolePermissions> getUserRolesPermissionsForUserWithOrgAccess( @NonNull final UserId userId, @NonNull final ClientAndOrgId clientAndOrgId) { return userRolePermissionsDAO.retrieveUserRolesPermissionsForUserWithOrgAccess( clientAndOrgId.getClientId(), clientAndOrgId.getOrgId(), userId, Env.getLocalDate()); } public Money convertMoney( @NonNull final Money amount, @NonNull final CurrencyId toCurrencyId, @NonNull final ClientAndOrgId clientAndOrgId) { if (CurrencyId.equals(amount.getCurrencyId(), toCurrencyId)) { return amount; } final CurrencyConversionContext conversionCtx = currencyBL.createCurrencyConversionContext( null, // TODAY (CurrencyConversionTypeId)null, clientAndOrgId.getClientId(), clientAndOrgId.getOrgId()); final CurrencyConversionResult conversionResult = currencyBL.convert( conversionCtx, amount.toBigDecimal(), amount.getCurrencyId(), toCurrencyId); if (conversionResult == null) { throw new NoCurrencyRateFoundException( currencyBL.getCurrencyCodeById(amount.getCurrencyId()), currencyBL.getCurrencyCodeById(toCurrencyId), conversionCtx.getConversionDate(), null); } return Money.of(conversionResult.getAmount(), toCurrencyId); } public I_AD_User getUserById(@NonNull final UserId userId) { return userDAO.getById(userId); } public String getUserFullname() { return getUserFullnameById(getUserId()); } public String getUserFullnameById(@NonNull final UserId userId) { return userDAO.retrieveUserFullName(userId);
} public OrgInfo getOrgInfoById(@NonNull final OrgId orgId) { return orgsRepo.getOrgInfoById(orgId); } public void sendNotification(@NonNull final WFUserNotification notification) { notificationBL.sendAfterCommit(UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC) .recipientUserId(notification.getUserId()) .contentADMessage(notification.getContent().getAdMessage()) .contentADMessageParams(notification.getContent().getParams()) .targetAction(notification.getDocumentToOpen() != null ? UserNotificationRequest.TargetRecordAction.of(notification.getDocumentToOpen()) : null) .build()); } public MailTextBuilder newMailTextBuilder( @NonNull final TableRecordReference documentRef, @NonNull final MailTemplateId mailTemplateId) { return mailService.newMailTextBuilder(mailTemplateId) .recordAndUpdateBPartnerAndContact(getPO(documentRef)); } public void save(@NonNull final WFEventAudit audit) { auditRepo.save(audit); } public void addEventAudit(@NonNull final WFEventAudit audit) { auditList.add(audit); } public void createNewAttachment( @NonNull final Object referencedRecord, @NonNull final File file) { attachmentEntryService.createNewAttachment(referencedRecord, file); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WorkflowExecutionContext.java
1