instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Spring Boot application配置
spring.jpa.hibernate.ddl-auto=update spring.datasource.todos.url=jdbc:h2:mem:todos spring.datasource.todos.username=sa spring.datasource.todos.password=null spring.datasource.todos.driverClassName=org.h2.Driver spring.datasource.todos.hikari.connectionTimeout=44444 spring.datasource.topics.url=jdbc:h2:mem:top
ics spring.datasource.topics.username=sa spring.datasource.topics.password=null spring.datasource.topics.driverClassName=org.h2.Driver
repos\tutorials-master\persistence-modules\spring-data-jdbc\src\main\resources\application-multipledatasources.properties
2
请完成以下Spring Boot application配置
# redis config #redis机器ip spring.data.redis.host=127.0.0.1 #redis端口 spring.data.redis.port=6379 #redis密码 spring.data.redis.password= #目标数据库序号 spring.data.redis.database=1 #redis超时时间 spring.data.redis.connect-timeout=10000ms #连接池配置 #连接池中最小的空闲链接 默认为0 spring.data.redis.lettuce.pool.min-idle=0 #连接池中最大的空闲连接 默认为 8 spring.data.redis.lettu
ce.pool.max-idle=8 #连接池中的最大连接数 默认为8 spring.data.redis.lettuce.pool.max-active=8 #连接池最大阻塞等待时间 负值表示没有限制 spring.data.redis.lettuce.pool.min-idle=-1
repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-redis\src\main\resources\application.properties
2
请完成以下Java代码
public ImmutableSet<String> getEntityTypeNames() { return entries.keySet(); } public EntityTypeEntry getByEntityTypeOrNull(final String entityType) { Check.assumeNotEmpty(entityType, "entityType not empty"); // fail because in most of the cases is a development error return entries.get(entityType); } public EntityTypeEntry getByEntityType(final String entityType) { final EntityTypeEntry entry = getByEntityTypeOrNull(entityType); if (entry == null) { final AdempiereException ex = new AdempiereException("No EntityType entry found for entity type: " + entityType + "\n Available EntityTypes are: " + getEntityTypeNames()); logger.warn("", ex); } return entry; } public boolean isActive(final String entityType) { return getByEntityTypeOrNull(entityType) != null; } public boolean isDisplayedInUI(final String entityType) { final EntityTypeEntry entry = getByEntityTypeOrNull(entityType); if (entry == null) { return false; } return entry.isDisplayedInUI(); } public String getModelPackage(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return null; } return entry.getModelPackage(); } public String getWebUIServletListenerClass(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return null; } return entry.getWebUIServletListenerClass(); } public boolean isSystemMaintained(final String entityType) { final EntityTypeEntry entry = getByEntityType(entityType); if (entry == null) { return false; }
return entry.isSystemMaintained(); } } @Value @VisibleForTesting public static final class EntityTypeEntry { private final String entityType; private final String modelPackage; private final boolean displayedInUI; private final boolean systemMaintained; private final String webUIServletListenerClass; @Builder private EntityTypeEntry( final String entityType, final String modelPackage, final boolean displayedInUI, final boolean systemMaintained, final String webUIServletListenerClass) { super(); this.entityType = entityType; this.modelPackage = modelPackage; this.displayedInUI = displayedInUI; this.systemMaintained = systemMaintained; this.webUIServletListenerClass = webUIServletListenerClass; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\EntityTypesCache.java
1
请完成以下Java代码
private static ImmutableSet<String> extractFieldNames(final DocumentEntityDescriptor entityDescriptor) { return entityDescriptor.getFields().stream().map(DocumentFieldDescriptor::getFieldName).collect(ImmutableSet.toImmutableSet()); } public Set<String> findSimilar(String contextVariable) { final ImmutableSet.Builder<String> result = ImmutableSet.builder(); contextVariables.stream() .filter(item -> isSimilar(item, contextVariable)) .forEach(result::add); if (parent != null) { result.addAll(parent.findSimilar(contextVariable)); } return result.build(); } private static boolean isSimilar(@NonNull String contextVariable1, @NonNull String contextVariable2) { return contextVariable1.equalsIgnoreCase(contextVariable2); } public boolean contains(@NonNull final String contextVariable) { if (contextVariables.contains(contextVariable)) { return true; } if (knownMissing.contains(contextVariable)) { return true; } return parent != null && parent.contains(contextVariable); }
@Override @Deprecated public String toString() {return toSummaryString();} public String toSummaryString() { StringBuilder sb = new StringBuilder(); sb.append(name).append(":"); sb.append("\n\tContext variables: ").append(String.join(",", contextVariables)); if (!knownMissing.isEmpty()) { sb.append("\n\tKnown missing context variables: ").append(String.join(",", knownMissing)); } if (parent != null) { sb.append("\n--- parent: ----\n"); sb.append(parent.toSummaryString()); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariables.java
1
请完成以下Java代码
private static List<String> extract(TFDictionary suffixTreeSet, int size) { List<String> suffixList = new ArrayList<String>(size); for (TermFrequency termFrequency : suffixTreeSet.values()) { if (suffixList.size() >= size) break; suffixList.add(termFrequency.getKey()); } return suffixList; } /** * 此方法认为后缀一定是整个的词语,所以length是以词语为单位的 * @param length * @param size * @param extend * @return */ public List<String> extractSuffixByWords(int length, int size, boolean extend) { TFDictionary suffixTreeSet = new TFDictionary(); for (String key : tfDictionary.keySet()) { List<Term> termList = StandardTokenizer.segment(key); if (termList.size() > length) {
suffixTreeSet.add(combine(termList.subList(termList.size() - length, termList.size()))); if (extend) { for (int l = 1; l < length; ++l) { suffixTreeSet.add(combine(termList.subList(termList.size() - l, termList.size()))); } } } } return extract(suffixTreeSet, size); } private static String combine(List<Term> termList) { StringBuilder sbResult = new StringBuilder(); for (Term term : termList) { sbResult.append(term.word); } return sbResult.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\CommonSuffixExtractor.java
1
请完成以下Java代码
public int getDoc_User_ID() { return getSalesRep_ID(); } // getDoc_User_ID @Override public BigDecimal getApprovalAmt() { // TODO Auto-generated method stub return null; } @Override public int getC_Currency_ID() { // TODO Auto-generated method stub
return 0; } /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { final String docStatus = getDocStatus(); return DOCSTATUS_Completed.equals(docStatus) || DOCSTATUS_Closed.equals(docStatus) || DOCSTATUS_Reversed.equals(docStatus); } } // MDDOrder
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\model\MDDOrder.java
1
请完成以下Java代码
public void extractKeyParts(CacheKeyBuilder keyBuilder, Object targetObject, Object[] params) { // // include specified property values into the key for (final String keyProp : keyProperties) { if (targetObject instanceof PO) { final PO po = (PO)targetObject; if (po.get_ColumnIndex(keyProp) < 0) { final String msg = "Invalid keyProperty '" + keyProp + "' for cached method " + targetObject.getClass() // + "." + constructorOrMethod.getName() + ". Target PO has no such column; PO=" + po; throw new RuntimeException(msg); } final Object keyValue = po.get_Value(keyProp); keyBuilder.add(keyValue); } else { final StringBuilder getMethodName = new StringBuilder("get"); getMethodName.append(keyProp.substring(0, 1).toUpperCase());
getMethodName.append(keyProp.substring(1)); try { final Method method = targetObject.getClass().getMethod(getMethodName.toString()); final Object keyValue = method.invoke(targetObject); keyBuilder.add(keyValue); } catch (Exception e) { final String msg = "Invalid keyProperty '" + keyProp + "' for cached method " + targetObject.getClass().getName() // + "." + constructorOrMethod.getName() + ". Can't access getter method get" + keyProp + ". Exception " + e + "; message: " + e.getMessage(); throw new RuntimeException(msg, e); } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\TargetPOKeyPropertiesPartDescriptor.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_CM_AccessContainer[") .append(get_ID()).append("]"); return sb.toString(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */
public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Container getCM_Container() throws RuntimeException { return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name) .getPO(getCM_Container_ID(), get_TrxName()); } /** Set Web Container. @param CM_Container_ID Web Container contains content like images, text etc. */ public void setCM_Container_ID (int CM_Container_ID) { if (CM_Container_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID)); } /** Get Web Container. @return Web Container contains content like images, text etc. */ public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_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_CM_AccessContainer.java
1
请完成以下Java代码
public class User { private long id; private String email; private LocalDate birthDate; // constructors public User() { super(); } public User(long id, String email, LocalDate birthDate) { super(); this.id = id; this.email = email; this.birthDate = birthDate; } // getters and setters public long getId() { return id; } public void setId(long id) { this.id = id;
} public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getBirthDate() { return birthDate; } public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; } @Override public String toString() { return "User [id=" + id + ", email=" + email + ", birthDate=" + birthDate + "]"; } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\User.java
1
请完成以下Java代码
public java.math.BigDecimal getAssignedMoneyAmount () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedMoneyAmount); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Zugeordnete Menge. @param AssignedQuantity Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes */ @Override public void setAssignedQuantity (java.math.BigDecimal AssignedQuantity) { set_ValueNoCheck (COLUMNNAME_AssignedQuantity, AssignedQuantity); } /** Get Zugeordnete Menge. @return Zugeordneter Menge in der Maßeinheit des jeweiligen Produktes */ @Override public java.math.BigDecimal getAssignedQuantity () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssignedQuantity); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public de.metas.contracts.model.I_C_Flatrate_RefundConfig getC_Flatrate_RefundConfig() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class); } @Override public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig) { set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig); } /** Set C_Flatrate_RefundConfig. @param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */ @Override public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID) { if (C_Flatrate_RefundConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID)); } /** Get C_Flatrate_RefundConfig.
@return C_Flatrate_RefundConfig */ @Override public int getC_Flatrate_RefundConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) { if (C_Invoice_Candidate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java
1
请完成以下Java代码
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_QtyCUsPerTU.equals(parameter.getColumnName())) { final I_M_HU fromHU = getSingleSelectedPickingSlotTopLevelHU(); return retrieveQtyCU(fromHU); } else { return DEFAULT_VALUE_NOTAVAILABLE; } } @Override protected String doIt() throws Exception { if (qtyCUsPerTU == null || qtyCUsPerTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } final I_M_HU fromHU = getSingleSelectedPickingSlotTopLevelHU(); final IAllocationSource source = HUListAllocationSourceDestination .of(fromHU) .setDestroyEmptyHUs(true); final IHUProducerAllocationDestination destination = createHUProducer(fromHU); HULoader.of(source, destination) .setAllowPartialUnloads(false) .setAllowPartialLoads(false) .load(prepareUnloadRequest(fromHU, qtyCUsPerTU).setForceQtyAllocation(true).create()); // If the source HU was destroyed, then "remove" it from picking slots if (handlingUnitsBL.isDestroyedRefreshFirst(fromHU)) { pickingCandidateService.inactivateForHUId(HuId.ofRepoId(fromHU.getM_HU_ID())); } return MSG_OK; }
@Override protected void postProcess(final boolean success) { if (!success) { return; } // Invalidate views getPickingSlotsClearingView().invalidateAll(); getPackingHUsView().invalidateAll(); } private IHUProducerAllocationDestination createHUProducer(@NonNull final I_M_HU fromHU) { final PickingSlotRow pickingRow = getRootRowForSelectedPickingSlotRows(); final IHUStorageFactory storageFactory = Services.get(IHandlingUnitsBL.class).getStorageFactory(); final IHUStorage storage = storageFactory.getStorage(fromHU); final ProductId singleProductId = storage.getSingleProductIdOrNull(); final I_C_UOM uom = Services.get(IProductBL.class).getStockUOM(singleProductId); final LUTUProducerDestination lutuProducerDestination = createNewHUProducer(pickingRow, targetHUPI); lutuProducerDestination.addCUPerTU(singleProductId, qtyCUsPerTU, uom); return lutuProducerDestination; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutHUAndAddToNewHU.java
1
请完成以下Java代码
public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID) { if (MobileUI_UserProfile_Picking_ID < 1) set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null); else set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID); } @Override public int getMobileUI_UserProfile_Picking_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID); } @Override public void setPickingProfile_Filter_ID (final int PickingProfile_Filter_ID) { if (PickingProfile_Filter_ID < 1) set_ValueNoCheck (COLUMNNAME_PickingProfile_Filter_ID, null); else set_ValueNoCheck (COLUMNNAME_PickingProfile_Filter_ID, PickingProfile_Filter_ID); } @Override public int getPickingProfile_Filter_ID() {
return get_ValueAsInt(COLUMNNAME_PickingProfile_Filter_ID); } @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.adempiere.adempiere\base\src\main\java-gen\de\metas\picking\model\X_PickingProfile_Filter.java
1
请完成以下Java代码
private static void assertNotChangingRegularAndCustomizationFields(final I_AD_Element_Trl adElementTrl) { final Set<String> changedRegularFields = new HashSet<>(); final Set<String> changedCustomizationFields = new HashSet<>(); if (isValueChanged(adElementTrl, I_AD_Element_Trl.COLUMNNAME_IsUseCustomization)) { changedCustomizationFields.add(I_AD_Element_Trl.COLUMNNAME_IsUseCustomization); } // for (final ADElementTranslatedColumn field : ADElementTranslatedColumn.values()) { if (field.hasCustomizedField() && isValueChanged(adElementTrl, field.getCustomizationColumnName())) { changedCustomizationFields.add(field.getCustomizationColumnName()); } if (isValueChanged(adElementTrl, field.getColumnName())) { changedRegularFields.add(field.getColumnName()); } } // if (!changedRegularFields.isEmpty() && !changedCustomizationFields.isEmpty()) { throw new AdempiereException("Changing regular fields and customization fields is not allowed." + "\n Regular fields changed: " + changedRegularFields + "\n Customization fields changed: " + changedCustomizationFields) .markAsUserValidationError(); } } private static boolean isValueChanged(final I_AD_Element_Trl adElementTrl, final String columnName) { return InterfaceWrapperHelper.isValueChanged(adElementTrl, columnName); } private enum ADElementTranslatedColumn { Name(I_AD_Element_Trl.COLUMNNAME_Name, I_AD_Element_Trl.COLUMNNAME_Name_Customized), // Description(I_AD_Element_Trl.COLUMNNAME_Description, I_AD_Element_Trl.COLUMNNAME_Description_Customized), // Help(I_AD_Element_Trl.COLUMNNAME_Help, I_AD_Element_Trl.COLUMNNAME_Help_Customized), // PrintName(I_AD_Element.COLUMNNAME_PrintName), //
PO_Description(I_AD_Element.COLUMNNAME_PO_Description), // PO_Help(I_AD_Element.COLUMNNAME_PO_Help), // PO_Name(I_AD_Element.COLUMNNAME_PO_Name), // PO_PrintName(I_AD_Element.COLUMNNAME_PO_PrintName), // CommitWarning(I_AD_Element.COLUMNNAME_CommitWarning), // WebuiNameBrowse(I_AD_Element.COLUMNNAME_WEBUI_NameBrowse), // WebuiNameNew(I_AD_Element.COLUMNNAME_WEBUI_NameNew), // WebuiNameNewBreadcrumb(I_AD_Element.COLUMNNAME_WEBUI_NameNewBreadcrumb) // ; @Getter private final String columnName; @Getter private final String customizationColumnName; ADElementTranslatedColumn(@NonNull final String columnName) { this.columnName = columnName; this.customizationColumnName = null; } ADElementTranslatedColumn( @NonNull final String columnName, @Nullable final String customizationColumnName) { this.columnName = columnName; this.customizationColumnName = customizationColumnName; } public boolean hasCustomizedField() { return getCustomizationColumnName() != null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\translation\interceptor\AD_Element_Trl.java
1
请完成以下Java代码
public String getDisplayName() { final I_M_Product product = Services.get(IProductDAO.class).getById(getProductId()); final StringBuilder name = new StringBuilder() .append(product.getName()).append("#").append(product.getM_Product_ID()); return name.toString(); } @Override public IHUDocumentLine getReversal() { throw new UnsupportedOperationException("Getting reversal for " + this + " is not supported"); } @Override public ProductId getProductId() { return storage.getProductId(); } @Override public BigDecimal getQty() { return storage.getQtyCapacity(); } @Override public I_C_UOM getC_UOM() { return storage.getC_UOM(); } @Override public BigDecimal getQtyAllocated() { return storage.getQtyFree(); } @Override public BigDecimal getQtyToAllocate() { return storage.getQty().toBigDecimal(); } @Override public Object getTrxReferencedModel() {
return referenceModel; } protected IProductStorage getStorage() { return storage; } @Override public IAllocationSource createAllocationSource(final I_M_HU hu) { return HUListAllocationSourceDestination.of(hu); } @Override public boolean isReadOnly() { return readonly; } @Override public void setReadOnly(final boolean readonly) { this.readonly = readonly; } @Override public I_M_HU_Item getInnerHUItem() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java
1
请完成以下Java代码
public static boolean isNew(final Object model) { return getDocument(model).isNew(); } public <T> T getDynAttribute(final String attributeName) { return getDocument().getDynAttribute(attributeName); } public Object setDynAttribute(final String attributeName, final Object value) { return getDocument().setDynAttribute(attributeName, value); } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { final DocumentInterfaceWrapper wrapper = getWrapper(model); return wrapper == null ? false : wrapper.isOldValues(); } @Override public Set<String> getColumnNames() { return document.getFieldNames(); } @Override public int getColumnIndex(final String columnName) { throw new UnsupportedOperationException("DocumentInterfaceWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isReadonlyVirtualField(); } @Override public boolean isKeyColumnName(final String columnName)
{ final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isKey(); } @Override public boolean isCalculated(final String columnName) { final IDocumentFieldView field = document.getFieldViewOrNull(columnName); return field != null && field.isCalculated(); } @Override public boolean setValueNoCheck(final String columnName, final Object value) { return setValue(columnName, value); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapper.java
1
请完成以下Java代码
public PublicKeyCredentialCreationOptionsBuilder excludeCredentials( List<PublicKeyCredentialDescriptor> excludeCredentials) { this.excludeCredentials = excludeCredentials; return this; } /** * Sets the {@link #getAuthenticatorSelection()} property. * @param authenticatorSelection the authenticator selection * @return the PublicKeyCredentialCreationOptionsBuilder */ public PublicKeyCredentialCreationOptionsBuilder authenticatorSelection( AuthenticatorSelectionCriteria authenticatorSelection) { this.authenticatorSelection = authenticatorSelection; return this; } /** * Sets the {@link #getAttestation()} property. * @param attestation the attestation * @return the PublicKeyCredentialCreationOptionsBuilder */ public PublicKeyCredentialCreationOptionsBuilder attestation(AttestationConveyancePreference attestation) { this.attestation = attestation; return this; } /** * Sets the {@link #getExtensions()} property. * @param extensions the extensions * @return the PublicKeyCredentialCreationOptionsBuilder */ public PublicKeyCredentialCreationOptionsBuilder extensions(AuthenticationExtensionsClientInputs extensions) { this.extensions = extensions; return this; }
/** * Allows customizing the builder using the {@link Consumer} that is passed in. * @param customizer the {@link Consumer} that can be used to customize the * {@link PublicKeyCredentialCreationOptionsBuilder} * @return the PublicKeyCredentialCreationOptionsBuilder */ public PublicKeyCredentialCreationOptionsBuilder customize( Consumer<PublicKeyCredentialCreationOptionsBuilder> customizer) { customizer.accept(this); return this; } /** * Builds a new {@link PublicKeyCredentialCreationOptions} * @return the new {@link PublicKeyCredentialCreationOptions} */ public PublicKeyCredentialCreationOptions build() { return new PublicKeyCredentialCreationOptions(this.rp, this.user, this.challenge, this.pubKeyCredParams, this.timeout, this.excludeCredentials, this.authenticatorSelection, this.attestation, this.extensions); } } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialCreationOptions.java
1
请完成以下Java代码
public LocalDate getCreationDate() { return creationDate; } public LocalDate getLastLoginDate() { return lastLoginDate; } public void setLastLoginDate(LocalDate lastLoginDate) { this.lastLoginDate = lastLoginDate; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public String toString() { return "User [name=" + name + ", id=" + id + "]"; } @Override public boolean equals(Object o) { if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && age == user.age && Objects.equals(name, user.name) && Objects.equals(creationDate, user.creationDate) && Objects.equals(email, user.email) && Objects.equals(status, user.status); } @Override public int hashCode() { return Objects.hash(id, name, creationDate, age, email, status); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\query\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public class SysConfigUIDefaultsRepository { public static SysConfigUIDefaultsRepository ofLookAndFeelId(final String lookAndFeelId) { return new SysConfigUIDefaultsRepository(lookAndFeelId); } public static SysConfigUIDefaultsRepository ofCurrentLookAndFeelId() { final String lookAndFeelId = UIManager.getLookAndFeel().getID(); return new SysConfigUIDefaultsRepository(lookAndFeelId); } // services private static final transient Logger logger = LogManager.getLogger(SysConfigUIDefaultsRepository.class); private final UIDefaultsSerializer serializer = new UIDefaultsSerializer(); private final transient ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); private final transient IDeveloperModeBL developerModeBL = Services.get(IDeveloperModeBL.class); private static final String SYSCONFIG_PREFIX = "LAF."; private final String lookAndFeelId; public SysConfigUIDefaultsRepository(final String lookAndFeelId) { super(); Check.assumeNotEmpty(lookAndFeelId, "lookAndFeelId not empty"); this.lookAndFeelId = lookAndFeelId; } public void setValue(final Object key, final Object value) { final String sysconfigName = createSysConfigName(key); try { final String sysconfigValue = serializer.toString(value); saveSysConfig(sysconfigName, sysconfigValue); } catch (Exception e) { logger.error("Failed saving " + sysconfigName + ": " + value, e); } } private void saveSysConfig(final String sysconfigName, final String sysconfigValue) { if (!DB.isConnected()) { logger.warn("DB not connected. Cannot write: " + sysconfigName + "=" + sysconfigValue); return; } developerModeBL.executeAsSystem(new ContextRunnable() { @Override public void run(Properties sysCtx) { sysConfigBL.setValue(sysconfigName, sysconfigValue, ClientId.SYSTEM, OrgId.ANY); } }); }
private String createSysConfigName(Object key) { return createSysConfigPrefix() + "." + key.toString(); } private String createSysConfigPrefix() { return SYSCONFIG_PREFIX + lookAndFeelId; } public void loadAllFromSysConfigTo(final UIDefaults uiDefaults) { if (!DB.isConnected()) { return; } final String prefix = createSysConfigPrefix() + "."; final boolean removePrefix = true; final Properties ctx = Env.getCtx(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx)); final Map<String, String> map = sysConfigBL.getValuesForPrefix(prefix, removePrefix, clientAndOrgId); for (final Map.Entry<String, String> mapEntry : map.entrySet()) { final String key = mapEntry.getKey(); final String valueStr = mapEntry.getValue(); try { final Object value = serializer.fromString(valueStr); uiDefaults.put(key, value); } catch (Exception ex) { logger.warn("Failed loading " + key + ": " + valueStr + ". Skipped.", ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SysConfigUIDefaultsRepository.java
2
请完成以下Java代码
public void destroy() throws Exception { unregister(this.registered); } private Collection<ObjectName> register() { return this.endpoints.stream().filter(this::hasOperations).map(this::register).toList(); } private boolean hasOperations(ExposableJmxEndpoint endpoint) { return !CollectionUtils.isEmpty(endpoint.getOperations()); } private ObjectName register(ExposableJmxEndpoint endpoint) { Assert.notNull(endpoint, "'endpoint' must not be null"); try { ObjectName name = this.objectNameFactory.getObjectName(endpoint); EndpointMBean mbean = new EndpointMBean(this.responseMapper, this.classLoader, endpoint); this.mBeanServer.registerMBean(mbean, name); return name; } catch (MalformedObjectNameException ex) { throw new IllegalStateException("Invalid ObjectName for " + getEndpointDescription(endpoint), ex); } catch (Exception ex) { throw new MBeanExportException("Failed to register MBean for " + getEndpointDescription(endpoint), ex); } } private void unregister(Collection<ObjectName> objectNames) { objectNames.forEach(this::unregister); } private void unregister(ObjectName objectName) { try { if (logger.isDebugEnabled()) { logger.debug("Unregister endpoint with ObjectName '" + objectName + "' from the JMX domain");
} this.mBeanServer.unregisterMBean(objectName); } catch (InstanceNotFoundException ex) { // Ignore and continue } catch (MBeanRegistrationException ex) { throw new JmxException("Failed to unregister MBean with ObjectName '" + objectName + "'", ex); } } private String getEndpointDescription(ExposableJmxEndpoint endpoint) { return "endpoint '" + endpoint.getEndpointId() + "'"; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\JmxEndpointExporter.java
1
请完成以下Java代码
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId, Authentication principal, ServerWebExchange exchange) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(exchange, "exchange cannot be null"); // @formatter:off return exchange.getSession() .map(this::getAuthorizedClients) .flatMap((clients) -> Mono.justOrEmpty((T) clients.get(clientRegistrationId))); // @formatter:on } @Override public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, ServerWebExchange exchange) { Assert.notNull(authorizedClient, "authorizedClient cannot be null"); Assert.notNull(exchange, "exchange cannot be null"); // @formatter:off return exchange.getSession() .doOnSuccess((session) -> { Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session); authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient); session.getAttributes().put(this.sessionAttributeName, authorizedClients); }) .then(Mono.empty()); // @formatter:on } @Override public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal, ServerWebExchange exchange) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); Assert.notNull(exchange, "exchange cannot be null"); // @formatter:off return exchange.getSession() .doOnSuccess((session) -> { Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session); authorizedClients.remove(clientRegistrationId); if (authorizedClients.isEmpty()) { session.getAttributes().remove(this.sessionAttributeName); } else { session.getAttributes().put(this.sessionAttributeName, authorizedClients); } }) .then(Mono.empty()); // @formatter:on } private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(WebSession session) { Assert.notNull(session, "session cannot be null"); Map<String, OAuth2AuthorizedClient> authorizedClients = session.getAttribute(this.sessionAttributeName); return (authorizedClients != null) ? authorizedClients : new HashMap<>(); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\WebSessionServerOAuth2AuthorizedClientRepository.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String get(String key) { return null; } @Override public boolean descriptions() { return obtain(PrometheusProperties::isDescriptions, PrometheusConfig.super::descriptions); } @Override public Duration step() { return obtain(PrometheusProperties::getStep, PrometheusConfig.super::step); } @Override public @Nullable Properties prometheusProperties() { return get(this::fromPropertiesMap, PrometheusConfig.super::prometheusProperties);
} private @Nullable Properties fromPropertiesMap(PrometheusProperties prometheusProperties) { Map<String, String> additionalProperties = prometheusProperties.getProperties(); if (additionalProperties.isEmpty()) { return null; } Properties properties = PrometheusConfig.super.prometheusProperties(); if (properties == null) { properties = new Properties(); } properties.putAll(additionalProperties); return properties; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusPropertiesConfigAdapter.java
2
请完成以下Java代码
public static MSV3OrderSyncResponse error(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId, @NonNull final Throwable ex) { String errorMsg = ex.getLocalizedMessage(); if (errorMsg == null || errorMsg.trim().length() < 5) { errorMsg = ex.toString(); } return _builder() .orderId(orderId) .bpartnerId(bpartnerId) .errorMsg(errorMsg) .build(); } @JsonProperty("bpartnerId") BPartnerId bpartnerId; @JsonProperty("orderId") Id orderId; @JsonProperty("errorMsg") String errorMsg; @JsonProperty("items")
List<MSV3OrderSyncResponseItem> items; @Builder(builderMethodName = "_builder") @JsonCreator private MSV3OrderSyncResponse( @JsonProperty("orderId") @NonNull final Id orderId, @JsonProperty("bpartnerId") @NonNull final BPartnerId bpartnerId, @JsonProperty("errorMsg") final String errorMsg, @JsonProperty("items") @Singular final List<MSV3OrderSyncResponseItem> items) { this.bpartnerId = bpartnerId; this.orderId = orderId; this.errorMsg = errorMsg; this.items = items != null ? ImmutableList.copyOf(items) : ImmutableList.of(); } public boolean isError() { return errorMsg != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\protocol\MSV3OrderSyncResponse.java
1
请在Spring Boot框架中完成以下Java代码
public class ShipmentScheduleId implements RepoIdAware { private static final String M_SHIPMENT_SCHEDULE_TABLE_NAME = "M_ShipmentSchedule"; public static ShipmentScheduleId ofRepoId(final int repoId) { return new ShipmentScheduleId(repoId); } public static ShipmentScheduleId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } // NOTE: we need this String deserializer in order to use ShipmentScheduleId as a map key in a map that needs to deserialized from json @JsonCreator public static ShipmentScheduleId ofString(@NonNull final String repoIdStr) { return RepoIdAwares.ofObject(repoIdStr, ShipmentScheduleId.class, ShipmentScheduleId::ofRepoId); } public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<ShipmentScheduleId> ids) { if (ids.isEmpty()) { return ImmutableSet.of(); } return ids.stream().map(ShipmentScheduleId::getRepoId).collect(ImmutableSet.toImmutableSet()); } public static ImmutableSet<ShipmentScheduleId> fromIntSet(@NonNull final Collection<Integer> repoIds) { if (repoIds.isEmpty()) { return ImmutableSet.of(); }
return repoIds.stream().map(ShipmentScheduleId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet()); } int repoId; private ShipmentScheduleId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_ShipmentSchedule_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final ShipmentScheduleId id) { return id != null ? id.getRepoId() : -1; } public TableRecordReference toTableRecordReference() { return TableRecordReference.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, getRepoId()); } public static boolean equals(@Nullable final ShipmentScheduleId id1, @Nullable final ShipmentScheduleId id2) {return Objects.equals(id1, id2);} public static TableRecordReferenceSet toTableRecordReferenceSet(@NonNull final Collection<ShipmentScheduleId> ids) { return TableRecordReferenceSet.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, ids); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\ShipmentScheduleId.java
2
请完成以下Java代码
public static Sheet getSheet(Workbook workbook, String sheetName) { return workbook.getSheet(sheetName); } public static List<String> getColumnNames1(Sheet sheet) { List<String> columnNames = new ArrayList<>(); Row headerRow = sheet.getRow(0); if (headerRow != null) { for (Cell cell : headerRow) { if (cell.getCellType() != CellType.BLANK && cell.getStringCellValue() != null && !cell.getStringCellValue() .trim() .isEmpty()) { columnNames.add(cell.getStringCellValue() .trim()); } } } return columnNames;
} public static List<String> getColumnNames(Sheet sheet) { Row headerRow = sheet.getRow(0); if (headerRow == null) { return Collections.EMPTY_LIST; } return StreamSupport.stream(headerRow.spliterator(), false) .filter(cell -> cell.getCellType() != CellType.BLANK) .map(nonEmptyCell -> nonEmptyCell.getStringCellValue()) .filter(cellValue -> cellValue != null && !cellValue.trim() .isEmpty()) .map(String::trim) .collect(Collectors.toList()); } }
repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\poi\columnnames\ExcelUtils.java
1
请完成以下Java代码
public String getBrandStory() { return brandStory; } public void setBrandStory(String brandStory) { this.brandStory = brandStory; } @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(", name=").append(name); sb.append(", firstLetter=").append(firstLetter); sb.append(", sort=").append(sort); sb.append(", factoryStatus=").append(factoryStatus); sb.append(", showStatus=").append(showStatus); sb.append(", productCount=").append(productCount); sb.append(", productCommentCount=").append(productCommentCount); sb.append(", logo=").append(logo); sb.append(", bigPic=").append(bigPic); sb.append(", brandStory=").append(brandStory); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrand.java
1
请完成以下Java代码
public String toString() { return "POInfo.Column[" + ColumnName + ",ID=" + AD_Column_ID + ",DisplayType=" + this.displayType + ",ColumnClass=" + ColumnClass + "]"; } // toString @Nullable private static BigDecimal toBigDecimalOrNull(final String valueStr, final String name) { final String valueNorm = StringUtils.trimBlankToNull(valueStr); if(valueNorm == null) { return null; } try { return new BigDecimal(valueNorm); } catch (final Exception ex) // i.e. NumberFormatException { logger.error("Cannot parse {}=`{}`. Returning null.", name, valueNorm, ex); return null; } } public String getColumnName() { return this.ColumnName; } public AdColumnId getAD_Column_ID() { return this.AD_Column_ID; } boolean isTranslated() { return this.IsTranslated; } public String getColumnSQL() { return this.ColumnSQL; } public boolean isVirtualColumn() { return this.virtualColumn; } public String getColumnSqlForSelect() { return sqlColumnForSelect; } public ReferenceId getAD_Reference_Value_ID() { return AD_Reference_Value_ID; } public boolean isSelectionColumn() { return IsSelectionColumn; } public boolean isMandatory() { return IsMandatory; } public boolean isKey() { return IsKey; } public boolean isParent() { return IsParent; } public boolean isStaleable() { return IsStaleable; }
public boolean isLookup() { return org.compiere.util.DisplayType.isLookup(displayType); } public int getAD_Sequence_ID() { return AD_Sequence_ID; } public boolean isIdentifier() { return IsIdentifier; } @Nullable public String getReferencedTableNameOrNull() { return _referencedTableName.orElse(null); } private static Optional<String> computeReferencedTableName( final int displayType, @Nullable final TableName adReferenceValueTableName) { // Special lookups (Location, Locator etc) final String refTableName = DisplayType.getTableName(displayType); if (refTableName != null) { return Optional.of(refTableName); } if (DisplayType.isLookup(displayType) && adReferenceValueTableName != null) { return Optional.of(adReferenceValueTableName.getAsString()); } return Optional.empty(); } public boolean isPasswordColumn() { return DisplayType.isPassword(ColumnName, displayType); } } // POInfoColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfoColumn.java
1
请完成以下Java代码
public String getCdtrNames() { return entry.getNtryDtls().stream() .flatMap(entryDetails1 -> entryDetails1.getTxDtls().stream()) .map(EntryTransaction2::getRltdPties) .filter(party -> party != null && party.getCdtr() != null) .map(party -> party.getCdtr().getNm()) .filter(Check::isNotBlank) .collect(Collectors.joining(" ")); } @Override @Nullable public String getLineReference() { return entry.getNtryRef(); } @Override @NonNull protected String getUnstructuredRemittanceInfo(@NonNull final String delimiter) { return String.join(delimiter, getUnstructuredRemittanceInfoList()); } @Override @NonNull protected List<String> getUnstructuredRemittanceInfoList() { return getEntryTransaction() .stream() .findFirst() .map(EntryTransaction2::getRmtInf) .map(RemittanceInformation5::getUstrd) .orElse(ImmutableList.of()) .stream() .map(str -> Arrays.asList(str.split(" "))) .flatMap(List::stream) .filter(Check::isNotBlank) .collect(Collectors.toList()); } @Override @NonNull protected String getLineDescription(@NonNull final String delimiter) { return getLineDescriptionList().stream() .filter(Check::isNotBlank) .collect(Collectors.joining(delimiter)); } @Override @NonNull protected List<String> getLineDescriptionList() { final List<String> lineDesc = new ArrayList<>();
final String addtlNtryInfStr = entry.getAddtlNtryInf(); if (addtlNtryInfStr != null) { lineDesc.addAll( Arrays.stream(addtlNtryInfStr.split(" ")) .filter(Check::isNotBlank) .collect(Collectors.toList())); } final List<String> trxDetails = getEntryTransaction() .stream() .map(EntryTransaction2::getAddtlTxInf) .filter(Objects::nonNull) .map(str -> Arrays.asList(str.split(" "))) .flatMap(List::stream) .filter(Check::isNotBlank) .collect(Collectors.toList()); lineDesc.addAll(trxDetails); return lineDesc; } @Override @Nullable protected String getCcy() { return entry.getAmt().getCcy(); } @Override @Nullable protected BigDecimal getAmtValue() { return entry.getAmt().getValue(); } public boolean isBatchTransaction() {return getEntryTransaction().size() > 1;} @Override public List<ITransactionDtlsWrapper> getTransactionDtlsWrapper() { return getEntryTransaction() .stream() .map(tr -> TransactionDtls2Wrapper.builder().entryDtls(tr).build()) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\v02\BatchReportEntry2Wrapper.java
1
请完成以下Java代码
protected boolean ignoreApplicationContext(@Nullable ApplicationContext applicationContext) { return false; } protected Supplier<C> getContext(ServerWebExchange exchange) { Supplier<C> context = this.context; if (context == null) { synchronized (this.contextLock) { context = this.context; if (context == null) { context = createContext(exchange); initialized(context); this.context = context; } } } return context; } /** * Called once the context has been initialized. * @param context a supplier for the initialized context (may throw an exception) */ protected void initialized(Supplier<C> context) { } @SuppressWarnings("unchecked") private Supplier<C> createContext(ServerWebExchange exchange) { ApplicationContext context = exchange.getApplicationContext(); Assert.state(context != null, "No ApplicationContext found on ServerWebExchange."); if (this.contextClass.isInstance(context)) { return () -> (C) context; } return () -> context.getBean(this.contextClass);
} /** * Returns {@code true} if the specified context is a * {@link WebServerApplicationContext} with a matching server namespace. * @param context the context to check * @param serverNamespace the server namespace to match against * @return {@code true} if the server namespace of the context matches * @since 4.0.1 */ protected final boolean hasServerNamespace(@Nullable ApplicationContext context, String serverNamespace) { if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) { return false; } return WebServerApplicationContext.hasServerNamespace(context, serverNamespace); } /** * Returns the server namespace if the specified context is a * {@link WebServerApplicationContext}. * @param context the context * @return the server namespace or {@code null} if the context is not a * {@link WebServerApplicationContext} * @since 4.0.1 */ protected final @Nullable String getServerNamespace(@Nullable ApplicationContext context) { if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) { return null; } return WebServerApplicationContext.getServerNamespace(context); } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\web\reactive\ApplicationContextServerWebExchangeMatcher.java
1
请完成以下Java代码
public int rows() { return getRowDimension(); } public int cols() { return getColumnDimension(); } /** * 取出第j列作为一个列向量 * @param j * @return */ public Matrix col(int j) { double[][] X = new double[m][1]; for (int i = 0; i < m; i++) { X[i][0] = A[i][j]; } return new Matrix(X); } /** * 取出第i行作为一个行向量 * @param i * @return */ public Matrix row(int i) { double[][] X = new double[1][n]; for (int j = 0; j < n; j++) { X[0][j] = A[i][j]; } return new Matrix(X); } public Matrix block(int i, int j, int p, int q) { return getMatrix(i, i + p - 1, j, j + q - 1); } /** * 返回矩阵的立方(以数组形式) * @return */ public double[][] cube() { double[][] X = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++)
{ X[i][j] = Math.pow(A[i][j], 3.); } } return X; } public void setZero() { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = 0.; } } } public void save(DataOutputStream out) throws Exception { out.writeInt(m); out.writeInt(n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { out.writeDouble(A[i][j]); } } } public boolean load(ByteArray byteArray) { m = byteArray.nextInt(); n = byteArray.nextInt(); A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = byteArray.nextDouble(); } } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Matrix.java
1
请完成以下Java代码
public String modelFileFolder() { return outputFolder() + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); } /** * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated */ @Override public String apiFileFolder() { return outputFolder() + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); } /** * Use this callback to extend the standard set of lambdas available to templates.
* @return */ @Override protected ImmutableMap.Builder<String, Mustache.Lambda> addMustacheLambdas() { // Start with parent lambdas ImmutableMap.Builder<String, Mustache.Lambda> builder = super.addMustacheLambdas(); // Add custom lambda to convert operationIds in suitable java constants return builder.put("javaconstant", new JavaConstantLambda()) .put("path", new PathLambda()); } static final List<String> JAVA_RESERVED_WORDS = Arrays.asList("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "continue", "const", "default", "do", "double", "else", "enum", "exports", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "module", "native", "new", "package", "private", "protected", "public", "requires", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "var", "void", "volatile", "while"); }
repos\tutorials-master\spring-swagger-codegen-modules\openapi-custom-generator\src\main\java\com\baeldung\openapi\generators\camelclient\JavaCamelClientGenerator.java
1
请完成以下Java代码
public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board() { return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); } @Override public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board) { set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board); } @Override public void setWEBUI_Board_ID (final int WEBUI_Board_ID) { if (WEBUI_Board_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID); } @Override public int getWEBUI_Board_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID);
} @Override public void setWEBUI_Board_Lane_ID (final int WEBUI_Board_Lane_ID) { if (WEBUI_Board_Lane_ID < 1) set_ValueNoCheck (COLUMNNAME_WEBUI_Board_Lane_ID, null); else set_ValueNoCheck (COLUMNNAME_WEBUI_Board_Lane_ID, WEBUI_Board_Lane_ID); } @Override public int getWEBUI_Board_Lane_ID() { return get_ValueAsInt(COLUMNNAME_WEBUI_Board_Lane_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_Lane.java
1
请完成以下Java代码
public BPartnerId getBill_BPartner_ID() { return BPartnerId.ofRepoId(getC_Flatrate_Term().getBill_BPartner_ID()); } @Override public int getBill_Location_ID() { return getC_Flatrate_Term().getBill_Location_ID(); } @Override public int getBill_User_ID() { return getC_Flatrate_Term().getBill_User_ID(); } @Override public int getC_Currency_ID() { return Services.get(IPriceListDAO.class).getById(PriceListId.ofRepoId(getM_PriceList_Version().getM_PriceList_ID())).getC_Currency_ID(); } @Override public CountryId getCountryId() { return CoalesceUtil.coalesceSuppliersNotNull( // first, try the contract's location from the tine the contract was created () -> { final I_C_Location billLocationValue = getC_Flatrate_Term().getBill_Location_Value(); return billLocationValue != null ? CountryId.ofRepoId(billLocationValue.getC_Country_ID()) : null; }, // second, try the current C_Location of the C_BPartner_Location () -> { final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class); return bPartnerDAO.getCountryId(BPartnerLocationId.ofRepoId(getC_Flatrate_Term().getBill_BPartner_ID(), getC_Flatrate_Term().getBill_Location_ID())); } ); } @Override public I_M_PriceList_Version getM_PriceList_Version() { return _priceListVersion; } @Override public PricingSystemId getPricingSystemId() { PricingSystemId pricingSystemId = _pricingSystemId; if (pricingSystemId == null)
{ pricingSystemId = _pricingSystemId = PricingSystemId.ofRepoId(getC_Flatrate_Term().getM_PricingSystem_ID()); } return pricingSystemId; } @Override public I_C_Flatrate_Term getC_Flatrate_Term() { if (_flatrateTerm == null) { _flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID()); // shouldn't be null because we prevent even material-tracking purchase orders without a flatrate term. Check.errorIf(_flatrateTerm == null, "M_Material_Tracking {} has no flatrate term", materialTracking); } return _flatrateTerm; } @Override public String getInvoiceRule() { if (!_invoiceRuleSet) { // // Try getting the InvoiceRule from Flatrate Term final I_C_Flatrate_Term flatrateTerm = getC_Flatrate_Term(); final String invoiceRule = flatrateTerm .getC_Flatrate_Conditions() .getInvoiceRule(); Check.assumeNotEmpty(invoiceRule, "Unable to retrieve invoiceRule from materialTracking {}", materialTracking); _invoiceRule = invoiceRule; _invoiceRuleSet = true; } return _invoiceRule; } /* package */void setM_PriceList_Version(final I_M_PriceList_Version priceListVersion) { _priceListVersion = priceListVersion; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingAsVendorInvoicingInfo.java
1
请完成以下Spring Boot application配置
server: port: 8080 servlet: context-path: /demo spring: datasource: hikari: username: root password: root driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false
&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8 mybatis-plus: global-config: # 关闭banner banner: false
repos\spring-boot-demo-master\demo-rbac-shiro\src\main\resources\application.yml
2
请完成以下Java代码
protected void executeExecutionListeners(HasExecutionListeners elementWithExecutionListeners, String eventType) { executeExecutionListeners(elementWithExecutionListeners, execution, eventType); } /** * Executes the execution listeners defined on the given element, with the given event type, * and passing the provided execution to the {@link ExecutionListener} instances. */ protected void executeExecutionListeners( HasExecutionListeners elementWithExecutionListeners, ExecutionEntity executionEntity, String eventType ) { commandContext .getProcessEngineConfiguration() .getListenerNotificationHelper() .executeExecutionListeners(elementWithExecutionListeners, executionEntity, eventType); } /** * Returns the first parent execution of the provided execution that is a scope. */ protected ExecutionEntity findFirstParentScopeExecution(ExecutionEntity executionEntity) { ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); ExecutionEntity parentScopeExecution = null; ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(executionEntity.getParentId()); while (currentlyExaminedExecution != null && parentScopeExecution == null) { if (currentlyExaminedExecution.isScope()) { parentScopeExecution = currentlyExaminedExecution; } else {
currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId()); } } return parentScopeExecution; } public CommandContext getCommandContext() { return commandContext; } public void setCommandContext(CommandContext commandContext) { this.commandContext = commandContext; } public Agenda getAgenda() { return agenda; } public void setAgenda(DefaultActivitiEngineAgenda agenda) { this.agenda = agenda; } public ExecutionEntity getExecution() { return execution; } public void setExecution(ExecutionEntity execution) { this.execution = execution; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\AbstractOperation.java
1
请完成以下Java代码
public void onRefresh(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onRefresh(calloutRecord); } } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onRefreshAll(calloutRecord); } } @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { for (final ITabCallout tabCallout : tabCallouts) { tabCallout.onAfterQuery(calloutRecord); } } public static final class Builder { private final List<ITabCallout> tabCalloutsAll = new ArrayList<>(); private Builder() { super(); } public ITabCallout build() {
if (tabCalloutsAll.isEmpty()) { return ITabCallout.NULL; } else if (tabCalloutsAll.size() == 1) { return tabCalloutsAll.get(0); } else { return new CompositeTabCallout(tabCalloutsAll); } } public Builder addTabCallout(final ITabCallout tabCallout) { Check.assumeNotNull(tabCallout, "tabCallout not null"); if (tabCalloutsAll.contains(tabCallout)) { return this; } tabCalloutsAll.add(tabCallout); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\impl\CompositeTabCallout.java
1
请在Spring Boot框架中完成以下Java代码
private String getNewToken(String sessionId, Long userId) { String src = sessionId + userId + NumberUtil.genRandomNum(4); return SystemUtil.genToken(src); } @Override public AdminUser selectById(Long id) { return adminUserDao.getAdminUserById(id); } @Override public AdminUser selectByUserName(String userName) { return adminUserDao.getAdminUserByUserName(userName); } @Override public int save(AdminUser user) { //密码加密 user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8")); return adminUserDao.addUser(user);
} @Override public int updatePassword(AdminUser user) { return adminUserDao.updateUserPassword(user.getId(), MD5Util.MD5Encode(user.getPassword(), "UTF-8")); } @Override public int deleteBatch(Integer[] ids) { return adminUserDao.deleteBatch(ids); } @Override public AdminUser getAdminUserByToken(String userToken) { return adminUserDao.getAdminUserByToken(userToken); } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\service\impl\AdminUserServiceImpl.java
2
请完成以下Java代码
public LocalDate getAsLocalDate() {return LocalDate.parse(value);} // NOTE: Quantity class is not accessible from this project :( @NonNull public ImmutablePair<BigDecimal, Integer> getAsQuantity() { try { final List<String> parts = Splitter.on(QTY_SEPARATOR).splitToList(value); if (parts.size() != 2) { throw new AdempiereException("Cannot get Quantity from " + this); } return ImmutablePair.of(new BigDecimal(parts.get(0)), Integer.parseInt(parts.get(1))); } catch (AdempiereException ex) { throw ex;
} catch (final Exception ex) { throw new AdempiereException("Cannot get Quantity from " + this, ex); } } @NonNull public String getAsString() {return value;} @NonNull public <T> T deserializeTo(@NonNull final Class<T> targetClass) { return JSONObjectMapper.forClass(targetClass).readValue(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\rest_workflows\facets\WorkflowLaunchersFacetId.java
1
请完成以下Java代码
public Todo syncJackson() throws Exception { String response = sampleApiRequest(); Todo[] todo = objectMapper.readValue(response, Todo[].class); return todo[1]; } public Todo asyncJackson() throws Exception { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/todos")) .build(); TodoAppClient todoAppClient = new TodoAppClient(); List<Todo> todo = HttpClient.newHttpClient() .sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenApply(todoAppClient::readValueJackson) .get(); return todo.get(1); } public Todo asyncGson() throws Exception { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://jsonplaceholder.typicode.com/todos")) .build(); TodoAppClient todoAppClient = new TodoAppClient();
List<Todo> todo = HttpClient.newHttpClient() .sendAsync(request, BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenApply(todoAppClient::readValueGson) .get(); return todo.get(1); } List<Todo> readValueJackson(String content) { try { return objectMapper.readValue(content, new TypeReference<List<Todo>>() { }); } catch (IOException ioe) { throw new CompletionException(ioe); } } List<Todo> readValueGson(String content) { return gson.fromJson(content, new TypeToken<List<Todo>>() { }.getType()); } }
repos\tutorials-master\core-java-modules\core-java-11-3\src\main\java\com\baeldung\httppojo\TodoAppClient.java
1
请完成以下Java代码
class MoveTargetResolver { private final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class); public MoveTarget resolve(@NonNull final ScannedCode target) { final GlobalQRCode globalQRCode = target.toGlobalQRCodeIfMatching().orNullIfError(); if (globalQRCode != null) { if (LocatorQRCode.isTypeMatching(globalQRCode)) { final LocatorQRCode locatorQRCode = LocatorQRCode.ofGlobalQRCode(globalQRCode); return resolveLocatorQRCode(locatorQRCode); } else if (HUQRCode.isTypeMatching(globalQRCode)) { return resolveHUQRCode(globalQRCode); } else { throw new AdempiereException("Move target not handled: " + globalQRCode); } } // // Try searching by locator value { final LocatorQRCode locatorQRCode = warehouseBL.getLocatorQRCodeByValue(target.getAsString()).orElse(null); if (locatorQRCode != null) { return resolveLocatorQRCode(locatorQRCode); } } throw new AdempiereException("Move target not handled: " + target);
} private MoveTarget resolveLocatorQRCode(final LocatorQRCode locatorQRCode) { final I_M_Locator locator = warehouseBL.getLocatorById(locatorQRCode.getLocatorId(), I_M_Locator.class); return MoveTarget.builder() .locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID())) .isPlaceAggTUsOnNewLUAfterMove(locator.isPlaceAggHUOnNewLU()) .build(); } private static MoveTarget resolveHUQRCode(final GlobalQRCode globalQRCode) { return MoveTarget.builder() .huQRCode(HUQRCode.fromGlobalQRCode(globalQRCode)) .isPlaceAggTUsOnNewLUAfterMove(false) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\MoveTargetResolver.java
1
请完成以下Java代码
public boolean isPeanuts() { return peanuts; } public void setPeanuts(boolean peanuts) { this.peanuts = peanuts; } public boolean isCelery() { return celery; } public void setCelery(boolean celery) { this.celery = celery; } public boolean isSesameSeeds() { return sesameSeeds;
} public void setSesameSeeds(boolean sesameSeeds) { this.sesameSeeds = sesameSeeds; } public Long getId() { return id; } @Override public String toString() { return "MealAsSingleEntity [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]"; } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\multipletables\secondarytable\MealAsSingleEntity.java
1
请完成以下Java代码
public int getC_Customer_Retention_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Customer_Retention_ID); if (ii == null) return 0; return ii.intValue(); } /** * CustomerRetention AD_Reference_ID=540937 * Reference name: C_BPartner_TimeSpan_List */ public static final int CUSTOMERRETENTION_AD_Reference_ID=540937; /** Neukunde = N */ public static final String CUSTOMERRETENTION_Neukunde = "N"; /** Stammkunde = S */ public static final String CUSTOMERRETENTION_Stammkunde = "S"; /** Set Customer Retention. @param CustomerRetention Customer Retention */
@Override public void setCustomerRetention (java.lang.String CustomerRetention) { set_Value (COLUMNNAME_CustomerRetention, CustomerRetention); } /** Get Customer Retention. @return Customer Retention */ @Override public java.lang.String getCustomerRetention () { return (java.lang.String)get_Value(COLUMNNAME_CustomerRetention); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customer_Retention.java
1
请完成以下Java代码
public void propertyChange(final PropertyChangeEvent evt) { final boolean DEBUG = false; final PropertyChangeListener delegate = getDelegate(); if (delegate == null) { // delegate reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("delegate of {0} is expired", this)); } return; } final Object source = evt.getSource(); final PropertyChangeEvent evtNew; if (source instanceof Reference) { final Reference<?> sourceRef = (Reference<?>)source; final Object sourceObj = sourceRef.get(); if (sourceObj == null) { // reference expired if (DEBUG) { // TODO remove before integrating into base line!! System.out.println(StringUtils.formatMessage("sourceObj of {0} is expired", this)); } return; } evtNew = new PropertyChangeEvent(sourceObj, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
evtNew.setPropagationId(evt.getPropagationId()); } else { evtNew = evt; } delegate.propertyChange(evtNew); } @Override public String toString() { return "WeakPropertyChangeListener [delegate=" + delegate + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\WeakPropertyChangeListener.java
1
请完成以下Java代码
public Timestamp encrypt(Timestamp value) { return value; } // encrypt /** * Decryption. * The methods must recognize clear text values * * @param value encrypted value * @return decrypted String */ @Override public Timestamp decrypt(Timestamp value) { return value; } // decrypt /** * Convert String to Digest. * JavaScript version see - http://pajhome.org.uk/crypt/md5/index.html * * @param value message * @return HexString of message (length = 32 characters) */ @Override public String getDigest(String value) { if (m_md == null) { try { m_md = MessageDigest.getInstance("MD5"); // m_md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } // Reset MessageDigest object m_md.reset(); // Convert String to array of bytes byte[] input = value.getBytes(StandardCharsets.UTF_8); // feed this array of bytes to the MessageDigest object m_md.update(input); // Get the resulting bytes after the encryption process byte[] output = m_md.digest(); m_md.reset(); // return convertToHexString(output); } // getDigest /** * Checks, if value is a valid digest
* * @param value digest string * @return true if valid digest */ @Override public boolean isDigest(String value) { if (value == null || value.length() != 32) return false; // needs to be a hex string, so try to convert it return (convertHexString(value) != null); } // isDigest /** * String Representation * * @return info */ @Override public String toString() { return MoreObjects.toStringHelper(this) .add("cipher", m_cipher) .toString(); } } // Secure
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Secure.java
1
请完成以下Java代码
private static I_M_Forecast extractForecast(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_M_Forecast.class); } @Override public String getSummary(final DocumentTableFields docFields) { return extractForecast(docFields).getName(); } @Override public String getDocumentInfo(final DocumentTableFields docFields) { return getSummary(docFields); } @Override public int getDoc_User_ID(final DocumentTableFields docFields) { return extractForecast(docFields).getCreatedBy(); } @Override public int getC_Currency_ID(final DocumentTableFields docFields) { return -1; } @Override public BigDecimal getApprovalAmt(final DocumentTableFields docFields) { return BigDecimal.ZERO; } @Override public File createPDF(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public String completeIt(final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); forecast.setDocAction(IDocument.ACTION_None); return IDocument.STATUS_Completed; } @Override public void approveIt(final DocumentTableFields docFields) { } @Override public void rejectIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void voidIt(final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(forecast.getDocStatus()); if (docStatus.isClosedReversedOrVoided()) { throw new AdempiereException("Document Closed: " + docStatus); } getLines(forecast).forEach(this::voidLine); forecast.setProcessed(true); forecast.setDocAction(IDocument.ACTION_None); } @Override public void unCloseIt(final DocumentTableFields docFields) {
throw new UnsupportedOperationException(); } @Override public void reverseCorrectIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void reverseAccrualIt(final DocumentTableFields docFields) { throw new UnsupportedOperationException(); } @Override public void reactivateIt(final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); forecast.setProcessed(false); forecast.setDocAction(IDocument.ACTION_Complete); } @Override public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields) { final I_M_Forecast forecast = extractForecast(docFields); return TimeUtil.asLocalDate(forecast.getDatePromised()); } private void voidLine(@NonNull final I_M_ForecastLine line) { line.setQty(BigDecimal.ZERO); line.setQtyCalculated(BigDecimal.ZERO); InterfaceWrapperHelper.save(line); } private List<I_M_ForecastLine> getLines(@NonNull final I_M_Forecast forecast) { return forecastDAO.retrieveLinesByForecastId(ForecastId.ofRepoId(forecast.getM_Forecast_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\ForecastDocumentHandler.java
1
请完成以下Java代码
public Collection<String> getConsumes() { return Collections.unmodifiableCollection(this.consumes); } /** * Returns the media types that the operation produces. * @return the produced media types */ public Collection<String> getProduces() { return Collections.unmodifiableCollection(this.produces); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } WebOperationRequestPredicate other = (WebOperationRequestPredicate) obj; boolean result = true; result = result && this.consumes.equals(other.consumes); result = result && this.httpMethod == other.httpMethod; result = result && this.canonicalPath.equals(other.canonicalPath); result = result && this.produces.equals(other.produces); return result; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.consumes.hashCode();
result = prime * result + this.httpMethod.hashCode(); result = prime * result + this.canonicalPath.hashCode(); result = prime * result + this.produces.hashCode(); return result; } @Override public String toString() { StringBuilder result = new StringBuilder(this.httpMethod + " to path '" + this.path + "'"); if (!CollectionUtils.isEmpty(this.consumes)) { result.append(" consumes: ").append(StringUtils.collectionToCommaDelimitedString(this.consumes)); } if (!CollectionUtils.isEmpty(this.produces)) { result.append(" produces: ").append(StringUtils.collectionToCommaDelimitedString(this.produces)); } return result.toString(); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebOperationRequestPredicate.java
1
请完成以下Spring Boot application配置
spring: security: user: name: user1 password: password baeldung: security: server: registration: registrar-client-id: registrar-client registrar-client-secret: "{noop}secret" debug: true logging: level:
org.springframework.security: TRACE server: servlet: session: cookie: name: SASESSIONID
repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-authorization-server\src\main\resources\application.yaml
2
请完成以下Java代码
public String joinStreet1AndStreet2(@NonNull final Address deliveryAddress) { return Joiner .on(STREET_DELIMITER) .skipNulls() .join(deliveryAddress.getStreet1(), deliveryAddress.getStreet2()); } /** * @return a pair with street1 being left and street2 being right. Both might be {@code null}. */ public IPair<String, String> splitIntoStreet1AndStreet2(@NonNull final String streets1And2) { final List<String> list = Splitter.on(STREET_DELIMITER) .limit(2) .splitToList(streets1And2); return ImmutablePair.of( list.size() > 0 ? list.get(0) : null, list.size() > 1 ? list.get(1) : null); } private static String dateToCsvString(@Nullable final LocalDate date) { if (date == null) { return ""; } return date.format(DATE_FORMATTER); } private static String timeToString(@Nullable final LocalTime time) { if (time == null) { return ""; } return time.format(TIME_FORMATTER); } private static String intToString(@NonNull final Optional<Integer> integer)
{ if (integer.isPresent()) { return Integer.toString(integer.get()); } return ""; } private static String intToString(@Nullable final Integer integer) { if (integer == null) { return ""; } return Integer.toString(integer); } private static String bigDecimalToString(@Nullable final BigDecimal bigDecimal) { if (bigDecimal == null) { return ""; } return bigDecimal.toString(); } private static String stringToString(@NonNull final Optional<String> string) { if (string.isPresent()) { return string.get(); } return ""; } private String truncateCheckDigitFromParcelNo(@NonNull final String parcelNumber) { return StringUtils.trunc(parcelNumber, 11, TruncateAt.STRING_END); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\Converters.java
1
请完成以下Java代码
public C_Aggregation_Builder setContext(final IContextAware context) { this.context = context; return this; } public C_Aggregation_Builder setName(final String name) { this.name = name; return this; } public C_Aggregation_Builder setAD_Table_ID(final int adTableId) { this.adTableId = adTableId; return this; } public C_Aggregation_Builder setAD_Table_ID(final String tableName) { this.adTableId = Services.get(IADTableDAO.class).retrieveTableId(tableName); return this; } public C_Aggregation_Builder setIsDefault(final boolean isDefault) { this.isDefault = isDefault; return this; } public C_Aggregation_Builder setIsDefaultSO(final boolean isDefaultSO) { this.isDefaultSO = isDefaultSO; return this; } public C_Aggregation_Builder setIsDefaultPO(final boolean isDefaultPO) { this.isDefaultPO = isDefaultPO; return this;
} public C_Aggregation_Builder setAggregationUsageLevel(final String aggregationUsageLevel) { this.aggregationUsageLevel = aggregationUsageLevel; return this; } public C_AggregationItem_Builder newItem() { if (adTableId <= 0) { throw new AdempiereException("Before creating a new item, a adTableId needs to be set to the builder") .appendParametersToMessage() .setParameter("C_Aggregation_Builder", this); } final C_AggregationItem_Builder itemBuilder = new C_AggregationItem_Builder(this, AdTableId.ofRepoId(adTableId)); itemBuilders.add(itemBuilder); return itemBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_Aggregation_Builder.java
1
请在Spring Boot框架中完成以下Java代码
public void setUploadPath(String uploadPath) { PmsUtil.uploadPath = uploadPath; } public static String saveErrorTxtByList(List<String> msg, String name) { Date d = new Date(); String saveDir = "logs" + File.separator + DateUtils.yyyyMMdd.get().format(d) + File.separator; String saveFullDir = uploadPath + File.separator + saveDir; File saveFile = new File(saveFullDir); if (!saveFile.exists()) { saveFile.mkdirs(); } name += DateUtils.yyyymmddhhmmss.get().format(d) + Math.round(Math.random() * 10000); String saveFilePath = saveFullDir + name + ".txt"; try { //封装目的地 BufferedWriter bw = new BufferedWriter(new FileWriter(saveFilePath)); //遍历集合
for (String s : msg) { //写数据 if (s.indexOf("_") > 0) { String[] arr = s.split("_"); bw.write("第" + arr[0] + "行:" + arr[1]); } else { bw.write(s); } //bw.newLine(); bw.write("\r\n"); } //释放资源 bw.flush(); bw.close(); } catch (Exception e) { log.info("excel导入生成错误日志文件异常:" + e.getMessage()); } return saveDir + name + ".txt"; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\PmsUtil.java
2
请完成以下Java代码
public Optional<LocalDate> getBestBeforeDate() { return getAttribute(AttributeConstants.ATTR_BestBeforeDate).map(HUQRCodeAttribute::getValueAsLocalDate); } @Override public Optional<LocalDate> getProductionDate() { return getAttribute(AttributeConstants.ProductionDate).map(HUQRCodeAttribute::getValueAsLocalDate); } @Override public Optional<String> getLotNumber() { return getAttribute(AttributeConstants.ATTR_LotNumber).map(HUQRCodeAttribute::getValue); } private Optional<HUQRCodeAttribute> getAttribute(@NonNull final AttributeCode attributeCode) {
return attributes.stream().filter(attribute -> AttributeCode.equals(attribute.getCode(), attributeCode)).findFirst(); } private static String extractPrintableBottomText(final HUQRCode qrCode) { return qrCode.getPackingInfo().getHuUnitType().getShortDisplayName() + " ..." + qrCode.toDisplayableQRCode(); } public Optional<HUQRCodeProductInfo> getProduct() {return Optional.ofNullable(product);} @JsonIgnore public Optional<ProductId> getProductId() {return getProduct().map(HUQRCodeProductInfo::getId);} @JsonIgnore public ProductId getProductIdNotNull() {return getProductId().orElseThrow(() -> new AdempiereException("QR Code does not contain product information: " + this));} public HuPackingInstructionsId getPackingInstructionsId() {return getPackingInfo().getPackingInstructionsId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCode.java
1
请完成以下Java代码
public InvalidRequestException invalidRequestEngineNotFoundForName(String engineName) { return new InvalidRequestException(Status.BAD_REQUEST, "Process engine with name " + engineName + " does not exist"); } public InvalidRequestException setupActionNotAvailable() { return new InvalidRequestException(Status.FORBIDDEN, "Setup action not available"); } public RestException processEngineProviderNotFound() { return new RestException(Status.BAD_REQUEST, "Could not find an implementation of the " + ProcessEngineProvider.class + "- SPI"); } public void infoWebappSuccessfulLogin(String username) { logInfo("001", "Successful login for user {}.", username); } public void infoWebappFailedLogin(String username, String reason) { logInfo("002", "Failed login attempt for user {}. Reason: {}", username, reason); } public void infoWebappLogout(String username) { logInfo("003", "Successful logout for user {}.", username); } public void traceCacheValidationTime(Date cacheValidationTime) { logTrace("004", "Cache validation time: {}", cacheValidationTime); }
public void traceCacheValidationTimeUpdated(Date cacheValidationTime, Date newCacheValidationTime) { logTrace("005", "Cache validation time updated from: {} to: {}", cacheValidationTime, newCacheValidationTime); } public void traceAuthenticationUpdated(String engineName) { logTrace("006", "Authentication updated: {}", engineName); } public void traceAuthenticationRemoved(String engineName) { logTrace("007", "Authentication removed: {}", engineName); } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\WebappLogger.java
1
请完成以下Java代码
public void setIsSameTax (boolean IsSameTax) { set_Value (COLUMNNAME_IsSameTax, Boolean.valueOf(IsSameTax)); } /** Get Same Tax. @return Use the same tax as the main transaction */ public boolean isSameTax () { Object oo = get_Value(COLUMNNAME_IsSameTax); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Price includes Tax. @param IsTaxIncluded Tax is included in the price */ public void setIsTaxIncluded (boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, Boolean.valueOf(IsTaxIncluded)); } /** Get Price includes Tax. @return Tax is included in the price */ public boolean isTaxIncluded () { Object oo = get_Value(COLUMNNAME_IsTaxIncluded); 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Charge.java
1
请完成以下Java代码
public List<RelatedDocumentsCandidateGroup> retrieveRelatedDocumentsCandidates( @NonNull final IZoomSource fromDocument, @Nullable final AdWindowId targetWindowId) { // Return empty if not enabled if (!enabled.get()) { return ImmutableList.of(); } if (!fromDocument.isSingleKeyRecord()) { return ImmutableList.of(); } // // Get the Fact_Acct AD_Window_ID final AdWindowId factAcctWindowId = CoalesceUtil.coalesceSuppliers( () -> RecordWindowFinder.findAdWindowId(TABLENAME_Fact_Acct_Transactions_View).orElse(null), () -> RecordWindowFinder.findAdWindowId(I_Fact_Acct.Table_Name).orElse(null) ); if (factAcctWindowId == null) { return ImmutableList.of(); } // If not our target window ID, return nothing if (targetWindowId != null && !AdWindowId.equals(targetWindowId, factAcctWindowId)) { return ImmutableList.of(); } // Return nothing if source is not Posted if (fromDocument.hasField(COLUMNNAME_Posted)) {
final boolean posted = fromDocument.getFieldValueAsBoolean(COLUMNNAME_Posted); if (!posted) { return ImmutableList.of(); } } // // Build query and check count if needed final MQuery query = new MQuery(I_Fact_Acct.Table_Name); query.addRestriction(I_Fact_Acct.COLUMNNAME_AD_Table_ID, Operator.EQUAL, fromDocument.getAD_Table_ID()); query.addRestriction(I_Fact_Acct.COLUMNNAME_Record_ID, Operator.EQUAL, fromDocument.getRecord_ID()); final ITranslatableString windowCaption = adWindowDAO.retrieveWindowName(factAcctWindowId); final RelatedDocumentsCountSupplier recordsCountSupplier = new FactAcctRelatedDocumentsCountSupplier(fromDocument.getAD_Table_ID(), fromDocument.getRecord_ID()); return ImmutableList.of( RelatedDocumentsCandidateGroup.of( RelatedDocumentsCandidate.builder() .id(RelatedDocumentsId.ofString(I_Fact_Acct.Table_Name)) .internalName(I_Fact_Acct.Table_Name) .targetWindow(RelatedDocumentsTargetWindow.ofAdWindowId(factAcctWindowId)) .priority(relatedDocumentsPriority) .querySupplier(RelatedDocumentsQuerySuppliers.ofQuery(query)) .windowCaption(windowCaption) .documentsCountSupplier(recordsCountSupplier) .build())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\fact_acct\FactAcctRelatedDocumentsProvider.java
1
请完成以下Java代码
public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; }
public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleController { Map<Integer, Article> database = new HashMap<>(); @GetMapping public ResponseEntity<Collection<Article>> getArticles() { Collection<Article> values = database.values(); if (values.isEmpty()) { return ResponseEntity.noContent().build(); } return ResponseEntity.ok(values); } @GetMapping("/{id}") public ResponseEntity<Article> getArticle(@PathVariable("id") Integer id) { Article article = database.get(id); if (article == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(article); } @PostMapping
public void createArticle(@RequestBody Article article) { database.put(article.getId(), article); } @PutMapping("/{id}") public void updateArticle(@PathVariable("id") Integer id, @RequestBody Article article) { assert Objects.equals(id, article.getId()); database.remove(id); database.put(id, article); } @DeleteMapping("/{id}") public void deleteArticle(@PathVariable Integer id) { database.remove(id); } @DeleteMapping() public void deleteArticles() { database.clear(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\restclient\ArticleController.java
2
请在Spring Boot框架中完成以下Java代码
public class HelloWorldController { @RequestMapping("/hello") public Map<String, Object> showHelloWorld(){ Map<String, Object> map = new HashMap<>(); map.put("msg", "HelloWorld"); return map; } @RequestMapping("/exportExcel") public void export(HttpServletResponse response) throws Exception { //mock datas Goods goods1 = new Goods(); List<GoodType> goodTypeList1 = new ArrayList<>(); GoodType goodType1 = new GoodType(); goodType1.setTypeId("apple-1"); goodType1.setTypeName("apple-red"); goodTypeList1.add(goodType1); GoodType goodType2 = new GoodType(); goodType2.setTypeId("apple-2"); goodType2.setTypeName("apple-white"); goodTypeList1.add(goodType2); goods1.setNo(110); goods1.setName("apple"); goods1.setShelfLife(new Date()); goods1.setGoodTypes(goodTypeList1); Goods goods2 = new Goods(); List<GoodType> goodTypeList2 = new ArrayList<>(); GoodType goodType21 = new GoodType(); goodType21.setTypeId("wine-1"); goodType21.setTypeName("wine-red"); goodTypeList2.add(goodType21); GoodType goodType22 = new GoodType(); goodType22.setTypeId("wine-2"); goodType22.setTypeName("wine-white"); goodTypeList2.add(goodType22); goods2.setNo(111); goods2.setName("wine"); goods2.setShelfLife(new Date()); goods2.setGoodTypes(goodTypeList2);
List<Goods> goodsList = new ArrayList<Goods>(); goodsList.add(goods1); goodsList.add(goods2); for (Goods goods : goodsList) { System.out.println(goods); } //export FileUtil.exportExcel(goodsList, Goods.class,"product.xls",response); } @RequestMapping("/importExcel") public void importExcel() throws Exception { //loal file String filePath = "C:\\Users\\Dell\\Downloads\\product.xls"; //anaysis excel List<Goods> goodsList = FileUtil.importExcel(filePath,0,1,Goods.class); //also use MultipartFile,invoke FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) System.out.println("load data count【"+goodsList.size()+"】row"); //TODO save datas for (Goods goods:goodsList) { JSONObject.toJSONString(goods); } } }
repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\controller\HelloWorldController.java
2
请完成以下Java代码
public UomId getUomId() { return orderLineInfo.getUomId(); } public void setOrderLineInfo(@NonNull final OrderCostDetailOrderLinePart orderLineInfo) { this.costAmount.assertCurrencyId(orderLineInfo.getCurrencyId()); Quantity.assertSameUOM(this.inoutQty, orderLineInfo.getQtyOrdered()); this.orderLineInfo = orderLineInfo; } void setCostAmount(@NonNull final Money costAmountNew) { costAmountNew.assertCurrencyId(orderLineInfo.getCurrencyId()); this.costAmount = costAmountNew; }
void addInOutCost(@NonNull Money amt, @NonNull Quantity qty) { this.inoutCostAmount = this.inoutCostAmount.add(amt); this.inoutQty = this.inoutQty.add(qty); } public OrderCostDetail copy(@NonNull final OrderCostCloneMapper mapper) { return toBuilder() .id(null) .orderLineInfo(orderLineInfo.withOrderLineId(mapper.getTargetOrderLineId(orderLineInfo.getOrderLineId()))) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostDetail.java
1
请完成以下Java代码
public String toString() { return "TrxCallableWithTrxName-wrapper[" + callable + "]"; } @Override public T call(final String localTrxName) throws Exception { return callable.call(); } @Override public T call() throws Exception { throw new IllegalStateException("This method shall not be called");
} @Override public boolean doCatch(final Throwable e) throws Throwable { return callable.doCatch(e); } @Override public void doFinally() { callable.doFinally(); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxCallableWrappers.java
1
请完成以下Java代码
protected ArrayKey mkKey(final I_M_AttributeSetInstance model) { return Util.mkKey(model.getClass().getName(), model.getM_AttributeSetInstance_ID()); } @Override protected boolean isNullModel(final I_M_AttributeSetInstance model) { if (model == null) { return true; } // Case: null marker was returned. See "getModelFromObject" method. return model.getM_AttributeSetInstance_ID() <= 0; } @Override protected ASIWithPackingItemTemplateAttributeStorage createAttributeStorage(final I_M_AttributeSetInstance model) { return new ASIWithPackingItemTemplateAttributeStorage(this, model); } @Override public IAttributeStorage getAttributeStorageIfHandled(final Object modelObj) {
final I_M_AttributeSetInstance asi = getModelFromObject(modelObj); if (asi == null) { return null; } // Case: this modelObj is handled by this factory but there was no ASI value set // => don't go forward and ask other factories but instead return an NullAttributeStorage if (asi.getM_AttributeSetInstance_ID() <= 0) { return NullAttributeStorage.instance; } return getAttributeStorageForModel(asi); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ASIAwareAttributeStorageFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(columnDefinition = "BINARY(16)") private UUID id; private int age; private String name; private String genre; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) {
this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAssignedUUID\src\main\java\com\bookstore\entity\Author.java
2
请完成以下Java代码
public List<JSONMenuNode> getNodeBreadcrumbMenu(@PathVariable(PARAM_NodeId) final String nodeId) { userSession.assertLoggedIn(); final List<MenuNode> children = getMenuTree().getNodeById(nodeId) .getChildren() .stream() .filter(MenuNode::isEffectiveLeafNode) .collect(ImmutableList.toImmutableList()); return JSONMenuNode.ofList(children, menuTreeRepository); } @GetMapping("/elementPath") public JSONMenuNode getPath( @RequestParam(name = PARAM_Type) final JSONMenuNodeType jsonType, @RequestParam(name = PARAM_ElementId) final String elementIdStr, @RequestParam(name = PARAM_IncludeLastNode, required = false, defaultValue = "false") @Parameter(description = "Shall we include the last node") final boolean includeLastNode) { userSession.assertLoggedIn(); final MenuNodeType menuNodeType = jsonType.toMenuNodeType(); final DocumentId elementId = DocumentId.of(elementIdStr); final List<MenuNode> path = getMenuTree() .getPath(menuNodeType, elementId) .orElseGet(() -> getPathOfMissingElement(menuNodeType, elementId, userSession.getAD_Language())); return JSONMenuNode.ofPath(path, includeLastNode, menuTreeRepository); } private List<MenuNode> getPathOfMissingElement(final MenuNodeType type, final DocumentId elementId, final String adLanguage) { if (type == MenuNodeType.Window) { final String caption = documentDescriptorFactory.getDocumentDescriptor(WindowId.of(elementId)) .getLayout() .getCaption(adLanguage); return ImmutableList.of(MenuNode.builder() .setType(type, elementId) .setCaption(caption) .setAD_Menu_ID_None() .build()); } else {
throw new NoMenuNodesFoundException("No menu node found for type=" + type + " and elementId=" + elementId); } } @GetMapping("/queryPaths") public JSONMenuNode query( @RequestParam(name = PARAM_NameQuery) final String nameQuery, @RequestParam(name = PARAM_ChildrenLimit, required = false, defaultValue = "0") final int childrenLimit, @RequestParam(name = "childrenInclusive", required = false, defaultValue = "false") @Parameter(description = "true if groups that were matched shall be populated with it's leafs, even if those leafs are not matching") final boolean includeLeafsIfGroupAccepted) { userSession.assertLoggedIn(); final MenuNode rootFiltered = getMenuTree() .filter(nameQuery, includeLeafsIfGroupAccepted); if (rootFiltered == null) { throw new NoMenuNodesFoundException(); } if (rootFiltered.getChildren().isEmpty()) { throw new NoMenuNodesFoundException(); } return JSONMenuNode.builder(rootFiltered) .setMaxLeafNodes(childrenLimit) .setIsFavoriteProvider(menuTreeRepository) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuRestController.java
1
请完成以下Java代码
public java.lang.String getTenderType () { return (java.lang.String)get_Value(COLUMNNAME_TenderType); } /** * TrxType AD_Reference_ID=215 * Reference name: C_Payment Trx Type */ public static final int TRXTYPE_AD_Reference_ID=215; /** Verkauf = S */ public static final String TRXTYPE_Verkauf = "S"; /** Delayed Capture = D */ public static final String TRXTYPE_DelayedCapture = "D"; /** Kredit (Zahlung) = C */ public static final String TRXTYPE_KreditZahlung = "C"; /** Voice Authorization = F */ public static final String TRXTYPE_VoiceAuthorization = "F"; /** Autorisierung = A */ public static final String TRXTYPE_Autorisierung = "A"; /** Löschen = V */ public static final String TRXTYPE_Loeschen = "V"; /** Rückzahlung = R */ public static final String TRXTYPE_Rueckzahlung = "R"; /** Set Transaction Type. @param TrxType Type of credit card transaction */ @Override public void setTrxType (java.lang.String TrxType) { set_Value (COLUMNNAME_TrxType, TrxType); } /** Get Transaction Type. @return Type of credit card transaction */ @Override public java.lang.String getTrxType () { return (java.lang.String)get_Value(COLUMNNAME_TrxType); } /** Set Prüfziffer. @param VoiceAuthCode Voice Authorization Code from credit card company */ @Override public void setVoiceAuthCode (java.lang.String VoiceAuthCode) { set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode);
} /** Get Prüfziffer. @return Voice Authorization Code from credit card company */ @Override public java.lang.String getVoiceAuthCode () { return (java.lang.String)get_Value(COLUMNNAME_VoiceAuthCode); } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) { return Env.ZERO; } return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Payment.java
1
请在Spring Boot框架中完成以下Java代码
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServerFactoryBean) { CacheServerFactoryBean cacheServerFactoryBean = (CacheServerFactoryBean) bean; ServerLoadProbe serverLoadProbe = ObjectUtils.<ServerLoadProbe>get(bean, "serverLoadProbe"); if (serverLoadProbe != null) { cacheServerFactoryBean.setServerLoadProbe(wrap(serverLoadProbe)); } } return bean; } @Nullable @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServer) { CacheServer cacheServer = (CacheServer) bean; Optional.ofNullable(cacheServer.getLoadProbe()) .filter(it -> !(it instanceof ActuatorServerLoadProbeWrapper)) .filter(it -> cacheServer.getLoadPollInterval() > 0) .filter(it -> !cacheServer.isRunning()) .ifPresent(serverLoadProbe -> cacheServer.setLoadProbe(new ActuatorServerLoadProbeWrapper(serverLoadProbe))); } return bean; }
private ServerLoadProbe wrap(ServerLoadProbe serverLoadProbe) { return new ActuatorServerLoadProbeWrapper(serverLoadProbe); } }; } public static final class PeerCacheCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Cache peerCache = CacheUtils.getCache(); ClientCache clientCache = CacheUtils.getClientCache(); return peerCache != null || clientCache == null; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator-autoconfigure\src\main\java\org\springframework\geode\boot\actuate\autoconfigure\config\PeerCacheHealthIndicatorConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @ApiModelProperty(example = "oneTaskCase") public String getCaseDefinitionKey() { return caseDefinitionKey; } public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } @ApiModelProperty(example = "My case name") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "myBusinessKey") public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "tenant1") public String getTenantId() { return tenantId; } @ApiModelProperty(example = "overrideTenant1") public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; }
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getTransientVariables() { return transientVariables; } public void setTransientVariables(List<RestVariable> transientVariables) { this.transientVariables = transientVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getStartFormVariables() { return startFormVariables; } public void setStartFormVariables(List<RestVariable> startFormVariables) { this.startFormVariables = startFormVariables; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } @JsonIgnore public boolean isTenantSet() { return tenantId != null && !StringUtils.isEmpty(tenantId); } public boolean getReturnVariables() { return returnVariables; } public void setReturnVariables(boolean returnVariables) { this.returnVariables = returnVariables; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceCreateRequest.java
2
请完成以下Java代码
public void setDataType (final java.lang.String DataType) { set_Value (COLUMNNAME_DataType, DataType); } @Override public java.lang.String getDataType() { return get_ValueAsString(COLUMNNAME_DataType); } @Override public void setDecimalPointPosition (final int DecimalPointPosition) { set_Value (COLUMNNAME_DecimalPointPosition, DecimalPointPosition); } @Override public int getDecimalPointPosition() { return get_ValueAsInt(COLUMNNAME_DecimalPointPosition); } @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 setEndNo (final int EndNo) {
set_Value (COLUMNNAME_EndNo, EndNo); } @Override public int getEndNo() { return get_ValueAsInt(COLUMNNAME_EndNo); } @Override public void setStartNo (final int StartNo) { set_Value (COLUMNNAME_StartNo, StartNo); } @Override public int getStartNo() { return get_ValueAsInt(COLUMNNAME_StartNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ScannableCode_Format_Part.java
1
请完成以下Java代码
public int getOrder() { return RouteToRequestUrlFilter.ROUTE_TO_URL_FILTER_ORDER + 10; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR); String scheme = requestUrl.getScheme(); if (isAlreadyRouted(exchange) || !"stream".equals(scheme)) { return chain.filter(exchange); } setAlreadyRouted(exchange); ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders); return serverRequest.bodyToMono(byte[].class).flatMap(requestBody -> { ServerHttpRequest request = exchange.getRequest(); HttpHeaders headers = request.getHeaders(); Message<?> inputMessage = null; MessageBuilder<?> builder = MessageBuilder.withPayload(requestBody); if (!CollectionUtils.isEmpty(request.getQueryParams())) {
// TODO: move HeaderUtils builder = builder.setHeader(MessageHeaderUtils.HTTP_REQUEST_PARAM, request.getQueryParams().toSingleValueMap()); // TODO: sanitize? } inputMessage = builder.copyHeaders(headers.toSingleValueMap()).build(); // TODO: output content type boolean send = streamBridge.send(requestUrl.getHost(), inputMessage); HttpStatus responseStatus = (send) ? HttpStatus.OK : HttpStatus.BAD_REQUEST; SetStatusGatewayFilterFactory.Config config = new SetStatusGatewayFilterFactory.Config(); config.setStatus(responseStatus.name()); return setStatusFilter.apply(config).filter(exchange, chain); }); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\StreamRoutingFilter.java
1
请完成以下Java代码
public static ThingsBoardThreadFactory forName(String name) { return new ThingsBoardThreadFactory(name); } private ThingsBoardThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-"; } public static void updateCurrentThreadName(String threadSuffix) { String name = Thread.currentThread().getName(); int spliteratorIndex = name.indexOf(THREAD_TOPIC_SEPARATOR); if (spliteratorIndex > 0) { name = name.substring(0, spliteratorIndex); } name = name + THREAD_TOPIC_SEPARATOR + threadSuffix;
Thread.currentThread().setName(name); } public static void addThreadNamePrefix(String prefix) { String name = Thread.currentThread().getName(); name = prefix + "-" + name; Thread.currentThread().setName(name); } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(false); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\ThingsBoardThreadFactory.java
1
请完成以下Java代码
public void shutdownExecutor() { shutdownLock.lock(); try { shutdown0(); } finally { shutdownLock.unlock(); } } @Override protected void executeTask(@NonNull final WorkpackageProcessorTask task) { logger.debug("Going to submit task={} to executor={}", task, executor); executor.execute(task); logger.debug("Done submitting task"); } private void shutdown0() { logger.info("shutdown - Shutdown started for executor={}", executor); executor.shutdown(); int retryCount = 5;
boolean terminated = false; while (!terminated && retryCount > 0) { logger.info("shutdown - waiting for executor to be terminated; retries left={}; executor={}", retryCount, executor); try { terminated = executor.awaitTermination(5 * 1000, TimeUnit.MICROSECONDS); } catch (final InterruptedException e) { logger.warn("Failed shutting down executor for " + name + ". Retry " + retryCount + " more times."); terminated = false; } retryCount--; } executor.shutdownNow(); logger.info("Shutdown finished"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\ThreadPoolQueueProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class ZebraPrinterService { private static final String SSCC18_FILE_NAME_TEMPLATE = "sscc_lables_:timestamp.csv"; private static final String TIMESTAMP_PLACEHOLDER = ":timestamp"; private static final String CSV_FORMAT = "text/csv"; private final ZebraConfigRepository zebraConfigRepository = SpringContextHolder.instance.getBean(ZebraConfigRepository.class); /** * Creates a CSV file for SSCC18 labels based on given {@link de.metas.esb.edi.model.I_EDI_Desadv_Pack_Item} IDs. * * @return {@link ReportResultData} containing information required for SSCC18 labels in CSV format. */ public ReportResultData createCSV_FileForSSCC18_Labels( final Collection<EDIDesadvPackId> desadvPackIds, final ZebraConfigId zebraConfigId, final PInstanceId pInstanceId ) { final ZebraConfigId zebraConfigToUse = zebraConfigId != null ? zebraConfigId : zebraConfigRepository.getDefaultZebraConfigId(); final I_AD_Zebra_Config zebraConfig = zebraConfigRepository.getById(zebraConfigToUse); DB.createT_Selection(pInstanceId, desadvPackIds, ITrx.TRXNAME_ThreadInherited); final ImmutableList<List<String>> resultRows = DB.getSQL_ResultRowsAsListsOfStrings(zebraConfig.getSQL_Select(), Collections.singletonList(pInstanceId), ITrx.TRXNAME_ThreadInherited); Check.assumeNotEmpty(resultRows, "SSCC information records must be available!"); final StringBuilder ssccLabelsInformationAsCSV = new StringBuilder(zebraConfig.getHeader_Line1()); ssccLabelsInformationAsCSV.append("\n").append(zebraConfig.getHeader_Line2()); final Joiner joiner = Joiner.on(","); resultRows.stream() .map(row -> row.stream().map(this::escapeCSV).collect(Collectors.toList())) .map(joiner::join) .forEach(row -> ssccLabelsInformationAsCSV.append("\n").append(row)); return buildResult(ssccLabelsInformationAsCSV.toString(), zebraConfig.getEncoding()); } private String escapeCSV(final String valueToEscape)
{ final String escapedQuote = "\""; return escapedQuote + StringUtils.nullToEmpty(valueToEscape).replace(escapedQuote, escapedQuote + escapedQuote) + escapedQuote; } private ReportResultData buildResult(final String fileData, final String fileEncoding) { final byte[] fileDataBytes = fileData.getBytes(Charset.forName(fileEncoding)); return ReportResultData.builder() .reportData(new ByteArrayResource(fileDataBytes)) .reportFilename(SSCC18_FILE_NAME_TEMPLATE.replace(TIMESTAMP_PLACEHOLDER, String.valueOf(System.currentTimeMillis()))) .reportContentType(CSV_FORMAT) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\ZebraPrinterService.java
2
请完成以下Java代码
public class WebSocketServer { /** * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 */ private static final CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>(); /** * 与某个客户端的连接会话,需要通过它来给客户端发送数据 */ private Session session; /** * 接收sid */ private String sid=""; /** * 连接建立成功调用的方法 * */ @OnOpen public void onOpen(Session session,@PathParam("sid") String sid) { this.session = session; //如果存在就先删除一个,防止重复推送消息 webSocketSet.removeIf(webSocket -> webSocket.sid.equals(sid)); webSocketSet.add(this); this.sid=sid; } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { log.info("收到来"+sid+"的信息:"+message); //群发消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { log.error(e.getMessage(),e); } } } @OnError public void onError(Session session, Throwable error) { log.error("发生错误", error); } /** * 实现服务器主动推送 */ private void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 * */
public static void sendInfo(SocketMsg socketMsg,@PathParam("sid") String sid) throws IOException { String message = JSON.toJSONString(socketMsg); log.info("推送消息到"+sid+",推送内容:"+message); for (WebSocketServer item : webSocketSet) { try { //这里可以设定只推送给这个sid的,为null则全部推送 if(sid==null) { item.sendMessage(message); }else if(item.sid.equals(sid)){ item.sendMessage(message); } } catch (IOException ignored) { } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WebSocketServer that = (WebSocketServer) o; return Objects.equals(session, that.session) && Objects.equals(sid, that.sid); } @Override public int hashCode() { return Objects.hash(session, sid); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\websocket\WebSocketServer.java
1
请完成以下Java代码
public ELContext getElContext(VariableScope variableScope) { ELContext elContext = null; if (variableScope instanceof VariableScopeImpl) { VariableScopeImpl variableScopeImpl = (VariableScopeImpl) variableScope; elContext = variableScopeImpl.getCachedElContext(); } if (elContext == null) { elContext = createElContext(variableScope); if (variableScope instanceof VariableScopeImpl) { ((VariableScopeImpl) variableScope).setCachedElContext(elContext); } } return elContext; } protected ActivitiElContext createElContext(VariableScope variableScope) { return (ActivitiElContext) new ELContextBuilder() .withResolvers(createElResolver(variableScope)) .buildWithCustomFunctions(customFunctionProviders); } protected ELResolver createElResolver(VariableScope variableScope) { CompositeELResolver elResolver = new CompositeELResolver(); elResolver.add(new VariableScopeElResolver(variableScope)); if (customELResolvers != null) { customELResolvers.forEach(elResolver::add); } addBeansResolver(elResolver); addBaseResolvers(elResolver); return elResolver; } protected void addBeansResolver(CompositeELResolver elResolver) { if (beans != null) { // ACT-1102: Also expose all beans in configuration when using // standalone activiti, not // in spring-context elResolver.add(new ReadOnlyMapELResolver(beans)); } } private void addBaseResolvers(CompositeELResolver elResolver) {
elResolver.add(new ArrayELResolver()); elResolver.add(new ListELResolver()); elResolver.add(new MapELResolver()); elResolver.add(new CustomMapperJsonNodeELResolver()); elResolver.add(new DynamicBeanPropertyELResolver(ItemInstance.class, "getFieldValue", "setFieldValue")); // TODO: needs verification elResolver.add(new ELResolverReflectionBlockerDecorator(new BeanELResolver())); } public Map<Object, Object> getBeans() { return beans; } public void setBeans(Map<Object, Object> beans) { this.beans = beans; } public ELContext getElContext(Map<String, Object> availableVariables) { CompositeELResolver elResolver = new CompositeELResolver(); addBaseResolvers(elResolver); return new ELContextBuilder() .withResolvers(elResolver) .withVariables(availableVariables) .buildWithCustomFunctions(customFunctionProviders); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\ExpressionManager.java
1
请完成以下Java代码
public TbQueueConsumer<TbProtoQueueMsg<ToTransportMsg>> createTransportNotificationsConsumer() { TbKafkaConsumerTemplate.TbKafkaConsumerTemplateBuilder<TbProtoQueueMsg<ToTransportMsg>> responseBuilder = TbKafkaConsumerTemplate.builder(); responseBuilder.settings(kafkaSettings); responseBuilder.topic(topicService.buildTopicName(transportNotificationSettings.getNotificationsTopic() + "." + serviceInfoProvider.getServiceId())); responseBuilder.clientId("transport-api-notifications-" + serviceInfoProvider.getServiceId()); responseBuilder.groupId(topicService.buildTopicName("transport-node-" + serviceInfoProvider.getServiceId())); responseBuilder.decoder(msg -> new TbProtoQueueMsg<>(msg.getKey(), ToTransportMsg.parseFrom(msg.getData()), msg.getHeaders())); responseBuilder.admin(notificationAdmin); responseBuilder.statsService(consumerStatsService); return responseBuilder.build(); } @Override public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> createToUsageStatsServiceMsgProducer() { TbKafkaProducerTemplate.TbKafkaProducerTemplateBuilder<TbProtoQueueMsg<ToUsageStatsServiceMsg>> requestBuilder = TbKafkaProducerTemplate.builder(); requestBuilder.settings(kafkaSettings); requestBuilder.clientId("transport-node-us-producer-" + serviceInfoProvider.getServiceId()); requestBuilder.defaultTopic(topicService.buildTopicName(coreSettings.getUsageStatsTopic())); requestBuilder.admin(coreAdmin); return requestBuilder.build(); } @Override public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> createHousekeeperMsgProducer() { return TbKafkaProducerTemplate.<TbProtoQueueMsg<ToHousekeeperServiceMsg>>builder() .settings(kafkaSettings) .clientId("tb-transport-housekeeper-producer-" + serviceInfoProvider.getServiceId())
.defaultTopic(topicService.buildTopicName(coreSettings.getHousekeeperTopic())) .admin(housekeeperAdmin) .build(); } @PreDestroy private void destroy() { if (coreAdmin != null) { coreAdmin.destroy(); } if (ruleEngineAdmin != null) { ruleEngineAdmin.destroy(); } if (transportApiRequestAdmin != null) { transportApiRequestAdmin.destroy(); } if (transportApiResponseAdmin != null) { transportApiResponseAdmin.destroy(); } if (notificationAdmin != null) { notificationAdmin.destroy(); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\KafkaTbTransportQueueFactory.java
1
请完成以下Java代码
public String toString() { return getClass().getSimpleName() + "[" + "\nstorage=" + storage + "\nreferenceModel=" + referenceModel + "]"; } @Override public IAllocationResult load(final IAllocationRequest request) { if (request.getQty().signum() == 0) { return AllocationUtils.nullResult(); } final IAllocationRequest requestActual = storage.addQty(request); // // Create Allocation result final boolean outTrx = false; final IAllocationResult result = createAllocationResult(request, requestActual, outTrx); // // Return the result return result; } @Override public IAllocationResult unload(final IAllocationRequest request) { final IAllocationRequest requestActual = storage.removeQty(request); final boolean outTrx = true; return createAllocationResult(request, requestActual, outTrx); } private IAllocationResult createAllocationResult( final IAllocationRequest request, final IAllocationRequest requestActual, final boolean outTrx) { final IHUTransactionCandidate trx = createHUTransaction(requestActual, outTrx); return AllocationUtils.createQtyAllocationResult( request.getQty(), // qtyToAllocate requestActual.getQty(), // qtyAllocated Arrays.asList(trx), // trxs Collections.<IHUTransactionAttribute> emptyList() // attributeTrxs ); } private IHUTransactionCandidate createHUTransaction(final IAllocationRequest request, final boolean outTrx) { final HUTransactionCandidate trx = new HUTransactionCandidate(getReferenceModel(), getM_HU_Item(), getVHU_Item(), request, outTrx); return trx; }
public IProductStorage getStorage() { return storage; } private I_M_HU_Item getM_HU_Item() { return huItem; } private I_M_HU_Item getVHU_Item() { // TODO: implement: get VHU Item or create it return huItem; } public Object getReferenceModel() { return referenceModel; } @Override public List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext) { final IAllocationRequest request = AllocationUtils.createQtyRequest(huContext, storage.getProductId(), // product storage.getQty(), // qty huContext.getDate() // date ); final IAllocationResult result = unload(request); return Collections.singletonList(ImmutablePair.of(request, result)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractAllocationSourceDestination.java
1
请完成以下Java代码
public String getSummary() { final IMsgBL msgBL = Services.get(IMsgBL.class); StringBuilder sb = new StringBuilder(); sb.append(getDocumentNo()); // : Total Lines = 123.00 (#1) sb.append(": ") .append(msgBL.translate(getCtx(),"TotalDr")).append("=").append(getTotalDr()) .append(" ") .append(msgBL.translate(getCtx(),"TotalCR")).append("=").append(getTotalCr()) .append(" (#").append(getJournals().length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) sb.append(" - ").append(getDescription()); return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getDateDoc()); } /** * String Representation * @return info */ @Override public String toString () { StringBuffer sb = new StringBuffer ("MJournalBatch["); sb.append(get_ID()).append(",").append(getDescription()) .append(",DR=").append(getTotalDr()) .append(",CR=").append(getTotalCr()) .append ("]"); return sb.toString (); } // toString /** * Get Document Info * @return document info (untranslated) */ @Override public String getDocumentInfo() { MDocType dt = MDocType.get(getCtx(), getC_DocType_ID()); return dt.getName() + " " + getDocumentNo(); } // getDocumentInfo /** * Create PDF * @return File or null */ @Override public File createPDF () {
try { File temp = File.createTempFile(get_TableName()+get_ID()+"_", ".pdf"); return createPDF (temp); } catch (Exception e) { log.error("Could not create PDF - " + e.getMessage()); } return null; } // getPDF /** * Create PDF file * @param file output file * @return file if success */ public File createPDF (File file) { // ReportEngine re = ReportEngine.get (getCtx(), ReportEngine.INVOICE, getC_Invoice_ID()); // if (re == null) return null; // return re.getPDF(file); } // createPDF /** * Get Process Message * @return clear text error message */ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * @return AD_User_ID (Created By) */ @Override public int getDoc_User_ID() { return getCreatedBy(); } // getDoc_User_ID /** * Get Document Approval Amount * @return DR amount */ @Override public BigDecimal getApprovalAmt() { return getTotalDr(); } // getApprovalAmt } // MJournalBatch
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournalBatch.java
1
请完成以下Java代码
public static MHRPayroll forValue(Properties ctx, String value) { if (Check.isEmpty(value, true)) { return null; } int AD_Client_ID = Env.getAD_Client_ID(ctx); final String key = AD_Client_ID+"#"+value; MHRPayroll payroll = s_cacheValue.get(key); if (payroll != null) { return payroll; } final String whereClause = COLUMNNAME_Value+"=? AND AD_Client_ID IN (?,?)"; payroll = new Query(ctx, Table_Name, whereClause, null) .setParameters(new Object[]{value, 0, AD_Client_ID}) .setOnlyActiveRecords(true) .setOrderBy("AD_Client_ID DESC") .first(); if (payroll != null) { s_cacheValue.put(key, payroll); s_cache.put(payroll.get_ID(), payroll); } return payroll; } /** * Get Payroll by ID * @param ctx * @param HR_Payroll_ID * @return payroll */ public static MHRPayroll get(Properties ctx, int HR_Payroll_ID) { if (HR_Payroll_ID <= 0) return null; // MHRPayroll payroll = s_cache.get(HR_Payroll_ID); if (payroll != null) return payroll; // payroll = new MHRPayroll(ctx, HR_Payroll_ID, null); if (payroll.get_ID() == HR_Payroll_ID) { s_cache.put(HR_Payroll_ID, payroll); } else { payroll = null; } return payroll; } /** * Standard Constructor * @param ctx context * @param HR_Payroll_ID id
*/ public MHRPayroll (Properties ctx, int HR_Payroll_ID, String trxName) { super (ctx, HR_Payroll_ID, trxName); if (HR_Payroll_ID == 0) { setProcessing (false); // N } } // HRPayroll /** * Load Constructor * @param ctx context * @param rs result set */ public MHRPayroll (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } /** * Parent Constructor * @param parent parent */ public MHRPayroll (MCalendar calendar) { this (calendar.getCtx(), 0, calendar.get_TrxName()); setClientOrg(calendar); //setC_Calendar_ID(calendar.getC_Calendar_ID()); } // HRPayroll } // MPayroll
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRPayroll.java
1
请在Spring Boot框架中完成以下Java代码
public String getUnit() { return unit; } /** * Sets the value of the unit property. * * @param value * allowed object is * {@link String } * */ public void setUnit(String value) { this.unit = value; } /** * Packaging unit type used by the supplier. If customer's and supplier's packaging unit type is different this should be used for suppliers's packaging unit type. * * @return * possible object is * {@link String } * */ public String getSupplierUnit() {
return supplierUnit; } /** * Sets the value of the supplierUnit property. * * @param value * allowed object is * {@link String } * */ public void setSupplierUnit(String value) { this.supplierUnit = value; } } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ConsignmentPackagingSequenceType.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected void prepare() { final IQueryFilter<I_M_ReceiptSchedule> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBuilder<de.metas.inoutcandidate.model.I_M_ReceiptSchedule> queryBuilderForShipmentSchedulesSelection = receiptScheduleDAO.createQueryForReceiptScheduleSelection(getCtx(), userSelectionFilter); // Create selection and return how many items were added final int selectionCount = queryBuilderForShipmentSchedulesSelection .create() .createSelection(getPinstanceId());
if (selectionCount <= 0) { throw new AdempiereException(MSG_NO_UNPROCESSED_LINES) .markAsUserValidationError(); } } @Override protected String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); receiptScheduleBL.updateExportStatus(APIExportStatus.ofCode(exportStatus), pinstanceId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_ChangeExportStatus.java
1
请完成以下Java代码
K id() { return id_; } /** * Get the pointer of a feature vector * * @return the pointer of a feature vector */ SparseVector feature() { return feature_; } /** * Add a feature. * * @param key the key of a feature * @param value the value of a feature */ void add_feature(int key, double value) { feature_.put(key, value); } /** * Set features. * * @param feature a feature vector */ void set_features(SparseVector feature) { feature_ = feature; } /** * Clear features.
*/ void clear() { feature_.clear(); } /** * Apply IDF(inverse document frequency) weighting. * * @param df document frequencies * @param ndocs the number of documents */ void idf(HashMap<Integer, Integer> df, int ndocs) { for (Map.Entry<Integer, Double> entry : feature_.entrySet()) { Integer denom = df.get(entry.getKey()); if (denom == null) denom = 1; entry.setValue((double) (entry.getValue() * Math.log(ndocs / denom))); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Document<?> document = (Document<?>) o; return id_ != null ? id_.equals(document.id_) : document.id_ == null; } @Override public int hashCode() { return id_ != null ? id_.hashCode() : 0; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\cluster\Document.java
1
请完成以下Java代码
protected boolean isReachable(PvmActivity srcActivity, PvmActivity targetActivity, Set<PvmActivity> visitedActivities) { // if source has no outputs, it is the end of the process, and its parent process should be checked. if (srcActivity.getOutgoingTransitions().isEmpty()) { visitedActivities.add(srcActivity); if (!(srcActivity.getParent() instanceof PvmActivity)) { return false; } srcActivity = (PvmActivity) srcActivity.getParent(); } if (srcActivity.equals(targetActivity)) { return true; } // To avoid infinite looping, we must capture every node we visit // and check before going further in the graph if we have already visited // the node. visitedActivities.add(srcActivity); List<PvmTransition> transitionList = srcActivity.getOutgoingTransitions(); if (transitionList != null && !transitionList.isEmpty()) { for (PvmTransition pvmTransition : transitionList) { PvmActivity destinationActivity = pvmTransition.getDestination(); if (destinationActivity != null && !visitedActivities.contains(destinationActivity)) {
boolean reachable = isReachable(destinationActivity, targetActivity, visitedActivities); // If false, we should investigate other paths, and not yet return the // result if (reachable) { return true; } } } } return false; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\InclusiveGatewayActivityBehavior.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Externe Datensatz-ID. @param RemoteRecordId Externe Datensatz-ID */ @Override public void setRemoteRecordId (java.lang.String RemoteRecordId) { set_Value (COLUMNNAME_RemoteRecordId, RemoteRecordId); } /** Get Externe Datensatz-ID. @return Externe Datensatz-ID */
@Override public java.lang.String getRemoteRecordId () { return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId); } /** Set Anfangsdatum. @param StartDate First effective day (inclusive) */ @Override public void setStartDate (java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Anfangsdatum. @return First effective day (inclusive) */ @Override public java.sql.Timestamp getStartDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Campaign.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { if (jobId == null) { throw new ActivitiIllegalArgumentException("jobId is null"); } // We need to refetch the job, as it could have been deleted by another concurrent job // For exampel: an embedded subprocess with a couple of async tasks and a timer on the boundary of the subprocess // when the timer fires, all executions and thus also the jobs inside of the embedded subprocess are destroyed. // However, the async task jobs could already have been fetched and put in the queue.... while in reality they have been deleted. // A refetch is thus needed here to be sure that it exists for this transaction. Job job = commandContext.getJobEntityManager().findById(jobId); if (job == null) { log.debug( "Job does not exist anymore and will not be executed. It has most likely been deleted " + "as part of another concurrent part of the process instance." ); return null; }
if (log.isDebugEnabled()) { log.debug("Executing async job {}", job.getId()); } executeInternal(commandContext, job); return null; } protected void executeInternal(CommandContext commandContext, Job job) { commandContext.getJobManager().execute(job); if (commandContext.getEventDispatcher().isEnabled()) { commandContext .getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_EXECUTION_SUCCESS, job)); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ExecuteAsyncJobCmd.java
1
请在Spring Boot框架中完成以下Java代码
public void removeVariables(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } @Override public void removeVariablesLocal(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } @Override public void setTransientVariablesLocal(Map<String, Object> transientVariables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } @Override public void setTransientVariableLocal(String variableName, Object variableValue) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } @Override public void setTransientVariables(Map<String, Object> transientVariables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } @Override public void setTransientVariable(String variableName, Object variableValue) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } @Override public Object getTransientVariableLocal(String variableName) { return null; } @Override public Map<String, Object> getTransientVariablesLocal() { return null; } @Override public Object getTransientVariable(String variableName) { return null; } @Override public Map<String, Object> getTransientVariables() {
return null; } @Override public void removeTransientVariableLocal(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } @Override public void removeTransientVariablesLocal() { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } @Override public void removeTransientVariable(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } @Override public void removeTransientVariables() { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } @Override public String getTenantId() { return null; } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\el\NoExecutionVariableScope.java
2
请完成以下Java代码
public Instant toInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atStartOfDay().atZone(orgMapper.apply(orgId)).toInstant(); } public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant(); } public LocalDate toLocalDate() { return localDate; } public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) { return Timestamp.from(toInstant(orgMapper)); } @Override public int compareTo(final @Nullable LocalDateAndOrgId o) { return compareToByLocalDate(o); } /**
* In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes. * A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?" * That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s. * * @see #compareTo(LocalDateAndOrgId) */ private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o) { if (o == null) { return 1; } return this.localDate.compareTo(o.localDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
1
请完成以下Java代码
private static void varargMethod(String... varargs) { for (String element : varargs) { System.out.println(element); } } private static void transformIntoList() { Integer[] anArray = new Integer[] {1, 2, 3, 4, 5}; // Naïve implementation List<Integer> aList = new ArrayList<>(); // We create an empty list for (int element : anArray) { // We iterate over array's elements and add them to the list aList.add(element); } // Pretty implementation aList = Arrays.asList(anArray); // Drawbacks try { aList.remove(0); } catch (UnsupportedOperationException e) { System.out.println(e.getMessage()); } try { aList.add(6); } catch (UnsupportedOperationException e) { System.out.println(e.getMessage()); } int[] anotherArray = new int[] {1, 2, 3, 4, 5}; // List<Integer> anotherList = Arrays.asList(anotherArray); } private static void transformIntoStream() { int[] anArray = new int[] {1, 2, 3, 4, 5}; IntStream aStream = Arrays.stream(anArray); Integer[] anotherArray = new Integer[] {1, 2, 3, 4, 5}; Stream<Integer> anotherStream = Arrays.stream(anotherArray, 2, 4); } private static void sort() { int[] anArray = new int[] {5, 2, 1, 4, 8}; Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8} Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8}; Arrays.sort(anotherArray); // anArray is now {1, 2, 4, 5, 8}
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"}; Arrays.sort(yetAnotherArray, 1, 3, Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"} } private static void search() { int[] anArray = new int[] {5, 2, 1, 4, 8}; for (int i = 0; i < anArray.length; i++) { if (anArray[i] == 4) { System.out.println("Found at index " + i); break; } } Arrays.sort(anArray); int index = Arrays.binarySearch(anArray, 4); System.out.println("Found at index " + index); } private static void merge() { int[] anArray = new int[] {5, 2, 1, 4, 8}; int[] anotherArray = new int[] {10, 4, 9, 11, 2}; int[] resultArray = new int[anArray.length + anotherArray.length]; for (int i = 0; i < resultArray.length; i++) { resultArray[i] = (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length]); } for (int element : resultArray) { System.out.println(element); } Arrays.setAll(resultArray, i -> (i < anArray.length ? anArray[i] : anotherArray[i - anArray.length])); for (int element : resultArray) { System.out.println(element); } } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\array\ArrayReferenceGuide.java
1
请完成以下Java代码
protected void executeInternal(CommandContext commandContext, ProcessDefinitionEntity processDefinition) { // Update category processDefinition.setCategory(category); // Remove process definition from cache, it will be refetched later DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = commandContext .getProcessEngineConfiguration() .getProcessDefinitionCache(); if (processDefinitionCache != null) { processDefinitionCache.remove(processDefinitionId); } if (commandContext.getEventDispatcher().isEnabled()) { commandContext .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, processDefinition) ); } }
public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetProcessDefinitionCategoryCmd.java
1
请在Spring Boot框架中完成以下Java代码
private Object getFactoryValue(ExpressionTree expression, Object factoryValue) { Object durationValue = getFactoryValue(expression, factoryValue, DURATION_OF, DURATION_SUFFIX); if (durationValue != null) { return durationValue; } Object dataSizeValue = getFactoryValue(expression, factoryValue, DATA_SIZE_OF, DATA_SIZE_SUFFIX); if (dataSizeValue != null) { return dataSizeValue; } Object periodValue = getFactoryValue(expression, factoryValue, PERIOD_OF, PERIOD_SUFFIX); if (periodValue != null) { return periodValue; } return factoryValue; } private Object getFactoryValue(ExpressionTree expression, Object factoryValue, String prefix,
Map<String, String> suffixMapping) { Object instance = expression.getInstance(); if (instance != null && instance.toString().startsWith(prefix)) { String type = instance.toString(); type = type.substring(prefix.length(), type.indexOf('(')); String suffix = suffixMapping.get(type); return (suffix != null) ? factoryValue + suffix : null; } return null; } Map<String, Object> getFieldValues() { return this.fieldValues; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\JavaCompilerFieldValuesParser.java
2
请完成以下Java代码
public class ShipmentDeclarationDocumentHandler implements DocumentHandler { @Override public String getSummary(DocumentTableFields docFields) { return extractShipmentDeclaration(docFields).getDocumentNo(); } @Override public String getDocumentInfo(DocumentTableFields docFields) { return getSummary(docFields); } @Override public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); return TimeUtil.asLocalDate(shipmentDeclaration.getDeliveryDate()); } @Override public int getDoc_User_ID(DocumentTableFields docFields) { return extractShipmentDeclaration(docFields).getCreatedBy(); } @Override public String completeIt(DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); shipmentDeclaration.setProcessed(true);
shipmentDeclaration.setDocAction(IDocument.ACTION_ReActivate); return IDocument.STATUS_Completed; } @Override public void reactivateIt(DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); shipmentDeclaration.setProcessed(false); shipmentDeclaration.setDocAction(IDocument.ACTION_Complete); } private static I_M_Shipment_Declaration extractShipmentDeclaration(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_M_Shipment_Declaration.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\document\ShipmentDeclarationDocumentHandler.java
1
请完成以下Spring Boot application配置
info.app.name=spring-boot-actuator info.app.version= 1.0.0 info.app.test=test management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always #manageme
nt.endpoints.web.base-path=/manage management.endpoint.shutdown.enabled=true
repos\spring-boot-leaning-master\2.x_42_courses\第 5-2 课:使用 Spring Boot Actuator 监控应用\spring-boot-actuator\src\main\resources\application.properties
2
请完成以下Java代码
public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) {
this.email = email; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getRole() { return role; } public void setRole(Integer role) { this.role = role; } }
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\bean\User.java
1
请在Spring Boot框架中完成以下Java代码
public int getM_Product_ID() { return M_Product_ID; } public String getProductDescription() { return productDescription; } public String getProductAttributes() { return productAttributes; } public int getM_ProductPrice_ID() { return M_ProductPrice_ID; } public int getM_ProductPrice_Attribute_ID() { return M_ProductPrice_Attribute_ID; }
public int getM_HU_PI_Item_Product_ID() { return M_HU_PI_Item_Product_ID; } public int getC_BPartner_ID() { return C_BPartner_ID; } public int getC_BPartner_Location_ID() { return C_BPartner_Location_ID; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\Excel_OLCand_Row.java
2
请完成以下Java代码
public final class OAuth2WebClientHttpServiceGroupConfigurer implements WebClientHttpServiceGroupConfigurer { private final HttpRequestValues.Processor processor = ClientRegistrationIdProcessor.DEFAULT_INSTANCE; private final ExchangeFilterFunction filter; private OAuth2WebClientHttpServiceGroupConfigurer(ExchangeFilterFunction filter) { this.filter = filter; } @Override public void configureGroups(Groups<WebClient.Builder> groups) { // @formatter:off groups.forEachClient((group, client) -> client.filter(this.filter) ); groups.forEachProxyFactory((group, factory) -> factory.httpRequestValuesProcessor(this.processor) ); // @formatter:on } /** * Create an instance for Reactive web applications from the provided * {@link ReactiveOAuth2AuthorizedClientManager}. * * It will add {@link ServerOAuth2AuthorizedClientExchangeFilterFunction} to the * {@link WebClient} and {@link ClientRegistrationIdProcessor} to the * {@link org.springframework.web.service.invoker.HttpServiceProxyFactory}.
* @param authorizedClientManager the manager to use. * @return the {@link OAuth2WebClientHttpServiceGroupConfigurer}. */ public static OAuth2WebClientHttpServiceGroupConfigurer from( ReactiveOAuth2AuthorizedClientManager authorizedClientManager) { ServerOAuth2AuthorizedClientExchangeFilterFunction filter = new ServerOAuth2AuthorizedClientExchangeFilterFunction( authorizedClientManager); return new OAuth2WebClientHttpServiceGroupConfigurer(filter); } /** * Create an instance for Servlet based environments from the provided * {@link OAuth2AuthorizedClientManager}. * * It will add {@link ServletOAuth2AuthorizedClientExchangeFilterFunction} to the * {@link WebClient} and {@link ClientRegistrationIdProcessor} to the * {@link org.springframework.web.service.invoker.HttpServiceProxyFactory}. * @param authorizedClientManager the manager to use. * @return the {@link OAuth2WebClientHttpServiceGroupConfigurer}. */ public static OAuth2WebClientHttpServiceGroupConfigurer from( OAuth2AuthorizedClientManager authorizedClientManager) { ServletOAuth2AuthorizedClientExchangeFilterFunction filter = new ServletOAuth2AuthorizedClientExchangeFilterFunction( authorizedClientManager); return new OAuth2WebClientHttpServiceGroupConfigurer(filter); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\reactive\function\client\support\OAuth2WebClientHttpServiceGroupConfigurer.java
1
请完成以下Java代码
public boolean deleteEntries(boolean force) { getEntries(true); for (MDunningRunEntry entry : m_entries) { entry.delete(force); } boolean ok = getEntries(true).length == 0; if (ok) m_entries = null; return ok; } // deleteEntries /** * Get/Create Entry for BPartner * @param C_BPartner_ID business partner * @param C_Currency_ID currency * @param SalesRep_ID sales rep * @param C_DunningLevel_ID dunning level * @return entry */ public MDunningRunEntry getEntry (int C_BPartner_ID, int C_Currency_ID, int SalesRep_ID, int C_DunningLevel_ID) { // TODO: Related BP int C_BPartnerRelated_ID = C_BPartner_ID; // getEntries(false);
for (int i = 0; i < m_entries.length; i++) { MDunningRunEntry entry = m_entries[i]; if (entry.getC_BPartner_ID() == C_BPartnerRelated_ID && entry.getC_DunningLevel_ID() == C_DunningLevel_ID) return entry; } // New Entry MDunningRunEntry entry = new MDunningRunEntry (this); I_C_BPartner bp = Services.get(IBPartnerDAO.class).getById(C_BPartnerRelated_ID); entry.setBPartner(bp, true); // AR hardcoded // if (entry.getSalesRep_ID() == 0) entry.setSalesRep_ID (SalesRep_ID); entry.setC_Currency_ID (C_Currency_ID); entry.setC_DunningLevel_ID(C_DunningLevel_ID); // m_entries = null; return entry; } // getEntry } // MDunningRun
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRun.java
1
请完成以下Java代码
private static PriceSpecification applyPartialPriceChangeTo( @NonNull final PartialPriceChange changes, @NonNull final PriceSpecification price) { final PriceSpecificationType priceType = coalesce(changes.getPriceType(), price.getType()); if (priceType == PriceSpecificationType.NONE) { return PriceSpecification.none(); } else if (priceType == PriceSpecificationType.BASE_PRICING_SYSTEM) { final PricingSystemId requestBasePricingSystemId = changes.getBasePricingSystemId() != null ? changes.getBasePricingSystemId().orElse(null) : null; final PricingSystemId basePricingSystemId = coalesce(requestBasePricingSystemId, price.getBasePricingSystemId(), PricingSystemId.NONE); final Money surcharge = extractMoney( changes.getPricingSystemSurchargeAmt(), changes.getCurrencyId(), price.getPricingSystemSurcharge(), extractDefaultCurrencyIdSupplier(changes)); return PriceSpecification.basePricingSystem(basePricingSystemId, surcharge); } else if (priceType == PriceSpecificationType.FIXED_PRICE) { final Money fixedPrice = extractMoney( changes.getFixedPriceAmt(), changes.getCurrencyId(), price.getFixedPrice(), extractDefaultCurrencyIdSupplier(changes)); return PriceSpecification.fixedPrice(fixedPrice); } else { throw new AdempiereException("Unknow price type: " + priceType); } } private static Supplier<CurrencyId> extractDefaultCurrencyIdSupplier(final PartialPriceChange changes) { if (changes.getDefaultCurrencyId() != null) { return changes::getDefaultCurrencyId; } else { final ICurrencyBL currenciesService = Services.get(ICurrencyBL.class); return () -> currenciesService.getBaseCurrencyId(Env.getClientId(), Env.getOrgId()); } } @NonNull private static Money extractMoney( @Nullable final BigDecimal amount,
@Nullable final CurrencyId currencyId, @Nullable final Money fallback, @NonNull final Supplier<CurrencyId> defaultCurrencyIdSupplier) { if (amount == null && currencyId == null && fallback != null) { return fallback; } final BigDecimal amountEffective = coalesce( amount, fallback != null ? fallback.toBigDecimal() : BigDecimal.ZERO); final CurrencyId currencyIdEffective = coalesceSuppliers( () -> currencyId, () -> fallback != null ? fallback.getCurrencyId() : null, defaultCurrencyIdSupplier); if (currencyIdEffective == null) { // shall not happen throw new AdempiereException("No currency set"); } return Money.of(amountEffective, currencyIdEffective); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowReducers.java
1
请完成以下Java代码
public static class ColumnSource { final private int length; final private String name; final private int type; } private List<ColumnSource> createSourceColumns() { final ByteArrayInputStream input = new ByteArrayInputStream(getFileContent()); final InputStreamReader inputStreamReader = new InputStreamReader(input); final List<ColumnSource> columns = new ArrayList<>(); try (final BufferedReader reader = new BufferedReader(inputStreamReader)) { String currentTextLine; while ((currentTextLine = reader.readLine()) != null) { if (Check.isEmpty(currentTextLine, true)) { continue; } final String trimmedtextLine = currentTextLine.trim(); final ColumnSource column = builColumnSource(trimmedtextLine); columns.add(column); } } catch (final IOException e) { throw new AdempiereException(e.getLocalizedMessage(), e); } return ImmutableList.copyOf(columns); } private ColumnSource builColumnSource(@NonNull final String esrImportLineText) { final String[] fields = esrImportLineText.split(","); return ColumnSource.builder() .name(fields[0]) .type(Integer.valueOf(fields[1])) .length(Integer.valueOf(fields[2])) .build(); } private I_AD_Table createTargetTable() { final I_AD_Table targetTable = InterfaceWrapperHelper.newInstance(I_AD_Table.class); targetTable.setName(getTargetTableName());
targetTable.setTableName(getTargetTableName()); targetTable.setEntityType(getEntityType()); save(targetTable); return targetTable; } private I_AD_Column createColumn(final ColumnSource sourceColumn, final I_AD_Table targetTable) { final I_AD_Column colTarget = InterfaceWrapperHelper.newInstance(I_AD_Column.class); colTarget.setAD_Org_ID(0); colTarget.setAD_Table_ID(targetTable.getAD_Table_ID()); colTarget.setEntityType(getEntityType()); final Properties ctx = Env.getCtx(); M_Element element = M_Element.get(ctx, sourceColumn.getName()); if (element == null) { element = new M_Element(ctx, sourceColumn.getName(), targetTable.getEntityType(), ITrx.TRXNAME_ThreadInherited); element.setColumnName(sourceColumn.getName()); element.setName(sourceColumn.getName()); element.setPrintName(sourceColumn.getName()); element.saveEx(ITrx.TRXNAME_ThreadInherited); addLog("@AD_Element_ID@ " + element.getColumnName() + ": @Created@"); // metas } colTarget.setAD_Element_ID(element.getAD_Element_ID()); colTarget.setName(targetTable.getName()); colTarget.setIsAllowLogging(false); colTarget.setFieldLength(sourceColumn.getLength()); colTarget.setAD_Reference_ID(sourceColumn.getType()); colTarget.setIsActive(true); colTarget.setIsUpdateable(true); save(colTarget); addLog("@AD_Column_ID@ " + targetTable.getTableName() + "." + colTarget.getColumnName() + ": @Created@"); return colTarget; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\CreateColumnsProducer.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultTbEntityRelationService extends AbstractTbEntityService implements TbEntityRelationService { private final RelationService relationService; @Override public EntityRelation save(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { ActionType actionType = ActionType.RELATION_ADD_OR_UPDATE; try { var savedRelation = relationService.saveRelation(tenantId, relation); logEntityActionService.logEntityRelationAction(tenantId, customerId, savedRelation, user, actionType, null, savedRelation); return savedRelation; } catch (Exception e) { logEntityActionService.logEntityRelationAction(tenantId, customerId, relation, user, actionType, e, relation); throw e; } } @Override public EntityRelation delete(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { ActionType actionType = ActionType.RELATION_DELETED; try { var found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); if (found == null) { throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); } logEntityActionService.logEntityRelationAction(tenantId, customerId, found, user, actionType, null, found); return found; } catch (Exception e) { logEntityActionService.logEntityRelationAction(tenantId, customerId,
relation, user, actionType, e, relation); throw e; } } @Override public void deleteCommonRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, User user) { try { relationService.deleteEntityCommonRelations(tenantId, entityId); logEntityActionService.logEntityAction(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user); } catch (Exception e) { logEntityActionService.logEntityAction(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user, e); throw e; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\entity\relation\DefaultTbEntityRelationService.java
2
请完成以下Java代码
public void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException(); } this.age = age; } public int getAge() { return age; } @Override public String toString() { return this.name; } private class StudentGrade { private BigDecimal grade = BigDecimal.ZERO; private Date updatedAt; public StudentGrade(int grade) {
this.grade = new BigDecimal(grade); this.updatedAt = new Date(); } public BigDecimal getGrade() { return grade; } public Date getDate() { return updatedAt; } } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\publicmodifier\Student.java
1
请在Spring Boot框架中完成以下Java代码
public class DocOutboundProducerService implements IDocOutboundProducerService { @NonNull private static final Logger logger = LogManager.getLogger(DocOutboundProducerService.class); @NonNull private final HashMap<AdTableId, IDocOutboundProducer> outboundProducers = new HashMap<>(); @NonNull private final ReentrantLock outboundProducersLock = new ReentrantLock(); @Override public void registerProducer(final IDocOutboundProducer producer) { outboundProducersLock.lock(); try { registerProducer0(producer); } finally { outboundProducersLock.unlock(); } } private void registerProducer0(@NonNull final IDocOutboundProducer producer) { final AdTableId tableId = producer.getTableId(); Check.assumeNotNull(tableId, "Producer {} shall have a tableId", producer); if(outboundProducers.containsKey(tableId)) { logger.warn("Tried to register producer for tableId {} but it was already registered. This should be checked beforehand.", tableId); return; } producer.init(this); outboundProducers.put(tableId, producer); } @Override public void unregisterProducerByTableId(@NonNull final AdTableId tableId) { outboundProducersLock.lock(); try { unregisterProducerByTableId0(tableId); } finally { outboundProducersLock.unlock(); } } private void unregisterProducerByTableId0(@NonNull final AdTableId tableId) { final IDocOutboundProducer producer = outboundProducers.get(tableId); if (producer == null) { // no producer was not registered for given config, nothing to unregister return;
} producer.destroy(this); outboundProducers.remove(tableId); } private List<IDocOutboundProducer> getProducersList() { return new ArrayList<>(outboundProducers.values()); } @Override public void createDocOutbound(@NonNull final Object model) { for (final IDocOutboundProducer producer : getProducersList()) { if (!producer.accept(model)) { continue; } producer.createDocOutbound(model); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundProducerService.java
2
请完成以下Java代码
public void setDocStatus (final @Nullable java.lang.String DocStatus) { throw new IllegalArgumentException ("DocStatus is virtual column"); } @Override public java.lang.String getDocStatus() { return get_ValueAsString(COLUMNNAME_DocStatus); } @Override public void setNote (final @Nullable java.lang.String Note) { set_ValueNoCheck (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } @Override public void setPriceEntered_Override (final @Nullable BigDecimal PriceEntered_Override) { set_Value (COLUMNNAME_PriceEntered_Override, PriceEntered_Override); } @Override public BigDecimal getPriceEntered_Override() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceEntered_Override); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInvoiced (final BigDecimal QtyInvoiced) { set_Value (COLUMNNAME_QtyInvoiced, QtyInvoiced); } @Override public BigDecimal getQtyInvoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM) { set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM); } @Override public BigDecimal getQtyInvoicedInUOM() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToInvoice_Override (final @Nullable BigDecimal QtyToInvoice_Override) { set_Value (COLUMNNAME_QtyToInvoice_Override, QtyToInvoice_Override); } @Override public BigDecimal getQtyToInvoice_Override() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToInvoice_Override); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Line_Alloc.java
1
请在Spring Boot框架中完成以下Java代码
private TbTenantRuleEngineStats getTenantStats(TbProtoQueueMsg<ToRuleEngineMsg> m) { ToRuleEngineMsg reMsg = m.getValue(); return tenantStats.computeIfAbsent(new UUID(reMsg.getTenantIdMSB(), reMsg.getTenantIdLSB()), TbTenantRuleEngineStats::new); } public ConcurrentMap<UUID, TbTenantRuleEngineStats> getTenantStats() { return tenantStats; } public String getQueueName() { return queueName; } public ConcurrentMap<TenantId, RuleEngineException> getTenantExceptions() { return tenantExceptions; } public void printStats() { int total = totalMsgCounter.get();
if (total > 0) { StringBuilder stats = new StringBuilder(); counters.forEach(counter -> { stats.append(counter.getName()).append(" = [").append(counter.get()).append("] "); }); if (tenantId.isSysTenantId()) { log.info("[{}] Stats: {}", queueName, stats); } else { log.info("[{}][{}] Stats: {}", queueName, tenantId, stats); } } } public void reset() { counters.forEach(StatsCounter::clear); tenantStats.clear(); tenantExceptions.clear(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbRuleEngineConsumerStats.java
2
请在Spring Boot框架中完成以下Java代码
public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutDeleteReason() { return withoutDeleteReason; } public void setWithoutDeleteReason(Boolean withoutDeleteReason) { this.withoutDeleteReason = withoutDeleteReason; } public String getTaskCandidateGroup() { return taskCandidateGroup; } public void setTaskCandidateGroup(String taskCandidateGroup) { this.taskCandidateGroup = taskCandidateGroup; } public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; }
public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java
2