instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class OrderADRModelAttributeSetInstanceListener implements IModelAttributeSetInstanceListener { @NonNull private final OrderLineADRModelAttributeSetInstanceListener orderLineListener; private static final List<String> sourceColumnNames = Collections.singletonList(I_C_Order.COLUMNNAME_C_BPartner_ID); @Override public @NonNull String getSourceTableName() { return I_C_Order.Table_Name; } @Override public List<String> getSourceColumnNames() { return sourceColumnNames; }
@Override public void modelChanged(final Object model) { final IOrderDAO orderDAO = Services.get(IOrderDAO.class); final I_C_Order order = InterfaceWrapperHelper.create(model, I_C_Order.class); final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order); for (final I_C_OrderLine line : orderLines) { orderLineListener.modelChanged(line); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\listeners\adr\OrderADRModelAttributeSetInstanceListener.java
2
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaExecutionListener.class, CAMUNDA_ELEMENT_EXECUTION_LISTENER) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaExecutionListener>() { public CamundaExecutionListener newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaExecutionListenerImpl(instanceContext); } }); camundaEventAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EVENT) .namespace(CAMUNDA_NS) .build(); camundaClassAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CLASS) .namespace(CAMUNDA_NS) .build(); camundaExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EXPRESSION) .namespace(CAMUNDA_NS) .build(); camundaDelegateExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DELEGATE_EXPRESSION) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); camundaFieldCollection = sequenceBuilder.elementCollection(CamundaField.class) .build(); camundaScriptChild = sequenceBuilder.element(CamundaScript.class) .build(); typeBuilder.build(); } public CamundaExecutionListenerImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getCamundaEvent() { return camundaEventAttribute.getValue(this);
} public void setCamundaEvent(String camundaEvent) { camundaEventAttribute.setValue(this, camundaEvent); } public String getCamundaClass() { return camundaClassAttribute.getValue(this); } public void setCamundaClass(String camundaClass) { camundaClassAttribute.setValue(this, camundaClass); } public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaDelegateExpression() { return camundaDelegateExpressionAttribute.getValue(this); } public void setCamundaDelegateExpression(String camundaDelegateExpression) { camundaDelegateExpressionAttribute.setValue(this, camundaDelegateExpression); } public Collection<CamundaField> getCamundaFields() { return camundaFieldCollection.get(this); } public CamundaScript getCamundaScript() { return camundaScriptChild.getChild(this); } public void setCamundaScript(CamundaScript camundaScript) { camundaScriptChild.setChild(this, camundaScript); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaExecutionListenerImpl.java
1
请完成以下Java代码
public void insert() { log.info(""); // --- Delete first int no = delete(); // Handle NULL if (m_Value == null || m_Value.length() == 0) { if (DisplayType.isLookup(m_DisplayType)) { m_Value = "-1"; // -1 may cause problems (BPartner - M_DiscountSchema } else if (DisplayType.isDate(m_DisplayType)) { m_Value = " "; } else { ADialog.warn(m_WindowNo, this, "ValuePreferenceNotInserted"); return; } } // --- Inserting int Client_ID = cbClient.isSelected() ? m_AD_Client_ID : 0; int Org_ID = cbOrg.isSelected() ? m_AD_Org_ID : 0; int AD_Preference_ID = DB.getNextID(m_ctx, I_AD_Preference.Table_Name); // StringBuffer sql = new StringBuffer ("INSERT INTO AD_Preference (" + "AD_Preference_ID, AD_Client_ID, AD_Org_ID, IsActive, Created,CreatedBy,Updated,UpdatedBy," + "AD_Window_ID, AD_User_ID, Attribute, Value) VALUES ("); sql.append(AD_Preference_ID).append(",").append(Client_ID).append(",").append(Org_ID) .append(", 'Y',now(),").append(m_AD_User_ID).append(",now(),").append(m_AD_User_ID).append(", "); if (cbWindow.isSelected()) { sql.append(m_adWindowId.getRepoId()).append(","); } else { sql.append("NULL,") ;
} if (cbUser.isSelected()) { sql.append(m_AD_User_ID).append(","); } else { sql.append("NULL,"); } // sql.append(DB.TO_STRING(m_Attribute)).append(",").append(DB.TO_STRING(m_Value)).append(")"); // log.debug( sql.toString()); no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), null); if (no == 1) { Env.setContext(m_ctx, getContextKey(), m_Value); ADialog.info(m_WindowNo, this, "ValuePreferenceInserted"); } else { ADialog.warn(m_WindowNo, this, "ValuePreferenceNotInserted"); } } // insert } // ValuePreference
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\ValuePreference.java
1
请完成以下Java代码
public SequenceFlow getDefault() { return defaultAttribute.getReferenceTargetElement(this); } public void setDefault(SequenceFlow defaultFlow) { defaultAttribute.setReferenceTargetElement(this, defaultFlow); } public IoSpecification getIoSpecification() { return ioSpecificationChild.getChild(this); } public void setIoSpecification(IoSpecification ioSpecification) { ioSpecificationChild.setChild(this, ioSpecification); } public Collection<Property> getProperties() { return propertyCollection.get(this); } public Collection<DataInputAssociation> getDataInputAssociations() { return dataInputAssociationCollection.get(this); }
public Collection<DataOutputAssociation> getDataOutputAssociations() { return dataOutputAssociationCollection.get(this); } public Collection<ResourceRole> getResourceRoles() { return resourceRoleCollection.get(this); } public LoopCharacteristics getLoopCharacteristics() { return loopCharacteristicsChild.getChild(this); } public void setLoopCharacteristics(LoopCharacteristics loopCharacteristics) { loopCharacteristicsChild.setChild(this, loopCharacteristics); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ActivityImpl.java
1
请完成以下Java代码
public boolean isNeedsCaseDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(CaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName()); } public List<CaseInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds; } public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) { this.safeCaseInstanceIds = safeCaseInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceQueryImpl.java
1
请完成以下Java代码
public class FindFolder { public static long numberOfFilesIn_classic(String path) { File currentFile = new File(path); File[] filesOrNull = currentFile.listFiles(); long currentFileNumber = currentFile.isFile() ? 1 : 0; if (filesOrNull == null) { return currentFileNumber; } for (File file : filesOrNull) { if (file.isDirectory()) { currentFileNumber += numberOfFilesIn_classic(file.getAbsolutePath()); } else if (file.isFile()) { currentFileNumber += 1; } } return currentFileNumber; } public static long numberOfFilesIn_Stream(String path) { File currentFile = new File(path); File[] filesOrNull = currentFile.listFiles(); long currentFileNumber = currentFile.isFile() ? 1 : 0; if (filesOrNull == null) { return currentFileNumber; } return currentFileNumber + Arrays.stream(filesOrNull) .mapToLong(FindFolder::filesInside) .sum(); } private static long filesInside(File it) { if (it.isFile()) { return 1; } else if (it.isDirectory()) { return numberOfFilesIn_Stream(it.getAbsolutePath()); } else { return 0; } } public static long numberOfFilesIn_Walk(String path) { Path dir = Path.of(path); try (Stream<Path> stream = Files.walk(dir)) {
return stream.parallel() .map(getFileOrEmpty()) .flatMap(Optional::stream) .filter(it -> !it.isDirectory()) .count(); } catch (IOException e) { throw new RuntimeException(e); } } private static Function<Path, Optional<File>> getFileOrEmpty() { return it -> { try { return Optional.of(it.toFile()); } catch (UnsupportedOperationException e) { println(e); return Optional.empty(); } }; } public static long numberOfFilesIn_NIO(String path) { try (Stream<Path> stream = Files.find( Paths.get(path), Integer.MAX_VALUE, (__, attr) -> attr.isRegularFile()) ) { return stream.count(); } catch (IOException e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-23\src\main\java\com\baeldung\javafeatures\FindFolder.java
1
请完成以下Java代码
public boolean isEnableEagerExecutionTreeFetching() { return enableEagerExecutionTreeFetching; } public void setEnableEagerExecutionTreeFetching(boolean enableEagerExecutionTreeFetching) { this.enableEagerExecutionTreeFetching = enableEagerExecutionTreeFetching; } public boolean isEnableExecutionRelationshipCounts() { return enableExecutionRelationshipCounts; } public void setEnableExecutionRelationshipCounts(boolean enableExecutionRelationshipCounts) { this.enableExecutionRelationshipCounts = enableExecutionRelationshipCounts; } public boolean isEnableTaskRelationshipCounts() { return enableTaskRelationshipCounts; } public void setEnableTaskRelationshipCounts(boolean enableTaskRelationshipCounts) { this.enableTaskRelationshipCounts = enableTaskRelationshipCounts; } public boolean isValidateExecutionRelationshipCountConfigOnBoot() { return validateExecutionRelationshipCountConfigOnBoot; } public void setValidateExecutionRelationshipCountConfigOnBoot(boolean validateExecutionRelationshipCountConfigOnBoot) { this.validateExecutionRelationshipCountConfigOnBoot = validateExecutionRelationshipCountConfigOnBoot; }
public boolean isValidateTaskRelationshipCountConfigOnBoot() { return validateTaskRelationshipCountConfigOnBoot; } public void setValidateTaskRelationshipCountConfigOnBoot(boolean validateTaskRelationshipCountConfigOnBoot) { this.validateTaskRelationshipCountConfigOnBoot = validateTaskRelationshipCountConfigOnBoot; } public boolean isEnableLocalization() { return enableLocalization; } public void setEnableLocalization(boolean enableLocalization) { this.enableLocalization = enableLocalization; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\PerformanceSettings.java
1
请完成以下Java代码
public Quantity extractMedianCUQtyPerChildHU(@NonNull final ProductId productId) { if (getChildHUs().isEmpty()) { return getProductQtysInStockUOM().get(productId); } final ImmutableList<BigDecimal> allQuantities = this.getChildHUs() .stream() .filter(hu -> hu.getProductQtysInStockUOM().containsKey(productId)) .map(hu -> hu.getProductQtysInStockUOM().get(productId).toBigDecimal()) .sorted() .collect(ImmutableList.toImmutableList()); final BigDecimal qtyCU = allQuantities.get(allQuantities.size() / 2); return Quantitys.of(qtyCU, productId); } @Nullable
public String getPackagingGTIN(@NonNull final BPartnerId bpartnerId) { final String gtin = packagingGTINs.get(bpartnerId); if (Check.isNotBlank(gtin)) { return gtin; } return packagingGTINs.get(BPartnerId.NONE); } @VisibleForTesting public ImmutableMap<BPartnerId, String> getAllPackaginGTINs() { return ImmutableMap.copyOf(packagingGTINs); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\HU.java
1
请完成以下Java代码
public void onValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueOld, final Object valueNew) { // nothing } /** * @return <code>bull</code> */ @Override public Object generateSeedValue(final IAttributeSet attributeSet, final I_M_Attribute attribute, final Object valueInitialDefault) { return valueInitialDefault; } /** * @return <code>false</code> */ @Override public boolean isReadonlyUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{ return false; } @Override public boolean isAlwaysEditableUI(final IAttributeValueContext ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) { return false; } @Override public boolean isDisplayedUI(final IAttributeSet attributeSet, final I_M_Attribute attribute) { return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\spi\NullAttributeValueCallout.java
1
请完成以下Java代码
public COL getCell(@NonNull final ROW row, @NonNull final String fieldName) { final int fieldIndex = getFieldIndexByName(fieldName); return row.getCols().get(fieldIndex); } private int getFieldIndexByName(final String fieldName) { ImmutableMap<String, Integer> fieldName2FieldIndex = this._fieldName2FieldIndex; if (fieldName2FieldIndex == null) { fieldName2FieldIndex = this._fieldName2FieldIndex = createFieldName2FieldIndexMap(); } final Integer fieldIndex = fieldName2FieldIndex.get(fieldName); if (fieldIndex == null) { throw new IllegalArgumentException("A field with name `" + fieldName + "` is not included in the current file; metadata=" + this);
} return fieldIndex; } private ImmutableMap<String, Integer> createFieldName2FieldIndexMap() { ImmutableMap.Builder<String, Integer> builder = ImmutableMap.<String, Integer> builder(); for (int i = 0, size = fields.size(); i < size; i++) { final String fieldName = fields.get(i).getName(); builder.put(fieldName, i); } return builder.build(); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\METADATA.java
1
请完成以下Java代码
public void setDD_OrderLine_ID (final int DD_OrderLine_ID) { if (DD_OrderLine_ID < 1) set_Value (COLUMNNAME_DD_OrderLine_ID, null); else set_Value (COLUMNNAME_DD_OrderLine_ID, DD_OrderLine_ID); } @Override public int getDD_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_DD_OrderLine_ID); } @Override public void setM_HU_Reservation_ID (final int M_HU_Reservation_ID) { if (M_HU_Reservation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Reservation_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Reservation_ID, M_HU_Reservation_ID); } @Override public int getM_HU_Reservation_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Reservation_ID); } @Override public de.metas.handlingunits.model.I_M_Picking_Job_Step getM_Picking_Job_Step() { return get_ValueAsPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class); } @Override public void setM_Picking_Job_Step(final de.metas.handlingunits.model.I_M_Picking_Job_Step M_Picking_Job_Step) { set_ValueFromPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class, M_Picking_Job_Step); } @Override public void setM_Picking_Job_Step_ID (final int M_Picking_Job_Step_ID) { if (M_Picking_Job_Step_ID < 1) set_Value (COLUMNNAME_M_Picking_Job_Step_ID, null); else set_Value (COLUMNNAME_M_Picking_Job_Step_ID, M_Picking_Job_Step_ID); } @Override public int getM_Picking_Job_Step_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID); } @Override public void setQtyReserved (final BigDecimal QtyReserved) {
set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Reservation.java
1
请完成以下Java代码
private BigDecimal getNetAmount(@NonNull final IQualityInvoiceLine line) { final IPricingResult pricingResult = line.getPrice(); Check.assumeNotNull(pricingResult, "pricingResult not null"); Check.assume(pricingResult.isCalculated(), "Price is calculated for {}", line); final BigDecimal price = pricingResult.getPriceStd(); final UomId priceUomId = pricingResult.getPriceUomId(); final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class); final Quantity qtyInPricingUom = uomConversionBL.convertQuantityTo( line.getQty(), UOMConversionContext.of(line.getProductId()), priceUomId); final CurrencyPrecision pricePrecision = pricingResult.getPrecision(); final BigDecimal netAmt = pricePrecision.round(price.multiply(qtyInPricingUom.toBigDecimal())); return netAmt; }
/** * Creates an {@link QualityInvoiceLine} instance. * <p> * Product, Qty, UOM are copied from given {@link IQualityInspectionLine}. */ private QualityInvoiceLine createQualityInvoiceLine(final IQualityInspectionLine qiLine) { final QualityInvoiceLine invoiceLine = new QualityInvoiceLine(); invoiceLine.setM_Product(qiLine.getM_Product()); invoiceLine.setProductName(qiLine.getName()); invoiceLine.setPercentage(qiLine.getPercentage()); invoiceLine.setQty(Quantity.of(qiLine.getQtyProjected(), qiLine.getC_UOM())); invoiceLine.setHandlingUnitsInfo(qiLine.getHandlingUnitsInfoProjected()); return invoiceLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\invoicing\impl\QualityInvoiceLineGroupsBuilder.java
1
请完成以下Java代码
public void onInit(final InitEvent event) { timeZoneField.setItems(List.of(TimeZone.getAvailableIDs())); } @Subscribe public void onInitEntity(final InitEntityEvent<User> event) { usernameField.setReadOnly(false); passwordField.setVisible(true); confirmPasswordField.setVisible(true); } @Subscribe public void onReady(final ReadyEvent event) { if (entityStates.isNew(getEditedEntity())) { usernameField.focus(); }
} @Subscribe public void onValidation(final ValidationEvent event) { if (entityStates.isNew(getEditedEntity()) && !Objects.equals(passwordField.getValue(), confirmPasswordField.getValue())) { event.getErrors().add(messageBundle.getMessage("passwordsDoNotMatch")); } } @Subscribe protected void onBeforeSave(final BeforeSaveEvent event) { if (entityStates.isNew(getEditedEntity())) { getEditedEntity().setPassword(passwordEncoder.encode(passwordField.getValue())); } } }
repos\tutorials-master\spring-boot-modules\jmix\src\main\java\com\baeldung\jmix\expensetracker\view\user\UserDetailView.java
1
请完成以下Java代码
public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * ResponsibleType AD_Reference_ID=304 * Reference name: WF_Participant Type */ public static final int RESPONSIBLETYPE_AD_Reference_ID=304; /** Organisation = O */ public static final String RESPONSIBLETYPE_Organisation = "O"; /** Human = H */ public static final String RESPONSIBLETYPE_Human = "H";
/** Rolle = R */ public static final String RESPONSIBLETYPE_Rolle = "R"; /** Systemressource = S */ public static final String RESPONSIBLETYPE_Systemressource = "S"; /** Other = X */ public static final String RESPONSIBLETYPE_Other = "X"; @Override public void setResponsibleType (final java.lang.String ResponsibleType) { set_Value (COLUMNNAME_ResponsibleType, ResponsibleType); } @Override public java.lang.String getResponsibleType() { return get_ValueAsString(COLUMNNAME_ResponsibleType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Responsible.java
1
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() {
return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\boot\noconverterfound\model\Student.java
1
请完成以下Java代码
public UserOperationLogQuery operationType(String operationType) { ensureNotNull("operationType", operationType); this.operationType = operationType; return this; } public UserOperationLogQuery property(String property) { ensureNotNull("property", property); this.property = property; return this; } public UserOperationLogQuery entityType(String entityType) { ensureNotNull("entityType", entityType); this.entityType = entityType; return this; } public UserOperationLogQuery entityTypeIn(String... entityTypes) { ensureNotNull("entity types", (Object[]) entityTypes); this.entityTypes = entityTypes; return this; } public UserOperationLogQuery category(String category) { ensureNotNull("category", category); this.category = category; return this; } public UserOperationLogQuery categoryIn(String... categories) { ensureNotNull("categories", (Object[]) categories); this.categories = categories; return this; } public UserOperationLogQuery afterTimestamp(Date after) { this.timestampAfter = after; return this; } public UserOperationLogQuery beforeTimestamp(Date before) { this.timestampBefore = before; return this; } public UserOperationLogQuery orderByTimestamp() { return orderBy(OperationLogQueryProperty.TIMESTAMP);
} public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntryCountByQueryCriteria(this); } public List<UserOperationLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getOperationLogManager() .findOperationLogEntriesByQueryCriteria(this, page); } public boolean isTenantIdSet() { return isTenantIdSet; } public UserOperationLogQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; this.isTenantIdSet = true; return this; } public UserOperationLogQuery withoutTenantId() { this.tenantIds = null; this.isTenantIdSet = true; return this; } @Override protected boolean hasExcludingConditions() { return super.hasExcludingConditions() || CompareUtil.areNotInAscendingOrder(timestampAfter, timestampBefore); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserOperationLogQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
protected <T> T checkNotNull(Optional<T> reference, String notFoundMessage) throws ThingsboardException { if (reference.isPresent()) { return reference.get(); } else { throw new ThingsboardException(notFoundMessage, ThingsboardErrorCode.ITEM_NOT_FOUND); } } protected <I extends EntityId> I emptyId(EntityType entityType) { return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID); } protected ListenableFuture<UUID> autoCommit(User user, EntityId entityId) { if (vcService != null) { return vcService.autoCommit(user, entityId);
} else { // We do not support auto-commit for rule engine return Futures.immediateFailedFuture(new RuntimeException("Operation not supported!")); } } protected ListenableFuture<UUID> autoCommit(User user, EntityType entityType, List<UUID> entityIds) { if (vcService != null) { return vcService.autoCommit(user, entityType, entityIds); } else { // We do not support auto-commit for rule engine return Futures.immediateFailedFuture(new RuntimeException("Operation not supported!")); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\AbstractTbEntityService.java
2
请完成以下Java代码
private static boolean isSkipLogging(@NonNull final Sql sql) { return sql.isEmpty() || isSkipLogging(sql.getSqlCommand()); } private static boolean isSkipLogging(@NonNull final String sqlCommand) { // Always log DDL (flagged) commands if (sqlCommand.startsWith(DDL_PREFIX)) { return false; } final String sqlCommandUC = sqlCommand.toUpperCase().trim(); // // Don't log selects if (sqlCommandUC.startsWith("SELECT ")) { return true; } // // Don't log DELETE FROM Some_Table WHERE AD_Table_ID=? AND Record_ID=? if (sqlCommandUC.startsWith("DELETE FROM ") && sqlCommandUC.endsWith(" WHERE AD_TABLE_ID=? AND RECORD_ID=?"))
{ return true; } // // Check that INSERT/UPDATE/DELETE statements are about our ignored tables final ImmutableSet<String> exceptionTablesUC = Services.get(IMigrationLogger.class).getTablesToIgnoreUC(Env.getClientIdOrSystem()); for (final String tableNameUC : exceptionTablesUC) { if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("DELETE FROM " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("DELETE " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("UPDATE " + tableNameUC + " ")) return true; if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + "(")) return true; } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLoggerHolder.java
1
请完成以下Java代码
public GitIgnoreSection getGeneral() { return this.general; } public GitIgnoreSection getSts() { return this.sts; } public GitIgnoreSection getIntellijIdea() { return this.intellijIdea; } public GitIgnoreSection getNetBeans() { return this.netBeans; } public GitIgnoreSection getVscode() { return this.vscode; } /** * Representation of a section of a {@code .gitignore} file. */ public static class GitIgnoreSection implements Section { private final String name; private final LinkedList<String> items; public GitIgnoreSection(String name) { this.name = name; this.items = new LinkedList<>();
} public void add(String... items) { this.items.addAll(Arrays.asList(items)); } public LinkedList<String> getItems() { return this.items; } @Override public void write(PrintWriter writer) { if (!this.items.isEmpty()) { if (this.name != null) { writer.println(); writer.println(String.format("### %s ###", this.name)); } this.items.forEach(writer::println); } } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitIgnore.java
1
请完成以下Java代码
public class ActivityStartedListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNActivityStartedEvent>> processRuntimeEventListeners; private ToActivityStartedConverter converter; public ActivityStartedListenerDelegate( List<BPMNElementEventListener<BPMNActivityStartedEvent>> processRuntimeEventListeners, ToActivityStartedConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiActivityEvent) {
converter .from((ActivitiActivityEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNActivityStartedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ActivityStartedListenerDelegate.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<Class<? extends ShipmentScheduleUpdatedEvent>> getHandledEventType() { return ImmutableList.of(ShipmentScheduleUpdatedEvent.class); } @Override public void handleEvent(@NonNull final ShipmentScheduleUpdatedEvent event) { final DemandDetailsQuery demandDetailsQuery = DemandDetailsQuery.ofShipmentScheduleId(event.getShipmentScheduleId()); final CandidatesQuery candidatesQuery = CandidatesQuery .builder() .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .demandDetailsQuery(demandDetailsQuery) .build(); final Candidate candidate = candidateRepository.retrieveLatestMatchOrNull(candidatesQuery); final Candidate updatedCandidate; final DemandDetail demandDetail = DemandDetail.forDocumentLine( event.getShipmentScheduleId(), event.getDocumentLineDescriptor(), event.getMaterialDescriptor().getQuantity()); if (candidate == null)
{ updatedCandidate = Candidate .builderForEventDescriptor(event.getEventDescriptor()) .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .type(CandidateType.DEMAND) .businessCase(CandidateBusinessCase.SHIPMENT) .businessCaseDetail(demandDetail) .build(); } else { updatedCandidate = candidate.toBuilder() .materialDescriptor(event.getMaterialDescriptor()) .minMaxDescriptor(event.getMinMaxDescriptor()) .businessCaseDetail(demandDetail) .build(); } candidateChangeHandler.onCandidateNewOrChange(updatedCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\shipmentschedule\ShipmentScheduleUpdatedHandler.java
2
请完成以下Java代码
default String getBirthdate() { return this.getClaimAsString(StandardClaimNames.BIRTHDATE); } /** * Returns the user's time zone {@code (zoneinfo)}. * @return the user's time zone */ default String getZoneInfo() { return this.getClaimAsString(StandardClaimNames.ZONEINFO); } /** * Returns the user's locale {@code (locale)}. * @return the user's locale */ default String getLocale() { return this.getClaimAsString(StandardClaimNames.LOCALE); } /** * Returns the user's preferred phone number {@code (phone_number)}. * @return the user's preferred phone number */ default String getPhoneNumber() { return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER); } /** * Returns {@code true} if the user's phone number has been verified * {@code (phone_number_verified)}, otherwise {@code false}. * @return {@code true} if the user's phone number has been verified, otherwise * {@code false} */ default Boolean getPhoneNumberVerified() { return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED); }
/** * Returns the user's preferred postal address {@code (address)}. * @return the user's preferred postal address */ default AddressStandardClaim getAddress() { Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS); return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build() : new DefaultAddressStandardClaim.Builder().build()); } /** * Returns the time the user's information was last updated {@code (updated_at)}. * @return the time the user's information was last updated */ default Instant getUpdatedAt() { return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java
1
请完成以下Java代码
static String usingCharacterToUpperCaseMethod(String input) { if (input == null || input.isEmpty()) { return null; } return Arrays.stream(input.split("\\s+")) .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1)) .collect(Collectors.joining(" ")); } static String usingStringToUpperCaseMethod(String input) { if (input == null || input.isEmpty()) { return null; }
return Arrays.stream(input.split("\\s+")) .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1)) .collect(Collectors.joining(" ")); } static String usingStringUtilsClass(String input) { if (input == null || input.isEmpty()) { return null; } return Arrays.stream(input.split("\\s+")) .map(StringUtils::capitalize) .collect(Collectors.joining(" ")); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-7\src\main\java\com\baeldung\capitalizefirstcharactereachword\CapitalizeFirstCharacterEachWordUtils.java
1
请完成以下Java代码
public Map<String, List<DmnExtensionAttribute>> getAttributes() { return attributes; } public void setAttributes(Map<String, List<DmnExtensionAttribute>> attributes) { this.attributes = attributes; } public String getAttributeValue(String namespace, String name) { List<DmnExtensionAttribute> attributes = getAttributes().get(name); if (attributes != null && !attributes.isEmpty()) { for (DmnExtensionAttribute attribute : attributes) { if ((namespace == null && attribute.getNamespace() == null) || namespace.equals(attribute.getNamespace())) { return attribute.getValue(); } } } return null; } public void addAttribute(DmnExtensionAttribute attribute) { if (attribute != null && attribute.getName() != null && !attribute.getName().trim().isEmpty()) { List<DmnExtensionAttribute> attributeList = null; if (!this.attributes.containsKey(attribute.getName())) { attributeList = new ArrayList<>(); this.attributes.put(attribute.getName(), attributeList); } this.attributes.get(attribute.getName()).add(attribute); } } public void setValues(DmnElement otherElement) { setId(otherElement.getId()); extensionElements = new LinkedHashMap<>(); if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) { for (String key : otherElement.getExtensionElements().keySet()) { List<DmnExtensionElement> otherElementList = otherElement.getExtensionElements().get(key); if (otherElementList != null && !otherElementList.isEmpty()) {
List<DmnExtensionElement> elementList = new ArrayList<>(); for (DmnExtensionElement extensionElement : otherElementList) { elementList.add(extensionElement.clone()); } extensionElements.put(key, elementList); } } } attributes = new LinkedHashMap<>(); if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) { for (String key : otherElement.getAttributes().keySet()) { List<DmnExtensionAttribute> otherAttributeList = otherElement.getAttributes().get(key); if (otherAttributeList != null && !otherAttributeList.isEmpty()) { List<DmnExtensionAttribute> attributeList = new ArrayList<>(); for (DmnExtensionAttribute extensionAttribute : otherAttributeList) { attributeList.add(extensionAttribute.clone()); } attributes.put(key, attributeList); } } } } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnElement.java
1
请在Spring Boot框架中完成以下Java代码
public List<UserVO> list() { // 查询列表 List<UserVO> result = new ArrayList<>(); result.add(new UserVO().setId(1).setUsername("yudaoyuanma")); result.add(new UserVO().setId(2).setUsername("woshiyutou")); result.add(new UserVO().setId(3).setUsername("chifanshuijiao")); // 返回列表 return result; } /** * 获得指定用户编号的用户 * * @param id 用户编号 * @return 用户 */ @GetMapping("/get") // URL 修改成 /get public UserVO get(@RequestParam("id") Integer id) { // 查询并返回用户 return new UserVO().setId(id).setUsername(UUID.randomUUID().toString()); } /** * 添加用户 * * @param addDTO 添加用户信息 DTO * @return 添加成功的用户编号 */ @PostMapping("add") // URL 修改成 /add public Integer add(UserAddDTO addDTO) { // 插入用户记录,返回编号 Integer returnId = UUID.randomUUID().hashCode(); // 返回用户编号
return returnId; } /** * 更新指定用户编号的用户 * * @param updateDTO 更新用户信息 DTO * @return 是否修改成功 */ @PostMapping("/update") // URL 修改成 /update ,RequestMethod 改成 POST public Boolean update(UserUpdateDTO updateDTO) { // 更新用户记录 Boolean success = true; // 返回更新是否成功 return success; } /** * 删除指定用户编号的用户 * * @param id 用户编号 * @return 是否删除成功 */ @DeleteMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE public Boolean delete(@RequestParam("id") Integer id) { // 删除用户记录 Boolean success = false; // 返回是否更新成功 return success; } }
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\controller\UserController2.java
2
请完成以下Java代码
static String getGroupId() { return KafkaUtils.getConsumerGroupId(); } /** * Set up the common headers. * @param acknowledgment the acknowledgment (can be Acknowledgment or ShareAcknowledgment). * @param consumer the consumer (can be Consumer or ShareConsumer). * @param rawHeaders the raw headers map. * @param theKey the key. * @param topic the topic. * @param partition the partition. * @param offset the offset. * @param timestampType the timestamp type. * @param timestamp the timestamp. */ @SuppressWarnings("NullAway") // Dataflow analysis limitation default void commonHeaders(@Nullable Object acknowledgment, @Nullable Object consumer, Map<String, Object> rawHeaders, @Nullable Object theKey, Object topic, Object partition, Object offset,
@Nullable Object timestampType, Object timestamp) { rawHeaders.put(KafkaHeaders.RECEIVED_TOPIC, topic); rawHeaders.put(KafkaHeaders.RECEIVED_PARTITION, partition); rawHeaders.put(KafkaHeaders.OFFSET, offset); rawHeaders.put(KafkaHeaders.TIMESTAMP_TYPE, timestampType); rawHeaders.put(KafkaHeaders.RECEIVED_TIMESTAMP, timestamp); JavaUtils.INSTANCE .acceptIfNotNull(KafkaHeaders.RECEIVED_KEY, theKey, (key, val) -> rawHeaders.put(key, val)) .acceptIfNotNull(KafkaHeaders.GROUP_ID, MessageConverter.getGroupId(), (key, val) -> rawHeaders.put(key, val)) .acceptIfNotNull(KafkaHeaders.ACKNOWLEDGMENT, acknowledgment, (key, val) -> rawHeaders.put(key, val)) .acceptIfNotNull(KafkaHeaders.CONSUMER, consumer, (key, val) -> rawHeaders.put(key, val)); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\MessageConverter.java
1
请完成以下Java代码
public void addAttributeValueListener(final IAttributeValueListener listener) { // nothing } @Override public List<ValueNamePair> getAvailableValues() { throw new InvalidAttributeValueException("method not supported for " + this); } @Override public IAttributeValuesProvider getAttributeValuesProvider() { throw new InvalidAttributeValueException("method not supported for " + this); } @Override public I_C_UOM getC_UOM() { return null; } @Override public IAttributeValueCallout getAttributeValueCallout() { return NullAttributeValueCallout.instance; } @Override public IAttributeValueGenerator getAttributeValueGeneratorOrNull() { return null; } @Override public void removeAttributeValueListener(final IAttributeValueListener listener) { // nothing } @Override public boolean isReadonlyUI() { return true; }
@Override public boolean isDisplayedUI() { return false; } @Override public boolean isMandatory() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public NamePair getNullAttributeValue() { return null; } /** * @return true; we consider Null attributes as always generated */ @Override public boolean isNew() { return true; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\NullAttributeValue.java
1
请完成以下Java代码
public void setK_IndexStop_ID (int K_IndexStop_ID) { if (K_IndexStop_ID < 1) set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, null); else set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, Integer.valueOf(K_IndexStop_ID)); } /** Get Index Stop. @return Keyword not to be indexed */ public int getK_IndexStop_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexStop_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID)
{ if (R_RequestType_ID < 1) set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_K_IndexStop.java
1
请完成以下Java代码
public class X_M_Allergen_Trl extends org.compiere.model.PO implements I_M_Allergen_Trl, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1742196258L; /** Standard Constructor */ public X_M_Allergen_Trl (final Properties ctx, final int M_Allergen_Trl_ID, @Nullable final String trxName) { super (ctx, M_Allergen_Trl_ID, trxName); } /** Load Constructor */ public X_M_Allergen_Trl (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } /** * AD_Language AD_Reference_ID=106 * Reference name: AD_Language */ public static final int AD_LANGUAGE_AD_Reference_ID=106; @Override public void setAD_Language (final java.lang.String AD_Language) { set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language); } @Override public java.lang.String getAD_Language() { return get_ValueAsString(COLUMNNAME_AD_Language); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated); } @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public org.compiere.model.I_M_Allergen getM_Allergen() { return get_ValueAsPO(COLUMNNAME_M_Allergen_ID, org.compiere.model.I_M_Allergen.class); }
@Override public void setM_Allergen(final org.compiere.model.I_M_Allergen M_Allergen) { set_ValueFromPO(COLUMNNAME_M_Allergen_ID, org.compiere.model.I_M_Allergen.class, M_Allergen); } @Override public void setM_Allergen_ID (final int M_Allergen_ID) { if (M_Allergen_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, M_Allergen_ID); } @Override public int getM_Allergen_ID() { return get_ValueAsInt(COLUMNNAME_M_Allergen_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trl.java
1
请完成以下Java代码
public void setDocTypeInvoicingPoolId(@Nullable final DocTypeInvoicingPoolId docTypeInvoicingPoolId) { this.docTypeInvoicingPoolId = docTypeInvoicingPoolId; } @Override public void setDocTypeInvoiceId(@Nullable final DocTypeId docTypeId) { this.docTypeInvoiceId = docTypeId; } @Override public boolean isTaxIncluded() { return taxIncluded; } public void setTaxIncluded(boolean taxIncluded) { this.taxIncluded = taxIncluded; } /** * Negate all line amounts */ public void negateAllLineAmounts() { for (final IInvoiceCandAggregate lineAgg : getLines()) { lineAgg.negateLineAmounts(); } } /** * Calculates total net amount by summing up all {@link IInvoiceLineRW#getNetLineAmt()}s. * * @return total net amount */ public Money calculateTotalNetAmtFromLines() { final List<IInvoiceCandAggregate> lines = getLines(); Check.assume(lines != null && !lines.isEmpty(), "Invoice {} was not aggregated yet", this); Money totalNetAmt = Money.zero(currencyId); for (final IInvoiceCandAggregate lineAgg : lines) { for (final IInvoiceLineRW line : lineAgg.getAllLines()) { final Money lineNetAmt = line.getNetLineAmt(); totalNetAmt = totalNetAmt.add(lineNetAmt); } } return totalNetAmt; } public void setPaymentTermId(@Nullable final PaymentTermId paymentTermId) { this.paymentTermId = paymentTermId; } @Override public PaymentTermId getPaymentTermId() { return paymentTermId; } public void setPaymentRule(@Nullable final String paymentRule) { this.paymentRule = paymentRule; } @Override public String getPaymentRule() { return paymentRule; } @Override public String getExternalId() { return externalId; } @Override
public int getC_Async_Batch_ID() { return C_Async_Batch_ID; } public void setC_Async_Batch_ID(final int C_Async_Batch_ID) { this.C_Async_Batch_ID = C_Async_Batch_ID; } public String setExternalId(String externalId) { return this.externalId = externalId; } @Override public int getC_Incoterms_ID() { return C_Incoterms_ID; } public void setC_Incoterms_ID(final int C_Incoterms_ID) { this.C_Incoterms_ID = C_Incoterms_ID; } @Override public String getIncotermLocation() { return incotermLocation; } public void setIncotermLocation(final String incotermLocation) { this.incotermLocation = incotermLocation; } @Override public InputDataSourceId getAD_InputDataSource_ID() { return inputDataSourceId;} public void setAD_InputDataSource_ID(final InputDataSourceId inputDataSourceId){this.inputDataSourceId = inputDataSourceId;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceHeaderImpl.java
1
请完成以下Java代码
public void setBPartnerId(@Nullable final BPartnerId bPartnerId) { if (BPartnerId.equals(this.C_BPartner_ID, bPartnerId)) { return; } this.C_BPartner_ID = bPartnerId; this.C_BPartner_Location_ID = null; } @NonNull private BigDecimal computeCurrencyRate() { final BigDecimal amtAcct = getAmtAcctDr().add(getAmtAcctCr()); final BigDecimal amtSource = getAmtSourceDr().add(getAmtSourceCr()); if (amtAcct.signum() == 0 || amtSource.signum() == 0) { return BigDecimal.ZERO; // dev-note: does not matter } final CurrencyPrecision schemaCurrencyPrecision = getAcctSchema().getStandardPrecision(); return amtAcct.divide(amtSource, schemaCurrencyPrecision.toInt(), schemaCurrencyPrecision.getRoundingMode()); } public void updateCurrencyRateIfNotSet() { if (getCurrencyRate().signum() == 0 || getCurrencyRate().compareTo(BigDecimal.ONE) == 0) { updateCurrencyRate(); } } public void updateCurrencyRate() { setCurrencyRate(computeCurrencyRate()); } public void setTaxIdAndUpdateVatCode(@Nullable final TaxId taxId) { if (TaxId.equals(this.taxId, taxId)) { return; } this.taxId = taxId; this.vatCode = computeVATCode().map(VATCode::getCode).orElse(null); } private Optional<VATCode> computeVATCode()
{ if (taxId == null) { return Optional.empty(); } final boolean isSOTrx = m_docLine != null ? m_docLine.isSOTrx() : m_doc.isSOTrx(); return services.findVATCode(VATCodeMatchingRequest.builder() .setC_AcctSchema_ID(getAcctSchemaId().getRepoId()) .setC_Tax_ID(taxId.getRepoId()) .setIsSOTrx(isSOTrx) .setDate(this.dateAcct) .build()); } public void updateFAOpenItemTrxInfo() { if (openItemTrxInfo != null) { return; } this.openItemTrxInfo = services.computeOpenItemTrxInfo(this).orElse(null); } void setOpenItemTrxInfo(@Nullable final FAOpenItemTrxInfo openItemTrxInfo) { this.openItemTrxInfo = openItemTrxInfo; } public void updateFrom(@NonNull FactAcctChanges changes) { setAmtSource(changes.getAmtSourceDr(), changes.getAmtSourceCr()); setAmtAcct(changes.getAmtAcctDr(), changes.getAmtAcctCr()); updateCurrencyRate(); if (changes.getAccountId() != null) { this.accountId = changes.getAccountId(); } setTaxIdAndUpdateVatCode(changes.getTaxId()); setDescription(changes.getDescription()); this.M_Product_ID = changes.getProductId(); this.userElementString1 = changes.getUserElementString1(); this.C_OrderSO_ID = changes.getSalesOrderId(); this.C_Activity_ID = changes.getActivityId(); this.appliedUserChanges = changes; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLine.java
1
请完成以下Java代码
private void handleBroadcast(Message message, ChannelHandlerContext context) { final String channelId = id(context.channel()); System.out.printf("[clients: %d] message: %s\n", clients.size(), message); clients.forEach((id, channel) -> { if (!id.equals(channelId)) { ChannelFuture relay = channel.writeAndFlush(message.toString()); relay.addListener(new ChannelInfoListener("message relayed to " + id)); } }); history.add(message.toString() + "\n"); if (history.size() > MAX_HISTORY) history.poll(); } @Override public void channelRead0(ChannelHandlerContext context, String msg) { handleBroadcast(Message.parse(msg), context); } @Override public void channelActive(final ChannelHandlerContext context) { Channel channel = context.channel(); clients.put(id(channel), channel); history.forEach(channel::writeAndFlush);
handleBroadcast(new OnlineMessage(id(channel)), context); } @Override public void channelInactive(ChannelHandlerContext context) { Channel channel = context.channel(); clients.remove(id(channel)); handleBroadcast(new OfflineMessage(id(channel)), context); } private static String id(Channel channel) { return channel.id() .asShortText(); } }
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\netty\customhandlersandlisteners\handler\ServerEventHandler.java
1
请完成以下Java代码
public void onGetAttributesResponse(TransportProtos.GetAttributeResponseMsg getAttributesResponse) { logUnsupportedCommandMessage(getAttributesResponse); } @Override public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg attributeUpdateNotification) { logUnsupportedCommandMessage(attributeUpdateNotification); } @Override public void onRemoteSessionCloseCommand(UUID sessionId, TransportProtos.SessionCloseNotificationProto sessionCloseNotification) { } @Override public void onDeviceDeleted(DeviceId deviceId) { } @Override public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg toDeviceRequest) { logUnsupportedCommandMessage(toDeviceRequest); } @Override public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg toServerResponse) { logUnsupportedCommandMessage(toServerResponse); } private void logUnsupportedCommandMessage(Object update) { log.trace("[{}] Ignore unsupported update: {}", state.getDeviceId(), update); } public static boolean isConRequest(TbCoapObservationState state) { if (state != null) { return state.getExchange().advanced().getRequest().isConfirmable(); } else {
return false; } } public static boolean isMulticastRequest(TbCoapObservationState state) { if (state != null) { return state.getExchange().advanced().getRequest().isMulticast(); } return false; } protected void respond(Response response) { response.getOptions().setContentFormat(TbCoapContentFormatUtil.getContentFormat(exchange.getRequestOptions().getContentFormat(), state.getContentFormat())); response.setConfirmable(exchange.advanced().getRequest().isConfirmable()); exchange.respond(response); } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\callback\AbstractSyncSessionCallback.java
1
请完成以下Java代码
public static int usingSinglePassThrough(int[] arr) { int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; for (int num : arr) { if (num < smallest) { secondSmallest = smallest; smallest = num; } else if (num < secondSmallest && num != smallest) { secondSmallest = num; } } if (secondSmallest == Integer.MAX_VALUE) { return -1; } else { return secondSmallest; } }
public static int usingMinHeap(int[] arr) { if (arr.length < 2) { return -1; } PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for (int num : arr) { if (minHeap.isEmpty() || num != minHeap.peek()) { minHeap.offer(num); } } // Check if the heap less than 2 (all elements were the same) if (minHeap.size() < 2) { return -1; } minHeap.poll(); // Remove the smallest element return minHeap.peek(); // Second smallest element is at the root (peek) } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\secondsmallest\FindSecondSmallestNumber.java
1
请完成以下Java代码
public void showCodeSnippetFormattingUsingCodeTag() { // do nothing } /** * This is an example to show issue faced while using annotations in Javadocs * * <pre> * * public class Application(){ * @Getter * {@code List<Integer> nums = new ArrayList<>(); } * } * * </pre> */ public void showCodeSnippetFormattingIssueUsingCodeTag() { // do nothing } /** * This is an example to show usage of javadoc code tag for handling '@' character * * <pre> * * public class Application(){ * {@code @Getter} * {@code List<Integer> nums = new ArrayList<>(); } * } * * </pre> */ public void showCodeSnippetAnnotationFormattingUsingCodeTag() { // do nothing } /** * This is an example to show difference in javadoc literal and code tag * * <p> * * {@literal @Getter} * {@literal List<Integer> nums = new ArrayList<>(); } * * <br /> * {@code @Getter} * {@code List<Integer> nums = new ArrayList<>(); } * </p> */ public void showCodeSnippetCommentsFormattingUsingCodeAndLiteralTag() { // do nothing } /**
* This is an example to illustrate a basic jQuery code snippet embedded in documentation comments * <pre> * {@code <script>} * $document.ready(function(){ * console.log("Hello World!); * }) * {@code </script>} * </pre> */ public void showJSCodeSnippetUsingJavadoc() { // do nothing } /** * This is an example to illustrate an HTML code snippet embedded in documentation comments * <pre>{@code * <html> * <body> * <h1>Hello World!</h1> * </body> * </html>} * </pre> * */ public void showHTMLCodeSnippetUsingJavadoc() { // do nothing } /** * This is an example to illustrate an HTML code snippet embedded in documentation comments * <pre> * <html> * <body> * <h1>Hello World!</h1> * </body> * </html> * </pre> * */ public void showHTMLCodeSnippetIssueUsingJavadoc() { // do nothing } }
repos\tutorials-master\core-java-modules\core-java-documentation\src\main\java\com\baeldung\javadoc\CodeSnippetFormatting.java
1
请在Spring Boot框架中完成以下Java代码
public class WorkplaceUserAssignRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<UserId, Optional<WorkplaceId>> byUserId = CCache.<UserId, Optional<WorkplaceId>>builder() .tableName(I_C_Workplace_User_Assign.Table_Name) .build(); @NonNull public Optional<WorkplaceId> getWorkplaceIdByUserId(@NonNull final UserId userId) { return byUserId.getOrLoad(userId, this::retrieveWorkplaceIdByUserId); } @NonNull private Optional<WorkplaceId> retrieveWorkplaceIdByUserId(@NonNull final UserId userId) { return retrieveActiveRecordByUserId(userId).map(WorkplaceUserAssignRepository::extractWorkplaceId); } private static WorkplaceId extractWorkplaceId(final I_C_Workplace_User_Assign record) {return WorkplaceId.ofRepoId(record.getC_Workplace_ID());} @NonNull private Optional<I_C_Workplace_User_Assign> retrieveActiveRecordByUserId(final @NonNull UserId userId)
{ return queryBL.createQueryBuilder(I_C_Workplace_User_Assign.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Workplace_User_Assign.COLUMNNAME_AD_User_ID, userId) .create() .firstOnlyOptional(I_C_Workplace_User_Assign.class); } public void create(@NonNull final WorkplaceAssignmentCreateRequest request) { final UserId userId = request.getUserId(); final WorkplaceId workplaceId = request.getWorkplaceId(); final I_C_Workplace_User_Assign record = retrieveActiveRecordByUserId(userId) .orElseGet(() -> InterfaceWrapperHelper.newInstance(I_C_Workplace_User_Assign.class)); record.setIsActive(true); record.setAD_User_ID(userId.getRepoId()); record.setC_Workplace_ID(workplaceId.getRepoId()); InterfaceWrapperHelper.save(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceUserAssignRepository.java
2
请完成以下Java代码
public String greet() { Outer anonymous = new Outer() { @Override public String greet() { return "Running Anonymous Class..."; } }; return anonymous.greet(); } // Anonymous inner class implementing an interface public String greet(String name) { HelloWorld helloWorld = new HelloWorld() { @Override public String greet(String name) { return "Welcome to " + name; } }; return helloWorld.greet(name); } // Anonymous inner class implementing nested interface public String greetSomeone(String name) { HelloSomeone helloSomeOne = new HelloSomeone() { @Override public String greet(String name) { return "Hello " + name; } }; return helloSomeOne.greet(name); } // Nested interface within a class interface HelloOuter { public String hello(String name); } // Enum within a class enum Color { RED, GREEN, BLUE; } } interface HelloWorld { public String greet(String name); // Nested class within an interface class InnerClass implements HelloWorld { @Override public String greet(String name) { return "Inner class within an interface"; } }
// Nested interface within an interfaces interface HelloSomeone { public String greet(String name); } // Enum within an interface enum Directon { NORTH, SOUTH, EAST, WEST; } } enum Level { LOW, MEDIUM, HIGH; } enum Foods { DRINKS, EATS; // Enum within Enum enum DRINKS { APPLE_JUICE, COLA; } enum EATS { POTATO, RICE; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-types-3\src\main\java\com\baeldung\classfile\Outer.java
1
请完成以下Java代码
public final boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public final int hashCode() { String key = getKey(); Object value = getValue(); return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } }; } public void remove() { iterator.remove(); } }; } public int size() { return variables.size(); } }; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("{\n"); for (Entry<String, TypedValue> variable : variables.entrySet()) { stringBuilder.append(" "); stringBuilder.append(variable.getKey()); stringBuilder.append(" => "); stringBuilder.append(variable.getValue()); stringBuilder.append("\n"); } stringBuilder.append("}"); return stringBuilder.toString(); }
public boolean equals(Object obj) { return asValueMap().equals(obj); } public int hashCode() { return asValueMap().hashCode(); } public Map<String, Object> asValueMap() { return new HashMap<String, Object>(this); } public TypedValue resolve(String variableName) { return getValueTyped(variableName); } public boolean containsVariable(String variableName) { return containsKey(variableName); } public VariableContext asVariableContext() { return this; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\VariableMapImpl.java
1
请完成以下Java代码
public void setM_Material_Tracking_Ref_ID (int M_Material_Tracking_Ref_ID) { if (M_Material_Tracking_Ref_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Ref_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Ref_ID, Integer.valueOf(M_Material_Tracking_Ref_ID)); } /** Get Material Tracking Reference. @return Material Tracking Reference */ @Override public int getM_Material_Tracking_Ref_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Ref_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bewegungsdatum. @param MovementDate Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde */ @Override public void setMovementDate (java.sql.Timestamp MovementDate) { throw new IllegalArgumentException ("MovementDate is virtual column"); } /** Get Bewegungsdatum. @return Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde */ @Override public java.sql.Timestamp getMovementDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_MovementDate); } /** 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 BigDecimal.ZERO; return bd; } /** Set Empfangene Menge. @param QtyReceived Empfangene Menge */ @Override public void setQtyReceived (java.math.BigDecimal QtyReceived)
{ throw new IllegalArgumentException ("QtyReceived is virtual column"); } /** Get Empfangene Menge. @return Empfangene Menge */ @Override public java.math.BigDecimal getQtyReceived () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived); 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_Value (COLUMNNAME_Record_ID, null); else set_Value (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(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\model\X_M_Material_Tracking_Ref.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public Long getMemberLevelId() { return memberLevelId; } public void setMemberLevelId(Long memberLevelId) { this.memberLevelId = memberLevelId; } public BigDecimal getMemberPrice() { return memberPrice; } public void setMemberPrice(BigDecimal memberPrice) { this.memberPrice = memberPrice; } public String getMemberLevelName() { return memberLevelName; } public void setMemberLevelName(String memberLevelName) { this.memberLevelName = memberLevelName; }
@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(", productId=").append(productId); sb.append(", memberLevelId=").append(memberLevelId); sb.append(", memberPrice=").append(memberPrice); sb.append(", memberLevelName=").append(memberLevelName); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsMemberPrice.java
1
请完成以下Java代码
private I_C_BPartner_Location computeHandoverLocationOverride(@NonNull final I_C_OLCand olCand) { final BPartnerId handOverPartnerOverrideId = BPartnerId.ofRepoIdOrNull(olCand.getHandOver_Partner_Override_ID()); if (handOverPartnerOverrideId == null) { // in case the handover bpartner Override was deleted, also delete the handover Location Override return null; } else { final I_C_BPartner partner = olCandEffectiveValuesBL.getC_BPartner_Effective(olCand); final I_C_BPartner handoverPartnerOverride = bPartnerDAO.getById(handOverPartnerOverrideId); final I_C_BP_Relation handoverRelation = bpRelationDAO.retrieveHandoverBPRelation(partner, handoverPartnerOverride); if (handoverRelation == null) { // this shall never happen, since both Handover_BPartner and Handover_BPartner_Override must come from such a bpp relation. // but I will leave this condition here as extra safety return null; } else
{ final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(handoverRelation.getC_BPartnerRelation_ID(), handoverRelation.getC_BPartnerRelation_Location_ID()); return bPartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId); } } } private static void setHandOverLocationOverride( @NonNull final I_C_OLCand olCand, @Nullable final I_C_BPartner_Location handOverLocation) { olCand.setHandOver_Location_Override_ID(handOverLocation != null ? handOverLocation.getC_BPartner_Location_ID() : -1); olCand.setHandOver_Location_Override_Value_ID(handOverLocation != null ? handOverLocation.getC_Location_ID() : -1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\OLCandLocationsUpdaterService.java
1
请完成以下Java代码
public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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 Interest Area. @param R_InterestArea_ID Interest Area or Topic */
public void setR_InterestArea_ID (int R_InterestArea_ID) { if (R_InterestArea_ID < 1) set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null); else set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID)); } /** Get Interest Area. @return Interest Area or Topic */ public int getR_InterestArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_InterestArea.java
1
请在Spring Boot框架中完成以下Java代码
public class Client { @Id @GeneratedValue private Long id; private String name; private String email; public Client() { } public Client(String name, String email) { this.name = name; this.email = email; } public Client(Long id, String name, String email) { this.id = id; this.name = name; this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\spring-boot-modules\spring-boot-react\src\main\java\com\baeldung\springbootreact\domain\Client.java
2
请完成以下Java代码
public class PMMMessageDAO implements IPMMMessageDAO { public List<I_PMM_Message> retrieveMessages(final Properties ctx) { return Services.get(IQueryBL.class) .createQueryBuilder(I_PMM_Message.class, ctx, ITrx.TRXNAME_ThreadInherited) .addOnlyActiveRecordsFilter() // .orderBy() .addColumn(I_PMM_Message.COLUMNNAME_PMM_Message_ID) .endOrderBy() // .create() .list(); } @Override public String retrieveMessagesAsString(final Properties ctx) { final StringBuilder messages = new StringBuilder(); for (final I_PMM_Message pmmMessage : retrieveMessages(ctx)) {
final String message = pmmMessage.getMsgText(); if (Check.isEmpty(message, true)) { continue; } if (messages.length() > 0) { messages.append("\n"); } messages.append(message.trim()); } return messages.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMMMessageDAO.java
1
请在Spring Boot框架中完成以下Java代码
public class Service { /** * Factory method to construct a new {@link Service} initialized with a {@link String name}. * * @param name {@link String} containing the name of the {@link Service}. * @return a new {@link Service} configured with the given {@link String name}. * @throws IllegalArgumentException if the {@link String name} is {@literal null} or empty. * @see #Service(String) */ public static Service with(String name) { return new Service(name); } private final String name; /** * Constructs a new {@link Service} initialized with a {@link String name}. * * @param name {@link String} containing the name of the {@link Service}. * @throws IllegalArgumentException if the {@link String name} is {@literal null} or empty. */ Service(String name) { Assert.hasText(name, String.format("Service name [%s] is required", name)); this.name = name; }
/** * Returns the {@link String name} of this {@link Service}. * * @return this {@link Service Service's} {@link String name}. */ public String getName() { return this.name; } @Override public String toString() { return getName(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\support\Service.java
2
请完成以下Java代码
private List<DictModel> virtualDictData() { List<DictModel> dict = new ArrayList<>(); dict.add(new DictModel("bj", "北京")); dict.add(new DictModel("sd", "山东")); dict.add(new DictModel("ah", "安徽")); return dict; } /** * Online表单 http 增强,add、edit增强示例 * @param params * @return */ @PostMapping("/enhanceJavaHttp") public Result<?> enhanceJavaHttp(@RequestBody JSONObject params) { log.info(" --- params:" + params.toJSONString()); String tableName = params.getString("tableName"); JSONObject record = params.getJSONObject("record"); /* * 业务场景一: 获取提交表单数据,进行其他业务关联操作 * (比如:根据入库单,同步更改库存) */ log.info(" --- tableName:" + tableName); log.info(" --- 行数据:" + record.toJSONString()); /* * 业务场景二: 保存数据之前进行数据的校验 * 直接返回错误状态即可
*/ String phone = record.getString("phone"); if (oConvertUtils.isEmpty(phone)) { return Result.error("手机号不能为空!"); } /* * 业务场景三: 保存数据之对数据的处理 * 直接操作 record 即可 */ record.put("phone", "010-" + phone); /* 其他业务场景自行实现 */ // 返回场景一: 不对 record 做任何修改的情况下,可以直接返回 code, // 返回 0 = 丢弃当前数据 // 返回 1 = 新增当前数据 // 返回 2 = 修改当前数据 TODO(?)存疑 // return Result.OK(1); // 返回场景二: 需要对 record 做修改的情况下,需要返回一个JSONObject对象(或者Map也行) JSONObject res = new JSONObject(); res.put("code", 1); // 将 record 返回以进行修改 res.put("record", record); // TODO 不要 code 的概念 return Result.OK(res); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\online\OnlCgformDemoController.java
1
请在Spring Boot框架中完成以下Java代码
private static IPricingContext createBasePricingSystemPricingCtx(@NonNull final IPricingContext pricingCtx, @NonNull final PricingSystemId basePricingSystemId) { Check.assumeNotNull(pricingCtx.getCountryId(), "Given pricingCtx needs to have a country-ID, so we can later dedic the priceListId! pricingCtx={}", pricingCtx); final IEditablePricingContext newPricingCtx = pricingCtx.copy(); newPricingCtx.setPricingSystemId(basePricingSystemId); newPricingCtx.setPriceListId(null); // will be recomputed newPricingCtx.setPriceListVersionId(null); // will be recomputed newPricingCtx.setSkipCheckingPriceListSOTrxFlag(false); newPricingCtx.setDisallowDiscount(true); newPricingCtx.setFailIfNotCalculated(); return newPricingCtx; } private void computeDiscountForPricingConditionsBreak(final PricingConditionsResultBuilder result, final PricingConditionsBreak pricingConditionsBreak) { final Percent discount; if (pricingConditionsBreak.isBpartnerFlatDiscount()) { discount = request.getBpartnerFlatDiscount(); } else {
discount = pricingConditionsBreak.getDiscount(); } result.discount(discount); } private PricingConditionsBreak findMatchingPricingConditionBreak() { if (request.getForcePricingConditionsBreak() != null) { return request.getForcePricingConditionsBreak(); } else { final PricingConditions pricingConditions = getPricingConditions(); return pricingConditions.pickApplyingBreak(request.getPricingConditionsBreakQuery()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\impl\CalculatePricingConditionsCommand.java
2
请完成以下Java代码
public String asDoc() { Check.assume(Type.DOC.equals(type), "The type of this instance needs to be {}; this={}", Type.DOC, this); return value; } public String asValue() { Check.assume(Type.VALUE.equals(type), "The type of this instance needs to be {}; this={}", Type.VALUE, this); return value; } public String asInternalName() { Check.assume(Type.INTERNALNAME.equals(type), "The type of this instance needs to be {}; this={}", Type.INTERNALNAME, this); return value; }
public boolean isMetasfreshId() { return Type.METASFRESH_ID.equals(type); } public boolean isExternalId() { return Type.EXTERNAL_ID.equals(type); } public boolean isValue() { return Type.VALUE.equals(type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\IdentifierString.java
1
请完成以下Java代码
private static RoleIndexConfigEnum getEnumByCode(String roleCode) { for (RoleIndexConfigEnum e : RoleIndexConfigEnum.values()) { if (e.roleCode.equals(roleCode)) { return e; } } return null; } /** * 根据code找index * @param roleCode 角色编码 * @return */ private static String getIndexByCode(String roleCode) { for (RoleIndexConfigEnum e : RoleIndexConfigEnum.values()) { if (e.roleCode.equals(roleCode)) { return e.componentUrl; } } return null; } public static String getIndexByRoles(List<String> roles) { String[] rolesArray = roles.toArray(new String[roles.size()]); for (RoleIndexConfigEnum e : RoleIndexConfigEnum.values()) { if (oConvertUtils.isIn(e.roleCode,rolesArray)){ return e.componentUrl;
} } return null; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public String getComponentUrl() { return componentUrl; } public void setComponentUrl(String componentUrl) { this.componentUrl = componentUrl; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\RoleIndexConfigEnum.java
1
请在Spring Boot框架中完成以下Java代码
public static Instant asInstantNotNull(@NonNull final String offsetDateTime) { return Instant.parse(offsetDateTime); } @Nullable public static Instant asInstant(@Nullable final OffsetDateTime offsetDateTime) { if (offsetDateTime == null) { return null; } // we can't loose the millis. final long millis = offsetDateTime.toEpochSecond() * 1000 + offsetDateTime.getLong(MILLI_OF_SECOND); return Instant.ofEpochMilli(millis); } @Nullable public static LocalDate asJavaLocalDate(@Nullable final org.threeten.bp.LocalDate localDate) { if (localDate == null) { return null; } return LocalDate.ofEpochDay(localDate.getLong(EPOCH_DAY)); } @Nullable public static org.threeten.bp.LocalDate fromJavaLocalDate(@Nullable final LocalDate localDate)
{ if (localDate == null) { return null; } return org.threeten.bp.LocalDate.ofEpochDay(localDate.toEpochDay()); } @Nullable public static List<BigDecimal> asBigDecimalIds(@Nullable final List<String> ids) { if (ids == null || ids.isEmpty()) { return null; } return ids.stream() .map(BigDecimal::new) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\common\AlbertaUtil.java
2
请完成以下Java代码
public de.metas.contracts.model.I_C_Flatrate_DataEntry getC_Flatrate_DataEntry() { return get_ValueAsPO(COLUMNNAME_C_Flatrate_DataEntry_ID, de.metas.contracts.model.I_C_Flatrate_DataEntry.class); } @Override public void setC_Flatrate_DataEntry(final de.metas.contracts.model.I_C_Flatrate_DataEntry C_Flatrate_DataEntry) { set_ValueFromPO(COLUMNNAME_C_Flatrate_DataEntry_ID, de.metas.contracts.model.I_C_Flatrate_DataEntry.class, C_Flatrate_DataEntry); } @Override public void setC_Flatrate_DataEntry_ID (final int C_Flatrate_DataEntry_ID) { if (C_Flatrate_DataEntry_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_DataEntry_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_DataEntry_ID, C_Flatrate_DataEntry_ID); } @Override public int getC_Flatrate_DataEntry_ID() { return get_ValueAsInt(COLUMNNAME_C_Flatrate_DataEntry_ID); } @Override public void setC_UOM_ID (final int C_UOM_ID) { if (C_UOM_ID < 1) set_Value (COLUMNNAME_C_UOM_ID, null); else set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID); } @Override public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public org.compiere.model.I_M_AttributeSetInstance getM_AttributeSetInstance() { return get_ValueAsPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class); } @Override public void setM_AttributeSetInstance(final org.compiere.model.I_M_AttributeSetInstance M_AttributeSetInstance) { set_ValueFromPO(COLUMNNAME_M_AttributeSetInstance_ID, org.compiere.model.I_M_AttributeSetInstance.class, M_AttributeSetInstance); } @Override public void setM_AttributeSetInstance_ID (final int M_AttributeSetInstance_ID) {
if (M_AttributeSetInstance_ID < 0) set_Value (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_Value (COLUMNNAME_M_AttributeSetInstance_ID, M_AttributeSetInstance_ID); } @Override public int getM_AttributeSetInstance_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID); } @Override public void setQty_Reported (final @Nullable BigDecimal Qty_Reported) { set_Value (COLUMNNAME_Qty_Reported, Qty_Reported); } @Override public BigDecimal getQty_Reported() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry_Detail.java
1
请完成以下Java代码
public void setAttributeName (final java.lang.String AttributeName) { set_Value (COLUMNNAME_AttributeName, AttributeName); } @Override public java.lang.String getAttributeName() { return get_ValueAsString(COLUMNNAME_AttributeName); } @Override public void setAttributeValue (final java.lang.String AttributeValue) { set_Value (COLUMNNAME_AttributeValue, AttributeValue); } @Override public java.lang.String getAttributeValue() { return get_ValueAsString(COLUMNNAME_AttributeValue); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); }
@Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; @Override public void setEntityType (final java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } @Override public java.lang.String getEntityType() { return get_ValueAsString(COLUMNNAME_EntityType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Para.java
1
请在Spring Boot框架中完成以下Java代码
private static final class IssuerResolver { private final String issuer; private final Set<String> endpointUris; private IssuerResolver(AuthorizationServerSettings authorizationServerSettings) { if (authorizationServerSettings.getIssuer() != null) { this.issuer = authorizationServerSettings.getIssuer(); this.endpointUris = Collections.emptySet(); } else { this.issuer = null; this.endpointUris = new HashSet<>(); this.endpointUris.add("/.well-known/oauth-authorization-server"); this.endpointUris.add("/.well-known/openid-configuration"); for (Map.Entry<String, Object> setting : authorizationServerSettings.getSettings().entrySet()) { if (setting.getKey().endsWith("-endpoint")) { this.endpointUris.add((String) setting.getValue()); } } } } private String resolve(HttpServletRequest request) { if (this.issuer != null) { return this.issuer; } // Resolve Issuer Identifier dynamically from request String path = request.getRequestURI(); if (!StringUtils.hasText(path)) { path = ""; } else { for (String endpointUri : this.endpointUris) { if (path.contains(endpointUri)) { path = path.replace(endpointUri, ""); break; } } } // @formatter:off return UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request)) .replacePath(path) .replaceQuery(null) .fragment(null) .build() .toUriString();
// @formatter:on } } private static final class DefaultAuthorizationServerContext implements AuthorizationServerContext { private final String issuer; private final AuthorizationServerSettings authorizationServerSettings; private DefaultAuthorizationServerContext(String issuer, AuthorizationServerSettings authorizationServerSettings) { this.issuer = issuer; this.authorizationServerSettings = authorizationServerSettings; } @Override public String getIssuer() { return this.issuer; } @Override public AuthorizationServerSettings getAuthorizationServerSettings() { return this.authorizationServerSettings; } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\AuthorizationServerContextFilter.java
2
请完成以下Java代码
public void setIsOneQRCodeForAggregatedHUs (final boolean IsOneQRCodeForAggregatedHUs) { set_Value (COLUMNNAME_IsOneQRCodeForAggregatedHUs, IsOneQRCodeForAggregatedHUs); } @Override public boolean isOneQRCodeForAggregatedHUs() { return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForAggregatedHUs); } @Override public void setIsOneQRCodeForMatchingAttributes (final boolean IsOneQRCodeForMatchingAttributes) { set_Value (COLUMNNAME_IsOneQRCodeForMatchingAttributes, IsOneQRCodeForMatchingAttributes); } @Override public boolean isOneQRCodeForMatchingAttributes() { return get_ValueAsBoolean(COLUMNNAME_IsOneQRCodeForMatchingAttributes); } @Override public void setName (final String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public String getName() { return get_ValueAsString(COLUMNNAME_Name); }
@Override public void setQRCode_Configuration_ID (final int QRCode_Configuration_ID) { if (QRCode_Configuration_ID < 1) set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, null); else set_ValueNoCheck (COLUMNNAME_QRCode_Configuration_ID, QRCode_Configuration_ID); } @Override public int getQRCode_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_QRCode_Configuration_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_QRCode_Configuration.java
1
请完成以下Java代码
public void addInfosAndMonitorSpan( @NonNull final Event event, @NonNull final Topic topic, @NonNull final Consumer<Event> enqueueEvent) { final Event.Builder eventToSendBuilder = event.toBuilder(); final PerformanceMonitoringService.Metadata request = PerformanceMonitoringService.Metadata.builder() .type(de.metas.monitoring.adapter.PerformanceMonitoringService.Type.EVENTBUS_REMOTE_ENDPOINT) .className("EventBus") .functionName("enqueueEvent") .label("de.metas.event.distributed-event.senderId", event.getSenderId()) .label("de.metas.event.distributed-event.topicName", topic.getName()) .build(); perfMonService.monitor( () -> enqueueEvent.accept(eventToSendBuilder.build()), request); } public void extractInfosAndMonitor( @NonNull final Event event, @NonNull final Topic topic,
@NonNull final Runnable processEvent) { final PerformanceMonitoringService.Metadata metadata = PerformanceMonitoringService.Metadata.builder() .className("RabbitMQEventBusRemoteEndpoint") .functionName("onEvent") .type(de.metas.monitoring.adapter.PerformanceMonitoringService.Type.EVENTBUS_REMOTE_ENDPOINT) .label("de.metas.event.remote-event.senderId", event.getSenderId()) .label("de.metas.event.remote-event.topicName", topic.getName()) .build(); perfMonService.monitor( processEvent, metadata); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBusMonitoringService.java
1
请完成以下Java代码
private IDocumentLUTUConfigurationManager getLUTUConfigurationManager() { if (_lutuConfigurationManager == null) { final List<I_M_InOutLine> inOutLines = getInOutLines(); _lutuConfigurationManager = huInOutBL.createLUTUConfigurationManager(inOutLines); markNotConfigurable(); } return _lutuConfigurationManager; } /** * @return the LU/TU configuration to be used when generating HUs. */ private I_M_HU_LUTU_Configuration getM_HU_LUTU_Configuration() { if (_lutuConfiguration != null) { return _lutuConfiguration; } _lutuConfiguration = getLUTUConfigurationManager().getCurrentLUTUConfigurationOrNull(); Check.assumeNotNull(_lutuConfiguration, "_lutuConfiguration not null"); markNotConfigurable(); return _lutuConfiguration; } private ILUTUProducerAllocationDestination getLUTUProducerAllocationDestination() { if (_lutuProducer != null)
{ return _lutuProducer; } final I_M_HU_LUTU_Configuration lutuConfiguration = getM_HU_LUTU_Configuration(); _lutuProducer = lutuConfigurationFactory.createLUTUProducerAllocationDestination(lutuConfiguration); markNotConfigurable(); return _lutuProducer; } CustomerReturnLineHUGenerator setIHUTrxListeners(@NonNull final List<IHUTrxListener> customerListeners) { assertConfigurable(); this._customerListeners = ImmutableList.copyOf(customerListeners); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnLineHUGenerator.java
1
请完成以下Java代码
public int getSeatingCapacity() { return seatingCapacity; } public void setSeatingCapacity(int seatingCapacity) { this.seatingCapacity = seatingCapacity; } public double getTopSpeed() { return topSpeed; } public void setTopSpeed(double topSpeed) { this.topSpeed = topSpeed; } } public static class Sedan extends Car { public Sedan() { } public Sedan(String make, String model, int seatingCapacity, double topSpeed) { super(make, model, seatingCapacity, topSpeed); } }
public static class Crossover extends Car { private double towingCapacity; public Crossover() { } public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) { super(make, model, seatingCapacity, topSpeed); this.towingCapacity = towingCapacity; } public double getTowingCapacity() { return towingCapacity; } public void setTowingCapacity(double towingCapacity) { this.towingCapacity = towingCapacity; } } }
repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\IgnoranceAnnotationStructure.java
1
请完成以下Java代码
public class TransactionalMessageProducer { private static final String DATA_MESSAGE_1 = "Put any space separated data here for count"; private static final String DATA_MESSAGE_2 = "Output will contain count of every word in the message"; public static void main(String[] args) { KafkaProducer<String, String> producer = createKafkaProducer(); producer.initTransactions(); try { producer.beginTransaction(); Stream.of(DATA_MESSAGE_1, DATA_MESSAGE_2) .forEach(s -> producer.send(new ProducerRecord<String, String>("input", null, s))); producer.commitTransaction(); } catch (KafkaException e) { producer.abortTransaction();
} } private static KafkaProducer<String, String> createKafkaProducer() { Properties props = new Properties(); props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ENABLE_IDEMPOTENCE_CONFIG, "true"); props.put(TRANSACTIONAL_ID_CONFIG, "prod-0"); props.put(KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); props.put(VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); return new KafkaProducer(props); } }
repos\tutorials-master\apache-kafka\src\main\java\com\baeldung\kafka\exactlyonce\TransactionalMessageProducer.java
1
请在Spring Boot框架中完成以下Java代码
public static void assertCanEdit(final Document document, final IUserRolePermissions permissions) { final BooleanWithReason canEdit = checkCanEdit(document, permissions); if (canEdit.isFalse()) { throw DocumentPermissionException.of(DocumentPermission.Update, canEdit.getReason()); } } public static boolean canEdit(final Document document, final IUserRolePermissions permissions) { final BooleanWithReason canEdit = checkCanEdit(document, permissions); return canEdit.isTrue(); } private static BooleanWithReason checkCanEdit(@NonNull final Document document, @NonNull final IUserRolePermissions permissions) { // In case document type is not Window, return OK because we cannot validate final DocumentPath documentPath = document.getDocumentPath(); if (documentPath.getDocumentType() != DocumentType.Window) { return BooleanWithReason.TRUE; // OK } // Check if we have window write permission final AdWindowId adWindowId = documentPath.getWindowId().toAdWindowIdOrNull(); if (adWindowId != null && !permissions.checkWindowPermission(adWindowId).hasWriteAccess()) { return BooleanWithReason.falseBecause("no window edit permission"); } final int adTableId = getAdTableId(document); if (adTableId <= 0) { return BooleanWithReason.TRUE; // not table based => OK } final int recordId = getRecordId(document); final ClientId adClientId = document.getClientId(); final OrgId adOrgId = document.getOrgId(); if (adOrgId == null) { return BooleanWithReason.TRUE; // the user cleared the field; field is flagged as mandatory; until user set the field, don't make a fuss.
} return permissions.checkCanUpdate(adClientId, adOrgId, adTableId, recordId); } private static int getAdTableId(final Document document) { final String tableName = document.getEntityDescriptor().getTableNameOrNull(); if (tableName == null) { // cannot apply security because this is not table based return -1; // OK } return Services.get(IADTableDAO.class).retrieveTableId(tableName); } private static int getRecordId(final Document document) { if (document.isNew()) { return -1; } else { return document.getDocumentId().toIntOr(-1); } } public static boolean isNewDocumentAllowed(@NonNull final DocumentEntityDescriptor entityDescriptor, @NonNull final UserSession userSession) { final AdWindowId adWindowId = entityDescriptor.getWindowId().toAdWindowIdOrNull(); if (adWindowId == null) {return true;} final IUserRolePermissions permissions = userSession.getUserRolePermissions(); final ElementPermission windowPermission = permissions.checkWindowPermission(adWindowId); if (!windowPermission.hasWriteAccess()) {return false;} final ILogicExpression allowExpr = entityDescriptor.getAllowCreateNewLogic(); final LogicExpressionResult allow = allowExpr.evaluateToResult(userSession.toEvaluatee(), IExpressionEvaluator.OnVariableNotFound.ReturnNoResult); return allow.isTrue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\DocumentPermissionsHelper.java
2
请在Spring Boot框架中完成以下Java代码
private void createStepHUAlternativeRecord( @NonNull final PickingJobCreateRepoRequest.StepPickFrom pickFrom, @NonNull final ProductId productId, @NonNull final PickingJobStepId pickingJobStepId, @NonNull final PickingJobId pickingJobId, @NonNull final OrgId orgId) { final I_M_Picking_Job_Step_HUAlternative record = InterfaceWrapperHelper.newInstance(I_M_Picking_Job_Step_HUAlternative.class); record.setM_Picking_Job_ID(pickingJobId.getRepoId()); record.setM_Picking_Job_Step_ID(pickingJobStepId.getRepoId()); record.setAD_Org_ID(orgId.getRepoId()); record.setM_Picking_Job_HUAlternative_ID(loader.getPickingJobHUAlternativeId(pickingJobId, pickFrom.getPickFromHUId(), productId).getRepoId()); record.setPickFrom_Warehouse_ID(pickFrom.getPickFromLocatorId().getWarehouseId().getRepoId()); record.setPickFrom_Locator_ID(pickFrom.getPickFromLocatorId().getRepoId()); record.setPickFrom_HU_ID(pickFrom.getPickFromHUId().getRepoId()); InterfaceWrapperHelper.save(record); loader.addAlreadyLoadedFromDB(record); } private void createPickFromAlternative( @NonNull final PickFromAlternativeCreateRequest from, @NonNull final OrgId orgId) { final I_M_Picking_Job_HUAlternative record = InterfaceWrapperHelper.newInstance(I_M_Picking_Job_HUAlternative.class); record.setM_Picking_Job_ID(from.getPickingJobId().getRepoId()); record.setAD_Org_ID(orgId.getRepoId()); record.setPickFrom_Warehouse_ID(from.getPickFromLocatorId().getWarehouseId().getRepoId()); record.setPickFrom_Locator_ID(from.getPickFromLocatorId().getRepoId()); record.setPickFrom_HU_ID(from.getPickFromHUId().getRepoId()); record.setM_Product_ID(from.getProductId().getRepoId()); record.setC_UOM_ID(from.getQtyAvailable().getUomId().getRepoId()); record.setQtyAvailable(from.getQtyAvailable().toBigDecimal()); InterfaceWrapperHelper.save(record); loader.addAlreadyLoadedFromDB(record);
PickingJobPickFromAlternativeId.ofRepoId(record.getM_Picking_Job_HUAlternative_ID()); } // // // @Value @Builder private static class PickFromAlternativeCreateRequest { @NonNull LocatorId pickFromLocatorId; @NonNull HuId pickFromHUId; @NonNull ProductId productId; @NonNull Quantity qtyAvailable; @NonNull PickingJobId pickingJobId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\PickingJobCreateRepoHelper.java
2
请在Spring Boot框架中完成以下Java代码
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { // 创建 RedisTemplate 对象 RedisTemplate<String, Object> template = new RedisTemplate<>(); // 设置开启事务支持 template.setEnableTransactionSupport(true); // 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。 template.setConnectionFactory(factory); // 使用 String 序列化方式,序列化 KEY 。 template.setKeySerializer(RedisSerializer.string()); // 使用 JSON 序列化方式(库是 Jackson ),序列化 VALUE 。 template.setValueSerializer(RedisSerializer.json()); return template; } // Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // ObjectMapper objectMapper = new ObjectMapper();// <1> //// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // // jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // template.setValueSerializer(jackson2JsonRedisSerializer);
// @Bean // PUB/SUB 使用的 Bean ,需要时打开。 public RedisMessageListenerContainer listenerContainer(RedisConnectionFactory factory) { // 创建 RedisMessageListenerContainer 对象 RedisMessageListenerContainer container = new RedisMessageListenerContainer(); // 设置 RedisConnection 工厂。😈 它就是实现多种 Java Redis 客户端接入的秘密工厂。感兴趣的胖友,可以自己去撸下。 container.setConnectionFactory(factory); // 添加监听器 container.addMessageListener(new TestChannelTopicMessageListener(), new ChannelTopic("TEST")); // container.addMessageListener(new TestChannelTopicMessageListener(), new ChannelTopic("AOTEMAN")); // container.addMessageListener(new TestPatternTopicMessageListener(), new PatternTopic("TEST")); return container; } }
repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-with-jedis\src\main\java\cn\iocoder\springboot\labs\lab10\springdatarediswithjedis\config\RedisConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public IPage<SysUser> getPositionUserList(Page<SysUser> page, String positionId) { return page.setRecords(sysUserPositionMapper.getPositionUserList(page, positionId)); } @Override public void saveUserPosition(String userIds, String positionId) { String[] userIdArray = userIds.split(SymbolConstant.COMMA); //存在的用户 StringBuilder userBuilder = new StringBuilder(); for (String userId : userIdArray) { //获取成员是否存在于职位中 Long count = sysUserPositionMapper.getUserPositionCount(userId, positionId); if (count == 0) { //插入到用户职位关系表里面 SysUserPosition userPosition = new SysUserPosition(); userPosition.setPositionId(positionId); userPosition.setUserId(userId); sysUserPositionMapper.insert(userPosition); } else { userBuilder.append(userId).append(SymbolConstant.COMMA); } } //如果用户id存在,说明已存在用户职位关系表中,提示用户已存在 String uIds = userBuilder.toString(); if (oConvertUtils.isNotEmpty(uIds)) {
//查询用户列表 List<SysUser> sysUsers = userMapper.selectBatchIds(Arrays.asList(uIds.split(SymbolConstant.COMMA))); String realnames = sysUsers.stream().map(SysUser::getRealname).collect(Collectors.joining(SymbolConstant.COMMA)); throw new JeecgBootException(realnames + "已存在该职位中"); } } @Override public void removeByPositionId(String positionId) { sysUserPositionMapper.removeByPositionId(positionId); } @Override public void removePositionUser(String userIds, String positionId) { String[] userIdArray = userIds.split(SymbolConstant.COMMA); sysUserPositionMapper.removePositionUser(Arrays.asList(userIdArray),positionId); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysUserPositionServiceImpl.java
2
请完成以下Java代码
public CmmnTransform createTransform() { return factory.createTransform(this); } public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public CmmnTransformFactory getFactory() { return factory; } public void setFactory(CmmnTransformFactory factory) { this.factory = factory; }
public List<CmmnTransformListener> getTransformListeners() { return transformListeners; } public void setTransformListeners(List<CmmnTransformListener> transformListeners) { this.transformListeners = transformListeners; } public DefaultCmmnElementHandlerRegistry getCmmnElementHandlerRegistry() { return cmmnElementHandlerRegistry; } public void setCmmnElementHandlerRegistry(DefaultCmmnElementHandlerRegistry registry) { this.cmmnElementHandlerRegistry = registry; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransformer.java
1
请完成以下Java代码
public static PricingSystemId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static final PricingSystemId NULL = null; public static final PricingSystemId NONE = new PricingSystemId(100); int repoId; private PricingSystemId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "repoId"); } public boolean isNone() { return repoId == NONE.repoId; }
@Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final PricingSystemId id) { return id != null ? id.getRepoId() : -1; } public static boolean equals(@Nullable final PricingSystemId o1, @Nullable final PricingSystemId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\pricing\PricingSystemId.java
1
请完成以下Java代码
public static MResolution get (Properties ctx, int R_Resolution_ID) { Integer key = new Integer (R_Resolution_ID); MResolution retValue = (MResolution) s_cache.get (key); if (retValue != null) return retValue; retValue = new MResolution (ctx, R_Resolution_ID, null); if (retValue.get_ID () != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer,MResolution> s_cache = new CCache<Integer,MResolution>("R_Resolution", 10); /************************************************************************** * Standard Constructor * @param ctx context * @param R_Resolution_ID id * @param trxName */ public MResolution (Properties ctx, int R_Resolution_ID, String trxName)
{ super (ctx, R_Resolution_ID, trxName); } // MResolution /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MResolution (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MResolution } // MResolution
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MResolution.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleService { @Autowired private ArticleDao articleDao; /** * 新增文章 */ @Transactional(rollbackFor = Exception.class) public JSONObject addArticle(JSONObject jsonObject) { articleDao.addArticle(jsonObject); return CommonUtil.successJson(); } /** * 文章列表
*/ public JSONObject listArticle(JSONObject jsonObject) { CommonUtil.fillPageParam(jsonObject); int count = articleDao.countArticle(jsonObject); List<JSONObject> list = articleDao.listArticle(jsonObject); return CommonUtil.successPage(jsonObject, list, count); } /** * 更新文章 */ @Transactional(rollbackFor = Exception.class) public JSONObject updateArticle(JSONObject jsonObject) { articleDao.updateArticle(jsonObject); return CommonUtil.successJson(); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\service\ArticleService.java
2
请完成以下Java代码
public void addToBacklog(String activityRef, BacklogErrorCallback callback) { BACKLOG.put(activityRef, callback); } public ActivityImpl createActivity(String activityId) { ActivityImpl activity = new ActivityImpl(activityId, processDefinition); if (activityId!=null) { if (processDefinition.findActivity(activityId) != null) { throw new PvmException("duplicate activity id '" + activityId + "'"); } if (BACKLOG.containsKey(activityId)) { BACKLOG.remove(activityId); } namedFlowActivities.put(activityId, activity); } activity.flowScope = this; flowActivities.add(activity); return activity; } public boolean isAncestorFlowScopeOf(ScopeImpl other) { ScopeImpl otherAncestor = other.getFlowScope(); while (otherAncestor != null) { if (this == otherAncestor) { return true; } else { otherAncestor = otherAncestor.getFlowScope(); } } return false; } public boolean contains(ActivityImpl activity) { if (namedFlowActivities.containsKey(activity.getId())) { return true; } for (ActivityImpl nestedActivity : flowActivities) { if (nestedActivity.contains(activity)) { return true; } } return false; } // event listeners ////////////////////////////////////////////////////////// @SuppressWarnings("unchecked") @Deprecated public List<ExecutionListener> getExecutionListeners(String eventName) { return (List) super.getListeners(eventName); } @Deprecated public void addExecutionListener(String eventName, ExecutionListener executionListener) { super.addListener(eventName, executionListener); } @Deprecated public void addExecutionListener(String eventName, ExecutionListener executionListener, int index) { super.addListener(eventName, executionListener, index); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Deprecated public Map<String, List<ExecutionListener>> getExecutionListeners() { return (Map) super.getListeners(); } // getters and setters ////////////////////////////////////////////////////// public List<ActivityImpl> getActivities() { return flowActivities; } public Set<ActivityImpl> getEventActivities() { return eventActivities; } public boolean isSubProcessScope() { return isSubProcessScope; } public void setSubProcessScope(boolean isSubProcessScope) { this.isSubProcessScope = isSubProcessScope; } @Override public ProcessDefinitionImpl getProcessDefinition() { return processDefinition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ScopeImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ConnectorsAutoConfiguration { @Bean @ConditionalOnMissingBean public ExpressionManager expressionManager(List<CustomFunctionProvider> customFunctionProviders) { ExpressionManager expressionManager = new ExpressionManager(); expressionManager.setCustomFunctionProviders(customFunctionProviders); return expressionManager; } @Bean @ConditionalOnMissingBean public ExpressionResolver expressionResolver(ExpressionManager expressionManager, ObjectMapper objectMapper) { return new ExpressionResolver(expressionManager, objectMapper, new DefaultDelegateInterceptor()); } @Bean @ConditionalOnMissingBean public IntegrationContextBuilder integrationContextBuilder( ExtensionsVariablesMappingProvider variablesMappingProvider, ExpressionManager expressionManager ) { return new IntegrationContextBuilder(variablesMappingProvider, expressionManager); } @Bean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME) @ConditionalOnMissingBean(name = DefaultActivityBehaviorFactory.DEFAULT_SERVICE_TASK_BEAN_NAME) public DefaultServiceTaskBehavior defaultServiceTaskBehavior( ApplicationContext applicationContext, IntegrationContextBuilder integrationContextBuilder, VariablesPropagator variablesPropagator ) { return new DefaultServiceTaskBehavior(applicationContext, integrationContextBuilder, variablesPropagator);
} @Bean @ConditionalOnMissingBean public ExtensionsVariablesMappingProvider variablesMappingProvider( ProcessExtensionService processExtensionService, ExpressionResolver expressionResolver, VariableParsingService variableParsingService ) { return new ExtensionsVariablesMappingProvider( processExtensionService, expressionResolver, variableParsingService ); } @Bean @ConditionalOnMissingBean public VariablesPropagator variablesPropagator(VariablesCalculator variablesCalculator) { return new VariablesPropagator(variablesCalculator); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ConnectorsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public Exposure getExposure() { return this.exposure; } public String getBasePath() { return this.basePath; } public void setBasePath(String basePath) { Assert.isTrue(basePath.isEmpty() || basePath.startsWith("/"), "'basePath' must start with '/' or be empty"); this.basePath = cleanBasePath(basePath); } private String cleanBasePath(String basePath) { if (StringUtils.hasText(basePath) && basePath.endsWith("/")) { return basePath.substring(0, basePath.length() - 1); } return basePath; } public Map<String, String> getPathMapping() { return this.pathMapping; } public Discovery getDiscovery() { return this.discovery; } public static class Exposure { /** * Endpoint IDs that should be included or '*' for all. */ private Set<String> include = new LinkedHashSet<>(); /** * Endpoint IDs that should be excluded or '*' for all. */ private Set<String> exclude = new LinkedHashSet<>(); public Set<String> getInclude() { return this.include; } public void setInclude(Set<String> include) { this.include = include; } public Set<String> getExclude() { return this.exclude; } public void setExclude(Set<String> exclude) {
this.exclude = exclude; } } public static class Discovery { /** * Whether the discovery page is enabled. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\WebEndpointProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class WeekSupply extends AbstractSyncConfirmAwareEntity { @ManyToOne @Lazy @NonNull private BPartner bpartner; @ManyToOne @NonNull private Product product; @NonNull private java.sql.Date day; @Nullable private String trend; protected WeekSupply() { } @Builder private WeekSupply( @NonNull final BPartner bpartner, @NonNull final Product product, @NonNull final LocalDate day) { this.bpartner = bpartner; this.product = product; this.day = DateUtils.toSqlDate(day); } @Override protected void toString(final MoreObjects.ToStringHelper toStringHelper) { toStringHelper .add("product", product) .add("bpartner", bpartner) .add("day", day) .add("trend", trend); } public Long getProductId() { return product.getId(); } public String getProductIdAsString() { return product.getIdAsString(); } public String getProductUUID() { return product.getUuid(); }
public String getBpartnerUUID() { return bpartner.getUuid(); } public LocalDate getDay() { return day.toLocalDate(); } public YearWeek getWeek() { return YearWeekUtil.ofLocalDate(day.toLocalDate()); } @Nullable public Trend getTrend() { return Trend.ofNullableCode(trend); } @Nullable public String getTrendAsString() { return trend; } public void setTrend(@Nullable final Trend trend) { this.trend = trend != null ? trend.getCode() : null; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\WeekSupply.java
2
请完成以下Spring Boot application配置
spring: application: name: dubbo-registry-zookeeper-consumer-sample demo: service: version: 1.0.0 embedded: zookeeper: port: 2181 dubbo: registry: address: zookeeper://127.0.0.1:${embedd
ed.zookeeper.port} file: ${user.home}/dubbo-cache/${spring.application.name}/dubbo.cache
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-samples\registry-samples\zookeeper-samples\consumer-sample\src\main\resources\application.yml
2
请完成以下Java代码
public final class GettingStartedSection extends PreDefinedSection { private final BulletedSection<Link> referenceDocs; private final BulletedSection<Link> guides; private final BulletedSection<Link> additionalLinks; GettingStartedSection(MustacheTemplateRenderer templateRenderer) { super("Getting Started"); this.referenceDocs = new BulletedSection<>(templateRenderer, "documentation/reference-documentation"); this.guides = new BulletedSection<>(templateRenderer, "documentation/guides"); this.additionalLinks = new BulletedSection<>(templateRenderer, "documentation/additional-links"); } @Override public boolean isEmpty() { return referenceDocs().isEmpty() && guides().isEmpty() && additionalLinks().isEmpty() && super.isEmpty(); } @Override protected List<Section> resolveSubSections(List<Section> sections) { List<Section> allSections = new ArrayList<>(); allSections.add(this.referenceDocs); allSections.add(this.guides); allSections.add(this.additionalLinks); allSections.addAll(sections); return allSections; } public GettingStartedSection addReferenceDocLink(String href, String description) { this.referenceDocs.addItem(new Link(href, description)); return this; } public BulletedSection<Link> referenceDocs() { return this.referenceDocs; } public GettingStartedSection addGuideLink(String href, String description) { this.guides.addItem(new Link(href, description)); return this; } public BulletedSection<Link> guides() { return this.guides; } public GettingStartedSection addAdditionalLink(String href, String description) { this.additionalLinks.addItem(new Link(href, description));
return this; } public BulletedSection<Link> additionalLinks() { return this.additionalLinks; } /** * Internal representation of a link. */ public static class Link { private final String href; private final String description; Link(String href, String description) { this.href = href; this.description = description; } public String getHref() { return this.href; } public String getDescription() { return this.description; } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\GettingStartedSection.java
1
请完成以下Java代码
public class Jsp { /** * Class name of the servlet to use for JSPs. If registered is true and this class is * on the classpath then it will be registered. */ private String className = "org.apache.jasper.servlet.JspServlet"; private Map<String, String> initParameters = new HashMap<>(); /** * Whether the JSP servlet is registered. */ private boolean registered = true; public Jsp() { this.initParameters.put("development", "false"); } /** * Return the class name of the servlet to use for JSPs. If {@link #getRegistered() * registered} is {@code true} and this class is on the classpath then it will be * registered. * @return the class name of the servlet to use for JSPs */ public String getClassName() { return this.className; } public void setClassName(String className) { this.className = className; } /**
* Return the init parameters used to configure the JSP servlet. * @return the init parameters */ public Map<String, String> getInitParameters() { return this.initParameters; } public void setInitParameters(Map<String, String> initParameters) { this.initParameters = initParameters; } /** * Return whether the JSP servlet is registered. * @return {@code true} to register the JSP servlet */ public boolean getRegistered() { return this.registered; } public void setRegistered(boolean registered) { this.registered = registered; } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\Jsp.java
1
请完成以下Java代码
public int getReturnCode() { return m_returnCode; } // getReturnCode /** * Sets initial answer (i.e. button that will be preselected by default). * * Please note that this is not the default answer that will be returned by {@link #getReturnCode()} if user does nothing (i.e. closes the window). * It is just the preselectated button. * * @param initialAnswer {@link #A_OK}, {@link #A_CANCEL}. */ public void setInitialAnswer(final int initialAnswer) { // If the inial answer did not actual changed, do nothing if (this._initialAnswer == initialAnswer) { return; } // // Configure buttons accelerator (KeyStroke) and RootPane's default button final JRootPane rootPane = getRootPane(); final CButton okButton = confirmPanel.getOKButton(); final AppsAction okAction = (AppsAction)okButton.getAction(); final CButton cancelButton = confirmPanel.getCancelButton(); final AppsAction cancelAction = (AppsAction)cancelButton.getAction(); if (initialAnswer == A_OK) { okAction.setDefaultAccelerator(); cancelAction.setDefaultAccelerator(); rootPane.setDefaultButton(okButton); } else if (initialAnswer == A_CANCEL) { // NOTE: we need to set the OK's Accelerator keystroke to null because in most of the cases it is "Enter" // and we want to prevent user for hiting ENTER by mistake okAction.setAccelerator(null); cancelAction.setDefaultAccelerator(); rootPane.setDefaultButton(cancelButton);
} else { throw new IllegalArgumentException("Unknown inital answer: " + initialAnswer); } // // Finally, set the new inial answer this._initialAnswer = initialAnswer; } public int getInitialAnswer() { return this._initialAnswer; } /** * Request focus on inital answer. */ private void focusInitialAnswerButton() { final CButton defaultButton; if (_initialAnswer == A_OK) { defaultButton = confirmPanel.getOKButton(); } else if (_initialAnswer == A_CANCEL) { defaultButton = confirmPanel.getCancelButton(); } else { return; } defaultButton.requestFocusInWindow(); } } // ADialogDialog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ADialogDialog.java
1
请在Spring Boot框架中完成以下Java代码
protected void setOwner(TenantId tenantId, OtaPackage otaPackage, IdProvider idProvider) { otaPackage.setTenantId(tenantId); } @Override protected OtaPackage prepare(EntitiesImportCtx ctx, OtaPackage otaPackage, OtaPackage oldOtaPackage, OtaPackageExportData exportData, IdProvider idProvider) { otaPackage.setDeviceProfileId(idProvider.getInternalId(otaPackage.getDeviceProfileId())); return otaPackage; } @Override protected OtaPackage findExistingEntity(EntitiesImportCtx ctx, OtaPackage otaPackage, IdProvider idProvider) { OtaPackage existingOtaPackage = super.findExistingEntity(ctx, otaPackage, idProvider); if (existingOtaPackage == null && ctx.isFindExistingByName()) { existingOtaPackage = otaPackageService.findOtaPackageByTenantIdAndTitleAndVersion(ctx.getTenantId(), otaPackage.getTitle(), otaPackage.getVersion()); } return existingOtaPackage; } @Override protected OtaPackage deepCopy(OtaPackage otaPackage) { return new OtaPackage(otaPackage);
} @Override protected OtaPackage saveOrUpdate(EntitiesImportCtx ctx, OtaPackage otaPackage, OtaPackageExportData exportData, IdProvider idProvider, CompareResult compareResult) { if (otaPackage.hasUrl()) { OtaPackageInfo info = new OtaPackageInfo(otaPackage); return new OtaPackage(otaPackageService.saveOtaPackageInfo(info, info.hasUrl())); } return otaPackageService.saveOtaPackage(otaPackage); } @Override public EntityType getEntityType() { return EntityType.OTA_PACKAGE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\OtaPackageImportService.java
2
请完成以下Java代码
private void generatePublicKeyRPK(String publX, String publY, String privS) { try { /*Get Elliptic Curve Parameter spec for secp256r1 */ AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); algoParameters.init(new ECGenParameterSpec("secp256r1")); ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); if (publX != null && !publX.isEmpty() && publY != null && !publY.isEmpty()) { // Get point values byte[] publicX = Hex.decodeHex(publX.toCharArray()); byte[] publicY = Hex.decodeHex(publY.toCharArray()); /* Create key specs */ KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), parameterSpec); /* Get keys */ this.serverPublicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
} if (privS != null && !privS.isEmpty()) { /* Get point values */ byte[] privateS = Hex.decodeHex(privS.toCharArray()); /* Create key specs */ KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); /* Get keys */ this.serverPrivateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); } } catch (GeneralSecurityException | IllegalArgumentException e) { log.error("[{}] Failed generate Server KeyRPK", e.getMessage()); throw new RuntimeException(e); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\secure\LwM2mRPkCredentials.java
1
请在Spring Boot框架中完成以下Java代码
public int getLockLease() { return this.lockLease; } public void setLockLease(int lockLease) { this.lockLease = lockLease; } public int getLockTimeout() { return this.lockTimeout; } public void setLockTimeout(int lockTimeout) { this.lockTimeout = lockTimeout; } public int getMessageSyncInterval() { return this.messageSyncInterval; } public void setMessageSyncInterval(int messageSyncInterval) { this.messageSyncInterval = messageSyncInterval; } public int getSearchTimeout() {
return this.searchTimeout; } public void setSearchTimeout(int searchTimeout) { this.searchTimeout = searchTimeout; } public boolean isUseClusterConfiguration() { return this.useClusterConfiguration; } public void setUseClusterConfiguration(boolean useClusterConfiguration) { this.useClusterConfiguration = useClusterConfiguration; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PeerCacheProperties.java
2
请完成以下Java代码
public void setM_HU_Item_ID(final int Ref_HU_Item_ID) { this.Ref_HU_Item_ID = Ref_HU_Item_ID; } @Override public int getM_HU_Item_ID() { return Ref_HU_Item_ID; } @Override public int getAD_Table_ID() { return AD_Table_ID; } @Override public void setAD_Table_ID(final int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID;
} @Override public void setRecord_ID(final int record_ID) { Record_ID = record_ID; } @Override public void setM_HU_ID(int m_hu_ID) { M_HU_ID = m_hu_ID; } @Override public int getM_HU_ID() { return M_HU_ID; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java
1
请完成以下Java代码
public static MChatType get (Properties ctx, int CM_ChatType_ID) { Integer key = new Integer (CM_ChatType_ID); MChatType retValue = (MChatType)s_cache.get (key); if (retValue != null) return retValue; retValue = new MChatType (ctx, CM_ChatType_ID, null); if (retValue.get_ID () != CM_ChatType_ID) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MChatType> s_cache = new CCache<Integer, MChatType> ("CM_ChatType", 20); /** * Standard Constructor * @param ctx context * @param CM_ChatType_ID id * @param trxName transaction */ public MChatType (Properties ctx, int CM_ChatType_ID, String trxName) { super (ctx, CM_ChatType_ID, trxName);
if (CM_ChatType_ID == 0) setModerationType (MODERATIONTYPE_NotModerated); } // MChatType /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MChatType (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MChatType } // MChatType
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MChatType.java
1
请在Spring Boot框架中完成以下Java代码
static class GolfApplicationConfiguration { // tag::application-runner[] @Bean ApplicationRunner runGolfTournament(PgaTourService pgaTourService) { return args -> { GolfTournament golfTournament = GolfTournament.newGolfTournament("The Masters") .at(GolfCourseBuilder.buildAugustaNational()) .register(GolferBuilder.buildGolfers(GolferBuilder.FAVORITE_GOLFER_NAMES)) .buildPairings() .play(); pgaTourService.manage(golfTournament); }; } // end::application-runner[] }
// end::application-configuration[] // tag::geode-configuration[] @Configuration @UseMemberName(APPLICATION_NAME) @EnableCachingDefinedRegions(serverRegionShortcut = RegionShortcut.REPLICATE) static class GeodeConfiguration { } // end::geode-configuration[] // tag::peer-cache-configuration[] @PeerCacheApplication @Profile("peer-cache") @Import({ AsyncInlineCachingConfiguration.class, AsyncInlineCachingRegionConfiguration.class }) static class PeerCacheApplicationConfiguration { } // end::peer-cache-configuration[] } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\BootGeodeAsyncInlineCachingClientApplication.java
2
请完成以下Java代码
public class FibonacciResource { private static final Logger logger = LoggerFactory.getLogger(FibonacciResource.class); private final FibonacciService fibonacciService; public FibonacciResource(FibonacciService fibonacciService) { this.fibonacciService = fibonacciService; } @GET @Produces(MediaType.TEXT_PLAIN) public String getFibonacciSequence(@QueryParam("iterations") Integer iterations) { if (iterations == null) { iterations = 10; //default value } logger.info("Received request with iterations: " + iterations); List<Integer> fibSequence = fibonacciService.generateSequence(iterations);
return fibSequence.toString(); } @PostConstruct public void startLoad() { for (int i = 0; i < Runtime.getRuntime().availableProcessors(); i++) { new Thread(() -> { while (true) { Math.pow(Math.random(), Math.random()); // Keep CPU busy } }).start(); } } }
repos\tutorials-master\quarkus-modules\quarkus-extension\quarkus-load-shedding\src\main\java\com\baeldung\quarkus\FibonacciResource.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig { @Bean UnboundIdContainer ldapContainer() throws Exception { return new UnboundIdContainer("dc=baeldung,dc=com", "classpath:users.ldif"); } @Bean LdapAuthoritiesPopulator authorities(BaseLdapPathContextSource contextSource) { String groupSearchBase = "ou=groups"; DefaultLdapAuthoritiesPopulator authorities = new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase); authorities.setGroupSearchFilter("(member={0})"); return authorities; } @Bean AuthenticationManager authenticationManager(BaseLdapPathContextSource contextSource, LdapAuthoritiesPopulator authorities) { LdapBindAuthenticationManagerFactory factory = new LdapBindAuthenticationManagerFactory(contextSource); factory.setUserSearchBase("ou=people");
factory.setUserSearchFilter("(uid={0})"); return factory.createAuthenticationManager(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(auth -> auth .requestMatchers("/", "/home", "/css/**") .permitAll() .anyRequest() .authenticated()) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login").permitAll()) .logout(logout -> logout.logoutSuccessUrl("/")).build(); } }
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\config\SecurityConfig.java
2
请完成以下Java代码
public ProcessEngine getProcessEngine(String name) { return serviceContainer.getServiceValue(ServiceTypes.PROCESS_ENGINE, name); } @Override public List<ProcessEngine> getProcessEngines() { return serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_ENGINE); } @Override public Set<String> getProcessEngineNames() { Set<String> processEngineNames = new HashSet<String>(); List<ProcessEngine> processEngines = getProcessEngines(); for (ProcessEngine processEngine : processEngines) { processEngineNames.add(processEngine.getName()); } return processEngineNames; } // process application service implementation ///////////////////////////////// @Override public Set<String> getProcessApplicationNames() { List<JmxManagedProcessApplication> processApplications = serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_APPLICATION); Set<String> processApplicationNames = new HashSet<String>(); for (JmxManagedProcessApplication jmxManagedProcessApplication : processApplications) { processApplicationNames.add(jmxManagedProcessApplication.getProcessApplicationName()); } return processApplicationNames; } @Override public ProcessApplicationInfo getProcessApplicationInfo(String processApplicationName) { JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); if (processApplicationService == null) { return null; } else { return processApplicationService.getProcessApplicationInfo();
} } @Override public ProcessApplicationReference getDeployedProcessApplication(String processApplicationName) { JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); if (processApplicationService == null) { return null; } else { return processApplicationService.getProcessApplicationReference(); } } // Getter / Setter //////////////////////////////////////////////////////////// public PlatformServiceContainer getServiceContainer() { return serviceContainer; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\RuntimeContainerDelegateImpl.java
1
请完成以下Java代码
public class Coordinates { private double longitude; private double latitude; private String placeName; public Coordinates() {} public Coordinates(double longitude, double latitude, String placeName) { this.longitude = longitude; this.latitude = latitude; this.placeName = placeName; } public double calculateDistance(Coordinates c) { double s1 = Math.abs(this.longitude - c.longitude); double s2 = Math.abs(this.latitude - c.latitude); return Math.hypot(s1, s2); } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude;
} public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public String getPlaceName() { return placeName; } public void setPlaceName(String placeName) { this.placeName = placeName; } }
repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\methodmultiplereturnvalues\Coordinates.java
1
请完成以下Java代码
public void addDeploymentMappings(List<ImmutablePair<String, String>> mappings) { addDeploymentMappings(mappings, null); } /** * Add mappings of deployment ids to resource ids to the overall element * mapping list. All elements from <code>idList</code> that are not part of * the mappings will be added to the list of <code>null</code> deployment id * mappings. * * @param mappingsList * the mappings to add * @param idList * the list of ids to check for missing elements concerning the * mappings to add */ public void addDeploymentMappings(List<ImmutablePair<String, String>> mappingsList, Collection<String> idList) { if (ids != null) { ids = null; mappings = null; } Set<String> missingIds = idList == null ? null : new HashSet<>(idList); mappingsList.forEach(pair -> { String deploymentId = pair.getLeft(); Set<String> idSet = collectedMappings.get(deploymentId); if (idSet == null) { idSet = new HashSet<>(); collectedMappings.put(deploymentId, idSet); } idSet.add(pair.getRight()); if (missingIds != null) { missingIds.remove(pair.getRight()); } }); // add missing ids to "null" deployment id if (missingIds != null && !missingIds.isEmpty()) { Set<String> nullIds = collectedMappings.get(null); if (nullIds == null) { nullIds = new HashSet<>(); collectedMappings.put(null, nullIds); } nullIds.addAll(missingIds); } } /** * @return the list of ids that are mapped to deployment ids, ordered by * deployment id */ public List<String> getIds() { if (ids == null) { createDeploymentMappings(); } return ids;
} /** * @return the list of {@link DeploymentMapping}s */ public DeploymentMappings getMappings() { if (mappings == null) { createDeploymentMappings(); } return mappings; } public boolean isEmpty() { return collectedMappings.isEmpty(); } protected void createDeploymentMappings() { ids = new ArrayList<>(); mappings = new DeploymentMappings(); for (Entry<String, Set<String>> mapping : collectedMappings.entrySet()) { ids.addAll(mapping.getValue()); mappings.add(new DeploymentMapping(mapping.getKey(), mapping.getValue().size())); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchElementConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
private ServiceRepairProjectCostCollector removeSingleCostCollectorOfType( @NonNull final ServiceRepairProjectCostCollectorType type) { final ImmutableList<ServiceRepairProjectCostCollector> result = removeCostCollectorsOfType(type); if (result.size() == 1) { return result.get(0); } else { throw new AdempiereException("Expected one and only one cost collector of type " + type + " but got " + result); } } private ImmutableList<ServiceRepairProjectCostCollector> removeCostCollectorsOfType(@NonNull final ServiceRepairProjectCostCollectorType type) { final ImmutableList.Builder<ServiceRepairProjectCostCollector> result = ImmutableList.builder(); for (final Iterator<ServiceRepairProjectCostCollector> it = costCollectorsToAggregate.iterator(); it.hasNext(); ) { final ServiceRepairProjectCostCollector costCollector = it.next(); if (costCollector.getType() == type) { result.add(costCollector); it.remove(); } } return result.build(); } @Override public Stream<Map.Entry<ServiceRepairProjectCostCollectorId, OrderAndLineId>> streamQuotationLineIdsIndexedByCostCollectorId() { if (repairedProductToReturnCostCollector == null || repairedProductToReturnLineBuilder == null) { throw new AdempiereException("Order/quotation line for repaired product was not created yet"); } final LinkedHashSet<Map.Entry<ServiceRepairProjectCostCollectorId, OrderAndLineId>> orderAndLineIds = new LinkedHashSet<>(); orderAndLineIds.add(GuavaCollectors.entry(repairedProductToReturnCostCollector.getId(), repairedProductToReturnLineBuilder.getCreatedOrderAndLineId())); if (servicePerformedLineBuilder != null) { orderAndLineIds.add(GuavaCollectors.entry(repairedProductToReturnCostCollector.getId(), servicePerformedLineBuilder.getCreatedOrderAndLineId()));
} return orderAndLineIds.stream(); } @Override public GroupTemplate getGroupTemplate() { final GroupTemplate.GroupTemplateBuilder builder = GroupTemplate.builder() .name(groupCaption) .isNamePrinted(false); if (repairedProductToReturnCostCollector.getWarrantyCase().isYes() && repairServicePerformedId != null) { builder.compensationLine(GroupTemplateCompensationLine.builder() .productId(repairServicePerformedId) .compensationType(GroupCompensationType.Discount) .percentage(Percent.ONE_HUNDRED) .build()); } builder.regularLinesToAdd(ImmutableList.of()); return builder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\RepairedProductAggregator.java
2
请在Spring Boot框架中完成以下Java代码
public CommonResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) { UmsRole umsRole = new UmsRole(); umsRole.setStatus(status); int count = roleService.update(id, umsRole); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取角色相关菜单") @RequestMapping(value = "/listMenu/{roleId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsMenu>> listMenu(@PathVariable Long roleId) { List<UmsMenu> roleList = roleService.listMenu(roleId); return CommonResult.success(roleList); } @ApiOperation("获取角色相关资源") @RequestMapping(value = "/listResource/{roleId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResource>> listResource(@PathVariable Long roleId) { List<UmsResource> roleList = roleService.listResource(roleId); return CommonResult.success(roleList); }
@ApiOperation("给角色分配菜单") @RequestMapping(value = "/allocMenu", method = RequestMethod.POST) @ResponseBody public CommonResult allocMenu(@RequestParam Long roleId, @RequestParam List<Long> menuIds) { int count = roleService.allocMenu(roleId, menuIds); return CommonResult.success(count); } @ApiOperation("给角色分配资源") @RequestMapping(value = "/allocResource", method = RequestMethod.POST) @ResponseBody public CommonResult allocResource(@RequestParam Long roleId, @RequestParam List<Long> resourceIds) { int count = roleService.allocResource(roleId, resourceIds); return CommonResult.success(count); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsRoleController.java
2
请完成以下Java代码
public class ActivitiErrorMessageImpl implements ActivitiErrorMessage { private int code; private String message; public ActivitiErrorMessageImpl() {} public ActivitiErrorMessageImpl(int status, String message) { this.code = status; this.message = message; } @Override public int getCode() { return code;
} public void setCode(int status) { this.code = status; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-model-shared-impl\src\main\java\org\activiti\api\runtime\model\impl\ActivitiErrorMessageImpl.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public LocalDate getBirthDate() { return birthDate; } public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate; } public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public Boolean getCanDriveACar() { return canDriveACar; } public void setCanDriveACar(Boolean canDriveACar) { this.canDriveACar = canDriveACar; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\suppliercallable\data\User.java
1
请完成以下Java代码
public int toInt() { return precision; } /** * @return always RoundingMode#UP. Example: we convert 300GR to piece; one piece is one kilo; we need one piece and not 0 piece as the result, so we need to round UP. */ public RoundingMode getRoundingMode() { return RoundingMode.UP; } public BigDecimal roundIfNeeded(@NonNull final BigDecimal qty) { if (qty.scale() > precision) { return qty.setScale(precision, getRoundingMode()); } else { return qty; } } public BigDecimal round(@NonNull final BigDecimal qty) { return qty.setScale(precision, getRoundingMode()); }
public BigDecimal adjustToPrecisionWithoutRoundingIfPossible(@NonNull final BigDecimal qty) { // NOTE: it seems that ZERO is a special case of BigDecimal, so we are computing it right away if (qty == null || qty.signum() == 0) { return BigDecimal.ZERO.setScale(precision); } final BigDecimal qtyNoZero = qty.stripTrailingZeros(); final int qtyScale = qtyNoZero.scale(); if (qtyScale >= precision) { // Qty's actual scale is bigger than UOM precision, don't touch it return qtyNoZero; } else { // Qty's actual scale is less than UOM precision. Try to convert it to UOM precision // NOTE: we are using without scale because it shall be scaled without any problem return qtyNoZero.setScale(precision, RoundingMode.HALF_UP); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMPrecision.java
1
请完成以下Java代码
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public java.lang.String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } @Override public void setUserElementString2 (final @Nullable java.lang.String UserElementString2) { set_Value (COLUMNNAME_UserElementString2, UserElementString2); } @Override public java.lang.String getUserElementString2() { return get_ValueAsString(COLUMNNAME_UserElementString2); } @Override public void setUserElementString3 (final @Nullable java.lang.String UserElementString3) { set_Value (COLUMNNAME_UserElementString3, UserElementString3); } @Override public java.lang.String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override public void setUserElementString4 (final @Nullable java.lang.String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override public java.lang.String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); }
@Override public void setUserElementString5 (final @Nullable java.lang.String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public java.lang.String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable java.lang.String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public java.lang.String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournalLine.java
1
请完成以下Java代码
public String getInMessageRef() { return inMessageRef; } public void setInMessageRef(String inMessageRef) { this.inMessageRef = inMessageRef; } public String getOutMessageRef() { return outMessageRef; } public void setOutMessageRef(String outMessageRef) { this.outMessageRef = outMessageRef; } public List<String> getErrorMessageRef() { return errorMessageRef; } public void setErrorMessageRef(List<String> errorMessageRef) { this.errorMessageRef = errorMessageRef; } public Operation clone() { Operation clone = new Operation(); clone.setValues(this);
return clone; } public void setValues(Operation otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setImplementationRef(otherElement.getImplementationRef()); setInMessageRef(otherElement.getInMessageRef()); setOutMessageRef(otherElement.getOutMessageRef()); errorMessageRef = new ArrayList<String>(); if (otherElement.getErrorMessageRef() != null && !otherElement.getErrorMessageRef().isEmpty()) { errorMessageRef.addAll(otherElement.getErrorMessageRef()); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Operation.java
1
请完成以下Java代码
public class DrawBufferedCircle { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame("Circle"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new CircleImagePanel(64, 3)); // final size: 64x64, supersample: 3x f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } static class CircleImagePanel extends JPanel { private final int finalSize; private final BufferedImage circleImage; public CircleImagePanel(int finalSize, int scale) { this.finalSize = finalSize; this.circleImage = makeCircleImage(finalSize, scale); setPreferredSize(new Dimension(finalSize + 16, finalSize + 16)); setBackground(Color.WHITE); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); try { int x = (getWidth() - finalSize) / 2; int y = (getHeight() - finalSize) / 2; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(circleImage, x, y, finalSize, finalSize, null); } finally { g2.dispose(); } } private BufferedImage makeCircleImage(int finalSize, int scale) {
int hi = finalSize * scale; BufferedImage img = new BufferedImage(hi, hi, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = img.createGraphics(); try { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); g2.setComposite(AlphaComposite.Src); float stroke = 6f * scale / 3f; double diameter = hi - stroke - (4 * scale); double x = (hi - diameter) / 2.0; double y = (hi - diameter) / 2.0; Shape circle = new Ellipse2D.Double(x, y, diameter, diameter); g2.setPaint(new Color(0xBBDEFB)); g2.fill(circle); g2.setPaint(new Color(0x0D47A1)); g2.setStroke(new BasicStroke(stroke, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g2.draw(circle); } finally { g2.dispose(); } return img; } } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\drawcircle\DrawBufferedCircle.java
1
请完成以下Java代码
private boolean createReferenceNo(PO po, IReferenceNoGeneratorInstance generatorInstance) { try { Services.get(IReferenceNoBL.class).linkReferenceNo(po, generatorInstance); if (p_IsTest) { rollback(); } else { commitEx(); } return true; } catch (Exception e) { addLog("Cannot create reference no for " + po + " (generator=" + generatorInstance + "): " + e.getLocalizedMessage()); log.warn(e.getLocalizedMessage(), e); } return false; } private static Map<Integer, List<IReferenceNoGeneratorInstance>> groupByTableId(final List<IReferenceNoGeneratorInstance> generatorInstances) { final Map<Integer, List<IReferenceNoGeneratorInstance>> map = new HashMap<>(); for (final IReferenceNoGeneratorInstance generatorInstance : generatorInstances)
{ for (final int adTableId : generatorInstance.getAssignedTableIds()) { List<IReferenceNoGeneratorInstance> list = map.get(adTableId); if (list == null) { list = new ArrayList<>(); map.put(adTableId, list); } list.add(generatorInstance); } } return map; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\process\CreateMissingReferenceNo.java
1
请在Spring Boot框架中完成以下Java代码
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/","/login").permitAll()//根路径和/login路径不拦截 .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") //2登陆页面路径为/login .defaultSuccessUrl("/chat") //3登陆成功转向chat页面 .permitAll() .and() .logout() .permitAll(); }
//4在内存中配置两个用户 wyf 和 wisely ,密码和用户名一致,角色是 USER @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin").password("admin").roles("USER") .and() .withUser("abel").password("abel").roles("USER"); } //5忽略静态资源的拦截 @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/static/**"); } }
repos\springBoot-master\springWebSocket\src\main\java\com\us\example\config\WebSecurityConfig.java
2
请完成以下Spring Boot application配置
bar=hello logging.structured.format.console=ecs logging.structured.json.exclude=@timestamp logging.structured.json.rename[process.pid]=process.procid logging.structured.json.add.foo=${bar} logging.structured.json.customizer=smoketest.structuredlogging.SampleJsonMembersCustomizer #--- spring.config.activate.on-profile=custom logging.structured.format.console=smoketest.structuredlogging.CustomStructuredLogFormatter #--- spring.config.activate.on-profile=on-error logging.structured.json.customizer=smoketest.structuredlogging.Duplic
ateJsonMembersCustomizer #--- logging.config=classpath:custom-logback.xml spring.config.activate.on-profile=on-error-custom-logback-file logging.structured.json.customizer=smoketest.structuredlogging.DuplicateJsonMembersCustomizer
repos\spring-boot-4.0.1\smoke-test\spring-boot-smoke-test-structured-logging\src\main\resources\application.properties
2
请完成以下Java代码
public void setTaskId(String taskId) { this.taskId = taskId; } @Override public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Override public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getContentId() { return contentId; } public void setContentId(String contentId) { this.contentId = contentId; } public ByteArrayEntity getContent() { return content; } public void setContent(ByteArrayEntity content) { this.content = content;
} public void setUserId(String userId) { this.userId = userId; } @Override public String getUserId() { return userId; } @Override public Date getTime() { return time; } @Override public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntity.java
1
请完成以下Java代码
public String getEventType() { return eventType.name(); } public CallableElement getEventPayload() { return eventPayload; } public void setJobDeclaration(EventSubscriptionJobDeclaration jobDeclaration) { this.jobDeclaration = jobDeclaration; } public EventSubscriptionEntity createSubscriptionForStartEvent(ProcessDefinitionEntity processDefinition) { EventSubscriptionEntity eventSubscriptionEntity = new EventSubscriptionEntity(eventType); VariableScope scopeForExpression = StartProcessVariableScope.getSharedInstance(); String eventName = resolveExpressionOfEventName(scopeForExpression); eventSubscriptionEntity.setEventName(eventName); eventSubscriptionEntity.setActivityId(activityId); eventSubscriptionEntity.setConfiguration(processDefinition.getId()); eventSubscriptionEntity.setTenantId(processDefinition.getTenantId()); return eventSubscriptionEntity; } /** * Creates and inserts a subscription entity depending on the message type of this declaration. */ public EventSubscriptionEntity createSubscriptionForExecution(ExecutionEntity execution) { EventSubscriptionEntity eventSubscriptionEntity = new EventSubscriptionEntity(execution, eventType); String eventName = resolveExpressionOfEventName(execution); eventSubscriptionEntity.setEventName(eventName); if (activityId != null) { ActivityImpl activity = execution.getProcessDefinition().findActivity(activityId); eventSubscriptionEntity.setActivity(activity); } eventSubscriptionEntity.insert(); LegacyBehavior.removeLegacySubscriptionOnParent(execution, eventSubscriptionEntity); return eventSubscriptionEntity; } /**
* Resolves the event name within the given scope. */ public String resolveExpressionOfEventName(VariableScope scope) { if (isExpressionAvailable()) { if(scope instanceof BaseDelegateExecution) { // the variable scope execution is also the current context execution // during expression evaluation the current context is updated with the scope execution return (String) eventName.getValue(scope, (BaseDelegateExecution) scope); } else { return (String) eventName.getValue(scope); } } else { return null; } } protected boolean isExpressionAvailable() { return eventName != null; } public void updateSubscription(EventSubscriptionEntity eventSubscription) { String eventName = resolveExpressionOfEventName(eventSubscription.getExecution()); eventSubscription.setEventName(eventName); eventSubscription.setActivityId(activityId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\EventSubscriptionDeclaration.java
1
请完成以下Java代码
public class C_DocLine_Sort { @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE , ifColumnsChanged = { I_C_DocLine_Sort.COLUMNNAME_DocBaseType , I_C_DocLine_Sort.COLUMNNAME_IsActive , I_C_DocLine_Sort.COLUMNNAME_IsDefault }) public void validateNoConflictingBPConfiguration(final I_C_DocLine_Sort sort) { if (!sort.isActive()) { return; // if it was deactivated } // // Services final IQueryBL queryBL = Services.get(IQueryBL.class); final Properties ctx = InterfaceWrapperHelper.getCtx(sort); final String trxName = InterfaceWrapperHelper.getTrxName(sort); final IQuery<I_C_DocLine_Sort> activeDocLineSortSubQuery = queryBL.createQueryBuilder(I_C_DocLine_Sort.class, ctx, trxName) .setJoinOr() .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_DocLine_Sort.COLUMN_C_DocLine_Sort_ID, sort.getC_DocLine_Sort_ID()) .create(); // // Header query builder final IQueryBuilder<I_C_DocLine_Sort> docLineQueryBuilder = queryBL.createQueryBuilder(I_C_DocLine_Sort.class, ctx, trxName) .addInSubQueryFilter(I_C_DocLine_Sort.COLUMN_C_DocLine_Sort_ID, I_C_DocLine_Sort.COLUMN_C_DocLine_Sort_ID, activeDocLineSortSubQuery); // // IsDefault docLineQueryBuilder.addEqualsFilter(I_C_DocLine_Sort.COLUMN_IsDefault, sort.isDefault()); // // DocBaseType docLineQueryBuilder.addEqualsFilter(I_C_DocLine_Sort.COLUMN_DocBaseType, sort.getDocBaseType());
final IQuery<I_C_BP_DocLine_Sort> activeBPSubQuery = queryBL.createQueryBuilder(I_C_BP_DocLine_Sort.class, ctx, trxName) .setJoinOr() .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_DocLine_Sort.COLUMN_C_DocLine_Sort_ID, sort.getC_DocLine_Sort_ID()) .create(); // // Collect BPartner links final IQueryBuilder<I_C_BP_DocLine_Sort> bpQueryBuilder = docLineQueryBuilder .andCollectChildren(I_C_BP_DocLine_Sort.COLUMN_C_DocLine_Sort_ID, I_C_BP_DocLine_Sort.class) .addInSubQueryFilter(I_C_BP_DocLine_Sort.COLUMN_C_BP_DocLine_Sort_ID, I_C_BP_DocLine_Sort.COLUMN_C_BP_DocLine_Sort_ID, activeBPSubQuery); final List<Integer> bpIdSeen = new ArrayList<>(); final List<I_C_BP_DocLine_Sort> bpDocLineSortConfigs = bpQueryBuilder .create() .list(); for (final I_C_BP_DocLine_Sort bpDocLineSort : bpDocLineSortConfigs) { final int bpartnerId = bpDocLineSort.getC_BPartner_ID(); if (bpIdSeen.contains(bpartnerId)) { throw new AdempiereException("@DuplicateBPDocLineSort@"); } bpIdSeen.add(bpartnerId); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\docline\sort\model\validator\C_DocLine_Sort.java
1
请完成以下Java代码
private Stream<JsonExternalReferenceLookupItem> getAdditionalExternalReferenceItems(@NonNull final ExternalReference externalReference) { if ((externalReference.getExternalReferenceType() instanceof BPartnerExternalReferenceType)) { final BPartnerId bPartnerId = BPartnerId.ofRepoId(externalReference.getRecordId()); return getAdditionalExternalReferenceItems(bPartnerId, externalReference.getExternalSystem()); } return Stream.empty(); } @NonNull private Stream<JsonExternalReferenceLookupItem> getAdditionalExternalReferenceItems( @NonNull final BPartnerId bPartnerId, @NonNull final ExternalSystem externalSystem) { final ExternalReferenceResolver externalReferenceResolver = ExternalReferenceResolver.of(externalSystem, externalReferenceRepository); final BPartnerComposite bPartnerComposite = bpartnerCompositeRepository.getById(bPartnerId); final Stream<Integer> bPartnerLocationIds = bPartnerComposite.streamBPartnerLocationIds() .filter(Objects::nonNull) .map(BPartnerLocationId::getRepoId); final Stream.Builder<JsonExternalReferenceLookupItem> lookupItemCollector = Stream.builder(); externalReferenceResolver.getLookupItems(bPartnerLocationIds, BPLocationExternalReferenceType.BPARTNER_LOCATION) .forEach(lookupItemCollector::add); final Stream<Integer> bPartnerContactIds = bPartnerComposite.streamContactIds() .filter(Objects::nonNull) .map(BPartnerContactId::getRepoId); externalReferenceResolver.getLookupItems(bPartnerContactIds, ExternalUserReferenceType.USER_ID) .forEach(lookupItemCollector::add); return lookupItemCollector.build(); } @NonNull private static JsonExternalReferenceLookupItem toJsonExternalReferenceLookupItem(@NonNull final ExternalReference externalReference) { return JsonExternalReferenceLookupItem.builder() .id(externalReference.getExternalReference()) .type(externalReference.getExternalReferenceType().getCode()) .build(); } @Value(staticConstructor = "of")
private static class ExternalReferenceResolver { ExternalSystem externalSystemType; ExternalReferenceRepository externalReferenceRepository; public Stream<JsonExternalReferenceLookupItem> getLookupItems( @NonNull final Stream<Integer> metasfreshRecordIdStream, @NonNull final IExternalReferenceType externalReferenceType) { return metasfreshRecordIdStream .map(id -> GetExternalReferenceByRecordIdReq.builder() .recordId(id) .externalSystem(externalSystemType) .externalReferenceType(externalReferenceType) .build()) .map(externalReferenceRepository::getExternalReferenceByMFReference) .filter(Optional::isPresent) .map(Optional::get) .map(ExportExternalReferenceToRabbitMQService::toJsonExternalReferenceLookupItem); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\rabbitmqhttp\ExportExternalReferenceToRabbitMQService.java
1