instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
private RedisConnectionFactory connectionFactory(Integer maxActive, Integer maxIdle, Integer minIdle, Integer maxWait, String host, String password, Integer timeout, Integer port, Integer database) { RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host); redisStandaloneConfiguration.setPort(port); redisStandaloneConfiguration.setDatabase(database); redisStandaloneConfiguration.setPassword(RedisPassword.of(password)); GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxTotal(maxActive); poolConfig.setMinIdle(minIdle); poolConfig.setMaxIdle(maxIdle); poolConfig.setMaxWaitMillis(maxWait); LettuceClientConfiguration lettucePoolingConfig = LettucePoolingClientConfiguration.builder() .poolConfig(poolConfig).shutdownTimeout(Duration.ofMillis(timeout)).build(); LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, lettucePoolingConfig); connectionFactory.afterPropertiesSet(); return connectionFactory; } /** * 创建 RedisTemplate 连接类型,此处为hash *
* @param factory * @return */ private RedisTemplate<Object, Object> getTemplate(RedisConnectionFactory factory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); template.setValueSerializer(jackson2JsonRedisSerializer(new ObjectMapper())); template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jackson2JsonRedisSerializer(new ObjectMapper())); template.afterPropertiesSet(); return template; } /** * 对value 进行序列化 * * @param objectMapper * @return */ private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(ObjectMapper objectMapper) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); return jackson2JsonRedisSerializer; } }
repos\springBoot-master\springboot-redis-queue\src\main\java\cn\abel\queue\config\RedisConfig.java
2
请完成以下Java代码
public String getTreeType() { final String keyColumnName = tableName + "_ID"; final String treeType; if (keyColumnName.equals("AD_Menu_ID")) { treeType = X_AD_Tree.TREETYPE_Menu; } else if (keyColumnName.equals("C_ElementValue_ID")) { treeType = X_AD_Tree.TREETYPE_ElementValue; } else if (keyColumnName.equals("M_Product_ID")) { treeType = X_AD_Tree.TREETYPE_Product; } else if (keyColumnName.equals("C_BPartner_ID")) { treeType = X_AD_Tree.TREETYPE_BPartner; } else if (keyColumnName.equals("AD_Org_ID")) { treeType = X_AD_Tree.TREETYPE_Organization; } else if (keyColumnName.equals("C_Project_ID")) { treeType = X_AD_Tree.TREETYPE_Project; } else if (keyColumnName.equals("M_ProductCategory_ID")) { treeType = X_AD_Tree.TREETYPE_ProductCategory; } else if (keyColumnName.equals("M_BOM_ID")) { treeType = X_AD_Tree.TREETYPE_BoM; } else if (keyColumnName.equals("C_SalesRegion_ID")) { treeType = X_AD_Tree.TREETYPE_SalesRegion; } else if (keyColumnName.equals("C_Campaign_ID")) { treeType = X_AD_Tree.TREETYPE_Campaign; } else if (keyColumnName.equals("C_Activity_ID")) { treeType = X_AD_Tree.TREETYPE_Activity; } else if (keyColumnName.equals("CM_CStage_ID")) { treeType = X_AD_Tree.TREETYPE_CMContainerStage; } else if (keyColumnName.equals("CM_Container_ID")) { treeType = X_AD_Tree.TREETYPE_CMContainer; } else if (keyColumnName.equals("CM_Media_ID")) { treeType = X_AD_Tree.TREETYPE_CMMedia;
} else if (keyColumnName.equals("CM_Template_ID")) { treeType = X_AD_Tree.TREETYPE_CMTemplate; } else { treeType = null; } return treeType; } @Override public void setTableName(final String tableName) { this.tableName = tableName; } protected String getTableName() { return tableName; } @Override public final void disableRoleAccessCheckWhileLoading() { this.checkRoleAccessWhileLoading = false; } protected final boolean isCheckRoleAccessWhileLoading() { return checkRoleAccessWhileLoading; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\tree\spi\impl\DefaultPOTreeSupport.java
1
请在Spring Boot框架中完成以下Java代码
BuildCustomizer<Build> groovyDependenciesConfigurer(ProjectDescription description) { return new GroovyDependenciesConfigurer(GROOVY4.match(description.getPlatformVersion())); } /** * Groovy source code contributions for projects using war packaging. */ @Configuration @ConditionalOnPackaging(WarPackaging.ID) static class WarPackagingConfiguration { @Bean ServletInitializerCustomizer<GroovyTypeDeclaration> javaServletInitializerCustomizer( ProjectDescription description) { return (typeDeclaration) -> { GroovyMethodDeclaration configure = GroovyMethodDeclaration.method("configure") .modifiers(Modifier.PROTECTED) .returning("org.springframework.boot.builder.SpringApplicationBuilder") .parameters( Parameter.of("application", "org.springframework.boot.builder.SpringApplicationBuilder")) .body(CodeBlock.ofStatement("application.sources($L)", description.getApplicationName())); configure.annotations().addSingle(ClassName.of(Override.class)); typeDeclaration.addMethodDeclaration(configure);
}; } } /** * Configuration for Groovy projects built with Maven. */ @Configuration @ConditionalOnBuildSystem(MavenBuildSystem.ID) static class GroovyMavenProjectConfiguration { @Bean GroovyMavenBuildCustomizer groovyBuildCustomizer() { return new GroovyMavenBuildCustomizer(); } } }
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\groovy\GroovyProjectGenerationDefaultContributorsConfiguration.java
2
请完成以下Java代码
public final ClassBasedFacetCollectorFactory<ModelType> registerFacetCollectorClasses(final Class<? extends IFacetCollector<ModelType>>... facetCollectorClasses) { if (facetCollectorClasses == null || facetCollectorClasses.length == 0) { return this; } for (final Class<? extends IFacetCollector<ModelType>> facetCollectorClass : facetCollectorClasses) { registerFacetCollectorClass(facetCollectorClass); } return this; } public IFacetCollector<ModelType> createFacetCollectors() { final CompositeFacetCollector<ModelType> collectors = new CompositeFacetCollector<>(); for (final Class<? extends IFacetCollector<ModelType>> collectorClass : facetCollectorClasses) { try {
final IFacetCollector<ModelType> collector = collectorClass.newInstance(); collectors.addFacetCollector(collector); } catch (final Exception e) { logger.warn("Failed to instantiate collector " + collectorClass + ". Skip it.", e); } } if (!collectors.hasCollectors()) { throw new IllegalStateException("No valid facet collector classes were defined"); } return collectors; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\ClassBasedFacetCollectorFactory.java
1
请完成以下Java代码
public boolean abortOperationIfNewStateEqualsOldState() { return false; } public abstract String getOperationName(); @Override public String toString() { PlanItem planItem = planItemInstanceEntity.getPlanItem(); StringBuilder stringBuilder = new StringBuilder(); String operationName = getOperationName(); stringBuilder.append(operationName != null ? operationName : "[Change plan item state]").append(" "); if (planItem != null) { stringBuilder.append(planItem); } stringBuilder.append(" (CaseInstance id: "); stringBuilder.append(planItemInstanceEntity.getCaseInstanceId()); stringBuilder.append(", PlanItemInstance id: "); stringBuilder.append(planItemInstanceEntity.getId()); stringBuilder.append("), "); String currentState = planItemInstanceEntity.getState(); String newState = getNewState(); if (!Objects.equals(currentState, newState)) {
stringBuilder.append("from [").append(currentState).append("] to new state: [").append(getNewState()).append("]"); stringBuilder.append(" with transition ["); stringBuilder.append(getLifeCycleTransition()); stringBuilder.append("]"); } else { stringBuilder.append("will remain in state [").append(newState).append("]"); } return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\AbstractChangePlanItemInstanceStateOperation.java
1
请完成以下Java代码
public boolean isRealChange(final PropertyChangeEvent e) { return true; } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } @Override protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed) { // Forward all key events on this component to the text field. // We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component. // Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here. if (m_text != null && condition == WHEN_FOCUSED) { // Usually the text component does not have focus yet but it was requested, so, considering that: // * we are requesting the focus just to make sure // * we select all text (once) => as an effect, on first key pressed the editor content (which is selected) will be deleted and replaced with the new typing // * make sure that in the focus event which will come, the text is not selected again, else, if user is typing fast, the editor content will be only what he typed last. if(!m_text.hasFocus()) { skipNextSelectAllOnFocusGained = true; m_text.requestFocus(); if (m_text.getDocument().getLength() > 0) {
m_text.selectAll(); } } if (m_text.processKeyBinding(ks, e, condition, pressed)) { return true; } } // // Fallback to super return super.processKeyBinding(ks, e, condition, pressed); } } // VNumber
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VNumber.java
1
请完成以下Java代码
public class Base64StringKeyGenerator implements StringKeyGenerator { private static final int DEFAULT_KEY_LENGTH = 32; private final BytesKeyGenerator keyGenerator; private final Base64.Encoder encoder; /** * Creates an instance with keyLength of 32 bytes and standard Base64 encoding. */ public Base64StringKeyGenerator() { this(DEFAULT_KEY_LENGTH); } /** * Creates an instance with the provided key length in bytes and standard Base64 * encoding. * @param keyLength the key length in bytes */ public Base64StringKeyGenerator(int keyLength) { this(Base64.getEncoder(), keyLength); } /** * Creates an instance with keyLength of 32 bytes and the provided encoder. * @param encoder the encoder to use */ public Base64StringKeyGenerator(Base64.Encoder encoder) { this(encoder, DEFAULT_KEY_LENGTH); } /** * Creates an instance with the provided key length and encoder. * @param encoder the encoder to use * @param keyLength the key length to use */ public Base64StringKeyGenerator(Base64.Encoder encoder, int keyLength) {
if (encoder == null) { throw new IllegalArgumentException("encode cannot be null"); } if (keyLength <= 0) { throw new IllegalArgumentException("keyLength must be greater than 0"); } this.encoder = encoder; this.keyGenerator = KeyGenerators.secureRandom(keyLength); } @Override public String generateKey() { byte[] key = this.keyGenerator.generateKey(); byte[] base64EncodedKey = this.encoder.encode(key); return new String(base64EncodedKey); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\keygen\Base64StringKeyGenerator.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final Optional<ProcessPreconditionsResolution> preconditionsResolution = checkValidSelection(); if (preconditionsResolution.isPresent()) { return ProcessPreconditionsResolution.rejectWithInternalReason(preconditionsResolution.get().getRejectReason()); } if (!isForceDelivery()) { return ProcessPreconditionsResolution.rejectWithInternalReason(" Use 'WEBUI_Picking_PickQtyToNewHU' for non force shipping records!"); } return ProcessPreconditionsResolution.accept();
} protected String doIt() { final HuId packToHuId = createNewHuId(); forcePick(getQtyToPack(), packToHuId); printPickingLabelIfAutoPrint(packToHuId); invalidatePackablesView(); invalidatePickingSlotsView(); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_ForcePickToNewHU.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_R_CategoryUpdates[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_User getAD_User() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getAD_User_ID(), get_TrxName()); } /** Set User/Contact. @param AD_User_ID User within the system - Internal or Business Partner Contact */ public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Self-Service. @param IsSelfService This is a Self-Service entry or this entry can be changed via Self-Service */ public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); } /** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_R_Category getR_Category() throws RuntimeException { return (I_R_Category)MTable.get(getCtx(), I_R_Category.Table_Name) .getPO(getR_Category_ID(), get_TrxName()); } /** Set Category. @param R_Category_ID Request Category */ public void setR_Category_ID (int R_Category_ID) { if (R_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_R_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_R_Category_ID, Integer.valueOf(R_Category_ID)); } /** Get Category. @return Request Category */ public int getR_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Category_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_CategoryUpdates.java
1
请在Spring Boot框架中完成以下Java代码
private void changeHUStatusFromPickedToActive(final Collection<I_M_HU> topLevelHUs) { topLevelHUs.forEach(this::changeHUStatusFromPickedToActive); } private void changeHUStatusFromPickedToActive(final I_M_HU topLevelHU) { if (X_M_HU.HUSTATUS_Picked.equals(topLevelHU.getHUStatus())) { huService.setHUStatusActive(topLevelHU); } } private HUTransformService newHUTransformService() { return HUTransformService.builder() .huQRCodesService(huService.getHuQRCodesService()) .build(); } @NonNull private PickingJob reinitializePickingTargetIfDestroyed(final PickingJob pickingJob) { if (isLineLevelPickTarget(pickingJob)) { return pickingJob.withLuPickingTarget(lineId, this::reinitializeLUPickingTarget); } else { return pickingJob.withLuPickingTarget(null, this::reinitializeLUPickingTarget); } } private boolean isLineLevelPickTarget(final PickingJob pickingJob) {return pickingJob.isLineLevelPickTarget();} @Nullable private LUPickingTarget reinitializeLUPickingTarget(@Nullable final LUPickingTarget luPickingTarget) { if (luPickingTarget == null) { return null;
} final HuId luId = luPickingTarget.getLuId(); if (luId == null) { return luPickingTarget; } final I_M_HU lu = huService.getById(luId); if (!huService.isDestroyedOrEmptyStorage(lu)) { return luPickingTarget; } final HuPackingInstructionsIdAndCaption luPI = huService.getEffectivePackingInstructionsIdAndCaption(lu); return LUPickingTarget.ofPackingInstructions(luPI); } // // // @Value @Builder private static class StepUnpickInstructions { @NonNull PickingJobStepId stepId; @NonNull PickingJobStepPickFromKey pickFromKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobUnPickCommand.java
2
请完成以下Java代码
public I_AD_PInstance getAD_PInstance() throws RuntimeException { return (I_AD_PInstance)MTable.get(getCtx(), I_AD_PInstance.Table_Name) .getPO(getAD_PInstance_ID(), get_TrxName()); } /** Set Process Instance. @param AD_PInstance_ID Instance of the process */ public void setAD_PInstance_ID (int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_Value (COLUMNNAME_AD_PInstance_ID, null); else set_Value (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID)); } /** Get Process Instance. @return Instance of the process */ public int getAD_PInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Temporal MRP & CRP. @param T_MRP_CRP_ID Temporal MRP & CRP */ public void setT_MRP_CRP_ID (int T_MRP_CRP_ID) { if (T_MRP_CRP_ID < 1) set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, null); else set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, Integer.valueOf(T_MRP_CRP_ID)); } /** Get Temporal MRP & CRP. @return Temporal MRP & CRP */ public int getT_MRP_CRP_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_T_MRP_CRP_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\eevolution\model\X_T_MRP_CRP.java
1
请完成以下Java代码
public @NonNull String getColumnSql(@NonNull String columnName) { return buildSql(columnName); } @Override public String getValueSql(Object value, List<Object> params) { final String valueSql; if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; valueSql = modelValue.getColumnName(); } else { valueSql = "?"; params.add(value); } return buildSql(valueSql);
} @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return null; } final String str = (String)value; // implementation detail: we use `subSequence` because we want to match the Postgres LPAD implementation. The returned string is of the EXACT required length, even if that means the string will be shortened. return StringUtils.leftPad(str.trim(), size, padStr).subSequence(0, size); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\LpadQueryFilterModifier.java
1
请在Spring Boot框架中完成以下Java代码
public class TimerJobSchedulerImpl implements TimerJobScheduler { protected final JobServiceConfiguration jobServiceConfiguration; public TimerJobSchedulerImpl(JobServiceConfiguration jobServiceConfiguration) { this.jobServiceConfiguration = jobServiceConfiguration; } @Override public void rescheduleTimerJobAfterExecution(JobEntity timerJob, VariableScope variableScope) { if (timerJob.getRepeat() != null) { TimerJobEntityManager timerJobEntityManager = jobServiceConfiguration.getTimerJobEntityManager(); TimerJobEntity newTimerJobEntity = timerJobEntityManager.createAndCalculateNextTimer(timerJob, variableScope); if (newTimerJobEntity != null) { if (jobServiceConfiguration.getInternalJobManager() != null) { jobServiceConfiguration.getInternalJobManager().preRepeatedTimerSchedule(newTimerJobEntity, variableScope); } scheduleTimerJob(newTimerJobEntity); } } } @Override public void scheduleTimerJob(TimerJobEntity timerJob) { scheduleTimer(timerJob); sendTimerScheduledEvent(timerJob); }
protected void scheduleTimer(TimerJobEntity timerJob) { if (timerJob == null) { throw new FlowableException("Empty timer job can not be scheduled"); } callJobProcessors(jobServiceConfiguration, JobProcessorContext.Phase.BEFORE_CREATE, timerJob); jobServiceConfiguration.getTimerJobEntityManager().insert(timerJob); } protected void sendTimerScheduledEvent(TimerJobEntity timerJob) { FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent( FlowableEngineEventType.TIMER_SCHEDULED, timerJob), jobServiceConfiguration.getEngineName()); } } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\TimerJobSchedulerImpl.java
2
请完成以下Java代码
private static Incoterms ofRecord(@NotNull final I_C_Incoterms record) { return Incoterms.builder() .id(IncotermsId.ofRepoId(record.getC_Incoterms_ID())) .name(record.getName()) .value(record.getValue()) .isDefault(record.isDefault()) .defaultLocation(record.getDefaultLocation()) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .build(); } private static final class IncotermsMap { private final ImmutableMap<IncotermsId, Incoterms> byId; private final ImmutableMap<OrgId, Incoterms> defaultByOrgId; private final ImmutableMap<ValueAndOrgId, Incoterms> byValueAndOrgId; IncotermsMap(final List<Incoterms> list) { this.byId = Maps.uniqueIndex(list, Incoterms::getId); this.defaultByOrgId = list.stream().filter(Incoterms::isDefault) .collect(ImmutableMap.toImmutableMap(Incoterms::getOrgId, incoterms->incoterms)); this.byValueAndOrgId = Maps.uniqueIndex(list, incoterm -> ValueAndOrgId.builder().value(incoterm.getValue()).orgId(incoterm.getOrgId()).build()); } @NonNull public Incoterms getById(@NonNull final IncotermsId id) { final Incoterms incoterms = byId.get(id); if (incoterms == null) { throw new AdempiereException("Incoterms not found by ID: " + id); } return incoterms; } @Nullable public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId) { return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY));
} @NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId) { final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()), byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build())); if (incoterms == null) { throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY); } return incoterms; } @Builder @Value private static class ValueAndOrgId { @NonNull String value; @NonNull OrgId orgId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java
1
请完成以下Java代码
public static final Number mod(TypeConverter converter, Object o1, Object o2) { if (o1 == null && o2 == null) { return LONG_ZERO; } if (isBigDecimalOrFloatOrDoubleOrDotEe(o1) || isBigDecimalOrFloatOrDoubleOrDotEe(o2)) { return (converter.convert(o1, Double.class) % converter.convert(o2, Double.class)); } if (o1 instanceof BigInteger || o2 instanceof BigInteger) { return converter.convert(o1, BigInteger.class).remainder(converter.convert(o2, BigInteger.class)); } return (converter.convert(o1, Long.class) % converter.convert(o2, Long.class)); } public static final Number neg(TypeConverter converter, Object value) { if (value == null) { return LONG_ZERO; } if (value instanceof BigDecimal) { return ((BigDecimal) value).negate(); } if (value instanceof BigInteger) { return ((BigInteger) value).negate(); } if (value instanceof Double) { return Double.valueOf(-((Double) value).doubleValue()); } if (value instanceof Float) {
return Float.valueOf(-((Float) value).floatValue()); } if (value instanceof String) { if (isDotEe((String) value)) { return Double.valueOf(-converter.convert(value, Double.class).doubleValue()); } return Long.valueOf(-converter.convert(value, Long.class).longValue()); } if (value instanceof Long) { return Long.valueOf(-((Long) value).longValue()); } if (value instanceof Integer) { return Integer.valueOf(-((Integer) value).intValue()); } if (value instanceof Short) { return Short.valueOf((short) -((Short) value).shortValue()); } if (value instanceof Byte) { return Byte.valueOf((byte) -((Byte) value).byteValue()); } throw new ELException(LocalMessages.get("error.negate", value.getClass())); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\misc\NumberOperations.java
1
请完成以下Java代码
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); metadataSources.addAnnotatedClass(Item.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() .build(); } private static ServiceRegistry configureServiceRegistry() throws IOException { return configureServiceRegistry(getProperties()); } private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
return new StandardServiceRegistryBuilder().applySettings(properties) .build(); } public static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties")); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\HibernateUtil.java
1
请完成以下Java代码
public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID) { this.AD_Column_ID = AD_Column_ID; return this; } public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName) { return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID()); } private EventListener getEditorListener() { // null allowed return editorListener; } /** * @param listener VetoableChangeListener that gets called if the field is changed. */ public VPanelFormFieldBuilder setEditorListener(EventListener listener)
{ this.editorListener = listener; return this; } public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel) { this.bindEditorToModel = bindEditorToModel; return this; } public VPanelFormFieldBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
1
请完成以下Java代码
public void setBpartnerName(final String bpartnerName) { this.bpartnerName = bpartnerName; this.bpartnerNameSet = true; } public void setAddress1(final String address1) { this.address1 = address1; this.address1Set = true; } public void setAddress2(final String address2) { this.address2 = address2; this.address2Set = true; } public void setAddress3(final String address3) { this.address3 = address3; this.address3Set = true; } public void setAddress4(final String address4) { this.address4 = address4; this.address4Set = true; } public void setPoBox(final String poBox) { this.poBox = poBox; this.poBoxSet = true; } public void setPostal(final String postal) { this.postal = postal; this.postalSet = true; } public void setCity(final String city) { this.city = city; this.citySet = true; } public void setDistrict(final String district) { this.district = district; this.districtSet = true;
} public void setRegion(final String region) { this.region = region; this.regionSet = true; } public void setCountryCode(final String countryCode) { this.countryCode = countryCode; this.countryCodeSet = true; } public void setGln(final String gln) { this.gln = gln; this.glnSet = true; } public void setShipTo(final Boolean shipTo) { this.shipTo = shipTo; this.shipToSet = true; } public void setShipToDefault(final Boolean shipToDefault) { this.shipToDefault = shipToDefault; this.shipToDefaultSet = true; } public void setBillTo(final Boolean billTo) { this.billTo = billTo; this.billToSet = true; } public void setBillToDefault(final Boolean billToDefault) { this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) { this.syncAdvise = syncAdvise; this.syncAdviseSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestLocation.java
1
请完成以下Java代码
public String toString() { final StringBuilder sb = new StringBuilder(); if (loginOrgId != null) { sb.append("@Login_Org_ID@=" + loginOrgId.getRepoId()); } if (sb.length() > 0) { sb.append(", "); } sb.append("@IsOrgLoginMandatory@=@" + (orgLoginMandatory ? "Y" : "N") + "@"); return sb.insert(0, getClass().getSimpleName() + "[") .append("]") .toString(); } @Override public boolean isInheritable() { return false; } private OrgId getLoginOrgId() { return loginOrgId; } private boolean isOrgLoginMandatory() { return orgLoginMandatory; }
public boolean isValidOrg(final OrgResource org) { if (isOrgLoginMandatory() && !org.isRegularOrg()) { logger.debug("Not valid {} because is OrgLoginMandatory is set", org); return false; } // Enforce Login_Org_ID: final OrgId loginOrgId = getLoginOrgId(); if (loginOrgId != null && !OrgId.equals(loginOrgId, org.getOrgId())) { logger.debug("Not valid {} because is not Login_Org_ID", org); return false; } return true; } public Predicate<OrgResource> asOrgResourceMatcher() { return this::isValidOrg; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\LoginOrgConstraint.java
1
请完成以下Java代码
public Builder setInternalName(final String internalName) { this.internalName = internalName; return this; } public Builder setUIStyle(@Nullable final String uiStyle) { this.uiStyle = uiStyle; return this; } public Builder addColumn(final DocumentLayoutColumnDescriptor.Builder columnBuilder) { Check.assumeNotNull(columnBuilder, "Parameter columnBuilder is not null"); columnsBuilders.add(columnBuilder); return this; } public Builder addColumn(final List<DocumentLayoutElementDescriptor.Builder> elementsBuilders) { if (elementsBuilders == null || elementsBuilders.isEmpty()) { return this; } final DocumentLayoutElementGroupDescriptor.Builder elementsGroupBuilder = DocumentLayoutElementGroupDescriptor.builder(); elementsBuilders.stream() .map(elementBuilder -> DocumentLayoutElementLineDescriptor.builder().addElement(elementBuilder)) .forEach(elementLineBuilder -> elementsGroupBuilder.addElementLine(elementLineBuilder)); final DocumentLayoutColumnDescriptor.Builder column = DocumentLayoutColumnDescriptor.builder().addElementGroup(elementsGroupBuilder); addColumn(column); return this; } public Builder setInvalid(final String invalidReason) { Check.assumeNotEmpty(invalidReason, "invalidReason is not empty"); this.invalidReason = invalidReason; logger.trace("Layout section was marked as invalid: {}", this); return this; } public Builder setClosableMode(@NonNull final ClosableMode closableMode) { this.closableMode = closableMode; return this; } public Builder setCaptionMode(@NonNull final CaptionMode captionMode) { this.captionMode = captionMode;
return this; } public boolean isValid() { return invalidReason == null; } public boolean isInvalid() { return invalidReason != null; } public boolean isNotEmpty() { return streamElementBuilders().findAny().isPresent(); } private Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders() { return columnsBuilders.stream().flatMap(DocumentLayoutColumnDescriptor.Builder::streamElementBuilders); } public Builder setExcludeSpecialFields() { streamElementBuilders().forEach(elementBuilder -> elementBuilder.setExcludeSpecialFields()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSectionDescriptor.java
1
请完成以下Java代码
public class ThirdPartySupportedToken extends UsernamePasswordToken { private String username; private char[] password; private boolean rememberMe = false; private String host; /** * 第三方token。 */ private String accessToken; public ThirdPartySupportedToken( String username, String password, String accessToken) { this.username = username; this.password = password != null ? password.toCharArray() : null; this.accessToken = accessToken; } @Override public String getUsername() { return this.username; } @Override public void setUsername(String username) { this.username = username; } @Override public char[] getPassword() { return this.password; } @Override public void setPassword(char[] password) { this.password = password; } @Override public Object getPrincipal() { return this.getUsername(); } @Override
public Object getCredentials() { return this.getPassword(); } @Override public String getHost() { return this.host; } @Override public void setHost(String host) { this.host = host; } @Override public boolean isRememberMe() { return this.rememberMe; } @Override public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Override public void clear() { super.clear(); this.accessToken = null; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\credentials\ThirdPartySupportedToken.java
1
请完成以下Java代码
public class ProcessInstanceStartEventSubscriptionDeletionBuilderImpl implements ProcessInstanceStartEventSubscriptionDeletionBuilder { protected final RuntimeServiceImpl runtimeService; protected String processDefinitionId; protected String tenantId; protected final Map<String, Object> correlationParameterValues = new HashMap<>(); public ProcessInstanceStartEventSubscriptionDeletionBuilderImpl(RuntimeServiceImpl runtimeService) { this.runtimeService = runtimeService; } @Override public ProcessInstanceStartEventSubscriptionDeletionBuilder processDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } @Override public ProcessInstanceStartEventSubscriptionDeletionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public ProcessInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) { correlationParameterValues.put(parameterName, parameterValue); return this; } @Override public ProcessInstanceStartEventSubscriptionDeletionBuilder addCorrelationParameterValues(Map<String, Object> parameters) { correlationParameterValues.putAll(parameters); return this; } public String getProcessDefinitionId() { return processDefinitionId;
} public String getTenantId() { return tenantId; } public boolean hasCorrelationParameterValues() { return correlationParameterValues.size() > 0; } public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } @Override public void deleteSubscriptions() { checkValidInformation(); runtimeService.deleteProcessInstanceStartEventSubscriptions(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(processDefinitionId)) { throw new FlowableIllegalArgumentException("The process definition must be provided using the exact id of the version the subscription was registered for."); } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ProcessInstanceStartEventSubscriptionDeletionBuilderImpl.java
1
请完成以下Java代码
public boolean isEnablePasswordPolicy() { return enablePasswordPolicy; } public ProcessEngineConfiguration setEnablePasswordPolicy(boolean enablePasswordPolicy) { this.enablePasswordPolicy = enablePasswordPolicy; return this; } public PasswordPolicy getPasswordPolicy() { return passwordPolicy; } public ProcessEngineConfiguration setPasswordPolicy(PasswordPolicy passwordPolicy) { this.passwordPolicy = passwordPolicy; return this; } public boolean isEnableCmdExceptionLogging() { return enableCmdExceptionLogging; } public ProcessEngineConfiguration setEnableCmdExceptionLogging(boolean enableCmdExceptionLogging) { this.enableCmdExceptionLogging = enableCmdExceptionLogging; return this; } public boolean isEnableReducedJobExceptionLogging() { return enableReducedJobExceptionLogging; } public ProcessEngineConfiguration setEnableReducedJobExceptionLogging(boolean enableReducedJobExceptionLogging) { this.enableReducedJobExceptionLogging = enableReducedJobExceptionLogging; return this; } public String getDeserializationAllowedClasses() { return deserializationAllowedClasses; } public ProcessEngineConfiguration setDeserializationAllowedClasses(String deserializationAllowedClasses) { this.deserializationAllowedClasses = deserializationAllowedClasses; return this; } public String getDeserializationAllowedPackages() { return deserializationAllowedPackages; }
public ProcessEngineConfiguration setDeserializationAllowedPackages(String deserializationAllowedPackages) { this.deserializationAllowedPackages = deserializationAllowedPackages; return this; } public DeserializationTypeValidator getDeserializationTypeValidator() { return deserializationTypeValidator; } public ProcessEngineConfiguration setDeserializationTypeValidator(DeserializationTypeValidator deserializationTypeValidator) { this.deserializationTypeValidator = deserializationTypeValidator; return this; } public boolean isDeserializationTypeValidationEnabled() { return deserializationTypeValidationEnabled; } public ProcessEngineConfiguration setDeserializationTypeValidationEnabled(boolean deserializationTypeValidationEnabled) { this.deserializationTypeValidationEnabled = deserializationTypeValidationEnabled; return this; } public String getInstallationId() { return installationId; } public ProcessEngineConfiguration setInstallationId(String installationId) { this.installationId = installationId; return this; } public boolean isSkipOutputMappingOnCanceledActivities() { return skipOutputMappingOnCanceledActivities; } public void setSkipOutputMappingOnCanceledActivities(boolean skipOutputMappingOnCanceledActivities) { this.skipOutputMappingOnCanceledActivities = skipOutputMappingOnCanceledActivities; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\ProcessEngineConfiguration.java
1
请完成以下Java代码
public static class Builder { private TableColumnResource resource; private final Set<Access> accesses = new LinkedHashSet<>(); public TableColumnPermission build() { return new TableColumnPermission(this); } public Builder setFrom(final TableColumnPermission columnPermission) { setResource(columnPermission.getResource()); setAccesses(columnPermission.accesses); return this; } public Builder setResource(final TableColumnResource resource) { this.resource = resource; return this; } public final Builder addAccess(final Access access) { accesses.add(access); return this; } public final Builder removeAccess(final Access access) { accesses.remove(access); return this; }
public final Builder setAccesses(final Set<Access> acceses) { accesses.clear(); accesses.addAll(acceses); return this; } public final Builder addAccesses(final Set<Access> acceses) { accesses.addAll(acceses); return this; } public final Builder removeAllAccesses() { accesses.clear(); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnPermission.java
1
请完成以下Java代码
default String getMainListenerId() { throw new UnsupportedOperationException("This container does not support retrieving the main listener id"); } /** * Get arbitrary static information that will be added to the * {@link KafkaHeaders#LISTENER_INFO} header of all records. * @return the info. * @since 2.8.6 */ @Nullable default byte[] getListenerInfo() { throw new UnsupportedOperationException("This container does not support retrieving the listener info"); } /** * If this container has child containers, return true if at least one child is running. If there are not * child containers, returns {@link #isRunning()}. * @return true if a child is running. * @since 2.7.3 */ default boolean isChildRunning() { return isRunning(); } /** * Return true if the container is running, has never been started, or has been * stopped. * @return true if the state is as expected. * @since 2.8 * @see #stopAbnormally(Runnable) */ default boolean isInExpectedState() { return true; } /** * Stop the container after some exception so that {@link #isInExpectedState()} will * return false. * @param callback the callback. * @since 2.8 * @see #isInExpectedState() */ default void stopAbnormally(Runnable callback) {
stop(callback); } /** * If this container has child containers, return the child container that is assigned * the topic/partition. Return this when there are no child containers. * @param topic the topic. * @param partition the partition. * @return the container. */ default MessageListenerContainer getContainerFor(String topic, int partition) { return this; } /** * Notify a parent container that a child container has stopped. * @param child the container. * @param reason the reason. * @since 2.9.7 */ default void childStopped(MessageListenerContainer child, ConsumerStoppedEvent.Reason reason) { } /** * Notify a parent container that a child container has started. * @param child the container. * @since 3.3 */ default void childStarted(MessageListenerContainer child) { } @Override default void destroy() { stop(); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\MessageListenerContainer.java
1
请完成以下Java代码
public class DomXmlLogger extends ExternalTaskClientLogger { public void usingDocumentBuilderFactory(String name) { logDebug("001", "Using document builder factory '{}'", name); } public void createdDocumentBuilder() { logDebug("002", "Successfully created new document builder"); } public void documentBuilderFactoryConfiguration(String property, String value) { logDebug("003", "DocumentBuilderFactory configuration '{}' '{}'", property, value); } public void parsingInput() { logDebug("004", "Parsing input into DOM document."); } public DataFormatException unableToCreateParser(Exception cause) { return new DataFormatException(exceptionMessage("005", "Unable to create DocumentBuilder"), cause); } public DataFormatException unableToParseInput(Exception e) { return new DataFormatException(exceptionMessage("006", "Unable to parse input into DOM document"), e); } public DataFormatException unableToCreateTransformer(Exception cause) { return new DataFormatException(exceptionMessage("007", "Unable to create a transformer to write element"), cause); } public DataFormatException unableToTransformElement(Node element, Exception cause) {
return new DataFormatException(exceptionMessage("008", "Unable to transform element '{}:{}'", element.getNamespaceURI(), element.getNodeName()), cause); } public DataFormatException unableToWriteInput(Object parameter, Throwable cause) { return new DataFormatException(exceptionMessage("009", "Unable to write object '{}' to xml element", parameter.toString()), cause); } public DataFormatException unableToDeserialize(Object node, String canonicalClassName, Throwable cause) { return new DataFormatException( exceptionMessage("010", "Cannot deserialize '{}...' to java class '{}'", node.toString(), canonicalClassName), cause); } public DataFormatException unableToCreateMarshaller(Throwable cause) { return new DataFormatException(exceptionMessage("011", "Cannot create marshaller"), cause); } public DataFormatException unableToCreateContext(Throwable cause) { return new DataFormatException(exceptionMessage("012", "Cannot create context"), cause); } public DataFormatException unableToCreateUnmarshaller(Throwable cause) { return new DataFormatException(exceptionMessage("013", "Cannot create unmarshaller"), cause); } public DataFormatException classNotFound(String classname, ClassNotFoundException cause) { return new DataFormatException(exceptionMessage("014", "Class {} not found ", classname), cause); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlLogger.java
1
请完成以下Java代码
public void setPlannedAmt (final BigDecimal PlannedAmt) { set_ValueNoCheck (COLUMNNAME_PlannedAmt, PlannedAmt); } @Override public BigDecimal getPlannedAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt) { set_ValueNoCheck (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt); } @Override public BigDecimal getPlannedMarginAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedPrice (final BigDecimal PlannedPrice) { set_ValueNoCheck (COLUMNNAME_PlannedPrice, PlannedPrice); } @Override public BigDecimal getPlannedPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPlannedQty (final BigDecimal PlannedQty) { set_ValueNoCheck (COLUMNNAME_PlannedQty, PlannedQty); } @Override public BigDecimal getPlannedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setSKU (final @Nullable java.lang.String SKU) { set_ValueNoCheck (COLUMNNAME_SKU, SKU); } @Override public java.lang.String getSKU() { return get_ValueAsString(COLUMNNAME_SKU); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Details_v.java
1
请完成以下Java代码
protected I_M_HU_Snapshot retrieveModelSnapshot(final I_M_HU hu) { return query(I_M_HU_Snapshot.class) .addEqualsFilter(I_M_HU_Snapshot.COLUMN_M_HU_ID, hu.getM_HU_ID()) .addEqualsFilter(I_M_HU_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId()) .create() .firstOnlyNotNull(I_M_HU_Snapshot.class); } @Override protected void restoreModelWhenSnapshotIsMissing(final I_M_HU model) { throw new HUException("Cannot restore " + model + " because snapshot is missing"); } @Override protected int getModelId(final I_M_HU_Snapshot modelSnapshot) { return modelSnapshot.getM_HU_ID(); } @Override protected I_M_HU getModel(final I_M_HU_Snapshot modelSnapshot) { return modelSnapshot.getM_HU(); } @Override protected Map<Integer, I_M_HU_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU_Item huItem) { return query(I_M_HU_Snapshot.class) .addEqualsFilter(I_M_HU_Snapshot.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID()) .addEqualsFilter(I_M_HU_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId()) .create() .map(I_M_HU_Snapshot.class, snapshot2ModelIdFunction); } @Override protected Map<Integer, I_M_HU> retrieveModelsByParent(I_M_HU_Item huItem) { return query(I_M_HU.class) .addEqualsFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItem.getM_HU_Item_ID()) .create() .mapById(I_M_HU.class); } /** * Recursively collect all M_HU_IDs and M_HU_Item_IDs starting from <code>startHUIds</code> to the bottom, including those too. * * @param startHUIds * @param huIdsCollector
* @param huItemIdsCollector */ protected final void collectHUAndItemIds(final Set<Integer> startHUIds, final Set<Integer> huIdsCollector, final Set<Integer> huItemIdsCollector) { Set<Integer> huIdsToCheck = new HashSet<>(startHUIds); while (!huIdsToCheck.isEmpty()) { huIdsCollector.addAll(huIdsToCheck); final Set<Integer> huItemIds = retrieveM_HU_Item_Ids(huIdsToCheck); huItemIdsCollector.addAll(huItemIds); final Set<Integer> includedHUIds = retrieveIncludedM_HUIds(huItemIds); huIdsToCheck = new HashSet<>(includedHUIds); huIdsToCheck.removeAll(huIdsCollector); } } private final Set<Integer> retrieveM_HU_Item_Ids(final Set<Integer> huIds) { if (huIds.isEmpty()) { return Collections.emptySet(); } final List<Integer> huItemIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Item.class, getContext()) .addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds) .create() .listIds(); return new HashSet<>(huItemIdsList); } private final Set<Integer> retrieveIncludedM_HUIds(final Set<Integer> huItemIds) { if (huItemIds.isEmpty()) { return Collections.emptySet(); } final List<Integer> huIdsList = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class, getContext()) .addInArrayOrAllFilter(I_M_HU.COLUMN_M_HU_Item_Parent_ID, huItemIds) .create() .listIds(); return new HashSet<>(huIdsList); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_SnapshotHandler.java
1
请完成以下Java代码
protected ITranslatableString buildMessage() { final TranslatableStringBuilder message = TranslatableStrings.builder(); final ITranslatableString originalMessage = getOriginalMessage(); if (!TranslatableStrings.isBlank(originalMessage)) { message.append(originalMessage); } else { message.append("Unknown evaluation error"); } if (!expressions.isEmpty()) { message.append("\nExpressions trace:");
for (final IExpression<?> expression : expressions) { message.append("\n * ").appendObj(expression); } } if (!Check.isEmpty(partialEvaluatedExpression)) { message.append("\nPartial evaluated expression: ").append(partialEvaluatedExpression); } return message.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\exceptions\ExpressionEvaluationException.java
1
请完成以下Java代码
public CompositePermissionCheck getPermissionChecks() { return permissionChecks; } public void setAtomicPermissionChecks(List<PermissionCheck> permissionChecks) { this.permissionChecks.setAtomicChecks(permissionChecks); } public void addAtomicPermissionCheck(PermissionCheck permissionCheck) { permissionChecks.addAtomicCheck(permissionCheck); } public void setPermissionChecks(CompositePermissionCheck permissionChecks) { this.permissionChecks = permissionChecks; } public boolean isRevokeAuthorizationCheckEnabled() { return isRevokeAuthorizationCheckEnabled; } public void setRevokeAuthorizationCheckEnabled(boolean isRevokeAuthorizationCheckEnabled) {
this.isRevokeAuthorizationCheckEnabled = isRevokeAuthorizationCheckEnabled; } public void setHistoricInstancePermissionsEnabled(boolean historicInstancePermissionsEnabled) { this.historicInstancePermissionsEnabled = historicInstancePermissionsEnabled; } /** * Used in SQL mapping */ public boolean isHistoricInstancePermissionsEnabled() { return historicInstancePermissionsEnabled; } public boolean isUseLeftJoin() { return useLeftJoin; } public void setUseLeftJoin(boolean useLeftJoin) { this.useLeftJoin = useLeftJoin; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\AuthorizationCheck.java
1
请完成以下Java代码
private List<Resource> resolve(String location) throws IOException { List<Resource> resources = new ArrayList<>( Arrays.asList(this.resourcePatternResolver.getResources(location))); resources.sort((r1, r2) -> { try { return r1.getURL().toString().compareTo(r2.getURL().toString()); } catch (IOException ex) { return 0; } }); return resources; } } /** * Scripts to be used to initialize the database. * * @since 3.0.0 */ public static class Scripts implements Iterable<Resource> { private final List<Resource> resources; private boolean continueOnError; private String separator = ";"; private @Nullable Charset encoding; public Scripts(List<Resource> resources) { this.resources = resources; } @Override public Iterator<Resource> iterator() { return this.resources.iterator(); } public Scripts continueOnError(boolean continueOnError) { this.continueOnError = continueOnError; return this; } public boolean isContinueOnError() { return this.continueOnError; }
public Scripts separator(String separator) { this.separator = separator; return this; } public String getSeparator() { return this.separator; } public Scripts encoding(@Nullable Charset encoding) { this.encoding = encoding; return this; } public @Nullable Charset getEncoding() { return this.encoding; } } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\AbstractScriptDatabaseInitializer.java
1
请在Spring Boot框架中完成以下Java代码
public List<DADRE1> getDADRE1() { if (dadre1 == null) { dadre1 = new ArrayList<DADRE1>(); } return this.dadre1; } /** * Gets the value of the dtrsd1 property. * * @return * possible object is * {@link DTRSD1 } * */ public DTRSD1 getDTRSD1() { return dtrsd1; } /** * Sets the value of the dtrsd1 property. * * @param value * allowed object is * {@link DTRSD1 } * */ public void setDTRSD1(DTRSD1 value) { this.dtrsd1 = value; } /** * Gets the value of the dmark1 property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the dmark1 property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDMARK1().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DMARK1 } * * */ public List<DMARK1> getDMARK1() { if (dmark1 == null) {
dmark1 = new ArrayList<DMARK1>(); } return this.dmark1; } /** * Gets the value of the dqvar1 property. * * @return * possible object is * {@link DQVAR1 } * */ public DQVAR1 getDQVAR1() { return dqvar1; } /** * Sets the value of the dqvar1 property. * * @param value * allowed object is * {@link DQVAR1 } * */ public void setDQVAR1(DQVAR1 value) { this.dqvar1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DETAILXlief.java
2
请完成以下Java代码
public void incrementCountProcessed() { getMeter(METERNAME_Processed).plusOne(); } @Override public long getCountErrors() { return getMeter(METERNAME_Error).getGauge(); } @Override public void incrementCountErrors() { getMeter(METERNAME_Error).plusOne(); } @Override public long getQueueSize() { return getMeter(METERNAME_QueueSize).getGauge(); } @Override public void incrementQueueSize()
{ getMeter(METERNAME_QueueSize).plusOne(); } @Override public void decrementQueueSize() { getMeter(METERNAME_QueueSize).minusOne(); } @Override public long getCountSkipped() { return getMeter(METERNAME_Skipped).getGauge(); } @Override public void incrementCountSkipped() { getMeter(METERNAME_Skipped).plusOne(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\MonitorableQueueProcessorStatistics.java
1
请完成以下Java代码
public HistoricVariableInstanceQuery variableValueLike(String variableName, String variableValue) { wrappedHistoricVariableInstanceQuery.variableValueLike(variableName, variableValue); return this; } @Override public HistoricVariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) { wrappedHistoricVariableInstanceQuery.variableValueLikeIgnoreCase(variableName, variableValue); return this; } @Override public HistoricVariableInstanceQuery orderByVariableName() { wrappedHistoricVariableInstanceQuery.orderByVariableName(); return this; } @Override public HistoricVariableInstanceQuery asc() { wrappedHistoricVariableInstanceQuery.asc(); return this; } @Override public HistoricVariableInstanceQuery desc() { wrappedHistoricVariableInstanceQuery.desc(); return this; } @Override public HistoricVariableInstanceQuery orderBy(QueryProperty property) { wrappedHistoricVariableInstanceQuery.orderBy(property); return this; } @Override public HistoricVariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { wrappedHistoricVariableInstanceQuery.orderBy(property, nullHandlingOnOrder); return this; }
@Override public long count() { return wrappedHistoricVariableInstanceQuery.count(); } @Override public HistoricVariableInstance singleResult() { return wrappedHistoricVariableInstanceQuery.singleResult(); } @Override public List<HistoricVariableInstance> list() { return wrappedHistoricVariableInstanceQuery.list(); } @Override public List<HistoricVariableInstance> listPage(int firstResult, int maxResults) { return wrappedHistoricVariableInstanceQuery.listPage(firstResult, maxResults); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\CmmnHistoricVariableInstanceQueryImpl.java
1
请完成以下Java代码
public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Column span. @param SpanX Number of columns spanned */ public void setSpanX (int SpanX) { set_Value (COLUMNNAME_SpanX, Integer.valueOf(SpanX)); } /** Get Column span. @return Number of columns spanned */ public int getSpanX () { Integer ii = (Integer)get_Value(COLUMNNAME_SpanX); if (ii == null) return 0; return ii.intValue(); } /** Set Row Span. @param SpanY Number of rows spanned */ public void setSpanY (int SpanY) { set_Value (COLUMNNAME_SpanY, Integer.valueOf(SpanY)); } /** Get Row Span. @return Number of rows spanned */ public int getSpanY () { Integer ii = (Integer)get_Value(COLUMNNAME_SpanY); if (ii == null) return 0; return ii.intValue(); } public I_C_POSKeyLayout getSubKeyLayout() throws RuntimeException { return (I_C_POSKeyLayout)MTable.get(getCtx(), I_C_POSKeyLayout.Table_Name) .getPO(getSubKeyLayout_ID(), get_TrxName()); } /** Set Key Layout. @param SubKeyLayout_ID
Key Layout to be displayed when this key is pressed */ public void setSubKeyLayout_ID (int SubKeyLayout_ID) { if (SubKeyLayout_ID < 1) set_Value (COLUMNNAME_SubKeyLayout_ID, null); else set_Value (COLUMNNAME_SubKeyLayout_ID, Integer.valueOf(SubKeyLayout_ID)); } /** Get Key Layout. @return Key Layout to be displayed when this key is pressed */ public int getSubKeyLayout_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SubKeyLayout_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } @Override public I_AD_Reference getAD_Reference() throws RuntimeException { return (I_AD_Reference)MTable.get(getCtx(), I_AD_Reference.Table_Name) .getPO(getAD_Reference_ID(), get_TrxName()); } @Override public int getAD_Reference_ID() { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Reference_ID); if (ii == null) return 0; return ii.intValue(); } @Override public void setAD_Reference_ID(int AD_Reference_ID) { if (AD_Reference_ID < 1) set_Value (COLUMNNAME_AD_Reference_ID, null); else set_Value (COLUMNNAME_AD_Reference_ID, Integer.valueOf(AD_Reference_ID)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_POSKey.java
1
请完成以下Java代码
public static boolean mapException(Exception e, ActivityExecution execution, List<MapExceptionEntry> exceptionMap) { return mapException(e, execution, exceptionMap, false); } public static boolean mapException(Exception e, ActivityExecution execution, List<MapExceptionEntry> exceptionMap, boolean wrapped) { if (exceptionMap == null) { return false; } if (wrapped && e instanceof ActivitiActivityExecutionException) { e = (Exception) e.getCause(); } String defaultMap = null; for (MapExceptionEntry me : exceptionMap) { String exceptionClass = me.getClassName(); String errorCode = me.getErrorCode(); String rootCause = me.getRootCause(); // save the first mapping with no exception class as default map if (StringUtils.isNotEmpty(errorCode) && StringUtils.isEmpty(exceptionClass) && defaultMap == null) { // if rootCause is set, check if it matches the exception if (StringUtils.isNotEmpty(rootCause)) { if (ExceptionUtils.getRootCause(e).getClass().getName().equals(rootCause)) { defaultMap = errorCode; continue; } } else { defaultMap = errorCode; continue; } } // ignore if error code or class are not defined if (StringUtils.isEmpty(errorCode) || StringUtils.isEmpty(exceptionClass)) continue;
if (e.getClass().getName().equals(exceptionClass)) { if (StringUtils.isNotEmpty(rootCause)) { if (ExceptionUtils.getRootCause(e).getClass().getName().equals(rootCause)) { propagateError(errorCode, execution); } continue; } propagateError(errorCode, execution); return true; } if (me.isAndChildren()) { Class<?> exceptionClassClass = ReflectUtil.loadClass(exceptionClass); if (exceptionClassClass.isAssignableFrom(e.getClass())) { if (StringUtils.isNotEmpty(rootCause)) { if (ExceptionUtils.getRootCause(e).getClass().getName().equals(rootCause)) { propagateError(errorCode, execution); return true; } } else { propagateError(errorCode, execution); return true; } } } } if (defaultMap != null) { propagateError(defaultMap, execution); return true; } return false; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\ErrorPropagation.java
1
请完成以下Java代码
public boolean canRead(String processDefinitionKey, String appName) { return hasPermission(processDefinitionKey, SecurityPolicyAccess.READ, appName); } @Override public boolean canWrite(String processDefinitionKey, String appName) { return hasPermission(processDefinitionKey, SecurityPolicyAccess.WRITE, appName); } public boolean hasPermission( String processDefinitionKey, SecurityPolicyAccess securityPolicyAccess, String appName ) { // No security policies defined, allowed to see everything if (securityPoliciesProperties.getPolicies().isEmpty()) { return true; } // If you are an admin you can see everything , @TODO: make it more flexible if (securityManager.getAuthenticatedUserRoles().contains("ACTIVITI_ADMIN")) { return true; } Set<String> keys = new HashSet<>(); Map<String, Set<String>> policiesMap = getAllowedKeys(securityPolicyAccess); if (policiesMap.get(appName) != null) { keys.addAll(policiesMap.get(appName)); } //also factor for case sensitivity and hyphens (which are stripped when specified through env var) if (appName != null && policiesMap.get(appName.replaceAll("-", "").toLowerCase()) != null) {
keys.addAll(policiesMap.get(appName.replaceAll("-", "").toLowerCase())); } return ( anEntryInSetStartsKey(keys, processDefinitionKey) || keys.contains(securityPoliciesProperties.getWildcard()) ); } //startsWith logic supports the case of audit where only definition id might be available and it would start with the key //protected scope means we can override where exact matching more appropriate (consider keys ProcessWithVariables and ProcessWithVariables2) //even for audit would be better if we had a known separator which cant be part of key - this seems best we can do for now protected boolean anEntryInSetStartsKey(Set<String> keys, String processDefinitionKey) { for (String key : keys) { if (processDefinitionKey.startsWith(key)) { return true; } } return false; } protected SecurityPoliciesProperties getSecurityPoliciesProperties() { return securityPoliciesProperties; } }
repos\Activiti-develop\activiti-core-common\activiti-spring-security-policies\src\main\java\org\activiti\core\common\spring\security\policies\BaseSecurityPoliciesManagerImpl.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { card.previous(cardContainer); } }); next.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { card.next(cardContainer); } }); ctrl.add(previous); ctrl.add(next); dialogContent.add(ctrl, BorderLayout.NORTH); } dialog.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } class PreviewMouseAdapter extends MouseAdapter { private JDialog dialog;
private Window window; PreviewMouseAdapter(JDialog d, Window w) { dialog = d; window = w; } @Override public void mouseClicked(MouseEvent e) { dialog.dispose(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { AEnv.showWindow(window); } }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowMenu.java
1
请完成以下Java代码
public void setM_Allergen(final org.compiere.model.I_M_Allergen M_Allergen) { set_ValueFromPO(COLUMNNAME_M_Allergen_ID, org.compiere.model.I_M_Allergen.class, M_Allergen); } @Override public void setM_Allergen_ID (final int M_Allergen_ID) { if (M_Allergen_ID < 1) set_Value (COLUMNNAME_M_Allergen_ID, null); else set_Value (COLUMNNAME_M_Allergen_ID, M_Allergen_ID); } @Override public int getM_Allergen_ID() { return get_ValueAsInt(COLUMNNAME_M_Allergen_ID); } @Override public void setM_Product_Allergen_ID (final int M_Product_Allergen_ID) { if (M_Product_Allergen_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Allergen_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Allergen_ID, M_Product_Allergen_ID); } @Override public int getM_Product_Allergen_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Allergen_ID);
} @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Allergen.java
1
请完成以下Java代码
public @Nullable String getHost() { return determineTargetConnectionFactory().getHost(); } @Override public int getPort() { return determineTargetConnectionFactory().getPort(); } @Override public String getVirtualHost() { return determineTargetConnectionFactory().getVirtualHost(); } @Override public String getUsername() { return determineTargetConnectionFactory().getUsername(); } @Override public @Nullable ConnectionFactory getTargetConnectionFactory(Object key) { return this.targetConnectionFactories.get(key); } /** * Specify whether to apply a validation enforcing all {@link ConnectionFactory#isPublisherConfirms()} and * {@link ConnectionFactory#isPublisherReturns()} have a consistent value. * <p> * A consistent value means that all ConnectionFactories must have the same value between all * {@link ConnectionFactory#isPublisherConfirms()} and the same value between all * {@link ConnectionFactory#isPublisherReturns()}. * </p> * <p> * Note that in any case the values between {@link ConnectionFactory#isPublisherConfirms()} and * {@link ConnectionFactory#isPublisherReturns()} don't need to be equals between each other. * </p> * @param consistentConfirmsReturns true to validate, false to not validate. * @since 2.4.4 */ public void setConsistentConfirmsReturns(boolean consistentConfirmsReturns) { this.consistentConfirmsReturns = consistentConfirmsReturns; } /** * Adds the given {@link ConnectionFactory} and associates it with the given lookup key. * @param key the lookup key. * @param connectionFactory the {@link ConnectionFactory}. */ protected void addTargetConnectionFactory(Object key, ConnectionFactory connectionFactory) { this.targetConnectionFactories.put(key, connectionFactory); for (ConnectionListener listener : this.connectionListeners) { connectionFactory.addConnectionListener(listener); } checkConfirmsAndReturns(connectionFactory); } /** * Removes the {@link ConnectionFactory} associated with the given lookup key and returns it. * @param key the lookup key
* @return the {@link ConnectionFactory} that was removed */ protected ConnectionFactory removeTargetConnectionFactory(Object key) { return this.targetConnectionFactories.remove(key); } /** * Determine the current lookup key. This will typically be implemented to check a thread-bound context. * * @return The lookup key. */ protected abstract @Nullable Object determineCurrentLookupKey(); @Override public void destroy() { resetConnection(); } @Override public void resetConnection() { this.targetConnectionFactories.values().forEach(ConnectionFactory::resetConnection); if (this.defaultTargetConnectionFactory != null) { this.defaultTargetConnectionFactory.resetConnection(); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\AbstractRoutingConnectionFactory.java
1
请完成以下Java代码
public String toString() { return "LoginRequest [username=" + username + ", password=*********" + ", hostKey=" + hostKey + "]"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; } public String getHostKey() { return hostKey; } public void setHostKey(String hostKey) { this.hostKey = hostKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\LoginRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class Developer { // private int id; private String name; private String blog; private int phone; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBlog() { return blog; } public void setBlog(String blog) {
this.blog = blog; } public int getPhone() { return phone; } public void setPhone(int phone) { this.phone = phone; } @Override public String toString() { return "Developer{" + "id=" + id + ", name='" + name + '\'' + ", blog='" + blog + '\'' + ", phone=" + phone + '}'; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Annotation-LookService\src\main\java\spring\annotation\model\Developer.java
2
请完成以下Java代码
public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set Search Key. @param Value
Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java
1
请完成以下Java代码
public void updateSalesPartnerInCustomerMaterdata(@NonNull final I_C_Order orderRecord) { final boolean performUpdate = sysConfigBL.getBooleanValue(CommissionConstants.SYSCONFIG_UPDATE_SALESPARTNER_IN_MASTER_DATA, true /*preserve old behavior by default*/, ClientAndOrgId.ofClientAndOrg(orderRecord.getAD_Client_ID(), orderRecord.getAD_Org_ID())); if (!performUpdate) { return; } if (!orderRecord.isSOTrx()) { return; } final BPartnerId effectiveBillPartnerId = orderBL.getEffectiveBillPartnerId(orderRecord); if (effectiveBillPartnerId == null) { return; // no customer whose master data we we could update } final BPartnerId salesBPartnerId = BPartnerId.ofRepoIdOrNull(orderRecord.getC_BPartner_SalesRep_ID()); if (salesBPartnerId == null || salesBPartnerId.equals(effectiveBillPartnerId)) { return; // leave the master data untouched } final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final I_C_BPartner billBPartnerRecord = bpartnerDAO.getById(effectiveBillPartnerId); billBPartnerRecord.setC_BPartner_SalesRep_ID(orderRecord.getC_BPartner_SalesRep_ID()); saveRecord(billBPartnerRecord); } @DocValidate(timings = ModelValidator.TIMING_BEFORE_COMPLETE) public void preventCompleteIfMissingSalesPartner(@NonNull final I_C_Order orderRecord) { final DocumentSalesRepDescriptor documentSalesRepDescriptor = documentSalesRepDescriptorFactory.forDocumentRecord(orderRecord); if (documentSalesRepDescriptor.validatesOK()) { return; // nothing to do
} throw documentSalesRepDescriptorService.createMissingSalesRepException(); } /** * Validate that both C_Order.SalesPartnerCode and C_Order.C_BPartner_SalesRep_ID point to the same BPartner */ private void validateSalesPartnerAssignment(@NonNull final I_C_Order orderRecord) { final BPartnerId salesRepId = BPartnerId.ofRepoIdOrNull(orderRecord.getC_BPartner_SalesRep_ID()); if (salesRepId == null || Check.isBlank(orderRecord.getSalesPartnerCode())) { return; } final OrgId orderOrgId = OrgId.ofRepoId(orderRecord.getAD_Org_ID()); final BPartnerId salesBPartnerIdBySalesCode = bpartnerDAO .getBPartnerIdBySalesPartnerCode(orderRecord.getSalesPartnerCode(), ImmutableSet.of(orderOrgId, OrgId.ANY)) .orElse(null); if (salesBPartnerIdBySalesCode != null && !salesBPartnerIdBySalesCode.equals(salesRepId)) { throw new AdempiereException("C_Order.SalesPartnerCode doesn't match C_Order.C_BPartner_SalesRep_ID") .appendParametersToMessage() .setParameter("C_Order.C_Order_ID", orderRecord.getC_Order_ID()) .setParameter("C_Order.SalesPartnerCode", orderRecord.getSalesPartnerCode()) .setParameter("C_Order.C_BPartner_SalesRep_ID", salesRepId.getRepoId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\salesrep\interceptor\C_Order.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultPrintFormatsRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); private final CCache<ClientId, DefaultPrintFormats> cache = CCache.<ClientId, DefaultPrintFormats>builder() .tableName(I_AD_PrintForm.Table_Name) .build(); public DefaultPrintFormats getByClientId(@NonNull final ClientId clientId) { return cache.getOrLoad(clientId, this::retrieveByClientId); } private DefaultPrintFormats retrieveByClientId(@NonNull final ClientId clientId) { final I_AD_PrintForm record = queryBL.createQueryBuilderOutOfTrx(I_AD_PrintForm.class) .addEqualsFilter(I_AD_PrintForm.COLUMNNAME_AD_Client_ID, clientId) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_AD_PrintForm.class);
if (record == null) { return DefaultPrintFormats.NONE; } return toDefaultPrintFormats(record); } private static DefaultPrintFormats toDefaultPrintFormats(final I_AD_PrintForm record) { return DefaultPrintFormats.builder() .orderPrintFormatId(PrintFormatId.ofRepoIdOrNull(record.getOrder_PrintFormat_ID())) .invoicePrintFormatId(PrintFormatId.ofRepoIdOrNull(record.getInvoice_PrintFormat_ID())) .shipmentPrintFormatId(PrintFormatId.ofRepoIdOrNull(record.getShipment_PrintFormat_ID())) .manufacturingOrderPrintFormatId(PrintFormatId.ofRepoIdOrNull(record.getManuf_Order_PrintFormat_ID())) .distributionOrderPrintFormatId(PrintFormatId.ofRepoIdOrNull(record.getDistrib_Order_PrintFormat_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DefaultPrintFormatsRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class TestSocketController { @Autowired private WebSocket webSocket; @PostMapping("/sendAll") public Result<String> sendAll(@RequestBody JSONObject jsonObject) { Result<String> result = new Result<String>(); String message = jsonObject.getString("message"); JSONObject obj = new JSONObject(); obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_TOPIC); obj.put(WebsocketConst.MSG_ID, "M0001"); obj.put(WebsocketConst.MSG_TXT, message); webSocket.sendMessage(obj.toJSONString()); result.setResult("群发!"); return result; } @PostMapping("/sendUser")
public Result<String> sendUser(@RequestBody JSONObject jsonObject) { Result<String> result = new Result<String>(); String userId = jsonObject.getString("userId"); String message = jsonObject.getString("message"); JSONObject obj = new JSONObject(); obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER); obj.put(WebsocketConst.MSG_USER_ID, userId); obj.put(WebsocketConst.MSG_ID, "M0001"); obj.put(WebsocketConst.MSG_TXT, message); webSocket.sendMessage(userId, obj.toJSONString()); result.setResult("单发"); return result; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\controller\TestSocketController.java
2
请在Spring Boot框架中完成以下Java代码
public PickingJobQtyAvailable execute() { final PickingJobQtyAvailable.PickingJobQtyAvailableBuilder result = PickingJobQtyAvailable.builder(); final PickingJob pickingJob = getPickingJob(); for (PickingJobLine line : pickingJob.getLines()) { final Quantity qtyAvailableToPick = allocateLine(line); result.line(PickingJobLineQtyAvailable.builder() .lineId(line.getId()) .qtyRemainingToPick(line.getQtyRemainingToPick()) .qtyAvailableToPick(qtyAvailableToPick) .build()); } return result.build(); } private ImmutableSet<ProductId> getProductIdsRemainingToBePicked() { final PickingJob pickingJob = getPickingJob(); return pickingJob.streamLines() .filter(line -> !line.isFullyPicked()) .map(PickingJobLine::getProductId) .collect(ImmutableSet.toImmutableSet()); } @NonNull private PickingJob getPickingJob() { return pickingJobSupplier.get(); } private PickingJob retrievePickingJob() { @NonNull final PickingJob pickingJob = pickingJobService.getById(pickingJobId); pickingJob.assertCanBeEditedBy(callerId); return pickingJob; } @Nullable
private Quantity allocateLine(PickingJobLine line) { final Quantity qtyRemainingToPick = line.getQtyRemainingToPick(); if (line.isFullyPicked()) { return qtyRemainingToPick.toZeroIfNegative(); } final ProductAvailableStocks availableStocks = getAvailableStocks(); if (availableStocks == null) { return null; // N/A } return availableStocks.allocateQty(line.getProductId(), qtyRemainingToPick); } @Nullable private ProductAvailableStocks getAvailableStocks() { return availableStocksSupplier.get(); } @Nullable private ProductAvailableStocks computeAvailableStocks() { final Workplace workplace = warehouseService.getWorkplaceByUserId(callerId).orElse(null); if (workplace == null) {return null;} final ProductAvailableStocks availableStocks = huService.newAvailableStocksProvider(workplace); if (availableStocks == null) {return null;} availableStocks.warmUpByProductIds(getProductIdsRemainingToBePicked()); return availableStocks; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\get_qty_available\PickingJobGetQtyAvailableCommand.java
2
请完成以下Java代码
public HistoricJobLogQuery orderByTenantId() { return orderBy(HistoricJobLogQueryProperty.TENANT_ID); } @Override public HistoricJobLogQuery orderByHostname() { return orderBy(HistoricJobLogQueryProperty.HOSTNAME); } // results ////////////////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsCountByQueryCriteria(this); } public List<HistoricJobLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsByQueryCriteria(this, page); } // getter ////////////////////////////////// public boolean isTenantIdSet() { return isTenantIdSet; } public String getJobId() { return jobId; } public String getJobExceptionMessage() { return jobExceptionMessage; } public String getJobDefinitionId() { return jobDefinitionId; } public String getJobDefinitionType() { return jobDefinitionType; } public String getJobDefinitionConfiguration() { return jobDefinitionConfiguration; } public String[] getActivityIds() { return activityIds; } public String[] getFailedActivityIds() { return failedActivityIds; } public String[] getExecutionIds() { return executionIds; } public String getProcessInstanceId() { return processInstanceId; }
public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() { return state; } public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请完成以下Java代码
public class User implements Serializable { private static final long serialVersionUID = 1L; protected static final HashMap<String, User> DB = new HashMap<>(); static { DB.put("admin", new User("admin", "password")); DB.put("user", new User("user", "pass")); } private String name; private String password; private List<Date> logins = new ArrayList<Date>(); public User(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Date> getLogins() { return logins; } public void setLogins(List<Date> logins) { this.logins = logins; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\user\check\User.java
1
请在Spring Boot框架中完成以下Java代码
public class User implements Serializable, UserDetails { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String username; private String password; private String role; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; }
@Override public boolean isEnabled() { return true; } public void setUsername(String username) { this.username = username; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return Arrays.asList(new SimpleGrantedAuthority(getRole())); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\User.java
2
请完成以下Spring Boot application配置
spring: application: name: myApp cloud: consul: host: localhost port: 8500 discovery: healthCheckPath: /my-health-check healthCheckInterval: 20s enabled: true instanceId: ${spring.application.name}:${random.value} server: port: 0 cluster: leader: serviceName: cluster serviceId: node-1 consul: host: l
ocalhost port: 8500 discovery: enabled: false session: ttl: 15 refresh: 7 election: envelopeTemplate: services/%s/leader
repos\tutorials-master\spring-cloud-modules\spring-cloud-consul\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class CachingService { @Autowired CacheManager cacheManager; public void putToCache(String cacheName, String key, String value) { cacheManager.getCache(cacheName).put(key, value); } public String getFromCache(String cacheName, String key) { String value = null; if (cacheManager.getCache(cacheName).get(key) != null) { value = cacheManager.getCache(cacheName).get(key).get().toString(); } return value; } @CacheEvict(value = "first", key = "#cacheKey") public void evictSingleCacheValue(String cacheKey) { } @CacheEvict(value = "first", allEntries = true) public void evictAllCacheValues() { } public void evictSingleCacheValue(String cacheName, String cacheKey) {
cacheManager.getCache(cacheName).evict(cacheKey); } public void evictAllCacheValues(String cacheName) { cacheManager.getCache(cacheName).clear(); } public void evictAllCaches() { cacheManager.getCacheNames() .parallelStream() .forEach(cacheName -> cacheManager.getCache(cacheName).clear()); } @Scheduled(fixedRate = 6000) public void evictAllcachesAtIntervals() { evictAllCaches(); } }
repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\eviction\service\CachingService.java
2
请完成以下Java代码
public JsonNode createJsonNode(Object parameter) { if(parameter instanceof SpinJsonNode) { return (JsonNode) ((SpinJsonNode) parameter).unwrap(); } else if(parameter instanceof String) { return createJsonNode((String) parameter); } else if(parameter instanceof Integer) { return createJsonNode((Integer) parameter); } else if(parameter instanceof Boolean) { return createJsonNode((Boolean) parameter); } else if(parameter instanceof Float) { return createJsonNode((Float) parameter); } else if(parameter instanceof Long) { return createJsonNode((Long) parameter); } else if(parameter instanceof Number) { return createJsonNode(((Number) parameter).doubleValue()); } else if(parameter instanceof List) { return createJsonNode((List<Object>) parameter); } else if(parameter instanceof Map) { return createJsonNode((Map<String, Object>) parameter); } else if (parameter == null) { return createNullJsonNode(); } else { throw LOG.unableToCreateNode(parameter.getClass().getSimpleName()); } } public JsonNode createJsonNode(String parameter) { return objectMapper.getNodeFactory().textNode(parameter); } public JsonNode createJsonNode(Integer parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Float parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Double parameter) {
return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Long parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Boolean parameter) { return objectMapper.getNodeFactory().booleanNode(parameter); } public JsonNode createJsonNode(List<Object> parameter) { if (parameter != null) { ArrayNode node = objectMapper.getNodeFactory().arrayNode(); for(Object entry : parameter) { node.add(createJsonNode(entry)); } return node; } else { return createNullJsonNode(); } } public JsonNode createJsonNode(Map<String, Object> parameter) { if (parameter != null) { ObjectNode node = objectMapper.getNodeFactory().objectNode(); for (Map.Entry<String, Object> entry : parameter.entrySet()) { node.set(entry.getKey(), createJsonNode(entry.getValue())); } return node; } else { return createNullJsonNode(); } } public JsonNode createNullJsonNode() { return objectMapper.getNodeFactory().nullNode(); } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormat.java
1
请完成以下Java代码
public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public int getComm() { return comm; } public void setComm(int comm) {
this.comm = comm; } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } @Override public String toString() { return String.format("Employee [empNo=%d, ename=%s, job=%s, mgr=%d, hiredate=%s, sal=%d, comm=%d, deptno=%d]", empNo, ename, job, mgr, hiredate, sal, comm, deptno); } }
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\flexypool\Employee.java
1
请完成以下Java代码
public Builder setAD_OrgTrx_ID(final int AD_OrgTrx_ID) { setSegmentValue(AcctSegmentType.OrgTrx, AD_OrgTrx_ID); return this; } public Builder setC_LocFrom_ID(final int C_LocFrom_ID) { setSegmentValue(AcctSegmentType.LocationFrom, C_LocFrom_ID); return this; } public Builder setC_LocTo_ID(final int C_LocTo_ID) { setSegmentValue(AcctSegmentType.LocationTo, C_LocTo_ID); return this; } public Builder setC_SalesRegion_ID(@Nullable final SalesRegionId C_SalesRegion_ID) { setSegmentValue(AcctSegmentType.SalesRegion, SalesRegionId.toRepoId(C_SalesRegion_ID)); return this; } public Builder setC_Project_ID(final int C_Project_ID) { setSegmentValue(AcctSegmentType.Project, C_Project_ID); return this; } public Builder setC_Campaign_ID(final int C_Campaign_ID) { setSegmentValue(AcctSegmentType.Campaign, C_Campaign_ID); return this; } public Builder setC_Activity_ID(final int C_Activity_ID) { setSegmentValue(AcctSegmentType.Activity, C_Activity_ID); return this; } public Builder setSalesOrderId(final int C_OrderSO_ID) { setSegmentValue(AcctSegmentType.SalesOrder, C_OrderSO_ID); return this; } public Builder setUser1_ID(final int user1_ID) { setSegmentValue(AcctSegmentType.UserList1, user1_ID); return this; } public Builder setUser2_ID(final int user2_ID) { setSegmentValue(AcctSegmentType.UserList2, user2_ID);
return this; } public Builder setUserElement1_ID(final int userElement1_ID) { setSegmentValue(AcctSegmentType.UserElement1, userElement1_ID); return this; } public Builder setUserElement2_ID(final int userElement2_ID) { setSegmentValue(AcctSegmentType.UserElement2, userElement2_ID); return this; } public Builder setUserElementString1(final String userElementString1) { setSegmentValue(AcctSegmentType.UserElementString1, userElementString1); return this; } public Builder setUserElementString2(final String userElementString2) { setSegmentValue(AcctSegmentType.UserElementString2, userElementString2); return this; } public Builder setUserElementString3(final String userElementString3) { setSegmentValue(AcctSegmentType.UserElementString3, userElementString3); return this; } public Builder setUserElementString4(final String userElementString4) { setSegmentValue(AcctSegmentType.UserElementString4, userElementString4); return this; } public Builder setUserElementString5(final String userElementString5) { setSegmentValue(AcctSegmentType.UserElementString5, userElementString5); return this; } public Builder setUserElementString6(final String userElementString6) { setSegmentValue(AcctSegmentType.UserElementString6, userElementString6); return this; } public Builder setUserElementString7(final String userElementString7) { setSegmentValue(AcctSegmentType.UserElementString7, userElementString7); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountDimension.java
1
请完成以下Java代码
default boolean isNullExpression() { return false; } /** * Resolves all variables which available and returns a new string expression. * * @param ctx * @return string expression with all available variables resolved. * @throws ExpressionEvaluationException */ default IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException { final String expressionStr = evaluate(ctx, OnVariableNotFound.Preserve); return StringExpressionCompiler.instance.compile(expressionStr); } /** * Turns this expression in an expression which caches it's evaluation results. * If this expression implements {@link ICachedStringExpression} it will be returned directly without any wrapping. * * @return cached expression */ default ICachedStringExpression caching() { return CachedStringExpression.wrapIfPossible(this); } /** * @return same as {@link #toString()} but the whole string representation will be on one line (new lines are stripped)
*/ default String toOneLineString() { return toString() .replace("\r", "") .replace("\n", ""); } default CompositeStringExpression.Builder toComposer() { return composer().append(this); } @Override String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IStringExpression.java
1
请完成以下Java代码
public IStringExpression toOrderByStringExpression() { final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias) ? joinOnTableNameOrAlias + "." + joinOnColumnName : joinOnColumnName; if (sqlExpression == null) { return ConstantStringExpression.of(joinOnColumnNameFQ); } else { return sqlExpression.toOrderByStringExpression(joinOnColumnNameFQ); } } public SqlSelectDisplayValue withJoinOnTableNameOrAlias(@Nullable final String joinOnTableNameOrAlias) { return !Objects.equals(this.joinOnTableNameOrAlias, joinOnTableNameOrAlias) ? toBuilder().joinOnTableNameOrAlias(joinOnTableNameOrAlias).build() : this;
} public String toSqlOrderByUsingColumnNameAlias() { final String columnNameAliasFQ = joinOnTableNameOrAlias != null ? joinOnTableNameOrAlias + "." + columnNameAlias : columnNameAlias; if (sqlExpression != null) { return columnNameAliasFQ + "[" + sqlExpression.getNameSqlArrayIndex() + "]"; } else { return columnNameAliasFQ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlSelectDisplayValue.java
1
请完成以下Java代码
public class Customer implements Comparable<Customer> { private Integer id; private String name; private Long phone; private String locality; private String city; private String zip; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getPhone() { return phone; } public void setPhone(Long phone) { this.phone = phone; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public Customer(Integer id, String name, Long phone, String locality, String city, String zip) { super(); this.id = id; this.name = name; this.phone = phone; this.locality = locality; this.city = city; this.zip = zip; } public Customer(Integer id, String name, Long phone) { super(); this.id = id;
this.name = name; this.phone = phone; } public Customer(String name) { super(); this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Customer other = (Customer) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public int compareTo(Customer o) { return this.name.compareTo(o.getName()); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Customer [id=").append(id).append(", name=").append(name).append(", phone=").append(phone).append("]"); return builder.toString(); } }
repos\tutorials-master\libraries-apache-commons-collections\src\main\java\com\baeldung\commons\collections\collectionutils\Customer.java
1
请完成以下Java代码
public String getListenerId() { return this.listenerId; } /** * Return the consumer group id. * @return the consumer group id. * @since 3.2 */ public @Nullable String getGroupId() { return this.groupId; } /** * Return the client id. * @return the client id. * @since 3.2 */ @Nullable public String getClientId() { return this.clientId; } /** * Return the source topic. * @return the source. */ public String getSource() { return this.record.topic(); } /** * Return the consumer record. * @return the record. * @since 3.0.6 */
public ConsumerRecord<?, ?> getRecord() { return this.record; } /** * Return the partition. * @return the partition. * @since 3.2 */ public String getPartition() { return Integer.toString(this.record.partition()); } /** * Return the offset. * @return the offset. * @since 3.2 */ public String getOffset() { return Long.toString(this.record.offset()); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaRecordReceiverContext.java
1
请完成以下Java代码
public void setIsForeignCustomer (final boolean IsForeignCustomer) { throw new IllegalArgumentException ("IsForeignCustomer is virtual column"); } @Override public boolean isForeignCustomer() { return get_ValueAsBoolean(COLUMNNAME_IsForeignCustomer); } @Override public void setIsPrintoutForOtherUser (final boolean IsPrintoutForOtherUser) { set_Value (COLUMNNAME_IsPrintoutForOtherUser, IsPrintoutForOtherUser); } @Override public boolean isPrintoutForOtherUser() { return get_ValueAsBoolean(COLUMNNAME_IsPrintoutForOtherUser); } /** * ItemName AD_Reference_ID=540735 * Reference name: ItemName */ public static final int ITEMNAME_AD_Reference_ID=540735; /** Rechnung = Rechnung */ public static final String ITEMNAME_Rechnung = "Rechnung"; /** Mahnung = Mahnung */ public static final String ITEMNAME_Mahnung = "Mahnung"; /** Mitgliedsausweis = Mitgliedsausweis */ public static final String ITEMNAME_Mitgliedsausweis = "Mitgliedsausweis"; /** Brief = Brief */ public static final String ITEMNAME_Brief = "Brief"; /** Sofort-Druck PDF = Sofort-Druck PDF */ public static final String ITEMNAME_Sofort_DruckPDF = "Sofort-Druck PDF"; /** PDF = PDF */ public static final String ITEMNAME_PDF = "PDF"; /** Versand/Wareneingang = Versand/Wareneingang */ public static final String ITEMNAME_VersandWareneingang = "Versand/Wareneingang"; @Override public void setItemName (final @Nullable java.lang.String ItemName) { set_Value (COLUMNNAME_ItemName, ItemName); } @Override public java.lang.String getItemName() { return get_ValueAsString(COLUMNNAME_ItemName); }
@Override public void setPrintingQueueAggregationKey (final @Nullable java.lang.String PrintingQueueAggregationKey) { set_Value (COLUMNNAME_PrintingQueueAggregationKey, PrintingQueueAggregationKey); } @Override public java.lang.String getPrintingQueueAggregationKey() { return get_ValueAsString(COLUMNNAME_PrintingQueueAggregationKey); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue.java
1
请完成以下Java代码
public class RecordMigelType extends RecordServiceType { @XmlAttribute(name = "tariff_type", required = true) protected String tariffType; /** * Gets the value of the tariffType property. * * @return * possible object is * {@link String } * */ public String getTariffType() { return tariffType;
} /** * Sets the value of the tariffType property. * * @param value * allowed object is * {@link String } * */ public void setTariffType(String value) { this.tariffType = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordMigelType.java
1
请完成以下Java代码
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; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoViaFullJoins\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public void init() { if (workQueueSize < 1) { workQueueSize = 1000; } if (this.keepAliveTime < 1) { this.keepAliveTime = 1000; } int coreSize = 0; if (this.corePoolSize < 1) { coreSize = Runtime.getRuntime().availableProcessors(); maxPoolSize = Math.round(((float) (coreSize * notifyRadio)) / 10); corePoolSize = coreSize / 4; if (corePoolSize < 1) { corePoolSize = 1; } } // NOTICE: corePoolSize不能大于maxPoolSize,否则会出错 if (maxPoolSize < corePoolSize) { maxPoolSize = corePoolSize; } /** * ThreadPoolExecutor就是依靠BlockingQueue的阻塞机制来维持线程池,当池子里的线程无事可干的时候就通过workQueue.take()阻塞住 */ BlockingQueue<Runnable> notifyWorkQueue = new ArrayBlockingQueue<Runnable>(workQueueSize); executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, notifyWorkQueue, new ThreadPoolExecutor.CallerRunsPolicy()); LOG.info("NotifyExecutor Info : CPU = " + coreSize + " | corePoolSize = " + corePoolSize + " | maxPoolSize = " + maxPoolSize + " | workQueueSize = " + workQueueSize); } public void destroy() { executor.shutdownNow(); } public void execute(Runnable command) { executor.execute(command); } public void showExecutorInfo() { LOG.info("NotifyExecutor Info : corePoolSize = " + corePoolSize + " | maxPoolSize = " + maxPoolSize + " | workQueueSize = " +
workQueueSize + " | taskCount = " + executor.getTaskCount() + " | activeCount = " + executor.getActiveCount() + " | completedTaskCount = " + executor.getCompletedTaskCount()); } public void setNotifyRadio(int notifyRadio) { this.notifyRadio = notifyRadio; } public void setWorkQueueSize(int workQueueSize) { this.workQueueSize = workQueueSize; } public void setKeepAliveTime(long keepAliveTime) { this.keepAliveTime = keepAliveTime; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } }
repos\roncoo-pay-master\roncoo-pay-app-settlement\src\main\java\com\roncoo\pay\app\settlement\utils\SettThreadPoolExecutor.java
1
请完成以下Spring Boot application配置
server: port: 8088 spring: freemarker: # 启用 freemarker 模板 enabled: true # 是否缓存 cache: false # Content Type content-type: text/html # 编码 charset: utf-8 # 模板后缀 suffix: .ftl # 引用 request 的属性名称 request-context-attribute: request # 是否暴露 request 域中的属性 expose-request-attributes: false # 是否暴露session域中的属性 expose-session-attributes: false # request 域中的属性是否可以覆盖 controller 的 model 的同名项。默认 false,如果发生同名属性覆盖的情况会抛出异常 allow-request-override: true # session 域中的属性是否可以覆盖 controller 的 model 的同名项。默认 false,如果发生同名属性覆盖的情况会抛出异常 allow-session-override: true # 暴露官方提供的宏 expose-spring-macro-helpers: true # 启动时检查模板位置是否有效 check-template-location: true
# 优先加载文件系统的模板 prefer-file-system-access: true # 模板所在位置(目录) template-loader-path: - classpath:/templates/ settings: datetime_format: yyyy-MM-dd HH:mm:ss # date 输出格式化 template_update_delay: 30m # 模板引擎刷新时间 default_encoding: utf-8 # 默认编码
repos\springboot-demo-master\freemaker\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class InitBeanInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor { @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { System.out.println("Bean实例化的后置处理器-执行:InitBeanInstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation 方法 处理:" + beanName); return null; } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { System.out.println("Bean实例化的后置处理器-执行:InitBeanInstantiationAwareBeanPostProcessor.postProcessAfterInstantiation 方法 处理:" + beanName); return true; } @Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { System.out.println("Bean实例化的后置处理器-执行:InitBeanInstantiationAwareBeanPostProcessor.postProcessPropertyValues 方法 处理:" + beanName);
return null; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("Bean实例化的后置处理器-执行:InitBeanInstantiationAwareBeanPostProcessor.postProcessBeforeInitialization 方法 处理:" + beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("Bean实例化的后置处理器-执行:InitBeanInstantiationAwareBeanPostProcessor.postProcessAfterInitialization 方法 处理:" + beanName); return bean; } }
repos\spring-boot-student-master\spring-boot-student-spring\src\main\java\com\xiaolyuh\init\destory\InitBeanInstantiationAwareBeanPostProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public int save(T entity) { //说明:保存一个实体,null的属性也会保存,不会使用数据库默认值 return mapper.insert(entity); } @Override public int delete(Object key) { //说明:根据主键字段进行删除,方法参数必须包含完整的主键属性 return mapper.deleteByPrimaryKey(key); } @Override public int updateAll(T entity) { //说明:根据主键更新实体全部字段,null值会被更新 return mapper.updateByPrimaryKey(entity);
} @Override public int updateNotNull(T entity) { //根据主键更新属性不为null的值 return mapper.updateByPrimaryKeySelective(entity); } @Override public List<T> selectByExample(Object example) { //说明:根据Example条件进行查询 //重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列 return mapper.selectByExample(example); } }
repos\SpringAll-master\27.Spring-Boot-Mapper-PageHelper\src\main\java\com\springboot\service\impl\BaseService.java
2
请完成以下Java代码
public void setAD_Table(org.compiere.model.I_AD_Table AD_Table) { set_ValueFromPO(COLUMNNAME_AD_Table_ID, org.compiere.model.I_AD_Table.class, AD_Table); } /** Set DB-Tabelle. @param AD_Table_ID Database Table information */ @Override public void setAD_Table_ID (int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID)); } /** Get DB-Tabelle. @return Database Table information */ @Override public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Validation Rule Depends On. @param AD_Val_Rule_Dep_ID Validation Rule Depends On */ @Override public void setAD_Val_Rule_Dep_ID (int AD_Val_Rule_Dep_ID) { if (AD_Val_Rule_Dep_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Dep_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Dep_ID, Integer.valueOf(AD_Val_Rule_Dep_ID)); } /** Get Validation Rule Depends On. @return Validation Rule Depends On */ @Override public int getAD_Val_Rule_Dep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_Dep_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class); } @Override public void setAD_Val_Rule(org.compiere.model.I_AD_Val_Rule AD_Val_Rule) { set_ValueFromPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, AD_Val_Rule); } /** Set Dynamische Validierung. @param AD_Val_Rule_ID Regel für die dynamische Validierung */ @Override public void setAD_Val_Rule_ID (int AD_Val_Rule_ID) { if (AD_Val_Rule_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_ID, Integer.valueOf(AD_Val_Rule_ID)); } /** Get Dynamische Validierung. @return Regel für die dynamische Validierung */ @Override public int getAD_Val_Rule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Technical note. @param TechnicalNote A note that is not indended for the user documentation, but for developers, customizers etc */ @Override public void setTechnicalNote (java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } /** Get Technical note. @return A note that is not indended for the user documentation, but for developers, customizers etc */ @Override public java.lang.String getTechnicalNote () { return (java.lang.String)get_Value(COLUMNNAME_TechnicalNote); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule_Dep.java
1
请完成以下Java代码
public void deleteUser(String userId) { getIdmIdentityService().deleteUser(userId); } @Override public void setUserPicture(String userId, Picture picture) { getIdmIdentityService().setUserPicture(userId, picture); } @Override public Picture getUserPicture(String userId) { return getIdmIdentityService().getUserPicture(userId); } @Override public void setAuthenticatedUserId(String authenticatedUserId) { Authentication.setAuthenticatedUserId(authenticatedUserId); } @Override public String getUserInfo(String userId, String key) { return getIdmIdentityService().getUserInfo(userId, key); } @Override public List<String> getUserInfoKeys(String userId) { return getIdmIdentityService().getUserInfoKeys(userId); }
@Override public void setUserInfo(String userId, String key, String value) { getIdmIdentityService().setUserInfo(userId, key, value); } @Override public void deleteUserInfo(String userId, String key) { getIdmIdentityService().deleteUserInfo(userId, key); } protected IdmIdentityService getIdmIdentityService() { IdmIdentityService idmIdentityService = EngineServiceUtil.getIdmIdentityService(configuration); if (idmIdentityService == null) { throw new FlowableException("Trying to use idm identity service when it is not initialized"); } return idmIdentityService; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\IdentityServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderLineDescriptor implements DocumentLineDescriptor { public static OrderLineDescriptor cast(@NonNull final DocumentLineDescriptor documentLineDescriptor) { return (OrderLineDescriptor)documentLineDescriptor; } int orderLineId; int orderId; int orderBPartnerId; int docTypeId; @Builder @JsonCreator public OrderLineDescriptor( @JsonProperty("orderLineId") final int orderLineId, @JsonProperty("orderId") final int orderId, @JsonProperty("orderBPartnerId") final int orderBPartnerId, @JsonProperty("docTypeId") final int docTypeId) { this.orderLineId = orderLineId;
this.orderId = orderId; this.orderBPartnerId = orderBPartnerId; this.docTypeId = docTypeId; } @Override public void validate() { checkIdGreaterThanZero("orderLineId", orderLineId); checkIdGreaterThanZero("orderId", orderId); checkIdGreaterThanZero("orderBPartnerId", orderBPartnerId); checkIdGreaterThanZero("docTypeId", docTypeId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\OrderLineDescriptor.java
2
请完成以下Java代码
void hide() { if (status == Status.PUBLISHED) { status = Status.HIDDEN; } throw new IllegalStateException("we cannot hide an article with status=" + status); } void archive() { if (status != Status.ARCHIVED) { status = Status.ARCHIVED; } throw new IllegalStateException("the article is already archived"); } void comment(Username user, String message) { comments.add(new Comment(user, message)); } void like(Username user) { likedBy.add(user); } void dislike(Username user) { likedBy.remove(user); } public Slug getSlug() { return slug; } public Username getAuthor() { return author; } public String getTitle() { return title;
} public String getContent() { return content; } public Status getStatus() { return status; } public List<Comment> getComments() { return Collections.unmodifiableList(comments); } public List<Username> getLikedBy() { return Collections.unmodifiableList(likedBy); } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddjmolecules\article\Article.java
1
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoginDto login = (LoginDto) o; return Objects.equals(this.user, login.user) && Objects.equals(this.pass, login.pass); } @Override public int hashCode() { return Objects.hash(user, pass); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LoginDto {\n"); sb.append(" user: ")
.append(toIndentedString(user)) .append("\n"); sb.append(" pass: ") .append(toIndentedString(pass)) .append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString() .replace("\n", "\n "); } }
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\dto\LoginDto.java
1
请完成以下Java代码
static boolean hasUniqueDigits(int num) { String str = Integer.toString(num); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) { return false; } } } return true; } static int combinatorial(int n) { if (n == 0) return 1; int result = 10; int current = 9; int available = 9; for (int i = 2; i <= n; i++) { current *= available; result += current; available--; } return result; } static int dp(int n) {
if (n == 0) return 1; int result = 10; int current = 9; int available = 9; for (int i = 2; i <= n; i++) { current *= available; result += current; available--; } return result; } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\uniquedigitcounter\UniqueDigitCounter.java
1
请完成以下Java代码
public class Factorial { public long factorialUsingForLoop(int n) { long fact = 1; for (int i = 2; i <= n; i++) { fact = fact * i; } return fact; } public long factorialUsingStreams(int n) { return LongStream.rangeClosed(1, n) .reduce(1, (long x, long y) -> x * y); } public long factorialUsingRecursion(int n) { if (n <= 2) { return n; } return n * factorialUsingRecursion(n - 1); } private Long[] factorials = new Long[20]; public long factorialUsingMemoize(int n) { if (factorials[n] != null) { return factorials[n]; } if (n <= 2) { return n; } long nthValue = n * factorialUsingMemoize(n - 1); factorials[n] = nthValue; return nthValue;
} public BigInteger factorialHavingLargeResult(int n) { BigInteger result = BigInteger.ONE; for (int i = 2; i <= n; i++) result = result.multiply(BigInteger.valueOf(i)); return result; } public long factorialUsingApacheCommons(int n) { return CombinatoricsUtils.factorial(n); } public BigInteger factorialUsingGuava(int n) { return BigIntegerMath.factorial(n); } }
repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\algorithms\factorial\Factorial.java
1
请完成以下Java代码
public final GeneralCopyRecordSupport setAdWindowId(final @Nullable AdWindowId adWindowId) { this.adWindowId = adWindowId; return this; } @SuppressWarnings("SameParameterValue") @Nullable protected final <T> T getParentModel(final Class<T> modelType) { return parentPO != null ? InterfaceWrapperHelper.create(parentPO, modelType) : null; } private int getParentID() { return parentPO != null ? parentPO.get_ID() : -1; } /** * Allows other modules to install customer code to be executed each time a record was copied. */ @Override public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener) { if (!recordCopiedListeners.contains(listener)) {
recordCopiedListeners.add(listener); } return this; } @Override public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener) { if (!childRecordCopiedListeners.contains(listener)) { childRecordCopiedListeners.add(listener); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java
1
请完成以下Java代码
private static RuntimeException mkEx(final String msg, final Throwable cause) { final RuntimeException ex = Check.newException(msg); if (cause != null) { ex.initCause(cause); } return ex; } private static final ConcurrentHashMap<Class<? extends RepoIdAware>, RepoIdAwareDescriptor> repoIdAwareDescriptors = new ConcurrentHashMap<>(); @Value @Builder @VisibleForTesting
static class RepoIdAwareDescriptor { @NonNull IntFunction<RepoIdAware> ofRepoIdFunction; @NonNull IntFunction<RepoIdAware> ofRepoIdOrNullFunction; } public static <T, R extends RepoIdAware> Comparator<T> comparingNullsLast(@NonNull final Function<T, R> keyMapper) { return Comparator.comparing(keyMapper, Comparator.nullsLast(Comparator.naturalOrder())); } public static <T extends RepoIdAware> boolean equals(@Nullable final T id1, @Nullable final T id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\RepoIdAwares.java
1
请完成以下Java代码
protected void prepare() { if (I_M_ShipmentSchedule.Table_Name.equals(getTableName()) && getRecord_ID() > 0) { shipmentSchedule = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_ShipmentSchedule.class, ITrx.TRXNAME_None); } } @Override protected String doIt() throws Exception { if (shipmentSchedule == null || shipmentSchedule.getM_ShipmentSchedule_ID() <= 0) { throw new FillMandatoryException(I_M_ShipmentSchedule.COLUMNNAME_M_ShipmentSchedule_ID); } final ShipmentScheduleQtyOnHandStorage storagesContainer = shipmentScheduleQtyOnHandStorageFactory.ofShipmentSchedule(shipmentSchedule); final ShipmentScheduleAvailableStock storageDetails = storagesContainer.getStockDetailsMatching(shipmentSchedule); addLog("@QtyOnHand@ (@Total@): " + storageDetails.getTotalQtyAvailable()); for (int storageIndex = 0; storageIndex < storageDetails.size(); storageIndex++) {
final ShipmentScheduleAvailableStockDetail storageDetail = storageDetails.getStorageDetail(storageIndex); addLog("------------------------------------------------------------"); addLog(storageDetail.toString()); } // // Also show the Storage Query { final StockDataQuery materialQuery = storagesContainer.toQuery(shipmentSchedule); addLog("------------------------------------------------------------"); addLog("Storage Query:"); addLog(String.valueOf(materialQuery)); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_ShowMatchingStorages.java
1
请完成以下Java代码
class AutoBytePool { /** * 获取缓冲区 * @return 缓冲区 */ byte[] getBuffer() { return _buf; } /** * 取字节 * @param id 字节下标 * @return 字节 */ byte get(int id) { return _buf[id]; } /** * 设置值 * @param id 下标 * @param value 值 */ void set(int id, byte value) { _buf[id] = value; } /** * 是否为空 * @return true表示为空 */ boolean empty() { return (_size == 0); } /** * 缓冲区大小 * @return 大小 */ int size() { return _size; } /** * 清空缓存 */ void clear() { resize(0); _buf = null; _size = 0; _capacity = 0; } /** * 在末尾加一个值 * @param value 值 */ void add(byte value) { if (_size == _capacity) { resizeBuf(_size + 1); } _buf[_size++] = value; } /** * 将最后一个值去掉 */ void deleteLast() { --_size; } /** * 重设大小 * @param size 大小 */ void resize(int size) { if (size > _capacity) { resizeBuf(size); } _size = size;
} /** * 重设大小,并且在末尾加一个值 * @param size 大小 * @param value 值 */ void resize(int size, byte value) { if (size > _capacity) { resizeBuf(size); } while (_size < size) { _buf[_size++] = value; } } /** * 增加容量 * @param size 容量 */ void reserve(int size) { if (size > _capacity) { resizeBuf(size); } } /** * 设置缓冲区大小 * @param size 大小 */ private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) { capacity = size; } else { capacity = 1; while (capacity < size) { capacity <<= 1; } } byte[] buf = new byte[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } /** * 缓冲区 */ private byte[] _buf; /** * 大小 */ private int _size; /** * 容量 */ private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoBytePool.java
1
请在Spring Boot框架中完成以下Java代码
public class BasicConfiguration { private boolean value; private String message; private int number; public boolean isValue() { return value; } public void setValue(boolean value) { this.value = value; } public String getMessage() {
return message; } public void setMessage(String message) { this.message = message; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } }
repos\spring-boot-examples-master\spring-boot-rest-services\src\main\java\com\in28minutes\springboot\configuration\BasicConfiguration.java
2
请完成以下Java代码
public static GLCategoryId ofRepoId(final int repoId) { if (repoId == NONE.getRepoId()) { return NONE; } return new GLCategoryId(repoId); } @NonNull public static GLCategoryId ofRepoIdOrNone(final int repoId) { return repoId > 0 ? new GLCategoryId(repoId) : NONE; } public static int toRepoId(@Nullable final GLCategoryId glCategoryId) { return glCategoryId != null ? glCategoryId.getRepoId() : -1; } @Nullable
public static GLCategoryId ofRepoIdOrNull(final int repoId) { if (repoId < 0) { return null; } return ofRepoIdOrNone(repoId); } private GLCategoryId(final int repoId) { this.repoId = Check.assumeGreaterOrEqualToZero(repoId, "GL_Category_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\GLCategoryId.java
1
请完成以下Java代码
public CalloutException setParameter(final @NonNull String name, final Object value) { super.setParameter(name, value); return this; } public CalloutException setCalloutInstance(final ICalloutInstance calloutInstance) { this.calloutInstance = calloutInstance; setParameter("calloutInstance", calloutInstance); return this; } public CalloutException setCalloutInstanceIfAbsent(final ICalloutInstance calloutInstance) { if (this.calloutInstance == null) { setCalloutInstance(calloutInstance); } return this; } public CalloutException setCalloutExecutor(final ICalloutExecutor calloutExecutor) { this.calloutExecutor = calloutExecutor; return this; } public CalloutException setCalloutExecutorIfAbsent(final ICalloutExecutor calloutExecutor) { if (this.calloutExecutor == null) { setCalloutExecutor(calloutExecutor); } return this;
} public CalloutException setField(final ICalloutField field) { this.field = field; setParameter("field", field); return this; } public CalloutException setFieldIfAbsent(final ICalloutField field) { if (this.field == null) { setField(field); } return this; } public ICalloutField getCalloutField() { return field; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\exceptions\CalloutException.java
1
请完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder ("X_C_RecurrentPayment[") .append(get_ID()).append("]"); return sb.toString(); } @Override public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setC_BPartner(org.compiere.model.I_C_BPartner C_BPartner) { set_ValueFromPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class, C_BPartner); } /** Set Business Partner . @param C_BPartner_ID Identifies a Business Partner */ @Override public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Business Partner . @return Identifies a Business Partner */ @Override public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class); } @Override public void setC_BPartner_Location(org.compiere.model.I_C_BPartner_Location C_BPartner_Location) { set_ValueFromPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class, C_BPartner_Location); }
/** Set Partner Location. @param C_BPartner_Location_ID Identifies the (ship to) address for this Business Partner */ @Override public void setC_BPartner_Location_ID (int C_BPartner_Location_ID) { if (C_BPartner_Location_ID < 1) set_Value (COLUMNNAME_C_BPartner_Location_ID, null); else set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID)); } /** Get Partner Location. @return Identifies the (ship to) address for this Business Partner */ @Override public int getC_BPartner_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Recurrent Payment. @param C_RecurrentPayment_ID Recurrent Payment */ @Override public void setC_RecurrentPayment_ID (int C_RecurrentPayment_ID) { if (C_RecurrentPayment_ID < 1) set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, null); else set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, Integer.valueOf(C_RecurrentPayment_ID)); } /** Get Recurrent Payment. @return Recurrent Payment */ @Override public int getC_RecurrentPayment_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPayment_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPayment.java
1
请完成以下Java代码
public class TransactionPrice3Choice { @XmlElement(name = "DealPric") protected Price2 dealPric; @XmlElement(name = "Prtry") protected List<ProprietaryPrice2> prtry; /** * Gets the value of the dealPric property. * * @return * possible object is * {@link Price2 } * */ public Price2 getDealPric() { return dealPric; } /** * Sets the value of the dealPric property. * * @param value * allowed object is * {@link Price2 } * */ public void setDealPric(Price2 value) { this.dealPric = value; } /** * Gets the value of the prtry property.
* * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryPrice2 } * * */ public List<ProprietaryPrice2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryPrice2>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionPrice3Choice.java
1
请完成以下Java代码
public int getAD_Client_ID() { return m_node.getClientId().getRepoId(); } // getAD_Client_ID /** * Is the node Editable * @return yes if the Client is the same */ public boolean isEditable() { return getAD_Client_ID() == Env.getAD_Client_ID(Env.getCtx()); } // isEditable public WFNodeId getNodeId() { return m_node.getId(); } public WorkflowNodeModel getModel() { return m_node; } // getModel /** * Set Location - also for Node. * @param x x * @param y y */ public void setLocation (int x, int y) { super.setLocation (x, y); m_node.setXPosition(x); m_node.setYPosition(y); } /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer("WFNode["); sb.append(getNodeId().getRepoId()).append("-").append(m_name) .append(",").append(getBounds()) .append("]"); return sb.toString(); } // toString /** * Get Font. * Italics if not editable * @return font */ public Font getFont () { Font base = new Font(null); if (!isEditable()) return base; // Return Bold Italic Font return new Font(base.getName(), Font.ITALIC | Font.BOLD, base.getSize()); } // getFont /************************************************************************** * Get Preferred Size * @return size */ public Dimension getPreferredSize () { return s_size;
} // getPreferredSize /** * Paint Component * @param g Graphics */ protected void paintComponent (Graphics g) { Graphics2D g2D = (Graphics2D)g; // center icon m_icon.paintIcon(this, g2D, s_size.width/2 - m_icon.getIconWidth()/2, 5); // Paint Text Color color = getForeground(); g2D.setPaint(color); Font font = getFont(); // AttributedString aString = new AttributedString(m_name); aString.addAttribute(TextAttribute.FONT, font); aString.addAttribute(TextAttribute.FOREGROUND, color); AttributedCharacterIterator iter = aString.getIterator(); // LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext()); float width = s_size.width - m_icon.getIconWidth() - 2; TextLayout layout = measurer.nextLayout(width); // center text float xPos = (float)(s_size.width/2 - layout.getBounds().getWidth()/2); float yPos = m_icon.getIconHeight() + 20; // layout.draw(g2D, xPos, yPos); width = s_size.width - 4; // 2 pt while (measurer.getPosition() < iter.getEndIndex()) { layout = measurer.nextLayout(width); yPos += layout.getAscent() + layout.getDescent() + layout.getLeading(); layout.draw(g2D, xPos, yPos); } } // paintComponent } // WFNode
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFNodeComponent.java
1
请完成以下Java代码
public byte[] getBytes() { return bytes; } public Object getPersistentState() { return new PersistentState(name, bytes); } // getters and setters //////////////////////////////////////////////////////// public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]";
} // Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) { this.name = name; this.bytes = bytes; } public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java
1
请完成以下Java代码
public void setExcerpt (String Excerpt) { set_ValueNoCheck (COLUMNNAME_Excerpt, Excerpt); } /** Get Excerpt. @return Surrounding text of the keyword */ public String getExcerpt () { return (String)get_Value(COLUMNNAME_Excerpt); } /** Set Keyword. @param Keyword Case insensitive keyword */ public void setKeyword (String Keyword) { set_ValueNoCheck (COLUMNNAME_Keyword, Keyword); } /** Get Keyword. @return Case insensitive keyword */ public String getKeyword () { return (String)get_Value(COLUMNNAME_Keyword); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getKeyword()); } /** Set Index. @param K_INDEX_ID Text Search Index */ public void setK_INDEX_ID (int K_INDEX_ID) { if (K_INDEX_ID < 1) set_ValueNoCheck (COLUMNNAME_K_INDEX_ID, null); else set_ValueNoCheck (COLUMNNAME_K_INDEX_ID, Integer.valueOf(K_INDEX_ID)); } /** Get Index. @return Text Search Index */ public int getK_INDEX_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_INDEX_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } public I_R_RequestType getR_RequestType() throws RuntimeException { return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) .getPO(getR_RequestType_ID(), get_TrxName()); } /** Set Request Type. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1) set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null); else set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Request Type. @return Type of request (e.g. Inquiry, Complaint, ..) */ public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Source Updated. @param SourceUpdated Date the source document was updated */ public void setSourceUpdated (Timestamp SourceUpdated) { set_Value (COLUMNNAME_SourceUpdated, SourceUpdated); } /** Get Source Updated. @return Date the source document was updated */ public Timestamp getSourceUpdated () { return (Timestamp)get_Value(COLUMNNAME_SourceUpdated); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Index.java
1
请在Spring Boot框架中完成以下Java代码
private ContractLine importContractLineNoSave(final Contract contract, final SyncContractLine syncContractLine, final Map<String, ContractLine> contractLines) { // If delete request, skip importing the contract line. // As a result, if there is a contract line for this sync-contract line, it will be deleted below. if (syncContractLine.isDeleted()) { return null; } ContractLine contractLine = contractLines.remove(syncContractLine.getUuid()); // // Product final SyncProduct syncProductNoDelete = assertNotDeleteRequest_WarnAndFix(syncContractLine.getProduct(), "importing contract lines"); Product product = contractLine == null ? null : contractLine.getProduct(); product = productsImportService.importProduct(syncProductNoDelete, product) .orElseThrow(() -> new RuntimeException("Deleted product cannot be used in " + syncContractLine)); // // Contract Line if (contractLine == null) { contractLine = new ContractLine(); contractLine.setUuid(syncContractLine.getUuid()); contractLine.setContract(contract); } contractLine.setDeleted(false);
contractLine.setProduct(product); logger.debug("Imported: {} -> {}", syncContractLine, contractLine); return contractLine; } public void deleteContract(final Contract contract) { contractsRepo.delete(contract); contractsRepo.flush(); logger.debug("Deleted: {}", contract); } private void deleteContractLine(final ContractLine contractLine) { contractLinesRepo.delete(contractLine); contractLinesRepo.flush(); logger.debug("Deleted: {}", contractLine); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncContractImportService.java
2
请完成以下Java代码
public void setEvaluationStartDate (final java.sql.Timestamp EvaluationStartDate) { set_Value (COLUMNNAME_EvaluationStartDate, EvaluationStartDate); } @Override public java.sql.Timestamp getEvaluationStartDate() { return get_ValueAsTimestamp(COLUMNNAME_EvaluationStartDate); } @Override public org.compiere.model.I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class); } @Override public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement); } @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_Value (COLUMNNAME_M_CostElement_ID, null); else set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID); } @Override public void setM_CostRevaluation_ID (final int M_CostRevaluation_ID) { if (M_CostRevaluation_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, M_CostRevaluation_ID); } @Override public int getM_CostRevaluation_ID() { return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID); } @Override public void setPosted (final boolean Posted) {
set_Value (COLUMNNAME_Posted, Posted); } @Override public boolean isPosted() { return get_ValueAsBoolean(COLUMNNAME_Posted); } @Override public void setPostingError_Issue_ID (final int PostingError_Issue_ID) { if (PostingError_Issue_ID < 1) set_Value (COLUMNNAME_PostingError_Issue_ID, null); else set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID); } @Override public int getPostingError_Issue_ID() { return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID); } @Override public void setProcessed (final boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluation.java
1
请在Spring Boot框架中完成以下Java代码
public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } public String getTenantId() { return tenantId; } @ApiParam("Only return jobs with the given tenant id") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } @ApiParam("Only return jobs with a tenantId like the given value") public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } @ApiParam("Only return jobs without a tenantId") public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public boolean isLocked() { return locked; } @ApiParam("Only return jobs that are locked") public void setLocked(boolean locked) { this.locked = locked;
} public boolean isUnlocked() { return unlocked; } @ApiParam("Only return jobs that are unlocked") public void setUnlocked(boolean unlocked) { this.unlocked = unlocked; } public boolean isWithoutScopeType() { return withoutScopeType; } @ApiParam("Only return jobs without a scope type") public void setWithoutScopeType(boolean withoutScopeType) { this.withoutScopeType = withoutScopeType; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobQueryRequest.java
2
请完成以下Java代码
public void clear() { pipeList.clear(); } @Override public boolean equals(Object o) { return pipeList.equals(o); } @Override public int hashCode() { return pipeList.hashCode(); } @Override public Pipe<List<IWord>, List<IWord>> get(int index) { return pipeList.get(index); } @Override public Pipe<List<IWord>, List<IWord>> set(int index, Pipe<List<IWord>, List<IWord>> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<List<IWord>, List<IWord>> element) { pipeList.add(index, element); } @Override public Pipe<List<IWord>, List<IWord>> remove(int index) { return pipeList.remove(index); } @Override public int indexOf(Object o)
{ return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<List<IWord>, List<IWord>>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<List<IWord>, List<IWord>>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\SegmentPipeline.java
1
请完成以下Java代码
public final class TablePermission implements Permission { public static final ImmutableSet<Access> ALL_ACCESSES = ImmutableSet.of(Access.READ, Access.WRITE, Access.REPORT, Access.EXPORT); public static final TablePermission NONE = builder() .resource(TableResource.ANY_TABLE) .accesses(ImmutableSet.of()) .build(); public static final TablePermission ALL = builder() .resource(TableResource.ANY_TABLE) .accesses(ALL_ACCESSES) .build(); @Getter private final TableResource resource; private final ImmutableSet<Access> accesses; @lombok.Builder(toBuilder = true) private TablePermission( @NonNull TableResource resource, final Set<Access> accesses) { this.resource = resource; this.accesses = accesses != null ? ImmutableSet.copyOf(accesses) : ImmutableSet.of(); } @Override public Permission mergeWith(final Permission permissionFrom)
{ final TablePermission tablePermissionFrom = PermissionInternalUtils.checkCompatibleAndCastToTarget(this, permissionFrom); return toBuilder() .accesses(ImmutableSet.<Access> builder() .addAll(this.accesses) .addAll(tablePermissionFrom.accesses) .build()) .build(); } @Override public boolean hasAccess(final Access access) { return accesses.contains(access); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TablePermission.java
1
请完成以下Java代码
public class User { private String login; private long id; private String url; private String company; private String blog; private String email; public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getCompany() { return company;
} public void setCompany(String company) { this.company = company; } public String getBlog() { return blog; } public void setBlog(String blog) { this.blog = blog; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}'; } }
repos\tutorials-master\libraries-http\src\main\java\com\baeldung\retrofitguide\User.java
1
请完成以下Java代码
public String completeIt(@NonNull final DocumentTableFields docFields) { final I_C_DunningDoc dunningDocRecord = extractDunningDoc(docFields); dunningDocRecord.setDocAction(IDocument.ACTION_ReActivate); if (dunningDocRecord.isProcessed()) { throw new DunningException("@Processed@=@Y@"); } final IDunningDAO dunningDao = Services.get(IDunningDAO.class); final List<I_C_DunningDoc_Line> lines = dunningDao.retrieveDunningDocLines(dunningDocRecord); final IDunningBL dunningBL = Services.get(IDunningBL.class); for (final I_C_DunningDoc_Line line : lines) { for (final I_C_DunningDoc_Line_Source source : dunningDao.retrieveDunningDocLineSources(line)) { dunningBL.processSourceAndItsCandidates(dunningDocRecord, source); } line.setProcessed(true); InterfaceWrapperHelper.save(line); } // // Delivery stop (https://github.com/metasfresh/metasfresh/issues/2499) dunningBL.makeDeliveryStopIfNeeded(dunningDocRecord); dunningDocRecord.setProcessed(true);
return IDocument.STATUS_Completed; } @Override public void reactivateIt(@NonNull final DocumentTableFields docFields) { final I_C_DunningDoc dunningDocRecord = extractDunningDoc(docFields); dunningDocRecord.setProcessed(false); dunningDocRecord.setDocAction(IDocument.ACTION_Complete); } private static I_C_DunningDoc extractDunningDoc(@NonNull final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_C_DunningDoc.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\DunningDocDocumentHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfiguration { private static final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(10); } @Bean // This could be your database lookup. There are some complete implementations in spring-security-web. UserDetailsService userDetailsService(final PasswordEncoder passwordEncoder) { return username -> { log.debug("Searching user: {}", username); switch (username) { case "guest": { return new User(username, passwordEncoder.encode(username + "Password"), Collections.emptyList()); } case "user": { final List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("ROLE_GREET")); return new User(username, passwordEncoder.encode(username + "Password"), authorities); } default: { throw new UsernameNotFoundException("Could not find user!"); } } }; } @Bean
// One of your authentication providers. // They ensure that the credentials are valid and populate the user's authorities. DaoAuthenticationProvider daoAuthenticationProvider( final UserDetailsService userDetailsService, final PasswordEncoder passwordEncoder) { final DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService); provider.setPasswordEncoder(passwordEncoder); return provider; } @Bean // Add the authentication providers to the manager. AuthenticationManager authenticationManager(final DaoAuthenticationProvider daoAuthenticationProvider) { final List<AuthenticationProvider> providers = new ArrayList<>(); providers.add(daoAuthenticationProvider); return new ProviderManager(providers); } @Bean // Configure which authentication types you support. GrpcAuthenticationReader authenticationReader() { return new BasicGrpcAuthenticationReader(); // final List<GrpcAuthenticationReader> readers = new ArrayList<>(); // readers.add(new BasicGrpcAuthenticationReader()); // readers.add(new SSLContextGrpcAuthenticationReader()); // return new CompositeGrpcAuthenticationReader(readers); } }
repos\grpc-spring-master\examples\security-grpc-server\src\main\java\net\devh\boot\grpc\examples\security\server\SecurityConfiguration.java
2
请完成以下Java代码
private boolean isOrderFullyDelivered() { if (invoiceCandidateRecord.getC_Order_ID() <= 0) { logger.debug("C_Order_ID={}; -> return false"); return false; } final IOrderDAO orderDAO = Services.get(IOrderDAO.class); for (final I_C_OrderLine oLine : orderDAO.retrieveOrderLines(invoiceCandidateRecord.getC_Order())) { try (final MDCCloseable oLineMDC = TableRecordMDC.putTableRecordReference(oLine)) { final BigDecimal toInvoice = oLine.getQtyOrdered().subtract(oLine.getQtyInvoiced()); if (toInvoice.signum() == 0 && oLine.getM_Product_ID() > 0) { logger.debug("C_OrderLine has QtyOrdered={}, QtyInvoiced={}, M_Product_ID={} and remaining qty to invoice={} -> consider fully delivered", oLine.getQtyOrdered(), oLine.getQtyInvoiced(), oLine.getM_Product_ID(), toInvoice); continue; } final ProductId olProductId = ProductId.ofRepoIdOrNull(oLine.getM_Product_ID()); // in the DB it's mandatory, but in many unit tests it's not relevant and not set if (!productBL.isStocked(olProductId)) {
logger.debug("C_OrderLine has M_Product_ID={} which is not a (physical) item -> consider fully delivered", oLine.getM_Product_ID()); } final boolean fullyDelivered = oLine.getQtyOrdered().compareTo(oLine.getQtyDelivered()) == 0; if (!fullyDelivered) { logger.debug("C_OrderLine has QtyOrdered={} is <= QtyDelivered={} -> return false", oLine.getQtyOrdered(), oLine.getQtyDelivered()); return false; } } } logger.debug("C_Order_ID={}; has all lines fully delivered -> return true", invoiceCandidateRecord.getC_Order_ID()); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\OrderedDataLoader.java
1
请完成以下Java代码
public I_M_Product getRelatedProduct() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getRelatedProduct_ID(), get_TrxName()); } /** Set Related Product. @param RelatedProduct_ID Related Product */ public void setRelatedProduct_ID (int RelatedProduct_ID) { if (RelatedProduct_ID < 1) set_ValueNoCheck (COLUMNNAME_RelatedProduct_ID, null); else set_ValueNoCheck (COLUMNNAME_RelatedProduct_ID, Integer.valueOf(RelatedProduct_ID)); } /** Get Related Product. @return Related Product */ public int getRelatedProduct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_RelatedProduct_ID); if (ii == null) return 0; return ii.intValue(); } /** RelatedProductType AD_Reference_ID=313 */ public static final int RELATEDPRODUCTTYPE_AD_Reference_ID=313; /** Web Promotion = P */ public static final String RELATEDPRODUCTTYPE_WebPromotion = "P"; /** Alternative = A */ public static final String RELATEDPRODUCTTYPE_Alternative = "A";
/** Supplemental = S */ public static final String RELATEDPRODUCTTYPE_Supplemental = "S"; /** Set Related Product Type. @param RelatedProductType Related Product Type */ public void setRelatedProductType (String RelatedProductType) { set_ValueNoCheck (COLUMNNAME_RelatedProductType, RelatedProductType); } /** Get Related Product Type. @return Related Product Type */ public String getRelatedProductType () { return (String)get_Value(COLUMNNAME_RelatedProductType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RelatedProduct.java
1
请完成以下Java代码
public void setM_Product_Category_ID (int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, Integer.valueOf(M_Product_Category_ID)); } /** Get Produkt Kategorie. @return Kategorie eines Produktes */ @Override public int getM_Product_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3 Product_Category. @param MSV3_Server_Product_Category_ID MSV3 Product_Category */ @Override public void setMSV3_Server_Product_Category_ID (int MSV3_Server_Product_Category_ID)
{ if (MSV3_Server_Product_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_Server_Product_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_Server_Product_Category_ID, Integer.valueOf(MSV3_Server_Product_Category_ID)); } /** Get MSV3 Product_Category. @return MSV3 Product_Category */ @Override public int getMSV3_Server_Product_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Server_Product_Category_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Server_Product_Category.java
1
请完成以下Java代码
protected void removeLastFieldSeparator(final StringBuffer buffer) { final int len = buffer.length(); final int sepLen = getFieldSeparator().length() + getDepth(); if (len > 0 && sepLen > 0 && len >= sepLen) { buffer.setLength(len - sepLen); } } private boolean noReflectionNeeded(final Object value) { try { return value != null && (value.getClass().getName().startsWith("java.lang.") || value.getClass().getMethod("toString").getDeclaringClass() != Object.class); } catch (final NoSuchMethodException e) { throw new IllegalStateException(e); } } @Override protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) { if (getDepth() >= maxDepth || noReflectionNeeded(value)) { appendTabified(buffer, String.valueOf(value)); } else { new ExtendedReflectionToStringBuilder(value, this, buffer, null, false, false).toString(); } } // another helpful method, for collections: @Override protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> col) { appendSummarySize(buffer, fieldName, col.size()); final ExtendedReflectionToStringBuilder builder = new ExtendedReflectionToStringBuilder( col.toArray(), // object
this, // style, buffer, //buffer, null, //reflectUpToClass, true, // outputTransients, true // outputStatics ); builder.toString(); } @Override protected String getShortClassName(final Class<?> cls) { if (cls != null && cls.isArray() && getDepth() > 0) { return ""; } return super.getShortClassName(cls); } static class MutableInteger { private int value; MutableInteger(final int value) { this.value = value; } public final int get() { return value; } public final void increment() { ++value; } public final void decrement() { --value; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\RecursiveIndentedMultilineToStringStyle.java
1
请完成以下Java代码
public static String parseContext(Evaluatee source, String expression) { if (expression == null || expression.length() == 0) return null; // int pos = 0; String finalExpression = expression; while (pos < expression.length()) { int first = expression.indexOf('@', pos); if (first == -1) return expression; int second = expression.indexOf('@', first+1); if (second == -1) { s_log.error("No second @ in Logic: {}", expression); return null; } String variable = expression.substring(first+1, second); String eval = getValue(source, variable); s_log.trace("{}={}", variable, eval); if (Check.isEmpty(eval, true)) { eval = Env.getContext(Env.getCtx(), variable); } finalExpression = finalExpression.replaceFirst("@"+variable+"@", eval); // pos = second + 1; } return finalExpression; }
public static boolean hasVariable(Evaluatee source, String variableName) { if (source instanceof Evaluatee2) { final Evaluatee2 source2 = (Evaluatee2)source; return source2.has_Variable(variableName); } else { return !Check.isEmpty(source.get_ValueAsString(variableName)); } } public static void parseDepends (final List<String> list, final IExpression<?> expr) { if (expr == null) { return; } list.addAll(expr.getParameterNames()); } } // Evaluator
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Evaluator.java
1
请完成以下Java代码
public void setDefaultMaxInactiveInterval(Duration defaultMaxInactiveInterval) { Assert.notNull(defaultMaxInactiveInterval, "defaultMaxInactiveInterval must not be null"); this.defaultMaxInactiveInterval = defaultMaxInactiveInterval; } @Override public Mono<Void> save(MapSession session) { return Mono.fromRunnable(() -> { if (!session.getId().equals(session.getOriginalId())) { this.sessions.remove(session.getOriginalId()); } this.sessions.put(session.getId(), new MapSession(session)); }); } @Override public Mono<MapSession> findById(String id) { // @formatter:off return Mono.defer(() -> Mono.justOrEmpty(this.sessions.get(id)) .filter((session) -> !session.isExpired()) .map(MapSession::new) .doOnNext((session) -> session.setSessionIdGenerator(this.sessionIdGenerator)) .switchIfEmpty(deleteById(id).then(Mono.empty()))); // @formatter:on } @Override public Mono<Void> deleteById(String id) { return Mono.fromRunnable(() -> this.sessions.remove(id)); } @Override public Mono<MapSession> createSession() { // @formatter:off
return Mono.fromSupplier(() -> this.sessionIdGenerator.generate()) .subscribeOn(Schedulers.boundedElastic()) .publishOn(Schedulers.parallel()) .map((sessionId) -> { MapSession result = new MapSession(sessionId); result.setMaxInactiveInterval(this.defaultMaxInactiveInterval); result.setSessionIdGenerator(this.sessionIdGenerator); return result; }); // @formatter:on } /** * Sets the {@link SessionIdGenerator} to use. * @param sessionIdGenerator the non-null {@link SessionIdGenerator} to use * @since 3.2 */ public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { Assert.notNull(sessionIdGenerator, "sessionIdGenerator cannot be null"); this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\ReactiveMapSessionRepository.java
1
请完成以下Java代码
public static QtyTU ofString(@NonNull final String stringValue) { return ofInt(NumberUtils.asInt(stringValue)); } @JsonCreator @Nullable public static QtyTU ofNullableString(@Nullable final String stringValue) { final String stringValueNorm = StringUtils.trimBlankToNull(stringValue); return stringValueNorm != null ? ofString(stringValueNorm) : null; } public static final QtyTU ZERO; public static final QtyTU ONE; public static final QtyTU TWO; public static final QtyTU THREE; public static final QtyTU FOUR; private static final QtyTU[] cache = new QtyTU[] { ZERO = new QtyTU(0), ONE = new QtyTU(1), TWO = new QtyTU(2), THREE = new QtyTU(3), FOUR = new QtyTU(4), new QtyTU(5), new QtyTU(6), new QtyTU(7), new QtyTU(8), new QtyTU(9), new QtyTU(10), }; final int intValue; private QtyTU(final int intValue) { Check.assumeGreaterOrEqualToZero(intValue, "QtyTU"); this.intValue = intValue; } @Override @Deprecated public String toString() { return String.valueOf(intValue); } public static boolean equals(@Nullable final QtyTU qtyTU1, @Nullable final QtyTU qtyTU2) {return Objects.equals(qtyTU1, qtyTU2);} @JsonValue public int toInt() { return intValue; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(intValue); } @Override public int compareTo(@NonNull final QtyTU other) { return this.intValue - other.intValue; } public int compareTo(@NonNull final BigDecimal other) { return this.intValue - other.intValueExact(); } public boolean isGreaterThan(@NonNull final QtyTU other) {return compareTo(other) > 0;} public boolean isZero() {return intValue == 0;} public boolean isPositive() {return intValue > 0;} public boolean isOne() {return intValue == 1;} public QtyTU add(@NonNull final QtyTU toAdd) { if (this.intValue == 0) { return toAdd; }
else if (toAdd.intValue == 0) { return this; } else { return ofInt(this.intValue + toAdd.intValue); } } public QtyTU subtractOrZero(@NonNull final QtyTU toSubtract) { if (toSubtract.intValue == 0) { return this; } else { return ofInt(Math.max(this.intValue - toSubtract.intValue, 0)); } } public QtyTU min(@NonNull final QtyTU other) { return this.intValue <= other.intValue ? this : other; } public Quantity computeQtyCUsPerTUUsingTotalQty(@NonNull final Quantity qtyCUsTotal) { if (isZero()) { throw new AdempiereException("Cannot determine Qty CUs/TU when QtyTU is zero of total CUs " + qtyCUsTotal); } else if (isOne()) { return qtyCUsTotal; } else { return qtyCUsTotal.divide(toInt()); } } public Quantity computeTotalQtyCUsUsingQtyCUsPerTU(@NonNull final Quantity qtyCUsPerTU) { return qtyCUsPerTU.multiply(toInt()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\QtyTU.java
1