instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public at.erpel.schemas._1p0.documents.extensions.edifact.DeliveryDetailsExtensionType getDeliveryDetailsExtension() { return deliveryDetailsExtension; } /** * Sets the value of the deliveryDetailsExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.DeliveryDetailsExtensionType } * */ public void setDeliveryDetailsExtension(at.erpel.schemas._1p0.documents.extensions.edifact.DeliveryDetailsExtensionType value) { this.deliveryDetailsExtension = value; } /** * Gets the value of the erpelDeliveryDetailsExtension property. * * @return * possible object is * {@link CustomType }
* */ public CustomType getErpelDeliveryDetailsExtension() { return erpelDeliveryDetailsExtension; } /** * Sets the value of the erpelDeliveryDetailsExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelDeliveryDetailsExtension(CustomType value) { this.erpelDeliveryDetailsExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\DeliveryDetailsExtensionType.java
2
请完成以下Java代码
private static String normalizeSingleArgumentBeforeFormat_Iterable( @NonNull final Iterable<Object> iterable, final String adLanguage) { final StringBuilder result = new StringBuilder(); for (final Object item : iterable) { String itemNormStr; try { final Object itemNormObj = normalizeSingleArgumentBeforeFormat(item, adLanguage); itemNormStr = itemNormObj != null ? itemNormObj.toString() : "-"; } catch (Exception ex) {
s_log.warn("Failed normalizing argument `{}`. Using toString().", item, ex); itemNormStr = item.toString(); } if (!(result.length() == 0)) { result.append(", "); } result.append(itemNormStr); } return result.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\MessageFormatter.java
1
请完成以下Java代码
public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public void afterPropertiesSet() { this.registered = register(); } @Override public void destroy() throws Exception { unregister(this.registered); } private Collection<ObjectName> register() { return this.endpoints.stream().filter(this::hasOperations).map(this::register).toList(); } private boolean hasOperations(ExposableJmxEndpoint endpoint) { return !CollectionUtils.isEmpty(endpoint.getOperations()); } private ObjectName register(ExposableJmxEndpoint endpoint) { Assert.notNull(endpoint, "'endpoint' must not be null"); try { ObjectName name = this.objectNameFactory.getObjectName(endpoint); EndpointMBean mbean = new EndpointMBean(this.responseMapper, this.classLoader, endpoint); this.mBeanServer.registerMBean(mbean, name); return name; } catch (MalformedObjectNameException ex) { throw new IllegalStateException("Invalid ObjectName for " + getEndpointDescription(endpoint), ex); } catch (Exception ex) { throw new MBeanExportException("Failed to register MBean for " + getEndpointDescription(endpoint), ex); } }
private void unregister(Collection<ObjectName> objectNames) { objectNames.forEach(this::unregister); } private void unregister(ObjectName objectName) { try { if (logger.isDebugEnabled()) { logger.debug("Unregister endpoint with ObjectName '" + objectName + "' from the JMX domain"); } this.mBeanServer.unregisterMBean(objectName); } catch (InstanceNotFoundException ex) { // Ignore and continue } catch (MBeanRegistrationException ex) { throw new JmxException("Failed to unregister MBean with ObjectName '" + objectName + "'", ex); } } private String getEndpointDescription(ExposableJmxEndpoint endpoint) { return "endpoint '" + endpoint.getEndpointId() + "'"; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\JmxEndpointExporter.java
1
请完成以下Java代码
public Object remove(Object key) { if (UNSTORED_KEYS.contains(key)) { return null; } return wrappedBindings.remove(key); } public void clear() { wrappedBindings.clear(); } public boolean containsValue(Object value) { return calculateBindingMap().containsValue(value); } public boolean isEmpty() { return calculateBindingMap().isEmpty(); }
protected Map<String, Object> calculateBindingMap() { Map<String, Object> bindingMap = new HashMap<String, Object>(); for (Resolver resolver : scriptResolvers) { for (String key : resolver.keySet()) { bindingMap.put(key, resolver.get(key)); } } Set<java.util.Map.Entry<String, Object>> wrappedBindingsEntries = wrappedBindings.entrySet(); for (Entry<String, Object> entry : wrappedBindingsEntries) { bindingMap.put(entry.getKey(), entry.getValue()); } return bindingMap; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\ScriptBindings.java
1
请完成以下Java代码
public class InvalidIdentifierException extends AdempiereException { public InvalidIdentifierException(final IdentifierString invalidIdentifier) { this(invalidIdentifier != null ? invalidIdentifier.toJson() : null, null, null); } public InvalidIdentifierException(@Nullable final String invalidIdentifierString) { this(invalidIdentifierString, null, null) ; } public InvalidIdentifierException( @Nullable final String invalidIdentifierString, @Nullable final Object objectWithInvalidIdentifier)
{ this(invalidIdentifierString, objectWithInvalidIdentifier, null); } public InvalidIdentifierException( @Nullable final String invalidIdentifierString, @Nullable final Object objectWithInvalidIdentifier, @Nullable final Throwable cause) { super("Unable to interpret identifierString=" + invalidIdentifierString, cause); if (objectWithInvalidIdentifier != null) { appendParametersToMessage(); setParameter("objectWithInvalidIdentifier", objectWithInvalidIdentifier); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\exception\InvalidIdentifierException.java
1
请在Spring Boot框架中完成以下Java代码
public class C_Order { private final OrderAvailableToPromiseTool orderAvailableToPromiseTool; public C_Order( @NonNull final AvailableToPromiseRepository stockRepository, @NonNull final ModelProductDescriptorExtractor productDescriptorFactory) { orderAvailableToPromiseTool = OrderAvailableToPromiseTool.builder() .stockRepository(stockRepository) .productDescriptorFactory(productDescriptorFactory) .build(); } @DocValidate(timings = ModelValidator.TIMING_AFTER_REACTIVATE) public void updateQtyAvailableToPromise(final I_C_Order orderRecord) { if (!orderRecord.isSOTrx()) { return; // as of now, ATP values are only of interest for the sales side } orderAvailableToPromiseTool.updateOrderLineRecords(orderRecord); } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void resetQtyAvailableToPromise(final I_C_Order orderRecord) { if (!orderRecord.isSOTrx()) { return; // as of now, ATP values are only of interest for the sales side } orderAvailableToPromiseTool.resetQtyAvailableToPromise(orderRecord); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = { I_C_Order.COLUMNNAME_PreparationDate }) public void updateQtyAvailableToPromiseWhenPreparationDateIsChanged(final I_C_Order orderRecord) { if (!orderRecord.isSOTrx()) { return; // as of now, ATP values are only of interest for the sales side } orderAvailableToPromiseTool.updateOrderLineRecords(orderRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\interceptor\C_Order.java
2
请完成以下Java代码
public void updateDocActions(final DocActionOptionsContext optionsCtx) { final IDocActionOptionsCustomizer customizers = getDocActionOptionsCustomizers(optionsCtx.getTableName()); customizers.customizeValidActions(optionsCtx); // // Apply role access final DocTypeId docTypeId = optionsCtx.getDocTypeId(); if (docTypeId != null) { final UserRolePermissionsKey permissionsKey = optionsCtx.getUserRolePermissionsKey(); final IUserRolePermissions role = Services.get(IUserRolePermissionsDAO.class).getUserRolePermissions(permissionsKey); role.applyActionAccess(optionsCtx); } } private IDocActionOptionsCustomizer getDocActionOptionsCustomizers(@Nullable final String contextTableName) { final ArrayList<IDocActionOptionsCustomizer> customizers = new ArrayList<>(2); customizers.add(DefaultDocActionOptionsCustomizer.instance); if (contextTableName != null)
{ final IDocActionOptionsCustomizer tableSpecificCustomizer = _docActionOptionsCustomizerByTableName.get().get(contextTableName); if (tableSpecificCustomizer != null) { customizers.add(tableSpecificCustomizer); } } return CompositeDocActionOptionsCustomizer.ofList(customizers); } private static ImmutableMap<String, IDocActionOptionsCustomizer> retrieveDocActionOptionsCustomizer() { final ImmutableMap<String, IDocActionOptionsCustomizer> customizers = SpringContextHolder.instance.getBeansOfType(IDocActionOptionsCustomizer.class) .stream() .collect(ImmutableMap.toImmutableMap(IDocActionOptionsCustomizer::getAppliesToTableName, Function.identity())); logger.info("Loaded {}(s): {}", IDocActionOptionsCustomizer.class, customizers); return customizers; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\DocActionOptionsBL.java
1
请完成以下Java代码
public void setCM_Template_ID (int CM_Template_ID) { if (CM_Template_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Template_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Template_ID, Integer.valueOf(CM_Template_ID)); } /** Get Template. @return Template defines how content is displayed */ public int getCM_Template_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Template_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Template Table. @param CM_TemplateTable_ID CM Template Table Link */ public void setCM_TemplateTable_ID (int CM_TemplateTable_ID) { if (CM_TemplateTable_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_TemplateTable_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_TemplateTable_ID, Integer.valueOf(CM_TemplateTable_ID)); } /** Get Template Table. @return CM Template Table Link */ public int getCM_TemplateTable_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_TemplateTable_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 Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); }
/** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Other SQL Clause. @param OtherClause Other SQL Clause */ public void setOtherClause (String OtherClause) { set_Value (COLUMNNAME_OtherClause, OtherClause); } /** Get Other SQL Clause. @return Other SQL Clause */ public String getOtherClause () { return (String)get_Value(COLUMNNAME_OtherClause); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_TemplateTable.java
1
请在Spring Boot框架中完成以下Java代码
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("Load user by username " + username); final UserDetails user = availableUsers.get(username); if (user == null) { throw new UsernameNotFoundException(username); } return user; } /** * Create demo users (note: obviously in a real system these would be persisted * in database or retrieved from another system). */
private void populateDemoUsers() { logger.info("Populate demo users"); availableUsers.put("user", createUser("user", "password", Arrays.asList(SecurityRole.ROLE_USER))); availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); } private User createUser(final String username, final String password, final List<SecurityRole> roles) { logger.info("Create user " + username); final List<GrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.toString())).collect(Collectors.toList()); return new User(username, password, true, true, true, true, authorities); } }
repos\tutorials-master\spring-security-modules\spring-security-web-persistent-login\src\main\java\com\baeldung\service\MyUserDetailsService.java
2
请完成以下Java代码
public class LUIdsAndTopLevelTUIdsCollector { private final HashSet<HuId> allTopLevelHUIds = new HashSet<>(); private final HashSet<HuId> luIds = new HashSet<>(); private final HashSet<HuId> topLevelTUIds = new HashSet<>(); public void addLUId(@NonNull final HuId luId) { allTopLevelHUIds.add(luId); luIds.add(luId); } public void addTopLevelTUId(@NonNull final HuId tuId) { allTopLevelHUIds.add(tuId); topLevelTUIds.add(tuId); } public boolean isEmpty() {
return allTopLevelHUIds.isEmpty(); } public ImmutableSet<HuId> getAllTopLevelHUIds() { return ImmutableSet.copyOf(allTopLevelHUIds); } public ImmutableSet<HuId> getLUIds() { return ImmutableSet.copyOf(luIds); } public ImmutableSet<HuId> getTopLevelTUIds() { return ImmutableSet.copyOf(topLevelTUIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\LUIdsAndTopLevelTUIdsCollector.java
1
请完成以下Java代码
public int getSupervisor_ID() { return get_ValueAsInt(COLUMNNAME_Supervisor_ID); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { throw new IllegalArgumentException ("Timestamp is virtual column"); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount) { set_Value (COLUMNNAME_UnlockAccount, UnlockAccount); } @Override public java.lang.String getUnlockAccount() { return get_ValueAsString(COLUMNNAME_UnlockAccount); } @Override public void setUserPIN (final @Nullable java.lang.String UserPIN) {
set_Value (COLUMNNAME_UserPIN, UserPIN); } @Override public java.lang.String getUserPIN() { return get_ValueAsString(COLUMNNAME_UserPIN); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Long getTimestamp() { return this.timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public Player getCreator() { return this.creator; }
public void setCreator(Player creator) { this.creator = creator; addPlayer(creator); } public void addPlayer(Player player) { this.players.add(player); } public List<Player> getPlayers() { return Collections.unmodifiableList(this.players); } public GameSettings getSettings() { return this.settings; } public void setSettings(GameSettings settings) { this.settings = settings; } }
repos\tutorials-master\libraries-data\src\main\java\com\baeldung\modelmapper\domain\Game.java
1
请完成以下Java代码
default HUPackingAwareCopy prepareCopyFrom(final IHUPackingAware from) { return HUPackingAwareCopy.from(from); } /** * Copies all fields from one {@link IHUPackingAware} to another. */ default void copy(final IHUPackingAware to, final IHUPackingAware from) { prepareCopyFrom(from).copyTo(to); } /** * Note: doesn't save. */ void setQtyTU(IHUPackingAware record); Capacity calculateCapacity(IHUPackingAware record); /** * Sets Qty CU from packing instructions and {@code qtyPacks} * * @param qtyPacks a.k.ak Qty TUs */ void setQtyCUFromQtyTU(IHUPackingAware record, int qtyPacks);
/** * This method verifies if the qtyCU given as parameter fits the qtyPacks. If it does, the record will not be updated. * In case the QtyCU is too big or too small to fit in the QtyPacks, it will be changed to the maximum capacity required by the QtyPacks and the M_HU_PI_Item_Product of the record */ void updateQtyIfNeeded(IHUPackingAware record, int qtyPacks, Quantity qtyCU); void computeAndSetQtysForNewHuPackingAware(final PlainHUPackingAware huPackingAware, final BigDecimal quickInputQty); boolean isInfiniteCapacityTU(IHUPackingAware huPackingAware); void setQtyTUFromQtyLU(IHUPackingAware packingAware); void setQtyLUFromQtyTU(IHUPackingAware record); void validateLUQty(@Nullable BigDecimal luQty); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\IHUPackingAwareBL.java
1
请在Spring Boot框架中完成以下Java代码
public void setDay(int value) { this.day = value; } /** * Gets the value of the fromTime1 property. * * @return * possible object is * {@link Integer } * */ public Integer getFromTime1() { return fromTime1; } /** * Sets the value of the fromTime1 property. * * @param value * allowed object is * {@link Integer } * */ public void setFromTime1(Integer value) { this.fromTime1 = value; } /** * Gets the value of the toTime1 property. * * @return * possible object is * {@link Integer } * */ public Integer getToTime1() { return toTime1; } /** * Sets the value of the toTime1 property. * * @param value * allowed object is * {@link Integer } * */ public void setToTime1(Integer value) { this.toTime1 = value; } /** * Gets the value of the fromTime2 property. * * @return * possible object is * {@link Integer } * */ public Integer getFromTime2() { return fromTime2; } /** * Sets the value of the fromTime2 property. * * @param value * allowed object is * {@link Integer } * */ public void setFromTime2(Integer value) { this.fromTime2 = value; } /** * Gets the value of the toTime2 property. * * @return * possible object is * {@link Integer } * */ public Integer getToTime2() { return toTime2; } /** * Sets the value of the toTime2 property. * * @param value * allowed object is * {@link Integer }
* */ public void setToTime2(Integer value) { this.toTime2 = value; } /** * Gets the value of the extraPickup property. * * @return * possible object is * {@link Boolean } * */ public Boolean isExtraPickup() { return extraPickup; } /** * Sets the value of the extraPickup property. * * @param value * allowed object is * {@link Boolean } * */ public void setExtraPickup(Boolean value) { this.extraPickup = value; } /** * Gets the value of the collectionRequestAddress property. * * @return * possible object is * {@link Address } * */ public Address getCollectionRequestAddress() { return collectionRequestAddress; } /** * Sets the value of the collectionRequestAddress property. * * @param value * allowed object is * {@link Address } * */ public void setCollectionRequestAddress(Address value) { this.collectionRequestAddress = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Pickup.java
2
请完成以下Java代码
public String getActionName() { return ACTION_Name; } public boolean isEnabled() { final Properties ctx = Env.getCtx(); final UserId loggedUserId = Env.getLoggedUserId(ctx); return userId2enabled.getOrLoad(loggedUserId, this::retrieveEnabledNoFail); } private boolean retrieveEnabledNoFail(final UserId loggedUserId) { try { return retrieveEnabled(loggedUserId); } catch (Exception ex) { logger.error(ex.getLocalizedMessage(), ex); return false; } } private boolean retrieveEnabled(final UserId loggedUserId) { final AdWindowId windowId = AdWindowId.ofRepoIdOrNull(MTable.get(Env.getCtx(), I_AD_Field.Table_Name).getAD_Window_ID()); if (windowId == null) { return false; } final ClientId clientId = Env.getClientId(); final LocalDate date = Env.getLocalDate(); // // Makes sure the logged in user has at least one role assigned which has read-write access to our window return Services.get(IUserRolePermissionsDAO.class) .matchUserRolesPermissionsForUser( clientId, loggedUserId, date, rolePermissions -> rolePermissions.checkWindowPermission(windowId).hasWriteAccess());
} public void save(final GridTab gridTab) { Services.get(ITrxManager.class).runInNewTrx(() -> save0(gridTab)); } private void save0(final GridTab gridTab) { Check.assumeNotNull(gridTab, "gridTab not null"); for (final GridField gridField : gridTab.getFields()) { save(gridField); } } private void save(final GridField gridField) { final GridFieldVO gridFieldVO = gridField.getVO(); final AdFieldId adFieldId = gridFieldVO.getAD_Field_ID(); if (adFieldId == null) { return; } final I_AD_Field adField = InterfaceWrapperHelper.load(adFieldId, I_AD_Field.class); if (adField == null) { return; } adField.setIsDisplayedGrid(gridFieldVO.isDisplayedGrid()); adField.setSeqNoGrid(gridFieldVO.getSeqNoGrid()); adField.setColumnDisplayLength(gridFieldVO.getLayoutConstraints().getColumnDisplayLength()); InterfaceWrapperHelper.save(adField); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveStateModel.java
1
请在Spring Boot框架中完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord;
} public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + '\'' + ", passWord='" + passWord + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 4-7 课:Spring Boot 简单集成 MongoDB\spring-boot-mongodb-repository\src\main\java\com\neo\model\User.java
2
请完成以下Java代码
default LookupDataSourceContext.Builder newContextForFetchingByIds(@NonNull final Collection<?> ids) { return newContextForFetchingById(null) .putFilterById(IdsToFilter.ofMultipleValues(ids)); } default LookupValuesList retrieveLookupValueByIdsInOrder(@NonNull final LookupDataSourceContext evalCtx) { return evalCtx.streamSingleIdContexts() .map(this::retrieveLookupValueById) .filter(Objects::nonNull) .collect(LookupValuesList.collect()); } LookupDataSourceContext.Builder newContextForFetchingList(); LookupValuesPage retrieveEntities(LookupDataSourceContext evalCtx); // // Caching //@formatter:off /** @return true if this fetcher already has caching embedded so on upper levels, caching is not needed */
boolean isCached(); /** @return cache prefix; relevant only if {@link #isCached()} returns <code>false</code> */ @Nullable String getCachePrefix(); default List<CCacheStats> getCacheStats() { return ImmutableList.of(); } //@formatter:on /** * @return tableName if available */ Optional<String> getLookupTableName(); /** * @return optional WindowId to be used when zooming into */ Optional<WindowId> getZoomIntoWindowId(); void cacheInvalidate(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceFetcher.java
1
请在Spring Boot框架中完成以下Java代码
public R<IPage<Notice>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> notice, Query query) { IPage<Notice> pages = noticeService.page(Condition.getPage(query), Condition.getQueryWrapper(notice, Notice.class)); return R.data(pages); } /** * 新增 */ @PostMapping("/save") @ApiOperationSupport(order = 3) @Operation(summary = "新增", description = "传入notice") public R save(@RequestBody Notice notice) { return R.status(noticeService.save(notice)); } /** * 修改 */ @PostMapping("/update") @ApiOperationSupport(order = 4) @Operation(summary = "修改", description = "传入notice") public R update(@RequestBody Notice notice) { return R.status(noticeService.updateById(notice)); } /** * 新增或修改 */ @PostMapping("/submit")
@ApiOperationSupport(order = 5) @Operation(summary = "新增或修改", description = "传入notice") public R submit(@RequestBody Notice notice) { return R.status(noticeService.saveOrUpdate(notice)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 6) @Operation(summary = "逻辑删除", description = "传入notice") public R remove(@Parameter(description = "主键集合") @RequestParam String ids) { boolean temp = noticeService.deleteLogic(Func.toLongList(ids)); return R.status(temp); } }
repos\SpringBlade-master\blade-service\blade-demo\src\main\java\com\example\demo\controller\NoticeController.java
2
请完成以下Java代码
public int size() { return delegate.size(); } }; } private class DecoratingEntryIterator implements Iterator<Entry<String, Object>> { private final Iterator<Entry<String, Object>> delegate; DecoratingEntryIterator(Iterator<Entry<String, Object>> delegate) { this.delegate = delegate; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public Entry<String, Object> next() { Entry<String, Object> entry = delegate.next(); return new AbstractMap.SimpleEntry<>(entry.getKey(), cachingResolver.resolveProperty(entry.getKey())); } } @Override public void forEach(BiConsumer<? super String, ? super Object> action) { delegate.forEach((k, v) -> action.accept(k, cachingResolver.resolveProperty(k))); } private class DecoratingEntryValueIterator implements Iterator<Object> { private final Iterator<Entry<String, Object>> entryIterator;
DecoratingEntryValueIterator(Iterator<Entry<String, Object>> entryIterator) { this.entryIterator = entryIterator; } @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public Object next() { Entry<String, Object> entry = entryIterator.next(); return cachingResolver.resolveProperty(entry.getKey()); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\EncryptableMapWrapper.java
1
请完成以下Java代码
public static SysConfigUIDefaultsRepository ofCurrentLookAndFeelId() { final String lookAndFeelId = UIManager.getLookAndFeel().getID(); return new SysConfigUIDefaultsRepository(lookAndFeelId); } // services private static final transient Logger logger = LogManager.getLogger(SysConfigUIDefaultsRepository.class); private final UIDefaultsSerializer serializer = new UIDefaultsSerializer(); private final transient ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); private final transient IDeveloperModeBL developerModeBL = Services.get(IDeveloperModeBL.class); private static final String SYSCONFIG_PREFIX = "LAF."; private final String lookAndFeelId; public SysConfigUIDefaultsRepository(final String lookAndFeelId) { super(); Check.assumeNotEmpty(lookAndFeelId, "lookAndFeelId not empty"); this.lookAndFeelId = lookAndFeelId; } public void setValue(final Object key, final Object value) { final String sysconfigName = createSysConfigName(key); try { final String sysconfigValue = serializer.toString(value); saveSysConfig(sysconfigName, sysconfigValue); } catch (Exception e) { logger.error("Failed saving " + sysconfigName + ": " + value, e); } } private void saveSysConfig(final String sysconfigName, final String sysconfigValue) { if (!DB.isConnected()) { logger.warn("DB not connected. Cannot write: " + sysconfigName + "=" + sysconfigValue); return; } developerModeBL.executeAsSystem(new ContextRunnable() { @Override public void run(Properties sysCtx) { sysConfigBL.setValue(sysconfigName, sysconfigValue, ClientId.SYSTEM, OrgId.ANY); } }); } private String createSysConfigName(Object key) { return createSysConfigPrefix() + "." + key.toString(); } private String createSysConfigPrefix() { return SYSCONFIG_PREFIX + lookAndFeelId; }
public void loadAllFromSysConfigTo(final UIDefaults uiDefaults) { if (!DB.isConnected()) { return; } final String prefix = createSysConfigPrefix() + "."; final boolean removePrefix = true; final Properties ctx = Env.getCtx(); final ClientAndOrgId clientAndOrgId = ClientAndOrgId.ofClientAndOrg(Env.getAD_Client_ID(ctx), Env.getAD_Org_ID(ctx)); final Map<String, String> map = sysConfigBL.getValuesForPrefix(prefix, removePrefix, clientAndOrgId); for (final Map.Entry<String, String> mapEntry : map.entrySet()) { final String key = mapEntry.getKey(); final String valueStr = mapEntry.getValue(); try { final Object value = serializer.fromString(valueStr); uiDefaults.put(key, value); } catch (Exception ex) { logger.warn("Failed loading " + key + ": " + valueStr + ". Skipped.", ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\SysConfigUIDefaultsRepository.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class AbstractProcessEngineConfiguration { public ProcessEngineFactoryBean springProcessEngineBean(SpringProcessEngineConfiguration configuration) { ProcessEngineFactoryBean processEngineFactoryBean = new ProcessEngineFactoryBean(); processEngineFactoryBean.setProcessEngineConfiguration(configuration); return processEngineFactoryBean; } public RuntimeService runtimeServiceBean(ProcessEngine processEngine) { return processEngine.getRuntimeService(); } public RepositoryService repositoryServiceBean(ProcessEngine processEngine) { return processEngine.getRepositoryService(); } public TaskService taskServiceBean(ProcessEngine processEngine) { return processEngine.getTaskService();
} public HistoryService historyServiceBean(ProcessEngine processEngine) { return processEngine.getHistoryService(); } public ManagementService managementServiceBeanBean(ProcessEngine processEngine) { return processEngine.getManagementService(); } public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) { return processEngine.getProcessEngineConfiguration().getIntegrationContextManager(); } public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) { return processEngine.getProcessEngineConfiguration().getIntegrationContextService(); } }
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AbstractProcessEngineConfiguration.java
2
请完成以下Java代码
public int getUnitsPerPallet() { return get_ValueAsInt(COLUMNNAME_UnitsPerPallet); } @Override public void setUOM_MultiplierRate (final @Nullable BigDecimal UOM_MultiplierRate) { set_Value (COLUMNNAME_UOM_MultiplierRate, UOM_MultiplierRate); } @Override public BigDecimal getUOM_MultiplierRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_UOM_MultiplierRate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } @Override public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } @Override public java.lang.String getVendorProductNo() { return get_ValueAsString(COLUMNNAME_VendorProductNo); } @Override public void setVolume (final @Nullable BigDecimal Volume) { set_Value (COLUMNNAME_Volume, Volume); } @Override
public BigDecimal getVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeight (final @Nullable BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } @Override public BigDecimal getWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeightUOM (final @Nullable java.lang.String WeightUOM) { set_Value (COLUMNNAME_WeightUOM, WeightUOM); } @Override public java.lang.String getWeightUOM() { return get_ValueAsString(COLUMNNAME_WeightUOM); } @Override public void setWeight_UOM_ID (final int Weight_UOM_ID) { if (Weight_UOM_ID < 1) set_Value (COLUMNNAME_Weight_UOM_ID, null); else set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID); } @Override public int getWeight_UOM_ID() { return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } @Override public void setX12DE355 (final @Nullable java.lang.String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } @Override public java.lang.String getX12DE355() { return get_ValueAsString(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Product.java
1
请在Spring Boot框架中完成以下Java代码
public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } public String getErrType() { return errType; } public void setErrType(String errType) { this.errType = errType == null ? null : errType.trim(); } public String getHandleStatus() { return handleStatus; } public void setHandleStatus(String handleStatus) { this.handleStatus = handleStatus == null ? null : handleStatus.trim(); } public String getHandleValue() { return handleValue; } public void setHandleValue(String handleValue) { this.handleValue = handleValue == null ? null : handleValue.trim(); } public String getHandleRemark() { return handleRemark; }
public void setHandleRemark(String handleRemark) { this.handleRemark = handleRemark == null ? null : handleRemark.trim(); } public String getOperatorName() { return operatorName; } public void setOperatorName(String operatorName) { this.operatorName = operatorName == null ? null : operatorName.trim(); } public String getOperatorAccountNo() { return operatorAccountNo; } public void setOperatorAccountNo(String operatorAccountNo) { this.operatorAccountNo = operatorAccountNo == null ? null : operatorAccountNo.trim(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistake.java
2
请完成以下Java代码
public void setPointsSum_Invoiceable (final BigDecimal PointsSum_Invoiceable) { set_ValueNoCheck (COLUMNNAME_PointsSum_Invoiceable, PointsSum_Invoiceable); } @Override public BigDecimal getPointsSum_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Invoiced (final BigDecimal PointsSum_Invoiced) { set_Value (COLUMNNAME_PointsSum_Invoiced, PointsSum_Invoiced); } @Override public BigDecimal getPointsSum_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Settled (final BigDecimal PointsSum_Settled) { set_Value (COLUMNNAME_PointsSum_Settled, PointsSum_Settled); } @Override public BigDecimal getPointsSum_Settled()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_ToSettle (final BigDecimal PointsSum_ToSettle) { set_Value (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle); } @Override public BigDecimal getPointsSum_ToSettle() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Share.java
1
请完成以下Java代码
public AnnotatedTableFactory setModel(final TableModel model) { this.model = model; return this; } /** * @param selectionMode * @see ListSelectionModel#setSelectionMode(int) */ public AnnotatedTableFactory setSelectionMode(final int selectionMode) { this.selectionMode = selectionMode; return this; } public AnnotatedTableFactory addListSelectionListener(final ListSelectionListener listener) { Check.assumeNotNull(listener, "listener not null"); selectionListeners.add(listener); return this; } public AnnotatedTableFactory setCreateStandardSelectActions(final boolean createStandardSelectActions) { this.createStandardSelectActions = createStandardSelectActions; return this; } /** * Adds an popup action. *
* NOTE to developer: you can easily implement table popup actions by extending {@link AnnotatedTableAction}. * * @param action * @return this */ public AnnotatedTableFactory addPopupAction(final Action action) { Check.assumeNotNull(action, "action not null"); if (!popupActions.contains(action)) { popupActions.add(action); } return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableFactory.java
1
请在Spring Boot框架中完成以下Java代码
public String getModeOfDispatch() { return modeOfDispatch; } /** * Sets the value of the modeOfDispatch property. * * @param value * allowed object is * {@link String } * */ public void setModeOfDispatch(String value) { this.modeOfDispatch = value; } /** * The number of packages in the given delivery. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getNumberOfPackages() { return numberOfPackages; } /** * Sets the value of the numberOfPackages property. * * @param value * allowed object is * {@link BigInteger } * */ public void setNumberOfPackages(BigInteger value) { this.numberOfPackages = value; } /** * The name of the driver performing the delivery. * * @return * possible object is * {@link String } * */ public String getNameOfDriver() { return nameOfDriver; } /** * Sets the value of the nameOfDriver property. * * @param value * allowed object is * {@link String } * */ public void setNameOfDriver(String value) { this.nameOfDriver = value;
} /** * The license plate number of the vehicle performing the delivery. * * @return * possible object is * {@link String } * */ public String getTransportVehicleLicenseNumber() { return transportVehicleLicenseNumber; } /** * Sets the value of the transportVehicleLicenseNumber property. * * @param value * allowed object is * {@link String } * */ public void setTransportVehicleLicenseNumber(String value) { this.transportVehicleLicenseNumber = value; } /** * Gets the value of the deliveryDetailsExtension property. * * @return * possible object is * {@link DeliveryDetailsExtensionType } * */ public DeliveryDetailsExtensionType getDeliveryDetailsExtension() { return deliveryDetailsExtension; } /** * Sets the value of the deliveryDetailsExtension property. * * @param value * allowed object is * {@link DeliveryDetailsExtensionType } * */ public void setDeliveryDetailsExtension(DeliveryDetailsExtensionType value) { this.deliveryDetailsExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryDetailsType.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setDisableCommand (final @Nullable java.lang.String DisableCommand) { set_Value (COLUMNNAME_DisableCommand, DisableCommand); } @Override public java.lang.String getDisableCommand() { return get_ValueAsString(COLUMNNAME_DisableCommand); } @Override public void setEnableCommand (final @Nullable java.lang.String EnableCommand) { set_Value (COLUMNNAME_EnableCommand, EnableCommand); } @Override public java.lang.String getEnableCommand() { return get_ValueAsString(COLUMNNAME_EnableCommand); } @Override public de.metas.externalsystem.model.I_ExternalSystem getExternalSystem() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class); } @Override public void setExternalSystem(final de.metas.externalsystem.model.I_ExternalSystem ExternalSystem) { set_ValueFromPO(COLUMNNAME_ExternalSystem_ID, de.metas.externalsystem.model.I_ExternalSystem.class, ExternalSystem); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } @Override public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID) { if (ExternalSystem_Service_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID); } @Override public int getExternalSystem_Service_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service.java
1
请完成以下Java代码
public Optional<DocSequenceId> getSerialNoSequenceId(@NonNull final PPOrderId ppOrderId) { final I_PP_Order_BOM orderBOM = orderBOMsRepo.getByOrderIdOrNull(ppOrderId); if (orderBOM == null) { throw new AdempiereException("@NotFound@ @PP_Order_BOM_ID@: " + ppOrderId); } return DocSequenceId.optionalOfRepoId(orderBOM.getSerialNo_Sequence_ID()); } @Override public QtyCalculationsBOM getQtyCalculationsBOM(@NonNull final I_PP_Order order) { final ImmutableList<QtyCalculationsBOMLine> lines = orderBOMsRepo.retrieveOrderBOMLines(order) .stream() .map(orderBOMLineRecord -> toQtyCalculationsBOMLine(order, orderBOMLineRecord)) .collect(ImmutableList.toImmutableList()); return QtyCalculationsBOM.builder() .lines(lines) .orderId(PPOrderId.ofRepoIdOrNull(order.getPP_Order_ID())) .build(); } @Override public void save(final I_PP_Order_BOMLine orderBOMLine) { orderBOMsRepo.save(orderBOMLine); } @Override public Set<ProductId> getProductIdsToIssue(final PPOrderId ppOrderId) { return getOrderBOMLines(ppOrderId, I_PP_Order_BOMLine.class) .stream()
.filter(bomLine -> BOMComponentType.ofNullableCodeOrComponent(bomLine.getComponentType()).isIssue()) .map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID())) .collect(ImmutableSet.toImmutableSet()); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(@NonNull final I_PP_Order ppOrder) { final WarehouseId warehouseId = WarehouseId.ofRepoId(ppOrder.getM_Warehouse_ID()); return getIssueFromWarehouseIds(warehouseId); } @Override public ImmutableSet<WarehouseId> getIssueFromWarehouseIds(final WarehouseId ppOrderWarehouseId) { return warehouseDAO.getWarehouseIdsOfSameGroup(ppOrderWarehouseId, WarehouseGroupAssignmentType.MANUFACTURING); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\impl\PPOrderBOMBL.java
1
请完成以下Java代码
public static <BT, T extends BT> void registerJUnitBeans(@NonNull final Class<BT> beanType, @NonNull final List<T> beansToAdd) { instance.junitRegisteredBeans.registerJUnitBeans(beanType, beansToAdd); } public static <T> Lazy<T> lazyBean(@NonNull final Class<T> requiredType) { return new Lazy<>(requiredType, null); } public static <T> Lazy<T> lazyBean(@NonNull final Class<T> requiredType, @Nullable final T initialBean) { return new Lazy<>(requiredType, initialBean); } public Optional<String> getProperty(@NonNull final String name) { if (applicationContext != null) { final String springContextValue = StringUtils.trimBlankToNull(applicationContext.getEnvironment().getProperty(name)); if (springContextValue != null) { logger.debug("Returning the spring context's value {}={} instead of looking up the AD_SysConfig record", name, springContextValue); return Optional.of(springContextValue); } } else { // If there is no Spring context then go an check JVM System Properties. // Usually we will get here when we will run some tools based on metasfresh framework. final Properties systemProperties = System.getProperties(); final String systemPropertyValue = StringUtils.trimBlankToNull(systemProperties.getProperty(name)); if (systemPropertyValue != null) { logger.debug("Returning the JVM system property's value {}={} instead of looking up the AD_SysConfig record", name, systemPropertyValue); return Optional.of(systemPropertyValue); } // If there is no JVM System Property then go and check environment variables return StringUtils.trimBlankToOptional(System.getenv(name)); } return Optional.empty(); } // //
// @ToString public static final class Lazy<T> { private final Class<T> requiredType; private T bean; private Lazy(@NonNull final Class<T> requiredType, @Nullable final T initialBean) { this.requiredType = requiredType; this.bean = initialBean; } @NonNull public T get() { T bean = this.bean; if (bean == null) { bean = this.bean = instance.getBean(requiredType); } return bean; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\SpringContextHolder.java
1
请在Spring Boot框架中完成以下Java代码
public User get(@PathVariable Long id) { log.info("获取用户id为 " + id + "的信息"); return new User(id, "mrbird", "123456"); } @GetMapping public List<User> get() { List<User> list = new ArrayList<>(); list.add(new User(1L, "mrbird", "123456")); list.add(new User(2L, "scott", "123456")); log.info("获取用户信息 " + list); return list; } @PostMapping
public void add(@RequestBody User user) { log.info("新增用户成功 " + user); } @PutMapping public void update(@RequestBody User user) { log.info("更新用户成功 " + user); } @DeleteMapping("/{id:\\d+}") public void delete(@PathVariable Long id) { log.info("删除用户成功 " + id); } }
repos\SpringAll-master\29.Spring-Cloud-Ribbon-LoadBalance\Eureka-Client\src\main\java\com\example\demo\controller\UserController.java
2
请完成以下Java代码
public boolean isGraphicalNotationDefined() { return isGraphicalNotationDefined; } public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) { this.isGraphicalNotationDefined = isGraphicalNotationDefined; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } public IOSpecification getIoSpecification() {
return ioSpecification; } public void setIoSpecification(IOSpecification ioSpecification) { this.ioSpecification = ioSpecification; } public String toString() { return "ProcessDefinitionEntity[" + id + "]"; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public Integer getAppVersion() { return this.appVersion; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java
1
请完成以下Java代码
public class User { private Long userId; private String userName; private Integer userAge; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() {
return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getUserAge() { return userAge; } public void setUserAge(Integer userAge) { this.userAge = userAge; } }
repos\Spring-Boot-In-Action-master\springbt_ehcache\src\main\java\cn\codesheep\springbt_ehcache\entity\User.java
1
请完成以下Java代码
public SqlLookupDescriptorFactory setCtxTableName(@Nullable final String ctxTableName) { this.ctxTableName = ctxTableName; this.filtersBuilder.setCtxTableName(ctxTableName); return this; } public SqlLookupDescriptorFactory setDisplayType(final ReferenceId displayType) { this.displayType = displayType; this.filtersBuilder.setDisplayType(ReferenceId.toRepoId(displayType)); return this; } public SqlLookupDescriptorFactory setAD_Reference_Value_ID(final ReferenceId AD_Reference_Value_ID) { this.AD_Reference_Value_ID = AD_Reference_Value_ID; return this; } public SqlLookupDescriptorFactory setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds) { this.filtersBuilder.setAdValRuleIds(adValRuleIds); return this; } private CompositeSqlLookupFilter getFilters() { return filtersBuilder.getOrBuild(); } private static boolean computeIsHighVolume(@NonNull final ReferenceId diplayType) { final int displayTypeInt = diplayType.getRepoId(); return DisplayType.TableDir != displayTypeInt && DisplayType.Table != displayTypeInt && DisplayType.List != displayTypeInt && DisplayType.Button != displayTypeInt; } /**
* Advice the lookup to show all records on which current user has at least read only access */ public SqlLookupDescriptorFactory setReadOnlyAccess() { this.requiredAccess = Access.READ; return this; } private Access getRequiredAccess(@NonNull final TableName tableName) { if (requiredAccess != null) { return requiredAccess; } // AD_Client_ID/AD_Org_ID (security fields): shall display only those entries on which current user has read-write access if (I_AD_Client.Table_Name.equals(tableName.getAsString()) || I_AD_Org.Table_Name.equals(tableName.getAsString())) { return Access.WRITE; } // Default: all entries on which current user has at least readonly access return Access.READ; } SqlLookupDescriptorFactory addValidationRules(final Collection<IValidationRule> validationRules) { this.filtersBuilder.addFilter(validationRules, null); return this; } SqlLookupDescriptorFactory setPageLength(final Integer pageLength) { this.pageLength = pageLength; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorFactory.java
1
请完成以下Java代码
public class CafeAddress extends WebPage { private String selectedCafe; private Address address; private Map<String, Address> cafeNamesAndAddresses = new HashMap<>(); public CafeAddress(final PageParameters parameters) { super(parameters); initCafes(); ArrayList<String> cafeNames = new ArrayList<>(cafeNamesAndAddresses.keySet()); selectedCafe = cafeNames.get(0); address = new Address(cafeNamesAndAddresses.get(selectedCafe).getAddress()); final Label addressLabel = new Label("address", new PropertyModel<String>(this.address, "address")); addressLabel.setOutputMarkupId(true); final DropDownChoice<String> cafeDropdown = new DropDownChoice<>("cafes", new PropertyModel<>(this, "selectedCafe"), cafeNames); cafeDropdown.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { String name = (String) cafeDropdown.getDefaultModel().getObject(); address.setAddress(cafeNamesAndAddresses.get(name).getAddress()); target.add(addressLabel); } }); add(addressLabel); add(cafeDropdown);
} private void initCafes() { this.cafeNamesAndAddresses.put("Linda's Cafe", new Address("35 Bower St.")); this.cafeNamesAndAddresses.put("Old Tree", new Address("2 Edgware Rd.")); } class Address implements Serializable { private String sAddress = ""; public Address(String address) { this.sAddress = address; } String getAddress() { return this.sAddress; } void setAddress(String address) { this.sAddress = address; } } }
repos\tutorials-master\web-modules\wicket\src\main\java\com\baeldung\wicket\examples\cafeaddress\CafeAddress.java
1
请完成以下Java代码
public class CookieStoreCleanupTrigger extends AbstractEventHandler<InstanceDeregisteredEvent> { private final PerInstanceCookieStore cookieStore; /** * Creates a trigger to cleanup the cookie store on deregistering of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance}. * @param publisher publisher of {@link InstanceEvent}s events * @param cookieStore the store to inform about deregistration of an * {@link de.codecentric.boot.admin.server.domain.entities.Instance} */ public CookieStoreCleanupTrigger(final Publisher<InstanceEvent> publisher, final PerInstanceCookieStore cookieStore) { super(publisher, InstanceDeregisteredEvent.class);
this.cookieStore = cookieStore; } @Override protected Publisher<Void> handle(final Flux<InstanceDeregisteredEvent> publisher) { return publisher.flatMap((event) -> { cleanupCookieStore(event); return Mono.empty(); }); } private void cleanupCookieStore(final InstanceDeregisteredEvent event) { cookieStore.cleanupInstance(event.getInstance()); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\cookies\CookieStoreCleanupTrigger.java
1
请在Spring Boot框架中完成以下Java代码
public String createOrder(String outTradeNo, String totalAmount, String subject) throws AlipayApiException { AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(), alipayConfig.getMerchantPrivateKey(), "json", "UTF-8", alipayConfig.getAlipayPublicKey(), "RSA2"); AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\",\"total_amount\":\"" + totalAmount + "\",\"subject\":\"" + subject + "\"}"); request.setNotifyUrl(alipayConfig.getNotifyUrl()); request.setReturnUrl(alipayConfig.getReturnUrl()); try { AlipayTradePrecreateResponse response = alipayClient.execute(request); if (response.isSuccess()) { return response.getQrCode(); // 返回二维码链接 } else { return "创建支付失败: " + response.getMsg(); } } catch (AlipayApiException e) { e.printStackTrace(); return "异常: " + e.getMessage(); } } public String queryPayment(String outTradeNo) { AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(), alipayConfig.getMerchantPrivateKey(), "json", "UTF-8", alipayConfig.getAlipayPublicKey(), "RSA2");
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\"}"); try { AlipayTradeQueryResponse response = alipayClient.execute(request); if (response.isSuccess()) { return response.getTradeStatus(); // 返回订单状态 } else { return "查询失败: " + response.getMsg(); } } catch (AlipayApiException e) { e.printStackTrace(); return "异常: " + e.getMessage(); } } }
repos\springboot-demo-master\Alipay-facetoface\src\main\java\com\et\service\AlipayService.java
2
请完成以下Java代码
public void setPriceStd (BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } /** Get Standard Price. @return Standard Price */ public BigDecimal getPriceStd () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Product Key.
@param ProductValue Key of the Product */ public void setProductValue (String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } /** Get Product Key. @return Key of the Product */ public String getProductValue () { return (String)get_Value(COLUMNNAME_ProductValue); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set UOM Code. @param X12DE355 UOM EDI X12 Code */ public void setX12DE355 (String X12DE355) { set_Value (COLUMNNAME_X12DE355, X12DE355); } /** Get UOM Code. @return UOM EDI X12 Code */ public String getX12DE355 () { return (String)get_Value(COLUMNNAME_X12DE355); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java
1
请完成以下Java代码
public ClientSetup setIBAN(final String iban) { if (!Check.isEmpty(iban, true)) { orgBankAccount.setIBAN(iban.trim()); } return this; } public ClientSetup setC_Bank_ID(final int bankId) { if (bankId > 0) { orgBankAccount.setC_Bank_ID(bankId); } return this; } public final int getC_Bank_ID() { return orgBankAccount.getC_Bank_ID(); } public ClientSetup setPhone(final String phone) { if (!Check.isEmpty(phone, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setPhone(phone.trim()); } return this; } public final String getPhone() { return orgContact.getPhone(); } public ClientSetup setFax(final String fax) { if (!Check.isEmpty(fax, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setFax(fax.trim()); } return this; } public final String getFax()
{ return orgContact.getFax(); } public ClientSetup setEMail(final String email) { if (!Check.isEmpty(email, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setEMail(email.trim()); } return this; } public final String getEMail() { return orgContact.getEMail(); } public ClientSetup setBPartnerDescription(final String bpartnerDescription) { if (Check.isEmpty(bpartnerDescription, true)) { return this; } orgBPartner.setDescription(bpartnerDescription.trim()); return this; } public String getBPartnerDescription() { return orgBPartner.getDescription(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\ClientSetup.java
1
请完成以下Java代码
public String getId() { return id; } public String getAssigneeId() { return assigneeId; } public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } public List<String> getGroups() { return groups; } public void setGroups(List<String> groups) { this.groups = groups; }
public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public boolean isStandalone() { return getProcessInstanceId() == null; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\GetTasksPayload.java
1
请完成以下Java代码
public IInvoiceCandInvalidUpdater setRecomputeTagToUse(final InvoiceCandRecomputeTag tag) { assertNotExecuted(); icTagger.setRecomputeTag(tag); return this; } @Override public IInvoiceCandInvalidUpdater setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds) { assertNotExecuted(); icTagger.setOnlyInvoiceCandidateIds(onlyInvoiceCandidateIds); return this; } private int getItemsPerBatch() { return sysConfigBL.getIntValue(SYSCONFIG_ItemsPerBatch, DEFAULT_ItemsPerBatch); } /** * IC update result. * * @author metas-dev <dev@metasfresh.com> */ private static final class ICUpdateResult { private int countOk = 0; private int countErrors = 0; public void addInvoiceCandidate() { countOk++; } public void incrementErrorsCount() { countErrors++; } @Override public String toString()
{ return getSummary(); } public String getSummary() { return "Updated " + countOk + " invoice candidates, " + countErrors + " errors"; } } /** * IC update exception handler */ private final class ICTrxItemExceptionHandler extends FailTrxItemExceptionHandler { private final ICUpdateResult result; public ICTrxItemExceptionHandler(@NonNull final ICUpdateResult result) { this.result = result; } /** * Resets the given IC to its old values, and sets an error flag in it. */ @Override public void onItemError(final Throwable e, final Object item) { result.incrementErrorsCount(); final I_C_Invoice_Candidate ic = InterfaceWrapperHelper.create(item, I_C_Invoice_Candidate.class); // gh #428: don't discard changes that were already made, because they might include a change of QtyInvoice. // in that case, a formerly Processed IC might need to be flagged as unprocessed. // if we discard all changes in this case, then we will have IsError='Y' and also an error message in the IC, // but the user will probably ignore it, because the IC is still flagged as processed. invoiceCandBL.setError(ic, e); // invoiceCandBL.discardChangesAndSetError(ic, e); invoiceCandDAO.save(ic); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandInvalidUpdater.java
1
请完成以下Java代码
public LwM2m.Version getSupportedObjectVersion(Integer objectid) { return this.supportedClientObjects != null ? this.supportedClientObjects.get(objectid) : null; } private void setSupportedClientObjects(){ if (this.registration.getSupportedObject() != null && this.registration.getSupportedObject().size() > 0) { this.supportedClientObjects = this.registration.getSupportedObject(); } else { this.supportedClientObjects = new ConcurrentHashMap<>(); for (Link link : this.registration.getSortedObjectLinks()) { if (link instanceof MixedLwM2mLink) { LwM2mPath path = ((MixedLwM2mLink) link).getPath(); // add supported objects if (path.isObject() || path.isObjectInstance()) { int objectId = path.getObjectId(); LwM2mAttribute<Version> versionParamValue = link.getAttributes().get(LwM2mAttributes.OBJECT_VERSION); if (versionParamValue != null) { // if there is a version attribute then use it as version for this object
this.supportedClientObjects.put(objectId, versionParamValue.getValue()); } else { // there is no version attribute attached. // In this case we use the DEFAULT_VERSION only if this object stored as supported object. Version currentVersion = this.supportedClientObjects.get(objectId); if (currentVersion == null) { this.supportedClientObjects.put(objectId, getDefaultObjectIDVer()); } } } } } } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\client\LwM2mClient.java
1
请完成以下Java代码
public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Kommentar/Hilfe. @param Help Comment or Hint */ @Override public void setHelp (java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Kommentar/Hilfe. @return Comment or Hint */ @Override public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Beta-Funktionalität. @param IsBetaFunctionality This functionality is considered Beta */ @Override public void setIsBetaFunctionality (boolean IsBetaFunctionality) { set_Value (COLUMNNAME_IsBetaFunctionality, Boolean.valueOf(IsBetaFunctionality)); } /** Get Beta-Funktionalität. @return This functionality is considered Beta */ @Override public boolean isBetaFunctionality () { Object oo = get_Value(COLUMNNAME_IsBetaFunctionality); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set jsp-URL. @param JSPURL Web URL of the jsp function */ @Override public void setJSPURL (java.lang.String JSPURL) { set_Value (COLUMNNAME_JSPURL, JSPURL); } /** Get jsp-URL. @return Web URL of the jsp function */ @Override public java.lang.String getJSPURL () { return (java.lang.String)get_Value(COLUMNNAME_JSPURL); } /** Set Is Modal. @param Modal Is Modal */ @Override public void setModal (boolean Modal) { set_Value (COLUMNNAME_Modal, Boolean.valueOf(Modal)); } /** Get Is Modal. @return Is Modal */ @Override public boolean isModal () { Object oo = get_Value(COLUMNNAME_Modal); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form.java
1
请完成以下Java代码
public ClientSoftwareId getClientSoftwareIdFromClientRequest(final Object soapRequestObj) { final BestellstatusAbfragen soapRequest = castToRequestFromClient(soapRequestObj); return ClientSoftwareId.of(soapRequest.getClientSoftwareKennung()); } private static BestellstatusAbfragen castToRequestFromClient(final Object soapRequestObj) { final BestellstatusAbfragen soapRequest = (BestellstatusAbfragen)soapRequestObj; return soapRequest; } @Override public JAXBElement<BestellstatusAbfragenResponse> encodeResponseToClient(final OrderStatusResponse response) { return toJAXB(response); }
private JAXBElement<BestellstatusAbfragenResponse> toJAXB(final OrderStatusResponse response) { final BestellstatusAntwort soapResponseContent = jaxbObjectFactory.createBestellstatusAntwort(); soapResponseContent.setId(response.getOrderId().getValueAsString()); soapResponseContent.setBestellSupportId(response.getSupportId().getValueAsInt()); soapResponseContent.setStatus(response.getOrderStatus().getV1SoapCode()); soapResponseContent.getAuftraege().addAll(response.getOrderPackages().stream() .map(orderConverters::toJAXB) .collect(ImmutableList.toImmutableList())); final BestellstatusAbfragenResponse soapResponse = jaxbObjectFactory.createBestellstatusAbfragenResponse(); soapResponse.setReturn(soapResponseContent); return jaxbObjectFactory.createBestellstatusAbfragenResponse(soapResponse); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\v1\OrderStatusJAXBConvertersV1.java
1
请完成以下Java代码
public void setUserCodeGenerator(OAuth2TokenGenerator<OAuth2UserCode> userCodeGenerator) { Assert.notNull(userCodeGenerator, "userCodeGenerator cannot be null"); this.userCodeGenerator = userCodeGenerator; } private static void throwError(String errorCode, String parameterName) { OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, ERROR_URI); throw new OAuth2AuthenticationException(error); } private static final class OAuth2DeviceCodeGenerator implements OAuth2TokenGenerator<OAuth2DeviceCode> { private final StringKeyGenerator deviceCodeGenerator = new Base64StringKeyGenerator( Base64.getUrlEncoder().withoutPadding(), 96); @Nullable @Override public OAuth2DeviceCode generate(OAuth2TokenContext context) { if (context.getTokenType() == null || !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) { return null; } Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive()); return new OAuth2DeviceCode(this.deviceCodeGenerator.generateKey(), issuedAt, expiresAt); } } private static final class UserCodeStringKeyGenerator implements StringKeyGenerator { // @formatter:off private static final char[] VALID_CHARS = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z' }; // @formatter:on private final BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(8); @Override public String generateKey() {
byte[] bytes = this.keyGenerator.generateKey(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { int offset = Math.abs(b % 20); sb.append(VALID_CHARS[offset]); } sb.insert(4, '-'); return sb.toString(); } } private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> { private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator(); @Nullable @Override public OAuth2UserCode generate(OAuth2TokenContext context) { if (context.getTokenType() == null || !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) { return null; } Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt .plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive()); return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
1
请完成以下Java代码
public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getArea() { return area; } public void setArea(String area) { this.area = area; }
public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } }
repos\spring-boot-quick-master\quick-swagger\src\main\java\com\quick\po\Address.java
1
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } @Override public String getId() { return id; } @Override public String getDisplayName() { return displayName; } @Override public IQueryFilter<ModelType> getFilter() { return filter; } @Override public IFacetCategory getFacetCategory() { return facetCategory; } public static class Builder<ModelType> { private String id = null; private String displayName; private IQueryFilter<ModelType> filter; private IFacetCategory facetCategory; private Builder() {
super(); } public Facet<ModelType> build() { return new Facet<>(this); } public Builder<ModelType> setId(final String id) { this.id = id; return this; } public Builder<ModelType> setDisplayName(final String displayName) { this.displayName = displayName; return this; } public Builder<ModelType> setFilter(final IQueryFilter<ModelType> filter) { this.filter = filter; return this; } public Builder<ModelType> setFacetCategory(final IFacetCategory facetCategory) { this.facetCategory = facetCategory; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\Facet.java
1
请在Spring Boot框架中完成以下Java代码
protected String doIt() { final Quantity qtyToReserve = getQtyToReserveParam(); final ImmutableSet<HuId> huIds = getSelectedTopLevelHUIds(); final ServiceRepairProjectTaskId taskId = getTaskId(); projectService.reserveSparePartsFromHUs(taskId, qtyToReserve, huIds); tasksCache.clear(); return MSG_OK; } private Quantity getQtyToReserveParam() { final Quantity qtyToReserve = Quantitys.of(qty, uomId); if (qtyToReserve.signum() <= 0) { throw new FillMandatoryException(PARAM_Qty); } return qtyToReserve; } private ServiceRepairProjectTask getTask() { return tasksCache.computeIfAbsent(getTaskId(), projectService::getTaskById); } private ServiceRepairProjectTaskId getTaskId() {
final HUsToIssueViewContext husToIssueViewContext = getHusToIssueViewContext(); return husToIssueViewContext.getTaskId(); } private ImmutableSet<HuId> getSelectedTopLevelHUIds() { return streamSelectedHUIds(HUEditorRowFilter.Select.ONLY_TOPLEVEL).collect(ImmutableSet.toImmutableSet()); } private HUsToIssueViewContext getHusToIssueViewContext() { return getView() .getParameter(HUsToIssueViewFactory.PARAM_HUsToIssueViewContext, HUsToIssueViewContext.class) .orElseThrow(() -> new AdempiereException("No view context")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\HUsToIssueView_IssueHUs.java
2
请完成以下Java代码
public String getHostname() throws UnknownHostException { return InetAddress.getLocalHost().getHostName(); } public String getBaseUrl() { return urlResolver.getBaseUrl(); } protected String getWorkerId() { return workerId; } protected List<ClientRequestInterceptor> getInterceptors() { return interceptors; } protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy; } public String getDefaultSerializationFormat() { return defaultSerializationFormat; } public String getDateFormat() {
return dateFormat; } public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
1
请完成以下Java代码
public class ProjectManifest { private String createdBy; private String creationDate; private String lastModifiedBy; private String lastModifiedDate; private String id; private String name; private String description; private String version; public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public String getLastModifiedDate() {
return lastModifiedDate; } public void setLastModifiedDate(String lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
repos\Activiti-develop\activiti-core-common\activiti-project-model\src\main\java\org\activiti\core\common\project\model\ProjectManifest.java
1
请完成以下Java代码
private PrintOptions createPrintOptions( @NonNull final DpdOrderCustomDeliveryData customDeliveryData) { final PrintOptions printOptions = shipmentServiceOF.createPrintOptions(); printOptions.setPaperFormat(customDeliveryData.getPaperFormat().getCode()); printOptions.setPrinterLanguage(customDeliveryData.getPrinterLanguage()); return printOptions; } private Login authenticateRequest() { // Login final GetAuth getAuthValue = loginServiceOF.createGetAuth(); getAuthValue.setDelisId(config.getDelisID()); getAuthValue.setPassword(config.getDelisPassword()); getAuthValue.setMessageLanguage(DpdConstants.DEFAULT_MESSAGE_LANGUAGE); final ILoggable epicLogger = getEpicLogger(); epicLogger.addLog("Creating login request"); final JAXBElement<GetAuth> getAuthElement = loginServiceOF.createGetAuth(getAuthValue); @SuppressWarnings("unchecked") final JAXBElement<GetAuthResponse> authenticationElement = (JAXBElement<GetAuthResponse>)doActualRequest(config.getLoginApiUrl(), getAuthElement, null, null); final Login login = authenticationElement.getValue().getReturn();
epicLogger.addLog("Finished login Request"); return login; } /** * no idea what this does, but tobias sais it's useful to have this special log, so here it is! */ @NonNull private ILoggable getEpicLogger() { return Loggables.withLogger(logger, Level.TRACE); } @Override public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request) { return JsonDeliveryAdvisorResponse.builder() .requestId(request.getId()) .shipperProduct(JsonShipperProduct.builder() .code(DpdShipperProduct.DPD_CLASSIC.getCode()) .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\DpdShipperGatewayClient.java
1
请完成以下Java代码
protected int[] extractFeature(String[] wordArray, String[] posArray, FeatureMap featureMap, int position) { StringBuilder sbFeature = new StringBuilder(); List<Integer> featureVec = new LinkedList<Integer>(); for (int i = 0; i < featureTemplateArray.length; i++) { Iterator<int[]> offsetIterator = featureTemplateArray[i].offsetList.iterator(); Iterator<String> delimiterIterator = featureTemplateArray[i].delimiterList.iterator(); delimiterIterator.next(); // ignore U0 之类的id while (offsetIterator.hasNext()) { int[] offset = offsetIterator.next(); int t = offset[0] + position; boolean first = offset[1] == 0; if (t < 0) sbFeature.append(FeatureIndex.BOS[-(t + 1)]); else if (t >= wordArray.length) sbFeature.append(FeatureIndex.EOS[t - wordArray.length]); else sbFeature.append(first ? wordArray[t] : posArray[t]); if (delimiterIterator.hasNext()) sbFeature.append(delimiterIterator.next()); else sbFeature.append(i); } addFeatureThenClear(sbFeature, featureVec, featureMap); } return toFeatureArray(featureVec); } }; } @Override protected String getDefaultFeatureTemplate()
{ return "# Unigram\n" + // form "U0:%x[-2,0]\n" + "U1:%x[-1,0]\n" + "U2:%x[0,0]\n" + "U3:%x[1,0]\n" + "U4:%x[2,0]\n" + // pos "U5:%x[-2,1]\n" + "U6:%x[-1,1]\n" + "U7:%x[0,1]\n" + "U8:%x[1,1]\n" + "U9:%x[2,1]\n" + // pos 2-gram "UA:%x[-2,1]%x[-1,1]\n" + "UB:%x[-1,1]%x[0,1]\n" + "UC:%x[0,1]%x[1,1]\n" + "UD:%x[1,1]%x[2,1]\n" + "UE:%x[2,1]%x[3,1]\n" + "\n" + "# Bigram\n" + "B"; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFNERecognizer.java
1
请完成以下Java代码
public void setValues(ValuedDataObject otherElement) { super.setValues(otherElement); if (otherElement.getValue() != null) { setValue(otherElement.getValue()); } } public String getType() { String structureRef = itemSubjectRef.getStructureRef(); return structureRef.substring(structureRef.indexOf(':') + 1); } @Override public int hashCode() { int result = 0; result = 31 * result + (itemSubjectRef.getStructureRef() != null ? itemSubjectRef.getStructureRef().hashCode() : 0); result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (value != null ? value.hashCode() : 0); return result; } @Override public boolean equals(Object o) { if (this == o) {
return true; } if (o == null || getClass() != o.getClass()) { return false; } ValuedDataObject otherObject = (ValuedDataObject) o; if (!otherObject.getItemSubjectRef().getStructureRef().equals(this.itemSubjectRef.getStructureRef())) { return false; } if (!otherObject.getId().equals(this.id)) { return false; } if (!otherObject.getName().equals(this.name)) { return false; } return otherObject.getValue().equals(this.value.toString()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ValuedDataObject.java
1
请完成以下Java代码
public static ListenableFuture<Long> factorialUsingGuavaServiceSubmit(int number) { ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); ListenableFuture<Long> factorialFuture = (ListenableFuture<Long>) service.submit(()-> factorial(number)); return factorialFuture; } /** * Finds factorial of a number using Guava's Futures.submitAsync() * @param number * @return */ @Loggable public static ListenableFuture<Long> factorialUsingGuavaFutures(int number) { ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool); AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() { public Long call() { return factorial(number); } }, service);
return Futures.submitAsync(asyncCallable, service); } /** * Finds factorial of a number using @Async of jcabi-aspects * @param number * @return */ @Async @Loggable public static Future<Long> factorialUsingJcabiAspect(int number) { Future<Long> factorialFuture = CompletableFuture.supplyAsync(() -> factorial(number)); return factorialFuture; } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\async\JavaAsync.java
1
请完成以下Java代码
public String toEdit(Model model,Long id) { User user=userRepository.findById(id); model.addAttribute("user", user); return "user/userEdit"; } @RequestMapping("/edit") public String edit(@Valid UserParam userParam, BindingResult result,ModelMap model) { String errorMsg=""; if(result.hasErrors()) { List<ObjectError> list = result.getAllErrors(); for (ObjectError error : list) { errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";"; } model.addAttribute("errorMsg",errorMsg); model.addAttribute("user", userParam); return "user/userEdit";
} User user=new User(); BeanUtils.copyProperties(userParam,user); user.setRegTime(new Date()); userRepository.save(user); return "redirect:/list"; } @RequestMapping("/delete") public String delete(Long id) { userRepository.delete(id); return "redirect:/list"; } }
repos\spring-boot-leaning-master\1.x\第06课:Jpa 和 Thymeleaf 实践\spring-boot-jpa-thymeleaf\src\main\java\com\neo\web\UserController.java
1
请在Spring Boot框架中完成以下Java代码
public static class BackoffConfig { private Duration firstBackoff = Duration.ofMillis(5); private @Nullable Duration maxBackoff; private int factor = 2; private boolean basedOnPreviousValue = true; public BackoffConfig() { } public BackoffConfig(Duration firstBackoff, Duration maxBackoff, int factor, boolean basedOnPreviousValue) { this.firstBackoff = firstBackoff; this.maxBackoff = maxBackoff; this.factor = factor; this.basedOnPreviousValue = basedOnPreviousValue; } public void validate() { Objects.requireNonNull(this.firstBackoff, "firstBackoff must be present"); } public Duration getFirstBackoff() { return firstBackoff; } public void setFirstBackoff(Duration firstBackoff) { this.firstBackoff = firstBackoff; } public @Nullable Duration getMaxBackoff() { return maxBackoff; } public void setMaxBackoff(Duration maxBackoff) { this.maxBackoff = maxBackoff; } public int getFactor() { return factor; } public void setFactor(int factor) { this.factor = factor; } public boolean isBasedOnPreviousValue() { return basedOnPreviousValue; } public void setBasedOnPreviousValue(boolean basedOnPreviousValue) { this.basedOnPreviousValue = basedOnPreviousValue; } @Override public String toString() { return new ToStringCreator(this).append("firstBackoff", firstBackoff) .append("maxBackoff", maxBackoff) .append("factor", factor)
.append("basedOnPreviousValue", basedOnPreviousValue) .toString(); } } public static class JitterConfig { private double randomFactor = 0.5; public void validate() { Assert.isTrue(randomFactor >= 0 && randomFactor <= 1, "random factor must be between 0 and 1 (default 0.5)"); } public JitterConfig() { } public JitterConfig(double randomFactor) { this.randomFactor = randomFactor; } public double getRandomFactor() { return randomFactor; } public void setRandomFactor(double randomFactor) { this.randomFactor = randomFactor; } @Override public String toString() { return new ToStringCreator(this).append("randomFactor", randomFactor).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java
2
请完成以下Java代码
public class MyRepoJdbc extends BaseRepo { static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private HikariDataSource ds; private SplittableRandom random = new SplittableRandom(); public MyRepoJdbc(boolean readOnly, boolean autocommit) { HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://localhost/baeldung?useUnicode=true&characterEncoding=UTF-8"); config.setUsername("baeldung"); config.setPassword("baeldung"); config.setReadOnly(readOnly); config.setAutoCommit(autocommit); ds = new HikariDataSource(config); } private Connection getConnection() throws SQLException { return ds.getConnection(); } public long runQuery(Boolean autoCommit, Boolean readOnly) { try { return execQuery(count -> runSql(count, autoCommit, readOnly));
} finally { ds.close(); } } private void runSql(AtomicLong count, Boolean autoCommit, Boolean readOnly) { if (Thread.interrupted()) { return; } try (Connection connect = getConnection(); PreparedStatement statement = connect.prepareStatement("select * from transactions where id = ?")) { if (autoCommit != null) connect.setAutoCommit(autoCommit); if (readOnly != null) connect.setReadOnly(readOnly); statement.setLong(1, 1L + random.nextLong(0, 100000)); ResultSet resultSet = statement.executeQuery(); if (autoCommit != null && !autoCommit) connect.commit(); count.incrementAndGet(); resultSet.close(); } catch (Exception ignored) { } } }
repos\tutorials-master\persistence-modules\read-only-transactions\src\main\java\com\baeldung\readonlytransactions\mysql\dao\MyRepoJdbc.java
1
请在Spring Boot框架中完成以下Java代码
public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; }
public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java
2
请完成以下Spring Boot application配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/myDb spring.datasource.username=root spring.datasource.password=root spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect spring.jpa.hibernate.ddl-auto=none spring.jpa.properties.hibernate.temp.use_jdbc_metadata_
defaults=false h2.datasource.url=jdbc:h2:mem:testdb h2.datasource.driver-class-name=org.h2.Driver h2.datasource.username=sa h2.datasource.password=
repos\tutorials-master\spring-boot-modules\spring-boot-data-3\src\main\resources\application.properties
2
请完成以下Java代码
private static final class TableColumnInfo2TableColumnExtSynchronizer implements PropertyChangeListener { private final WeakReference<TableColumnExt> columnExtRef; private boolean running = false; public TableColumnInfo2TableColumnExtSynchronizer(final TableColumnExt columnExt) { super(); columnExtRef = new WeakReference<>(columnExt); } private TableColumnExt getTableColumnExt() { return columnExtRef.getValue(); } @Override public void propertyChange(final PropertyChangeEvent evt) { // Avoid recursion if (running) { return; }
running = true; try { final TableColumnInfo columnMetaInfo = (TableColumnInfo)evt.getSource(); final TableColumnExt columnExt = getTableColumnExt(); if (columnExt == null) { // ColumnExt reference expired: // * remove this listener because there is no point to have this listener invoked in future // * exit quickly because there is nothing to do columnMetaInfo.removePropertyChangeListener(this); return; } updateColumnExtFromMetaInfo(columnExt, columnMetaInfo); } finally { running = false; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableColumnFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class BookstoreService { private final AuthorRepository authorRepository; private final BookRepository bookRepository; public BookstoreService(AuthorRepository authorRepository, BookRepository bookRepository) { this.authorRepository = authorRepository; this.bookRepository = bookRepository; } @Transactional public void newBookOfAuthor() { Author author = authorRepository.findById(1L).orElseThrow();
Book book = new Book(); book.setTitle("A History of Ancient Prague"); book.setIsbn("001-JN"); // this will set the id of the book as the id of the author book.setAuthor(author); bookRepository.save(book); } @Transactional(readOnly = true) public Book fetchBookByAuthorId() { Author author = authorRepository.findById(1L).orElseThrow(); return bookRepository.findById(author.getId()).orElseThrow(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOneToOneMapsId\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public int getPort() { return this.port; } @Override public void setPort(int port) { this.port = port; this.isEphemeral = port == 0; } @Override public void destroy() { stop(); } @Override public void afterPropertiesSet() { start(); } @Override public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException { this.context = (ConfigurableApplicationContext) applicationContext; } @Override public void start() { if (isRunning()) { return; } try { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(this.defaultPartitionSuffix); config.addAdditionalBindCredentials("uid=admin,ou=system", "secret"); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", this.port)); config.setEnforceSingleStructuralObjectClass(false); config.setEnforceAttributeSyntaxCompliance(true); DN dn = new DN(this.defaultPartitionSuffix); Entry entry = new Entry(dn); entry.addAttribute("objectClass", "top", "domain", "extensibleObject"); entry.addAttribute("dc", dn.getRDN().getAttributeValues()[0]); InMemoryDirectoryServer directoryServer = new InMemoryDirectoryServer(config); directoryServer.add(entry); importLdif(directoryServer); directoryServer.startListening(); this.port = directoryServer.getListenPort(); this.directoryServer = directoryServer; this.running = true; }
catch (LDAPException ex) { throw new RuntimeException("Server startup failed", ex); } } private void importLdif(InMemoryDirectoryServer directoryServer) { if (StringUtils.hasText(this.ldif)) { try { Resource[] resources = this.context.getResources(this.ldif); if (resources.length > 0) { if (!resources[0].exists()) { throw new IllegalArgumentException("Unable to find LDIF resource " + this.ldif); } try (InputStream inputStream = resources[0].getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } } @Override public void stop() { if (this.isEphemeral && this.context != null && !this.context.isClosed()) { return; } this.directoryServer.shutDown(true); this.running = false; } @Override public boolean isRunning() { return this.running; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\server\UnboundIdContainer.java
1
请完成以下Java代码
protected String createRedirectUrl(String serviceUrl) { return CommonUtils.constructRedirectUrl(this.loginUrl, this.serviceProperties.getServiceParameter(), serviceUrl, this.serviceProperties.isSendRenew(), false); } /** * Template method for you to do your own pre-processing before the redirect occurs. * @param request the HttpServletRequest * @param response the HttpServletResponse */ protected void preCommence(HttpServletRequest request, HttpServletResponse response) { } /** * The enterprise-wide CAS login URL. Usually something like * <code>https://www.mycompany.com/cas/login</code>. * @return the enterprise-wide CAS login URL */ public final @Nullable String getLoginUrl() { return this.loginUrl; } public final ServiceProperties getServiceProperties() { return this.serviceProperties; } public final void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public final void setServiceProperties(ServiceProperties serviceProperties) { this.serviceProperties = serviceProperties; } /** * Sets whether to encode the service url with the session id or not. * @param encodeServiceUrlWithSessionId whether to encode the service url with the * session id or not. */
public final void setEncodeServiceUrlWithSessionId(boolean encodeServiceUrlWithSessionId) { this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; } /** * Sets whether to encode the service url with the session id or not. * @return whether to encode the service url with the session id or not. * */ protected boolean getEncodeServiceUrlWithSessionId() { return this.encodeServiceUrlWithSessionId; } /** * Sets the {@link RedirectStrategy} to use * @param redirectStrategy the {@link RedirectStrategy} to use * @since 6.3 */ public void setRedirectStrategy(RedirectStrategy redirectStrategy) { Assert.notNull(redirectStrategy, "redirectStrategy cannot be null"); this.redirectStrategy = redirectStrategy; } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasAuthenticationEntryPoint.java
1
请完成以下Java代码
public List<CaseExecutionDto> getCaseExecutions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryCaseExecutions(queryDto, firstResult, maxResults); } @Override public List<CaseExecutionDto> queryCaseExecutions(CaseExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); CaseExecutionQuery query = queryDto.toQuery(engine); List<CaseExecution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults); List<CaseExecutionDto> executionResults = new ArrayList<CaseExecutionDto>(); for (CaseExecution execution : matchingExecutions) { CaseExecutionDto resultExecution = CaseExecutionDto.fromCaseExecution(execution); executionResults.add(resultExecution); } return executionResults; }
@Override public CountResultDto getCaseExecutionsCount(UriInfo uriInfo) { CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); return queryCaseExecutionsCount(queryDto); } @Override public CountResultDto queryCaseExecutionsCount(CaseExecutionQueryDto queryDto) { ProcessEngine engine = getProcessEngine(); queryDto.setObjectMapper(getObjectMapper()); CaseExecutionQuery query = queryDto.toQuery(engine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseExecutionRestServiceImpl.java
1
请完成以下Java代码
final class SortedSetReactiveRedisSessionExpirationStore { private final ReactiveRedisOperations<String, Object> sessionRedisOperations; private String namespace; private int retrieveCount = 100; SortedSetReactiveRedisSessionExpirationStore(ReactiveRedisOperations<String, Object> sessionRedisOperations, String namespace) { Assert.notNull(sessionRedisOperations, "sessionRedisOperations cannot be null"); Assert.hasText(namespace, "namespace cannot be null or empty"); this.sessionRedisOperations = sessionRedisOperations; this.namespace = namespace; } /** * Add the session id associated with the expiration time into the sorted set. * @param sessionId the session id * @param expiration the expiration time * @return a {@link Mono} that completes when the operation completes */ Mono<Void> add(String sessionId, Instant expiration) { long expirationInMillis = expiration.toEpochMilli(); return this.sessionRedisOperations.opsForZSet().add(getExpirationsKey(), sessionId, expirationInMillis).then(); } /** * Remove the session id from the sorted set. * @param sessionId the session id * @return a {@link Mono} that completes when the operation completes */ Mono<Void> remove(String sessionId) { return this.sessionRedisOperations.opsForZSet().remove(getExpirationsKey(), sessionId).then(); } /** * Retrieve the session ids that have the expiration time less than the value passed
* in {@code expiredBefore}. * @param expiredBefore the expiration time * @return a {@link Flux} that emits the session ids */ Flux<String> retrieveExpiredSessions(Instant expiredBefore) { Range<Double> range = Range.closed(0D, (double) expiredBefore.toEpochMilli()); Limit limit = Limit.limit().count(this.retrieveCount); return this.sessionRedisOperations.opsForZSet() .reverseRangeByScore(getExpirationsKey(), range, limit) .cast(String.class); } private String getExpirationsKey() { return this.namespace + "sessions:expirations"; } /** * Set the namespace for the keys used by this class. * @param namespace the namespace */ void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be null or empty"); this.namespace = namespace; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetReactiveRedisSessionExpirationStore.java
1
请完成以下Java代码
public void setId(int id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); long temp; temp = Double.doubleToLongBits(price); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false;
if (getClass() != obj.getClass()) return false; Product other = (Product) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) return false; return true; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\model\Product.java
1
请在Spring Boot框架中完成以下Java代码
public class Oauth2AuthorizationTokenConfig { /** * 声明 内存 TokenStore 实现,用来存储 token 相关. * 默认实现有 mysql、redis * * @return InMemoryTokenStore */ @Bean @Primary public TokenStore tokenStore() { return new InMemoryTokenStore(); } /** * jwt 令牌 配置,非对称加密 * * @return 转换器 */ @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { final JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter(); accessTokenConverter.setKeyPair(keyPair()); return accessTokenConverter; }
/** * 密钥 keyPair. * 可用于生成 jwt / jwk. * * @return keyPair */ @Bean public KeyPair keyPair() { KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("oauth2.jks"), "123456".toCharArray()); return keyStoreKeyFactory.getKeyPair("oauth2"); } /** * 加密方式,使用 BCrypt. * 参数越大加密次数越多,时间越久. * 默认为 10. * * @return PasswordEncoder */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\config\Oauth2AuthorizationTokenConfig.java
2
请完成以下Java代码
private void saveRpcResponseToEdgeQueue(TbContext ctx, TbMsg msg, String serviceIdStr, String sessionIdStr, String requestIdStr) { EdgeId edgeId; DeviceId deviceId; try { edgeId = new EdgeId(UUID.fromString(msg.getMetaData().getValue(DataConstants.EDGE_ID))); deviceId = new DeviceId(UUID.fromString(msg.getMetaData().getValue(DataConstants.DEVICE_ID))); } catch (Exception e) { String errMsg = String.format("[%s] Failed to parse edgeId or deviceId from metadata %s!", ctx.getTenantId(), msg.getMetaData()); ctx.tellFailure(msg, new RuntimeException(errMsg)); return; } ObjectNode body = JacksonUtil.newObjectNode(); body.put("serviceId", serviceIdStr); body.put("sessionId", sessionIdStr); body.put("requestId", requestIdStr); body.put("response", msg.getData());
EdgeEvent edgeEvent = EdgeUtils.constructEdgeEvent(ctx.getTenantId(), edgeId, EdgeEventType.DEVICE, EdgeEventActionType.RPC_CALL, deviceId, JacksonUtil.valueToTree(body)); ListenableFuture<Void> future = ctx.getEdgeEventService().saveAsync(edgeEvent); Futures.addCallback(future, new FutureCallback<>() { @Override public void onSuccess(Void result) { ctx.tellSuccess(msg); } @Override public void onFailure(@NonNull Throwable t) { ctx.tellFailure(msg, t); } }, ctx.getDbCallbackExecutor()); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\rpc\TbSendRPCReplyNode.java
1
请完成以下Java代码
public Builder setFacetFilter(final boolean facetFilter) { this.facetFilter = facetFilter; return this; } public boolean hasParameters() { return !parameters.isEmpty(); } public Builder addParameter(final DocumentFilterParamDescriptor.Builder parameter) { parameters.add(parameter); return this; } public Builder addInternalParameter(final String parameterName, final Object constantValue) { return addInternalParameter(DocumentFilterParam.ofNameEqualsValue(parameterName, constantValue)); }
public Builder addInternalParameter(final DocumentFilterParam parameter) { internalParameters.add(parameter); return this; } public Builder putDebugProperty(final String name, final Object value) { Check.assumeNotEmpty(name, "name is not empty"); if (debugProperties == null) { debugProperties = new LinkedHashMap<>(); } debugProperties.put("debug-" + name, value); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
private PropertyResolver getPropertyResolver(ConditionContext context) { return context.getEnvironment(); } private List<String> collectPropertyNames(AnnotationAttributes annotationAttributes) { String prefix = getPrefix(annotationAttributes); String[] names = getNames(annotationAttributes); return Arrays.stream(names).map(name -> prefix + name).collect(Collectors.toList()); } private String[] getNames(AnnotationAttributes annotationAttributes) { String[] names = annotationAttributes.getStringArray("name"); String[] values = annotationAttributes.getStringArray("value"); Assert.isTrue(names.length > 0 || values.length > 0, String.format("The name or value attribute of @%s is required", ConditionalOnMissingProperty.class.getSimpleName())); // TODO remove; not needed when using @AliasFor. /* Assert.isTrue(names.length * values.length == 0, String.format("The name and value attributes of @%s are exclusive", ConditionalOnMissingProperty.class.getSimpleName())); */ return names.length > 0 ? names : values; }
private String getPrefix(AnnotationAttributes annotationAttributes) { String prefix = annotationAttributes.getString("prefix"); return StringUtils.hasText(prefix) ? prefix.trim().endsWith(".") ? prefix.trim() : prefix.trim() + "." : ""; } private Collection<String> findMatchingProperties(PropertyResolver propertyResolver, List<String> propertyNames) { return propertyNames.stream().filter(propertyResolver::containsProperty).collect(Collectors.toSet()); } private ConditionOutcome determineConditionOutcome(Collection<String> matchingProperties) { if (!matchingProperties.isEmpty()) { return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingProperty.class) .found("property already defined", "properties already defined") .items(matchingProperties)); } return ConditionOutcome.match(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\condition\OnMissingPropertyCondition.java
2
请完成以下Java代码
public boolean isEmptyGroup() { return JSONMenuNodeType.group.equals(type) && (children == null || children.isEmpty()); } public static final class Builder { private final MenuNode node; private int maxDepth = Integer.MAX_VALUE; private int maxChildrenPerNode = Integer.MAX_VALUE; private int maxLeafNodes = Integer.MAX_VALUE; private MenuNodeFavoriteProvider menuNodeFavoriteProvider; private Builder(final MenuNode node) { this.node = node; } @Nullable public JSONMenuNode build() { final MutableInt maxLeafNodes = new MutableInt(this.maxLeafNodes); return newInstanceOrNull(node, maxDepth, maxChildrenPerNode, maxLeafNodes, menuNodeFavoriteProvider); } public Builder setMaxDepth(final int maxDepth) {
this.maxDepth = maxDepth > 0 ? maxDepth : Integer.MAX_VALUE; return this; } public Builder setMaxChildrenPerNode(final int maxChildrenPerNode) { this.maxChildrenPerNode = maxChildrenPerNode > 0 ? maxChildrenPerNode : Integer.MAX_VALUE; return this; } public Builder setMaxLeafNodes(final int maxLeafNodes) { this.maxLeafNodes = maxLeafNodes > 0 ? maxLeafNodes : Integer.MAX_VALUE; return this; } public Builder setIsFavoriteProvider(final MenuNodeFavoriteProvider menuNodeFavoriteProvider) { this.menuNodeFavoriteProvider = menuNodeFavoriteProvider; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\datatypes\json\JSONMenuNode.java
1
请完成以下Java代码
public Student mapRow(ResultSet rs, int rowNum) throws SQLException { var student = new Student(); student.setId(rs.getLong("id")); student.setName(rs.getString("name")); student.setPassportNumber(rs.getString("passport_number")); return student; } } public List<Student> findAll() { return jdbcTemplate.query(StudentQueries.getAllStudents(), new StudentRowMapper()); } public Student findById(long id) { return jdbcTemplate.queryForObject(StudentQueries.getAllStudentsById(), new BeanPropertyRowMapper<>(Student.class), id);
} public void deleteById(long id) { jdbcTemplate.update(StudentQueries.getDeleteStudentById(), id); } public int insert(Student student) { return jdbcTemplate.update(StudentQueries.getInsertStudent(), student.getId(), student.getName(), student.getPassportNumber()); } public int update(Student student) { return jdbcTemplate.update(StudentQueries.getUpdateStudent(), student.getName(), student.getPassportNumber(), student.getId()); } }
repos\spring-boot-examples-master\spring-boot-2-jdbc-with-h2\src\main\java\com\in28minutes\springboot\jdbc\h2\example\student\StudentJdbcTemplateRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class Student { @Id private int id; @Column(name = "full_name") private String fullName; @ManyToOne // switch these two lines to reproduce the exception // @Column(name = "university") @JoinColumn(name = "university_id") private University university; public int getId() { return id; } public void setId(int id) { this.id = id; }
public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public University getUniversity() { return university; } public void setUniversity(University university) { this.university = university; } }
repos\tutorials-master\persistence-modules\hibernate-exceptions-2\src\main\java\com\baeldung\hibernate\annotationexception\Student.java
2
请完成以下Java代码
public List<ProcessDefinition> getDeployedProcessDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class); } @Override public List<CaseDefinition> getDeployedCaseDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class); } @Override public List<DecisionDefinition> getDeployedDecisionDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class); } @Override public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class);
} @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", name=" + name + ", resources=" + resources + ", deploymentTime=" + deploymentTime + ", validatingSchema=" + validatingSchema + ", isNew=" + isNew + ", source=" + source + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java
1
请完成以下Java代码
public Map<String, Set<String>> getCustomUserIdentityLinks() { return customUserIdentityLinks; } public void setCustomUserIdentityLinks(Map<String, Set<String>> customUserIdentityLinks) { this.customUserIdentityLinks = customUserIdentityLinks; } public Map<String, Set<String>> getCustomGroupIdentityLinks() { return customGroupIdentityLinks; } public void setCustomGroupIdentityLinks(Map<String, Set<String>> customGroupIdentityLinks) { this.customGroupIdentityLinks = customGroupIdentityLinks; } public List<CustomProperty> getCustomProperties() { return customProperties; } public void setCustomProperties(List<CustomProperty> customProperties) { this.customProperties = customProperties; } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public UserTask clone() { UserTask clone = new UserTask(); clone.setValues(this); return clone; }
public void setValues(UserTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression()); setCandidateGroups(new ArrayList<String>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<String>(otherElement.getCandidateUsers())); setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks); setCustomUserIdentityLinks(otherElement.customUserIdentityLinks); formProperties = new ArrayList<FormProperty>(); if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) { for (FormProperty property : otherElement.getFormProperties()) { formProperties.add(property.clone()); } } taskListeners = new ArrayList<ActivitiListener>(); if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) { for (ActivitiListener listener : otherElement.getTaskListeners()) { taskListeners.add(listener.clone()); } } } @Override public void accept(ReferenceOverrider referenceOverrider) { referenceOverrider.override(this); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\UserTask.java
1
请在Spring Boot框架中完成以下Java代码
public void setNewValues(final I_AD_Sequence sequence) { Check.assumeNotNull(sequence, "sequence not null"); this.sequenceNameNew = sequence.getName(); this.currentNextNew = sequence.getCurrentNext(); this.currentNextSysNew = sequence.getCurrentNextSys(); this.newValuesSet = true; } public boolean isChange() { if (!newValuesSet) { return false; } if (newSequence) { return true; } if (!Objects.equals(this.sequenceName, this.sequenceNameNew)) { return true; } if (currentNext != currentNextNew) { return true; } if (currentNextSys != currentNextSysNew) { return true; } return false; } @Override public String toString() { final StringBuilder changes = new StringBuilder(); if (newValuesSet && !Objects.equals(sequenceName, sequenceNameNew)) { if (changes.length() > 0) { changes.append(", "); } changes.append("Name(new)=").append(sequenceNameNew); } if (newValuesSet && currentNext != currentNextNew) { if (changes.length() > 0) { changes.append(", "); }
changes.append("CurrentNext=").append(currentNext).append("->").append(currentNextNew); } if (newValuesSet && currentNextSys != currentNextSysNew) { if (changes.length() > 0) { changes.append(", "); } changes.append("CurrentNextSys=").append(currentNextSys).append("->").append(currentNextSysNew); } final StringBuilder sb = new StringBuilder(); sb.append("Sequence ").append(sequenceName); if (newSequence) { sb.append(" (new)"); } sb.append(": "); if (changes.length() > 0) { sb.append(changes); } else if (newSequence) { sb.append("just created"); } else { sb.append("no changes"); } return sb.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\TableSequenceChecker.java
2
请完成以下Java代码
private DataImportRunId getOrCreateDataImportRunId() { if (_dataImportRunId == null) { _dataImportRunId = dataImportRunService.createNewRun(DataImportRunCreateRequest.builder() .orgId(orgId) .userId(userId) .completeDocuments(completeDocuments) .importFormatId(importFormat.getId()) .dataImportConfigId(dataImportConfigId) .build()); } return _dataImportRunId; } private InsertIntoImportTableResult readSourceAndInsertIntoImportTable() { final ImpDataParser sourceParser = parserFactory.createParser(importFormat); final InsertIntoImportTableRequest request = InsertIntoImportTableRequest.builder() .importFormat(importFormat) .clientId(clientId) .orgId(orgId) .userId(userId) .dataImportRunId(getOrCreateDataImportRunId()) .dataImportConfigId(dataImportConfigId) .insertBatchSize(getInsertBatchSize()) .stream(sourceParser.streamDataLines(data)) .build(); final InsertIntoImportTableResult result = insertIntoImportTableService.insertData(request) .withFromResource(extractURI(data)); logger.debug("Insert into import table result: {}", result); return result; } @Nullable private static URI extractURI(final Resource resource) { try { return resource.getURI(); } catch (IOException e) { return null; } } private int getInsertBatchSize() { return sysConfigBL.getIntValue(SYSCONFIG_InsertBatchSize, -1); }
private PInstanceId getOrCreateRecordsToImportSelectionId() { if (_recordsToImportSelectionId == null) { final ImportTableDescriptor importTableDescriptor = importFormat.getImportTableDescriptor(); final DataImportRunId dataImportRunId = getOrCreateDataImportRunId(); final IQuery<Object> query = queryBL.createQueryBuilder(importTableDescriptor.getTableName()) .addEqualsFilter(ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID, dataImportRunId) .addEqualsFilter(ImportTableDescriptor.COLUMNNAME_I_ErrorMsg, null) .create(); _recordsToImportSelectionId = query.createSelection(); if (_recordsToImportSelectionId == null) { throw new AdempiereException("No records to import for " + query); } } return _recordsToImportSelectionId; } private DataImportResult createResult() { final Duration duration = Duration.between(startTime, SystemTime.asInstant()); return DataImportResult.builder() .dataImportConfigId(dataImportConfigId) .duration(duration) // .insertIntoImportTable(insertIntoImportTableResult) .importRecordsValidation(validationResult) .actualImport(actualImportResult) .asyncImportResult(asyncImportResult) // .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportCommand.java
1
请在Spring Boot框架中完成以下Java代码
public class CollectionConfig { @Bean public CollectionsBean getCollectionsBean() { return new CollectionsBean(new HashSet<>(Arrays.asList("John", "Adam", "Harry"))); } @Bean public List<String> nameList(){ return Arrays.asList("John", "Adam", "Harry", null); } @Bean public Map<Integer, String> nameMap(){ Map<Integer, String> nameMap = new HashMap<>(); nameMap.put(1, "John"); nameMap.put(2, "Adam"); nameMap.put(3, "Harry"); return nameMap; } @Bean @Qualifier("CollectionsBean") @Order(2)
public BaeldungBean getElement() { return new BaeldungBean("John"); } @Bean @Order(3) public BaeldungBean getAnotherElement() { return new BaeldungBean("Adam"); } @Bean @Order(1) public BaeldungBean getOneMoreElement() { return new BaeldungBean("Harry"); } }
repos\tutorials-master\spring-di-2\src\main\java\com\baeldung\collection\CollectionConfig.java
2
请完成以下Java代码
public IAttributeSetInstanceAware getM_Product() { return attributeSetInstanceAware; } public I_C_UOM getC_UOM() { return uom; } public BigDecimal getQty() { return qty; } public Timestamp getDateOrdered() { return dateOrdered; } /** * @return locator where Quantity currently is */ public I_M_Locator getM_Locator() { return locator; } public DistributionNetworkLine getDD_NetworkDistributionLine() { loadIfNeeded(); return networkLine; } public ResourceId getRawMaterialsPlantId() { loadIfNeeded(); return rawMaterialsPlantId; } public I_M_Warehouse getRawMaterialsWarehouse() { loadIfNeeded(); return rawMaterialsWarehouse; }
public I_M_Locator getRawMaterialsLocator() { loadIfNeeded(); return rawMaterialsLocator; } public OrgId getOrgId() { loadIfNeeded(); return orgId; } public BPartnerLocationId getOrgBPLocationId() { loadIfNeeded(); return orgBPLocationId; } public UserId getPlannerId() { loadIfNeeded(); return productPlanning == null ? null : productPlanning.getPlannerId(); } public WarehouseId getInTransitWarehouseId() { loadIfNeeded(); return inTransitWarehouseId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\process\RawMaterialsReturnDDOrderLineCandidate.java
1
请完成以下Java代码
public class BaseFeatureData { /** * 样本数量 */ public int n; /** * 一个特征在类目中分别出现几次(键是特征,值的键是类目) */ public int[][] featureCategoryJointCount; /** * 每个类目中的文档数量 */ public int[] categoryCounts; /** * 新的特征映射表 */ public BinTrie<Integer> wordIdTrie;
/** * 构造一个空白的统计对象 */ public BaseFeatureData(IDataSet dataSet) { Catalog catalog = dataSet.getCatalog(); Lexicon lexicon = dataSet.getLexicon(); n = dataSet.size(); featureCategoryJointCount = new int[lexicon.size()][catalog.size()]; categoryCounts = new int[catalog.size()]; // 执行统计 for (Document document : dataSet) { ++categoryCounts[document.category]; for (Map.Entry<Integer, int[]> entry : document.tfMap.entrySet()) { featureCategoryJointCount[entry.getKey()][document.category] += 1; } } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\features\BaseFeatureData.java
1
请完成以下Java代码
public class DmnElementReferenceImpl extends DmnModelElementInstanceImpl implements DmnElementReference { protected static Attribute<String> hrefAttribute; public DmnElementReferenceImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getHref() { return hrefAttribute.getValue(this); } public void setHref(String href) { hrefAttribute.setValue(this, href); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DmnElementReference.class, DMN_ELEMENT_REFERENCE)
.namespaceUri(LATEST_DMN_NS) .instanceProvider(new ModelTypeInstanceProvider<DmnElementReference>() { public DmnElementReference newInstance(ModelTypeInstanceContext instanceContext) { return new DmnElementReferenceImpl(instanceContext); } }); hrefAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_HREF) .required() .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DmnElementReferenceImpl.java
1
请完成以下Java代码
public String getType() { return type; } @Override public void setType(String type) { this.type = type; } @Override public String getUserId() { return userId; } @Override public void setUserId(String userId) { this.userId = userId; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getValue() { return value; } @Override public void setValue(String value) { this.value = value; } @Override public byte[] getPasswordBytes() { return passwordBytes; } @Override public void setPasswordBytes(byte[] passwordBytes) { this.passwordBytes = passwordBytes; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public String getName() { return key;
} @Override public String getUsername() { return value; } @Override public String getParentId() { return parentId; } @Override public void setParentId(String parentId) { this.parentId = parentId; } @Override public Map<String, String> getDetails() { return details; } @Override public void setDetails(Map<String, String> details) { this.details = details; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\IdentityInfoEntityImpl.java
1
请完成以下Java代码
private ShipperId getPartnerShipperId(@NonNull final BPartnerId partnerId) { return partnerDAO.getShipperId(partnerId); } @Override public PaymentTermId getPaymentTermId(@NonNull final I_C_Order orderRecord) { return PaymentTermId.ofRepoId(orderRecord.getC_PaymentTerm_ID()); } @Override public Money getGrandTotal(@NonNull final I_C_Order order) { final BigDecimal grandTotal = order.getGrandTotal(); return Money.of(grandTotal, CurrencyId.ofRepoId(order.getC_Currency_ID())); } @Override public void save(final I_C_Order order) { orderDAO.save(order); } @Override public void syncDatesFromTransportOrder(@NonNull final OrderId orderId, @NonNull final I_M_ShipperTransportation transportOrder) { final I_C_Order order = getById(orderId); order.setBLDate(transportOrder.getBLDate()); order.setETA(transportOrder.getETA());
save(order); } @Override public void syncDateInvoicedFromInvoice(@NonNull final OrderId orderId, @NonNull final I_C_Invoice invoice) { final I_C_Order order = getById(orderId); order.setInvoiceDate(invoice.getDateInvoiced()); save(order); } public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter) { return orderDAO.getByQueryFilter(queryFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderBL.java
1
请完成以下Java代码
private static void discardAllLinesFromSameGroupIfIncomplete(@NonNull final DeliveryLineCandidate deliveryLineCandidate) { if (CompleteStatus.OK.equals(deliveryLineCandidate.getCompleteStatus())) { return; } try (final IAutoCloseable shipmentScheduleMDCRestorer = ShipmentSchedulesMDC.removeCurrentShipmentScheduleId()) { for (final DeliveryLineCandidate candidateOfGroup : deliveryLineCandidate.getGroup().getLines()) { try (final MDCCloseable shipmentScheduleOfGroupMDC = ShipmentSchedulesMDC.putShipmentScheduleId(candidateOfGroup.getShipmentScheduleId())) { logger.debug("Discard this lineCandidate because candidate with ShipmentScheduleId={} is in same group and has completeStatus={}", deliveryLineCandidate.getShipmentScheduleId().getRepoId(), deliveryLineCandidate.getCompleteStatus()); candidateOfGroup.setQtyToDeliver(BigDecimal.ZERO); candidateOfGroup.setDiscarded(); // update the status to show why we set the quantity to zero candidateOfGroup.setCompleteStatus(CompleteStatus.INCOMPLETE_ORDER); } } } } @Override public DeliveryLineCandidate getLineCandidateForShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId) { return deliveryLineCandidatesByShipmentScheduleId.get(shipmentScheduleId); } @Override public void addStatusInfo(final DeliveryLineCandidate inOutLine, final String string) { StringBuilder currentInfos = line2StatusInfo.get(inOutLine); boolean firstInfo = false; if (currentInfos == null) { currentInfos = new StringBuilder(); line2StatusInfo.put(inOutLine, currentInfos); firstInfo = true; } if (!firstInfo) { currentInfos.append("; "); } currentInfos.append(string); } @Override public String getStatusInfos(final DeliveryLineCandidate inOutLine) {
final StringBuilder statusInfos = line2StatusInfo.get(inOutLine); if (statusInfos == null) { return ""; } return statusInfos.toString(); } public ImmutableList<DeliveryLineCandidate> getAllLines() { return ImmutableList.copyOf(deliveryLineCandidates); } @Value private static class ShipperKey { public static ShipperKey of(final Optional<ShipperId> shipperId, final WarehouseId warehouseId, final String bpartnerAddress) { return new ShipperKey(bpartnerAddress, warehouseId, shipperId.orElse(null)); } String bpartnerAddress; WarehouseId warehouseId; ShipperId shipperId; } @Value private static class OrderKey { public static OrderKey of( final DeliveryGroupCandidateGroupId groupId, final WarehouseId warehouseId, final String bpartnerAddress) { return new OrderKey(bpartnerAddress, warehouseId, groupId); } String bpartnerAddress; WarehouseId warehouseId; DeliveryGroupCandidateGroupId groupId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentSchedulesDuringUpdate.java
1
请完成以下Java代码
public void iterateUsingCollections(final List<String> list) { Collections.reverse(list); for (final String item : list) { System.out.println(item); } } /** * Iterate using Apache Commons {@link ReverseListIterator}. * * @param list the list */ public void iterateUsingApacheReverseListIterator(final List<String> list) { final ReverseListIterator listIterator = new ReverseListIterator(list); while (listIterator.hasNext()) { System.out.println(listIterator.next());
} } /** * Iterate using Guava {@link Lists} API. * * @param list the list */ public void iterateUsingGuava(final List<String> list) { final List<String> reversedList = Lists.reverse(list); for (final String item : reversedList) { System.out.println(item); } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\ReverseIterator.java
1
请完成以下Java代码
public class AuthorClassDto { private String genre; private String name; public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { int hash = 5; hash = 61 * hash + Objects.hashCode(this.genre); hash = 61 * hash + Objects.hashCode(this.name); return hash; } @Override public boolean equals(Object obj) {
if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorClassDto other = (AuthorClassDto) obj; if (!Objects.equals(this.genre, other.genre)) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return true; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNestedVsVirtualProjection\src\main\java\com\bookstore\dto\AuthorClassDto.java
1
请完成以下Java代码
public Set<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return values.getViewEditorRenderModeByFieldName(); } public BPartnerId getBPartnerId() {
return bpartner.getIdAs(BPartnerId::ofRepoId); } public InvoiceRow withPreparedForAllocationSet() { return withPreparedForAllocation(true); } public InvoiceRow withPreparedForAllocationUnset() { return withPreparedForAllocation(false); } public InvoiceRow withPreparedForAllocation(final boolean isPreparedForAllocation) { return this.isPreparedForAllocation != isPreparedForAllocation ? toBuilder().isPreparedForAllocation(isPreparedForAllocation).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRow.java
1
请完成以下Java代码
public long getInit() { return this.memoryUsage.getInit(); } public long getUsed() { return this.memoryUsage.getUsed(); } public long getCommitted() { return this.memoryUsage.getCommitted(); } public long getMax() { return this.memoryUsage.getMax(); } } /** * Garbage collection information. * * @since 3.5.0 */ public static class GarbageCollectorInfo {
private final String name; private final long collectionCount; GarbageCollectorInfo(GarbageCollectorMXBean garbageCollectorMXBean) { this.name = garbageCollectorMXBean.getName(); this.collectionCount = garbageCollectorMXBean.getCollectionCount(); } public String getName() { return this.name; } public long getCollectionCount() { return this.collectionCount; } } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\ProcessInfo.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDateMoved() { if (previousTime == null) { return false; } return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate)); } public boolean isDateMovedForwards() { if (previousTime == null) { return false; } return previousTime.isBefore(DateAndSeqNo.ofCandidate(candidate)); } /** * @return {@code true} there was no record before the save, or the record's date was changed. */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isDateChanged() { if (previousTime == null) { return true; } return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate)); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isQtyChanged() { return getQtyDelta().signum() != 0; } // TODO figure out if we really need this public Candidate toCandidateWithQtyDelta() { return candidate.withQuantity(getQtyDelta()); } /** * Convenience method that returns a new instance whose included {@link Candidate} has the given id. */ public CandidateSaveResult withCandidateId(@Nullable final CandidateId candidateId) {
return toBuilder() .candidate(candidate.withId(candidateId)) .build(); } /** * Convenience method that returns a new instance with negated candidate quantity and previousQty */ public CandidateSaveResult withNegatedQuantity() { return toBuilder() .candidate(candidate.withNegatedQuantity()) .previousQty(previousQty == null ? null : previousQty.negate()) .build(); } public CandidateSaveResult withParentId(@Nullable final CandidateId parentId) { return toBuilder() .candidate(candidate.withParentId(parentId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateSaveResult.java
2
请完成以下Java代码
public class Country { @SerializedName(value = "name") private String countryName; @SerializedName(value = "capital") private String countryCapital; @SerializedName(value = "continent") private String continentName; public Country(String countryName, String countryCapital, String continentName) { this.countryName = countryName; this.countryCapital = countryCapital; this.continentName = continentName; } @Override public String toString() { return "Country{" + "countryName='" + countryName + '\'' + ", countryCapital='" + countryCapital + '\'' + ", continentName='" + continentName + '\'' + '}'; } public String getCountryName() { return countryName; }
public void setCountryName(String countryName) { this.countryName = countryName; } public String getCountryCapital() { return countryCapital; } public void setCountryCapital(String countryCapital) { this.countryCapital = countryCapital; } public String getContinentName() { return continentName; } public void setContinentName(String continentName) { this.continentName = continentName; } }
repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\entities\Country.java
1
请在Spring Boot框架中完成以下Java代码
public static ItemMetadata newGroup(String name, String type, String sourceType, String sourceMethod) { return new ItemMetadata(ItemType.GROUP, name, null, type, sourceType, sourceMethod, null, null, null); } public static ItemMetadata newProperty(String prefix, String name, String type, String sourceType, String sourceMethod, String description, Object defaultValue, ItemDeprecation deprecation) { return new ItemMetadata(ItemType.PROPERTY, prefix, name, type, sourceType, sourceMethod, description, defaultValue, deprecation); } public static String newItemMetadataPrefix(String prefix, String suffix) { return prefix.toLowerCase(Locale.ENGLISH) + ConventionUtils.toDashedCase(suffix); } /** * The item type.
*/ public enum ItemType { /** * Group item type. */ GROUP, /** * Property item type. */ PROPERTY } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemMetadata.java
2
请完成以下Java代码
public String getF_NAME() { return F_NAME; } public void setF_NAME(String f_NAME) { F_NAME = f_NAME; } public String getF_PARENTID() { return F_PARENTID; } public void setF_PARENTID(String f_PARENTID) { F_PARENTID = f_PARENTID; } public String getF_FINANCIAL() { return F_FINANCIAL; } public void setF_FINANCIAL(String f_FINANCIAL) { F_FINANCIAL = f_FINANCIAL; } public String getF_CONTACTMAN() { return F_CONTACTMAN; } public void setF_CONTACTMAN(String f_CONTACTMAN) { F_CONTACTMAN = f_CONTACTMAN; } public String getF_TEL() { return F_TEL; } public void setF_TEL(String f_TEL) { F_TEL = f_TEL; } public String getF_EMAIL() { return F_EMAIL; } public void setF_EMAIL(String f_EMAIL) { F_EMAIL = f_EMAIL; } public String getF_CANTONLEV() { return F_CANTONLEV; } public void setF_CANTONLEV(String f_CANTONLEV) { F_CANTONLEV = f_CANTONLEV; } public String getF_TAXORGCODE() { return F_TAXORGCODE; } public void setF_TAXORGCODE(String f_TAXORGCODE) { F_TAXORGCODE = f_TAXORGCODE; } public String getF_MEMO() { return F_MEMO; } public void setF_MEMO(String f_MEMO) { F_MEMO = f_MEMO; } public String getF_USING() { return F_USING; } public void setF_USING(String f_USING) { F_USING = f_USING; } public String getF_USINGDATE() { return F_USINGDATE; } public void setF_USINGDATE(String f_USINGDATE) {
F_USINGDATE = f_USINGDATE; } public Integer getF_LEVEL() { return F_LEVEL; } public void setF_LEVEL(Integer f_LEVEL) { F_LEVEL = f_LEVEL; } public String getF_END() { return F_END; } public void setF_END(String f_END) { F_END = f_END; } public String getF_QRCANTONID() { return F_QRCANTONID; } public void setF_QRCANTONID(String f_QRCANTONID) { F_QRCANTONID = f_QRCANTONID; } public String getF_DECLARE() { return F_DECLARE; } public void setF_DECLARE(String f_DECLARE) { F_DECLARE = f_DECLARE; } public String getF_DECLAREISEND() { return F_DECLAREISEND; } public void setF_DECLAREISEND(String f_DECLAREISEND) { F_DECLAREISEND = f_DECLAREISEND; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscCanton.java
1
请在Spring Boot框架中完成以下Java代码
public class TilesApplicationConfiguration implements WebMvcConfigurer { /** * Configure TilesConfigurer. */ @Bean public TilesConfigurer tilesConfigurer() { TilesConfigurer tilesConfigurer = new TilesConfigurer(); tilesConfigurer.setDefinitions("/WEB-INF/views/**/tiles.xml"); tilesConfigurer.setCheckRefresh(true); return tilesConfigurer; } /** * Configure ViewResolvers to deliver views. */ @Override
public void configureViewResolvers(ViewResolverRegistry registry) { TilesViewResolver viewResolver = new TilesViewResolver(); registry.viewResolver(viewResolver); } /** * Configure ResourceHandlers to serve static resources */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); } }
repos\tutorials-master\spring-web-modules\spring-mvc-views\src\main\java\com\baeldung\themes\config\TilesApplicationConfiguration.java
2
请完成以下Java代码
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 Macro. @param Macro Macro */ public void setMacro (String Macro) { set_Value (COLUMNNAME_Macro, Macro); } /** Get Macro. @return Macro */ public String getMacro () { return (String)get_Value(COLUMNNAME_Macro); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sql SELECT. @param SelectClause SQL SELECT clause */ public void setSelectClause (String SelectClause) { set_Value (COLUMNNAME_SelectClause, SelectClause); } /** Get Sql SELECT. @return SQL SELECT clause */ public String getSelectClause () { return (String)get_Value(COLUMNNAME_SelectClause);
} /** TokenType AD_Reference_ID=397 */ public static final int TOKENTYPE_AD_Reference_ID=397; /** SQL Command = Q */ public static final String TOKENTYPE_SQLCommand = "Q"; /** Internal Link = I */ public static final String TOKENTYPE_InternalLink = "I"; /** External Link = E */ public static final String TOKENTYPE_ExternalLink = "E"; /** Style = S */ public static final String TOKENTYPE_Style = "S"; /** Set TokenType. @param TokenType Wiki Token Type */ public void setTokenType (String TokenType) { set_Value (COLUMNNAME_TokenType, TokenType); } /** Get TokenType. @return Wiki Token Type */ public String getTokenType () { return (String)get_Value(COLUMNNAME_TokenType); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WikiToken.java
1
请完成以下Java代码
public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; }
public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public int hashCode() { return Objects.hash(city, email, firstName, id, lastName, phoneNumber, postalCode, state, street); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Customer)) { return false; } Customer other = (Customer) obj; return Objects.equals(city, other.city) && Objects.equals(email, other.email) && Objects.equals(firstName, other.firstName) && id == other.id && Objects.equals(lastName, other.lastName) && Objects.equals(phoneNumber, other.phoneNumber) && Objects.equals(postalCode, other.postalCode) && Objects.equals(state, other.state) && Objects.equals(street, other.street); } @Override public String toString() { return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", street=" + street + ", postalCode=" + postalCode + ", city=" + city + ", state=" + state + ", phoneNumber=" + phoneNumber + ", email=" + email + "]"; } public static Customer[] fromMockFile() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); InputStream jsonFile = new FileInputStream("src/test/resources/json_optimization_mock_data.json"); Customer[] feedback = objectMapper.readValue(jsonFile, Customer[].class); return feedback; } }
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\Customer.java
1
请完成以下Java代码
public <T> T mapInternalToJava(Object parameter, String typeIdentifier) { return mapInternalToJava(parameter, typeIdentifier, null); } @Override public <T> T mapInternalToJava(Object parameter, String typeIdentifier, DeserializationTypeValidator validator) { try { //sometimes the class identifier is at once a fully qualified class name final Class<?> aClass = Class.forName(typeIdentifier, true, Thread.currentThread().getContextClassLoader()); return (T) mapInternalToJava(parameter, aClass, validator); } catch (ClassNotFoundException e) { JavaType javaType = format.constructJavaTypeFromCanonicalString(typeIdentifier); T result = mapInternalToJava(parameter, javaType, validator); return result; } } public <C> C mapInternalToJava(Object parameter, JavaType type) { return mapInternalToJava(parameter, type, null); } public <C> C mapInternalToJava(Object parameter, JavaType type, DeserializationTypeValidator validator) { JsonNode jsonNode = (JsonNode) parameter; try { validateType(type, validator); ObjectMapper mapper = format.getObjectMapper(); return mapper.readValue(mapper.treeAsTokens(jsonNode), type); } catch (IOException | SpinRuntimeException e) { throw LOG.unableToDeserialize(jsonNode, type, e); } } /** * Validate the type with the help of the validator.<br> * Note: when adjusting this method, please also consider adjusting * the {@code AbstractVariablesResource#validateType} in the REST API */ protected void validateType(JavaType type, DeserializationTypeValidator validator) { if (validator != null) { List<String> invalidTypes = new ArrayList<>(); validateType(type, validator, invalidTypes); if (!invalidTypes.isEmpty()) {
throw new SpinRuntimeException("The following classes are not whitelisted for deserialization: " + invalidTypes); } } } protected void validateType(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { if (!type.isPrimitive()) { if (!type.isArrayType()) { validateTypeInternal(type, validator, invalidTypes); } if (type.isMapLikeType()) { validateType(type.getKeyType(), validator, invalidTypes); } if (type.isContainerType() || type.hasContentType()) { validateType(type.getContentType(), validator, invalidTypes); } } } protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) { String className = type.getRawClass().getName(); if (!validator.validate(className) && !invalidTypes.contains(className)) { invalidTypes.add(className); } } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormatMapper.java
1
请在Spring Boot框架中完成以下Java代码
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("com.baeldung.hibernate.cache.model"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } @Bean public DataSource dataSource() throws NamingException { return (DataSource) new JndiTemplate().lookup(env.getProperty("jdbc.url")); } @Bean public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { return new JpaTransactionManager(emf);
} @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-hibernate-5\src\main\java\com\baeldung\spring\PersistenceJNDIConfig.java
2
请完成以下Java代码
public void setName(String name) { this.name = name; } public void setResources(Map<String, ResourceEntity> resources) { this.resources = resources; } public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } public boolean isValidatingSchema() { return validatingSchema; } public void setValidatingSchema(boolean validatingSchema) { this.validatingSchema = validatingSchema; } public boolean isNew() { return isNew; } public void setNew(boolean isNew) { this.isNew = isNew; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } @Override public List<ProcessDefinition> getDeployedProcessDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class); } @Override public List<CaseDefinition> getDeployedCaseDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class); } @Override public List<DecisionDefinition> getDeployedDecisionDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class); } @Override public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() { return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class); } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", name=" + name + ", resources=" + resources + ", deploymentTime=" + deploymentTime + ", validatingSchema=" + validatingSchema + ", isNew=" + isNew + ", source=" + source + ", tenantId=" + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java
1
请完成以下Java代码
public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { this.processInstanceQuery = processInstanceQuery; } public boolean isSkipIoMappings() { return skipIoMappings; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public void applyTo(ModificationBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) { for (ProcessInstanceModificationInstructionDto instruction : instructions) {
instruction.applyTo(builder, processEngine, objectMapper); } } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { this.historicProcessInstanceQuery = historicProcessInstanceQuery; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ModificationDto.java
1
请完成以下Java代码
public Tree build(String expression) throws TreeBuilderException { try { return createParser(expression).tree(); } catch (Scanner.ScanException e) { throw new TreeBuilderException(expression, e.position, e.encountered, e.expected, e.getMessage()); } catch (ParseException e) { throw new TreeBuilderException(expression, e.position, e.encountered, e.expected, e.getMessage()); } } protected Parser createParser(String expression) { return new Parser(this, expression); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != getClass()) { return false; } return features.equals(((Builder) obj).features); } @Override public int hashCode() { return getClass().hashCode(); } /** * Dump out abstract syntax tree for a given expression * * @param args array with one element, containing the expression string */ public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java " + Builder.class.getName() + " <expression string>"); System.exit(1); } PrintWriter out = new PrintWriter(System.out); Tree tree = null; try { tree = new Builder(Feature.METHOD_INVOCATIONS).build(args[0]); } catch (TreeBuilderException e) { System.out.println(e.getMessage());
System.exit(0); } NodePrinter.dump(out, tree.getRoot()); if (!tree.getFunctionNodes().iterator().hasNext() && !tree.getIdentifierNodes().iterator().hasNext()) { ELContext context = new ELContext() { @Override public VariableMapper getVariableMapper() { return null; } @Override public FunctionMapper getFunctionMapper() { return null; } @Override public ELResolver getELResolver() { return null; } }; out.print(">> "); try { out.println(tree.getRoot().getValue(new Bindings(null, null), context, null)); } catch (ELException e) { out.println(e.getMessage()); } } out.flush(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\Builder.java
1
请完成以下Java代码
public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority)); } return grantedAuthorities; } /** * Sets the prefix to use for {@link GrantedAuthority authorities} mapped by this * converter. Defaults to * {@link JwtGrantedAuthoritiesConverter#DEFAULT_AUTHORITY_PREFIX}. * @param authorityPrefix The authority prefix * @since 5.2 */ public void setAuthorityPrefix(String authorityPrefix) { Assert.notNull(authorityPrefix, "authorityPrefix cannot be null"); this.authorityPrefix = authorityPrefix; } /** * Sets the regex to use for splitting the value of the authorities claim into * {@link GrantedAuthority authorities}. Defaults to * {@link JwtGrantedAuthoritiesConverter#DEFAULT_AUTHORITIES_CLAIM_DELIMITER}. * @param authoritiesClaimDelimiter The regex used to split the authorities * @since 6.1 */ public void setAuthoritiesClaimDelimiter(String authoritiesClaimDelimiter) { Assert.notNull(authoritiesClaimDelimiter, "authoritiesClaimDelimiter cannot be null"); this.authoritiesClaimDelimiter = authoritiesClaimDelimiter; } /** * Sets the name of token claim to use for mapping {@link GrantedAuthority * authorities} by this converter. Defaults to * {@link JwtGrantedAuthoritiesConverter#WELL_KNOWN_AUTHORITIES_CLAIM_NAMES}. * @param authoritiesClaimName The token claim name to map authorities * @since 5.2 */ public void setAuthoritiesClaimName(String authoritiesClaimName) {
Assert.hasText(authoritiesClaimName, "authoritiesClaimName cannot be empty"); this.authoritiesClaimNames = Collections.singletonList(authoritiesClaimName); } private String getAuthoritiesClaimName(Jwt jwt) { for (String claimName : this.authoritiesClaimNames) { if (jwt.hasClaim(claimName)) { return claimName; } } return null; } private Collection<String> getAuthorities(Jwt jwt) { String claimName = getAuthoritiesClaimName(jwt); if (claimName == null) { this.logger.trace("Returning no authorities since could not find any claims that might contain scopes"); return Collections.emptyList(); } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for scopes in claim %s", claimName)); } Object authorities = jwt.getClaim(claimName); if (authorities instanceof String) { if (StringUtils.hasText((String) authorities)) { return Arrays.asList(((String) authorities).split(this.authoritiesClaimDelimiter)); } return Collections.emptyList(); } if (authorities instanceof Collection) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtGrantedAuthoritiesConverter.java
1