instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class MinHeap { HeapNode[] heapNodes; public MinHeap(HeapNode heapNodes[]) { this.heapNodes = heapNodes; heapifyFromLastLeafsParent(); } void heapifyFromLastLeafsParent() { int lastLeafsParentIndex = getParentNodeIndex(heapNodes.length); while (lastLeafsParentIndex >= 0) { heapify(lastLeafsParentIndex); lastLeafsParentIndex--; } } void heapify(int index) { int leftNodeIndex = getLeftNodeIndex(index); int rightNodeIndex = getRightNodeIndex(index); int smallestElementIndex = index; if (leftNodeIndex < heapNodes.length && heapNodes[leftNodeIndex].element < heapNodes[index].element) { smallestElementIndex = leftNodeIndex; } if (rightNodeIndex < heapNodes.length && heapNodes[rightNodeIndex].element < heapNodes[smallestElementIndex].element) { smallestElementIndex = rightNodeIndex; } if (smallestElementIndex != index) { swap(index, smallestElementIndex); heapify(smallestElementIndex); } } int getParentNodeIndex(int index) { return (index - 1) / 2; } int getLeftNodeIndex(int index) { return (2 * index + 1); } int getRightNodeIndex(int index) { return (2 * index + 2); } HeapNode getRootNode() { return heapNodes[0];
} void heapifyFromRoot() { heapify(0); } void swap(int i, int j) { HeapNode temp = heapNodes[i]; heapNodes[i] = heapNodes[j]; heapNodes[j] = temp; } static int[] merge(int[][] array) { HeapNode[] heapNodes = new HeapNode[array.length]; int resultingArraySize = 0; for (int i = 0; i < array.length; i++) { HeapNode node = new HeapNode(array[i][0], i); heapNodes[i] = node; resultingArraySize += array[i].length; } MinHeap minHeap = new MinHeap(heapNodes); int[] resultingArray = new int[resultingArraySize]; for (int i = 0; i < resultingArraySize; i++) { HeapNode root = minHeap.getRootNode(); resultingArray[i] = root.element; if (root.nextElementIndex < array[root.arrayIndex].length) { root.element = array[root.arrayIndex][root.nextElementIndex++]; } else { root.element = Integer.MAX_VALUE; } minHeap.heapifyFromRoot(); } return resultingArray; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\minheapmerge\MinHeap.java
1
请完成以下Java代码
public void setDHL_ShipmentOrderRequest_ID (final int DHL_ShipmentOrderRequest_ID) { if (DHL_ShipmentOrderRequest_ID < 1) set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, null); else set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, DHL_ShipmentOrderRequest_ID); } @Override public int getDHL_ShipmentOrderRequest_ID() { return get_ValueAsInt(COLUMNNAME_DHL_ShipmentOrderRequest_ID); } @Override public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() {
return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setRequestMessage (final @Nullable java.lang.String RequestMessage) { set_Value (COLUMNNAME_RequestMessage, RequestMessage); } @Override public java.lang.String getRequestMessage() { return get_ValueAsString(COLUMNNAME_RequestMessage); } @Override public void setResponseMessage (final @Nullable java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } @Override public java.lang.String getResponseMessage() { return get_ValueAsString(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_Dhl_ShipmentOrder_Log.java
1
请完成以下Java代码
public void setDiscountBaseAmt (final @Nullable BigDecimal DiscountBaseAmt) { set_ValueNoCheck (COLUMNNAME_DiscountBaseAmt, DiscountBaseAmt); } @Override public BigDecimal getDiscountBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DiscountBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setDiscountDate (final @Nullable java.sql.Timestamp DiscountDate) { set_Value (COLUMNNAME_DiscountDate, DiscountDate); } @Override public java.sql.Timestamp getDiscountDate() { return get_ValueAsTimestamp(COLUMNNAME_DiscountDate); } @Override public void setDiscountDays (final int DiscountDays) { set_Value (COLUMNNAME_DiscountDays, DiscountDays); } @Override public int getDiscountDays() { return get_ValueAsInt(COLUMNNAME_DiscountDays); } @Override public void setEDI_cctop_140_v_ID (final int EDI_cctop_140_v_ID) { if (EDI_cctop_140_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_140_v_ID, EDI_cctop_140_v_ID); } @Override public int getEDI_cctop_140_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_140_v_ID); } @Override public de.metas.esb.edi.model.I_EDI_cctop_invoic_v getEDI_cctop_invoic_v() { return get_ValueAsPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class); } @Override public void setEDI_cctop_invoic_v(final de.metas.esb.edi.model.I_EDI_cctop_invoic_v EDI_cctop_invoic_v) { set_ValueFromPO(COLUMNNAME_EDI_cctop_invoic_v_ID, de.metas.esb.edi.model.I_EDI_cctop_invoic_v.class, EDI_cctop_invoic_v); }
@Override public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID) { if (EDI_cctop_invoic_v_ID < 1) set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null); else set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID); } @Override public int getEDI_cctop_invoic_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID); } @Override public void setName (final @Nullable java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_140_v.java
1
请完成以下Java代码
public String getAwardName() { return awardName; } public void setAwardName(String awardName) { this.awardName = awardName; } public String getAttendType() { return attendType; } public void setAttendType(String attendType) { this.attendType = attendType; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @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(", categoryId=").append(categoryId); sb.append(", name=").append(name); sb.append(", createTime=").append(createTime); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", attendCount=").append(attendCount); sb.append(", attentionCount=").append(attentionCount); sb.append(", readCount=").append(readCount); sb.append(", awardName=").append(awardName); sb.append(", attendType=").append(attendType); sb.append(", content=").append(content); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopic.java
1
请在Spring Boot框架中完成以下Java代码
public Locale getLocale() { final Language language = getLanguage(); if (language != null) { return language.getLocale(); } return Locale.getDefault(); } public JXlsExporter setTemplateResourceName(final String templateResourceName) { this._templateResourceName = templateResourceName; return this; } private InputStream getTemplate() { if (_template != null) { return _template; } if (!Check.isEmpty(_templateResourceName, true)) { final ClassLoader loader = getLoader(); final InputStream template = loader.getResourceAsStream(_templateResourceName); if (template == null) { throw new JXlsExporterException("Could not find template for name: " + _templateResourceName + " using " + loader); } return template; } throw new JXlsExporterException("Template is not configured"); } public JXlsExporter setTemplate(final InputStream template) { this._template = template; return this; } private IXlsDataSource getDataSource() { Check.assumeNotNull(_dataSource, "dataSource not null"); return _dataSource; } public JXlsExporter setDataSource(final IXlsDataSource dataSource) { this._dataSource = dataSource; return this; } public JXlsExporter setResourceBundle(final ResourceBundle resourceBundle) { this._resourceBundle = resourceBundle; return this;
} private ResourceBundle getResourceBundle() { if (_resourceBundle != null) { return _resourceBundle; } if (!Check.isEmpty(_templateResourceName, true)) { String baseName = null; try { final int dotIndex = _templateResourceName.lastIndexOf('.'); baseName = dotIndex <= 0 ? _templateResourceName : _templateResourceName.substring(0, dotIndex); return ResourceBundle.getBundle(baseName, getLocale(), getLoader()); } catch (final MissingResourceException e) { logger.debug("No resource found for {}", baseName); } } return null; } public Map<String, String> getResourceBundleAsMap() { final ResourceBundle bundle = getResourceBundle(); if (bundle == null) { return ImmutableMap.of(); } return ResourceBundleMapWrapper.of(bundle); } public JXlsExporter setProperty(@NonNull final String name, @NonNull final Object value) { Check.assumeNotEmpty(name, "name not empty"); _properties.put(name, value); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JXlsExporter.java
2
请完成以下Java代码
private Step step() throws Exception { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(dataSourceItemReader()) .writer(list -> list.forEach(System.out::println)) .build(); } private ItemReader<TestData> dataSourceItemReader() throws Exception { JdbcPagingItemReader<TestData> reader = new JdbcPagingItemReader<>(); reader.setDataSource(dataSource); // 设置数据源 reader.setFetchSize(5); // 每次取多少条记录 reader.setPageSize(5); // 设置每页数据量 // 指定sql查询语句 select id,field1,field2,field3 from TEST MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider(); provider.setSelectClause("id,field1,field2,field3"); //设置查询字段 provider.setFromClause("from TEST"); // 设置从哪张表查询 // 将读取到的数据转换为TestData对象
reader.setRowMapper((resultSet, rowNum) -> { TestData data = new TestData(); data.setId(resultSet.getInt(1)); data.setField1(resultSet.getString(2)); // 读取第一个字段,类型为String data.setField2(resultSet.getString(3)); data.setField3(resultSet.getString(4)); return data; }); Map<String, Order> sort = new HashMap<>(1); sort.put("id", Order.ASCENDING); provider.setSortKeys(sort); // 设置排序,通过id 升序 reader.setQueryProvider(provider); // 设置namedParameterJdbcTemplate等属性 reader.afterPropertiesSet(); return reader; } }
repos\SpringAll-master\68.spring-batch-itemreader\src\main\java\cc\mrbird\batch\job\DataSourceItemReaderDemo.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.reject(); } final I_PP_Order ppOrder = ppOrderBL.getById(getPPOrderId(context.getSingleSelectedRecordId())); return ProcessPreconditionsResolution.acceptIf(isEligible(ppOrder)); } private static boolean isEligible(@Nullable final I_PP_Order ppOrder) { if (ppOrder == null) { return false; } final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus()); return docStatus.isDraftedOrInProgress(); } @Override protected String doIt() { final PPOrderId ppOrderId = getPPOrderId(getRecord_ID()); final OrderLineId orderLineId = getOrderLienId(); setC_OrderLine_ID(ppOrderId, orderLineId);
return MSG_OK; } private PPOrderId getPPOrderId(int ppOrderId) { return PPOrderId.ofRepoId(ppOrderId); } private OrderLineId getOrderLienId() { return OrderLineId.ofRepoId(p_C_OrderLine_ID); } private void setC_OrderLine_ID(@NonNull final PPOrderId ppOrderId, @NonNull final OrderLineId orderLineId) { ppOrderBL.setC_OrderLine(ppOrderId, orderLineId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_SetC_OrderLine.java
1
请完成以下Java代码
public class VariableInstanceHistoryListener implements VariableInstanceLifecycleListener<VariableInstanceEntity> { public static final VariableInstanceHistoryListener INSTANCE = new VariableInstanceHistoryListener(); @Override public void onCreate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_CREATE, variableInstance) && !variableInstance.isTransient()) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableCreateEvt(variableInstance, sourceScope); } }); } } @Override public void onDelete(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_DELETE, variableInstance) && !variableInstance.isTransient()) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableDeleteEvt(variableInstance, sourceScope);
} }); } } @Override public void onUpdate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_UPDATE, variableInstance) && !variableInstance.isTransient()) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableUpdateEvt(variableInstance, sourceScope); } }); } } protected HistoryLevel getHistoryLevel() { return Context.getProcessEngineConfiguration().getHistoryLevel(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceHistoryListener.java
1
请完成以下Java代码
public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { if (jdbcType == null) { throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters."); } try { if (useDefaultJdbcType) { JdbcType finalJdbcType = null; if (jdbcType.equals(JdbcType.NVARCHAR)) { finalJdbcType = JdbcType.VARCHAR; } else { finalJdbcType = jdbcType; } ps.setNull(i, finalJdbcType.TYPE_CODE); } else { ps.setNull(i, Types.NULL); } } catch (SQLException e) { throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " + "Cause: " + e, e); } } else { try { setNonNullParameter(ps, i, parameter, jdbcType); } catch (Exception e) { throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different configuration property. " + "Cause: " + e, e); }
} } @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, parameter); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { return rs.getString(columnName); } @Override public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return rs.getString(columnIndex); } @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getString(columnIndex); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\FlowableStringTypeHandler.java
1
请完成以下Java代码
private PickingSlotQueue getFromPickingSlotQueue() { PickingSlotQueue pickingSlotQueue = this._fromPickingSlotQueue; if (pickingSlotQueue == null) { pickingSlotQueue = this._fromPickingSlotQueue = pickingSlotService.getPickingSlotQueue(fromPickingSlotId); } return pickingSlotQueue; } private void setCurrentTarget(@NonNull final HUConsolidationTarget target) { this.job = this.job.withCurrentTarget(target); } @NonNull private HUConsolidationTarget getCurrentTarget() { return job.getCurrentTargetNotNull(); } private void consolidateFromLUs(@NonNull final List<I_M_HU> fromLUs) { if (fromLUs.isEmpty()) { return; } getCurrentTarget().apply(new HUConsolidationTarget.CaseConsumer() { @Override public void newLU(final HuPackingInstructionsId luPackingInstructionsId) {consolidate_FromLUs_ToNewLU(fromLUs, luPackingInstructionsId);} @Override public void existingLU(final HuId luId, final HUQRCode luQRCode) {consolidate_FromLUs_ToExistingLU(fromLUs, luId, luQRCode);} }); } @SuppressWarnings("unused") private void consolidate_FromLUs_ToNewLU(@NonNull final List<I_M_HU> fromLUs, @NonNull final HuPackingInstructionsId luPackingInstructionsId) { throw new UnsupportedOperationException(); // TODO } @SuppressWarnings("unused") private void consolidate_FromLUs_ToExistingLU(@NonNull final List<I_M_HU> fromLUs, @NonNull final HuId luId, @NonNull final HUQRCode luQRCode) { throw new UnsupportedOperationException(); // TODO
} private void consolidateFromTUs(@NonNull final List<I_M_HU> fromTUs) { if (fromTUs.isEmpty()) { return; } getCurrentTarget().apply(new HUConsolidationTarget.CaseConsumer() { @Override public void newLU(final HuPackingInstructionsId luPackingInstructionsId) {consolidate_FromTUs_ToNewLU(fromTUs, luPackingInstructionsId);} @Override public void existingLU(final HuId luId, final HUQRCode luQRCode) {consolidate_FromTUs_ToExistingLU(fromTUs, luId);} }); } private void consolidate_FromTUs_ToNewLU(@NonNull final List<I_M_HU> fromTUs, @NonNull final HuPackingInstructionsId luPackingInstructionsId) { if (fromTUs.isEmpty()) { return; } final I_M_HU firstTU = fromTUs.get(0); final I_M_HU lu = huTransformService.tuToNewLU(firstTU, QtyTU.ONE, luPackingInstructionsId) .getSingleLURecord(); if (fromTUs.size() > 1) { final List<I_M_HU> remainingTUs = fromTUs.subList(1, fromTUs.size()); huTransformService.tusToExistingLU(remainingTUs, lu); } final HuId luId = HuId.ofRepoId(lu.getM_HU_ID()); final HUQRCode qrCode = huQRCodesService.getQRCodeByHuId(luId); setCurrentTarget(HUConsolidationTarget.ofExistingLU(luId, qrCode)); } private void consolidate_FromTUs_ToExistingLU(@NonNull final List<I_M_HU> fromTUs, @NonNull final HuId luId) { huTransformService.tusToExistingLUId(fromTUs, luId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\commands\consolidate\ConsolidateCommand.java
1
请在Spring Boot框架中完成以下Java代码
public ImmutableList<ApiAuditConfig> getActiveConfigsByOrgId(@NonNull final OrgId orgId) { return getMap().getActiveConfigsByOrgId(orgId); } public ImmutableList<ApiAuditConfig> getAllConfigsByOrgId(@NonNull final OrgId orgId) { return queryBL.createQueryBuilder(I_API_Audit_Config.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_API_Audit_Config.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY) .create() .list() .stream() .map(ApiAuditConfigRepository::fromRecord) .collect(ImmutableList.toImmutableList()); } @NonNull public ApiAuditConfig getConfigById(@NonNull final ApiAuditConfigId id) { return getMap().getConfigById(id); } private ApiAuditConfigsMap getMap() { return cache.getOrLoad(0, this::retrieveMap); } private ApiAuditConfigsMap retrieveMap() { return ApiAuditConfigsMap.ofList( queryBL.createQueryBuilder(I_API_Audit_Config.class) .create() .stream() .map(ApiAuditConfigRepository::fromRecord) .collect(ImmutableList.toImmutableList())); }
@NonNull private static ApiAuditConfig fromRecord(@NonNull final I_API_Audit_Config record) { return ApiAuditConfig.builder() .apiAuditConfigId(ApiAuditConfigId.ofRepoId(record.getAPI_Audit_Config_ID())) .active(record.isActive()) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .seqNo(record.getSeqNo()) .isBypassAudit(record.isBypassAudit()) .forceProcessedAsync(record.isForceProcessedAsync()) .keepRequestDays(record.getKeepRequestDays()) .keepRequestBodyDays(record.getKeepRequestBodyDays()) .keepResponseDays(record.getKeepResponseDays()) .keepResponseBodyDays(record.getKeepResponseBodyDays()) .keepErroredRequestDays(record.getKeepErroredRequestDays()) .method(HttpMethod.ofNullableCode(record.getMethod())) .pathPrefix(record.getPathPrefix()) .notifyUserInCharge(NotificationTriggerType.ofNullableCode(record.getNotifyUserInCharge())) .userGroupInChargeId(UserGroupId.ofRepoIdOrNull(record.getAD_UserGroup_InCharge_ID())) .performAuditAsync(!record.isSynchronousAuditLoggingEnabled()) .wrapApiResponse(record.isWrapApiResponse()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\config\ApiAuditConfigRepository.java
2
请完成以下Java代码
public boolean isNot() { return not; } public void setNot(boolean not) { this.not = not; } public boolean isNotAlphabetic() { return notAlphabetic; } public void setNotAlphabetic(boolean notAlphabetic) { this.notAlphabetic = notAlphabetic; } @Override public String toString() { return "SpelRelational{" + "equal=" + equal +
", equalAlphabetic=" + equalAlphabetic + ", notEqual=" + notEqual + ", notEqualAlphabetic=" + notEqualAlphabetic + ", lessThan=" + lessThan + ", lessThanAlphabetic=" + lessThanAlphabetic + ", lessThanOrEqual=" + lessThanOrEqual + ", lessThanOrEqualAlphabetic=" + lessThanOrEqualAlphabetic + ", greaterThan=" + greaterThan + ", greaterThanAlphabetic=" + greaterThanAlphabetic + ", greaterThanOrEqual=" + greaterThanOrEqual + ", greaterThanOrEqualAlphabetic=" + greaterThanOrEqualAlphabetic + ", and=" + and + ", andAlphabetic=" + andAlphabetic + ", or=" + or + ", orAlphabetic=" + orAlphabetic + ", not=" + not + ", notAlphabetic=" + notAlphabetic + '}'; } }
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRelational.java
1
请完成以下Java代码
public UserQuery createUserQuery() { return getIdmIdentityService().createUserQuery(); } @Override public NativeUserQuery createNativeUserQuery() { return getIdmIdentityService().createNativeUserQuery(); } @Override public GroupQuery createGroupQuery() { return getIdmIdentityService().createGroupQuery(); } @Override public NativeGroupQuery createNativeGroupQuery() { return getIdmIdentityService().createNativeGroupQuery(); } @Override public void createMembership(String userId, String groupId) { getIdmIdentityService().createMembership(userId, groupId); } @Override public void deleteGroup(String groupId) { getIdmIdentityService().deleteGroup(groupId); } @Override public void deleteMembership(String userId, String groupId) { getIdmIdentityService().deleteMembership(userId, groupId); } @Override public boolean checkPassword(String userId, String password) { return getIdmIdentityService().checkPassword(userId, password); } @Override public void deleteUser(String userId) {
getIdmIdentityService().deleteUser(userId); } @Override public void setUserPicture(String userId, Picture picture) { getIdmIdentityService().setUserPicture(userId, picture); } public Picture getUserPicture(String userId) { return getIdmIdentityService().getUserPicture(userId); } @Override public void setAuthenticatedUserId(String authenticatedUserId) { Authentication.setAuthenticatedUserId(authenticatedUserId); } @Override public String getUserInfo(String userId, String key) { return getIdmIdentityService().getUserInfo(userId, key); } @Override public List<String> getUserInfoKeys(String userId) { return getIdmIdentityService().getUserInfoKeys(userId); } @Override public void setUserInfo(String userId, String key, String value) { getIdmIdentityService().setUserInfo(userId, key, value); } @Override public void deleteUserInfo(String userId, String key) { getIdmIdentityService().deleteUserInfo(userId, key); } protected IdmIdentityService getIdmIdentityService() { return CommandContextUtil.getIdmIdentityService(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\IdentityServiceImpl.java
1
请完成以下Java代码
public int getFrequency () { Integer ii = (Integer)get_Value(COLUMNNAME_Frequency); if (ii == null) return 0; return ii.intValue(); } /** FrequencyType AD_Reference_ID=221 */ public static final int FREQUENCYTYPE_AD_Reference_ID=221; /** Minute = M */ public static final String FREQUENCYTYPE_Minute = "M"; /** Hour = H */ public static final String FREQUENCYTYPE_Hour = "H"; /** Day = D */ public static final String FREQUENCYTYPE_Day = "D"; /** Set Frequency Type. @param FrequencyType Frequency of event */ public void setFrequencyType (String FrequencyType) { set_Value (COLUMNNAME_FrequencyType, FrequencyType); } /** Get Frequency Type. @return Frequency of event */ public String getFrequencyType () { return (String)get_Value(COLUMNNAME_FrequencyType); } /** Set Days to keep Log. @param KeepLogDays Number of days to keep the log entries */ public void setKeepLogDays (int KeepLogDays) { set_Value (COLUMNNAME_KeepLogDays, Integer.valueOf(KeepLogDays)); } /** Get Days to keep Log. @return Number of days to keep the log entries */ public int getKeepLogDays () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays); 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 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; } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertProcessor.java
1
请完成以下Java代码
private boolean qtyToDeliverCatchOverrideIsChanged() { final Optional<Boolean> nullValuechanged = isNullValuesChanged(qtyToDeliverCatchOverrideInitial, qtyToDeliverCatchOverride); return nullValuechanged.orElseGet(() -> qtyToDeliverCatchOverrideInitial.compareTo(qtyToDeliverCatchOverride) != 0); } private static Optional<Boolean> isNullValuesChanged( @Nullable final Object initial, @Nullable final Object current) { final boolean wasNull = initial == null; final boolean isNull = current == null; if (wasNull) {
if (isNull) { return Optional.of(false); } return Optional.of(true); // was null and is not null anymore } if (isNull) { return Optional.of(true); // was not null and is now } return Optional.empty(); // was not null and still is not null; will need to compare the current values } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRow.java
1
请完成以下Java代码
public final IQualityInspectionLineBuilder setPercentage(final BigDecimal percentage) { _percentage = percentage; return this; } private BigDecimal getPercentage() { return _percentage; } @Override public final IQualityInspectionLineBuilder setName(final String name) { _name = name; return this; } protected final String getName() { return _name; } private IHandlingUnitsInfo getHandlingUnitsInfoToSet() { if (_handlingUnitsInfoSet) { return _handlingUnitsInfo; } return null; }
@Override public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfo = handlingUnitsInfo; _handlingUnitsInfoSet = true; return this; } private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet() { if (_handlingUnitsInfoProjectedSet) { return _handlingUnitsInfoProjected; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfoProjected = handlingUnitsInfo; _handlingUnitsInfoProjectedSet = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java
1
请完成以下Java代码
public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact. @return Accounting Fact */ public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Level no. @param LevelNo Level no */ public void setLevelNo (int LevelNo) { set_ValueNoCheck (COLUMNNAME_LevelNo, Integer.valueOf(LevelNo)); } /** Get Level no. @return Level no */ public int getLevelNo () { Integer ii = (Integer)get_Value(COLUMNNAME_LevelNo); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_ValueNoCheck (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 Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_ReportStatement.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age;
} public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + ", email=" + email + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootReferenceNaturalId\src\main\java\com\bookstore\entity\Author.java
1
请在Spring Boot框架中完成以下Java代码
public class DubboAutoConfiguration implements ApplicationContextAware, BeanDefinitionRegistryPostProcessor { /** * Creates {@link ServiceClassPostProcessor} Bean * * @param packagesToScan the packages to scan * @return {@link ServiceClassPostProcessor} */ @ConditionalOnProperty(prefix = DUBBO_SCAN_PREFIX, name = BASE_PACKAGES_PROPERTY_NAME) @ConditionalOnBean(name = BASE_PACKAGES_BEAN_NAME) @Bean public ServiceClassPostProcessor serviceClassPostProcessor(@Qualifier(BASE_PACKAGES_BEAN_NAME) Set<String> packagesToScan) { return new ServiceClassPostProcessor(packagesToScan); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (applicationContext instanceof ConfigurableApplicationContext) { ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext; DubboLifecycleComponentApplicationListener dubboLifecycleComponentApplicationListener = new DubboLifecycleComponentApplicationListener(applicationContext); context.addApplicationListener(dubboLifecycleComponentApplicationListener); DubboBootstrapApplicationListener dubboBootstrapApplicationListener = new DubboBootstrapApplicationListener(applicationContext); context.addApplicationListener(dubboBootstrapApplicationListener); } } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { // Remove the BeanDefinitions of ApplicationListener from DubboBeanUtils#registerCommonBeans(BeanDefinitionRegistry) // TODO Refactoring in Dubbo 2.7.9
removeBeanDefinition(registry, DubboLifecycleComponentApplicationListener.BEAN_NAME); removeBeanDefinition(registry, DubboBootstrapApplicationListener.BEAN_NAME); } private void removeBeanDefinition(BeanDefinitionRegistry registry, String beanName) { if (registry.containsBeanDefinition(beanName)) { registry.removeBeanDefinition(beanName); } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // DO NOTHING } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboAutoConfiguration.java
2
请完成以下Java代码
public class PrintStack { public static void givenStack_whenUsingToString_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); System.out.print(stack.toString()); } public static void givenStack_whenUsingForEach_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); List<Integer> result = new ArrayList<>(); for (Integer value : stack) { System.out.print(value + " "); } } public static void givenStack_whenUsingDirectForEach_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); stack.forEach(element -> System.out.println(element)); } public static void givenStack_whenUsingStreamReverse_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(20); stack.push(10); stack.push(30); Collections.reverse(stack); stack.forEach(System.out::println); } public static void givenStack_whenUsingIterator_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30);
Iterator<Integer> iterator = stack.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } } public static void givenStack_whenUsingListIteratorReverseOrder_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); ListIterator<Integer> iterator = stack.listIterator(stack.size()); while (iterator.hasPrevious()) { System.out.print(iterator.previous() + " "); } } public static void givenStack_whenUsingDeque_thenPrintStack() { Deque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); stack.forEach(e -> System.out.print(e + " ")); } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\PrintStack.java
1
请在Spring Boot框架中完成以下Java代码
public static class V1 { /** * ID of the custom device that is exporting metrics to Dynatrace. */ private @Nullable String deviceId; /** * Group for exported metrics. Used to specify custom device group name in the * Dynatrace UI. */ private @Nullable String group; /** * Technology type for exported metrics. Used to group metrics under a logical * technology name in the Dynatrace UI. */ private String technologyType = "java"; public @Nullable String getDeviceId() { return this.deviceId; } public void setDeviceId(@Nullable String deviceId) { this.deviceId = deviceId; } public @Nullable String getGroup() { return this.group; } public void setGroup(@Nullable String group) { this.group = group; } public String getTechnologyType() { return this.technologyType; } public void setTechnologyType(String technologyType) { this.technologyType = technologyType; } } public static class V2 { /** * Default dimensions that are added to all metrics in the form of key-value * pairs. These are overwritten by Micrometer tags if they use the same key. */ private @Nullable Map<String, String> defaultDimensions; /** * Whether to enable Dynatrace metadata export. */ private boolean enrichWithDynatraceMetadata = true; /** * Prefix string that is added to all exported metrics. */ private @Nullable String metricKeyPrefix;
/** * Whether to fall back to the built-in micrometer instruments for Timer and * DistributionSummary. */ private boolean useDynatraceSummaryInstruments = true; /** * Whether to export meter metadata (unit and description) to the Dynatrace * backend. */ private boolean exportMeterMetadata = true; public @Nullable Map<String, String> getDefaultDimensions() { return this.defaultDimensions; } public void setDefaultDimensions(@Nullable Map<String, String> defaultDimensions) { this.defaultDimensions = defaultDimensions; } public boolean isEnrichWithDynatraceMetadata() { return this.enrichWithDynatraceMetadata; } public void setEnrichWithDynatraceMetadata(Boolean enrichWithDynatraceMetadata) { this.enrichWithDynatraceMetadata = enrichWithDynatraceMetadata; } public @Nullable String getMetricKeyPrefix() { return this.metricKeyPrefix; } public void setMetricKeyPrefix(@Nullable String metricKeyPrefix) { this.metricKeyPrefix = metricKeyPrefix; } public boolean isUseDynatraceSummaryInstruments() { return this.useDynatraceSummaryInstruments; } public void setUseDynatraceSummaryInstruments(boolean useDynatraceSummaryInstruments) { this.useDynatraceSummaryInstruments = useDynatraceSummaryInstruments; } public boolean isExportMeterMetadata() { return this.exportMeterMetadata; } public void setExportMeterMetadata(boolean exportMeterMetadata) { this.exportMeterMetadata = exportMeterMetadata; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatraceProperties.java
2
请完成以下Java代码
public java.lang.String getProxyPassword () { return (java.lang.String)get_Value(COLUMNNAME_ProxyPassword); } /** Set Proxy port. @param ProxyPort Port of your proxy server */ @Override public void setProxyPort (int ProxyPort) { set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort)); } /** Get Proxy port. @return Port of your proxy server */ @Override public int getProxyPort () { Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort); if (ii == null) return 0; return ii.intValue(); } /** Set Require CreditCard Verification Code. @param RequireVV Require 3/4 digit Credit Verification Code */ @Override public void setRequireVV (boolean RequireVV) { set_Value (COLUMNNAME_RequireVV, Boolean.valueOf(RequireVV)); } /** Get Require CreditCard Verification Code. @return Require 3/4 digit Credit Verification Code */ @Override public boolean isRequireVV () { Object oo = get_Value(COLUMNNAME_RequireVV); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set User ID. @param UserID User ID or account number */ @Override public void setUserID (java.lang.String UserID) {
set_Value (COLUMNNAME_UserID, UserID); } /** Get User ID. @return User ID or account number */ @Override public java.lang.String getUserID () { return (java.lang.String)get_Value(COLUMNNAME_UserID); } /** Set Vendor ID. @param VendorID Vendor ID for the Payment Processor */ @Override public void setVendorID (java.lang.String VendorID) { set_Value (COLUMNNAME_VendorID, VendorID); } /** Get Vendor ID. @return Vendor ID for the Payment Processor */ @Override public java.lang.String getVendorID () { return (java.lang.String)get_Value(COLUMNNAME_VendorID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java
1
请完成以下Java代码
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 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); } /** 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; } /** Set Test Export Model. @param TestExportModel Test Export Model */ public void setTestExportModel (String TestExportModel) { set_Value (COLUMNNAME_TestExportModel, TestExportModel); } /** Get Test Export Model. @return Test Export Model */ public String getTestExportModel () { return (String)get_Value(COLUMNNAME_TestExportModel); } /** Set Test Import Model. @param TestImportModel Test Import Model */ public void setTestImportModel (String TestImportModel) { set_Value (COLUMNNAME_TestImportModel, TestImportModel); } /** Get Test Import Model. @return Test Import Model */ public String getTestImportModel () { return (String)get_Value(COLUMNNAME_TestImportModel); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); }
/** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Set Version. @param Version Version of the table definition */ public void setVersion (String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ public String getVersion () { return (String)get_Value(COLUMNNAME_Version); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Format.java
1
请完成以下Java代码
public void setModeratorStatus (java.lang.String ModeratorStatus) { set_Value (COLUMNNAME_ModeratorStatus, ModeratorStatus); } /** Get Moderation Status. @return Status of Moderation */ @Override public java.lang.String getModeratorStatus () { return (java.lang.String)get_Value(COLUMNNAME_ModeratorStatus); } /** Set Betreff. @param Subject Mail Betreff
*/ @Override public void setSubject (java.lang.String Subject) { set_Value (COLUMNNAME_Subject, Subject); } /** Get Betreff. @return Mail Betreff */ @Override public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatEntry.java
1
请完成以下Java代码
public class ContainerPausingBackOffHandler implements BackOffHandler { private final DefaultBackOffHandler defaultBackOffHandler = new DefaultBackOffHandler(); private final ListenerContainerPauseService pauser; /** * Create an instance with the provided {@link ListenerContainerPauseService}. * @param pauser the pause service. */ public ContainerPausingBackOffHandler(ListenerContainerPauseService pauser) { this.pauser = pauser; } @Override
public void onNextBackOff(@Nullable MessageListenerContainer container, @Nullable Exception exception, long nextBackOff) { if (container == null) { this.defaultBackOffHandler.onNextBackOff(container, exception, nextBackOff); // NOSONAR } else { this.pauser.pause(container, Duration.ofMillis(nextBackOff)); } } @Override public void onNextBackOff(MessageListenerContainer container, TopicPartition partition, long nextBackOff) { this.pauser.pausePartition(container, partition, Duration.ofMillis(nextBackOff)); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerPausingBackOffHandler.java
1
请完成以下Java代码
public class UserDetail { private String uid; private String login; private String password; private List<String> roles = new ArrayList<>(); //... UserDetail(String uid, String login, String password) { this.uid = uid; this.login = login; this.password = password; } public String getUid() { return uid; }
public String getLogin() { return login; } public String getPassword() { return password; } public List<String> getRoles() { return roles; } public void addRole(String role) { roles.add(role); } }
repos\tutorials-master\security-modules\java-ee-8-security-api\app-auth-custom-no-store\src\main\java\com\baeldung\javaee\security\UserDetail.java
1
请完成以下Java代码
public List<HistoricIdentityLink> execute(CommandContext commandContext) { if (taskId != null) { return getLinksForTask(commandContext); } else { return getLinksForProcessInstance(commandContext); } } @SuppressWarnings({ "unchecked", "rawtypes" }) protected List<HistoricIdentityLink> getLinksForTask(CommandContext commandContext) { HistoricTaskInstanceEntity task = commandContext.getHistoricTaskInstanceEntityManager().findById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException( "No historic task exists with the given id: " + taskId, HistoricTaskInstance.class ); } List<HistoricIdentityLink> identityLinks = (List) commandContext .getHistoricIdentityLinkEntityManager() .findHistoricIdentityLinksByTaskId(taskId); // Similar to GetIdentityLinksForTask, return assignee and owner as // identity link if (task.getAssignee() != null) { HistoricIdentityLinkEntity identityLink = commandContext.getHistoricIdentityLinkEntityManager().create(); identityLink.setUserId(task.getAssignee());
identityLink.setTaskId(task.getId()); identityLink.setType(IdentityLinkType.ASSIGNEE); identityLinks.add(identityLink); } if (task.getOwner() != null) { HistoricIdentityLinkEntity identityLink = commandContext.getHistoricIdentityLinkEntityManager().create(); identityLink.setTaskId(task.getId()); identityLink.setUserId(task.getOwner()); identityLink.setType(IdentityLinkType.OWNER); identityLinks.add(identityLink); } return identityLinks; } @SuppressWarnings({ "unchecked", "rawtypes" }) protected List<HistoricIdentityLink> getLinksForProcessInstance(CommandContext commandContext) { return (List) commandContext .getHistoricIdentityLinkEntityManager() .findHistoricIdentityLinksByProcessInstanceId(processInstanceId); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetHistoricIdentityLinksForTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
public String getCountryCode() { return countryCode; } public void setCountryCode(String countryCode) { this.countryCode = countryCode; } public Phone number(String number) { this.number = number; return this; } /** * The seller&#39;s primary phone number associated with the return address. When this number is provided in a contestPaymentDispute or contestPaymentDispute method, it is provided as one continuous numeric string, including the area code. So, if the phone number&#39;s area code was &#39;408&#39;, a number in this field may look something like this: &amp;quot;number&amp;quot; : * &amp;quot;4088084356&amp;quot; If the buyer is located in a different country than the seller, the seller&#39;s country calling code will need to be specified in the countryCode field. * * @return number **/ @javax.annotation.Nullable @ApiModelProperty(value = "The seller's primary phone number associated with the return address. When this number is provided in a contestPaymentDispute or contestPaymentDispute method, it is provided as one continuous numeric string, including the area code. So, if the phone number's area code was '408', a number in this field may look something like this: &quot;number&quot; : &quot;4088084356&quot; If the buyer is located in a different country than the seller, the seller's country calling code will need to be specified in the countryCode field.") public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Phone phone = (Phone)o; return Objects.equals(this.countryCode, phone.countryCode) && Objects.equals(this.number, phone.number);
} @Override public int hashCode() { return Objects.hash(countryCode, number); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Phone {\n"); sb.append(" countryCode: ").append(toIndentedString(countryCode)).append("\n"); sb.append(" number: ").append(toIndentedString(number)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Phone.java
2
请完成以下Java代码
public void setC_Print_Job_ID (int C_Print_Job_ID) { if (C_Print_Job_ID < 1) set_Value (COLUMNNAME_C_Print_Job_ID, null); else set_Value (COLUMNNAME_C_Print_Job_ID, Integer.valueOf(C_Print_Job_ID)); } @Override public int getC_Print_Job_ID() { return get_ValueAsInt(COLUMNNAME_C_Print_Job_ID); } @Override public void setc_print_job_name (java.lang.String c_print_job_name) { set_Value (COLUMNNAME_c_print_job_name, c_print_job_name); } @Override public java.lang.String getc_print_job_name() { return (java.lang.String)get_Value(COLUMNNAME_c_print_job_name); } @Override public void setdocument (java.lang.String document) { set_Value (COLUMNNAME_document, document); } @Override public java.lang.String getdocument() { return (java.lang.String)get_Value(COLUMNNAME_document); } @Override public void setDocumentNo (java.lang.String DocumentNo) { set_Value (COLUMNNAME_DocumentNo, DocumentNo); } @Override public java.lang.String getDocumentNo() { return (java.lang.String)get_Value(COLUMNNAME_DocumentNo); } @Override public void setFirstname (java.lang.String Firstname) { set_Value (COLUMNNAME_Firstname, Firstname); } @Override public java.lang.String getFirstname() { return (java.lang.String)get_Value(COLUMNNAME_Firstname); } @Override
public void setGrandTotal (java.math.BigDecimal GrandTotal) { set_Value (COLUMNNAME_GrandTotal, GrandTotal); } @Override public java.math.BigDecimal getGrandTotal() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_GrandTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setLastname (java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); } @Override public java.lang.String getLastname() { return (java.lang.String)get_Value(COLUMNNAME_Lastname); } @Override public void setprintjob (java.lang.String printjob) { set_Value (COLUMNNAME_printjob, printjob); } @Override public java.lang.String getprintjob() { return (java.lang.String)get_Value(COLUMNNAME_printjob); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_RV_Printing_Bericht_List_Per_Print_Job.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<AdWindowId> getNewBPartnerLocationWindowId() { return RecordWindowFinder.newInstance(I_C_BPartner_Location_QuickInput.Table_Name, customizedWindowInfoMapRepository) .ignoreExcludeFromZoomTargetsFlag() .findAdWindowId(); } @Nullable public BPartnerLocationId createBPartnerLocationFromTemplate(@NonNull final I_C_BPartner_Location_QuickInput template, @NonNull final BPartnerId bpartnerId) { final BPartnerLocation locationFromBPartnerLocationTemplate = getLocationFromBPartnerLocationTemplate(template); if (locationFromBPartnerLocationTemplate == null) { return null; } final BPartnerComposite bpartner = bpartnerCompositeRepository.getById(bpartnerId); bpartner.getLocations().add(locationFromBPartnerLocationTemplate); bpartnerCompositeRepository.save(bpartner, true); return Objects.requireNonNull(locationFromBPartnerLocationTemplate.getId()); } @Nullable private BPartnerLocation getLocationFromBPartnerLocationTemplate(final I_C_BPartner_Location_QuickInput template) { final LocationId uniqueLocationIdOfBPartnerTemplate = LocationId.ofRepoIdOrNull(template.getC_Location_ID()); if (uniqueLocationIdOfBPartnerTemplate == null) { return null;
} return BPartnerLocation.builder() .locationType(BPartnerLocationType.builder() .billTo(template.isBillTo()) .billToDefault(template.isBillToDefault()) .shipTo(template.isShipTo()) .shipToDefault(template.isShipToDefault()) .build()) .bpartnerName(template.getBPartnerName()) .ephemeral(template.isOneTime()) .existingLocationId(uniqueLocationIdOfBPartnerTemplate) .name(template.getName()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\quick_input\service\BPartnerLocationQuickInputService.java
2
请完成以下Java代码
private List<I_M_Shipment_Declaration_Line> retrieveLineRecords(@NonNull final ShipmentDeclarationId shipmentDeclarationId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_M_Shipment_Declaration_Line.class) .addEqualsFilter(I_M_Shipment_Declaration_Line.COLUMN_M_Shipment_Declaration_ID, shipmentDeclarationId) .create() .list(); } private void saveLine( @NonNull final ShipmentDeclarationLine line, @NonNull final ShipmentDeclarationId shipmentDeclarationId, final I_M_Shipment_Declaration_Line existingRecord) { final I_M_Shipment_Declaration_Line record; if (existingRecord == null) { record = newInstance(I_M_Shipment_Declaration_Line.class); } else { record = existingRecord; } record.setM_Shipment_Declaration_ID(shipmentDeclarationId.getRepoId()); record.setLineNo(line.getLineNo()); final InOutLineId shipmentLineId = line.getShipmentLineId(); record.setM_InOutLine_ID(shipmentLineId.getRepoId()); final OrgId orgId = line.getOrgId(); record.setAD_Org_ID(orgId.getRepoId());
final Quantity quantity = line.getQuantity(); record.setQty(quantity.toBigDecimal()); record.setC_UOM_ID(quantity.getUOMId()); final ProductId productId = line.getProductId(); record.setM_Product_ID(productId.getRepoId()); record.setPackageSize(line.getPackageSize()); saveRecord(record); line.setId(ShipmentDeclarationLineId.ofRepoId(record.getM_Shipment_Declaration_ID(), record.getM_Shipment_Declaration_Line_ID())); } public boolean existCompletedShipmentDeclarationsForShipmentId(final InOutId shipmentId) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_Shipment_Declaration.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addEqualsFilter(I_M_Shipment_Declaration.COLUMN_M_InOut_ID, shipmentId) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\repo\ShipmentDeclarationRepository.java
1
请完成以下Java代码
private static WebClient getWebClient() { WebClient.Builder webClientBuilder = WebClient.builder(); return webClientBuilder.build(); } public static InputStream getResponseAsInputStream(WebClient client, String url) throws IOException, InterruptedException { PipedOutputStream pipedOutputStream = new PipedOutputStream(); PipedInputStream pipedInputStream = new PipedInputStream(1024 * 10); pipedInputStream.connect(pipedOutputStream); Flux<DataBuffer> body = client.get() .uri(url) .exchangeToFlux(clientResponse -> { return clientResponse.body(BodyExtractors.toDataBuffers()); }) .doOnError(error -> { logger.error("error occurred while reading body", error); }) .doFinally(s -> { try { pipedOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } }) .doOnCancel(() -> { logger.error("Get request is cancelled"); }); DataBufferUtils.write(body, pipedOutputStream) .log("Writing to output buffer") .subscribe(); return pipedInputStream; } private static String readContentFromPipedInputStream(PipedInputStream stream) throws IOException { StringBuffer contentStringBuffer = new StringBuffer(); try { Thread pipeReader = new Thread(() -> { try { contentStringBuffer.append(readContent(stream)); } catch (IOException e) { throw new RuntimeException(e); } }); pipeReader.start(); pipeReader.join(); } catch (InterruptedException e) {
throw new RuntimeException(e); } finally { stream.close(); } return String.valueOf(contentStringBuffer); } private static String readContent(InputStream stream) throws IOException { StringBuffer contentStringBuffer = new StringBuffer(); byte[] tmp = new byte[stream.available()]; int byteCount = stream.read(tmp, 0, tmp.length); logger.info(String.format("read %d bytes from the stream\n", byteCount)); contentStringBuffer.append(new String(tmp)); return String.valueOf(contentStringBuffer); } public static void main(String[] args) throws IOException, InterruptedException { WebClient webClient = getWebClient(); InputStream inputStream = getResponseAsInputStream(webClient, REQUEST_ENDPOINT); Thread.sleep(3000); String content = readContentFromPipedInputStream((PipedInputStream) inputStream); logger.info("response content: \n{}", content.replace("}", "}\n")); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-3\src\main\java\com\baeldung\databuffer\DataBufferToInputStream.java
1
请在Spring Boot框架中完成以下Java代码
public void setQuotation_Order_ID (final int Quotation_Order_ID) { if (Quotation_Order_ID < 1) set_Value (COLUMNNAME_Quotation_Order_ID, null); else set_Value (COLUMNNAME_Quotation_Order_ID, Quotation_Order_ID); } @Override public int getQuotation_Order_ID() { return get_ValueAsInt(COLUMNNAME_Quotation_Order_ID); } @Override public org.compiere.model.I_C_OrderLine getQuotation_OrderLine() { return get_ValueAsPO(COLUMNNAME_Quotation_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setQuotation_OrderLine(final org.compiere.model.I_C_OrderLine Quotation_OrderLine) { set_ValueFromPO(COLUMNNAME_Quotation_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, Quotation_OrderLine); } @Override public void setQuotation_OrderLine_ID (final int Quotation_OrderLine_ID) { if (Quotation_OrderLine_ID < 1) set_Value (COLUMNNAME_Quotation_OrderLine_ID, null); else set_Value (COLUMNNAME_Quotation_OrderLine_ID, Quotation_OrderLine_ID); } @Override public int getQuotation_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_Quotation_OrderLine_ID); } /** * Type AD_Reference_ID=541251 * Reference name: C_Project_Repair_CostCollector_Type */ public static final int TYPE_AD_Reference_ID=541251; /** SparePartsToBeInvoiced = SP+ */ public static final String TYPE_SparePartsToBeInvoiced = "SP+"; /** SparePartsOwnedByCustomer = SPC */ public static final String TYPE_SparePartsOwnedByCustomer = "SPC"; /** RepairProductToReturn = RPC */
public static final String TYPE_RepairProductToReturn = "RPC"; /** RepairingConsumption = RP+ */ public static final String TYPE_RepairingConsumption = "RP+"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_ValueNoCheck (COLUMNNAME_VHU_ID, null); else set_ValueNoCheck (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_CostCollector.java
2
请完成以下Java代码
public class Movie { private String id; private String title; private String plot; public String getPlot() { return plot; } public void setPlot(String plot) { this.plot = plot; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() {
return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Movie{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", plot='" + plot + '\'' + '}'; } }
repos\spring-data-examples-main\mongodb\fragment-spi\sample\src\main\java\com\example\data\mongodb\Movie.java
1
请完成以下Java代码
public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Start No. @param StartNo Starting number/position */ public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ public int getStartNo () {
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java
1
请完成以下Java代码
public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public HttpHeaders getHttpHeaders() { return httpHeaders; } public String getHttpHeadersAsString() { return httpHeaders != null ? httpHeaders.formatAsString() : null; }
public void setHttpHeaders(HttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public byte[] getBodyBytes() { return bodyBytes; } public void setBodyBytes(byte[] bodyBytes) { this.bodyBytes = bodyBytes; } public boolean isBodyResponseHandled() { return bodyResponseHandled; } public void setBodyResponseHandled(boolean bodyResponseHandled) { this.bodyResponseHandled = bodyResponseHandled; } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpResponse.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> queryPageList(OpenApiAuth openApiAuth, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) { QueryWrapper<OpenApiAuth> queryWrapper = QueryGenerator.initQueryWrapper(openApiAuth, req.getParameterMap()); Page<OpenApiAuth> page = new Page<>(pageNo, pageSize); IPage<OpenApiAuth> pageList = service.page(page, queryWrapper); return Result.ok(pageList); } /** * 添加 * * @param openApiAuth * @return */ @PostMapping(value = "/add") public Result<?> add(@RequestBody OpenApiAuth openApiAuth) { service.save(openApiAuth); return Result.ok("添加成功!"); } /** * 编辑 * * @param openApiAuth * @return */ @PutMapping(value = "/edit") public Result<?> edit(@RequestBody OpenApiAuth openApiAuth) { service.updateById(openApiAuth); return Result.ok("修改成功!"); } /** * 通过id删除 * * @param id * @return */ @DeleteMapping(value = "/delete") public Result<?> delete(@RequestParam(name = "id", required = true) String id) { service.removeById(id); return Result.ok("删除成功!"); } /**
* 批量删除 * * @param ids * @return */ @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.service.removeByIds(Arrays.asList(ids.split(","))); return Result.ok("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { OpenApiAuth openApiAuth = service.getById(id); return Result.ok(openApiAuth); } /** * 生成AKSK * @return */ @GetMapping("genAKSK") public Result<String[]> genAKSK() { return Result.ok(AKSKGenerator.genAKSKPair()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\openapi\controller\OpenApiAuthController.java
2
请在Spring Boot框架中完成以下Java代码
public Session getSession() { return this.session; } public static class Session { /** * Acknowledge mode used when creating sessions. */ private AcknowledgeMode acknowledgeMode = AcknowledgeMode.AUTO; /** * Whether to use transacted sessions. */ private boolean transacted; public AcknowledgeMode getAcknowledgeMode() { return this.acknowledgeMode; } public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) { this.acknowledgeMode = acknowledgeMode; } public boolean isTransacted() { return this.transacted; } public void setTransacted(boolean transacted) { this.transacted = transacted; } } } public enum DeliveryMode { /** * Does not require that the message be logged to stable storage. This is the
* lowest-overhead delivery mode but can lead to lost of message if the broker * goes down. */ NON_PERSISTENT(1), /* * Instructs the JMS provider to log the message to stable storage as part of the * client's send operation. */ PERSISTENT(2); private final int value; DeliveryMode(int value) { this.value = value; } public int getValue() { return this.value; } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsProperties.java
2
请完成以下Java代码
public boolean isSetProcessInitiator() { return StringUtils.isNotEmpty(getProcessInitiatorHeaderName()); } public Map<String, Object> getReturnVarMap() { return returnVarMap; } public void setReturnVarMap(Map<String, Object> returnVarMap) { this.returnVarMap = returnVarMap; } public String getProcessInitiatorHeaderName() { return processInitiatorHeaderName; } public void setProcessInitiatorHeaderName(String processInitiatorHeaderName) {
this.processInitiatorHeaderName = processInitiatorHeaderName; } @Override public boolean isLenientProperties() { return true; } public long getTimeout() { return timeout; } public int getTimeResolution() { return timeResolution; } }
repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\FlowableEndpoint.java
1
请完成以下Java代码
public class Delivery { private final String consumerTag; private final Envelope envelope; private final String queue; private final AMQP.BasicProperties properties; private final byte[] body; public Delivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body, // NOSONAR String queue) { this.consumerTag = consumerTag; this.envelope = envelope; this.properties = properties; this.body = body; // NOSONAR this.queue = queue; } /** * Retrieve the consumer tag. * @return the consumer tag. */ public String getConsumerTag() { return this.consumerTag; } /** * Retrieve the message envelope. * @return the message envelope. */ public Envelope getEnvelope() {
return this.envelope; } /** * Retrieve the message properties. * @return the message properties. */ public BasicProperties getProperties() { return this.properties; } /** * Retrieve the message body. * @return the message body. */ public byte[] getBody() { return this.body; // NOSONAR } /** * Retrieve the queue. * @return the queue. */ public String getQueue() { return this.queue; } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\Delivery.java
1
请完成以下Java代码
public final class NullInfoWindowGridRowBuilders implements IInfoWindowGridRowBuilders { public static final NullInfoWindowGridRowBuilders instance = new NullInfoWindowGridRowBuilders(); private NullInfoWindowGridRowBuilders() { super(); } /** * @return {@link NullGridTabRowBuilder} always */ @Override public IGridTabRowBuilder getGridTabRowBuilder(int recordId) { return NullGridTabRowBuilder.instance; } /** * @return empty set
*/ @Override public Set<Integer> getRecordIds() { return Collections.emptySet(); } /** * @throws UnsupportedOperationException */ @Override public void addGridTabRowBuilder(int recordId, IGridTabRowBuilder builder) { throw new UnsupportedOperationException("Not supported"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\NullInfoWindowGridRowBuilders.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Object getPersistentState() { return ResourceEntityImpl.class; }
public void setGenerated(boolean generated) { this.generated = generated; } /** * Indicated whether or not the resource has been generated while deploying rather than being actual part of the deployment. */ public boolean isGenerated() { return generated; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "ResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ResourceEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Resource getConfig() { return this.config; } public void setConfig(@Nullable Resource config) { this.config = config; } } /** * JCache (JSR-107) specific cache properties. */ public static class JCache { /** * The location of the configuration file to use to initialize the cache manager. * The configuration file is dependent of the underlying cache implementation. */ private @Nullable Resource config; /** * Fully qualified name of the CachingProvider implementation to use to retrieve * the JSR-107 compliant cache manager. Needed only if more than one JSR-107 * implementation is available on the classpath. */ private @Nullable String provider; public @Nullable String getProvider() { return this.provider; } public void setProvider(@Nullable String provider) { this.provider = provider; } public @Nullable Resource getConfig() { return this.config; } public void setConfig(@Nullable Resource config) { this.config = config; } } /** * Redis-specific cache properties. */ public static class Redis { /** * Entry expiration. By default the entries never expire. */ private @Nullable Duration timeToLive; /** * Allow caching null values. */ private boolean cacheNullValues = true; /** * Key prefix. */ private @Nullable String keyPrefix;
/** * Whether to use the key prefix when writing to Redis. */ private boolean useKeyPrefix = true; /** * Whether to enable cache statistics. */ private boolean enableStatistics; public @Nullable Duration getTimeToLive() { return this.timeToLive; } public void setTimeToLive(@Nullable Duration timeToLive) { this.timeToLive = timeToLive; } public boolean isCacheNullValues() { return this.cacheNullValues; } public void setCacheNullValues(boolean cacheNullValues) { this.cacheNullValues = cacheNullValues; } public @Nullable String getKeyPrefix() { return this.keyPrefix; } public void setKeyPrefix(@Nullable String keyPrefix) { this.keyPrefix = keyPrefix; } public boolean isUseKeyPrefix() { return this.useKeyPrefix; } public void setUseKeyPrefix(boolean useKeyPrefix) { this.useKeyPrefix = useKeyPrefix; } public boolean isEnableStatistics() { return this.enableStatistics; } public void setEnableStatistics(boolean enableStatistics) { this.enableStatistics = enableStatistics; } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\CacheProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } /** * An auto-configured {@link AnnotationRepositoryConfigurationSource}. */ private class AutoConfiguredAnnotationRepositoryConfigurationSource extends AnnotationRepositoryConfigurationSource { AutoConfiguredAnnotationRepositoryConfigurationSource(AnnotationMetadata metadata, Class<? extends Annotation> annotation, ResourceLoader resourceLoader, Environment environment, BeanDefinitionRegistry registry, @Nullable BeanNameGenerator generator) {
super(metadata, annotation, resourceLoader, environment, registry, generator); } @Override public Streamable<String> getBasePackages() { return AbstractRepositoryConfigurationSourceSupport.this.getBasePackages(); } @Override public BootstrapMode getBootstrapMode() { return AbstractRepositoryConfigurationSourceSupport.this.getBootstrapMode(); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\data\AbstractRepositoryConfigurationSourceSupport.java
2
请完成以下Java代码
public void extendLock(String taskId, long newDuration) { ExtendLockRequestDto payload = new ExtendLockRequestDto(workerId, newDuration); String resourcePath = EXTEND_LOCK_RESOURCE_PATH.replace("{id}", taskId); String resourceUrl = getBaseUrl() + resourcePath; engineInteraction.postRequest(resourceUrl, payload, Void.class); } public byte[] getLocalBinaryVariable(String variableName, String executionId) { String resourcePath = getBaseUrl() + GET_BINARY_VARIABLE .replace(ID_PATH_PARAM, executionId) .replace(NAME_PATH_PARAM, variableName); return engineInteraction.getRequest(resourcePath); }
public String getBaseUrl() { return urlResolver.getBaseUrl(); } public String getWorkerId() { return workerId; } public void setTypedValues(TypedValues typedValues) { this.typedValues = typedValues; } public boolean isUsePriority() { return usePriority; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClient.java
1
请完成以下Java代码
public ResponseEntity<UserDetails> getUserInfo() { JwtUserDto jwtUser = (JwtUserDto) SecurityUtils.getCurrentUser(); return ResponseEntity.ok(jwtUser); } @ApiOperation("获取验证码") @AnonymousGetMapping(value = "/code") public ResponseEntity<Object> getCode() { // 获取运算的结果 Captcha captcha = captchaConfig.getCaptcha(); String uuid = properties.getCodeKey() + IdUtil.simpleUUID(); //当验证码类型为 arithmetic时且长度 >= 2 时,captcha.text()的结果有几率为浮点型 String captchaValue = captcha.text(); if (captcha.getCharType() - 1 == LoginCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(".")) { captchaValue = captchaValue.split("\\.")[0]; }
// 保存 redisUtils.set(uuid, captchaValue, captchaConfig.getExpiration(), TimeUnit.MINUTES); // 验证码信息 Map<String, Object> imgResult = new HashMap<String, Object>(2) {{ put("img", captcha.toBase64()); put("uuid", uuid); }}; return ResponseEntity.ok(imgResult); } @ApiOperation("退出登录") @AnonymousDeleteMapping(value = "/logout") public ResponseEntity<Object> logout(HttpServletRequest request) { onlineUserService.logout(tokenProvider.getToken(request)); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\rest\AuthController.java
1
请完成以下Java代码
public boolean open(String file) { return true; } public boolean open(InputStream stream) { return true; } public void clear() { } public int size() { return getMaxid_(); } public int ysize() { return y_.size(); } public int getMaxid_() { return maxid_; } public void setMaxid_(int maxid_) { this.maxid_ = maxid_; } public double[] getAlpha_() { return alpha_; } public void setAlpha_(double[] alpha_) { this.alpha_ = alpha_; } public float[] getAlphaFloat_() { return alphaFloat_; } public void setAlphaFloat_(float[] alphaFloat_) { this.alphaFloat_ = alphaFloat_; } public double getCostFactor_() { return costFactor_; } public void setCostFactor_(double costFactor_) { this.costFactor_ = costFactor_; } public int getXsize_() { return xsize_; } public void setXsize_(int xsize_) { this.xsize_ = xsize_; } public int getMax_xsize_() { return max_xsize_; } public void setMax_xsize_(int max_xsize_) { this.max_xsize_ = max_xsize_; } public int getThreadNum_() { return threadNum_; } public void setThreadNum_(int threadNum_) { this.threadNum_ = threadNum_; } public List<String> getUnigramTempls_() { return unigramTempls_; }
public void setUnigramTempls_(List<String> unigramTempls_) { this.unigramTempls_ = unigramTempls_; } public List<String> getBigramTempls_() { return bigramTempls_; } public void setBigramTempls_(List<String> bigramTempls_) { this.bigramTempls_ = bigramTempls_; } public List<String> getY_() { return y_; } public void setY_(List<String> y_) { this.y_ = y_; } public List<List<Path>> getPathList_() { return pathList_; } public void setPathList_(List<List<Path>> pathList_) { this.pathList_ = pathList_; } public List<List<Node>> getNodeList_() { return nodeList_; } public void setNodeList_(List<List<Node>> nodeList_) { this.nodeList_ = nodeList_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
1
请完成以下Java代码
public boolean containsAll(Collection<?> c) { return false; } @Override public boolean addAll(Collection<? extends E> c) { return false; } @Override public boolean addAll(int index, Collection<? extends E> c) { return false; } @Override public boolean removeAll(Collection<?> c) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } @Override public E get(int index) { return null; } @Override public E set(int index, E element) { return null;
} @Override public void add(int index, E element) { } @Override public E remove(int index) { return null; } @Override public int indexOf(Object o) { return 0; } @Override public int lastIndexOf(Object o) { return 0; } @Override public ListIterator<E> listIterator() { return null; } @Override public ListIterator<E> listIterator(int index) { return null; } @Override public List<E> subList(int fromIndex, int toIndex) { return null; } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\customiterators\MyList.java
1
请在Spring Boot框架中完成以下Java代码
public CacheErrorHandler errorHandler() { return new SimpleCacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) { // 处理缓存读取错误 log.error("Cache Get Error: {}",exception.getMessage()); } @Override public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) { // 处理缓存写入错误 log.error("Cache Put Error: {}",exception.getMessage()); } @Override public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) { // 处理缓存删除错误 log.error("Cache Evict Error: {}",exception.getMessage()); } @Override public void handleCacheClearError(RuntimeException exception, Cache cache) { // 处理缓存清除错误 log.error("Cache Clear Error: {}",exception.getMessage()); } }; } /** * Value 序列化 * * @param <T> * @author / */ static class FastJsonRedisSerializer<T> implements RedisSerializer<T> { private final Class<T> clazz; FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; }
@Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } String str = new String(bytes, StandardCharsets.UTF_8); return JSON.parseObject(str, clazz); } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\RedisConfiguration.java
2
请完成以下Java代码
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 Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override 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; } /** Set Ranking. @param Ranking Relative Rank Number */ @Override public void setRanking (int Ranking) { set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking)); } /** Get Ranking. @return Relative Rank Number */ @Override public int getRanking () { Integer ii = (Integer)get_Value(COLUMNNAME_Ranking); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse.java
1
请完成以下Java代码
public String toString() { return loginName; } /** * 重载hashCode,只计算loginName; */ @Override public int hashCode() { return Objects.hashCode(loginName); } /** * 重载equals,只计算loginName; */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; }
if (getClass() != obj.getClass()) { return false; } ShiroUser other = (ShiroUser) obj; if (loginName == null) { if (other.loginName != null) { return false; } } else if (!loginName.equals(other.loginName)) { return false; } return true; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroUser.java
1
请在Spring Boot框架中完成以下Java代码
public class AdIssueId implements RepoIdAware { @JsonCreator public static AdIssueId ofRepoId(final int repoId) { return new AdIssueId(repoId); } public static AdIssueId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static int toRepoId(@Nullable final AdIssueId id) { return id != null ? id.getRepoId() : -1; }
int repoId; private AdIssueId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Issue_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final AdIssueId id1, @Nullable final AdIssueId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\AdIssueId.java
2
请完成以下Java代码
public org.compiere.model.I_M_ForecastLine getM_ForecastLine() { return get_ValueAsPO(COLUMNNAME_M_ForecastLine_ID, org.compiere.model.I_M_ForecastLine.class); } @Override public void setM_ForecastLine(org.compiere.model.I_M_ForecastLine M_ForecastLine) { set_ValueFromPO(COLUMNNAME_M_ForecastLine_ID, org.compiere.model.I_M_ForecastLine.class, M_ForecastLine); } @Override public void setM_ForecastLine_ID (int M_ForecastLine_ID) { if (M_ForecastLine_ID < 1) set_Value (COLUMNNAME_M_ForecastLine_ID, null); else set_Value (COLUMNNAME_M_ForecastLine_ID, Integer.valueOf(M_ForecastLine_ID)); } @Override public int getM_ForecastLine_ID() { return get_ValueAsInt(COLUMNNAME_M_ForecastLine_ID); } @Override public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID)); } @Override public int getM_ShipmentSchedule_ID() {
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } @Override public void setPlannedQty (java.math.BigDecimal PlannedQty) { set_Value (COLUMNNAME_PlannedQty, PlannedQty); } @Override public java.math.BigDecimal getPlannedQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Demand_Detail.java
1
请在Spring Boot框架中完成以下Java代码
public class CostTypeId implements RepoIdAware { @JsonCreator public static CostTypeId ofRepoId(final int repoId) { return new CostTypeId(repoId); } public static CostTypeId ofRepoIdOrNull(final int repoId) { if (repoId <= 0) { return null; } else { return ofRepoId(repoId); } } public static int toRepoId(final CostTypeId id) {
return id != null ? id.getRepoId() : -1; } int repoId; private CostTypeId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_CostType_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(final CostTypeId id1, final CostTypeId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\costing\CostTypeId.java
2
请完成以下Java代码
public String getF_MEMO() { return F_MEMO; } public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_STATUS() { return F_STATUS; } public void setF_STATUS(String f_STATUS) { F_STATUS = f_STATUS; } public String getF_ISAUDIT() { return F_ISAUDIT; } public void setF_ISAUDIT(String f_ISAUDIT) { F_ISAUDIT = f_ISAUDIT; } public String getF_AUDITER() { return F_AUDITER; } public void setF_AUDITER(String f_AUDITER) { F_AUDITER = f_AUDITER; } public String getF_AUDITTIME() {
return F_AUDITTIME; } public void setF_AUDITTIME(String f_AUDITTIME) { F_AUDITTIME = f_AUDITTIME; } public String getF_VERSION() { return F_VERSION; } public void setF_VERSION(String f_VERSION) { F_VERSION = f_VERSION; } public String getF_BUDGETCODE() { return F_BUDGETCODE; } public void setF_BUDGETCODE(String f_BUDGETCODE) { F_BUDGETCODE = f_BUDGETCODE; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollSpecialShare.java
1
请完成以下Java代码
private Mono<CompletedPart> uploadPart(UploadState uploadState, ByteBuffer buffer) { final int partNumber = ++uploadState.partCounter; log.info("[I218] uploadPart: partNumber={}, contentLength={}",partNumber, buffer.capacity()); CompletableFuture<UploadPartResponse> request = s3client.uploadPart(UploadPartRequest.builder() .bucket(uploadState.bucket) .key(uploadState.filekey) .partNumber(partNumber) .uploadId(uploadState.uploadId) .contentLength((long) buffer.capacity()) .build(), AsyncRequestBody.fromPublisher(Mono.just(buffer))); return Mono .fromFuture(request) .map((uploadPartResult) -> { checkResult(uploadPartResult); log.info("[I230] uploadPart complete: part={}, etag={}",partNumber,uploadPartResult.eTag()); return CompletedPart.builder() .eTag(uploadPartResult.eTag()) .partNumber(partNumber) .build(); }); } private Mono<CompleteMultipartUploadResponse> completeUpload(UploadState state) { log.info("[I202] completeUpload: bucket={}, filekey={}, completedParts.size={}", state.bucket, state.filekey, state.completedParts.size()); CompletedMultipartUpload multipartUpload = CompletedMultipartUpload.builder() .parts(state.completedParts.values()) .build(); return Mono.fromFuture(s3client.completeMultipartUpload(CompleteMultipartUploadRequest.builder() .bucket(state.bucket) .uploadId(state.uploadId) .multipartUpload(multipartUpload) .key(state.filekey) .build())); } /**
* check result from an API call. * @param result Result from an API call */ private static void checkResult(SdkResponse result) { if (result.sdkHttpResponse() == null || !result.sdkHttpResponse().isSuccessful()) { throw new UploadFailedException(result); } } /** * Holds upload state during a multipart upload */ static class UploadState { final String bucket; final String filekey; String uploadId; int partCounter; Map<Integer, CompletedPart> completedParts = new HashMap<>(); int buffered = 0; UploadState(String bucket, String filekey) { this.bucket = bucket; this.filekey = filekey; } } }
repos\tutorials-master\aws-modules\aws-reactive\src\main\java\com\baeldung\aws\reactive\s3\UploadResource.java
1
请完成以下Java代码
public UUID getUuid() { return id; } @Override public void setUuid(UUID id) { this.id = id; } @Override public long getCreatedTime() { return createdTime; } public void setCreatedTime(long createdTime) { if (createdTime > 0) { this.createdTime = createdTime; } } protected static UUID getUuid(UUIDBased uuidBased) { if (uuidBased != null) { return uuidBased.getId(); } else { return null; } } protected static UUID getTenantUuid(TenantId tenantId) { if (tenantId != null) { return tenantId.getId(); } else { return EntityId.NULL_UUID; } } protected static <I> I getEntityId(UUID uuid, Function<UUID, I> creator) { return DaoUtil.toEntityId(uuid, creator); } protected static TenantId getTenantId(UUID uuid) { if (uuid != null && !uuid.equals(EntityId.NULL_UUID)) { return TenantId.fromUUID(uuid); } else { return TenantId.SYS_TENANT_ID; }
} protected JsonNode toJson(Object value) { if (value != null) { return JacksonUtil.valueToTree(value); } else { return null; } } protected <T> T fromJson(JsonNode json, Class<T> type) { return JacksonUtil.convertValue(json, type); } protected String listToString(List<?> list) { if (list != null) { return StringUtils.join(list, ','); } else { return ""; } } protected <E> List<E> listFromString(String string, Function<String, E> mappingFunction) { if (string != null) { return Arrays.stream(StringUtils.split(string, ',')) .filter(StringUtils::isNotBlank) .map(mappingFunction).collect(Collectors.toList()); } else { return Collections.emptyList(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\BaseSqlEntity.java
1
请完成以下Java代码
public List<String> getCamundaCandidateStarterUsersList() { String candidateStarterUsers = camundaCandidateStarterUsersAttribute.getValue(this); return StringUtil.splitCommaSeparatedList(candidateStarterUsers); } public void setCamundaCandidateStarterUsersList(List<String> camundaCandidateStarterUsersList) { String candidateStarterUsers = StringUtil.joinCommaSeparatedList(camundaCandidateStarterUsersList); camundaCandidateStarterUsersAttribute.setValue(this, candidateStarterUsers); } public String getCamundaJobPriority() { return camundaJobPriorityAttribute.getValue(this); } public void setCamundaJobPriority(String jobPriority) { camundaJobPriorityAttribute.setValue(this, jobPriority); } @Override public String getCamundaTaskPriority() { return camundaTaskPriorityAttribute.getValue(this); } @Override public void setCamundaTaskPriority(String taskPriority) { camundaTaskPriorityAttribute.setValue(this, taskPriority); } @Override public Integer getCamundaHistoryTimeToLive() { String ttl = getCamundaHistoryTimeToLiveString(); if (ttl != null) { return Integer.parseInt(ttl); } return null; } @Override public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) { var value = historyTimeToLive == null ? null : String.valueOf(historyTimeToLive); setCamundaHistoryTimeToLiveString(value); }
@Override public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLiveAttribute.getValue(this); } @Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { if (historyTimeToLive == null) { camundaHistoryTimeToLiveAttribute.removeAttribute(this); } else { camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive); } } @Override public Boolean isCamundaStartableInTasklist() { return camundaIsStartableInTasklistAttribute.getValue(this); } @Override public void setCamundaIsStartableInTasklist(Boolean isStartableInTasklist) { camundaIsStartableInTasklistAttribute.setValue(this, isStartableInTasklist); } @Override public String getCamundaVersionTag() { return camundaVersionTagAttribute.getValue(this); } @Override public void setCamundaVersionTag(String versionTag) { camundaVersionTagAttribute.setValue(this, versionTag); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ProcessImpl.java
1
请完成以下Java代码
public void notify(DelegateTask delegateTask) { validateParameters(); ScriptingEngines scriptingEngines = CommandContextUtil.getCmmnEngineConfiguration().getScriptingEngines(); String language = Objects.toString(this.language.getValue(delegateTask), null); if (language == null) { throw new FlowableIllegalStateException("'language' evaluated to null for taskListener of type 'script'"); } String script = Objects.toString(this.script.getValue(delegateTask), null); if (script == null) { throw new FlowableIllegalStateException("Script content is null or evaluated to null for taskListener of type 'script'"); } ScriptEngineRequest.Builder request = ScriptEngineRequest.builder() .script(script) .language(language) .scopeContainer(delegateTask) .traceEnhancer(trace -> trace.addTraceTag("type", "taskListener")); Object result = scriptingEngines.evaluate(request.build()).getResult(); if (resultVariable != null) { String resultVariable = Objects.toString(this.resultVariable.getValue(delegateTask), null); if (resultVariable != null) { delegateTask.setVariable(resultVariable, result); } } } protected void validateParameters() {
if (script == null) { throw new IllegalArgumentException("The field 'script' should be set on the TaskListener"); } if (language == null) { throw new IllegalArgumentException("The field 'language' should be set on the TaskListener"); } } public void setScript(Expression script) { this.script = script; } public void setLanguage(Expression language) { this.language = language; } public void setResultVariable(Expression resultVariable) { this.resultVariable = resultVariable; } public Expression getResultVariable() { return resultVariable; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\listener\ScriptTypeTaskListener.java
1
请完成以下Java代码
public String getRandom() { return random; } public void setRandom(String random) { this.random = random; } } public static class TopicPartition { protected String topic; protected Collection<String> partitions; public String getTopic() { return topic; }
public void setTopic(String topic) { this.topic = topic; } public Collection<String> getPartitions() { return partitions; } public void setPartitions(Collection<String> partitions) { this.partitions = partitions; } } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaInboundChannelModel.java
1
请完成以下Java代码
public class DetailedUserDto { private Long id; private String username; private Set<String> permissions; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
public Set<String> getPermissions() { return permissions; } public void setPermissions(Set<String> permissions) { this.permissions = permissions; } public static DetailedUserDto fromEntity(BasicUser user) { DetailedUserDto detailed = new DetailedUserDto(); detailed.setId(user.getId()); detailed.setUsername(user.getUsername()); detailed.setPermissions(user.getPermissions()); return detailed; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\osiv\web\DetailedUserDto.java
1
请完成以下Java代码
public String getId() { return id; } public String getBusinessKey() { return businessKey; } public String getCallActivityInstanceId() { return callActivityInstanceId; } public String getCallActivityId() { return callActivityId; } public String getProcessDefinitionId() { return processDefinitionId; }
public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionName() { return processDefinitionName; } public List<IncidentStatisticsDto> getIncidents() { return incidents; } public void setIncidents(List<IncidentStatisticsDto> incidents) { this.incidents = incidents; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\CalledProcessInstanceDto.java
1
请完成以下Java代码
public Object getPersistentState() { // entity is not updatable return TenantMembershipEntity.class; } public String getId() { return id; } public void setId(String id) { this.id = id; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } public GroupEntity getGroup() { return group; } public void setGroup(GroupEntity group) { this.group = group; } public String getTenantId() { return tenant.getId();
} public String getUserId() { if (user != null) { return user.getId(); } else { return null; } } public String getGroupId() { if (group != null) { return group.getId(); } else { return null; } } public TenantEntity getTenant() { return tenant; } public void setTenant(TenantEntity tenant) { this.tenant = tenant; } @Override public String toString() { return "TenantMembershipEntity [id=" + id + ", tenant=" + tenant + ", user=" + user + ", group=" + group + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TenantMembershipEntity.java
1
请完成以下Java代码
protected void performOutgoingBehavior(ActivityExecution execution, boolean checkConditions) { LOG.leavingActivity(execution.getActivity().getId()); String defaultSequenceFlow = (String) execution.getActivity().getProperty("default"); List<PvmTransition> transitionsToTake = new ArrayList<>(); List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions(); for (PvmTransition outgoingTransition : outgoingTransitions) { if (defaultSequenceFlow == null || !outgoingTransition.getId().equals(defaultSequenceFlow)) { Condition condition = (Condition) outgoingTransition.getProperty(BpmnParse.PROPERTYNAME_CONDITION); if (condition == null || !checkConditions || condition.evaluate(execution)) { transitionsToTake.add(outgoingTransition); } } } if (transitionsToTake.size() == 1) { execution.leaveActivityViaTransition(transitionsToTake.get(0)); } else if (transitionsToTake.size() >= 1) { execution.leaveActivityViaTransitions(transitionsToTake, Arrays.asList(execution)); } else { if (defaultSequenceFlow != null) { PvmTransition defaultTransition = execution.getActivity().findOutgoingTransition(defaultSequenceFlow); if (defaultTransition != null) { execution.leaveActivityViaTransition(defaultTransition); } else { throw LOG.missingDefaultFlowException(execution.getActivity().getId(), defaultSequenceFlow); } } else if (!outgoingTransitions.isEmpty()) { throw LOG.missingConditionalFlowException(execution.getActivity().getId()); } else { if (((ActivityImpl) execution.getActivity()).isCompensationHandler() && isAncestorCompensationThrowing(execution)) { execution.endCompensation();
} else { LOG.missingOutgoingSequenceFlow(execution.getActivity().getId()); execution.end(true); } } } } protected boolean isAncestorCompensationThrowing(ActivityExecution execution) { ActivityExecution parent = execution.getParent(); while (parent != null) { if (CompensationBehavior.isCompensationThrowing((PvmExecutionImpl) parent)) { return true; } parent = parent.getParent(); } return false; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnActivityBehavior.java
1
请完成以下Java代码
public void setupCallouts() { final IProgramaticCalloutProvider calloutProvider = Services.get(IProgramaticCalloutProvider.class); calloutProvider.registerAnnotatedCallout(this); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void beforeSave_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct) { updateItemProduct(itemProduct); setUOMItemProduct(itemProduct); Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct); // Validate the item product only if is saved. validateItemProduct(itemProduct); } @CalloutMethod(columnNames = { I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_ID, I_M_HU_PI_Item_Product.COLUMNNAME_Qty, I_M_HU_PI_Item_Product.COLUMNNAME_IsInfiniteCapacity }) public void onManualChange_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct, final ICalloutField field) { updateItemProduct(itemProduct); setUOMItemProduct(itemProduct); Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct); } private void updateItemProduct(final I_M_HU_PI_Item_Product itemProduct) { if (itemProduct.isAllowAnyProduct()) { itemProduct.setM_Product_ID(-1);
itemProduct.setIsInfiniteCapacity(true); } } private void setUOMItemProduct(final I_M_HU_PI_Item_Product huPiItemProduct) { final ProductId productId = ProductId.ofRepoIdOrNull(huPiItemProduct.getM_Product_ID()); if (productId == null) { // nothing to do return; } final UomId stockingUOMId = Services.get(IProductBL.class).getStockUOMId(productId); huPiItemProduct.setC_UOM_ID(stockingUOMId.getRepoId()); } private void validateItemProduct(final I_M_HU_PI_Item_Product itemProduct) { if (Services.get(IHUCapacityBL.class).isValidItemProduct(itemProduct)) { return; } final String errorMsg = Services.get(IMsgBL.class).getMsg(InterfaceWrapperHelper.getCtx(itemProduct), M_HU_PI_Item_Product.MSG_QUANTITY_INVALID); throw new AdempiereException(errorMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU_PI_Item_Product.java
1
请完成以下Java代码
public class DecisionRuleImpl extends DmnElementImpl implements DecisionRule { protected static ChildElementCollection<InputEntry> inputEntryCollection; protected static ChildElementCollection<OutputEntry> outputEntryCollection; public DecisionRuleImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Collection<InputEntry> getInputEntries() { return inputEntryCollection.get(this); } public Collection<OutputEntry> getOutputEntries() { return outputEntryCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionRule.class, DMN_ELEMENT_DECISION_RULE) .namespaceUri(LATEST_DMN_NS) .extendsType(DmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<DecisionRule>() { public DecisionRule newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionRuleImpl(instanceContext);
} }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputEntryCollection = sequenceBuilder.elementCollection(InputEntry.class) .build(); outputEntryCollection = sequenceBuilder.elementCollection(OutputEntry.class) .required() .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionRuleImpl.java
1
请完成以下Java代码
public class Plane { private final String name; private final String model; public Plane(String name, String model) { this.name = name; this.model = model; } public String getName() { return name; } public String getModel() { return model; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Plane plane = (Plane) o; return Objects.equals(name, plane.name) && Objects.equals(model, plane.model); } @Override public int hashCode() { return Objects.hash(name, model); } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-3\src\main\java\com\baeldung\arraycompare\Plane.java
1
请完成以下Java代码
public @Nullable Ssl getSsl() { return this.ssl; } @Override public void setSsl(@Nullable Ssl ssl) { this.ssl = ssl; } /** * Return the configured {@link SslBundles}. * @return the {@link SslBundles} or {@code null} * @since 3.2.0 */ public @Nullable SslBundles getSslBundles() { return this.sslBundles; } @Override public void setSslBundles(@Nullable SslBundles sslBundles) { this.sslBundles = sslBundles; } public @Nullable Http2 getHttp2() { return this.http2; } @Override public void setHttp2(@Nullable Http2 http2) { this.http2 = http2; } public @Nullable Compression getCompression() { return this.compression; } @Override public void setCompression(@Nullable Compression compression) { this.compression = compression; } public @Nullable String getServerHeader() { return this.serverHeader; } @Override public void setServerHeader(@Nullable String serverHeader) { this.serverHeader = serverHeader; } @Override public void setShutdown(Shutdown shutdown) { this.shutdown = shutdown; } /** * Returns the shutdown configuration that will be applied to the server. * @return the shutdown configuration * @since 2.3.0 */ public Shutdown getShutdown() { return this.shutdown; } /** * Return the {@link SslBundle} that should be used with this server. * @return the SSL bundle */ protected final SslBundle getSslBundle() {
return WebServerSslBundle.get(this.ssl, this.sslBundles); } protected final Map<String, SslBundle> getServerNameSslBundles() { Assert.state(this.ssl != null, "'ssl' must not be null"); return this.ssl.getServerNameBundles() .stream() .collect(Collectors.toMap(ServerNameSslBundle::serverName, (serverNameSslBundle) -> { Assert.state(this.sslBundles != null, "'sslBundles' must not be null"); return this.sslBundles.getBundle(serverNameSslBundle.bundle()); })); } /** * Return the absolute temp dir for given web server. * @param prefix server name * @return the temp dir for given server. */ protected final File createTempDir(String prefix) { try { File tempDir = Files.createTempDirectory(prefix + "." + getPort() + ".").toFile(); tempDir.deleteOnExit(); return tempDir; } catch (IOException ex) { throw new WebServerException( "Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\AbstractConfigurableWebServerFactory.java
1
请完成以下Java代码
public java.lang.String getTermDurationUnit() { return get_ValueAsString(COLUMNNAME_TermDurationUnit); } @Override public void setTermOfNotice (final int TermOfNotice) { set_Value (COLUMNNAME_TermOfNotice, TermOfNotice); } @Override public int getTermOfNotice() { return get_ValueAsInt(COLUMNNAME_TermOfNotice); } /** * TermOfNoticeUnit AD_Reference_ID=540281 * Reference name: TermDurationUnit */ public static final int TERMOFNOTICEUNIT_AD_Reference_ID=540281; /** Monat(e) = month */ public static final String TERMOFNOTICEUNIT_MonatE = "month"; /** Woche(n) = week */ public static final String TERMOFNOTICEUNIT_WocheN = "week"; /** Tag(e) = day */
public static final String TERMOFNOTICEUNIT_TagE = "day"; /** Jahr(e) = year */ public static final String TERMOFNOTICEUNIT_JahrE = "year"; @Override public void setTermOfNoticeUnit (final java.lang.String TermOfNoticeUnit) { set_Value (COLUMNNAME_TermOfNoticeUnit, TermOfNoticeUnit); } @Override public java.lang.String getTermOfNoticeUnit() { return get_ValueAsString(COLUMNNAME_TermOfNoticeUnit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Transition.java
1
请完成以下Java代码
private static <T extends PickingJobFacet, R> ImmutableSet<R> extract(Set<PickingJobFacet> facets, Class<T> type, Function<T, R> mapper) { if (facets.isEmpty()) { return ImmutableSet.of(); } return facets.stream() .map(facet -> facet.asTypeOrNull(type)) .filter(Objects::nonNull) .map(facet -> mapper.apply(facet.asType(type))) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public static FacetAwareItem ofList(final Set<PickingJobFacet> facets) { if (facets.isEmpty()) { return EMPTY; } return new FacetAwareItem(facets); } public boolean hasFacets() {return !facetsByGroup.isEmpty();} public boolean isMatching(@NonNull final PickingJobQuery.Facets query) { return isMatching(customerIds, query.getCustomerIds()) && isMatching(deliveryDays, query.getDeliveryDays())
&& isMatching(handoverLocationIds, query.getHandoverLocationIds()); } private static <T> boolean isMatching(final Set<T> values, final Set<T> requiredValues) { if (requiredValues.isEmpty()) { return true; } return values.stream().anyMatch(requiredValues::contains); } public ImmutableSet<PickingJobFacet> getFacets(@NonNull final PickingJobFacetGroup group) { return facetsByGroup.get(group); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\facets\PickingJobFacetsAccumulator.java
1
请完成以下Java代码
public static InputStream fileAsStream(String filename) { File classpathFile = getClasspathFile(filename); return fileAsStream(classpathFile); } /** * Returns the input stream of a file. * * @param file the File to load * @return the file content as input stream * @throws IoUtilException if the file cannot be loaded */ public static InputStream fileAsStream(File file) { try { return new BufferedInputStream(new FileInputStream(file)); } catch(FileNotFoundException e) { throw LOG.fileNotFoundException(file.getAbsolutePath(), e); } } /** * Returns the File for a filename. * * @param filename the filename to load * @return the file object */ public static File getClasspathFile(String filename) { if(filename == null) { throw LOG.nullParameter("filename"); } return getClasspathFile(filename, null); } /** * Returns the File for a filename. * * @param filename the filename to load * @param classLoader the classLoader to load file with, if null falls back to TCCL and then this class's classloader * @return the file object * @throws IoUtilException if the file cannot be loaded */ public static File getClasspathFile(String filename, ClassLoader classLoader) { if(filename == null) { throw LOG.nullParameter("filename");
} URL fileUrl = null; if (classLoader != null) { fileUrl = classLoader.getResource(filename); } if (fileUrl == null) { // Try the current Thread context classloader classLoader = Thread.currentThread().getContextClassLoader(); fileUrl = classLoader.getResource(filename); if (fileUrl == null) { // Finally, try the classloader for this class classLoader = IoUtil.class.getClassLoader(); fileUrl = classLoader.getResource(filename); } } if(fileUrl == null) { throw LOG.fileNotFoundException(filename); } try { return new File(fileUrl.toURI()); } catch(URISyntaxException e) { throw LOG.fileNotFoundException(filename, e); } } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\IoUtil.java
1
请在Spring Boot框架中完成以下Java代码
ThymeleafReactiveViewResolver thymeleafViewResolver(ISpringWebFluxTemplateEngine templateEngine, ThymeleafProperties properties) { ThymeleafReactiveViewResolver resolver = new ThymeleafReactiveViewResolver(); resolver.setTemplateEngine(templateEngine); mapProperties(properties, resolver); mapReactiveProperties(properties.getReactive(), resolver); // This resolver acts as a fallback resolver (e.g. like a // InternalResourceViewResolver) so it needs to have low precedence resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 5); return resolver; } private void mapProperties(ThymeleafProperties properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getEncoding).to(resolver::setDefaultCharset); resolver.setExcludedViewNames(properties.getExcludedViewNames()); resolver.setViewNames(properties.getViewNames()); } private void mapReactiveProperties(Reactive properties, ThymeleafReactiveViewResolver resolver) { PropertyMapper map = PropertyMapper.get(); map.from(properties::getMediaTypes).to(resolver::setSupportedMediaTypes); map.from(properties::getMaxChunkSize) .asInt(DataSize::toBytes) .when((size) -> size > 0) .to(resolver::setResponseMaxChunkSizeBytes); map.from(properties::getFullModeViewNames).to(resolver::setFullModeViewNames); map.from(properties::getChunkedModeViewNames).to(resolver::setChunkedModeViewNames); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(LayoutDialect.class) static class ThymeleafWebLayoutConfiguration { @Bean
@ConditionalOnMissingBean LayoutDialect layoutDialect() { return new LayoutDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(DataAttributeDialect.class) static class DataAttributeDialectConfiguration { @Bean @ConditionalOnMissingBean DataAttributeDialect dialect() { return new DataAttributeDialect(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ SpringSecurityDialect.class, CsrfToken.class }) static class ThymeleafSecurityDialectConfiguration { @Bean @ConditionalOnMissingBean SpringSecurityDialect securityDialect() { return new SpringSecurityDialect(); } } }
repos\spring-boot-4.0.1\module\spring-boot-thymeleaf\src\main\java\org\springframework\boot\thymeleaf\autoconfigure\ThymeleafAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class JacksonConfiguration { /** * Support for Java date and time API. * @return the corresponding Jackson module. */ @Bean public JavaTimeModule javaTimeModule() { return new JavaTimeModule(); } @Bean public Jdk8Module jdk8TimeModule() { return new Jdk8Module(); } /* * Support for Hibernate types in Jackson. */ @Bean public Hibernate5Module hibernate5Module() { return new Hibernate5Module(); } /* * Jackson Afterburner module to speed up serialization/deserialization.
*/ @Bean public AfterburnerModule afterburnerModule() { return new AfterburnerModule(); } /* * Module for serialization/deserialization of RFC7807 Problem. */ @Bean ProblemModule problemModule() { return new ProblemModule(); } /* * Module for serialization/deserialization of ConstraintViolationProblem. */ @Bean ConstraintViolationProblemModule constraintViolationProblemModule() { return new ConstraintViolationProblemModule(); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\JacksonConfiguration.java
2
请完成以下Java代码
public Object getPersistentState() { return null; // Not updatable } @Override public long getLogNumber() { return logNumber; } @Override public void setLogNumber(long logNumber) { this.logNumber = logNumber; } @Override public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getProcessDefinitionId() { return processDefinitionId; } @Override public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @Override public String getProcessInstanceId() { return processInstanceId; } @Override public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getExecutionId() { return executionId; } @Override public void setExecutionId(String executionId) { this.executionId = executionId; } @Override public String getTaskId() { return taskId; } @Override public void setTaskId(String taskId) { this.taskId = taskId; } @Override public Date getTimeStamp() { return timeStamp; } @Override public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } @Override public String getUserId() { return userId; } @Override public void setUserId(String userId) { this.userId = userId; }
@Override public byte[] getData() { return data; } @Override public void setData(byte[] data) { this.data = data; } @Override public String getLockOwner() { return lockOwner; } @Override public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } @Override public String getLockTime() { return lockTime; } @Override public void setLockTime(String lockTime) { this.lockTime = lockTime; } @Override public int getProcessed() { return isProcessed; } @Override public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
1
请完成以下Java代码
public void initEditor() { editor.setDocument(document); //undo = new UndoManager(); resetUndoManager(); document.addUndoableEditListener(undoHandler); editor.scrollRectToVisible(new Rectangle(0,0,0,0)); editor.setCaretPosition(0); } public boolean isDocumentChanged() { return undo.canUndo(); } public void setStyleSheet(Reader r) { StyleSheet css = new StyleSheet(); try { css.loadRules(r, null); /* * new InputStreamReader( * net.sf.memoranda.ui.htmleditor.HTMLEditor.class.getResourceAsStream("resources/css/default.css")), */ } catch (Exception ex) { ex.printStackTrace(); } editorKit.setStyleSheet(css); } public void reload() { } void doFind() { FindDialog dlg = new FindDialog(); //dlg.setLocation(linkActionB.getLocationOnScreen()); Dimension dlgSize = dlg.getSize(); //dlg.setSize(400, 300); Dimension frmSize = this.getSize(); Point loc = this.getLocationOnScreen(); dlg.setLocation( (frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); if (editor.getSelectedText() != null) dlg.txtSearch.setText(editor.getSelectedText()); else if (Context.get("LAST_SEARCHED_WORD") != null) dlg.txtSearch.setText(Context.get("LAST_SEARCHED_WORD").toString()); dlg.setVisible(true); if (dlg.CANCELLED) return; Context.put("LAST_SEARCHED_WORD", dlg.txtSearch.getText()); String repl = null; if (dlg.chkReplace.isSelected()) repl = dlg.txtReplace.getText(); Finder finder = new Finder( this, dlg.txtSearch.getText(), dlg.chkWholeWord.isSelected(), dlg.chkCaseSens.isSelected(), dlg.chkRegExp.isSelected(), repl); finder.start(); } // metas: begin public String getHtmlText() { try { StringWriter sw = new StringWriter(); new AltHTMLWriter(sw, this.document).write();
// new HTMLWriter(sw, editor.document).write(); String html = sw.toString(); return html; } catch (Exception e) { e.printStackTrace(); } return null; } public HTMLDocument getDocument() { return this.document; } @Override public void requestFocus() { this.editor.requestFocus(); } @Override public boolean requestFocus(boolean temporary) { return this.editor.requestFocus(temporary); } @Override public boolean requestFocusInWindow() { return this.editor.requestFocusInWindow(); } public void setText(String html) { this.editor.setText(html); } public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public ActionMap getEditorActionMap() { return this.editor.getActionMap(); } public InputMap getEditorInputMap(int condition) { return this.editor.getInputMap(condition); } public Keymap getEditorKeymap() { return this.editor.getKeymap(); } public JTextComponent getTextComponent() { return this.editor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java
1
请在Spring Boot框架中完成以下Java代码
private List<OAuth2AuthorizedClientProvider> getAdditionalAuthorizedClientProviders( Collection<OAuth2AuthorizedClientProvider> authorizedClientProviders) { List<OAuth2AuthorizedClientProvider> additionalAuthorizedClientProviders = new ArrayList<>( authorizedClientProviders); additionalAuthorizedClientProviders .removeIf((provider) -> KNOWN_AUTHORIZED_CLIENT_PROVIDERS.contains(provider.getClass())); return additionalAuthorizedClientProviders; } private <T extends OAuth2AuthorizedClientProvider> T getAuthorizedClientProviderByType( Collection<OAuth2AuthorizedClientProvider> authorizedClientProviders, Class<T> providerClass) { T authorizedClientProvider = null; for (OAuth2AuthorizedClientProvider current : authorizedClientProviders) { if (providerClass.isInstance(current)) { assertAuthorizedClientProviderIsNull(authorizedClientProvider); authorizedClientProvider = providerClass.cast(current); } } return authorizedClientProvider; } private static void assertAuthorizedClientProviderIsNull( OAuth2AuthorizedClientProvider authorizedClientProvider) { if (authorizedClientProvider != null) { // @formatter:off throw new BeanInitializationException(String.format( "Unable to create an %s bean. Expected one bean of type %s, but found multiple. " + "Please consider defining only a single bean of this type, or define an %s bean yourself.", OAuth2AuthorizedClientManager.class.getName(), authorizedClientProvider.getClass().getName(), OAuth2AuthorizedClientManager.class.getName())); // @formatter:on } }
private <T> String[] getBeanNamesForType(Class<T> beanClass) { return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, beanClass, true, true); } private <T> T getBeanOfType(ResolvableType resolvableType) { ObjectProvider<T> objectProvider = this.beanFactory.getBeanProvider(resolvableType, true); return objectProvider.getIfAvailable(); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\OAuth2ClientConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String prefix() { return "management.ganglia.metrics.export"; } @Override public @Nullable String get(String k) { return null; } @Override public boolean enabled() { return obtain(GangliaProperties::isEnabled, GangliaConfig.super::enabled); } @Override public Duration step() { return obtain(GangliaProperties::getStep, GangliaConfig.super::step); } @Override public TimeUnit durationUnits() { return obtain(GangliaProperties::getDurationUnits, GangliaConfig.super::durationUnits); } @Override public GMetric.UDPAddressingMode addressingMode() { return obtain(GangliaProperties::getAddressingMode, GangliaConfig.super::addressingMode);
} @Override public int ttl() { return obtain(GangliaProperties::getTimeToLive, GangliaConfig.super::ttl); } @Override public String host() { return obtain(GangliaProperties::getHost, GangliaConfig.super::host); } @Override public int port() { return obtain(GangliaProperties::getPort, GangliaConfig.super::port); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\ganglia\GangliaPropertiesConfigAdapter.java
2
请完成以下Java代码
public java.lang.String getPostingType () { return (java.lang.String)get_Value(COLUMNNAME_PostingType); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set SubLine ID. @param SubLine_ID Transaction sub line ID (internal) */ @Override public void setSubLine_ID (int SubLine_ID) { if (SubLine_ID < 1) set_ValueNoCheck (COLUMNNAME_SubLine_ID, null); else set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID)); } /** Get SubLine ID. @return Transaction sub line ID (internal) */ @Override public int getSubLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest_Source_v.java
1
请完成以下Java代码
public class ContainerPartitionPausingBackOffManager implements KafkaConsumerBackoffManager { private static final LogAccessor LOGGER = new LogAccessor(LogFactory.getLog(ContainerPartitionPausingBackOffManager.class)); private final ListenerContainerRegistry listenerContainerRegistry; private final BackOffHandler backOffHandler; /** * Construct an instance with the provided registry and back off handler. * @param listenerContainerRegistry the registry. * @param backOffHandler the handler. */ public ContainerPartitionPausingBackOffManager(ListenerContainerRegistry listenerContainerRegistry, BackOffHandler backOffHandler) { Assert.notNull(listenerContainerRegistry, "'listenerContainerRegistry' cannot be null"); Assert.notNull(backOffHandler, "'backOffHandler' cannot be null"); this.listenerContainerRegistry = listenerContainerRegistry; this.backOffHandler = backOffHandler; } /** * Backs off if the current time is before the dueTimestamp provided * in the {@link Context} object. * @param context the back off context for this execution. */ @Override public void backOffIfNecessary(Context context) { long backoffTime = context.getDueTimestamp() - System.currentTimeMillis(); LOGGER.debug(() -> "Back off time: " + backoffTime + " Context: " + context); if (backoffTime > 0) { pauseConsumptionAndThrow(context, backoffTime); } } private void pauseConsumptionAndThrow(Context context, Long backOffTime) throws KafkaBackoffException { TopicPartition topicPartition = context.getTopicPartition();
MessageListenerContainer container = getListenerContainerFromContext(context); container.pausePartition(topicPartition); this.backOffHandler.onNextBackOff(container, topicPartition, backOffTime); throw new KafkaBackoffException(String.format("Partition %s from topic %s is not ready for consumption, " + "backing off for approx. %s millis.", topicPartition.partition(), topicPartition.topic(), backOffTime), topicPartition, context.getListenerId(), context.getDueTimestamp()); } private MessageListenerContainer getListenerContainerFromContext(Context context) { MessageListenerContainer container = this.listenerContainerRegistry.getListenerContainer(context.getListenerId()); // NOSONAR if (container == null) { container = this.listenerContainerRegistry.getUnregisteredListenerContainer(context.getListenerId()); } Assert.notNull(container, () -> "No container found with id: " + context.getListenerId()); return container; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerPartitionPausingBackOffManager.java
1
请完成以下Java代码
public boolean isGranting() { return this.granting; } void setAuditFailure(boolean auditFailure) { this.auditFailure = auditFailure; } void setAuditSuccess(boolean auditSuccess) { this.auditSuccess = auditSuccess; } void setPermission(Permission permission) { Assert.notNull(permission, "Permission required"); this.permission = permission; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("AccessControlEntryImpl["); sb.append("id: ").append(this.id).append("; "); sb.append("granting: ").append(this.granting).append("; "); sb.append("sid: ").append(this.sid).append("; "); sb.append("permission: ").append(this.permission).append("; "); sb.append("auditSuccess: ").append(this.auditSuccess).append("; "); sb.append("auditFailure: ").append(this.auditFailure); sb.append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AccessControlEntryImpl.java
1
请完成以下Java代码
private Supplier<ICalloutInstance> supplyCalloutInstanceOrNull(final I_AD_ColumnCallout calloutDef) { if (calloutDef == null) { return null; } if (!calloutDef.isActive()) { return null; } try { final String classname = calloutDef.getClassname(); Check.assumeNotEmpty(classname, "classname is not empty"); final Optional<String> ruleValue = ScriptEngineFactory.extractRuleValueFromClassname(classname); if(ruleValue.isPresent()) {
return RuleCalloutInstance.supplier(ruleValue.get()); } else { return MethodNameCalloutInstance.supplier(classname); } } catch (final Exception e) { // We are just logging and discarding the error because there is nothing that we can do about it // More, we want to load the other callouts and not just fail logger.error("Failed creating callout instance for " + calloutDef, e); return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\impl\DefaultCalloutProvider.java
1
请完成以下Java代码
public class PostgresEdgeEventService extends BaseEdgeEventService { private final EdgeEventDao edgeEventDao; private final ApplicationEventPublisher eventPublisher; private final Optional<EdgeStatsCounterService> statsCounterService; private ExecutorService edgeEventExecutor; @PostConstruct public void initExecutor() { edgeEventExecutor = Executors.newSingleThreadExecutor(ThingsBoardThreadFactory.forName("edge-event-service")); } @PreDestroy public void shutdownExecutor() { if (edgeEventExecutor != null) { edgeEventExecutor.shutdown(); } } @Override public ListenableFuture<Void> saveAsync(EdgeEvent edgeEvent) { validateEdgeEvent(edgeEvent); ListenableFuture<Void> saveFuture = edgeEventDao.saveAsync(edgeEvent); Futures.addCallback(saveFuture, new FutureCallback<>() {
@Override public void onSuccess(Void result) { statsCounterService.ifPresent(statsCounterService -> statsCounterService.recordEvent(EdgeStatsKey.DOWNLINK_MSGS_ADDED, edgeEvent.getTenantId(), edgeEvent.getEdgeId(), 1)); eventPublisher.publishEvent(SaveEntityEvent.builder() .tenantId(edgeEvent.getTenantId()) .entityId(edgeEvent.getEdgeId()) .entity(edgeEvent) .build()); } @Override public void onFailure(@NotNull Throwable throwable) {} }, edgeEventExecutor); return saveFuture; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\edge\PostgresEdgeEventService.java
1
请在Spring Boot框架中完成以下Java代码
public String getRevision() { return revision; } /** * Sets the value of the revision property. * * @param value * allowed object is * {@link String } * */ public void setRevision(String value) { this.revision = value; } /** * Gets the value of the offsetX property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getOffsetX() { return offsetX; } /** * Sets the value of the offsetX property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setOffsetX(BigDecimal value) { this.offsetX = value; } /** * Gets the value of the offsetY property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getOffsetY() { return offsetY; } /** * Sets the value of the offsetY property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setOffsetY(BigDecimal value) { this.offsetY = value; } /** * Gets the value of the connectionType property. * * @return * possible object is * {@link String }
* */ public String getConnectionType() { return connectionType; } /** * Sets the value of the connectionType property. * * @param value * allowed object is * {@link String } * */ public void setConnectionType(String value) { this.connectionType = value; } /** * Gets the value of the barcodeCapable2D property. * */ public boolean isBarcodeCapable2D() { return barcodeCapable2D; } /** * Sets the value of the barcodeCapable2D property. * */ public void setBarcodeCapable2D(boolean value) { this.barcodeCapable2D = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Printer.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_PA_Benchmark[") .append(get_ID()).append("]"); return sb.toString(); } /** AccumulationType AD_Reference_ID=370 */ public static final int ACCUMULATIONTYPE_AD_Reference_ID=370; /** Average = A */ public static final String ACCUMULATIONTYPE_Average = "A"; /** Sum = S */ public static final String ACCUMULATIONTYPE_Sum = "S"; /** Set Accumulation Type. @param AccumulationType How to accumulate data on time axis */ public void setAccumulationType (String AccumulationType) { set_Value (COLUMNNAME_AccumulationType, AccumulationType); } /** Get Accumulation Type. @return How to accumulate data on time axis */ public String getAccumulationType () { return (String)get_Value(COLUMNNAME_AccumulationType); } /** 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); } /** 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 Benchmark. @param PA_Benchmark_ID Performance Benchmark */ public void setPA_Benchmark_ID (int PA_Benchmark_ID) { if (PA_Benchmark_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID)); } /** Get Benchmark. @return Performance Benchmark */ public int getPA_Benchmark_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Benchmark.java
1
请完成以下Java代码
public static JSONDocumentLayoutElementGroup of( @NonNull final DocumentLayoutElementGroupDescriptor elementGroup, @NonNull final JSONDocumentLayoutOptions jsonOpts) { return new JSONDocumentLayoutElementGroup(elementGroup, jsonOpts); } @Schema @JsonProperty("type") @JsonInclude(JsonInclude.Include.NON_NULL) @Getter private final JSONLayoutType type; @Schema(description = "Number of equal-width-columns into which the included elementsLines shall be displayed:\n" + "Notes:\n" + "* one element line per cell" + "* an empty element line shall be rendered as empty cell" + "* if you have e.g. columnCount=3 and four element lines, then the rightmost two cells of the last line shall be empty" + "* if this property is missing, then <code>1</code> should be assumed") @JsonProperty("columnCount") @JsonInclude(JsonInclude.Include.NON_NULL) @Getter private final Integer columnCount; @JsonProperty("internalName") @JsonInclude(JsonInclude.Include.NON_NULL) @Getter private final String internalName; @Schema(description = "Container for elementy that are supposed to be displayed next to each other\n" + "Notes:" + "* individual element lines might be empty for layout purposes; see <code>columnCount</code>\n" + "* in most of the cases, each elementLine has one element") @JsonProperty("elementsLine") @JsonInclude(JsonInclude.Include.ALWAYS) @Getter private final List<JSONDocumentLayoutElementLine> elementLines;
private JSONDocumentLayoutElementGroup( @NonNull final DocumentLayoutElementGroupDescriptor elementGroup, @NonNull final JSONDocumentLayoutOptions jsonOpts) { this.type = JSONLayoutType.fromNullable(elementGroup.getLayoutType()); this.columnCount = elementGroup.getColumnCount(); this.internalName = elementGroup.getInternalName(); this.elementLines = JSONDocumentLayoutElementLine.ofList(elementGroup.getElementLines(), jsonOpts); } @JsonCreator private JSONDocumentLayoutElementGroup( @JsonProperty("type") final JSONLayoutType type, @JsonProperty("columnCount") @Nullable final Integer columnCount, @JsonProperty("internalName") @Nullable final String internalName, @JsonProperty("elementsLine") @Nullable final List<JSONDocumentLayoutElementLine> elementLines) { this.type = type; this.columnCount = columnCount; this.internalName = internalName; this.elementLines = elementLines == null ? ImmutableList.of() : ImmutableList.copyOf(elementLines); } private boolean isEmpty() { final boolean atLeastOneLineIsFilled = elementLines .stream() .anyMatch(line -> !line.isEmpty()); return !atLeastOneLineIsFilled; } Stream<JSONDocumentLayoutElement> streamInlineTabElements() { return getElementLines().stream().flatMap(JSONDocumentLayoutElementLine::streamInlineTabElements); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutElementGroup.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "Room") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "string") public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public boolean isReadable() { return readable; } public void setReadable(boolean readable) { this.readable = readable;
} public boolean isWritable() { return writable; } public void setWritable(boolean writable) { this.writable = writable; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public String getDatePattern() { return datePattern; } public void setDatePattern(String datePattern) { this.datePattern = datePattern; } public List<RestEnumFormProperty> getEnumValues() { return enumValues; } public void setEnumValues(List<RestEnumFormProperty> enumValues) { this.enumValues = enumValues; } public void addEnumValue(RestEnumFormProperty enumValue) { enumValues.add(enumValue); } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\form\RestFormProperty.java
2
请完成以下Java代码
public Sentry getCurrentSentry() { return currentSentry; } public void setCurrentSentry(Sentry currentSentry) { this.currentSentry = currentSentry; } public SentryOnPart getCurrentSentryOnPart() { return currentSentryOnPart; } public void setCurrentSentryOnPart(SentryOnPart currentSentryOnPart) { this.currentSentryOnPart = currentSentryOnPart; } public PlanItem getCurrentPlanItem() { return currentPlanItem; } public void setCurrentPlanItem(PlanItem currentPlanItem) { this.currentPlanItem = currentPlanItem; } public CmmnDiShape getCurrentDiShape() { return currentDiShape; } public void setCurrentDiShape(CmmnDiShape currentDiShape) { this.currentDiShape = currentDiShape; } public CmmnDiEdge getCurrentDiEdge() { return currentDiEdge; } public void setCurrentDiEdge(CmmnDiEdge currentDiEdge) { this.currentDiEdge = currentDiEdge; } public List<Stage> getStages() { return stages; } public List<PlanFragment> getPlanFragments() { return planFragments; }
public List<Criterion> getEntryCriteria() { return entryCriteria; } public List<Criterion> getExitCriteria() { return exitCriteria; } public List<Sentry> getSentries() { return sentries; } public List<SentryOnPart> getSentryOnParts() { return sentryOnParts; } public List<SentryIfPart> getSentryIfParts() { return sentryIfParts; } public List<PlanItem> getPlanItems() { return planItems; } public List<PlanItemDefinition> getPlanItemDefinitions() { return planItemDefinitions; } public List<CmmnDiShape> getDiShapes() { return diShapes; } public List<CmmnDiEdge> getDiEdges() { return diEdges; } public GraphicInfo getCurrentLabelGraphicInfo() { return currentLabelGraphicInfo; } public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) { this.currentLabelGraphicInfo = labelGraphicInfo; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java
1
请完成以下Java代码
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 Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public List<Review> getReviews() { return reviews; } public void setReviews(List<Review> reviews) {
this.reviews = reviews; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
public T walkUntil(ReferenceWalker.WalkCondition<T> condition) { do { for (TreeVisitor<T> collector : preVisitor) { collector.visit(getCurrentElement()); } currentElements.addAll(nextElements()); currentElements.remove(0); for (TreeVisitor<T> collector : postVisitor) { collector.visit(getCurrentElement()); } } while (!condition.isFulfilled(getCurrentElement())); return getCurrentElement(); } public T getCurrentElement() { return currentElements.isEmpty() ? null : currentElements.get(0); }
public interface WalkCondition<S> { boolean isFulfilled(S element); } public static class NullCondition<S> implements ReferenceWalker.WalkCondition<S> { public boolean isFulfilled(S element) { return element == null; } public static <S> ReferenceWalker.WalkCondition<S> notNull() { return new NullCondition<S>(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\tree\ReferenceWalker.java
1
请完成以下Java代码
private void fetchEntityDetailsToMsg(ContactBased<I> contactBased, ObjectNode messageData, TbMsgMetaData msgMetaData) { String value = null; for (var entityDetail : config.getDetailsList()) { switch (entityDetail) { case ID: value = contactBased.getId().getId().toString(); break; case TITLE: value = contactBased.getName(); break; case ADDRESS: value = contactBased.getAddress(); break; case ADDRESS2: value = contactBased.getAddress2(); break; case CITY: value = contactBased.getCity(); break; case COUNTRY: value = contactBased.getCountry(); break; case STATE: value = contactBased.getState(); break; case EMAIL: value = contactBased.getEmail(); break; case PHONE: value = contactBased.getPhone();
break; case ZIP: value = contactBased.getZip(); break; case ADDITIONAL_INFO: if (contactBased.getAdditionalInfo().hasNonNull("description")) { value = contactBased.getAdditionalInfo().get("description").asText(); } break; } if (value == null) { continue; } setDetail(entityDetail.getRuleEngineName(), value, messageData, msgMetaData); } } private void setDetail(String property, String value, ObjectNode messageData, TbMsgMetaData msgMetaData) { String fieldName = getPrefix() + property; if (TbMsgSource.METADATA.equals(fetchTo)) { msgMetaData.putValue(fieldName, value); } else if (TbMsgSource.DATA.equals(fetchTo)) { messageData.put(fieldName, value); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractGetEntityDetailsNode.java
1
请完成以下Java代码
public void addComment(Comment comment) { comments.add(comment); } public void deleteComment(Comment comment) { comments.remove(comment); } public void setTitle(String title) { this.title = title; this.slug = toSlug(title); } public Optional<Comment> getCommentById(String commentId) { return comments.stream() .filter(comment -> comment.getId().equals(commentId)) .findFirst(); }
private String toSlug(String title) { return title.toLowerCase().replaceAll("[&|\\uFE30-\\uFFA0’”\\s?,.]+", "-"); } public boolean hasTag(String tag) { return tags.contains(tag); } public boolean isAuthor(String authorId) { return this.authorId.equals(authorId); } public boolean isAuthor(User author) { return isAuthor(author.getId()); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\Article.java
1
请完成以下Java代码
public int getM_Material_Tracking_Report_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_Line_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Ausgelagerte Menge. @param QtyIssued Ausgelagerte Menge */ @Override public void setQtyIssued (java.math.BigDecimal QtyIssued) { set_Value (COLUMNNAME_QtyIssued, QtyIssued); } /** Get Ausgelagerte Menge. @return Ausgelagerte Menge */ @Override public java.math.BigDecimal getQtyIssued () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued); if (bd == null) return Env.ZERO; return bd; } /** Set Empfangene Menge. @param QtyReceived Empfangene Menge */ @Override public void setQtyReceived (java.math.BigDecimal QtyReceived) { set_Value (COLUMNNAME_QtyReceived, QtyReceived); } /** Get Empfangene Menge. @return Empfangene Menge */ @Override public java.math.BigDecimal getQtyReceived () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report_Line.java
1
请完成以下Java代码
public CamundaBpmRunAdministratorAuthorizationProperties getAdminAuth() { return adminAuth; } public void setAdminAuth(CamundaBpmRunAdministratorAuthorizationProperties adminAuth) { this.adminAuth = adminAuth; } public List<CamundaBpmRunProcessEnginePluginProperty> getProcessEnginePlugins() { return processEnginePlugins; } public void setProcessEnginePlugins(List<CamundaBpmRunProcessEnginePluginProperty> processEnginePlugins) { this.processEnginePlugins = processEnginePlugins; } public CamundaBpmRunRestProperties getRest() { return rest; } public void setRest(CamundaBpmRunRestProperties rest) { this.rest = rest; }
public CamundaBpmRunDeploymentProperties getDeployment() { return deployment; } public void setDeployment(CamundaBpmRunDeploymentProperties deployment) { this.deployment = deployment; } @Override public String toString() { return "CamundaBpmRunProperties [" + "auth=" + auth + ", cors=" + cors + ", ldap=" + ldap + ", adminAuth=" + adminAuth + ", plugins=" + processEnginePlugins + ", rest=" + rest + ", deployment=" + deployment + "]"; } }
repos\camunda-bpm-platform-master\distro\run\core\src\main\java\org\camunda\bpm\run\property\CamundaBpmRunProperties.java
1
请完成以下Java代码
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 */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override 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; } /** Set Transaction Code. @param TransactionCode The transaction code represents the search definition */ @Override public void setTransactionCode (java.lang.String TransactionCode) { set_Value (COLUMNNAME_TransactionCode, TransactionCode); } /** Get Transaction Code. @return The transaction code represents the search definition */ @Override public java.lang.String getTransactionCode () { return (java.lang.String)get_Value(COLUMNNAME_TransactionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_I_Datev_Payment.java
1
请完成以下Java代码
public JsonCacheResetResponse resetForRecordId(@RequestParam("tableName") final String tableName, @RequestParam("recordId") final int recordId) { final JsonCacheResetResponse response = new JsonCacheResetResponse(); final long count = cacheMgt.reset(tableName, recordId); response.addLog("Cleared " + count + " cache entries for " + tableName + "/" + recordId); return response; } @GetMapping("/stats") public JsonGetStatsResponse getStats( @RequestParam(name = "cacheName", required = false) @Nullable final String cacheName, @RequestParam(name = "minSize", required = false) @Nullable final Integer minSize, @RequestParam(name = "labels", required = false) @Nullable final String labels, @RequestParam(name = "orderBy", required = false) @Nullable final String orderByString) { assertAuth(); return getStats( JsonCacheStatsQuery.builder() .cacheName(cacheName) .minSize(minSize) .labels(labels) .orderByString(orderByString) .build() ); } @PostMapping("/stats") public JsonGetStatsResponse getStats(@RequestBody @NonNull final JsonCacheStatsQuery jsonQuery) { assertAuth(); final CCacheStatsPredicate filter = jsonQuery.toCCacheStatsPredicate(); final CCacheStatsOrderBy orderBy = jsonQuery.toCCacheStatsOrderBy().orElse(DEFAULT_ORDER_BY); return cacheMgt.streamStats(filter) .sorted(orderBy) .map(JsonCacheStats::of) .collect(JsonGetStatsResponse.collect()); } @GetMapping("/byId/{cacheId}") public JsonCache getById( @PathVariable("cacheId") final String cacheIdStr, @RequestParam(name = "limit", required = false, defaultValue = "100") final int limit) { assertAuth(); final long cacheId = Long.parseLong(cacheIdStr); final CacheInterface cacheInterface = cacheMgt.getById(cacheId) .orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId)); if (cacheInterface instanceof CCache) { return JsonCache.of((CCache<?, ?>)cacheInterface, limit); } else
{ throw new AdempiereException("Cache of type " + cacheInterface.getClass().getSimpleName() + " is not supported"); } } @GetMapping("/byId/{cacheId}/reset") public void resetCacheById(@PathVariable("cacheId") final String cacheIdStr) { assertAuth(); final long cacheId = Long.parseLong(cacheIdStr); final CacheInterface cacheInterface = cacheMgt.getById(cacheId) .orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId)); cacheInterface.reset(); } @GetMapping("/remoteCacheInvalidationTableNames") public Set<String> getRemoteCacheInvalidationTableNames() { return cacheMgt.getTableNamesToBroadcast() .stream() .sorted() .collect(ImmutableSet.toImmutableSet()); } @GetMapping("/remoteCacheInvalidationTableNames/add") public void enableRemoteCacheInvalidationForTableName(@RequestParam("tableName") final String tableName) { cacheMgt.enableRemoteCacheInvalidationForTableName(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\CacheRestControllerTemplate.java
1
请完成以下Java代码
public static synchronized void destroy() { if (isInitialized()) { Map<String, DmnEngine> engines = new HashMap<>(dmnEngines); dmnEngines = new HashMap<>(); for (String dmnEngineName : engines.keySet()) { DmnEngine dmnEngine = engines.get(dmnEngineName); try { dmnEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (dmnEngineName == null ? "the default dmn engine" : "dmn engine " + dmnEngineName), e); } } dmnEngineInfosByName.clear();
dmnEngineInfosByResourceUrl.clear(); dmnEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { DmnEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngines.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public String getErrorMessage() { return errorMessage; } public String getTenantId() { return tenantId; } public String getState() { return state; } public Date getCreateTime() { return createTime; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricVariableInstanceDto fromHistoricVariableInstance(HistoricVariableInstance historicVariableInstance) { HistoricVariableInstanceDto dto = new HistoricVariableInstanceDto(); dto.id = historicVariableInstance.getId(); dto.name = historicVariableInstance.getName(); dto.processDefinitionKey = historicVariableInstance.getProcessDefinitionKey();
dto.processDefinitionId = historicVariableInstance.getProcessDefinitionId(); dto.processInstanceId = historicVariableInstance.getProcessInstanceId(); dto.executionId = historicVariableInstance.getExecutionId(); dto.activityInstanceId = historicVariableInstance.getActivityInstanceId(); dto.caseDefinitionKey = historicVariableInstance.getCaseDefinitionKey(); dto.caseDefinitionId = historicVariableInstance.getCaseDefinitionId(); dto.caseInstanceId = historicVariableInstance.getCaseInstanceId(); dto.caseExecutionId = historicVariableInstance.getCaseExecutionId(); dto.taskId = historicVariableInstance.getTaskId(); dto.tenantId = historicVariableInstance.getTenantId(); dto.state = historicVariableInstance.getState(); dto.createTime = historicVariableInstance.getCreateTime(); dto.removalTime = historicVariableInstance.getRemovalTime(); dto.rootProcessInstanceId = historicVariableInstance.getRootProcessInstanceId(); if(historicVariableInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, historicVariableInstance.getTypedValue()); } else { dto.errorMessage = historicVariableInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(historicVariableInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableInstanceDto.java
1
请完成以下Java代码
public void updateEdiEnabled(final I_C_Order order) { final int orderInputDataSourceId = order.getAD_InputDataSource_ID(); if (orderInputDataSourceId <= 0) { // nothing to do return; } final boolean isEdiEnabled = inputDataSourceBL.isEDIInputDataSource(orderInputDataSourceId); if (isEdiEnabled) { order.setIsEdiEnabled(true); } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_Order.COLUMNNAME_C_BPartner_ID) public void onPartnerChange(final I_C_Order order)
{ final I_C_BPartner partner = InterfaceWrapperHelper.create(order.getC_BPartner(), de.metas.edi.model.I_C_BPartner.class); if (partner == null) { // nothing to do return; } final boolean isEdiRecipient = partner.isEdiDesadvRecipient() || partner.isEdiInvoicRecipient(); // in case the partner was changed and the new one is not an edi recipient, the order will not be edi enabled // If the new bp is edi recipient, we leave it to the user to set the flag or not if (!isEdiRecipient) { order.setIsEdiEnabled(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\C_Order.java
1
请完成以下Java代码
public static void removeDeviceByName(@NonNull final String deviceName) { staticState.removeDeviceByName(deviceName); } private static String getDeviceParamValue(final String deviceName, final String parameterName, final String defaultValue) { return defaultValue; } private static Set<String> getDeviceRequestClassnames(final String deviceName, final AttributeCode attributeCode) { return DummyDevice.getDeviceRequestClassnames(); } public static DummyDeviceResponse generateRandomResponse() { final BigDecimal value = NumberUtils.randomBigDecimal(responseMinValue, responseMaxValue, 3); return new DummyDeviceResponse(value); } // // // // // private static class StaticStateHolder { private final HashMap<String, DeviceConfig> devicesByName = new HashMap<>(); private final ArrayListMultimap<AttributeCode, DeviceConfig> devicesByAttributeCode = ArrayListMultimap.create(); public synchronized void addDevice(final DeviceConfig device) { final String deviceName = device.getDeviceName(); final DeviceConfig existingDevice = removeDeviceByName(deviceName); devicesByName.put(deviceName, device); device.getAssignedAttributeCodes() .forEach(attributeCode -> devicesByAttributeCode.put(attributeCode, device));
logger.info("addDevice: {} -> {}", existingDevice, device); } public synchronized @Nullable DeviceConfig removeDeviceByName(@NonNull final String deviceName) { final DeviceConfig existingDevice = devicesByName.remove(deviceName); if (existingDevice != null) { existingDevice.getAssignedAttributeCodes() .forEach(attributeCode -> devicesByAttributeCode.remove(attributeCode, existingDevice)); } return existingDevice; } public synchronized ImmutableList<DeviceConfig> getAllDevices() { return ImmutableList.copyOf(devicesByName.values()); } public synchronized ImmutableList<DeviceConfig> getDeviceConfigsForAttributeCode(@NonNull final AttributeCode attributeCode) { return ImmutableList.copyOf(devicesByAttributeCode.get(attributeCode)); } public ImmutableSet<AttributeCode> getAllAttributeCodes() { return ImmutableSet.copyOf(devicesByAttributeCode.keySet()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\dummy\DummyDeviceConfigPool.java
1
请完成以下Java代码
public void manageRecordInterceptors(@NonNull final I_ExternalSystem_Config_ScriptedExportConversion config) { final I_ExternalSystem_Config_ScriptedExportConversion oldRecord = InterfaceWrapperHelper.createOld(config, I_ExternalSystem_Config_ScriptedExportConversion.class); final AdTableAndClientId oldTableAndClientId = Optional.ofNullable(AdTableId.ofRepoIdOrNull(oldRecord.getAD_Table_ID())) .map(tableId -> AdTableAndClientId.of(tableId, ClientId.ofRepoId(oldRecord.getAD_Client_ID()))) .orElse(null); final AdTableAndClientId tableAndClientId = AdTableAndClientId.of(AdTableId.ofRepoId(config.getAD_Table_ID()), ClientId.ofRepoId(config.getAD_Client_ID())); if (config.isActive()) { if (oldTableAndClientId != null && !oldTableAndClientId.equals(tableAndClientId) && !externalSystemScriptedExportConversionService.existsActive(oldTableAndClientId)) { externalSystemScriptedExportConversionInterceptorRegistry.unregisterInterceptorByTableAndClientId(oldTableAndClientId); } if (externalSystemScriptedExportConversionService.existsActiveOutOfTrx(tableAndClientId)) { return; } registerInterceptor(config); } else { if (!externalSystemScriptedExportConversionService.existsActive(tableAndClientId) && oldRecord.isActive()) { externalSystemScriptedExportConversionInterceptorRegistry.unregisterInterceptorByTableAndClientId(tableAndClientId); } } } private void registerInterceptor(@NonNull final ExternalSystemScriptedExportConversionConfig config) { final ExternalSystemScriptedExportConversionInterceptor interceptor = new ExternalSystemScriptedExportConversionInterceptor( engine,
externalSystemScriptedExportConversionService, AdTableAndClientId.of(config.getAdTableId(), config.getClientId())); externalSystemScriptedExportConversionInterceptorRegistry.registerInterceptor(interceptor); } private void registerInterceptor(@NonNull final I_ExternalSystem_Config_ScriptedExportConversion config) { final ExternalSystemScriptedExportConversionInterceptor interceptor = new ExternalSystemScriptedExportConversionInterceptor( engine, externalSystemScriptedExportConversionService, AdTableAndClientId.of( AdTableId.ofRepoId(config.getAD_Table_ID()), ClientId.ofRepoId(config.getAD_Client_ID()))); externalSystemScriptedExportConversionInterceptorRegistry.registerInterceptor(interceptor); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\interceptor\ExternalSystem_Config_ScriptedExportConversion.java
1