instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class FileEncodingApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered { private static final Log logger = LogFactory.getLog(FileEncodingApplicationListener.class); @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { ConfigurableEnvironment environment = event.getEnvironment(); String desired = environment.getProperty("spring.mandatory-file-encoding"); if (desired == null) { return; } String encoding = System.getProperty("file.encoding");
if (encoding != null && !desired.equalsIgnoreCase(encoding)) { if (logger.isErrorEnabled()) { logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired + "' (as defined in 'spring.mandatoryFileEncoding')."); logger.error("Environment variable LANG is '" + System.getenv("LANG") + "'. You could use a locale setting that matches encoding='" + desired + "'."); logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL") + "'. You could use a locale setting that matches encoding='" + desired + "'."); } throw new IllegalStateException("The Java Virtual Machine has not been configured to use the " + "desired default character encoding (" + desired + ")."); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\FileEncodingApplicationListener.java
1
请完成以下Java代码
public class ShipmentScheduleAndJobSchedulesCollection implements Iterable<ShipmentScheduleAndJobSchedules> { public static final ShipmentScheduleAndJobSchedulesCollection EMPTY = new ShipmentScheduleAndJobSchedulesCollection(ImmutableList.of()); private final ImmutableList<ShipmentScheduleAndJobSchedules> list; private ShipmentScheduleAndJobSchedulesCollection(final List<ShipmentScheduleAndJobSchedules> list) { this.list = list.stream() .sorted(comparing(ShipmentScheduleAndJobSchedules::getHeaderAggregationKey, nullsLast(naturalOrder())) .thenComparing(ShipmentScheduleAndJobSchedules::getShipmentScheduleId)) .collect(ImmutableList.toImmutableList()); Maps.uniqueIndex(this.list, ShipmentScheduleAndJobSchedules::getShipmentScheduleId); // avoid duplicates } public static ShipmentScheduleAndJobSchedulesCollection ofList(final List<ShipmentScheduleAndJobSchedules> list) { return list.isEmpty() ? EMPTY : new ShipmentScheduleAndJobSchedulesCollection(list); } public static ShipmentScheduleAndJobSchedulesCollection ofShipmentSchedules(final Collection<? extends de.metas.inoutcandidate.model.I_M_ShipmentSchedule> shipmentSchedules) { if (shipmentSchedules.isEmpty()) {return EMPTY;} return shipmentSchedules.stream() .map(ShipmentScheduleAndJobSchedules::ofShipmentSchedule) .collect(collect()); } public static Collector<ShipmentScheduleAndJobSchedules, ?, ShipmentScheduleAndJobSchedulesCollection> collect() { return GuavaCollectors.collectUsingListAccumulator(ShipmentScheduleAndJobSchedulesCollection::ofList); } public boolean isEmpty() {return list.isEmpty();} @Override public @NotNull Iterator<ShipmentScheduleAndJobSchedules> iterator() {return list.iterator();} public ImmutableSet<PickingJobScheduleId> getJobScheduleIds() { return list.stream()
.flatMap(schedule -> schedule.getJobScheduleIds().stream()) .collect(ImmutableSet.toImmutableSet()); } public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIdsWithoutJobSchedules() { return getShipmentScheduleIds(schedule -> !schedule.hasJobSchedules()); } public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIdsWithJobSchedules() { return getShipmentScheduleIds(ShipmentScheduleAndJobSchedules::hasJobSchedules); } public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds(@NonNull final Predicate<ShipmentScheduleAndJobSchedules> filter) { return list.stream() .filter(filter) .map(ShipmentScheduleAndJobSchedules::getShipmentScheduleId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleAndJobSchedulesCollection.java
1
请完成以下Java代码
public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) { this.nameLikeIgnoreCase = nameLikeIgnoreCase; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter;
} public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public void setInvolvedGroups(List<String> involvedGroups) { this.involvedGroups = involvedGroups; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java
1
请完成以下Java代码
public <S> S getService(ObjectName name) { return (S) servicesByName.get(name); } /** * get the service value for a specific service by name or null if no such * Service exists. * */ public <S> S getServiceValue(ObjectName name) { PlatformService<S> service = getService(name); if(service != null) { return service.getValue(); } else { return null; } } /** * get the service value for a specific service by name or null if no such * Service exists. * */ public <S> S getServiceValue(ServiceType type, String localName) { String globalName = composeLocalName(type, localName); ObjectName serviceName = getObjectName(globalName); return getServiceValue(serviceName); } /** * @return all services for a specific {@link ServiceType} */ @SuppressWarnings("unchecked") public <S> List<PlatformService<S>> getServicesByType(ServiceType type) { // query the MBeanServer for all services of the given type Set<String> serviceNames = getServiceNames(type); List<PlatformService<S>> res = new ArrayList<PlatformService<S>>(); for (String serviceName : serviceNames) { res.add((PlatformService<S>) servicesByName.get(getObjectName(serviceName))); } return res; } /** * @return the service names ( {@link ObjectName} ) for all services for a given type */ public Set<String> getServiceNames(ServiceType type) { String typeName = composeLocalName(type, "*"); ObjectName typeObjectName = getObjectName(typeName); Set<ObjectName> resultNames = getmBeanServer().queryNames(typeObjectName, null); Set<String> result= new HashSet<String>(); for (ObjectName objectName : resultNames) { result.add(objectName.toString()); } return result; } /** * @return the values of all services for a specific {@link ServiceType} */ @SuppressWarnings("unchecked") public <S> List<S> getServiceValuesByType(ServiceType type) { // query the MBeanServer for all services of the given type
Set<String> serviceNames = getServiceNames(type); List<S> res = new ArrayList<S>(); for (String serviceName : serviceNames) { PlatformService<S> BpmPlatformService = (PlatformService<S>) servicesByName.get(getObjectName(serviceName)); if (BpmPlatformService != null) { res.add(BpmPlatformService.getValue()); } } return res; } public MBeanServer getmBeanServer() { if (mBeanServer == null) { synchronized (this) { if (mBeanServer == null) { mBeanServer = createOrLookupMbeanServer(); } } } return mBeanServer; } public void setmBeanServer(MBeanServer mBeanServer) { this.mBeanServer = mBeanServer; } protected MBeanServer createOrLookupMbeanServer() { return ManagementFactory.getPlatformMBeanServer(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\MBeanServiceContainer.java
1
请完成以下Java代码
public int getCM_ChatType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Self-Service. @param IsSelfService This is a Self-Service entry or this entry can be changed via Self-Service */ public void setIsSelfService (boolean IsSelfService) { set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService)); }
/** Get Self-Service. @return This is a Self-Service entry or this entry can be changed via Self-Service */ public boolean isSelfService () { Object oo = get_Value(COLUMNNAME_IsSelfService); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatTypeUpdate.java
1
请完成以下Java代码
private ImmutableList<ShipmentScheduleAvailableStockDetail> getStockDetailsMatching(@NonNull final StockDataQuery query) { return stockDetails .stream() .filter(stockDetail -> matching(query, stockDetail)) .collect(ImmutableList.toImmutableList()); } private static boolean matching(final StockDataQuery query, final ShipmentScheduleAvailableStockDetail stockDetail) { // // Product if (!ProductId.equals(query.getProductId(), stockDetail.getProductId())) { return false; } // // Warehouse final Set<WarehouseId> queryWarehouseIds = query.getWarehouseIds();
if (!queryWarehouseIds.isEmpty() && !queryWarehouseIds.contains(stockDetail.getWarehouseId())) { return false; } // // Attributes final boolean queryMatchesAll = query.getStorageAttributesKey().isAll(); final boolean queryMatchesStockDetail = AttributesKey.equals(query.getStorageAttributesKey(), stockDetail.getStorageAttributesKey()); if (!queryMatchesAll && !queryMatchesStockDetail) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\ShipmentScheduleQtyOnHandStorage.java
1
请完成以下Java代码
public WindowId getWindowId() { throw new UnsupportedOperationException("windowId not available"); } @Override public void put(@NonNull final IView view) { views.put(view.getViewId(), view); } @Nullable @Override public IView getByIdOrNull(@NonNull final ViewId viewId) { return views.getIfPresent(viewId); } @Override public void closeById(@NonNull final ViewId viewId, @NonNull final ViewCloseAction closeAction) { // Don't remove the view if not allowed. // Will be removed when it will expire. final IView view = views.getIfPresent(viewId); if (view == null || !view.isAllowClosingPerUserRequest()) { return; } // // Notify the view that the user requested to be closed // IMPORTANT: fire this event before removing the view from storage. view.close(closeAction); // // Remove the view from storage // => will fire #onViewRemoved views.invalidate(viewId); views.cleanUp(); // also cleanup to prevent views cache to grow. } private void onViewRemoved(final RemovalNotification<Object, Object> notification) { final IView view = (IView)notification.getValue(); logger.debug("View `{}` removed from cache. Cause: {}", view.getViewId(), notification.getCause()); view.afterDestroy(); }
@Override public void invalidateView(final ViewId viewId) { final IView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); ViewChangesCollector.getCurrentOrAutoflush() .collectFullyChanged(view); } @Override public Stream<IView> streamAllViews() { return views.asMap().values().stream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\DefaultViewsRepositoryStorage.java
1
请完成以下Java代码
protected boolean doAppend(List<InstanceEvent> events) { if (events.isEmpty()) { return true; } InstanceId id = events.get(0).getInstance(); if (!events.stream().allMatch((event) -> event.getInstance().equals(id))) { throw new IllegalArgumentException("'events' must only refer to the same instance."); } List<InstanceEvent> oldEvents = eventLog.computeIfAbsent(id, (key) -> new ArrayList<>(maxLogSizePerAggregate + 1)); long lastVersion = getLastVersion(oldEvents); if (lastVersion >= events.get(0).getVersion()) { throw createOptimisticLockException(events.get(0), lastVersion); } List<InstanceEvent> newEvents = new ArrayList<>(oldEvents); newEvents.addAll(events); if (newEvents.size() > maxLogSizePerAggregate) { log.debug("Threshold for {} reached. Compacting events", id); compact(newEvents); } if (eventLog.replace(id, oldEvents, newEvents)) { log.debug("Events appended to log {}", events); return true; } log.debug("Unsuccessful attempt append the events {} ", events); return false;
} private void compact(List<InstanceEvent> events) { BinaryOperator<InstanceEvent> latestEvent = (e1, e2) -> (e1.getVersion() > e2.getVersion()) ? e1 : e2; Map<Class<?>, Optional<InstanceEvent>> latestPerType = events.stream() .collect(groupingBy(InstanceEvent::getClass, reducing(latestEvent))); events.removeIf((e) -> !Objects.equals(e, latestPerType.get(e.getClass()).orElse(null))); } private OptimisticLockingException createOptimisticLockException(InstanceEvent event, long lastVersion) { return new OptimisticLockingException( "Version " + event.getVersion() + " was overtaken by " + lastVersion + " for " + event.getInstance()); } protected static long getLastVersion(List<InstanceEvent> events) { return events.isEmpty() ? -1 : events.get(events.size() - 1).getVersion(); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\eventstore\ConcurrentMapEventStore.java
1
请完成以下Java代码
public Optional<UserId> resolveUserExternalIdentifier(@NonNull final OrgId orgId, @NonNull final ExternalIdentifier externalIdentifier) { if (ExternalIdentifier.Type.METASFRESH_ID.equals(externalIdentifier.getType())) { return Optional.of(UserId.ofRepoId(externalIdentifier.asMetasfreshId().getValue())); } else if (ExternalIdentifier.Type.EXTERNAL_REFERENCE.equals(externalIdentifier.getType())) { return externalReferenceService .resolveExternalReference(orgId, externalIdentifier, ExternalUserReferenceType.USER_ID) .map(jsonMetasfreshId -> UserId.ofRepoId(jsonMetasfreshId.getValue())); } else { throw new InvalidIdentifierException("Given ExternalIdentifier is not supported!") .appendParametersToMessage() .setParameter("ExternalIdentifier", externalIdentifier.getType()) .setParameter("RawValue", externalIdentifier.getRawValue()); } } public boolean isAutoInvoice(@NonNull final JsonOLCandCreateRequest request, @NonNull final BPartnerId bpartnerId) { if (request.getIsAutoInvoice() != null) { return request.getIsAutoInvoice(); } return bPartnerEffectiveBL.getById(bpartnerId).isAutoInvoice(SOTrx.SALES); } @Nullable
public Incoterms getIncoterms(@NonNull final JsonOLCandCreateRequest request, @NonNull final OrgId orgId, @NonNull final BPartnerId bPartnerId) { final Incoterms incoterms; if(request.getIncotermsValue() != null) { incoterms = incotermsRepository.getByValue(request.getIncotermsValue(), orgId); } else { incoterms = bPartnerEffectiveBL.getById(bPartnerId).getIncoterms(SOTrx.SALES); } if(incoterms == null) { return null; } return StringUtils.trimBlankToNull(request.getIncotermsLocation()) == null ? incoterms : incoterms.withLocationEffective(request.getIncotermsLocation()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\BPartnerMasterdataProvider.java
1
请完成以下Java代码
public Object getParameterValue(final int index, final boolean returnValueTo) { final Object field; if (returnValueTo) { field = getParameterToComponent(index); } else { field = getParameterComponent(index); } if (field instanceof CEditor) { final CEditor editor = (CEditor)field; return editor.getValue();
} else { throw new AdempiereException("Component type not supported - " + field); } } /** * Method called when one of the parameter fields changed */ protected void onFieldChanged() { // parent.executeQuery(); we don't want to query each time, because we might block the search } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\AbstractInfoQueryCriteriaGeneral.java
1
请完成以下Java代码
public ITranslatableString getSingleProductNameOrEmpty() { ProductId productId = null; ITranslatableString productName = TranslatableStrings.empty(); for (final PickingJobLine line : lines) { if (productId == null) { productId = line.getProductId(); } else if (!ProductId.equals(productId, line.getProductId())) { // found different products return TranslatableStrings.empty(); } productName = line.getProductName(); } return productName; } @Nullable public Quantity getSingleQtyToPickOrNull() { return extractQtyToPickOrNull(lines, PickingJobLine::getProductId, PickingJobLine::getQtyToPick); } @Nullable private static <T> Quantity extractQtyToPickOrNull( @NonNull final Collection<T> lines, @NonNull final Function<T, ProductId> extractProductId, @NonNull final Function<T, Quantity> extractQtyToPick) { ProductId productId = null; Quantity qtyToPick = null; for (final T line : lines) { final ProductId lineProductId = extractProductId.apply(line); if (productId == null) { productId = lineProductId; } else if (!ProductId.equals(productId, lineProductId)) { // found different products return null; } final Quantity lineQtyToPick = extractQtyToPick.apply(line); if (qtyToPick == null) { qtyToPick = lineQtyToPick; } else if (UomId.equals(qtyToPick.getUomId(), lineQtyToPick.getUomId())) {
qtyToPick = qtyToPick.add(lineQtyToPick); } else { // found different UOMs return null; } } return qtyToPick; } @NonNull public ImmutableSet<HuId> getPickedHuIds(@Nullable final PickingJobLineId lineId) { return lineId != null ? getLineById(lineId).getPickedHUIds() : getAllPickedHuIds(); } public ImmutableSet<HuId> getAllPickedHuIds() { return streamLines() .map(PickingJobLine::getPickedHUIds) .flatMap(Set::stream) .collect(ImmutableSet.toImmutableSet()); } public ImmutableSet<PPOrderId> getManufacturingOrderIds() { return streamLines() .map(PickingJobLine::getPickFromManufacturingOrderId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJob.java
1
请在Spring Boot框架中完成以下Java代码
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService { @Override public void saveRolePermission(String roleId, String permissionIds) { String ip = ""; try { //获取request HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); //获取IP地址 ip = IpUtils.getIpAddr(request); } catch (Exception e) { ip = "127.0.0.1"; } LambdaQueryWrapper<SysRolePermission> query = new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId); this.remove(query); List<SysRolePermission> list = new ArrayList<SysRolePermission>(); String[] arr = permissionIds.split(","); for (String p : arr) { if(oConvertUtils.isNotEmpty(p)) { SysRolePermission rolepms = new SysRolePermission(roleId, p); rolepms.setOperateDate(new Date()); rolepms.setOperateIp(ip); list.add(rolepms); } } this.saveBatch(list); } @Override public void saveRolePermission(String roleId, String permissionIds, String lastPermissionIds) { String ip = ""; try { //获取request HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); //获取IP地址 ip = IpUtils.getIpAddr(request); } catch (Exception e) { ip = "127.0.0.1"; } List<String> add = getDiff(lastPermissionIds,permissionIds); if(add!=null && add.size()>0) { List<SysRolePermission> list = new ArrayList<SysRolePermission>(); for (String p : add) { if(oConvertUtils.isNotEmpty(p)) { SysRolePermission rolepms = new SysRolePermission(roleId, p); rolepms.setOperateDate(new Date()); rolepms.setOperateIp(ip); list.add(rolepms); } }
this.saveBatch(list); } List<String> delete = getDiff(permissionIds,lastPermissionIds); if(delete!=null && delete.size()>0) { for (String permissionId : delete) { this.remove(new QueryWrapper<SysRolePermission>().lambda().eq(SysRolePermission::getRoleId, roleId).eq(SysRolePermission::getPermissionId, permissionId)); } } } /** * 从diff中找出main中没有的元素 * @param main * @param diff * @return */ private List<String> getDiff(String main,String diff){ if(oConvertUtils.isEmpty(diff)) { return null; } if(oConvertUtils.isEmpty(main)) { return Arrays.asList(diff.split(",")); } String[] mainArr = main.split(","); String[] diffArr = diff.split(","); Map<String, Integer> map = new HashMap(5); for (String string : mainArr) { map.put(string, 1); } List<String> res = new ArrayList<String>(); for (String key : diffArr) { if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) { res.add(key); } } return res; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysRolePermissionServiceImpl.java
2
请完成以下Java代码
private void updateTabFieldColumns(Properties ctx, I_AD_Tab tab, String trxName) { final String tableName = Services.get(IADTableDAO.class).retrieveTableName(tab.getAD_Table_ID()); final List<I_AD_Field> fields = new Query(ctx, I_AD_Field.Table_Name, I_AD_Field.COLUMNNAME_AD_Tab_ID + "=?", trxName) .setParameters(tab.getAD_Tab_ID()) .setOrderBy(I_AD_Field.COLUMNNAME_SeqNo) .list(I_AD_Field.class); for (I_AD_Field field : fields) { I_AD_Column columnOld = field.getAD_Column(); int columnId = MColumn.getColumn_ID(tableName, columnOld.getColumnName()); if (columnId > 0) { field.setAD_Column_ID(columnId); InterfaceWrapperHelper.save(field);
log.info("Updated AD_Column_ID for field " + field.getName()); } else { log.info("Deleting field " + field.getName()); InterfaceWrapperHelper.getPO(field).deleteEx(true); // TODO: use POWrapper.delete } } } @Override public String docValidate(PO po, int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\model\validator\ApplicationDictionary.java
1
请完成以下Java代码
public static void analyzeGCRoots() { LOGGER.info("Analyzing GC Roots:"); Collection<GCRoot> gcRoots = heap.getGCRoots(); if (gcRoots == null) { LOGGER.error("No GC Roots found"); return; } LOGGER.info("Total GC Roots: " + gcRoots.size()); int threadObj = 0, jniGlobal = 0, jniLocal = 0, javaFrame = 0, other = 0; for (GCRoot gcRoot : gcRoots) { Instance instance = gcRoot.getInstance(); String kind = gcRoot.getKind(); switch (kind) { case THREAD_OBJECT: threadObj++; break; case JNI_GLOBAL: jniGlobal++; break; case JNI_LOCAL: jniLocal++; break; case JAVA_FRAME: javaFrame++; break; default: other++; } if (threadObj + jniGlobal + jniLocal + javaFrame + other <= 10) { LOGGER.info(" GC Root: " + instance.getJavaClass().getName()); LOGGER.info(" Kind: " + kind);
LOGGER.info(" Size: " + instance.getSize() + " bytes"); } } LOGGER.info("\nGC Root Summary:"); LOGGER.info(" Thread Objects: " + threadObj); LOGGER.info(" JNI Global References: " + jniGlobal); LOGGER.info(" JNI Local References: " + jniLocal); LOGGER.info(" Java Frames: " + javaFrame); LOGGER.info(" Other: " + other); } public static void analyzeClassHistogram() { LOGGER.info("\nClass Histogram (Top 10 by instance count):"); List<JavaClass> unmodifiableClasses = heap.getAllClasses(); if (unmodifiableClasses == null) { LOGGER.error("No classes found"); return; } List<JavaClass> classes = new ArrayList<>(unmodifiableClasses); classes.sort((c1, c2) -> Long.compare(c2.getInstancesCount(), c1.getInstancesCount())); for (int i = 0; i < Math.min(10, classes.size()); i++) { JavaClass javaClass = classes.get(i); LOGGER.info(" " + javaClass.getName()); LOGGER.info(" Instances: " + javaClass.getInstancesCount()); LOGGER.info(" Total size: " + javaClass.getAllInstancesSize() + " bytes"); } } }
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\netbeanprofiler\SolApp.java
1
请完成以下Java代码
protected SpringSecurityLdapTemplate getLdapTemplate() { return this.ldapTemplate; } /** * Returns the attribute name of the LDAP attribute that will be mapped to the role * name Method available so that classes extending this can override * @return the attribute name used for role mapping * @see #setGroupRoleAttribute(String) */ protected final String getGroupRoleAttribute() { return this.groupRoleAttribute; } /** * Returns the search filter configured for this populator Method available so that * classes extending this can override * @return the search filter * @see #setGroupSearchFilter(String) */ protected final String getGroupSearchFilter() { return this.groupSearchFilter; } /** * Returns the role prefix used by this populator Method available so that classes * extending this can override * @return the role prefix * @see #setRolePrefix(String)
*/ protected final String getRolePrefix() { return this.rolePrefix; } /** * Returns true if role names are converted to uppercase Method available so that * classes extending this can override * @return true if role names are converted to uppercase. * @see #setConvertToUpperCase(boolean) */ protected final boolean isConvertToUpperCase() { return this.convertToUpperCase; } /** * Returns the search controls Method available so that classes extending this can * override the search controls used * @return the search controls */ private SearchControls getSearchControls() { return this.searchControls; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\DefaultLdapAuthoritiesPopulator.java
1
请完成以下Spring Boot application配置
logging: level: .: error org.springframework: ERROR com.mkyong: ERROR spring: profiles: active: "dev" main: banner-mode: "off" server: email: default@mkyong.com --- spring: profiles: dev server: email: dev@mkyong.com cluster: - ip: 127.0.0.1 path: /dev1 - ip: 127.0.0.2 path: /dev2 - ip: 127.0.0.3 path: /dev3 --- spring: profil
es: prod server: email: prod@mkyong.com cluster: - ip: 192.168.0.1 path: /app1 - ip: 192.168.0.2 path: /app2 - ip: 192.168.0.3 path: /app3
repos\spring-boot-master\profile-yaml\src\main\resources\application.yml
2
请完成以下Java代码
public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } @Override public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) { addExecutionListener(activity); } private void addExecutionListener(final ActivityImpl activity) { if (executionListener != null) { for (String event : EXECUTION_EVENTS) { addListenerOnCoreModelElement(activity, executionListener, event); } } } private void addExecutionListener(final TransitionImpl transition) { if (executionListener != null) { addListenerOnCoreModelElement(transition, executionListener, EVENTNAME_TAKE); } } private void addListenerOnCoreModelElement(CoreModelElement element, DelegateListener<?> listener, String event) { if (skippable) { element.addListener(event, listener); } else { element.addBuiltInListener(event, listener); } }
private void addTaskListener(TaskDefinition taskDefinition) { if (taskListener != null) { for (String event : TASK_EVENTS) { if (skippable) { taskDefinition.addTaskListener(event, taskListener); } else { taskDefinition.addBuiltInTaskListener(event, taskListener); } } } } /** * Retrieves task definition. * * @param activity the taskActivity * @return taskDefinition for activity */ private TaskDefinition taskDefinition(final ActivityImpl activity) { final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior(); return activityBehavior.getTaskDefinition(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java
1
请完成以下Java代码
public String asString() { return "messaging.operation"; } }, /** * Messaging destination name. */ MESSAGING_DESTINATION_NAME { @Override @NonNull public String asString() { return "messaging.destination.name"; } }, /** * Messaging destination kind. */ MESSAGING_DESTINATION_KIND { @Override @NonNull public String asString() { return "messaging.destination.kind"; } } } /** * Default {@link KafkaTemplateObservationConvention} for Kafka template key values. * * @author Gary Russell * @author Christian Mergenthaler * @author Wang Zhiyang * * @since 3.0
* */ public static class DefaultKafkaTemplateObservationConvention implements KafkaTemplateObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultKafkaTemplateObservationConvention INSTANCE = new DefaultKafkaTemplateObservationConvention(); @Override public KeyValues getLowCardinalityKeyValues(KafkaRecordSenderContext context) { return KeyValues.of( TemplateLowCardinalityTags.BEAN_NAME.withValue(context.getBeanName()), TemplateLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"), TemplateLowCardinalityTags.MESSAGING_OPERATION.withValue("publish"), TemplateLowCardinalityTags.MESSAGING_DESTINATION_KIND.withValue("topic"), TemplateLowCardinalityTags.MESSAGING_DESTINATION_NAME.withValue(context.getDestination())); } @Override public String getContextualName(KafkaRecordSenderContext context) { return context.getDestination() + " send"; } @Override @NonNull public String getName() { return "spring.kafka.template"; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaTemplateObservation.java
1
请完成以下Java代码
public String getSummary() { return "@M_Locator_ID@:" + locator.getValue() + " - " + (rawMaterialsWarehouse == null ? "?" : rawMaterialsWarehouse.getName()) + ", @M_Product_ID@:" + attributeSetInstanceAware.getM_Product().getName() + ", @Qty@:" + qty + " " + uom.getUOMSymbol(); } public boolean isValid() { loadIfNeeded(); return notValidReasons.isEmpty(); } public String getNotValidReasons() { return StringUtils.toString(notValidReasons, "; "); } 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
请在Spring Boot框架中完成以下Java代码
private void deleteLineCandidates( @NonNull final PPOrderDeletedEvent event, @NonNull final Candidate headerCandidate) { final List<PPOrderLine> ppOrderLines = event.getPpOrder().getLines(); final boolean simulated = headerCandidate.isSimulated(); for (final PPOrderLine ppOrderLine : ppOrderLines) { final Candidate existingLineCandidate = retrieveExistingLineCandidateOrNull(ppOrderLine, simulated); if (existingLineCandidate != null) { candidateChangeService.onCandidateDelete(existingLineCandidate); } } } @Nullable private Candidate retrieveExistingLineCandidateOrNull( @NonNull final PPOrderLine ppOrderLine, final boolean simulated) { final SimulatedQueryQualifier simulatedQueryQualifier = simulated ? SimulatedQueryQualifier.ONLY_SIMULATED : SimulatedQueryQualifier.EXCLUDE_SIMULATED; final ProductionDetailsQuery productionDetailsQuery = ProductionDetailsQuery.builder() .ppOrderLineIds(InSetPredicate.onlyOrNone(PPOrderBOMLineId.ofRepoIdOrNull(ppOrderLine.getPpOrderLineId()))) .build(); final CandidatesQuery lineCandidateQuery = CandidatesQuery.builder() .type(CandidateType.DEMAND)
.businessCase(CandidateBusinessCase.PRODUCTION) .productionDetailsQuery(productionDetailsQuery) .simulatedQueryQualifier(simulatedQueryQualifier) .groupId(null) .build(); return candidateRepositoryRetrieval.retrieveLatestMatchOrNull(lineCandidateQuery); } @NonNull private CandidatesQuery createPreExistingHeaderQuery(@NonNull final PPOrderDeletedEvent ppOrderCandidateDeletedEvent) { final PPOrder ppOrderCandidate = ppOrderCandidateDeletedEvent.getPpOrder(); return CandidatesQuery .builder() .productionDetailsQuery(ProductionDetailsQuery.builder() .ppOrderId(ppOrderCandidate.getPpOrderId()) .ppOrderLineIds(InSetPredicate.none()) // to get the header (main-product), we just need to exclude the PPOrderLine-IDs .build()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\pporder\PPOrderDeletedHandler.java
2
请完成以下Java代码
public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPaymentReference (final @Nullable java.lang.String PaymentReference) { set_Value (COLUMNNAME_PaymentReference, PaymentReference); } @Override public java.lang.String getPaymentReference() { return get_ValueAsString(COLUMNNAME_PaymentReference); } @Override public void setPostalCode (final @Nullable java.lang.String PostalCode) { set_Value (COLUMNNAME_PostalCode, PostalCode); } @Override public java.lang.String getPostalCode() { return get_ValueAsString(COLUMNNAME_PostalCode); } @Override public void setRecipientBankCountryId (final int RecipientBankCountryId) { set_Value (COLUMNNAME_RecipientBankCountryId, RecipientBankCountryId); } @Override public int getRecipientBankCountryId() { return get_ValueAsInt(COLUMNNAME_RecipientBankCountryId); } @Override public void setRecipientCountryId (final int RecipientCountryId) { set_Value (COLUMNNAME_RecipientCountryId, RecipientCountryId); } @Override public int getRecipientCountryId() { return get_ValueAsInt(COLUMNNAME_RecipientCountryId); } /** * RecipientType AD_Reference_ID=541372 * Reference name: RecipientTypeList */ public static final int RECIPIENTTYPE_AD_Reference_ID=541372; /** COMPANY = COMPANY */ public static final String RECIPIENTTYPE_COMPANY = "COMPANY"; /** INDIVIDUAL = INDIVIDUAL */ public static final String RECIPIENTTYPE_INDIVIDUAL = "INDIVIDUAL"; @Override public void setRecipientType (final java.lang.String RecipientType) { set_Value (COLUMNNAME_RecipientType, RecipientType); } @Override public java.lang.String getRecipientType() { return get_ValueAsString(COLUMNNAME_RecipientType); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null);
else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRegionName (final @Nullable java.lang.String RegionName) { set_Value (COLUMNNAME_RegionName, RegionName); } @Override public java.lang.String getRegionName() { return get_ValueAsString(COLUMNNAME_RegionName); } @Override public void setRevolut_Payment_Export_ID (final int Revolut_Payment_Export_ID) { if (Revolut_Payment_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_Revolut_Payment_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_Revolut_Payment_Export_ID, Revolut_Payment_Export_ID); } @Override public int getRevolut_Payment_Export_ID() { return get_ValueAsInt(COLUMNNAME_Revolut_Payment_Export_ID); } @Override public void setRoutingNo (final @Nullable java.lang.String RoutingNo) { set_Value (COLUMNNAME_RoutingNo, RoutingNo); } @Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java-gen\de\metas\payment\revolut\model\X_Revolut_Payment_Export.java
1
请完成以下Java代码
public class DefaultPropertyDetector implements EncryptablePropertyDetector { private String prefix = "ENC("; private String suffix = ")"; /** * <p>Constructor for DefaultPropertyDetector.</p> */ public DefaultPropertyDetector() { } /** * <p>Constructor for DefaultPropertyDetector.</p> * * @param prefix a {@link java.lang.String} object * @param suffix a {@link java.lang.String} object */ public DefaultPropertyDetector(String prefix, String suffix) { Assert.notNull(prefix, "Prefix can't be null"); Assert.notNull(suffix, "Suffix can't be null"); this.prefix = prefix; this.suffix = suffix; }
/** {@inheritDoc} */ @Override public boolean isEncrypted(String property) { if (property == null) { return false; } final String trimmedValue = property.trim(); return (trimmedValue.startsWith(prefix) && trimmedValue.endsWith(suffix)); } /** {@inheritDoc} */ @Override public String unwrapEncryptedValue(String property) { return property.substring( prefix.length(), (property.length() - suffix.length())); } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\detector\DefaultPropertyDetector.java
1
请完成以下Java代码
private static PickingJobReferenceList ofList(final List<PickingJobReference> list) { return !list.isEmpty() ? new PickingJobReferenceList(list) : EMPTY; } public static Collector<PickingJobReference, ?, PickingJobReferenceList> collect() { return GuavaCollectors.collectUsingListAccumulator(PickingJobReferenceList::ofList); } public boolean isEmpty() {return list.isEmpty();} public Stream<PickingJobReference> stream() {return list.stream();} public PickingJobReferenceList updateEach(@NonNull UnaryOperator<PickingJobReference> updater) { final ImmutableList<PickingJobReference> changedList = CollectionUtils.map(list, updater); return Objects.equals(list, changedList) ? this : ofList(changedList); } public ShipmentScheduleAndJobScheduleIdSet getScheduleIds()
{ return list.stream() .map(PickingJobReference::getScheduleIds) .filter(Objects::nonNull) .flatMap(ShipmentScheduleAndJobScheduleIdSet::stream) .collect(ShipmentScheduleAndJobScheduleIdSet.collect()); } public Set<ProductId> getProductIds() { return list.stream() .flatMap(job -> job.getProductIds().stream()) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobReferenceList.java
1
请完成以下Java代码
public void addTabSwitchingSupport(JComponent c) { if(c instanceof JTable) { ((JTable)c).getSelectionModel().addListSelectionListener(this); return; } else if( //c instanceof org.compiere.grid.ed.VEditor || c instanceof JTextComponent || //c instanceof ItemSelectable || c instanceof org.compiere.grid.ed.VCheckBox || //c instanceof org.compiere.grid.ed.VLookup || //c instanceof org.compiere.swing.CLabel || c instanceof AbstractButton) { c.addFocusListener(this); //c.addKeyListener(new MovementAdapter()); return; } else if(c instanceof org.compiere.grid.ed.VDate) { org.compiere.grid.ed.VDate d = ((org.compiere.grid.ed.VDate)c); //d.addFocusListener(this); d.addActionListener(this); //d.addKeyListener(new MovementAdapter()); return; } else if(c instanceof org.compiere.grid.ed.VLookup) { org.compiere.grid.ed.VLookup l = ((org.compiere.grid.ed.VLookup)c); //l.addFocusListener(this);
l.addActionListener(this); //l.addKeyListener(new MovementAdapter()); return; } } class MovementAdapter extends KeyAdapter { public void keyPressed(KeyEvent event) { // look for tab keys if(event.getKeyCode() == KeyEvent.VK_TAB || event.getKeyCode() == KeyEvent.VK_ENTER) { ((JComponent)event.getSource()).transferFocus(); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\TabSwitcher.java
1
请完成以下Java代码
public class IfPartImpl extends CmmnElementImpl implements IfPart { protected static AttributeReference<CaseFileItem> contextRefAttribute; // cmmn 1.1 protected static ChildElement<ConditionExpression> conditionChild; public IfPartImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public CaseFileItem getContext() { return contextRefAttribute.getReferenceTargetElement(this); } public void setContext(CaseFileItem caseFileItem) { contextRefAttribute.setReferenceTargetElement(this, caseFileItem); } public Collection<ConditionExpression> getConditions() { return conditionChild.get(this); } public ConditionExpression getCondition() { return conditionChild.getChild(this); } public void setCondition(ConditionExpression condition) { conditionChild.setChild(this, condition); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(IfPart.class, CMMN_ELEMENT_IF_PART) .namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<IfPart>() { public IfPart newInstance(ModelTypeInstanceContext instanceContext) { return new IfPartImpl(instanceContext); } }); contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF) .idAttributeReference(CaseFileItem.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); conditionChild = sequenceBuilder.element(ConditionExpression.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\IfPartImpl.java
1
请完成以下Java代码
public int getRevisionNext() { return revision + 1; } public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public boolean isInserted() { return isInserted; } public void setInserted(boolean isInserted) { this.isInserted = isInserted; }
public boolean isUpdated() { return isUpdated; } public void setUpdated(boolean isUpdated) { this.isUpdated = isUpdated; } public boolean isDeleted() { return isDeleted; } public void setDeleted(boolean isDeleted) { this.isDeleted = isDeleted; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntity.java
1
请完成以下Java代码
private ImmutableSet<ResourceId> getSelectedResourceIds() { final IView view = getView(); return getSelectedRowIdsAsSet() .stream() .map(view::getTableRecordReferenceOrNull) .filter(Objects::nonNull) .map(recordRef -> ResourceId.ofRepoId(recordRef.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); } private Set<DocumentId> getSelectedRowIdsAsSet() { final IView view = getView(); final DocumentIdsSelection rowIds = getSelectedRowIds(); final Set<DocumentId> rowIdsEffective;
if (rowIds.isEmpty()) { return ImmutableSet.of(); } else if (rowIds.isAll()) { rowIdsEffective = view.streamByIds(DocumentIdsSelection.ALL) .map(IViewRow::getId) .collect(ImmutableSet.toImmutableSet()); } else { rowIdsEffective = rowIds.toSet(); } return rowIdsEffective; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\resource\process\S_Resource_PrintQRCodes.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() {
return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java
2
请完成以下Java代码
public Set<String> getParameters(@Nullable final String contextTableName) { return PARAMETERS; } @Override public boolean accept(@Nullable final IValidationContext evalCtx, @Nullable final NamePair item) { final PaySelectionTrxType trxType = extractPaySelectionTrxType(evalCtx); if (trxType == null) { return true; } final PaySelectionMatchingMode paySelectionMatchingMode = extractPaySelectionMatchingMode(item); if (paySelectionMatchingMode == null) { return false; } return paySelectionMatchingMode.isCompatibleWith(trxType); } @Contract("null -> false") private static boolean isContextAvailable(@Nullable final IValidationContext evalCtx) { return evalCtx != IValidationContext.NULL && evalCtx != IValidationContext.DISABLED;
} @Nullable private static PaySelectionTrxType extractPaySelectionTrxType(@Nullable final IValidationContext evalCtx) { if (!isContextAvailable(evalCtx)) { return null; } final String code = evalCtx.get_ValueAsString(PARAM_PaySelectionTrxType); if (Check.isBlank(code)) { return null; } return PaySelectionTrxType.ofCode(code); } @Nullable private static PaySelectionMatchingMode extractPaySelectionMatchingMode(@Nullable final NamePair item) { return item != null ? PaySelectionMatchingMode.ofNullableCode(item.getID()) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\PaySelectionModeByPaySelectionTrxTypeValRule.java
1
请完成以下Java代码
public void measureCollectionsSortBestCase(BestCaseBenchmarkState state) { List<Integer> sortedList = new ArrayList<>(state.sortedList); Collections.sort(sortedList); } @Benchmark public void measureCollectionsSortAverageWorstCase(AverageWorstCaseBenchmarkState state) { List<Integer> unsortedList = new ArrayList<>(state.unsortedList); Collections.sort(unsortedList); } @State(Scope.Benchmark) public static class BestCaseBenchmarkState { List<Integer> sortedList; @Setup(Level.Trial) public void setUp() { sortedList = new ArrayList<>(); for (int i = 1; i <= 1000000; i++) { sortedList.add(i);
} } } @State(Scope.Benchmark) public static class AverageWorstCaseBenchmarkState { List<Integer> unsortedList; @Setup(Level.Trial) public void setUp() { unsortedList = new ArrayList<>(); for (int i = 1000000; i > 0; i--) { unsortedList.add(i); } } } }
repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\collectionssortcomplexity\CollectionsSortTimeComplexityJMH.java
1
请完成以下Java代码
public XhtmlFrameSetDocument appendTitle(Element value) { title.addElement(value); return(this); } /** Append to the title element for this XhtmlFrameSetDocument container. @param value adds to the value between the title tags */ public XhtmlFrameSetDocument appendTitle(String value) { title.addElement(value); return(this); } /** * Sets the codeset for this XhtmlFrameSetDocument */ public void setCodeset ( String codeset ) { this.codeset = codeset; } /** * Gets the codeset for this XhtmlFrameSetDocument * * @return the codeset */ public String getCodeset() { return this.codeset; } /** Write the container to the OutputStream */ public void output(OutputStream out) { // XhtmlFrameSetDocument is just a convient wrapper for html call html.output html.output(out); } /** Write the container to the PrinteWriter */
public void output(PrintWriter out) { // XhtmlFrameSetDocument is just a convient wrapper for html call html.output html.output(out); } /** Override the toString() method so that it prints something meaningful. */ public final String toString() { if ( getCodeset() != null ) return (html.toString(getCodeset())); else return(html.toString()); } /** Override the toString() method so that it prints something meaningful. */ public final String toString(String codeset) { return(html.toString(codeset)); } /** Allows the XhtmlFrameSetDocument to be cloned. Doesn't return an instanceof XhtmlFrameSetDocument returns instance of html. */ public Object clone() { return(html.clone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlFrameSetDocument.java
1
请完成以下Java代码
public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public Set<String> getActivityTypes() { return activityTypes; } public String getAssignee() { return assignee; } public String getCompletedBy() { return completedBy; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } public Date getStartedAfter() { return startedAfter; }
public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public List<String> getTenantIds() { return tenantIds; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public Collection<String> getProcessInstanceIds() { return processInstanceIds; } public Set<String> getCalledProcessInstanceIds() { return calledProcessInstanceIds; } public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) { this.calledProcessInstanceIds = calledProcessInstanceIds; } public List<List<String>> getSafeCalledProcessInstanceIds() { return safeCalledProcessInstanceIds; } public void setSafeCalledProcessInstanceIds(List<List<String>> safeCalledProcessInstanceIds) { this.safeCalledProcessInstanceIds = safeCalledProcessInstanceIds; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请完成以下Java代码
public void setMappingRule (final @Nullable java.lang.String MappingRule) { set_Value (COLUMNNAME_MappingRule, MappingRule); } @Override public java.lang.String getMappingRule() { return get_ValueAsString(COLUMNNAME_MappingRule); } @Override public void setMappingRuleValue (final @Nullable java.lang.String MappingRuleValue) { set_Value (COLUMNNAME_MappingRuleValue, MappingRuleValue); } @Override public java.lang.String getMappingRuleValue() { return get_ValueAsString(COLUMNNAME_MappingRuleValue); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override
public void setM_Shipper_Mapping_Config_ID (final int M_Shipper_Mapping_Config_ID) { if (M_Shipper_Mapping_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipper_Mapping_Config_ID, M_Shipper_Mapping_Config_ID); } @Override public int getM_Shipper_Mapping_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_Mapping_Config_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper_Mapping_Config.java
1
请完成以下Java代码
public class Book { private Integer bookId; private String title; private String author; public Book() {} public Book(Integer bookId, String title, String author) { this.bookId = bookId; this.title = title; this.author = author; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Book)) { return false; } Book book = (Book) o; if (!Objects.equals(bookId, book.bookId)) { return false; } if (!Objects.equals(title, book.title)) { return false; } return Objects.equals(author, book.author); } @Override public int hashCode() { int result = bookId != null ? bookId.hashCode() : 0; result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (author != null ? author.hashCode() : 0); return result;
} public Integer getBookId() { return bookId; } public void setBookId(Integer bookId) { this.bookId = bookId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\tocollection\Book.java
1
请完成以下Java代码
public void postConstruct() { startThread(); } private void startThread() { final Thread thread = new Thread(this::processEventsLoop); thread.setDaemon(true); thread.setName("BusinessRuleEventsProcessor"); thread.start(); logger.info("Started {}", thread); } private void processEventsLoop() { while (true) { try { sleep(); } catch (final InterruptedException e) { logger.info("Got interrupt request. Exiting."); Thread.currentThread().interrupt(); return; }
try { ruleService.processEvents(getRetrieveBatchSize()); } catch (final Exception ex) { logger.warn("Failed to process. Ignored.", ex); } } } private void sleep() throws InterruptedException { final Duration pollInterval = getPollInterval(); logger.debug("Sleeping {}", pollInterval); Thread.sleep(pollInterval.toMillis()); } private Duration getPollInterval() { final int pollIntervalInSeconds = sysConfigBL.getIntValue(SYSCONFIG_PollIntervalInSeconds, -1); return pollIntervalInSeconds > 0 ? Duration.ofSeconds(pollIntervalInSeconds) : DEFAULT_PollInterval; } private QueryLimit getRetrieveBatchSize() { final int retrieveBatchSize = sysConfigBL.getIntValue(SYSCONFIG_RetrieveBatchSize, -1); return retrieveBatchSize > 0 ? QueryLimit.ofInt(retrieveBatchSize) : DEFAULT_RetrieveBatchSize; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\server\BusinessRuleEventProcessorWatcher.java
1
请完成以下Java代码
public BPartnerPrintFormatMap getBPartnerPrintFormats(final BPartnerId bpartnerId) { return bpartnerBL.getPrintFormats(bpartnerId); } @NonNull public DefaultPrintFormats getDefaultPrintFormats(@NonNull final ClientId clientId) { return defaultPrintFormatsRepository.getByClientId(clientId); } @NonNull public AdProcessId getReportProcessIdByPrintFormatId(@NonNull final PrintFormatId printFormatId) { return getReportProcessIdByPrintFormatIdIfExists(printFormatId).get(); } @NonNull public ExplainedOptional<AdProcessId> getReportProcessIdByPrintFormatIdIfExists(@NonNull final PrintFormatId printFormatId) { final PrintFormat printFormat = printFormatRepository.getById(printFormatId); final AdProcessId reportProcessId = printFormat.getReportProcessId(); return reportProcessId != null ? ExplainedOptional.of(reportProcessId) : ExplainedOptional.emptyBecause("No report process defined by " + printFormat); } @NonNull public I_C_DocType getDocTypeById(@NonNull final DocTypeId docTypeId) { return docTypeDAO.getById(docTypeId);
} public PrintCopies getDocumentCopies( @Nullable final I_C_DocType docType, @Nullable final BPPrintFormatQuery bpPrintFormatQuery) { final BPPrintFormat bpPrintFormat = bpPrintFormatQuery == null ? null : bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery); if(bpPrintFormat == null) { return getDocumentCopies(docType); } return bpPrintFormat.getPrintCopies(); } private static PrintCopies getDocumentCopies(@Nullable final I_C_DocType docType) { return docType != null && !InterfaceWrapperHelper.isNull(docType, I_C_DocType.COLUMNNAME_DocumentCopies) ? PrintCopies.ofInt(docType.getDocumentCopies()) : PrintCopies.ONE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportAdvisorUtil.java
1
请完成以下Java代码
public ResponseEntity<List<DictDto>> queryAllDict(){ return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()),HttpStatus.OK); } @ApiOperation("查询字典") @GetMapping @PreAuthorize("@el.check('dict:list')") public ResponseEntity<PageResult<DictDto>> queryDict(DictQueryCriteria resources, Pageable pageable){ return new ResponseEntity<>(dictService.queryAll(resources,pageable),HttpStatus.OK); } @Log("新增字典") @ApiOperation("新增字典") @PostMapping @PreAuthorize("@el.check('dict:add')") public ResponseEntity<Object> createDict(@Validated @RequestBody Dict resources){ if (resources.getId() != null) { throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID"); } dictService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED);
} @Log("修改字典") @ApiOperation("修改字典") @PutMapping @PreAuthorize("@el.check('dict:edit')") public ResponseEntity<Object> updateDict(@Validated(Dict.Update.class) @RequestBody Dict resources){ dictService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除字典") @ApiOperation("删除字典") @DeleteMapping @PreAuthorize("@el.check('dict:del')") public ResponseEntity<Object> deleteDict(@RequestBody Set<Long> ids){ dictService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DictController.java
1
请完成以下Java代码
public class AuthenticationTrustResolverImpl implements AuthenticationTrustResolver { private Class<? extends Authentication> anonymousClass = AnonymousAuthenticationToken.class; private Class<? extends Authentication> rememberMeClass = RememberMeAuthenticationToken.class; Class<? extends Authentication> getAnonymousClass() { return this.anonymousClass; } Class<? extends Authentication> getRememberMeClass() { return this.rememberMeClass; } @Override public boolean isAnonymous(@Nullable Authentication authentication) { if ((this.anonymousClass == null) || (authentication == null)) { return false; } return this.anonymousClass.isAssignableFrom(authentication.getClass()); } @Override public boolean isRememberMe(@Nullable Authentication authentication) {
if ((this.rememberMeClass == null) || (authentication == null)) { return false; } return this.rememberMeClass.isAssignableFrom(authentication.getClass()); } public void setAnonymousClass(Class<? extends Authentication> anonymousClass) { this.anonymousClass = anonymousClass; } public void setRememberMeClass(Class<? extends Authentication> rememberMeClass) { this.rememberMeClass = rememberMeClass; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AuthenticationTrustResolverImpl.java
1
请在Spring Boot框架中完成以下Java代码
public TaskBuilder category(String category) { this.category = category; return this; } @Override public TaskBuilder parentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; return this; } @Override public TaskBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } @Override public TaskBuilder formKey(String formKey) { this.formKey = formKey; return this; } @Override public TaskBuilder taskDefinitionId(String taskDefinitionId) { this.taskDefinitionId = taskDefinitionId; return this; } @Override public TaskBuilder taskDefinitionKey(String taskDefinitionKey) { this.taskDefinitionKey = taskDefinitionKey; return this; } @Override public TaskBuilder identityLinks(Set<? extends IdentityLinkInfo> identityLinks) { this.identityLinks = identityLinks; return this; } @Override public TaskBuilder scopeId(String scopeId) { this.scopeId = scopeId; return this; } @Override public TaskBuilder scopeType(String scopeType) { this.scopeType = scopeType; return this; } @Override public String getId() { return id; } @Override public String getName() { return name; } @Override public String getDescription() { return description; } @Override public int getPriority() { return priority; } @Override public String getOwner() { return ownerId; } @Override public String getAssignee() { return assigneeId;
} @Override public String getTaskDefinitionId() { return taskDefinitionId; } @Override public String getTaskDefinitionKey() { return taskDefinitionKey; } @Override public Date getDueDate() { return dueDate; } @Override public String getCategory() { return category; } @Override public String getParentTaskId() { return parentTaskId; } @Override public String getTenantId() { return tenantId; } @Override public String getFormKey() { return formKey; } @Override public Set<? extends IdentityLinkInfo> getIdentityLinks() { return identityLinks; } @Override public String getScopeId() { return this.scopeId; } @Override public String getScopeType() { return this.scopeType; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java
2
请在Spring Boot框架中完成以下Java代码
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll()) .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringRequestMatchers( PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")), PathPatternRequestMatcher.withDefaults() .matcher(DELETE, this.adminServer.path("/instances/*")), PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**")))); return http.build(); } } @Profile("secure") @Configuration(proxyBeanMethods = false) public static class SecuritySecureConfig { private final AdminServerProperties adminServer; public SecuritySecureConfig(AdminServerProperties adminServer) { this.adminServer = adminServer; } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/assets/**"))) .permitAll() .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/login"))) .permitAll() .anyRequest() .authenticated()) .formLogin((formLogin) -> formLogin.loginPage(this.adminServer.path("/login")) .successHandler(successHandler)) .logout((logout) -> logout.logoutUrl(this.adminServer.path("/logout"))) .httpBasic(Customizer.withDefaults()) .csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .ignoringRequestMatchers( PathPatternRequestMatcher.withDefaults().matcher(POST, this.adminServer.path("/instances")), PathPatternRequestMatcher.withDefaults() .matcher(DELETE, this.adminServer.path("/instances/*")), PathPatternRequestMatcher.withDefaults().matcher(this.adminServer.path("/actuator/**")))); return http.build(); } } }
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-hazelcast\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminHazelcastApplication.java
2
请完成以下Java代码
private @Nullable String resolveSendTo(String value) { BeanExpressionContext beanExpressionContext = getBeanExpressionContext(); if (beanExpressionContext != null) { String resolvedValue = beanExpressionContext.getBeanFactory().resolveEmbeddedValue(value); BeanExpressionResolver resolverToUse = getResolver(); if (resolverToUse != null) { Object newValue = resolverToUse.evaluate(resolvedValue, beanExpressionContext); Assert.isInstanceOf(String.class, newValue, "Invalid @SendTo expression"); return (String) newValue; } } return value; } @Override protected StringBuilder getEndpointDescription() { return super.getEndpointDescription() .append(" | bean='").append(this.bean).append("'") .append(" | method='").append(this.method).append("'"); } /** * Provider of listener adapters. * @since 2.4 * */ public interface AdapterProvider { /** * Get an adapter instance. * @param batch true for a batch listener.
* @param bean the bean. * @param method the method. * @param returnExceptions true to return exceptions. * @param errorHandler the error handler. * @param batchingStrategy the batching strategy for batch listeners. * @return the adapter. */ MessagingMessageListenerAdapter getAdapter(boolean batch, @Nullable Object bean, @Nullable Method method, boolean returnExceptions, @Nullable RabbitListenerErrorHandler errorHandler, @Nullable BatchingStrategy batchingStrategy); } private static final class DefaultAdapterProvider implements AdapterProvider { @Override public MessagingMessageListenerAdapter getAdapter(boolean batch, @Nullable Object bean, @Nullable Method method, boolean returnExceptions, @Nullable RabbitListenerErrorHandler errorHandler, @Nullable BatchingStrategy batchingStrategy) { if (batch) { return new BatchMessagingMessageListenerAdapter(bean, method, returnExceptions, errorHandler, batchingStrategy); } else { return new MessagingMessageListenerAdapter(bean, method, returnExceptions, errorHandler); } } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\MethodRabbitListenerEndpoint.java
1
请完成以下Spring Boot application配置
# swagger-ui custom path springdoc.swagger-ui.path=/swagger-ui.html management.endpoints.enabled-by-default=false management.endpoint.info.enabled=false server.port=8081 # If you want to use Orkes Playground, then change the server url to https://play.orkes.io/api/ # Obtain key and secret by logging into # and navigating to applications menu, create an application
and generate key/secret conductor.security.client.key-id=CHANGE_ME conductor.security.client.secret=CHANGE_ME conductor.server.url=https://play.orkes.io/api/
repos\tutorials-master\microservices-modules\event-driven-microservice\src\main\resources\application.properties
2
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Image URL. @param ImageURL URL of image */ public void setImageURL (String ImageURL) { set_Value (COLUMNNAME_ImageURL, ImageURL); } /** Get Image URL. @return URL of image */ public String getImageURL () { return (String)get_Value(COLUMNNAME_ImageURL); } /** Set Name. @param Name Alphanumeric identifier of the entity
*/ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Image.java
1
请完成以下Java代码
public void setLabelFormatType (String LabelFormatType) { set_Value (COLUMNNAME_LabelFormatType, LabelFormatType); } /** Get Label Format Type. @return Label Format Type */ public String getLabelFormatType () { return (String)get_Value(COLUMNNAME_LabelFormatType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Print Text. @param PrintName The label text to be printed on a document or correspondence. */ public void setPrintName (String PrintName) { set_Value (COLUMNNAME_PrintName, PrintName); } /** Get Print Text. @return The label text to be printed on a document or correspondence. */ public String getPrintName () { return (String)get_Value(COLUMNNAME_PrintName); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); }
/** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } /** Set X Position. @param XPosition Absolute X (horizontal) position in 1/72 of an inch */ public void setXPosition (int XPosition) { set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition)); } /** Get X Position. @return Absolute X (horizontal) position in 1/72 of an inch */ public int getXPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_XPosition); if (ii == null) return 0; return ii.intValue(); } /** Set Y Position. @param YPosition Absolute Y (vertical) position in 1/72 of an inch */ public void setYPosition (int YPosition) { set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition)); } /** Get Y Position. @return Absolute Y (vertical) position in 1/72 of an inch */ public int getYPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_YPosition); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabelLine.java
1
请完成以下Java代码
public SecurityInfo getByOscoreIdentity(OscoreIdentity oscoreIdentity) { return null; } @Override public void put(TbLwM2MSecurityInfo tbSecurityInfo) throws NonUniqueSecurityInfoException { writeLock.lock(); try { String identity = null; if (tbSecurityInfo.getSecurityInfo() != null) { identity = tbSecurityInfo.getSecurityInfo().getPskIdentity(); if (identity != null) { TbLwM2MSecurityInfo infoByIdentity = securityByIdentity.get(identity); if (infoByIdentity != null && !tbSecurityInfo.getSecurityInfo().getEndpoint().equals(infoByIdentity.getEndpoint())) { throw new NonUniqueSecurityInfoException("PSK Identity " + identity + " is already used"); } securityByIdentity.put(tbSecurityInfo.getSecurityInfo().getPskIdentity(), tbSecurityInfo); } } TbLwM2MSecurityInfo previous = securityByEp.put(tbSecurityInfo.getEndpoint(), tbSecurityInfo); if (previous != null && previous.getSecurityInfo() != null) { String previousIdentity = previous.getSecurityInfo().getPskIdentity(); if (previousIdentity != null && !previousIdentity.equals(identity)) { securityByIdentity.remove(previousIdentity); } } } finally { writeLock.unlock(); } }
@Override public void remove(String endpoint) { writeLock.lock(); try { TbLwM2MSecurityInfo securityInfo = securityByEp.remove(endpoint); if (securityInfo != null && securityInfo.getSecurityInfo() != null && securityInfo.getSecurityInfo().getPskIdentity() != null) { securityByIdentity.remove(securityInfo.getSecurityInfo().getPskIdentity()); } } finally { writeLock.unlock(); } } @Override public TbLwM2MSecurityInfo getTbLwM2MSecurityInfoByEndpoint(String endpoint) { readLock.lock(); try { return securityByEp.get(endpoint); } finally { readLock.unlock(); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemorySecurityStore.java
1
请在Spring Boot框架中完成以下Java代码
public BatchPartQuery scopeType(String scopeType) { if (scopeType == null) { throw new FlowableIllegalArgumentException("scopeType is null"); } this.scopeType = scopeType; return this; } @Override public BatchPartQuery tenantId(String tenantId) { if (tenantId == null) { throw new FlowableIllegalArgumentException("tenantId is null"); } this.tenantId = tenantId; return this; } @Override public BatchPartQuery tenantIdLike(String tenantIdLike) { if (tenantIdLike == null) { throw new FlowableIllegalArgumentException("tenantIdLike is null"); } this.tenantIdLike = tenantIdLike; return this; } @Override public BatchPartQuery withoutTenantId() { this.withoutTenantId = true; return this; } @Override public BatchPartQuery completed() { this.completed = true; return this; } @Override public BatchPartQuery orderByBatchId() { return orderBy(BatchPartQueryProperty.BATCH_ID); } @Override public BatchPartQuery orderByCreateTime() { return orderBy(BatchPartQueryProperty.CREATE_TIME); } public String getId() { return id; } public String getType() { return type; } public String getBatchId() { return batchId;
} public String getSearchKey() { return searchKey; } public String getSearchKey2() { return searchKey2; } public String getBatchType() { return batchType; } public String getBatchSearchKey() { return batchSearchKey; } public String getBatchSearchKey2() { return batchSearchKey2; } public String getStatus() { return status; } public String getScopeId() { return scopeId; } public String getSubScopeId() { return subScopeId; } public String getScopeType() { return scopeType; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public boolean isCompleted() { return completed; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchPartQueryImpl.java
2
请完成以下Java代码
public String getObscuredValue (String clearValue) { setClearValue(clearValue); return getObscuredValue(); } // getObscuredValue /** * Get Obscured Value * @return Returns the obscuredValue. */ public String getObscuredValue () { if (m_obscuredValue != null) return m_obscuredValue; if (m_clearValue == null || m_clearValue.length() == 0) return m_clearValue; // boolean alpha = m_type.charAt(0) == 'A'; int clearStart = Integer.parseInt(m_type.substring(1,2)); int clearEnd = Integer.parseInt(m_type.substring(2)); // char[] chars = m_clearValue.toCharArray(); int length = chars.length; StringBuffer sb = new StringBuffer(length); for (int i = 0; i < length; i++) { char c = chars[i]; if (i < clearStart) sb.append(c);
else if (i >= length-clearEnd) sb.append(c); else { if (!alpha && !Character.isDigit(c)) sb.append(c); else sb.append('*'); } } m_obscuredValue = sb.toString(); return m_obscuredValue; } // getObscuredValue /************************************************************************** * test * @param args ignored */ public static void main (String[] args) { System.out.println (Obscure.obscure("1a2b3c4d5e6f7g8h9")); } // main } // Obscrure
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Obscure.java
1
请完成以下Java代码
public boolean retainAll(Collection<?> c) { return pipeList.retainAll(c); } @Override public void clear() { pipeList.clear(); } @Override public boolean equals(Object o) { return pipeList.equals(o); } @Override public int hashCode() { return pipeList.hashCode(); } @Override public Pipe<M, M> get(int index) { return pipeList.get(index); } @Override public Pipe<M, M> set(int index, Pipe<M, M> element) { return pipeList.set(index, element); } @Override public void add(int index, Pipe<M, M> element) { pipeList.add(index, element); } /** * 以最高优先级加入管道 * * @param pipe */ public void addFirst(Pipe<M, M> pipe) { pipeList.addFirst(pipe); } /** * 以最低优先级加入管道 * * @param pipe */ public void addLast(Pipe<M, M> pipe) { pipeList.addLast(pipe); } @Override public Pipe<M, M> remove(int index) {
return pipeList.remove(index); } @Override public int indexOf(Object o) { return pipeList.indexOf(o); } @Override public int lastIndexOf(Object o) { return pipeList.lastIndexOf(o); } @Override public ListIterator<Pipe<M, M>> listIterator() { return pipeList.listIterator(); } @Override public ListIterator<Pipe<M, M>> listIterator(int index) { return pipeList.listIterator(index); } @Override public List<Pipe<M, M>> subList(int fromIndex, int toIndex) { return pipeList.subList(fromIndex, toIndex); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\Pipeline.java
1
请完成以下Java代码
public List<Pair<Integer, Integer>> commonPrefixSearch(byte[] key, int offset, int maxResults) { ArrayList<Pair<Integer, Integer>> result = new ArrayList<Pair<Integer, Integer>>(); int unit = _array[0]; int nodePos = 0; // nodePos ^= unit.offset(); nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)); for (int i = offset; i < key.length; ++i) { byte b = key[i]; nodePos ^= (b & 0xff); unit = _array[nodePos]; // if (unit.label() != b) { if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff)) { return result; } // nodePos ^= unit.offset(); nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)); // if (unit.has_leaf()) { if (((unit >>> 8) & 1) == 1) { if (result.size() < maxResults) { // result.add(new Pair<i, _array[nodePos].value()); result.add(new Pair<Integer, Integer>(i + 1, _array[nodePos] & ((1 << 31) - 1))); } } }
return result; } /** * 大小 * * @return */ public int size() { return _array.length; } private static final int UNIT_SIZE = 4; // sizeof(int) private int[] _array; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DoubleArray.java
1
请完成以下Java代码
public ProcessInstanceBuilder transientVariable(String variableName, Object value) { if (this.transientVariables == null) { this.transientVariables = new HashMap<String, Object>(); } this.transientVariables.put(variableName, value); return this; } @Override public ProcessInstanceBuilder linkedProcessInstanceId(String linkedProcessInstanceId) { this.linkedProcessInstanceId = linkedProcessInstanceId; return this; } @Override public ProcessInstanceBuilder linkedProcessInstanceType(String linkedProcessInstanceType) { this.linkedProcessInstanceType = linkedProcessInstanceType; return this; } public boolean hasProcessDefinitionIdOrKey() { return this.getProcessDefinitionId() != null || this.getProcessDefinitionKey() != null; } public ProcessInstance start() { return runtimeService.startProcessInstance(this); } public ProcessInstance create() { return runtimeService.createProcessInstance(this); } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() {
return processDefinitionKey; } public String getMessageName() { return messageName; } public String getProcessInstanceName() { return processInstanceName; } public String getBusinessKey() { return businessKey; } public String getLinkedProcessInstanceId() { return linkedProcessInstanceId; } public String getLinkedProcessInstanceType() { return linkedProcessInstanceType; } public String getTenantId() { return tenantId; } public Map<String, Object> getVariables() { return variables; } public Map<String, Object> getTransientVariables() { return transientVariables; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\runtime\ProcessInstanceBuilderImpl.java
1
请完成以下Java代码
private static Document extractTextFromPptx(InputStream inputStream) throws IOException { try (XMLSlideShow ppt = new XMLSlideShow(inputStream)) { StringBuilder text = new StringBuilder(); for (XSLFSlide slide : ppt.getSlides()) { text.append("Slide ").append(slide.getSlideNumber()).append(":\n"); List<XSLFTextShape> shapes = slide.getShapes().stream() .filter(s -> s instanceof XSLFTextShape) .map(s -> (XSLFTextShape) s) .collect(Collectors.toList()); for (XSLFTextShape shape : shapes) { text.append(shape.getText()).append("\n"); } text.append("\n"); } return Document.from(text.toString()); } } /** * 提取ppt文件内容 * * @param inputStream * @return * @throws IOException * @author chenrui * @date 2025/3/5 14:43 * @deprecated 因为jeecg主项目目前不支持poi5.x, 自己实现提取功能. */ @Deprecated private static Document extractTextFromPpt(InputStream inputStream) throws IOException { try (org.apache.poi.hslf.usermodel.HSLFSlideShow ppt = new org.apache.poi.hslf.usermodel.HSLFSlideShow(inputStream)) { StringBuilder text = new StringBuilder(); for (org.apache.poi.hslf.usermodel.HSLFSlide slide : ppt.getSlides()) {
text.append("Slide ").append(slide.getSlideNumber()).append(":\n"); for (List<HSLFTextParagraph> shapes : slide.getTextParagraphs()) { text.append(HSLFTextParagraph.getText(shapes)).append("\n"); } text.append("\n"); } return Document.from(text.toString()); } } private static byte[] toByteArray(InputStream inputStream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int nRead; while ((nRead = inputStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } return buffer.toByteArray(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\document\TikaDocumentParser.java
1
请在Spring Boot框架中完成以下Java代码
protected boolean scheduleShortRunningWork(Runnable runnable) { EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get(); try { EnhancedQueueExecutor.execute(runnable); return true; } catch (Exception e) { // we must be able to schedule this log.log(Level.WARNING, "Cannot schedule long running work.", e); } return false; } protected boolean scheduleLongRunningWork(Runnable runnable) { final EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get(); boolean rejected = false;
try { EnhancedQueueExecutor.execute(runnable); } catch (RejectedExecutionException e) { rejected = true; } catch (Exception e) { // if it fails for some other reason, log a warning message long now = System.currentTimeMillis(); // only log every 60 seconds to prevent log flooding if((now-lastWarningLogged) >= (60*1000)) { log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e); } else { log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e); } } return !rejected; } }
repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java
2
请完成以下Java代码
public void setM_HU_Item_ID (final int M_HU_Item_ID) { if (M_HU_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_ID, M_HU_Item_ID); } @Override public int getM_HU_Item_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_ID); } @Override public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID) { if (M_HU_Item_Storage_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID); } @Override public int getM_HU_Item_Storage_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage.java
1
请完成以下Java代码
private IAllocationSource createAllocationSource(final I_M_ShipmentSchedule schedule) { final ShipmentScheduleQtyPickedProductStorage shipmentScheduleQtyPickedStorage = new ShipmentScheduleQtyPickedProductStorage(schedule); return new GenericAllocationSourceDestination(shipmentScheduleQtyPickedStorage, schedule); } @NonNull private ILUTUProducerAllocationDestination createLUTUProducerDestination(@NonNull final I_M_ShipmentSchedule schedule) { final I_M_HU_LUTU_Configuration lutuConfiguration = huShipmentScheduleBL.deriveM_HU_LUTU_Configuration(schedule); lutuConfigurationFactory.save(lutuConfiguration); final ILUTUProducerAllocationDestination luProducerDestination = lutuConfigurationFactory.createLUTUProducerAllocationDestination(lutuConfiguration); // // Make sure we have our LU PI configured if (luProducerDestination.isNoLU()) { throw new HUException("No Loading Unit found for TU: " + luProducerDestination.getTUPI() + "\n@M_ShipmentSchedule_ID@: " + schedule + "\n@Destination@: " + luProducerDestination); } return luProducerDestination; } @NonNull private List<ShipmentScheduleWithHU> getAlreadyPickedOnTheFlyButNotDelivered(@NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull final IHUContext huContext) { return shipmentScheduleAllocDAO.retrievePickedOnTheFlyAndNotDelivered(shipmentScheduleId, I_M_ShipmentSchedule_QtyPicked.class) .stream() .map(pickedLine -> ShipmentScheduleWithHU.ofShipmentScheduleQtyPicked(pickedLine, huContext)) .collect(ImmutableList.toImmutableList()); } @NonNull private Quantity getQtyToAllocate(@NonNull final List<ShipmentScheduleWithHU> alreadyAllocatedHUs, @NonNull final Quantity qtyToDeliver) { return alreadyAllocatedHUs.stream() .map(ShipmentScheduleWithHU::getQtyPicked) .reduce(qtyToDeliver, Quantity::subtract); } private void aggregateCUsToTUs(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return; }
ShipmentSchedulesCUsToTUsAggregator.builder() .huShipmentScheduleBL(huShipmentScheduleBL) .shipmentScheduleAllocDAO(shipmentScheduleAllocDAO) .handlingUnitsBL(handlingUnitsBL) // .shipmentScheduleIds(shipmentScheduleIds) // .build().execute(); } @NonNull public Set<InOutLineId> retrieveInOuLineIdByShipScheduleId(@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return shipmentScheduleAllocDAO.retrieveOnShipmentLineRecordsByScheduleIds(scheduleIds) .values() .stream() .map(de.metas.inoutcandidate.model.I_M_ShipmentSchedule_QtyPicked::getM_InOutLine_ID) .map(InOutLineId::ofRepoIdOrNull) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleWithHUService.java
1
请完成以下Java代码
public String toString() { return getClass().getName() + " [headerValue=" + this.headerValue + "]"; } /** * Represents the directive values expected by the {@link ClearSiteDataHeaderWriter}. */ public enum Directive { CACHE("cache"), COOKIES("cookies"), STORAGE("storage"), EXECUTION_CONTEXTS("executionContexts"), ALL("*"); private final String headerValue; Directive(String headerValue) { this.headerValue = "\"" + headerValue + "\""; } public String getHeaderValue() { return this.headerValue; }
} private static final class SecureRequestMatcher implements RequestMatcher { @Override public boolean matches(HttpServletRequest request) { return request.isSecure(); } @Override public String toString() { return "Is Secure"; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\ClearSiteDataHeaderWriter.java
1
请完成以下Java代码
public class NewPlatformVersionTrigger implements NotificationRuleTrigger { @Serial private static final long serialVersionUID = 3298785969736390092L; private final UpdateMessage updateInfo; @Override public NotificationRuleTriggerType getType() { return NotificationRuleTriggerType.NEW_PLATFORM_VERSION; } @Override public TenantId getTenantId() { return TenantId.SYS_TENANT_ID; }
@Override public EntityId getOriginatorEntityId() { return TenantId.SYS_TENANT_ID; } @Override public DeduplicationStrategy getDeduplicationStrategy() { return DeduplicationStrategy.ALL; } @Override public String getDeduplicationKey() { return String.join(":", NotificationRuleTrigger.super.getDeduplicationKey(), updateInfo.getCurrentVersion(), updateInfo.getLatestVersion()); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\rule\trigger\NewPlatformVersionTrigger.java
1
请在Spring Boot框架中完成以下Java代码
public class Comment { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String description; private Date date; public void setId(long id) { this.id = id; } public void setDescription(String description) { this.description = description; }
public void setDate(Date total) { this.date = total; } public long getId() { return id; } public String getDescription() { return description; } public Date getDate() { return date; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\data\persistence\unidirectionalcascadingdelete\Comment.java
2
请完成以下Java代码
private Optional<I_C_Order> getOrderByExternalId(@NonNull final OrderQuery orderQuery) { final OrgId orgId = assumeNotNull(orderQuery.getOrgId(), "Param query needs to have a non-null orgId; query={}", orderQuery); final ExternalId externalId = assumeNotNull(orderQuery.getExternalId(), "Param query needs to have a non-null externalId; query={}", orderQuery); final IQueryBuilder<I_C_Order> queryBuilder = createQueryBuilder() .addEqualsFilter(I_C_Order.COLUMNNAME_AD_Org_ID, orgId) .addEqualsFilter(I_C_Order.COLUMNNAME_ExternalId, externalId.getValue()); final InputDataSourceId dataSourceId = orderQuery.getInputDataSourceId(); if (dataSourceId != null) { queryBuilder.addEqualsFilter(I_C_Order.COLUMNNAME_AD_InputDataSource_ID, dataSourceId); } final ExternalSystemId externalSystemId = orderQuery.getExternalSystemId(); if (externalSystemId != null)
{ queryBuilder.addEqualsFilter(I_C_Order.COLUMNNAME_ExternalSystem_ID, externalSystemId); } return queryBuilder .create() .firstOnlyOptional(); } public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter) { return queryBL.createQueryBuilder(I_C_Order.class) .filter(queryFilter) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\AbstractOrderDAO.java
1
请完成以下Java代码
public HashcodeBuilder appendHashcode(final int hashcodeToAppend) { hashcode = prime * hashcode + hashcodeToAppend; return this; } public HashcodeBuilder append(Map<?, ?> map, boolean handleEmptyMapAsNull) { if (handleEmptyMapAsNull && (map == null || map.isEmpty())) { return append((Object)null); } return append(map); } public int toHashcode() { return hashcode; } /**
* Sames as {@link #toHashcode()} because: * <ul> * <li>we want to avoid bugs like calling this method instead of {@link #toHashcode()} * <li>the real hash code of this object does not matter * </ul> * * @deprecated Please use {@link #toHashcode()}. This method is present here, just to avoid some mistakes. */ @Deprecated @Override public int hashCode() { return toHashcode(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\HashcodeBuilder.java
1
请完成以下Java代码
public Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) { var identityProviderProperties = oAuth2Properties.getIdentityProvider(); var groupNameAttribute = identityProviderProperties.getGroupNameAttribute(); Set<GrantedAuthority> mappedAuthorities = new HashSet<>(); authorities.forEach(authority -> { if (authority instanceof OAuth2UserAuthority) { var oauth2UserAuthority = (OAuth2UserAuthority) authority; Object groupAttribute = oauth2UserAuthority.getAttributes().get(groupNameAttribute); if (groupAttribute == null) { logger.debug("Attribute {} is not available", groupNameAttribute); return; } if (groupAttribute instanceof Collection) { //noinspection unchecked Collection<String> groupsAttribute = (Collection<String>) groupAttribute; var grantedAuthorities = groupsAttribute.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); mappedAuthorities.addAll(grantedAuthorities); } else if (groupAttribute instanceof String) { String groupNameDelimiter = identityProviderProperties.getGroupNameDelimiter(); String groupsAttribute = (String) groupAttribute;
var grantedAuthorities = Arrays.stream(groupsAttribute.split(groupNameDelimiter)) .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); mappedAuthorities.addAll(grantedAuthorities); } else { logger.error("Could not map granted authorities, unsupported group attribute type: {}", groupAttribute.getClass()); } } }); logger.debug("Authorities mapped from {} to {}", authorities, mappedAuthorities); return mappedAuthorities; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\OAuth2GrantedAuthoritiesMapper.java
1
请完成以下Java代码
public void onBeforeElementDelete(@NonNull final I_AD_UI_Element uiElement) { final IQueryBL queryBL = Services.get(IQueryBL.class); queryBL.createQueryBuilder(I_AD_UI_ElementField.class) .addEqualsFilter(I_AD_UI_ElementField.COLUMN_AD_UI_Element_ID, uiElement.getAD_UI_Element_ID()) .create() .delete(); } @CalloutMethod(columnNames = I_AD_UI_Element.COLUMNNAME_AD_Field_ID) public void calloutOnFieldIdChanged(@NonNull final I_AD_UI_Element uiElement) { if (uiElement.getAD_Field_ID() > 0) { updateNameFromElement(uiElement); } } private void updateNameFromElement(@NonNull final I_AD_UI_Element uiElement) { final I_AD_Field field = uiElement.getAD_Field();
final AdElementId fieldElementId = getFieldElementId(field); final I_AD_Element fieldElement = Services.get(IADElementDAO.class).getById(fieldElementId.getRepoId()); uiElement.setName(fieldElement.getName()); uiElement.setDescription(fieldElement.getDescription()); uiElement.setHelp(fieldElement.getHelp()); } private AdElementId getFieldElementId(final I_AD_Field field) { if (field.getAD_Name_ID() > 0) { return AdElementId.ofRepoId(field.getAD_Name_ID()); } else { final I_AD_Column fieldColumn = field.getAD_Column(); return AdElementId.ofRepoId(fieldColumn.getAD_Element_ID()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\model\interceptor\AD_UI_Element.java
1
请完成以下Java代码
public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; return Objects.equals(this.code, _apiResponse.code) && Objects.equals(this.type, _apiResponse.type) && Objects.equals(this.message, _apiResponse.message); } @Override public int hashCode() { return Objects.hash(code, type, message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
1
请完成以下Java代码
public class RestException extends ExternalTaskClientException { protected Integer httpStatusCode; protected String type; protected Integer code; public RestException(String message, String type, Integer code) { super(message); this.type = type; this.code = code; } public RestException(String message, Throwable throwable) { super(message, throwable); } /** * @return the http status code from the Engine's REST API. */ public Integer getHttpStatusCode() { return getCause() == null ? httpStatusCode : ((RestException) getCause()).getHttpStatusCode(); } public void setHttpStatusCode(Integer httpStatusCode) { this.httpStatusCode = httpStatusCode; }
/** * @return the exception type from the Engine's REST API. */ public String getType() { return getCause() == null ? type : ((RestException) getCause()).getType(); } public void setType(String type) { this.type = type; } /** * @return the exception error code from the Engine's REST API. */ public Integer getCode() { return getCause() == null ? code : ((RestException) getCause()).getCode(); } public void setCode(Integer code) { this.code = code; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\exception\RestException.java
1
请完成以下Java代码
public int getReadCount() { return readCount; } public void setReadCount(int readCount) { this.readCount = readCount; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getLikeCount() { return likeCount; } public void setLikeCount(int likeCount) { this.likeCount = likeCount; } public String getComentTmp() { return comentTmp; } public void setComentTmp(String comentTmp) { this.comentTmp = comentTmp; } public List<String> getComment() { return comment; } public void setComment(List<String> comment) { this.comment = comment; } public String getUrl() {
return url; } public void setUrl(String url) { this.url = url; } public String getUrlMd5() { return urlMd5; } public void setUrlMd5(String urlMd5) { this.urlMd5 = urlMd5; } @Override public String toString() { return "Blog{" + "title='" + title + '\'' + ", publishDate=" + publishDate + ", readCountStr='" + readCountStr + '\'' + ", readCount=" + readCount + ", content='" + content + '\'' + ", likeCount=" + likeCount + ", comentTmp='" + comentTmp + '\'' + ", url='" + url + '\'' + ", comment=" + comment + '}'; } }
repos\spring-boot-quick-master\quick-vw-crawler\src\main\java\com\crawler\vw\entity\Blog.java
1
请完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } public Map<String, Object> getCorrelationProcessInstanceVariables() { return correlationProcessInstanceVariables; } public Map<String, Object> getCorrelationLocalVariables() { return correlationLocalVariables; } public Map<String, Object> getPayloadProcessInstanceVariables() { return payloadProcessInstanceVariables; } public VariableMap getPayloadProcessInstanceVariablesLocal() { return payloadProcessInstanceVariablesLocal; } public VariableMap getPayloadProcessInstanceVariablesToTriggeredScope() { return payloadProcessInstanceVariablesToTriggeredScope; } public boolean isExclusiveCorrelation() {
return isExclusiveCorrelation; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isExecutionsOnly() { return executionsOnly; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationBuilderImpl.java
1
请完成以下Java代码
public static HUConsolidationJobReference ofJob(@NonNull final HUConsolidationJob job) { return builder() .bpartnerLocationId(job.getShipToBPLocationId()) .pickingSlotIds(job.getPickingSlotIds()) .countHUs(null) .startedJobId(job.getId()) .build(); } public Params toParams() { return Params.builder() .value("bpartnerId", bpartnerLocationId.getBpartnerId().getRepoId()) .value("bpartnerLocationId", bpartnerLocationId.getRepoId()) .value("pickingSlotIds", RepoIdAwares.toCommaSeparatedString(pickingSlotIds)) .value("countHUs", countHUs) .value("startedJobId", startedJobId != null ? startedJobId.getRepoId() : null) .build(); } public boolean isStatsMissing() { return countHUs == null; } public OptionalInt getCountHUs() { return countHUs != null ? OptionalInt.of(countHUs) : OptionalInt.empty(); } public HUConsolidationJobReference withUpdatedStats(@NonNull final PickingSlotQueuesSummary summary) { final OptionalInt optionalCountHUs = summary.getCountHUs(pickingSlotIds); if (optionalCountHUs.isPresent()) {
final int countHUsNew = optionalCountHUs.getAsInt(); if (this.countHUs == null || this.countHUs != countHUsNew) { return toBuilder().countHUs(countHUsNew).build(); } else { return this; } } else { return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobReference.java
1
请完成以下Java代码
public int compare(Object o1, Object o2) { if (!(o1 instanceof MAssignmentSlot && o2 instanceof MAssignmentSlot)) throw new ClassCastException ("MAssignmentSlot.compare arguments not MAssignmentSlot"); MAssignmentSlot s1 = (MAssignmentSlot)o1; MAssignmentSlot s2 = (MAssignmentSlot)o2; // Start Date int result = s1.getStartTime().compareTo(s2.getStartTime()); if (result != 0) return result; // Status result = s2.getStatus() - s1.getStatus(); if (result != 0) return result; // End Date result = s1.getEndTime().compareTo(s2.getEndTime()); if (result != 0) return result; // Name result = s1.getName().compareTo(s2.getName()); if (result != 0) return result; // Description return s1.getDescription().compareTo(s2.getDescription()); } // compare /** * Indicates whether some other object is &quot;equal to&quot; this * Comparator. * @param obj the reference object with which to compare. * @return <code>true</code> only if the specified object is also * a comparator and it imposes the same ordering as this * comparator.
* @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#hashCode() */ public boolean equals(Object obj) { if (obj instanceof MAssignmentSlot) { MAssignmentSlot cmp = (MAssignmentSlot)obj; if (m_startTime.equals(cmp.getStartTime()) && m_endTime.equals(cmp.getEndTime()) && m_status == cmp.getStatus() && m_name.equals(cmp.getName()) && m_description.equals(cmp.getDescription())) return true; } return false; } // equals /** * HashCode of MAssignmentSlot * @return has code */ public int hashCode() { return m_startTime.hashCode() + m_endTime.hashCode() + m_status + m_name.hashCode() + m_description.hashCode(); } // hashCode } // MAssignmentSlot
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAssignmentSlot.java
1
请完成以下Java代码
private Optional<MqttMessage> processConvertFromGatewayAttributeResponseMsg(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { if (!StringUtils.isEmpty(responseMsg.getError())) { throw new AdaptorException(responseMsg.getError()); } else { JsonObject result = JsonConverter.getJsonObjectForGateway(deviceName, responseMsg); return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, result)); } } protected MqttPublishMessage createMqttPublishMsg(MqttDeviceAwareSessionContext ctx, String topic, JsonElement json) { MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, ctx.getQoSForTopic(topic), false, 0); MqttPublishVariableHeader header = new MqttPublishVariableHeader(topic, ctx.nextMsgId()); ByteBuf payload = ALLOCATOR.buffer(); payload.writeBytes(json.toString().getBytes(UTF8)); return new MqttPublishMessage(mqttFixedHeader, header, payload); } private Set<String> toStringSet(JsonElement requestBody, String name) { JsonElement element = requestBody.getAsJsonObject().get(name); if (element != null) { return new HashSet<>(Arrays.asList(element.getAsString().split(","))); } else { return null; } }
private static String validatePayload(UUID sessionId, ByteBuf payloadData, boolean isEmptyPayloadAllowed) throws AdaptorException { String payload = payloadData.toString(UTF8); if (payload == null) { log.debug("[{}] Payload is empty!", sessionId); if (!isEmptyPayloadAllowed) { throw new AdaptorException(new IllegalArgumentException("Payload is empty!")); } } return payload; } private int getRequestId(String topicName, String topic) { return Integer.parseInt(topicName.substring(topic.length())); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\adaptors\JsonMqttAdaptor.java
1
请在Spring Boot框架中完成以下Java代码
public void configureClientInboundChannel(final ChannelRegistration registration) { registration.interceptors(new LoggingChannelInterceptor()); // NOTE: atm we don't care if the inbound messages arrived in the right order // When and If we would care we would restrict the taskExecutor()'s corePoolSize to ONE. // see: configureClientOutboundChannel(). } @Override public boolean configureMessageConverters(final List<MessageConverter> messageConverters) { final MappingJackson2MessageConverter jsonConverter = new MappingJackson2MessageConverter(); jsonConverter.setObjectMapper(JsonObjectMapperHolder.sharedJsonObjectMapper()); messageConverters.add(jsonConverter); return true; } private static class LoggingChannelInterceptor implements ChannelInterceptor { private static final Logger logger = LogManager.getLogger(LoggingChannelInterceptor.class); @Override
public void afterSendCompletion(final @NonNull Message<?> message, final @NonNull MessageChannel channel, final boolean sent, final Exception ex) { if (!sent) { logger.warn("Failed sending: message={}, channel={}, sent={}", message, channel, sent, ex); } } @Override public void afterReceiveCompletion(final Message<?> message, final @NonNull MessageChannel channel, final Exception ex) { if (ex != null) { logger.warn("Failed receiving: message={}, channel={}", message, channel, ex); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\config\WebsocketConfig.java
2
请完成以下Java代码
public TableRecordReference getFirstRecord() { return getRecords().get(0); } } // // // // // public enum ViewOpenTarget { IncludedView, ModalOverlay, NewBrowserTab } @Immutable @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Value public static class WebuiViewToOpen { @JsonProperty("viewId") String viewId; @JsonProperty("profileId") String profileId; @JsonProperty("target") ViewOpenTarget target; @lombok.Builder @JsonCreator private WebuiViewToOpen( @JsonProperty("viewId") @NonNull final String viewId, @JsonProperty("profileId") @Nullable final String profileId, @JsonProperty("target") @NonNull final ViewOpenTarget target) { this.viewId = viewId; this.profileId = profileId; this.target = target; } public static WebuiViewToOpen modalOverlay(@NonNull final String viewId) { return builder().viewId(viewId).target(ViewOpenTarget.ModalOverlay).build(); } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Value public static class DisplayQRCode
{ @JsonProperty("code") String code; @lombok.Builder @JsonCreator private DisplayQRCode(@JsonProperty("code") @NonNull final String code) { this.code = code; } } @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) @lombok.Value @lombok.Builder public static class WebuiNewRecord { /** * If this string is used as field value * then the frontend will try to open the new record modal window to populate that field. * <p> * Used mainly to trigger new BPartner. */ public static final String FIELD_VALUE_NEW = "NEW"; @NonNull String windowId; /** * Field values to be set by frontend, after the NEW record is created */ @NonNull @Singular Map<String, String> fieldValues; public enum TargetTab { SAME_TAB, NEW_TAB, } @NonNull @Builder.Default TargetTab targetTab = TargetTab.SAME_TAB; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutionResult.java
1
请完成以下Java代码
public List<EventSubscriptionQueryValue> getEventSubscriptions() { return eventSubscriptions; } public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) { this.eventSubscriptions = eventSubscriptions; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getName() { return name; } public String getNameLike() { return nameLike; } public void setName(String name) { this.name = name; } public void setNameLike(String nameLike) { this.nameLike = nameLike; } public String getExecutionId() { return executionId; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean iswithException() { return withJobException; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null;
} public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage, @NonNull final String localTrxName) { final List<OLCandId> candidateIds = queueDAO.retrieveItems(workPackage, I_C_OLCand.class, localTrxName) .stream() .map(I_C_OLCand::getC_OLCand_ID) .map(OLCandId::ofRepoId) .collect(ImmutableList.toImmutableList()); if (candidateIds.isEmpty()) { Loggables.withLogger(logger, Level.DEBUG).addLog("No OLCands enqueued to be processed for C_Queue_WorkPackage_ID={}", workPackage.getC_Queue_WorkPackage_ID()); return Result.SUCCESS; } final PInstanceId enqueuedSelection = queryBL.createQueryBuilder(I_C_OLCand.class) .addInArrayFilter(I_C_OLCand.COLUMNNAME_C_OLCand_ID, candidateIds) .create() .createSelection(); final int olCandProcessorId = getParameters().getParameterAsInt(PARAM_OLCandProcessor_ID, C_OlCandProcessor_ID_Default); final boolean propagateAsyncBatchIdToOrderRecord = getParameters().getParameterAsBool(PARAM_PROPAGATE_ASYNC_BATCH_ID_TO_ORDER_RECORD);
final OLCandProcessorDescriptor olCandProcessorDescriptor = olCandProcessorRepo.getById(olCandProcessorId); try { olCandBL.process(IOLCandBL.OLCandProcessRequest.builder() .processor(olCandProcessorDescriptor) .selectionId(enqueuedSelection) .asyncBatchId(AsyncBatchId.ofRepoIdOrNull(workPackage.getC_Async_Batch_ID())) .propagateAsyncBatchIdToOrderRecord(propagateAsyncBatchIdToOrderRecord) .build()); } catch (final Exception ex) { Loggables.withLogger(logger, Level.ERROR).addLog("@Error@: " + ex.getLocalizedMessage()); Loggables.withLogger(logger, Level.ERROR).addLog("@Rollback@"); throw AdempiereException.wrapIfNeeded(ex); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\async\C_OLCandToOrderWorkpackageProcessor.java
1
请完成以下Java代码
public void afterCommit() { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.ROLLINGBACK)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void beforeCompletion() { transactionListener.execute(commandContext); } } ); } else if (transactionState.equals(TransactionState.ROLLED_BACK)) { TransactionSynchronizationManager.registerSynchronization( new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { if (TransactionSynchronization.STATUS_ROLLED_BACK == status) { transactionListener.execute(commandContext); } } } ); } } protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered { public void suspend() {} public void resume() {}
public void flush() {} public void beforeCommit(boolean readOnly) {} public void beforeCompletion() {} public void afterCommit() {} public void afterCompletion(int status) {} @Override public int getOrder() { return transactionSynchronizationAdapterOrder; } } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringTransactionContext.java
1
请在Spring Boot框架中完成以下Java代码
public class Metasfresh { @ManagedOperation public String[] getActiveTrxNames() { return Services.get(ITrxManager.class) .getActiveTransactionsList() .stream() .map((trx) -> trx.getTrxName()) .toArray((size) -> new String[size]); } @ManagedOperation public String getStrackTrace(String trxName) { return Services.get(IOpenTrxBL.class).getCreationStackTrace(trxName); } @ManagedOperation public String[] getServerContext() { final Properties ctx = Env.getCtx(); String[] context = Env.getEntireContext(ctx); Arrays.sort(context); return context; } @ManagedOperation public void setLogLevel(String levelName)
{ LogManager.setLevel(levelName); } @ManagedOperation public String getLogLevel() { final Level level = LogManager.getLevel(); return level == null ? null : level.toString(); } @ManagedOperation public void runFinalization() { System.runFinalization(); } @ManagedOperation public void resetLocalCache() { CacheMgt.get().reset(); } @ManagedOperation public void rotateMigrationScriptFile() { MigrationScriptFileLoggerHolder.closeMigrationScriptFiles(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\jmx\Metasfresh.java
2
请完成以下Java代码
public class TouristData { private String region; private String country; private String year; private String series; private Double value; private String footnotes; private String source; public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public Double getValue() { return value;
} public void setValue(Double value) { this.value = value; } public String getFootnotes() { return footnotes; } public void setFootnotes(String footnotes) { this.footnotes = footnotes; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } @Override public String toString() { return "TouristData [region=" + region + ", country=" + country + ", year=" + year + ", series=" + series + ", value=" + value + ", footnotes=" + footnotes + ", source=" + source + "]"; } }
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\differences\dataframe\dataset\rdd\TouristData.java
1
请完成以下Java代码
public class DeleteBatchCmd implements Command<Void> { protected boolean cascadeToHistory; protected String batchId; public DeleteBatchCmd(String batchId, boolean cascadeToHistory) { this.batchId = batchId; this.cascadeToHistory = cascadeToHistory; } @Override public Void execute(CommandContext commandContext) { ensureNotNull(BadUserRequestException.class, "Batch id must not be null", "batch id", batchId); BatchEntity batchEntity = commandContext.getBatchManager().findBatchById(batchId); ensureNotNull(BadUserRequestException.class, "Batch for id '" + batchId + "' cannot be found", "batch", batchEntity); checkAccess(commandContext, batchEntity); writeUserOperationLog(commandContext, batchEntity.getTenantId()); batchEntity.delete(cascadeToHistory, true); return null;
} protected void checkAccess(CommandContext commandContext, BatchEntity batch) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkDeleteBatch(batch); } } protected void writeUserOperationLog(CommandContext commandContext, String tenantId) { commandContext.getOperationLogManager() .logBatchOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, batchId, tenantId, new PropertyChange("cascadeToHistory", null, cascadeToHistory)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\DeleteBatchCmd.java
1
请完成以下Java代码
public static int getRepetitionCounter(PlanItemInstanceEntity repeatingPlanItemInstanceEntity) { Integer counter = (Integer) repeatingPlanItemInstanceEntity.getVariableLocal(getCounterVariable(repeatingPlanItemInstanceEntity)); if (counter == null) { return 0; } else { return counter.intValue(); } } public static boolean hasIgnoreCounterVariable(PlanItemInstanceEntity repeatingPlanItemInstanceEntity) { return repeatingPlanItemInstanceEntity.getPlanItem().getItemControl().getRepetitionRule().isIgnoreRepetitionCounterVariable(); } public static String getCounterVariable(PlanItemInstanceEntity repeatingPlanItemInstanceEntity) { String repetitionCounterVariableName = repeatingPlanItemInstanceEntity.getPlanItem().getItemControl().getRepetitionRule().getRepetitionCounterVariableName(); return repetitionCounterVariableName; } protected static PlanItemInstanceEntity createPlanItemInstanceDuplicateForCollectionRepetition(RepetitionRule repetitionRule, PlanItemInstanceEntity planItemInstanceEntity, String entryCriterionId, Object item, int index, CommandContext commandContext) { // check, if we need to set local variables as the item or item index Map<String, Object> localVariables = new HashMap<>(2); if (repetitionRule.hasElementVariable()) {
localVariables.put(repetitionRule.getElementVariableName(), item); } if (repetitionRule.hasElementIndexVariable()) { localVariables.put(repetitionRule.getElementIndexVariableName(), index); } PlanItemInstanceEntity childPlanItemInstanceEntity = PlanItemInstanceUtil.copyAndInsertPlanItemInstance(commandContext, planItemInstanceEntity, localVariables, false, false); // record the plan item being created based on the collection, so it gets synchronized to the history as well CommandContextUtil.getAgenda(commandContext).planCreateRepeatedPlanItemInstanceOperation(childPlanItemInstanceEntity); // The repetition counter is 1 based if (repetitionRule.getAggregations() != null || !repetitionRule.isIgnoreRepetitionCounterVariable()) { childPlanItemInstanceEntity.setVariableLocal(PlanItemInstanceUtil.getCounterVariable(childPlanItemInstanceEntity), index + 1); } // createPlanItemInstance operations will also sync planItemInstance history CommandContextUtil.getAgenda(commandContext).planActivatePlanItemInstanceOperation(childPlanItemInstanceEntity, entryCriterionId); return childPlanItemInstanceEntity; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\PlanItemInstanceUtil.java
1
请完成以下Java代码
public List<DataAssociation> getDataInputAssociations() { return dataInputAssociations; } public void setDataInputAssociations(List<DataAssociation> dataInputAssociations) { this.dataInputAssociations = dataInputAssociations; } public List<DataAssociation> getDataOutputAssociations() { return dataOutputAssociations; } public void setDataOutputAssociations(List<DataAssociation> dataOutputAssociations) { this.dataOutputAssociations = dataOutputAssociations; } public List<MapExceptionEntry> getMapExceptions() { return mapExceptions; } public void setMapExceptions(List<MapExceptionEntry> mapExceptions) { this.mapExceptions = mapExceptions; } public void setValues(Activity otherActivity) { super.setValues(otherActivity); setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue()); setDefaultFlow(otherActivity.getDefaultFlow()); setForCompensation(otherActivity.isForCompensation()); if (otherActivity.getLoopCharacteristics() != null) { setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone()); } if (otherActivity.getIoSpecification() != null) { setIoSpecification(otherActivity.getIoSpecification().clone());
} dataInputAssociations = new ArrayList<DataAssociation>(); if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) { for (DataAssociation association : otherActivity.getDataInputAssociations()) { dataInputAssociations.add(association.clone()); } } dataOutputAssociations = new ArrayList<DataAssociation>(); if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) { for (DataAssociation association : otherActivity.getDataOutputAssociations()) { dataOutputAssociations.add(association.clone()); } } boundaryEvents.clear(); for (BoundaryEvent event : otherActivity.getBoundaryEvents()) { boundaryEvents.add(event); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java
1
请完成以下Spring Boot application配置
spring: application: name: product-service server: port: '8080' priceClient: baseUrl: http://price-service:8081 management: tracing: sampling: probabilit
y: '1.0' otlp: tracing: endpoint: http://collector:4318/v1/traces
repos\tutorials-master\spring-boot-modules\spring-boot-open-telemetry\spring-boot-open-telemetry1\src\main\resources\application.yml
2
请完成以下Java代码
public int getAD_Issue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Issue_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public org.compiere.model.I_API_Request_Audit getAPI_Request_Audit() { return get_ValueAsPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class); } @Override public void setAPI_Request_Audit(final org.compiere.model.I_API_Request_Audit API_Request_Audit) { set_ValueFromPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class, API_Request_Audit); } @Override public void setAPI_Request_Audit_ID (final int API_Request_Audit_ID) { if (API_Request_Audit_ID < 1) set_Value (COLUMNNAME_API_Request_Audit_ID, null); else set_Value (COLUMNNAME_API_Request_Audit_ID, API_Request_Audit_ID); } @Override public int getAPI_Request_Audit_ID() { return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID); } @Override public void setAPI_Request_Audit_Log_ID (final int API_Request_Audit_Log_ID) { if (API_Request_Audit_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_API_Request_Audit_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_API_Request_Audit_Log_ID, API_Request_Audit_Log_ID); } @Override public int getAPI_Request_Audit_Log_ID() { return get_ValueAsInt(COLUMNNAME_API_Request_Audit_Log_ID); } @Override public void setLogmessage (final @Nullable java.lang.String Logmessage) { set_Value (COLUMNNAME_Logmessage, Logmessage); } @Override public java.lang.String getLogmessage() { return get_ValueAsString(COLUMNNAME_Logmessage); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID()
{ return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setTrxName (final @Nullable java.lang.String TrxName) { set_Value (COLUMNNAME_TrxName, TrxName); } @Override public java.lang.String getTrxName() { return get_ValueAsString(COLUMNNAME_TrxName); } /** * Type AD_Reference_ID=541329 * Reference name: TypeList */ public static final int TYPE_AD_Reference_ID=541329; /** Created = Created */ public static final String TYPE_Created = "Created"; /** Updated = Updated */ public static final String TYPE_Updated = "Updated"; /** Deleted = Deleted */ public static final String TYPE_Deleted = "Deleted"; @Override public void setType (final @Nullable java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit_Log.java
1
请完成以下Java代码
protected <T extends AppPlugin> CharSequence createPluginPackagesStr(String appName, String applicationPath, String contextPath) { final List<T> plugins = getPlugins(appName); StringBuilder builder = new StringBuilder(); for (T plugin : plugins) { if (builder.length() > 0) { builder.append(", ").append("\n"); } String pluginId = plugin.getId(); String definition = String.format(pluginPackageFormat, appName, pluginId, contextPath, applicationPath, appName, pluginId); builder.append(definition); } return "[" + builder.toString() + "]"; } protected <T extends AppPlugin> CharSequence createPluginDependenciesStr(String appName) { final List<T> plugins = getPlugins(appName); StringBuilder builder = new StringBuilder(); for (T plugin : plugins) { if (builder.length() > 0) { builder.append(", ").append("\n"); } String pluginId = plugin.getId();
String definition = String.format(pluginDependencyFormat, appName, pluginId, appName, pluginId); builder.append(definition); } return "[" + builder.toString() + "]"; } @SuppressWarnings("unchecked") protected <T extends AppPlugin> List<T> getPlugins(String appName) { if (COCKPIT_APP_NAME.equals(appName)) { return (List<T>) cockpitRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else if (ADMIN_APP_NAME.equals(appName)) { return (List<T>) adminRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else if (TASKLIST_APP_NAME.equals(appName)) { return (List<T>) tasklistRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else if (WELCOME_APP_NAME.equals(appName)) { return (List<T>) welcomeRuntimeDelegate.getAppPluginRegistry().getPlugins(); } else { return Collections.emptyList(); } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\engine\ProcessEnginesFilter.java
1
请完成以下Java代码
public MailTextBuilder record(final Object record) { _record = record; invalidateCache(); return this; } public MailTextBuilder recordAndUpdateBPartnerAndContact(final Object record) { record(record); if (record != null) { updateBPartnerAndContactFromRecord(record); } return this; } private void updateBPartnerAndContactFromRecord(@NonNull final Object record) { final BPartnerId bpartnerId = extractBPartnerId(record); if (bpartnerId != null) { bpartner(bpartnerId); } final UserId bpartnerContactId = extractBPartnerContactId(record); if (bpartnerContactId != null) { bpartnerContact(bpartnerContactId); } } private BPartnerId extractBPartnerId(final Object record) { final Object bpartnerIdObj = InterfaceWrapperHelper.getValueOrNull(record, "C_BPartner_ID"); if (!(bpartnerIdObj instanceof Integer)) { return null; } final int bpartnerRepoId = (Integer)bpartnerIdObj; return BPartnerId.ofRepoIdOrNull(bpartnerRepoId); } private UserId extractBPartnerContactId(final Object record) {
final Integer userIdObj = InterfaceWrapperHelper.getValueOrNull(record, "AD_User_ID"); if (!(userIdObj instanceof Integer)) { return null; } final int userRepoId = userIdObj.intValue(); return UserId.ofRepoIdOrNull(userRepoId); } private Object getRecord() { return _record; } public MailTextBuilder customVariable(@NonNull final String name, @Nullable final String value) { return customVariable(name, TranslatableStrings.anyLanguage(value)); } public MailTextBuilder customVariable(@NonNull final String name, @NonNull final ITranslatableString value) { _customVariables.put(name, value); invalidateCache(); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTextBuilder.java
1
请完成以下Java代码
public List<I_C_ProjectTask> getTasks() { return Services.get(IQueryBL.class).createQueryBuilder(I_C_ProjectTask.class) .addEqualsFilter(I_C_ProjectTask.COLUMNNAME_C_ProjectPhase_ID, getC_ProjectPhase_ID()) .orderBy(I_C_ProjectTask.COLUMNNAME_SeqNo) .create() .list(); } /** * @return number of tasks copied */ public int copyTasksFrom (final MProjectPhase fromPhase) { if (fromPhase == null) return 0; int count = 0; // final List<I_C_ProjectTask> myTasks = getTasks(); final List<I_C_ProjectTask> fromTasks = fromPhase.getTasks(); // Copy Project Tasks for (final I_C_ProjectTask fromTask : fromTasks) { // Check if Task already exists final int C_Task_ID = fromTask.getC_Task_ID(); boolean exists = false; if (C_Task_ID != 0) { for (final I_C_ProjectTask myTask : myTasks) { if (myTask.getC_Task_ID() == C_Task_ID) { exists = true; break; } } } // Phase exist if (exists) log.info("Task already exists here, ignored - " + fromTask); else { final I_C_ProjectTask toTask = InterfaceWrapperHelper.create(getCtx(), I_C_ProjectTask.class, get_TrxName()); PO.copyValues(
InterfaceWrapperHelper.getPO(fromTask), InterfaceWrapperHelper.getPO(toTask), getAD_Client_ID(), getAD_Org_ID()); toTask.setC_ProjectPhase_ID(getC_ProjectPhase_ID()); InterfaceWrapperHelper.save(toTask); count++; } } if (fromTasks.size() != count) log.warn("Count difference - ProjectPhase=" + fromTasks.size() + " <> Saved=" + count); return count; } @Override public String toString () { return "MProjectPhase[" + get_ID() + "-" + getSeqNo() + "-" + getName() + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProjectPhase.java
1
请在Spring Boot框架中完成以下Java代码
protected Mono<StatusInfo> convertStatusInfo(ClientResponse response) { boolean hasCompatibleContentType = response.headers() .contentType() .filter((mt) -> mt.isCompatibleWith(MediaType.APPLICATION_JSON) || this.apiMediaTypeHandler.isApiMediaType(mt)) .isPresent(); StatusInfo statusInfoFromStatus = this.getStatusInfoFromStatus(response.statusCode(), emptyMap()); if (hasCompatibleContentType) { return response.bodyToMono(RESPONSE_TYPE).map((body) -> { if (body.get("status") instanceof String) { return StatusInfo.from(body); } return getStatusInfoFromStatus(response.statusCode(), body); }).defaultIfEmpty(statusInfoFromStatus); } return response.releaseBody().then(Mono.just(statusInfoFromStatus)); } @SuppressWarnings("unchecked") protected StatusInfo getStatusInfoFromStatus(HttpStatusCode httpStatus, Map<String, ?> body) { if (httpStatus.is2xxSuccessful()) { return StatusInfo.ofUp(); } Map<String, Object> details = new LinkedHashMap<>(); details.put("status", httpStatus.value());
details.put("error", Objects.requireNonNull(HttpStatus.resolve(httpStatus.value())).getReasonPhrase()); if (body.get("details") instanceof Map) { details.putAll((Map<? extends String, ?>) body.get("details")); } else { details.putAll(body); } return StatusInfo.ofDown(details); } protected Mono<StatusInfo> handleError(Throwable ex) { Map<String, Object> details = new HashMap<>(); details.put("message", ex.getMessage()); details.put("exception", ex.getClass().getName()); return Mono.just(StatusInfo.ofOffline(details)); } protected void logError(Instance instance, Throwable ex) { if (instance.getStatusInfo().isOffline()) { log.debug("Couldn't retrieve status for {}", instance, ex); } else { log.info("Couldn't retrieve status for {}", instance, ex); } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\StatusUpdater.java
2
请完成以下Java代码
public static void closeQuietly(OutputStream os) { try { if (os != null) os.close(); } catch (IOException ignored) { } } public static void closeQuietly(Writer w) { try { if (w != null) w.close(); } catch (IOException ignored) { } }
/** * 数组分割 * * @param from 源 * @param to 目标 * @param <T> 类型 * @return 目标 */ public static <T> T[] shrink(T[] from, T[] to) { assert to.length <= from.length; System.arraycopy(from, 0, to, 0, to.length); return to; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Utility.java
1
请完成以下Java代码
public void setChunkUUID (final @Nullable java.lang.String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID); } @Override public java.lang.String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule)
{ set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_Recompute.java
1
请完成以下Java代码
private static boolean withinTheRangeOf(int c, int min, int max) { return c >= min && c <= max; } private void validateRedirectUris() { if (CollectionUtils.isEmpty(this.redirectUris)) { return; } for (String redirectUri : this.redirectUris) { Assert.isTrue(validateRedirectUri(redirectUri), "redirect_uri \"" + redirectUri + "\" is not a valid redirect URI or contains fragment"); } } private void validatePostLogoutRedirectUris() { if (CollectionUtils.isEmpty(this.postLogoutRedirectUris)) { return; } for (String postLogoutRedirectUri : this.postLogoutRedirectUris) {
Assert.isTrue(validateRedirectUri(postLogoutRedirectUri), "post_logout_redirect_uri \"" + postLogoutRedirectUri + "\" is not a valid post logout redirect URI or contains fragment"); } } private static boolean validateRedirectUri(String redirectUri) { try { URI validRedirectUri = new URI(redirectUri); return validRedirectUri.getFragment() == null; } catch (URISyntaxException ex) { return false; } } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\RegisteredClient.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return (java.lang.String)get_Value(COLUMNNAME_Description); } @Override public void setM_CommodityNumber_ID (int M_CommodityNumber_ID) { if (M_CommodityNumber_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CommodityNumber_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CommodityNumber_ID, Integer.valueOf(M_CommodityNumber_ID)); } @Override public int getM_CommodityNumber_ID() { return get_ValueAsInt(COLUMNNAME_M_CommodityNumber_ID); } @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
} @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\fresh\model\X_M_CommodityNumber.java
1
请完成以下Java代码
protected String encodeNonNullPassword(String rawPassword) { byte[] salt = new byte[this.saltLength]; this.secureRandom.nextBytes(salt); Hash hash = Password.hash(rawPassword).addSalt(salt).with(this.balloonHashingFunction); String encodedSalt = Base64.getEncoder().encodeToString(salt); String encodedHash = hash.getResult(); return encodedSalt + DELIMITER + encodedHash; } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { if (!encodedPassword.contains(DELIMITER)) { return false; } String[] parts = encodedPassword.split(DELIMITER, 2); if (parts.length != 2) { return false; } try { byte[] salt = Base64.getDecoder().decode(parts[0]); String expectedHash = parts[1]; Hash hash = Password.hash(rawPassword).addSalt(salt).with(this.balloonHashingFunction); return expectedHash.equals(hash.getResult());
} catch (IllegalArgumentException ex) { // Invalid Base64 encoding return false; } } @Override protected boolean upgradeEncodingNonNull(String encodedPassword) { // For now, we'll return false to maintain existing behavior // This could be enhanced in the future to check if the encoding parameters // match the current configuration return false; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password4j\BalloonHashingPassword4jPasswordEncoder.java
1
请完成以下Java代码
public static Field makeAccessible(Field field) { ReflectionUtils.makeAccessible(field); return field; } /** * Makes the {@link Method} accessible. * * @param method {@link Method} to make accessible; must not be {@literal null}. * @return the given {@link Method}. * @see java.lang.reflect.Method */ public static Method makeAccessible(Method method) { ReflectionUtils.makeAccessible(method); return method; } /** * Returns the given {@link Object value} or throws an {@link IllegalArgumentException} * if {@link Object value} is {@literal null}. * * @param <T> {@link Class type} of the {@link Object value}. * @param value {@link Object} to return. * @return the {@link Object value} or throw an {@link IllegalArgumentException} * if {@link Object value} is {@literal null}. * @see #returnValueThrowOnNull(Object, RuntimeException) */ public static <T> T returnValueThrowOnNull(T value) { return returnValueThrowOnNull(value, newIllegalArgumentException("Value must not be null")); } /** * Returns the given {@link Object value} or throws the given {@link RuntimeException} * if {@link Object value} is {@literal null}. * * @param <T> {@link Class type} of the {@link Object value}. * @param value {@link Object} to return. * @param exception {@link RuntimeException} to throw if {@link Object value} is {@literal null}. * @return the {@link Object value} or throw the given {@link RuntimeException} * if {@link Object value} is {@literal null}. */ public static <T> T returnValueThrowOnNull(T value, RuntimeException exception) { if (value == null) { throw exception; }
return value; } /** * Resolves the {@link Object invocation target} for the given {@link Method}. * * If the {@link Method} is {@link Modifier#STATIC} then {@literal null} is returned, * otherwise {@link Object target} will be returned. * * @param <T> {@link Class type} of the {@link Object target}. * @param target {@link Object} on which the {@link Method} will be invoked. * @param method {@link Method} to invoke on the {@link Object}. * @return the resolved {@link Object invocation method}. * @see java.lang.Object * @see java.lang.reflect.Method */ public static <T> T resolveInvocationTarget(T target, Method method) { return Modifier.isStatic(method.getModifiers()) ? null : target; } @FunctionalInterface public interface ExceptionThrowingOperation<T> { T run() throws Exception; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\util\ObjectUtils.java
1
请完成以下Java代码
public int getPartitionSize() { final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Name der DB-Tabelle. * * @param TableName Name der DB-Tabelle */ @Override
public void setTableName(final java.lang.String TableName) { set_ValueNoCheck(COLUMNNAME_TableName, TableName); } /** * Get Name der DB-Tabelle. * * @return Name der DB-Tabelle */ @Override public java.lang.String getTableName() { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Size_Per_Table_V.java
1
请完成以下Java代码
class C_BPartner { @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_C_Doc_Outbound_Log.COLUMNNAME_IsInvoiceEmailEnabled) public void updateFlag(final I_C_BPartner bpartner) { final Properties ctx = InterfaceWrapperHelper.getCtx(bpartner); final org.compiere.model.I_AD_User defaultContact = Services.get(IBPartnerDAO.class).retrieveDefaultContactOrNull(bpartner, I_AD_User.class); final I_AD_User user = InterfaceWrapperHelper.create(defaultContact,I_AD_User.class); final boolean isInvoiceEmailEnabled = Services.get(IBPartnerBL.class).isInvoiceEmailEnabled(bpartner, user); // // retrieve latest log final I_C_Doc_Outbound_Log docExchange = Services.get(IDocOutboundDAO.class).retrieveLog(new PlainContextAware(ctx), bpartner.getC_BPartner_ID(), Services.get(IADTableDAO.class).retrieveTableId(I_C_Invoice.Table_Name)); if (docExchange == null)
{ return; } // // update outbound log accordingly which will trigger a validator <code>C_Doc_Outbound_Log</code> which will create the notification // update only for invoices final int AD_Table_ID = Services.get(IADTableDAO.class).retrieveTableId(I_C_Invoice.Table_Name); if (AD_Table_ID == docExchange.getAD_Table_ID()) { docExchange.setIsInvoiceEmailEnabled(isInvoiceEmailEnabled); InterfaceWrapperHelper.save(docExchange); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\C_BPartner.java
1
请完成以下Java代码
public ExecutionTreeNode getTreeNode(String executionId) { return getTreeNode(executionId, root); } protected ExecutionTreeNode getTreeNode(String executionId, ExecutionTreeNode currentNode) { if (currentNode.getExecutionEntity().getId().equals(executionId)) { return currentNode; } List<ExecutionTreeNode> children = currentNode.getChildren(); if (currentNode.getChildren() != null && children.size() > 0) { int index = 0; while (index < children.size()) { ExecutionTreeNode result = getTreeNode(executionId, children.get(index)); if (result != null) { return result; } index++; } } return null; } @Override public Iterator<ExecutionTreeNode> iterator() { return new ExecutionTreeBfsIterator(this.getRoot()); } public ExecutionTreeBfsIterator bfsIterator() {
return new ExecutionTreeBfsIterator(this.getRoot()); } /** * Uses an {@link ExecutionTreeBfsIterator}, but returns the leafs first (so flipped order of BFS) */ public ExecutionTreeBfsIterator leafsFirstIterator() { return new ExecutionTreeBfsIterator(this.getRoot(), true); } @Override public String toString() { return root != null ? root.toString() : ""; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTree.java
1
请在Spring Boot框架中完成以下Java代码
public String getTenantId() { return tenantId; } public Collection<String> getTenantIds() { return tenantIds; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getConfiguration() { return configuration; } public Collection<String> getConfigurations() { return configurations; }
public boolean isWithoutConfiguration() { return withoutConfiguration; } public List<EventSubscriptionQueryImpl> getOrQueryObjects() { return orQueryObjects; } public EventSubscriptionQueryImpl getCurrentOrQueryObject() { return currentOrQueryObject; } public boolean isInOrStatement() { return inOrStatement; } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\EventSubscriptionQueryImpl.java
2
请完成以下Java代码
static ITranslatableString formatDateValue(@Nullable final java.util.Date valueDate) { return valueDate != null ? TranslatableStrings.date(valueDate) : TranslatableStrings.anyLanguage("-"); } static ITranslatableString formatDateValue(@Nullable final LocalDate valueDate) { return valueDate != null ? TranslatableStrings.date(valueDate) : TranslatableStrings.anyLanguage("-"); } private void appendSeparator(final TranslatableStringBuilder description) { if (description.isEmpty()) {
return; } description.append(SEPARATOR); } private void appendProductAttributes(final TranslatableStringBuilder description) { final boolean isInstanceAttribute = false; for (final Attribute attribute : attributesRepo.retrieveAttributes(attributeSetId, isInstanceAttribute)) { appendSeparator(description); description.append(attribute.getDisplayName()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\ASIDescriptionBuilderCommand.java
1
请完成以下Java代码
private static class ColorDocumentFieldValueLoader implements DocumentFieldValueLoader { @NonNull String sqlColumnName; @Override @Nullable public Object retrieveFieldValue( @NonNull final ResultSet rs, final boolean isDisplayColumnAvailable_NOTUSED, final String adLanguage_NOTUSED, final LookupDescriptor lookupDescriptor_NOTUSED) throws SQLException { final ColorId adColorId = ColorId.ofRepoIdOrNull(rs.getInt(sqlColumnName)); if (adColorId == null) {
return null; } final IColorRepository colorRepository = Services.get(IColorRepository.class); final MFColor color = colorRepository.getColorById(adColorId); if (color == null) { return null; } final Color awtColor = color.toFlatColor().getFlatColor(); return ColorValue.ofRGB(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocumentFieldValueLoaders.java
1
请完成以下Java代码
public Scripts continueOnError(boolean continueOnError) { this.continueOnError = continueOnError; return this; } public boolean isContinueOnError() { return this.continueOnError; } public Scripts separator(String separator) { this.separator = separator; return this; } public String getSeparator() {
return this.separator; } public Scripts encoding(@Nullable Charset encoding) { this.encoding = encoding; return this; } public @Nullable Charset getEncoding() { return this.encoding; } } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\AbstractScriptDatabaseInitializer.java
1
请在Spring Boot框架中完成以下Java代码
public class JwtTokenProvider { /** * THIS IS NOT A SECURE PRACTICE! For simplicity, we are storing a static key here. Ideally, in a * microservices environment, this key would be kept on a config-server. */ @Value("${security.jwt.token.secret-key:secret-key}") private String secretKey; @Value("${security.jwt.token.expire-length:3600000}") private long validityInMilliseconds = 3600000; // 1h @Autowired private MyUserDetails myUserDetails; @PostConstruct protected void init() { secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); } public String createToken(String username, List<Role> roles) { Claims claims = Jwts.claims().setSubject(username); claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).filter(Objects::nonNull) .collect(Collectors.toList())); Date now = new Date(); Date validity = new Date(now.getTime() + validityInMilliseconds); return Jwts.builder()// .setClaims(claims)// .setIssuedAt(now)// .setExpiration(validity)// .signWith(SignatureAlgorithm.HS256, secretKey)// .compact(); } public Authentication getAuthentication(String token) { UserDetails userDetails = myUserDetails.loadUserByUsername(getUsername(token)); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } public String getUsername(String token) {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject(); } public String resolveToken(HttpServletRequest req) { String bearerToken = req.getHeader("Authorization"); if (bearerToken != null && bearerToken.startsWith("Bearer ")) { return bearerToken.substring(7, bearerToken.length()); } return null; } public boolean validateToken(String token) { try { Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token); return true; } catch (JwtException | IllegalArgumentException e) { throw new CustomException("Expired or invalid JWT token", HttpStatus.INTERNAL_SERVER_ERROR); } } }
repos\spring-boot-quick-master\quick-jwt\src\main\java\com\quick\jwt\security\JwtTokenProvider.java
2
请完成以下Java代码
public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public String getProductUnit() { return productUnit; } public void setProductUnit(String productUnit) { this.productUnit = productUnit; } public Integer getNavStatus() { return navStatus; } public void setNavStatus(Integer navStatus) { this.navStatus = navStatus; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getDescription() { return description;
} public void setDescription(String description) { this.description = description; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", parentId=").append(parentId); sb.append(", name=").append(name); sb.append(", level=").append(level); sb.append(", productCount=").append(productCount); sb.append(", productUnit=").append(productUnit); sb.append(", navStatus=").append(navStatus); sb.append(", showStatus=").append(showStatus); sb.append(", sort=").append(sort); sb.append(", icon=").append(icon); sb.append(", keywords=").append(keywords); sb.append(", description=").append(description); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategory.java
1
请完成以下Java代码
public void setOnDelete (final boolean OnDelete) { set_Value (COLUMNNAME_OnDelete, OnDelete); } @Override public boolean isOnDelete() { return get_ValueAsBoolean(COLUMNNAME_OnDelete); } @Override public void setOnNew (final boolean OnNew) { set_Value (COLUMNNAME_OnNew, OnNew); } @Override public boolean isOnNew() { return get_ValueAsBoolean(COLUMNNAME_OnNew); } @Override public void setOnUpdate (final boolean OnUpdate) { set_Value (COLUMNNAME_OnUpdate, OnUpdate); } @Override public boolean isOnUpdate() { return get_ValueAsBoolean(COLUMNNAME_OnUpdate); } @Override public void setSource_Table_ID (final int Source_Table_ID) { if (Source_Table_ID < 1) set_Value (COLUMNNAME_Source_Table_ID, null); else set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID); }
@Override public int getSource_Table_ID() { return get_ValueAsInt(COLUMNNAME_Source_Table_ID); } @Override public void setTargetRecordMappingSQL (final java.lang.String TargetRecordMappingSQL) { set_Value (COLUMNNAME_TargetRecordMappingSQL, TargetRecordMappingSQL); } @Override public java.lang.String getTargetRecordMappingSQL() { return get_ValueAsString(COLUMNNAME_TargetRecordMappingSQL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Trigger.java
1