instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public <P> Object set(Map<String, Object> location, String target, P value) { return location.put(target, value); } @Override public Object recurse(Map<String, Object> location, String target) { return location.get(target); } }; private static final MultipartVariableMapper.Mapper<List<Object>> LIST_MAPPER = new MultipartVariableMapper.Mapper<List<Object>>() { @Override public <P> Object set(List<Object> location, String target, P value) { return location.set(Integer.parseInt(target), value); } @Override public Object recurse(List<Object> location, String target) { return location.get(Integer.parseInt(target)); } }; @SuppressWarnings({"unchecked", "rawtypes"}) public static <P> void mapVariable(String objectPath, Map<String, Object> variables, P file) { String[] segments = PERIOD.split(objectPath); if (segments.length < 2) { throw new RuntimeException("object-path in map must have at least two segments"); } else if (!"variables".equals(segments[0])) { throw new RuntimeException("can only map into variables"); } Object currentLocation = variables; for (int i = 1; i < segments.length; i++) { String segmentName = segments[i]; MultipartVariableMapper.Mapper mapper = determineMapper(currentLocation, objectPath, segmentName); if (i == segments.length - 1) {
if (null != mapper.set(currentLocation, segmentName, file)) { throw new RuntimeException("expected null value when mapping " + objectPath); } } else { currentLocation = mapper.recurse(currentLocation, segmentName); if (null == currentLocation) { throw new RuntimeException("found null intermediate value when trying to map " + objectPath); } } } } private static MultipartVariableMapper.Mapper<?> determineMapper(Object currentLocation, String objectPath, String segmentName) { if (currentLocation instanceof Map) { return MAP_MAPPER; } else if (currentLocation instanceof List) { return LIST_MAPPER; } throw new RuntimeException("expected a map or list at " + segmentName + " when trying to map " + objectPath); } interface Mapper<T> { <P> Object set(T location, String target, P value); Object recurse(T location, String target); } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphql\fileupload\MultipartVariableMapper.java
1
请完成以下Java代码
public class SysFillRule { /** * 主键ID */ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "主键ID") private java.lang.String id; /** * 规则名称 */ @Excel(name = "规则名称", width = 15) @Schema(description = "规则名称") private java.lang.String ruleName; /** * 规则Code */ @Excel(name = "规则Code", width = 15) @Schema(description = "规则Code") private java.lang.String ruleCode; /** * 规则实现类 */ @Excel(name = "规则实现类", width = 15) @Schema(description = "规则实现类") private java.lang.String ruleClass; /** * 规则参数 */ @Excel(name = "规则参数", width = 15) @Schema(description = "规则参数") private java.lang.String ruleParams; /** * 修改人 */ @Excel(name = "修改人", width = 15) @Schema(description = "修改人") private java.lang.String updateBy; /** * 修改时间 */ @Excel(name = "修改时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Schema(description = "修改时间") private java.util.Date updateTime; /** * 创建人 */ @Excel(name = "创建人", width = 15) @Schema(description = "创建人") private java.lang.String createBy; /** * 创建时间 */ @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @Schema(description = "创建时间") private java.util.Date createTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysFillRule.java
1
请在Spring Boot框架中完成以下Java代码
public class DDOrderDocStatusChangedHandler implements MaterialEventHandler<DDOrderDocStatusChangedEvent> { private final CandidateRepositoryRetrieval candidateRepositoryRetrieval; private final CandidateChangeService candidateChangeService; public DDOrderDocStatusChangedHandler( @NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval, @NonNull final CandidateChangeService candidateChangeService) { this.candidateChangeService = candidateChangeService; this.candidateRepositoryRetrieval = candidateRepositoryRetrieval; } @Override public Collection<Class<? extends DDOrderDocStatusChangedEvent>> getHandledEventType() { return ImmutableList.of(DDOrderDocStatusChangedEvent.class); } @Override public void handleEvent(@NonNull final DDOrderDocStatusChangedEvent ddOrderChangedDocStatusEvent) { final List<Candidate> candidatesForDDOrderId = DDOrderUtil .retrieveCandidatesForDDOrderId( candidateRepositoryRetrieval, ddOrderChangedDocStatusEvent.getDdOrderId()); Check.errorIf(candidatesForDDOrderId.isEmpty(), "No Candidates found for PP_Order_ID={} ", ddOrderChangedDocStatusEvent.getDdOrderId()); final DocStatus newDocStatusFromEvent = ddOrderChangedDocStatusEvent.getNewDocStatus(); final List<Candidate> updatedCandidatesToPersist = new ArrayList<>(); for (final Candidate candidateForDDOrderId : candidatesForDDOrderId) { final BigDecimal newQuantity = computeNewQuantity(newDocStatusFromEvent, candidateForDDOrderId); final DistributionDetail distributionDetail = // DistributionDetail.cast(candidateForDDOrderId.getBusinessCaseDetail());
final Candidate updatedCandidateToPersist = candidateForDDOrderId.toBuilder() // .status(newCandidateStatus) .materialDescriptor(candidateForDDOrderId.getMaterialDescriptor().withQuantity(newQuantity)) .businessCaseDetail(distributionDetail.toBuilder().ddOrderDocStatus(newDocStatusFromEvent).build()) .build(); updatedCandidatesToPersist.add(updatedCandidateToPersist); } updatedCandidatesToPersist.forEach(candidateChangeService::onCandidateNewOrChange); } private BigDecimal computeNewQuantity( @NonNull final DocStatus newDocStatusFromEvent, @NonNull final Candidate candidateForDDOrderId) { final BigDecimal newQuantity; if (newDocStatusFromEvent.isClosed()) { // Take the "actualQty" instead of max(actual, planned) newQuantity = candidateForDDOrderId.computeActualQty(); } else { // take the max(actual, planned) final BigDecimal plannedQty = candidateForDDOrderId.getBusinessCaseDetail().getQty(); newQuantity = candidateForDDOrderId.computeActualQty().max(plannedQty); } return newQuantity; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderDocStatusChangedHandler.java
2
请完成以下Java代码
public Builder attribute(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.attributes.put(name, value); return this; } /** * A {@code Consumer} of the attributes {@code Map} allowing the ability to add, * replace, or remove. * @param attributesConsumer a {@link Consumer} of the attributes {@code Map} * @return the {@link Builder} */ public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) { attributesConsumer.accept(this.attributes); return this; } /** * Builds a new {@link OAuth2Authorization}. * @return the {@link OAuth2Authorization} */ public OAuth2Authorization build() { Assert.hasText(this.principalName, "principalName cannot be empty"); Assert.notNull(this.authorizationGrantType, "authorizationGrantType cannot be null"); OAuth2Authorization authorization = new OAuth2Authorization(); if (!StringUtils.hasText(this.id)) {
this.id = UUID.randomUUID().toString(); } authorization.id = this.id; authorization.registeredClientId = this.registeredClientId; authorization.principalName = this.principalName; authorization.authorizationGrantType = this.authorizationGrantType; authorization.authorizedScopes = Collections.unmodifiableSet(!CollectionUtils.isEmpty(this.authorizedScopes) ? new HashSet<>(this.authorizedScopes) : new HashSet<>()); authorization.tokens = Collections.unmodifiableMap(this.tokens); authorization.attributes = Collections.unmodifiableMap(this.attributes); return authorization; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2Authorization.java
1
请完成以下Java代码
public void setJobCant (int JobCant) { set_Value (COLUMNNAME_JobCant, Integer.valueOf(JobCant)); } /** Get Job Cant. @return Job Cant */ public int getJobCant () { Integer ii = (Integer)get_Value(COLUMNNAME_JobCant); if (ii == null) return 0; return ii.intValue(); } /** 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()); } public org.eevolution.model.I_HR_Job getNext_Job() throws RuntimeException { return (org.eevolution.model.I_HR_Job)MTable.get(getCtx(), org.eevolution.model.I_HR_Job.Table_Name) .getPO(getNext_Job_ID(), get_TrxName()); } /** Set Next Job. @param Next_Job_ID Next Job */ public void setNext_Job_ID (int Next_Job_ID) { if (Next_Job_ID < 1) set_Value (COLUMNNAME_Next_Job_ID, null); else set_Value (COLUMNNAME_Next_Job_ID, Integer.valueOf(Next_Job_ID)); } /** Get Next Job. @return Next Job */ public int getNext_Job_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_Next_Job_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */ public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Job.java
1
请完成以下Java代码
public void execute(Runnable task) { asyncTaskExecutor.execute(task); } @Override public CompletableFuture<?> submit(Runnable task) { return asyncTaskExecutor.submitCompletable(task); } @Override public <T> CompletableFuture<T> submit(Callable<T> task) { return asyncTaskExecutor.submitCompletable(task); } @Override public void shutdown() { // This uses spring resources passed in the constructor, therefore there is nothing to shutdown here } public org.springframework.core.task.AsyncTaskExecutor getAsyncTaskExecutor() { return asyncTaskExecutor;
} @Override public int getRemainingCapacity() { Object executor = asyncTaskExecutor; if (isAsyncTaskExecutorAopProxied) { executor = AopProxyUtils.getSingletonTarget(asyncTaskExecutor); } if (executor instanceof ThreadPoolTaskExecutor) { return ((ThreadPoolTaskExecutor) executor).getThreadPoolExecutor().getQueue().remainingCapacity(); } else { return Integer.MAX_VALUE; } } }
repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\async\SpringAsyncTaskExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent(this.className, classLoader)) { Binder binder = Binder.get(environment); TemplateAvailabilityProperties properties = binder.bindOrCreate(this.propertyPrefix, this.propertiesClass); return isTemplateAvailable(view, resourceLoader, properties); } return false; } private boolean isTemplateAvailable(String view, ResourceLoader resourceLoader, TemplateAvailabilityProperties properties) { String location = properties.getPrefix() + view + properties.getSuffix(); for (String path : properties.getLoaderPath()) { if (resourceLoader.getResource(path + location).exists()) { return true; } } return false; } protected abstract static class TemplateAvailabilityProperties { private String prefix; private String suffix;
protected TemplateAvailabilityProperties(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } protected abstract List<String> getLoaderPath(); public String getPrefix() { return this.prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\template\PathBasedTemplateAvailabilityProvider.java
2
请完成以下Java代码
public ResponseEntity<ErrorItem> handle(ResourceNotFoundException e) { ErrorItem error = new ErrorItem(); error.setMessage(e.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } public static class ErrorItem { @JsonInclude(JsonInclude.Include.NON_NULL) private String code; private String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } public static class ErrorResponse {
private List<ErrorItem> errors = new ArrayList<>(); public List<ErrorItem> getErrors() { return errors; } public void setErrors(List<ErrorItem> errors) { this.errors = errors; } public void addError(ErrorItem error) { this.errors.add(error); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\exception\ApiExceptionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public final class SystemMetricsAutoConfiguration { @Bean @ConditionalOnMissingBean UptimeMetrics uptimeMetrics() { return new UptimeMetrics(); } @Bean @ConditionalOnMissingBean ProcessorMetrics processorMetrics(ObjectProvider<JvmCpuMeterConventions> jvmCpuMeterConventions) { JvmCpuMeterConventions conventions = jvmCpuMeterConventions.getIfAvailable(); return (conventions != null) ? new ProcessorMetrics(Collections.emptyList(), conventions) : new ProcessorMetrics(); }
@Bean @ConditionalOnMissingBean FileDescriptorMetrics fileDescriptorMetrics() { return new FileDescriptorMetrics(); } @Bean @ConditionalOnMissingBean DiskSpaceMetricsBinder diskSpaceMetrics(MetricsProperties properties) { List<File> paths = properties.getSystem().getDiskspace().getPaths(); return new DiskSpaceMetricsBinder(paths, Tags.empty()); } }
repos\spring-boot-main\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\system\SystemMetricsAutoConfiguration.java
2
请完成以下Java代码
public static Collection<EventPayloadInstance> createEventPayloadInstances(VariableScope variableScope, ExpressionManager expressionManager, BaseElement baseElement, EventModel eventDefinition) { List<EventPayloadInstance> eventPayloadInstances = new ArrayList<>(); List<ExtensionElement> inParameters = baseElement.getExtensionElements() .getOrDefault(CmmnXmlConstants.ELEMENT_EVENT_IN_PARAMETER, Collections.emptyList()); if (!inParameters.isEmpty()) { for (ExtensionElement inParameter : inParameters) { String source = inParameter.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IOPARAMETER_SOURCE); String target = inParameter.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IOPARAMETER_TARGET); EventPayload eventPayloadDefinition = eventDefinition.getPayload(target);
if (eventPayloadDefinition != null) { Expression sourceExpression = expressionManager.createExpression(source); Object value = sourceExpression.getValue(variableScope); eventPayloadInstances.add(new EventPayloadInstanceImpl(eventPayloadDefinition, value)); } } } return eventPayloadInstances; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\util\EventInstanceCmmnUtil.java
1
请完成以下Java代码
public B authorizationRequestUri(Function<UriBuilder, URI> authorizationRequestUriFunction) { if (authorizationRequestUriFunction != null) { this.authorizationRequestUriFunction = authorizationRequestUriFunction; } return getThis(); } public abstract T build(); private String buildAuthorizationRequestUri() { Map<String, Object> parameters = getParameters(); // Not encoded this.parametersConsumer.accept(parameters); MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(); parameters.forEach((k, v) -> { String key = encodeQueryParam(k); if (v instanceof Iterable) { ((Iterable<?>) v).forEach((value) -> queryParams.add(key, encodeQueryParam(String.valueOf(value)))); } else if (v != null && v.getClass().isArray()) { Object[] values = (Object[]) v; for (Object value : values) { queryParams.add(key, encodeQueryParam(String.valueOf(value))); } } else { queryParams.set(key, encodeQueryParam(String.valueOf(v))); } }); UriBuilder uriBuilder = this.uriBuilderFactory.uriString(this.authorizationUri).queryParams(queryParams); return this.authorizationRequestUriFunction.apply(uriBuilder).toString();
} protected Map<String, Object> getParameters() { Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put(OAuth2ParameterNames.RESPONSE_TYPE, this.responseType.getValue()); parameters.put(OAuth2ParameterNames.CLIENT_ID, this.clientId); if (!CollectionUtils.isEmpty(this.scopes)) { parameters.put(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(this.scopes, " ")); } if (this.state != null) { parameters.put(OAuth2ParameterNames.STATE, this.state); } if (this.redirectUri != null) { parameters.put(OAuth2ParameterNames.REDIRECT_URI, this.redirectUri); } parameters.putAll(this.additionalParameters); return parameters; } // Encode query parameter value according to RFC 3986 private static String encodeQueryParam(String value) { return UriUtils.encodeQueryParam(value, StandardCharsets.UTF_8); } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationRequest.java
1
请完成以下Java代码
public class JSONUserSession { @JsonProperty("loggedIn") private final boolean loggedIn; /** * login user */ @JsonProperty("username") @JsonInclude(JsonInclude.Include.NON_NULL) private final String username; /** * user's full name/display name */ @JsonProperty("fullname") @JsonInclude(JsonInclude.Include.NON_NULL) private final String fullname; @JsonProperty("email") @JsonInclude(JsonInclude.Include.NON_NULL) private final String email; @JsonProperty("avatarId") @JsonInclude(JsonInclude.Include.NON_NULL) private final String avatarId; @JsonProperty("rolename") @JsonInclude(JsonInclude.Include.NON_NULL) private final String rolename; @JsonProperty("orgname") @JsonInclude(JsonInclude.Include.NON_NULL) private final String orgname; @JsonProperty("language") private final JSONLookupValue language; @JsonProperty("locale") private final JSONUserSessionLocale locale; @JsonProperty("timeZone") private final String timeZone; @JsonProperty("defaultFlatrateConditionsId") private final ConditionsId defaultFlatrateConditionsId; @JsonProperty("defaultBoilerPlateId") private final BoilerPlateId defaultBoilerPlateId; @JsonProperty("websocketEndpoint") private final String websocketEndpoint; @JsonProperty("userProfileWindowId") @JsonInclude(JsonInclude.Include.NON_NULL) private final WindowId userProfileWindowId; @JsonProperty("userProfileId") @JsonInclude(JsonInclude.Include.NON_NULL) private final Integer userProfileId; @JsonProperty("settings") private final Map<String, String> settings; public JSONUserSession( @NonNull final UserSession userSession, @Nullable final Map<String, String> settings) { loggedIn = userSession.isLoggedIn(); if (loggedIn)
{ username = userSession.getUserName(); rolename = userSession.getRoleName(); orgname = userSession.getOrgName(); fullname = userSession.getUserFullname(); email = userSession.getUserEmail(); avatarId = userSession.getAvatarId(); defaultFlatrateConditionsId = userSession.getDefaultFlatrateConditionsId(); defaultBoilerPlateId = userSession.getDefaultBoilerPlateId(); userProfileWindowId = WindowConstants.WINDOWID_UserProfile; userProfileId = userSession.getLoggedUserId().getRepoId(); websocketEndpoint = userSession.getWebsocketEndpoint().getAsString(); } else { username = null; rolename = null; orgname = null; fullname = null; email = null; avatarId = null; defaultFlatrateConditionsId = null; defaultBoilerPlateId = null; userProfileWindowId = null; userProfileId = null; websocketEndpoint = null; } final Language language = userSession.getLanguage(); this.language = JSONLookupValue.of(language.getAD_Language(), language.getName()); this.locale = JSONUserSessionLocale.of(userSession.getUserSessionLocale()); timeZone = DateTimeConverters.toJson(userSession.getTimeZone()); this.settings = settings != null ? settings : ImmutableMap.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\json\JSONUserSession.java
1
请完成以下Java代码
public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } public List<FlowableListener> getTaskListeners() { return taskListeners; } public void setTaskListeners(List<FlowableListener> taskListeners) { this.taskListeners = taskListeners; } @Override public HumanTask clone() { HumanTask clone = new HumanTask();
clone.setValues(this); return clone; } public void setValues(HumanTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setSameDeployment(otherElement.isSameDeployment()); setValidateFormFields(otherElement.getValidateFormFields()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setTaskIdVariableName(otherElement.getTaskIdVariableName()); setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName()); setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers())); } }
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\HumanTask.java
1
请完成以下Java代码
public Boolean isArray() { return jsonNode.isArray(); } public SpinList<SpinJsonNode> elements() { if(jsonNode.isArray()) { Iterator<JsonNode> iterator = jsonNode.elements(); SpinList<SpinJsonNode> list = new SpinListImpl<SpinJsonNode>(); while(iterator.hasNext()) { SpinJsonNode node = dataFormat.createWrapperInstance(iterator.next()); list.add(node); } return list; } else { throw LOG.unableToParseValue(SpinList.class.getSimpleName(), jsonNode.getNodeType()); } } public List<String> fieldNames() { if(jsonNode.isContainerNode()) { Iterator<String> iterator = jsonNode.fieldNames(); List<String> list = new ArrayList<String>(); while(iterator.hasNext()) { list.add(iterator.next()); } return list; } else { throw LOG.unableToParseValue("Array/Object", jsonNode.getNodeType()); } } public JsonNodeType getNodeType() { return jsonNode.getNodeType(); } public SpinJsonPathQuery jsonPath(String expression) { ensureNotNull("expression", expression); try { JsonPath query = JsonPath.compile(expression); return new JacksonJsonPathQuery(this, query, dataFormat); } catch(InvalidPathException pex) { throw LOG.unableToCompileJsonPathExpression(expression, pex); } catch(IllegalArgumentException aex) { throw LOG.unableToCompileJsonPathExpression(expression, aex); } } /** * Maps the json represented by this object to a java object of the given type.<br> * Note: the desired target type is not validated and needs to be trusted. * * @throws SpinJsonException if the json representation cannot be mapped to the specified type */ public <C> C mapTo(Class<C> type) {
DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(jsonNode, type); } /** * Maps the json represented by this object to a java object of the given type. * Argument is to be supplied in Jackson's canonical type string format * (see {@link JavaType#toCanonical()}).<br> * Note: the desired target type is not validated and needs to be trusted. * * @throws SpinJsonException if the json representation cannot be mapped to the specified type * @throws SpinJsonDataFormatException if the parameter does not match a valid type */ public <C> C mapTo(String type) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(jsonNode, type); } /** * Maps the json represented by this object to a java object of the given type.<br> * Note: the desired target type is not validated and needs to be trusted. * * @throws SpinJsonException if the json representation cannot be mapped to the specified type */ public <C> C mapTo(JavaType type) { JacksonJsonDataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(jsonNode, type); } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\JacksonJsonNode.java
1
请在Spring Boot框架中完成以下Java代码
public TransactionalPackingItemSupport get() { return new TransactionalPackingItemSupport(trx); } }); } private final Map<Long, ItemState> items = new LinkedHashMap<>(); private TransactionalPackingItemSupport(final ITrx trx) { // // Register the commit/rollback transaction listeners trx.getTrxListenerManager() .newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> commit()); trx.getTrxListenerManager() .newEventListener(TrxEventTiming.AFTER_ROLLBACK) .invokeMethodJustOnce(false) // invoke the handling method on *every* commit, because that's how it was and I can't check now if it's really needed .registerHandlingMethod(innerTrx -> rollback()); } private synchronized void commit() { final List<ItemState> itemsToCommit = new ArrayList<>(items.values()); for (final ItemState item : itemsToCommit) { item.commit(); } items.clear(); } private synchronized void rollback() { items.clear(); } /** * Gets the current state for given transactional item. * * @param item * @return current stateș never returns null. */ public synchronized PackingItem getState(final TransactionalPackingItem item) { final long id = item.getId(); ItemState itemState = items.get(id); if (itemState == null) { itemState = new ItemState(item); items.put(id, itemState); } return itemState.getState(); } /** * Transactional item state holder. * * @author metas-dev <dev@metasfresh.com> * */ private static final class ItemState {
private final Reference<TransactionalPackingItem> transactionalItemRef; private final PackingItem state; public ItemState(final TransactionalPackingItem transactionalItem) { super(); // NOTE: we keep a weak reference to our transactional item // because in case nobody is referencing it, there is no point to update on commit. this.transactionalItemRef = new WeakReference<>(transactionalItem); state = transactionalItem.createNewState(); } public PackingItem getState() { return state; } public void commit() { final TransactionalPackingItem transactionalItem = transactionalItemRef.get(); if (transactionalItem == null) { // reference already expired return; } transactionalItem.commit(state); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\TransactionalPackingItemSupport.java
2
请在Spring Boot框架中完成以下Java代码
public BigInteger getExternalSeqNo() { return externalSeqNo; } /** * Sets the value of the externalSeqNo property. * * @param value * allowed object is * {@link BigInteger } * */ public void setExternalSeqNo(BigInteger value) { this.externalSeqNo = value; } /** * Gets the value of the cuombPartnerID property. * * @return * possible object is * {@link EDIExpCUOMType } * */ public EDIExpCUOMType getCUOMBPartnerID() { return cuombPartnerID; } /** * Sets the value of the cuombPartnerID property. * * @param value * allowed object is * {@link EDIExpCUOMType } * */ public void setCUOMBPartnerID(EDIExpCUOMType value) { this.cuombPartnerID = value; } /** * Gets the value of the qtyEnteredInBPartnerUOM property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getQtyEnteredInBPartnerUOM() { return qtyEnteredInBPartnerUOM; } /** * Sets the value of the qtyEnteredInBPartnerUOM property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setQtyEnteredInBPartnerUOM(BigDecimal value) {
this.qtyEnteredInBPartnerUOM = value; } /** * Gets the value of the bPartnerQtyItemCapacity property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getBPartnerQtyItemCapacity() { return bPartnerQtyItemCapacity; } /** * Sets the value of the bPartnerQtyItemCapacity property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setBPartnerQtyItemCapacity(BigDecimal value) { this.bPartnerQtyItemCapacity = value; } /** * Gets the value of the upctu property. * * @return * possible object is * {@link String } * */ public String getUPCTU() { return upctu; } /** * Sets the value of the upctu property. * * @param value * allowed object is * {@link String } * */ public void setUPCTU(String value) { this.upctu = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvLineType.java
2
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { invoke(new FilterInvocation(request, response, chain)); } public @Nullable FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } @Override public @Nullable SecurityMetadataSource obtainSecurityMetadataSource() { return this.securityMetadataSource; } public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource newSource) { this.securityMetadataSource = newSource; } @Override public Class<?> getSecureObjectClass() { return FilterInvocation.class; } public void invoke(FilterInvocation filterInvocation) throws IOException, ServletException { if (isApplied(filterInvocation) && this.observeOncePerRequest) { // filter already applied to this request and user wants us to observe // once-per-request handling, so don't re-do security checking filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse()); return; } // first time this request being called, so perform security checking if (filterInvocation.getRequest() != null && this.observeOncePerRequest) { filterInvocation.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE); } InterceptorStatusToken token = super.beforeInvocation(filterInvocation); try { filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse()); } finally {
super.finallyInvocation(token); } super.afterInvocation(token, null); } private boolean isApplied(FilterInvocation filterInvocation) { return (filterInvocation.getRequest() != null) && (filterInvocation.getRequest().getAttribute(FILTER_APPLIED) != null); } /** * Indicates whether once-per-request handling will be observed. By default this is * <code>true</code>, meaning the <code>FilterSecurityInterceptor</code> will only * execute once-per-request. Sometimes users may wish it to execute more than once per * request, such as when JSP forwards are being used and filter security is desired on * each included fragment of the HTTP request. * @return <code>true</code> (the default) if once-per-request is honoured, otherwise * <code>false</code> if <code>FilterSecurityInterceptor</code> will enforce * authorizations for each and every fragment of the HTTP request. */ public boolean isObserveOncePerRequest() { return this.observeOncePerRequest; } public void setObserveOncePerRequest(boolean observeOncePerRequest) { this.observeOncePerRequest = observeOncePerRequest; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\intercept\FilterSecurityInterceptor.java
1
请完成以下Java代码
public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getEngineVersion() { return engineVersion; } public String getAuthorizationUserId() { return authorizationUserId; } public String getProcDefId() { return procDefId; } public String getEventSubscriptionName() { return eventSubscriptionName; }
public String getEventSubscriptionType() { return eventSubscriptionType; } public boolean isIncludeAuthorization() { return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty()); } public List<List<String>> getSafeAuthorizationGroups() { return safeAuthorizationGroups; } public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) { this.safeAuthorizationGroups = safeAuthorizationGroups; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessDefinitionQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
final class CacheConfigurations { private static final Map<CacheType, String> MAPPINGS; static { Map<CacheType, String> mappings = new EnumMap<>(CacheType.class); mappings.put(CacheType.GENERIC, GenericCacheConfiguration.class.getName()); mappings.put(CacheType.HAZELCAST, HazelcastCacheConfiguration.class.getName()); mappings.put(CacheType.INFINISPAN, InfinispanCacheConfiguration.class.getName()); mappings.put(CacheType.JCACHE, JCacheCacheConfiguration.class.getName()); mappings.put(CacheType.COUCHBASE, CouchbaseCacheConfiguration.class.getName()); mappings.put(CacheType.REDIS, RedisCacheConfiguration.class.getName()); mappings.put(CacheType.CAFFEINE, CaffeineCacheConfiguration.class.getName()); mappings.put(CacheType.CACHE2K, Cache2kCacheConfiguration.class.getName()); mappings.put(CacheType.SIMPLE, SimpleCacheConfiguration.class.getName()); mappings.put(CacheType.NONE, NoOpCacheConfiguration.class.getName()); MAPPINGS = Collections.unmodifiableMap(mappings); }
private CacheConfigurations() { } static String getConfigurationClass(CacheType cacheType) { String configurationClassName = MAPPINGS.get(cacheType); Assert.state(configurationClassName != null, () -> "Unknown cache type " + cacheType); return configurationClassName; } static CacheType getType(String configurationClassName) { for (Map.Entry<CacheType, String> entry : MAPPINGS.entrySet()) { if (entry.getValue().equals(configurationClassName)) { return entry.getKey(); } } throw new IllegalStateException("Unknown configuration class " + configurationClassName); } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\CacheConfigurations.java
2
请完成以下Java代码
public class GetExecutionVariableCmd implements Command<Object>, Serializable { private static final long serialVersionUID = 1L; protected String executionId; protected String variableName; protected boolean isLocal; public GetExecutionVariableCmd(String executionId, String variableName, boolean isLocal) { this.executionId = executionId; this.variableName = variableName; this.isLocal = isLocal; } @Override public Object execute(CommandContext commandContext) { if (executionId == null) { throw new FlowableIllegalArgumentException("executionId is null"); } if (variableName == null) { throw new FlowableIllegalArgumentException("variableName is null"); } ExecutionEntity execution = CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId); if (execution == null) { throw new FlowableObjectNotFoundException("execution " + executionId + " doesn't exist", Execution.class); }
if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, execution.getProcessDefinitionId())) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); return compatibilityHandler.getExecutionVariable(executionId, variableName, isLocal); } Object value; if (isLocal) { value = execution.getVariableLocal(variableName, false); } else { value = execution.getVariable(variableName, false); } return value; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetExecutionVariableCmd.java
1
请完成以下Java代码
public CostDetailCreateRequest withAmount(@NonNull final CostAmount amt) { return withAmountAndType(amt, this.amtType); } public CostDetailCreateRequest withAmountAndType(@NonNull final CostAmount amt, @NonNull final CostAmountType amtType) { if (Objects.equals(this.amt, amt) && Objects.equals(this.amtType, amtType)) { return this; } return toBuilder().amt(amt).amtType(amtType).build(); } public CostDetailCreateRequest withAmountAndTypeAndQty(@NonNull final CostAmount amt, @NonNull final CostAmountType amtType, @NonNull final Quantity qty) { if (Objects.equals(this.amt, amt) && Objects.equals(this.amtType, amtType) && Objects.equals(this.qty, qty)) { return this; } return toBuilder().amt(amt).amtType(amtType).qty(qty).build(); } public CostDetailCreateRequest withAmountAndTypeAndQty(@NonNull final CostAmountAndQty amtAndQty, @NonNull final CostAmountType amtType) { return withAmountAndTypeAndQty(amtAndQty.getAmt(), amtType, amtAndQty.getQty()); } public CostDetailCreateRequest withAmountAndQty( @NonNull final CostAmount amt, @NonNull final Quantity qty) { if (Objects.equals(this.amt, amt) && Objects.equals(this.qty, qty)) { return this; } return toBuilder().amt(amt).qty(qty).build(); } public CostDetailCreateRequest withProductId(@NonNull final ProductId productId) { if (ProductId.equals(this.productId, productId)) { return this; } return toBuilder().productId(productId).build(); } public CostDetailCreateRequest withProductIdAndQty( @NonNull final ProductId productId, @NonNull final Quantity qty) { if (ProductId.equals(this.productId, productId)
&& Objects.equals(this.qty, qty)) { return this; } return toBuilder().productId(productId).qty(qty).build(); } public CostDetailCreateRequest withQty(@NonNull final Quantity qty) { if (Objects.equals(this.qty, qty)) { return this; } return toBuilder().qty(qty).build(); } public CostDetailCreateRequest withQtyZero() { return withQty(qty.toZero()); } public CostDetailBuilder toCostDetailBuilder() { final CostDetailBuilder costDetail = CostDetail.builder() .clientId(getClientId()) .orgId(getOrgId()) .acctSchemaId(getAcctSchemaId()) .productId(getProductId()) .attributeSetInstanceId(getAttributeSetInstanceId()) // .amtType(getAmtType()) .amt(getAmt()) .qty(getQty()) // .documentRef(getDocumentRef()) .description(getDescription()) .dateAcct(getDate()); if (isExplicitCostElement()) { costDetail.costElementId(getCostElementId()); } return costDetail; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostDetailCreateRequest.java
1
请完成以下Java代码
private Timestamp getNewerDateAcct() { Timestamp invoiceDate = null; Timestamp shipDate = null; if (getC_InvoiceLine_ID() > 0) { final String sql = "SELECT i.DateAcct " + "FROM C_InvoiceLine il" + " INNER JOIN C_Invoice i ON (i.C_Invoice_ID=il.C_Invoice_ID) " + "WHERE C_InvoiceLine_ID=?"; invoiceDate = DB.getSQLValueTS(null, sql, getC_InvoiceLine_ID()); } // if (getM_InOutLine_ID() > 0) { final String sql = "SELECT io.DateAcct " + "FROM M_InOutLine iol" + " INNER JOIN M_InOut io ON (io.M_InOut_ID=iol.M_InOut_ID) " + "WHERE iol.M_InOutLine_ID=?"; shipDate = DB.getSQLValueTS(null, sql, getM_InOutLine_ID()); } // // Assuming that order date is always earlier if (invoiceDate == null) { return shipDate; } if (shipDate == null) { return invoiceDate; } if (invoiceDate.after(shipDate)) { return invoiceDate; } return shipDate; } // getNewerDateAcct @Override protected boolean beforeDelete() { if (isPosted()) { MPeriod.testPeriodOpen(getCtx(), getDateTrx(), DocBaseType.MatchPO, getAD_Org_ID()); setPosted(false); Services.get(IFactAcctDAO.class).deleteForDocumentModel(this); } final ICostingService costDetailService = Adempiere.getBean(ICostingService.class); costDetailService.voidAndDeleteForDocument(CostingDocumentRef.ofMatchPOId(getM_MatchPO_ID()));
return true; } @Override protected boolean afterDelete(final boolean success) { if (!success) { return success; } // Order Delivered/Invoiced // (Reserved in VMatch and MInOut.completeIt) final I_C_OrderLine orderLine = getC_OrderLine(); if (orderLine != null) { if (getM_InOutLine_ID() > 0) { orderLine.setQtyDelivered(orderLine.getQtyDelivered().subtract(getQty())); } if (getC_InvoiceLine_ID() > 0) { orderLine.setQtyInvoiced(orderLine.getQtyInvoiced().subtract(getQty())); } InterfaceWrapperHelper.save(orderLine); } return true; } @Override public String toString() { return new StringBuilder("MMatchPO[") .append(getM_MatchPO_ID()) .append(",Qty=").append(getQty()) .append(",C_OrderLine_ID=").append(getC_OrderLine_ID()) .append(",M_InOutLine_ID=").append(getM_InOutLine_ID()) .append(",C_InvoiceLine_ID=").append(getC_InvoiceLine_ID()) .append("]") .toString(); } } // MMatchPO
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMatchPO.java
1
请完成以下Java代码
public final class ThreadLocalDecimalFormatter { public static ThreadLocalDecimalFormatter ofPattern(final String pattern) { final DecimalFormatSymbols symbols = null; // auto return new ThreadLocalDecimalFormatter(pattern, symbols); } public static ThreadLocalDecimalFormatter ofPattern(final String pattern, final DecimalFormatSymbols symbols) { return new ThreadLocalDecimalFormatter(pattern, symbols); } private final String pattern; // just for toString() private final ThreadLocal<DecimalFormat> formatterHolder; private ThreadLocalDecimalFormatter(final String pattern, final DecimalFormatSymbols symbols) { Check.assumeNotEmpty(pattern, "pattern is not empty"); this.pattern = pattern; final Supplier<? extends DecimalFormat> supplier; if (symbols == null) { supplier = () -> new DecimalFormat(pattern); } else
{ supplier = () -> new DecimalFormat(pattern, symbols); } formatterHolder = ThreadLocal.withInitial(supplier); formatterHolder.get(); // get an instance just to make sure the pattern is OK } private DecimalFormat getFormatter() { return formatterHolder.get(); } public String format(final Object obj) { return getFormatter().format(obj); } public String format(final double number) { return getFormatter().format(number); } public String format(final long number) { return getFormatter().format(number); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\ThreadLocalDecimalFormatter.java
1
请完成以下Java代码
public Optional<InstantAndOrgId> getSinglePreparationDate() {return getSingleValue(ScheduledPackageable::getPreparationDate);} public Optional<InstantAndOrgId> getSingleDeliveryDate() {return getSingleValue(ScheduledPackageable::getDeliveryDate);} public Optional<BPartnerLocationId> getSingleCustomerLocationId() {return getSingleValue(ScheduledPackageable::getCustomerLocationId);} public Optional<String> getSingleCustomerAddress() {return getSingleValue(ScheduledPackageable::getCustomerAddress);} public Optional<BPartnerLocationId> getSingleHandoverLocationId() {return getSingleValue(ScheduledPackageable::getHandoverLocationId);} public ProductId getSingleProductId() { return getSingleValue(ScheduledPackageable::getProductId).orElseThrow(() -> new AdempiereException("No single product found in " + list)); } public HUPIItemProductId getSinglePackToHUPIItemProductId() { return getSingleValue(ScheduledPackageable::getPackToHUPIItemProductId).orElseThrow(() -> new AdempiereException("No single PackToHUPIItemProductId found in " + list)); } public Quantity getQtyToPick() { return list.stream() .map(ScheduledPackageable::getQtyToPick) .reduce(Quantity::add) .orElseThrow(() -> new AdempiereException("No QtyToPick found in " + list)); } public Optional<ShipmentScheduleAndJobScheduleId> getSingleScheduleIdIfUnique()
{ final ShipmentScheduleAndJobScheduleIdSet scheduleIds = getScheduleIds(); return scheduleIds.size() == 1 ? Optional.of(scheduleIds.iterator().next()) : Optional.empty(); } public Optional<UomId> getSingleCatchWeightUomIdIfUnique() { final List<UomId> catchWeightUomIds = list.stream() .map(ScheduledPackageable::getCatchWeightUomId) // don't filter out null catch UOMs .distinct() .collect(Collectors.toList()); return catchWeightUomIds.size() == 1 ? Optional.ofNullable(catchWeightUomIds.get(0)) : Optional.empty(); } public Optional<PPOrderId> getSingleManufacturingOrderId() {return getSingleValue(ScheduledPackageable::getPickFromOrderId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageableList.java
1
请完成以下Spring Boot application配置
## Spring view resolver set up spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp ## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useSSL=false spring.datasource.username=root spring.datasource.password=posilka2020 #Hibernate Properties #The SQL dialect makes Hibernate generate better SQL for chosen database s
pring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect #Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto=update
repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\resources\application.properties
2
请完成以下Java代码
private static WFActivityStatus computeStatus( final @NonNull Quantity qtyToIssue, final @NonNull Quantity qtyIssued, final @NonNull ImmutableList<RawMaterialsIssueStep> steps) { if (qtyIssued.isZero()) { return WFActivityStatus.NOT_STARTED; } else if (qtyToIssue.compareTo(qtyIssued) <= 0 || steps.stream().allMatch(RawMaterialsIssueStep::isIssued)) { return WFActivityStatus.COMPLETED; } else { return WFActivityStatus.IN_PROGRESS; } } public Optional<Quantity> getQtyToIssueMin() { return issuingToleranceSpec != null ? Optional.of(issuingToleranceSpec.subtractFrom(qtyToIssue)) : Optional.empty(); } public Optional<Quantity> getQtyToIssueMax() { return issuingToleranceSpec != null ? Optional.of(issuingToleranceSpec.addTo(qtyToIssue)) : Optional.empty(); } public RawMaterialsIssueLine withChangedRawMaterialsIssueStep( @NonNull final PPOrderIssueScheduleId issueScheduleId, @NonNull UnaryOperator<RawMaterialsIssueStep> mapper) { final ImmutableList<RawMaterialsIssueStep> stepsNew = CollectionUtils.map( steps, step -> PPOrderIssueScheduleId.equals(step.getId(), issueScheduleId) ? mapper.apply(step) : step); return withSteps(stepsNew); } @NonNull public RawMaterialsIssueLine withSteps(final ImmutableList<RawMaterialsIssueStep> stepsNew) { return !Objects.equals(this.steps, stepsNew) ? toBuilder().steps(stepsNew).build() : this; } public boolean containsRawMaterialsIssueStep(final PPOrderIssueScheduleId issueScheduleId) { return steps.stream().anyMatch(step -> PPOrderIssueScheduleId.equals(step.getId(), issueScheduleId));
} @NonNull public ITranslatableString getProductValueAndProductName() { final TranslatableStringBuilder message = TranslatableStrings.builder() .append(getProductValue()) .append(" ") .append(getProductName()); return message.build(); } @NonNull public Quantity getQtyLeftToIssue() { return qtyToIssue.subtract(qtyIssued); } public boolean isAllowManualIssue() { return !issueMethod.isIssueOnlyForReceived(); } public boolean isIssueOnlyForReceived() {return issueMethod.isIssueOnlyForReceived();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\RawMaterialsIssueLine.java
1
请完成以下Java代码
public CoNLLSentence parse(List<Term> termList) { return parse(termList, 64, 1); } /** * 执行句法分析 * * @param termList 分词结果 * @param beamWidth 柱搜索宽度 * @param numOfThreads 多线程数 * @return 句法树 */ public CoNLLSentence parse(List<Term> termList, int beamWidth, int numOfThreads) { String[] words = new String[termList.size()]; String[] tags = new String[termList.size()]; int k = 0; for (Term term : termList) { words[k] = term.word; tags[k] = term.nature.toString(); ++k; } Configuration bestParse; try { bestParse = parser.parse(words, tags, false, beamWidth, numOfThreads); } catch (Exception e) { throw new RuntimeException(e); } CoNLLWord[] wordArray = new CoNLLWord[termList.size()];
for (int i = 0; i < words.length; i++) { wordArray[i] = new CoNLLWord(i + 1, words[i], tags[i]); } for (int i = 0; i < words.length; i++) { wordArray[i].DEPREL = parser.idWord(bestParse.state.getDependent(i + 1)); int index = bestParse.state.getHead(i + 1) - 1; if (index < 0 || index >= wordArray.length) { wordArray[i].HEAD = CoNLLWord.ROOT; } else { wordArray[i].HEAD = wordArray[index]; } } return new CoNLLSentence(wordArray); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\parser\KBeamArcEagerDependencyParser.java
1
请在Spring Boot框架中完成以下Java代码
public HistoricTaskQueryInterceptor getHistoricTaskQueryInterceptor() { return historicTaskQueryInterceptor; } public TaskServiceConfiguration setHistoricTaskQueryInterceptor(HistoricTaskQueryInterceptor historicTaskQueryInterceptor) { this.historicTaskQueryInterceptor = historicTaskQueryInterceptor; return this; } public boolean isEnableHistoricTaskLogging() { return enableHistoricTaskLogging; } public TaskServiceConfiguration setEnableHistoricTaskLogging(boolean enableHistoricTaskLogging) { this.enableHistoricTaskLogging = enableHistoricTaskLogging; return this; } @Override public TaskServiceConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) { this.enableEventDispatcher = enableEventDispatcher; return this; } @Override public TaskServiceConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; return this; } @Override public TaskServiceConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { this.eventListeners = eventListeners; return this; }
@Override public TaskServiceConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } public TaskPostProcessor getTaskPostProcessor() { return taskPostProcessor; } public TaskServiceConfiguration setTaskPostProcessor(TaskPostProcessor processor) { this.taskPostProcessor = processor; return this; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\TaskServiceConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
List<ConfigurationMetadataItem> getItems() { return this.items; } List<ConfigurationMetadataHint> getHints() { return this.hints; } /** * Resolve the name of an item against this instance. * @param item the item to resolve * @see ConfigurationMetadataProperty#setName(String) */ private void resolveName(ConfigurationMetadataItem item) { item.setName(item.getId()); // fallback ConfigurationMetadataSource source = getSource(item);
if (source != null) { String groupId = source.getGroupId(); String dottedPrefix = groupId + "."; String id = item.getId(); if (hasLength(groupId) && id.startsWith(dottedPrefix)) { String name = id.substring(dottedPrefix.length()); item.setName(name); } } } private static boolean hasLength(String string) { return (string != null && !string.isEmpty()); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\RawConfigurationMetadata.java
2
请完成以下Java代码
public void setMaxRequestSize(@Nullable DataSize maxRequestSize) { this.maxRequestSize = maxRequestSize; } /** * Sets the {@link DataSize size} threshold after which files will be written to disk. * @param fileSizeThreshold the file size threshold */ public void setFileSizeThreshold(@Nullable DataSize fileSizeThreshold) { this.fileSizeThreshold = fileSizeThreshold; } /** * Create a new {@link MultipartConfigElement} instance. * @return the multipart config element */ public MultipartConfigElement createMultipartConfig() { long maxFileSizeBytes = convertToBytes(this.maxFileSize, -1); long maxRequestSizeBytes = convertToBytes(this.maxRequestSize, -1);
long fileSizeThresholdBytes = convertToBytes(this.fileSizeThreshold, 0); return new MultipartConfigElement(this.location, maxFileSizeBytes, maxRequestSizeBytes, (int) fileSizeThresholdBytes); } /** * Return the amount of bytes from the specified {@link DataSize size}. If the size is * {@code null} or negative, returns {@code defaultValue}. * @param size the data size to handle * @param defaultValue the default value if the size is {@code null} or negative * @return the amount of bytes to use */ private long convertToBytes(@Nullable DataSize size, int defaultValue) { if (size != null && !size.isNegative()) { return size.toBytes(); } return defaultValue; } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\MultipartConfigFactory.java
1
请完成以下Java代码
public void setNm(String value) { this.nm = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link Party6ChoiceCH } * */ public Party6ChoiceCH getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Party6ChoiceCH } * */ public void setId(Party6ChoiceCH value) { this.id = value; } /** * Gets the value of the ctctDtls property. * * @return * possible object is * {@link ContactDetails2CH } * */
public ContactDetails2CH getCtctDtls() { return ctctDtls; } /** * Sets the value of the ctctDtls property. * * @param value * allowed object is * {@link ContactDetails2CH } * */ public void setCtctDtls(ContactDetails2CH value) { this.ctctDtls = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PartyIdentification32CHNameAndId.java
1
请完成以下Java代码
private void action_treeDelete(ListItem item) { log.info("Item=" + item); if (item != null) { MTreeNode info = new MTreeNode(item.id, 0, item.name, item.description, -1, item.isSummary, item.imageIndicator, false, null); centerTree.nodeChanged(false, info); deleteNode(item); } } // action_treeDelete /** * Action: Add All Nodes to Tree */ private void action_treeAddAll() { log.info(""); ListModel model = centerList.getModel(); int size = model.getSize(); int index = -1; for (index = 0; index < size; index++) { ListItem item = (ListItem)model.getElementAt(index);
action_treeAdd(item); } } // action_treeAddAll /** * Action: Delete All Nodes from Tree */ private void action_treeDeleteAll() { log.info(""); ListModel model = centerList.getModel(); int size = model.getSize(); int index = -1; for (index = 0; index < size; index++) { ListItem item = (ListItem)model.getElementAt(index); action_treeDelete(item); } } // action_treeDeleteAll } // VTreeMaintenance
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTreeMaintenance.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getSchemaLockWaitTime() { return schemaLockWaitTime; } public void setSchemaLockWaitTime(Duration schemaLockWaitTime) { this.schemaLockWaitTime = schemaLockWaitTime; } public boolean isEnableHistoryCleaning() { return enableHistoryCleaning; } public void setEnableHistoryCleaning(boolean enableHistoryCleaning) { this.enableHistoryCleaning = enableHistoryCleaning; } public String getHistoryCleaningCycle() { return historyCleaningCycle; } public void setHistoryCleaningCycle(String historyCleaningCycle) { this.historyCleaningCycle = historyCleaningCycle; } @Deprecated @DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration") public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) { this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays); } public Duration getHistoryCleaningAfter() { return historyCleaningAfter;
} public void setHistoryCleaningAfter(Duration historyCleaningAfter) { this.historyCleaningAfter = historyCleaningAfter; } public int getHistoryCleaningBatchSize() { return historyCleaningBatchSize; } public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) { this.historyCleaningBatchSize = historyCleaningBatchSize; } public String getVariableJsonMapper() { return variableJsonMapper; } public void setVariableJsonMapper(String variableJsonMapper) { this.variableJsonMapper = variableJsonMapper; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Person save(Person person) { Person p = personRepository.save(person); try { // 新开事务 独立回滚 selfProxyPersonService.delete(); } catch (Exception e) { e.printStackTrace(); } try { // 使用当前事务 全部回滚 selfProxyPersonService.save2(person); } catch (Exception e) { e.printStackTrace(); } personRepository.save(person);
return p; } @Transactional public void save2(Person person) { personRepository.save(person); throw new RuntimeException(); } @Transactional(propagation = Propagation.REQUIRES_NEW) public void delete() { personRepository.delete(1L); throw new RuntimeException(); } }
repos\spring-boot-student-master\spring-boot-student-data-jpa-transaction\src\main\java\com\xiaolyuh\service\PersonServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public class DistributionWarehouseService { @NonNull private final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class); @NonNull private final WorkplaceService workplaceService; @NonNull private final TrolleyService trolleyService; @NonNull private final LocatorScannedCodeResolverService locatorScannedCodeResolver; public String getWarehouseName(@NonNull final WarehouseId warehouseId) { return warehouseBL.getWarehouseName(warehouseId); } public String getLocatorName(@NonNull final LocatorId locatorId) { return warehouseBL.getLocatorNameById(locatorId); } @NonNull public Optional<Workplace> getWorkplaceByUserId(@NonNull final UserId userId) { return workplaceService.getWorkplaceByUserId(userId); } public WarehouseInfo getWarehouseInfoByRepoId(final int warehouseRepoId) { final WarehouseId warehouseId = WarehouseId.ofRepoId(warehouseRepoId); return WarehouseInfo.builder() .warehouseId(warehouseId) .caption(warehouseBL.getWarehouseName(warehouseId)) .build(); } public LocatorInfo getLocatorInfoByRepoId(final int locatorRepoId)
{ final I_M_Locator locator = warehouseBL.getLocatorByRepoId(locatorRepoId); final LocatorId locatorId = LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID()); return LocatorInfo.builder() .locatorId(locatorId) .qrCode(LocatorQRCode.ofLocator(locator)) .caption(locator.getValue()) .build(); } public LocatorScannedCodeResolverResult resolveLocator(@NonNull final ScannedCode scannedCode) { return locatorScannedCodeResolver.resolve(scannedCode); } public Optional<LocatorQRCode> getTrolleyByUserId(@NonNull final UserId userId) { return trolleyService.getCurrent(userId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\external_services\warehouse\DistributionWarehouseService.java
2
请完成以下Spring Boot application配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/jpatest spring.datasource.username=root spring.datasource.password=sang spring.jpa.hibernate.d
dl-auto=update spring.jpa.show-sql=true spring.jackson.serialization.indent_output=true
repos\JavaEETest-master\Test22-JPA\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public JsonDailyReport postDailyReport(@RequestBody @NonNull final JsonDailyReportRequest request) { final JsonDailyReportItemRequest requestItem = extractRequestItem(request); final User user = loginService.getLoggedInUser(); final BPartner bpartner = user.getBpartner(); final Contracts contracts = contractsService.getContracts(bpartner); final LocalDate date = requestItem.getDate(); final long productId = Long.parseLong(requestItem.getProductId()); final Product product = productSuppliesService.getProductById(productId); final ContractLine contractLine = contracts.getContractLineOrNull(product, date); final BigDecimal qty = requestItem.getQty(); productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder() .bpartner(bpartner) .contractLine(contractLine) .productId(productId) .date(date) .qty(qty) .build()); return getDailyReport(date) .withCountUnconfirmed(userConfirmationService.getCountUnconfirmed(user)); } private static JsonDailyReportItemRequest extractRequestItem(final JsonDailyReportRequest request) {
final List<JsonDailyReportItemRequest> requestItems = request.getItems(); if (requestItems.isEmpty()) { throw new BadRequestException("No request items mentioned"); } else if (requestItems.size() != 1) { throw new BadRequestException("Only one item is allowed"); } else { return requestItems.get(0); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\dailyReport\DailyReportRestController.java
2
请在Spring Boot框架中完成以下Java代码
public String getBatchSearchKey() { return batchSearchKey; } @Override public void setBatchSearchKey(String batchSearchKey) { this.batchSearchKey = batchSearchKey; } @Override public String getBatchSearchKey2() { return batchSearchKey2; } @Override public void setBatchSearchKey2(String batchSearchKey2) { this.batchSearchKey2 = batchSearchKey2; } @Override public String getStatus() { return status; } @Override public void setStatus(String status) { this.status = status; } @Override public ByteArrayRef getBatchDocRefId() { return batchDocRefId; } public void setBatchDocRefId(ByteArrayRef batchDocRefId) { this.batchDocRefId = batchDocRefId; } @Override public String getBatchDocumentJson(String engineType) { if (batchDocRefId != null) { byte[] bytes = batchDocRefId.getBytes(engineType); if (bytes != null) { return new String(bytes, StandardCharsets.UTF_8); } }
return null; } @Override public void setBatchDocumentJson(String batchDocumentJson, String engineType) { this.batchDocRefId = setByteArrayRef(this.batchDocRefId, BATCH_DOCUMENT_JSON_LABEL, batchDocumentJson, engineType); } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } protected static ByteArrayRef setByteArrayRef(ByteArrayRef byteArrayRef, String name, String value, String engineType) { if (byteArrayRef == null) { byteArrayRef = new ByteArrayRef(); } byte[] bytes = null; if (value != null) { bytes = value.getBytes(StandardCharsets.UTF_8); } byteArrayRef.setValue(name, bytes, engineType); return byteArrayRef; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public long findHistoryJobCountByQueryCriteria(HistoryJobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectHistoryJobCountByQueryCriteria", jobQuery); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateHistoryJobTenantIdForDeployment", params); } @Override public void bulkUpdateJobLockWithoutRevisionCheck(List<HistoryJobEntity> historyJobs, String lockOwner, Date lockExpirationTime) { Map<String, Object> params = new HashMap<>(3); params.put("lockOwner", lockOwner); params.put("lockExpirationTime", lockExpirationTime);
bulkUpdateEntities("updateHistoryJobLocks", params, "historyJobs", historyJobs); } @Override public void resetExpiredJob(String jobId) { Map<String, Object> params = new HashMap<>(2); params.put("id", jobId); getDbSqlSession().directUpdate("resetExpiredHistoryJob", params); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisHistoryJobDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public class QueryResultPage<T> { @NonNull PageDescriptor currentPageDescriptor; @Nullable PageDescriptor nextPageDescriptor; /** Number of all items that are part of the selection which this page is a part of. */ int totalSize; /** Point in time when the selection was done */ @NonNull Instant resultTimestamp; @NonNull ImmutableList<T> items; public <R> QueryResultPage<R> mapTo(@NonNull final Function<T, R> mapper) { final ImmutableList<R> mappedItems = items.stream() .map(mapper) .collect(ImmutableList.toImmutableList());
return new QueryResultPage<>(currentPageDescriptor, nextPageDescriptor, totalSize, resultTimestamp, mappedItems); } public <R> QueryResultPage<R> mapAllTo(@NonNull final Function<ImmutableList<T>, ImmutableList<R>> mapper) { return withItems(mapper.apply(getItems())); } public <R> QueryResultPage<R> withItems(@NonNull final ImmutableList<R> replacementItems) { return new QueryResultPage<>( currentPageDescriptor.withSize(replacementItems.size()), nextPageDescriptor, totalSize, resultTimestamp, replacementItems); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\QueryResultPage.java
2
请完成以下Java代码
public final class SyncUUIDs { private SyncUUIDs() { } public static String toUUIDString(final I_C_BPartner bpartner) { return UUIDs.fromIdAsString(bpartner.getC_BPartner_ID()); } public static int getC_BPartner_ID(final String uuid) { return UUIDs.toId(uuid); } public static String toUUIDString(final I_AD_User contact) { return UUIDs.fromIdAsString(contact.getAD_User_ID()); } public static UserId getUserId(@NonNull final String uuid) { return UserId.ofRepoId(UUIDs.toId(uuid)); } public static String toUUIDString(final I_PMM_Product pmmProduct) { return UUIDs.fromIdAsString(pmmProduct.getPMM_Product_ID()); } public static int getPMM_Product_ID(final String uuid) { return UUIDs.toId(uuid); } public static String toUUIDString(final I_C_Flatrate_Term contract) { return UUIDs.fromIdAsString(contract.getC_Flatrate_Term_ID()); }
public static int getC_Flatrate_Term_ID(final String uuid) { return UUIDs.toId(uuid); } public static String toUUIDString(final I_C_RfQResponseLine rfqResponseLine) { return toC_RfQReponseLine_UUID(rfqResponseLine.getC_RfQResponseLine_ID()); } public static String toC_RfQReponseLine_UUID(final int C_RfQResponseLine_ID) { return UUIDs.fromIdAsString(C_RfQResponseLine_ID); } public static int getC_RfQResponseLine_ID(final String uuid) { return UUIDs.toId(uuid); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncUUIDs.java
1
请完成以下Java代码
public static class Section { private String activityTitle; private String activitySubtitle; private String activityImage; private List<Fact> facts; private boolean markdown; @Data public static class Fact { private final String name; private final String value; } } @Data @JsonInclude(JsonInclude.Include.NON_NULL) public static class ActionCard { @JsonProperty("@type") private String type; // ActionCard, OpenUri private String name; private List<Input> inputs; // for ActionCard private List<Action> actions; // for ActionCard private List<Target> targets; @Data public static class Input { @JsonProperty("@type") private String type; // TextInput, DateInput, MultichoiceInput private String id; private boolean isMultiple; private String title; private boolean isMultiSelect; @Data public static class Choice { private final String display; private final String value; }
} @Data public static class Action { @JsonProperty("@type") private final String type; // HttpPOST private final String name; private final String target; // url } @Data public static class Target { private final String os; private final String uri; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\TeamsMessageCard.java
1
请完成以下Spring Boot application配置
quarkus.http.root-path=/api quarkus.load-shedding.enabled=true quarkus.load-shedding.max-limit=10 quarkus.load-shedding.initial-limit=5 quarkus.load-shedding.priority.enabled=true quarkus.load-shedding.
probe-factor=70 quarkus.load-shedding.alpha-factor=1 quarkus.load-shedding.beta-factor=5
repos\tutorials-master\quarkus-modules\quarkus-extension\quarkus-load-shedding\src\main\resources\application.properties
2
请完成以下Java代码
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate(); final int limit = evalCtx.getLimit(Integer.MAX_VALUE); final int offset = evalCtx.getOffset(0); return attributeValuesProvider.getAvailableValues(evalCtx) .stream() .map(namePair -> StringLookupValue.of( namePair.getID(), TranslatableStrings.constant(namePair.getName()), TranslatableStrings.constant(namePair.getDescription()))) .filter(filter) .collect(LookupValuesList.collect()) .pageByOffsetAndLimit(offset, limit); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } @Override public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression() { if (attributeValuesProvider instanceof DefaultAttributeValuesProvider) { final DefaultAttributeValuesProvider defaultAttributeValuesProvider = (DefaultAttributeValuesProvider)attributeValuesProvider;
final AttributeId attributeId = defaultAttributeValuesProvider.getAttributeId(); return SqlForFetchingLookupById.builder() .keyColumnNameFQ(ColumnNameFQ.ofTableAndColumnName(I_M_AttributeValue.Table_Name, I_M_AttributeValue.COLUMNNAME_Value)) .numericKey(false) .displayColumn(ConstantStringExpression.of(I_M_AttributeValue.COLUMNNAME_Name)) .descriptionColumn(ConstantStringExpression.of(I_M_AttributeValue.COLUMNNAME_Description)) .activeColumn(ColumnNameFQ.ofTableAndColumnName(I_M_AttributeValue.Table_Name, I_M_AttributeValue.COLUMNNAME_IsActive)) .sqlFrom(ConstantStringExpression.of(I_M_AttributeValue.Table_Name)) .additionalWhereClause(I_M_AttributeValue.Table_Name + "." + I_M_AttributeValue.COLUMNNAME_M_Attribute_ID + "=" + attributeId.getRepoId()) .build(); } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILookupDescriptor.java
1
请完成以下Java代码
public Optional<LocatorInfo> getSingleDropToLocator() { return lines.stream() .map(DistributionJobLine::getDropToLocator) .distinct() .collect(GuavaCollectors.singleElementOrEmpty()); } @Nullable public ProductId getSingleProductIdOrNull() { return lines.stream() .map(DistributionJobLine::getProductId) .distinct() .collect(GuavaCollectors.singleElementOrNull()); } @Nullable public Quantity getSingleUnitQuantityOrNull() { final MixedQuantity qty = lines.stream()
.map(DistributionJobLine::getQtyToMove) .distinct() .collect(MixedQuantity.collectAndSum()); return qty.toNoneOrSingleValue().orElse(null); } public Optional<DistributionJobLineId> getNextEligiblePickFromLineId(@NonNull final ProductId productId) { return lines.stream() .filter(line -> ProductId.equals(line.getProductId(), productId)) .filter(DistributionJobLine::isEligibleForPicking) .map(DistributionJobLine::getId) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJob.java
1
请完成以下Java代码
public Class<I_I_BPartner> getImportModelClass() { return I_I_BPartner.class; } @Override public String getImportTableName() { return I_I_BPartner.Table_Name; } @Override protected String getImportOrderBySql() { // gody: 20070113 - Order so the same values are consecutive. return I_I_BPartner.COLUMNNAME_BPValue
+ ", " + I_I_BPartner.COLUMNNAME_GlobalId + ", " + I_I_BPartner.COLUMNNAME_I_BPartner_ID; } @Override protected String getTargetTableName() { return I_C_BPartner.Table_Name; } @Override public I_I_BPartner retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException { return new X_I_BPartner(ctx, rs, ITrx.TRXNAME_ThreadInherited); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerImportProcess.java
1
请完成以下Java代码
public class SubmitTaskFormCmd implements Command<VariableMap>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected VariableMap properties; // only fetch variables if they are actually requested; // this avoids unnecessary loading of variables protected boolean returnVariables; protected boolean deserializeValues; public SubmitTaskFormCmd(String taskId, Map<String, Object> properties, boolean returnVariables, boolean deserializeValues) { this.taskId = taskId; this.properties = Variables.fromMap(properties); this.returnVariables = returnVariables; this.deserializeValues = deserializeValues; } public VariableMap execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull("Cannot find task with id " + taskId, "task", task); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkTaskWork(task); } TaskDefinition taskDefinition = task.getTaskDefinition(); if(taskDefinition != null) { TaskFormHandler taskFormHandler = taskDefinition.getTaskFormHandler(); taskFormHandler.submitFormVariables(properties, task); } else { // set variables on standalone task task.setVariables(properties); } ExecutionEntity execution = task.getProcessInstance(); ExecutionVariableSnapshotObserver variablesListener = null; if (returnVariables && execution != null) { variablesListener = new ExecutionVariableSnapshotObserver(execution, false, deserializeValues); }
// complete or resolve the task if (DelegationState.PENDING.equals(task.getDelegationState())) { task.resolve(); task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_RESOLVE); task.triggerUpdateEvent(); } else { task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_COMPLETE); task.complete(); } if (returnVariables) { if (variablesListener != null) { return variablesListener.getVariables(); } else { return task.getCaseDefinitionId() == null ? null : task.getVariablesTyped(false); } } else { return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SubmitTaskFormCmd.java
1
请完成以下Java代码
private boolean isValidVerificationRequest(final @NonNull IProcessPreconditionsContext context) { final InvoiceVerificationRunStatus currentStatus = getInvoiceVerificationRunStatus(context); return InvoiceVerificationRunStatus.Planned.equals(currentStatus); } @Override protected String doIt() throws Exception { final I_C_Invoice_Verification_Run run = getInvoiceVerificationRun(); setAsRunning(run); final InvoiceVerificationRunId invoiceVerificationRunId = InvoiceVerificationRunId.ofRepoId(run.getC_Invoice_Verification_Set_ID(), run.getC_Invoice_Verification_Run_ID()); invoiceVerificationDAO.createVerificationRunLines(invoiceVerificationRunId); setCompleted(run); return MSG_OK; } private void setAsRunning(final I_C_Invoice_Verification_Run run) { run.setStatus(InvoiceVerificationRunStatus.Running.getCode()); run.setDateStart(SystemTime.asTimestamp()); run.setAD_PInstance_ID(getPinstanceId().getRepoId()); InterfaceWrapperHelper.save(run); } private void setCompleted(final I_C_Invoice_Verification_Run run) { run.setStatus(InvoiceVerificationRunStatus.Finished.getCode()); run.setDateEnd(SystemTime.asTimestamp()); InterfaceWrapperHelper.save(run); } private InvoiceVerificationRunStatus getInvoiceVerificationRunStatus(final @NonNull IProcessPreconditionsContext context) { final I_C_Invoice_Verification_Run run = Check.assumeNotNull(queryBL.createQueryBuilder(I_C_Invoice_Verification_Run.class)
.addOnlyActiveRecordsFilter() .filter(context.getQueryFilter(I_C_Invoice_Verification_Run.class)) .create().firstOnly(I_C_Invoice_Verification_Run.class), "C_Invoice_Verification_Run with ID {} not found", context.getSingleSelectedRecordId()); return Check.isBlank(run.getStatus()) ? InvoiceVerificationRunStatus.Planned : InvoiceVerificationRunStatus.ofNullableCode(run.getStatus()); } @NonNull private I_C_Invoice_Verification_Run getInvoiceVerificationRun() { return Check.assumeNotNull(queryBL.createQueryBuilder(I_C_Invoice_Verification_Run.class) .addOnlyActiveRecordsFilter() .filter(getProcessInfo().getQueryFilterOrElseFalse()) .create().firstOnly(I_C_Invoice_Verification_Run.class), "C_Invoice_Verification_Run with ID {} not found", getProcessInfo().getRecord_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_Verification_Run_Execute.java
1
请完成以下Java代码
private List<Optional<? extends AbstractTsKvEntity>> findAllAndAggregateAsync(EntityId entityId, String key, long startTs, long endTs, long timeBucket, Aggregation aggregation) { long interval = endTs - startTs; long remainingPart = interval % timeBucket; List<TimescaleTsKvEntity> timescaleTsKvEntities; if (remainingPart == 0) { timescaleTsKvEntities = switchAggregation(key, startTs, endTs, timeBucket, aggregation, entityId.getId()); } else { interval = interval - remainingPart; timescaleTsKvEntities = new ArrayList<>(); timescaleTsKvEntities.addAll(switchAggregation(key, startTs, startTs + interval, timeBucket, aggregation, entityId.getId())); timescaleTsKvEntities.addAll(switchAggregation(key, startTs + interval, endTs, remainingPart, aggregation, entityId.getId())); } return toResultList(entityId, key, timescaleTsKvEntities); } private static List<Optional<? extends AbstractTsKvEntity>> toResultList(EntityId entityId, String key, List<TimescaleTsKvEntity> timescaleTsKvEntities) { if (!CollectionUtils.isEmpty(timescaleTsKvEntities)) { List<Optional<? extends AbstractTsKvEntity>> result = new ArrayList<>(); timescaleTsKvEntities.forEach(entity -> { if (entity != null && entity.isNotEmpty()) { entity.setEntityId(entityId.getId()); entity.setStrKey(key); result.add(Optional.of(entity)); } else { result.add(Optional.empty());
} }); return result; } else { return Collections.emptyList(); } } private List<TimescaleTsKvEntity> switchAggregation(String key, long startTs, long endTs, long timeBucket, Aggregation aggregation, UUID entityId) { Integer keyId = keyDictionaryDao.getOrSaveKeyId(key); switch (aggregation) { case AVG: return aggregationRepository.findAvg(entityId, keyId, timeBucket, startTs, endTs); case MAX: return aggregationRepository.findMax(entityId, keyId, timeBucket, startTs, endTs); case MIN: return aggregationRepository.findMin(entityId, keyId, timeBucket, startTs, endTs); case SUM: return aggregationRepository.findSum(entityId, keyId, timeBucket, startTs, endTs); case COUNT: return aggregationRepository.findCount(entityId, keyId, timeBucket, startTs, endTs); default: throw new IllegalArgumentException("Not supported aggregation type: " + aggregation); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\timescale\TimescaleTimeseriesDao.java
1
请完成以下Java代码
public Optional<String> getStrValue() { return kv.getStrValue(); } @Override public Optional<Long> getLongValue() { return kv.getLongValue(); } @Override public Optional<Boolean> getBooleanValue() { return kv.getBooleanValue(); } @Override public Optional<Double> getDoubleValue() { return kv.getDoubleValue(); } @Override public Optional<String> getJsonValue() { return kv.getJsonValue(); } @Override public Object getValue() { return kv.getValue(); } @Override public String getValueAsString() { return kv.getValueAsString();
} @Override public int getDataPoints() { int length; switch (getDataType()) { case STRING: length = getStrValue().get().length(); break; case JSON: length = getJsonValue().get().length(); break; default: return 1; } return Math.max(1, (length + MAX_CHARS_PER_DATA_POINT - 1) / MAX_CHARS_PER_DATA_POINT); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\BasicTsKvEntry.java
1
请完成以下Java代码
private static ExistingLockInfo toExistingLockInfo(@NonNull final LockInfo lockInfo, @NonNull final TableRecordReference tableRecordReference) { return ExistingLockInfo.builder() .ownerName(lockInfo.getLockOwner().getOwnerName()) .lockedRecord(tableRecordReference) .allowMultipleOwners(lockInfo.isAllowMultipleOwners()) .autoCleanup(lockInfo.isAutoCleanup()) .created(lockInfo.getAcquiredAt()) .build(); } @Override public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(@NonNull final TableRecordReferenceSet recordRefs) { if (recordRefs.isEmpty()) { return ImmutableSetMultimap.of(); } final ImmutableSetMultimap.Builder<TableRecordReference, ExistingLockInfo> result = ImmutableSetMultimap.builder(); try (final CloseableReentrantLock ignored = mainLock.open()) { for (final TableRecordReference recordRef : recordRefs) { final LockKey lockKey = LockKey.ofTableRecordReference(recordRef);
final RecordLocks recordLocks = locks.get(lockKey); if (recordLocks == null) { continue; } for (final LockInfo lockInfo : recordLocks.getLocks()) { result.put(recordRef, toExistingLockInfo(lockInfo, recordRef)); } } return result.build(); } } @Value(staticConstructor = "of") public static class LockKey { int adTableId; int recordId; public static LockKey ofTableRecordReference(@NonNull final TableRecordReference recordRef) {return of(recordRef.getAD_Table_ID(), recordRef.getRecord_ID());} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\spi\impl\PlainLockDatabase.java
1
请在Spring Boot框架中完成以下Java代码
public Authentication convert(HttpServletRequest request) { RequestMatcher.MatchResult result = this.requestMatcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = result.getVariables().get("registrationId"); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); if (clientRegistration == null) { this.logger.debug("Did not process OIDC Back-Channel Logout since no ClientRegistration was found"); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } String logoutToken = request.getParameter("logout_token"); if (logoutToken == null) { this.logger.debug("Failed to process OIDC Back-Channel Logout since no logout token was found"); throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST);
} return new OidcLogoutAuthenticationToken(logoutToken, clientRegistration); } /** * The logout endpoint. Defaults to * {@code /logout/connect/back-channel/{registrationId}}. * @param requestMatcher the {@link RequestMatcher} to use */ void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OidcLogoutAuthenticationConverter.java
2
请在Spring Boot框架中完成以下Java代码
private Mono<String> getTokenKey(Token token) { String keyId = token.getKeyId(); String cached = this.cachedTokenKeys.get(keyId); if (cached != null) { return Mono.just(cached); } return this.securityService.fetchTokenKeys() .doOnSuccess(this::cacheTokenKeys) .filter((tokenKeys) -> tokenKeys.containsKey(keyId)) .map((tokenKeys) -> { String tokenKey = tokenKeys.get(keyId); Assert.state(tokenKey != null, "No token key found for '%s'".formatted(keyId)); return tokenKey; }) .switchIfEmpty(Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_KEY_ID, "Key Id present in token header does not match"))); } private void cacheTokenKeys(Map<String, String> tokenKeys) { this.cachedTokenKeys = Map.copyOf(tokenKeys); } private boolean hasValidSignature(Token token, String key) { try { PublicKey publicKey = getPublicKey(key); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(publicKey); signature.update(token.getContent()); return signature.verify(token.getSignature()); } catch (GeneralSecurityException ex) { return false; } } private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { key = key.replace("-----BEGIN PUBLIC KEY-----\n", ""); key = key.replace("-----END PUBLIC KEY-----", ""); key = key.trim().replace("\n", ""); byte[] bytes = Base64.getDecoder().decode(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); return KeyFactory.getInstance("RSA").generatePublic(keySpec); } private Mono<Void> validateExpiry(Token token) { long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); if (currentTime > token.getExpiry()) { return Mono.error(new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired")); } return Mono.empty(); } private Mono<Void> validateIssuer(Token token) { return this.securityService.getUaaUrl() .map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl)) .filter((issuerUri) -> issuerUri.equals(token.getIssuer())) .switchIfEmpty(Mono .error(new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match"))) .then(); } private Mono<Void> validateAudience(Token token) { if (!token.getScope().contains("actuator.read")) { return Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_AUDIENCE, "Token does not have audience actuator")); } return Mono.empty(); } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\reactive\TokenValidator.java
2
请完成以下Java代码
public BigDecimal getApprovalAmt() { return getStatementDifference(); } // getApprovalAmt /** * Get Currency * * @return Currency */ @Override public int getC_Currency_ID() { return getCashBook().getC_Currency_ID(); } // getC_Currency_ID
/** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MCash
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MCash.java
1
请完成以下Java代码
public boolean verifyAllEqualUsingFrequency(List<String> list) { return list.isEmpty() || Collections.frequency(list, list.get(0)) == list.size(); } public boolean verifyAllEqualUsingStream(List<String> list) { return list.stream() .distinct() .count() <= 1; } public boolean verifyAllEqualAnotherUsingStream(List<String> list) { return list.isEmpty() || list.stream() .allMatch(list.get(0)::equals); } public boolean verifyAllEqualUsingGuava(List<String> list) { return Iterables.all(list, new Predicate<String>() {
public boolean apply(String s) { return s.equals(list.get(0)); } }); } public boolean verifyAllEqualUsingApacheCommon(List<String> list) { return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate<String>() { public boolean evaluate(String s) { return s.equals(list.get(0)); } }); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\allequalelements\VerifyAllEqualListElements.java
1
请完成以下Java代码
public class TbMsgToEmailNode implements TbNode { private static final String IMAGES = "images"; private static final String DYNAMIC = "dynamic"; private TbMsgToEmailNodeConfiguration config; private boolean dynamicMailBodyType; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { config = TbNodeUtils.convert(configuration, TbMsgToEmailNodeConfiguration.class); dynamicMailBodyType = DYNAMIC.equals(config.getMailBodyType()); } @Override public void onMsg(TbContext ctx, TbMsg msg) { TbEmail email = convert(msg); TbMsg emailMsg = buildEmailMsg(ctx, msg, email); ctx.tellNext(emailMsg, TbNodeConnectionType.SUCCESS); } private TbMsg buildEmailMsg(TbContext ctx, TbMsg msg, TbEmail email) { String emailJson = JacksonUtil.toString(email); return ctx.transformMsg(msg, TbMsgType.SEND_EMAIL, msg.getOriginator(), msg.getMetaData().copy(), emailJson); } private TbEmail convert(TbMsg msg) { TbEmail.TbEmailBuilder builder = TbEmail.builder(); builder.from(fromTemplate(config.getFromTemplate(), msg)); builder.to(fromTemplate(config.getToTemplate(), msg));
builder.cc(fromTemplate(config.getCcTemplate(), msg)); builder.bcc(fromTemplate(config.getBccTemplate(), msg)); String htmlStr = dynamicMailBodyType ? fromTemplate(config.getIsHtmlTemplate(), msg) : config.getMailBodyType(); builder.html(Boolean.parseBoolean(htmlStr)); builder.subject(fromTemplate(config.getSubjectTemplate(), msg)); builder.body(fromTemplate(config.getBodyTemplate(), msg)); String imagesStr = msg.getMetaData().getValue(IMAGES); if (!StringUtils.isEmpty(imagesStr)) { Map<String, String> imgMap = JacksonUtil.fromString(imagesStr, new TypeReference<HashMap<String, String>>() {}); builder.images(imgMap); } return builder.build(); } private String fromTemplate(String template, TbMsg msg) { return StringUtils.isNotEmpty(template) ? TbNodeUtils.processPattern(template, msg) : null; } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mail\TbMsgToEmailNode.java
1
请在Spring Boot框架中完成以下Java代码
public String deals() { log.info("Client is requesting new deals!"); List<TravelDeal> travelDealList = travelDealRepository.findAll(); if (!travelDealList.isEmpty()) { int randomDeal = new Random().nextInt(travelDealList.size()); return travelDealList.get(randomDeal) .toString(); } else { return "NO DEALS"; } } @RequestMapping(method = GET, path = "/") @ResponseBody public String get() throws UnknownHostException {
StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Host: ") .append(InetAddress.getLocalHost() .getHostName()) .append("<br/>"); stringBuilder.append("IP: ") .append(InetAddress.getLocalHost() .getHostAddress()) .append("<br/>"); stringBuilder.append("Type: ") .append("Travel Agency") .append("<br/>"); return stringBuilder.toString(); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-kubernetes\kubernetes-guide\travel-agency-service\src\main\java\com\baeldung\spring\cloud\kubernetes\travelagency\controller\TravelAgencyController.java
2
请完成以下Java代码
private static void cleanupModifier(StringBuffer result, String modifier) { Matcher m = FUZZY_MODIFIDER.matcher(modifier); if (m.matches()) { modifier = m.group(1); } for (int i = 0; i < modifier.length(); i++) { char c = modifier.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-') { result.append(c); } } } protected static Document parse(URL url) throws Exception { if (dbf == null) { dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true); } DocumentBuilder db = dbf.newDocumentBuilder(); return db.parse(url.toString()); } protected static void copyInputStream(InputStream in, OutputStream out) throws Exception { byte[] buffer = new byte[4096]; int len = in.read(buffer); while (len >= 0) { out.write(buffer, 0, len); len = in.read(buffer); } } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BpmnTransformer.java
1
请完成以下Java代码
public long getTotalSpace() throws IOException { return 0; } @Override public long getUsableSpace() throws IOException { return 0; } @Override public long getUnallocatedSpace() throws IOException { return 0; } @Override public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) { return getJarPathFileStore().supportsFileAttributeView(type); } @Override public boolean supportsFileAttributeView(String name) { return getJarPathFileStore().supportsFileAttributeView(name); } @Override public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) { return getJarPathFileStore().getFileStoreAttributeView(type); }
@Override public Object getAttribute(String attribute) throws IOException { try { return getJarPathFileStore().getAttribute(attribute); } catch (UncheckedIOException ex) { throw ex.getCause(); } } protected FileStore getJarPathFileStore() { try { return Files.getFileStore(this.fileSystem.getJarPath()); } catch (IOException ex) { throw new UncheckedIOException(ex); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileStore.java
1
请完成以下Java代码
protected void waitBeforeRetry(long waitTime) { try { Thread.sleep(waitTime); } catch (InterruptedException e) { log.debug("I am interrupted while waiting for a retry."); } } public void setNumOfRetries(int numOfRetries) { this.numOfRetries = numOfRetries; } public void setWaitIncreaseFactor(int waitIncreaseFactor) { this.waitIncreaseFactor = waitIncreaseFactor; } public void setWaitTimeInMs(int waitTimeInMs) {
this.waitTimeInMs = waitTimeInMs; } public int getNumOfRetries() { return numOfRetries; } public int getWaitIncreaseFactor() { return waitIncreaseFactor; } public int getWaitTimeInMs() { return waitTimeInMs; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\RetryInterceptor.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public int getPages() { return pages;
} public void setPages(int pages) { this.pages = pages; } public List<Chapter> getChapters() { return chapters; } public void setChapters(List<Chapter> chapters) { this.chapters = chapters; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseTriggers\src\main\java\com\bookstore\entity\Book.java
1
请完成以下Java代码
private Collection<String> getTrxNamesForCurrentThread() { return getTrxNamesForThreadId(Thread.currentThread().getId()); } private Collection<String> getTrxNamesForThreadId(final long threadId) { synchronized (threadId2TrxName) { Collection<String> trxNames = threadId2TrxName.get(threadId); if (trxNames == null) { trxNames = new HashSet<String>(); threadId2TrxName.put(threadId, trxNames); } return trxNames; } } private Collection<ITrxSavepoint> getSavepointsForTrxName(final String trxName) { synchronized (trxName2SavePoint) { Collection<ITrxSavepoint> savepoints = trxName2SavePoint.get(trxName); if (savepoints == null) { savepoints = new HashSet<ITrxSavepoint>(); trxName2SavePoint.put(trxName, savepoints); } return savepoints; } } private String mkStacktraceInfo(final Thread thread, final String beginStacktrace)
{ final StringBuilder msgSB = new StringBuilder(); msgSB.append(">>> Stacktrace at trx creation, commit or rollback:\n"); msgSB.append(beginStacktrace); msgSB.append(">>> Current stacktrace of the creating thread:\n"); if (thread.isAlive()) { msgSB.append(mkStacktrace(thread)); } else { msgSB.append("\t(Thread already finished)\n"); } final String msg = msgSB.toString(); return msg; } @Override public String getCreationStackTrace(final String trxName) { return trxName2Stacktrace.get(trxName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\OpenTrxBL.java
1
请完成以下Java代码
public int getAD_Task_ID() { return AD_Task_ID; } public void setAD_Task_ID(int aD_Task_ID) { AD_Task_ID = aD_Task_ID; } public int getWEBUI_Board_ID() { return WEBUI_Board_ID; } public void setWEBUI_Board_ID(final int WEBUI_Board_ID) { this.WEBUI_Board_ID = WEBUI_Board_ID; } public void setIsCreateNewRecord(final boolean isCreateNewRecord) { this.isCreateNewRecord = isCreateNewRecord; } public boolean isCreateNewRecord() { return isCreateNewRecord; } public void setWEBUI_NameBrowse(final String webuiNameBrowse) { this.webuiNameBrowse = webuiNameBrowse; } public String getWEBUI_NameBrowse() { return webuiNameBrowse; }
public void setWEBUI_NameNew(final String webuiNameNew) { this.webuiNameNew = webuiNameNew; } public String getWEBUI_NameNew() { return webuiNameNew; } public void setWEBUI_NameNewBreadcrumb(final String webuiNameNewBreadcrumb) { this.webuiNameNewBreadcrumb = webuiNameNewBreadcrumb; } public String getWEBUI_NameNewBreadcrumb() { return webuiNameNewBreadcrumb; } /** * @param mainTableName table name of main tab or null */ public void setMainTableName(String mainTableName) { this.mainTableName = mainTableName; } /** * @return table name of main tab or null */ public String getMainTableName() { return mainTableName; } } // MTreeNode
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTreeNode.java
1
请完成以下Java代码
private void copyHUAttribute(final I_M_HU_Attribute oldHUAttribute) { final HuId oldHUId = HuId.ofRepoId(oldHUAttribute.getM_HU_ID()); final HuId newHUId = old2new_M_HU_ID.get(oldHUId); if (newHUId == null) { throw new AdempiereException("HU was not already cloned for " + oldHUId); } final I_M_HU_Attribute newHUAttribute = InterfaceWrapperHelper.newInstance(I_M_HU_Attribute.class); InterfaceWrapperHelper.copyValues(oldHUAttribute, newHUAttribute); newHUAttribute.setM_HU_ID(newHUId.getRepoId()); newHUAttribute.setValue(oldHUAttribute.getValue()); // programmatically setting this because the framework handles it as a search key and avoids copying it InterfaceWrapperHelper.save(newHUAttribute); } private void copyHUStorage(final I_M_HU_Storage oldHUStorage) { final HuId oldHUId = HuId.ofRepoId(oldHUStorage.getM_HU_ID()); final HuId newHUId = old2new_M_HU_ID.get(oldHUId); if (newHUId == null) { throw new AdempiereException("HU was not already cloned for " + oldHUId); }
final I_M_HU_Storage newHUStorage = InterfaceWrapperHelper.newInstance(I_M_HU_Storage.class); InterfaceWrapperHelper.copyValues(oldHUStorage, newHUStorage); newHUStorage.setM_HU_ID(newHUId.getRepoId()); InterfaceWrapperHelper.save(newHUStorage); } private void copyHUItemStorage(final I_M_HU_Item_Storage oldHUItemStorage) { final HuItemId oldHUItemId = HuItemId.ofRepoId(oldHUItemStorage.getM_HU_Item_ID()); final HuItemId newHUItemId = old2new_M_HU_Item_ID.get(oldHUItemId); if (newHUItemId == null) { throw new AdempiereException("HU Item was not already cloned for " + oldHUItemId); } final I_M_HU_Item_Storage newHUItemStorage = InterfaceWrapperHelper.newInstance(I_M_HU_Item_Storage.class); InterfaceWrapperHelper.copyValues(oldHUItemStorage, newHUItemStorage); newHUItemStorage.setM_HU_Item_ID(newHUItemId.getRepoId()); InterfaceWrapperHelper.save(newHUItemStorage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CopyHUsCommand.java
1
请完成以下Java代码
public void setSubscriptionInfo (int AD_User_ID) { m_AD_User_ID = AD_User_ID; m_ci = MContactInterest.get(getCtx(), getR_InterestArea_ID(), AD_User_ID, false, get_TrxName()); } // setSubscription /** * Set AD_User_ID * @param AD_User_ID user */ public void setAD_User_ID (int AD_User_ID) { m_AD_User_ID = AD_User_ID; } /** * Get AD_User_ID * @return user */ public int getAD_User_ID () { return m_AD_User_ID; } /** * Get Subscribe Date * @return subscribe date */ public Timestamp getSubscribeDate () { if (m_ci != null)
return m_ci.getSubscribeDate(); return null; } /** * Get Opt Out Date * @return opt-out date */ public Timestamp getOptOutDate () { if (m_ci != null) return m_ci.getOptOutDate(); return null; } /** * Is Subscribed * @return true if sunscribed */ public boolean isSubscribed() { if (m_AD_User_ID <= 0 || m_ci == null) return false; // We have a BPartner Contact return m_ci.isSubscribed(); } // isSubscribed } // MInterestArea
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MInterestArea.java
1
请完成以下Java代码
public class ClusterAppFullAssignRequest { private List<ClusterAppAssignMap> clusterMap; private Set<String> remainingList; public List<ClusterAppAssignMap> getClusterMap() { return clusterMap; } public ClusterAppFullAssignRequest setClusterMap( List<ClusterAppAssignMap> clusterMap) { this.clusterMap = clusterMap; return this; } public Set<String> getRemainingList() {
return remainingList; } public ClusterAppFullAssignRequest setRemainingList(Set<String> remainingList) { this.remainingList = remainingList; return this; } @Override public String toString() { return "ClusterAppFullAssignRequest{" + "clusterMap=" + clusterMap + ", remainingList=" + remainingList + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\ClusterAppFullAssignRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class ShiroConfig { @Bean public Realm realm() { // 创建 SimpleAccountRealm 对象 SimpleAccountRealm realm = new SimpleAccountRealm(); // 添加两个用户。参数分别是 username、password、roles 。 realm.addAccount("admin", "admin", "ADMIN"); realm.addAccount("normal", "normal", "NORMAL"); return realm; } @Bean public DefaultWebSecurityManager securityManager() { // 创建 DefaultWebSecurityManager 对象 DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 设置其使用的 Realm securityManager.setRealm(this.realm()); return securityManager; } @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean() { // 创建 ShiroFilterFactoryBean 对象,用于创建 ShiroFilter 过滤器 ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean(); // 设置 SecurityManager filterFactoryBean.setSecurityManager(this.securityManager()); // 设置 URL 们 filterFactoryBean.setLoginUrl("/login"); // 登陆 URL filterFactoryBean.setSuccessUrl("/login_success"); // 登陆成功 URL filterFactoryBean.setUnauthorizedUrl("/unauthorized"); // 无权限 URL
// 设置 URL 的权限配置 filterFactoryBean.setFilterChainDefinitionMap(this.filterChainDefinitionMap()); return filterFactoryBean; } private Map<String, String> filterChainDefinitionMap() { Map<String, String> filterMap = new LinkedHashMap<>(); // 注意要使用有序的 LinkedHashMap ,顺序匹配 filterMap.put("/test/echo", "anon"); // 允许匿名访问 filterMap.put("/test/admin", "roles[ADMIN]"); // 需要 ADMIN 角色 filterMap.put("/test/normal", "roles[NORMAL]"); // 需要 NORMAL 角色 filterMap.put("/logout", "logout"); // 退出 filterMap.put("/**", "authc"); // 默认剩余的 URL ,需要经过认证 return filterMap; } }
repos\SpringBoot-Labs-master\lab-33\lab-33-shiro-demo\src\main\java\cn\iocoder\springboot\lab01\shirodemo\config\ShiroConfig.java
2
请完成以下Java代码
public String getScopeId() { return null; } @Override public String getSubScopeId() { return null; } @Override public String getScopeType() { return null; } @Override public String getScopeDefinitionId() { return null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("IdentityLinkEntity[id=").append(id);
sb.append(", type=").append(type); if (userId != null) { sb.append(", userId=").append(userId); } if (groupId != null) { sb.append(", groupId=").append(groupId); } if (taskId != null) { sb.append(", taskId=").append(taskId); } if (processInstanceId != null) { sb.append(", processInstanceId=").append(processInstanceId); } if (processDefId != null) { sb.append(", processDefId=").append(processDefId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntity.java
1
请完成以下Java代码
public final void setRabbitOperations(RabbitOperations rabbitOperations) { this.rabbitOperations = rabbitOperations; } /** * @return The {@link RabbitOperations} for the gateway. */ public final @Nullable RabbitOperations getRabbitOperations() { return this.rabbitOperations; } @Override public final void afterPropertiesSet() throws IllegalArgumentException, BeanInitializationException { if (this.rabbitOperations == null) { throw new IllegalArgumentException("'connectionFactory' or 'rabbitTemplate' is required"); }
try { initGateway(); } catch (Exception ex) { throw new BeanInitializationException("Initialization of Rabbit gateway failed: " + ex.getMessage(), ex); } } /** * Subclasses can override this for custom initialization behavior. * Gets called after population of this instance's bean properties. */ protected void initGateway() { } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\RabbitGatewaySupport.java
1
请完成以下Java代码
public void setInstrForDbtrAgt(String value) { this.instrForDbtrAgt = value; } /** * Gets the value of the purp property. * * @return * possible object is * {@link Purpose2CHCode } * */ public Purpose2CHCode getPurp() { return purp; } /** * Sets the value of the purp property. * * @param value * allowed object is * {@link Purpose2CHCode } * */ public void setPurp(Purpose2CHCode value) { this.purp = value; } /** * Gets the value of the rgltryRptg property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rgltryRptg property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRgltryRptg().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link RegulatoryReporting3 } * * */ public List<RegulatoryReporting3> getRgltryRptg() { if (rgltryRptg == null) { rgltryRptg = new ArrayList<RegulatoryReporting3>(); } return this.rgltryRptg; } /** * Gets the value of the rmtInf property. * * @return * possible object is * {@link RemittanceInformation5CH } * */ public RemittanceInformation5CH getRmtInf() { return rmtInf; } /** * Sets the value of the rmtInf property. * * @param value * allowed object is * {@link RemittanceInformation5CH } * */ public void setRmtInf(RemittanceInformation5CH value) { this.rmtInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\CreditTransferTransactionInformation10CH.java
1
请完成以下Java代码
public int getAD_Replication_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Replication_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Replicated. @param IsReplicated The data is successfully replicated */ public void setIsReplicated (boolean IsReplicated) { set_ValueNoCheck (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated)); } /** Get Replicated. @return The data is successfully replicated */ public boolean isReplicated () {
Object oo = get_Value(COLUMNNAME_IsReplicated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Run.java
1
请完成以下Java代码
public static TargetRecordAction ofRecordAndWindow(@NonNull final TableRecordReference record, @NonNull final AdWindowId adWindowId) { return builder().record(record).adWindowId(Optional.of(adWindowId)).build(); } public static TargetRecordAction of(@NonNull final String tableName, final int recordId) { return of(TableRecordReference.of(tableName, recordId)); } public static TargetRecordAction cast(final TargetAction targetAction) { return (TargetRecordAction)targetAction; } @NonNull @Builder.Default Optional<AdWindowId> adWindowId = Optional.empty(); @NonNull TableRecordReference record; String recordDisplayText; }
@lombok.Value @lombok.Builder public static class TargetViewAction implements TargetAction { public static TargetViewAction cast(final TargetAction targetAction) { return (TargetViewAction)targetAction; } @Nullable AdWindowId adWindowId; @NonNull String viewId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationRequest.java
1
请完成以下Java代码
private IAllocationResult createAllocationResult( final IAllocationRequest request, final IAllocationRequest requestActual, final boolean outTrx) { final IHUTransactionCandidate trx = createHUTransaction(requestActual, outTrx); return AllocationUtils.createQtyAllocationResult( request.getQty(), // qtyToAllocate requestActual.getQty(), // qtyAllocated Arrays.asList(trx), // trxs Collections.<IHUTransactionAttribute> emptyList() // attributeTrxs ); } private IHUTransactionCandidate createHUTransaction(final IAllocationRequest request, final boolean outTrx) { final HUTransactionCandidate trx = new HUTransactionCandidate(getReferenceModel(), getM_HU_Item(), getVHU_Item(), request, outTrx); return trx; } public IProductStorage getStorage() { return storage; } private I_M_HU_Item getM_HU_Item() { return huItem;
} private I_M_HU_Item getVHU_Item() { // TODO: implement: get VHU Item or create it return huItem; } public Object getReferenceModel() { return referenceModel; } @Override public List<IPair<IAllocationRequest, IAllocationResult>> unloadAll(final IHUContext huContext) { final IAllocationRequest request = AllocationUtils.createQtyRequest(huContext, storage.getProductId(), // product storage.getQty(), // qty huContext.getDate() // date ); final IAllocationResult result = unload(request); return Collections.singletonList(ImmutablePair.of(request, result)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractAllocationSourceDestination.java
1
请完成以下Java代码
public int getTaskHeight() { return taskHeight; } public void setTaskHeight(int taskHeight) { this.taskHeight = taskHeight; } public int getSubProcessMargin() { return subProcessMargin; } public void setSubProcessMargin(int subProcessMargin) { this.subProcessMargin = subProcessMargin; }
// Due to a bug (see // http://forum.jgraph.com/questions/5952/mxhierarchicallayout-not-correct-when-using-child-vertex) // We must extend the default hierarchical layout to tweak it a bit (see url // link) otherwise the layouting crashes. // // Verify again with a later release if fixed (ie the mxHierarchicalLayout // can be used directly) static class CustomLayout extends mxHierarchicalLayout { public CustomLayout(mxGraph graph, int orientation) { super(graph, orientation); this.traverseAncestors = false; } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BpmnAutoLayout.java
1
请完成以下Java代码
public class OverloadingErrors<T extends Serializable> { public void print() { System.out.println("Signature is: print()"); } /* // Uncommenting this method will lead to a compilation error: java: method print() is already defined in class // The method signature is independent from return type public int print() { System.out.println("Signature is: print()"); return 0; } */ /* // Uncommenting this method will lead to a compilation error: java: method print() is already defined in class // The method signature is independent from modifiers private final void print() { System.out.println("Signature is: print()"); } */ /* // Uncommenting this method will lead to a compilation error: java: method print() is already defined in class // The method signature is independent from thrown exception declaration public void print() throws IllegalStateException { System.out.println("Signature is: print()"); throw new IllegalStateException(); } */ public void print(int parameter) { System.out.println("Signature is: print(int)");
} /* // Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class // The method signature is independent from parameter names public void print(int anotherParameter) { System.out.println("Signature is: print(int)"); } */ public void printElement(T t) { System.out.println("Signature is: printElement(T)"); } /* // Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure // Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure public void printElement(Serializable o) { System.out.println("Signature is: printElement(Serializable)"); } */ public void print(Object... parameter) { System.out.println("Signature is: print(Object...)"); } /* // Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[]) // Even though the signatures appear different, after compilation they both resolve to sum(Object[]) public void print(Object[] parameter) { System.out.println("Signature is: print(Object[])"); } */ }
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\signature\OverloadingErrors.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width;
} @Override public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height; } @Override public void setHeight(int height) { this.height = height; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ParticipantProcess.java
1
请完成以下Java代码
public List<String> getKey() { return key; } public int[] getValue() { return value; } public void setValue(int[] value) { this.value = value; } public void setKey(List<String> key) { this.key = key; } public int[] getCheck() { return check; } public void setCheck(int[] check) { this.check = check; } public int[] getBase() { return base;
} public void setBase(int[] base) { this.base = base; } public int[] getLength() { return length; } public void setLength(int[] length) { this.length = length; } public void setSize(int size) { this.size = size; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\DoubleArrayTrieInteger.java
1
请在Spring Boot框架中完成以下Java代码
static class SpringBootDataGemFireSecuritySslEnvironmentPostProcessorEnabled { } @Conditional(SslTriggersCondition.class) static class AnySslTriggerCondition { } } static class SslTriggersCondition extends AnyNestedCondition { public SslTriggersCondition() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @Conditional(TrustedKeyStoreIsPresentCondition.class) static class TrustedKeyStoreCondition { } @ConditionalOnProperty(prefix = SECURITY_SSL_PROPERTY_PREFIX, name = { "keystore", "truststore" }) static class SpringDataGemFireSecuritySslKeyStoreAndTruststorePropertiesSet { } @ConditionalOnProperty(SECURITY_SSL_USE_DEFAULT_CONTEXT) static class SpringDataGeodeSslUseDefaultContextPropertySet { }
@ConditionalOnProperty({ GEMFIRE_SSL_KEYSTORE_PROPERTY, GEMFIRE_SSL_TRUSTSTORE_PROPERTY }) static class ApacheGeodeSslKeyStoreAndTruststorePropertiesSet { } } static class TrustedKeyStoreIsPresentCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); return locateKeyStoreInClassPath(environment).isPresent() || locateKeyStoreInFileSystem(environment).isPresent() || locateKeyStoreInUserHome(environment).isPresent(); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\SslAutoConfiguration.java
2
请完成以下Java代码
abstract class PaymentsToReconcileViewBasedProcess extends ViewBasedProcessTemplate implements IProcessPrecondition { @Override protected abstract ProcessPreconditionsResolution checkPreconditionsApplicable(); @Override protected final PaymentsToReconcileView getView() { return PaymentsToReconcileView.cast(super.getView()); } @Override protected final PaymentToReconcileRow getSingleSelectedRow() { return PaymentToReconcileRow.cast(super.getSingleSelectedRow()); } @Override protected final Stream<PaymentToReconcileRow> streamSelectedRows() { return super.streamSelectedRows() .map(PaymentToReconcileRow::cast); } protected final List<PaymentToReconcileRow> getSelectedPaymentToReconcileRows() { return streamSelectedRows() .collect(ImmutableList.toImmutableList()); } protected ViewId getBanksStatementReconciliationViewId() { return getView().getBankStatementViewId(); }
protected final BankStatementReconciliationView getBanksStatementReconciliationView() { final ViewId bankStatementViewId = getBanksStatementReconciliationViewId(); final IViewsRepository viewsRepo = getViewsRepo(); return BankStatementReconciliationView.cast(viewsRepo.getView(bankStatementViewId)); } protected final void invalidateBankStatementReconciliationView() { invalidateView(getBanksStatementReconciliationViewId()); } protected final BankStatementLineRow getSingleSelectedBankStatementRowOrNull() { final ViewRowIdsSelection selection = getParentViewRowIdsSelection(); if (selection == null || selection.isEmpty()) { return null; } final ImmutableList<BankStatementLineRow> rows = getBanksStatementReconciliationView() .streamByIds(selection) .collect(ImmutableList.toImmutableList()); return rows.size() == 1 ? rows.get(0) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\process\PaymentsToReconcileViewBasedProcess.java
1
请完成以下Java代码
public Attachment createAttachment(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, String url) { return commandExecutor.execute(new CreateAttachmentCmd(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription, null, url)); } public InputStream getAttachmentContent(String attachmentId) { return commandExecutor.execute(new GetAttachmentContentCmd(attachmentId)); } public InputStream getTaskAttachmentContent(String taskId, String attachmentId) { return commandExecutor.execute(new GetTaskAttachmentContentCmd(taskId, attachmentId)); } public void deleteAttachment(String attachmentId) { commandExecutor.execute(new DeleteAttachmentCmd(attachmentId)); } public void deleteTaskAttachment(String taskId, String attachmentId) { commandExecutor.execute(new DeleteAttachmentCmd(taskId, attachmentId)); } public Attachment getAttachment(String attachmentId) { return commandExecutor.execute(new GetAttachmentCmd(attachmentId)); } public Attachment getTaskAttachment(String taskId, String attachmentId) { return commandExecutor.execute(new GetTaskAttachmentCmd(taskId, attachmentId)); } public List<Attachment> getTaskAttachments(String taskId) { return commandExecutor.execute(new GetTaskAttachmentsCmd(taskId)); } public List<Attachment> getProcessInstanceAttachments(String processInstanceId) { return commandExecutor.execute(new GetProcessInstanceAttachmentsCmd(processInstanceId)); } public void saveAttachment(Attachment attachment) { commandExecutor.execute(new SaveAttachmentCmd(attachment)); }
public List<Task> getSubTasks(String parentTaskId) { return commandExecutor.execute(new GetSubTasksCmd(parentTaskId)); } public TaskReport createTaskReport() { return new TaskReportImpl(commandExecutor); } @Override public void handleBpmnError(String taskId, String errorCode) { commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode)); } @Override public void handleBpmnError(String taskId, String errorCode, String errorMessage) { commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage)); } @Override public void handleBpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) { commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage, variables)); } @Override public void handleEscalation(String taskId, String escalationCode) { commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode)); } @Override public void handleEscalation(String taskId, String escalationCode, Map<String, Object> variables) { commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode, variables)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public List<User> getByMap(Map<String, Object> map) { return userDao.getByMap(map); } @Override public User getById(Integer id) { return userDao.getById(id); } @Override public User create(User user) { userDao.create(user); return user; }
@Override public User update(User user) { userDao.update(user); return user; } @Override public int delete(Integer id) { return userDao.delete(id); } @Override public User getByUserName(String userName) { return userDao.getByUserName(userName); } }
repos\springBoot-master\springboot-dubbo\abel-user-provider\src\main\java\cn\abel\user\service\impl\UserServiceImpl.java
2
请完成以下Java代码
public void setFirstBackoff(Duration firstBackoff) { this.firstBackoff = firstBackoff; } public @Nullable Duration getMaxBackoff() { return maxBackoff; } public void setMaxBackoff(Duration maxBackoff) { this.maxBackoff = maxBackoff; } public int getFactor() { return factor; } public void setFactor(int factor) { this.factor = factor; } public boolean isBasedOnPreviousValue() { return basedOnPreviousValue; } public void setBasedOnPreviousValue(boolean basedOnPreviousValue) { this.basedOnPreviousValue = basedOnPreviousValue; } @Override public String toString() { return new ToStringCreator(this).append("firstBackoff", firstBackoff) .append("maxBackoff", maxBackoff) .append("factor", factor) .append("basedOnPreviousValue", basedOnPreviousValue) .toString(); } } public static class JitterConfig {
private double randomFactor = 0.5; public void validate() { Assert.isTrue(randomFactor >= 0 && randomFactor <= 1, "random factor must be between 0 and 1 (default 0.5)"); } public JitterConfig() { } public JitterConfig(double randomFactor) { this.randomFactor = randomFactor; } public double getRandomFactor() { return randomFactor; } public void setRandomFactor(double randomFactor) { this.randomFactor = randomFactor; } @Override public String toString() { return new ToStringCreator(this).append("randomFactor", randomFactor).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.jpa.properties.org.hibernate.envers.audit_strategy=org.hibernate.envers.strategy.ValidityAuditStrategy spring.jpa.open-in-view=false # for s
pecifying schema # for MySQL # spring.jpa.properties.org.hibernate.envers.default_catalog=... (e.g., bookstoredb) # for non-MySQL #spring.jpa.properties.org.hibernate.envers.default_schema=...
repos\Hibernate-SpringBoot-master\HibernateSpringBootEnvers\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyAndTenantId(String jobHandlerType, String processDefinitionKey, String tenantId) { Map<String, String> params = new HashMap<>(3); params.put("handlerType", jobHandlerType); params.put("processDefinitionKey", processDefinitionKey); params.put("tenantId", tenantId); return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyAndTenantId", params); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateTimerJobTenantIdForDeployment", params); } @Override public void bulkUpdateJobLockWithoutRevisionCheck(List<TimerJobEntity> timerJobEntities, String lockOwner, Date lockExpirationTime) {
Map<String, Object> params = new HashMap<>(3); params.put("lockOwner", lockOwner); params.put("lockExpirationTime", lockExpirationTime); bulkUpdateEntities("updateTimerJobLocks", params, "timerJobs", timerJobEntities); } @Override public void bulkDeleteWithoutRevision(List<TimerJobEntity> timerJobEntities) { bulkDeleteEntities("deleteTimerJobs", timerJobEntities); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisTimerJobDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public List<BatchPart> findBatchPartsByBatchId(String batchId) { HashMap<String, Object> params = new HashMap<>(); params.put("batchId", batchId); return getDbSqlSession().selectList("selectBatchPartsByBatchId", params); } @Override @SuppressWarnings("unchecked") public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) { HashMap<String, Object> params = new HashMap<>(); params.put("batchId", batchId); params.put("status", status); return getDbSqlSession().selectList("selectBatchPartsByBatchIdAndStatus", params); } @Override @SuppressWarnings("unchecked") public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) { HashMap<String, Object> params = new HashMap<>(); params.put("scopeId", scopeId); params.put("scopeType", scopeType); return getDbSqlSession().selectList("selectBatchPartsByScopeIdAndScopeType", params); } @Override
@SuppressWarnings("unchecked") public List<BatchPart> findBatchPartsByQueryCriteria(BatchPartQueryImpl batchPartQuery) { return getDbSqlSession().selectList("selectBatchPartsByQueryCriteria", batchPartQuery, getManagedEntityClass()); } @Override public long findBatchPartCountByQueryCriteria(BatchPartQueryImpl batchPartQuery) { return (Long) getDbSqlSession().selectOne("selectBatchPartCountByQueryCriteria", batchPartQuery); } @Override protected IdGenerator getIdGenerator() { return batchServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\data\impl\MybatisBatchPartDataManager.java
2
请完成以下Java代码
private void doCommit() { try { transactionManager.commit(); } catch (HeuristicMixedException e) { throw new TransactionException("Unable to commit transaction", e); } catch (HeuristicRollbackException e) { throw new TransactionException("Unable to commit transaction", e); } catch (RollbackException e) { throw new TransactionException("Unable to commit transaction", e); } catch (SystemException e) { throw new TransactionException("Unable to commit transaction", e); } catch (RuntimeException e) { doRollback(true, e); throw e; } catch (Error e) { doRollback(true, e); throw e; } } private void doRollback(boolean isNew, Throwable originalException) { Throwable rollbackEx = null; try { if (isNew) { transactionManager.rollback(); } else { transactionManager.setRollbackOnly(); } } catch (SystemException e) { LOGGER.debug("Error when rolling back transaction", e); } catch (RuntimeException e) { rollbackEx = e; throw e; } catch (Error e) {
rollbackEx = e; throw e; } finally { if (rollbackEx != null && originalException != null) { LOGGER.error("Error when rolling back transaction, original exception was:", originalException); } } } private static class TransactionException extends RuntimeException { private static final long serialVersionUID = 1L; private TransactionException() {} private TransactionException(String s) { super(s); } private TransactionException(String s, Throwable throwable) { super(s, throwable); } private TransactionException(Throwable throwable) { super(throwable); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\JtaTransactionInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getDuration() { return duration; } /** * Sets the value of the duration property. * * @param value * allowed object is * {@link Duration } * */ public void setDuration(Duration value) { this.duration = value; } /** * Details about discounts.Gets the value of the discount property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the discount property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDiscount().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DiscountType } * * */ public List<DiscountType> getDiscount() { if (discount == null) { discount = new ArrayList<DiscountType>(); } return this.discount; } /** * The minimum payment which must be paid at the payment due date. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getMinimumPayment() { return minimumPayment; } /** * Sets the value of the minimumPayment property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setMinimumPayment(BigDecimal value) { this.minimumPayment = value; }
/** * A free-text comment for the payment conditions. * * @return * possible object is * {@link String } * */ public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ public void setComment(String value) { this.comment = value; } /** * Gets the value of the paymentConditionsExtension property. * * @return * possible object is * {@link PaymentConditionsExtensionType } * */ public PaymentConditionsExtensionType getPaymentConditionsExtension() { return paymentConditionsExtension; } /** * Sets the value of the paymentConditionsExtension property. * * @param value * allowed object is * {@link PaymentConditionsExtensionType } * */ public void setPaymentConditionsExtension(PaymentConditionsExtensionType value) { this.paymentConditionsExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PaymentConditionsType.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApiDefinitionEntity entity = (ApiDefinitionEntity) o; return Objects.equals(id, entity.id) && Objects.equals(app, entity.app) && Objects.equals(ip, entity.ip) && Objects.equals(port, entity.port) && Objects.equals(gmtCreate, entity.gmtCreate) && Objects.equals(gmtModified, entity.gmtModified) && Objects.equals(apiName, entity.apiName) && Objects.equals(predicateItems, entity.predicateItems); } @Override public int hashCode() {
return Objects.hash(id, app, ip, port, gmtCreate, gmtModified, apiName, predicateItems); } @Override public String toString() { return "ApiDefinitionEntity{" + "id=" + id + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", apiName='" + apiName + '\'' + ", predicateItems=" + predicateItems + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\gateway\ApiDefinitionEntity.java
1
请完成以下Java代码
public void submitAcquiredJobs(String engineName, AcquiredJobs acquiredJobs) { acquiredJobsByEngine.put(engineName, acquiredJobs); } public void submitAdditionalJobBatch(String engineName, List<String> jobIds) { CollectionUtil.addToMapOfLists(additionalJobBatchesByEngine, engineName, jobIds); } public void reset() { additionalJobBatchesByEngine.clear(); // jobs that were rejected in the previous acquisition cycle // are to be resubmitted for execution in the current cycle additionalJobBatchesByEngine.putAll(rejectedJobBatchesByEngine); rejectedJobBatchesByEngine.clear(); acquiredJobsByEngine.clear(); acquisitionException = null; acquisitionTime = 0; isJobAdded = false; } /** * @return true, if for all engines there were less jobs acquired than requested */ public boolean areAllEnginesIdle() { for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) { int jobsAcquired = acquiredJobs.getJobIdBatches().size() + acquiredJobs.getNumberOfJobsFailedToLock(); if (jobsAcquired >= acquiredJobs.getNumberOfJobsAttemptedToAcquire()) { return false; } } return true; } /** * true if at least one job could not be locked, regardless of engine */ public boolean hasJobAcquisitionLockFailureOccurred() { for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) { if (acquiredJobs.getNumberOfJobsFailedToLock() > 0) { return true; } } return false; } // getters and setters public void setAcquisitionTime(long acquisitionTime) { this.acquisitionTime = acquisitionTime; } public long getAcquisitionTime() { return acquisitionTime; } /** * Jobs that were acquired in the current acquisition cycle. * @return */ public Map<String, AcquiredJobs> getAcquiredJobsByEngine() { return acquiredJobsByEngine; } /**
* Jobs that were rejected from execution in the acquisition cycle * due to lacking execution resources. * With an execution thread pool, these jobs could not be submitted due to * saturation of the underlying job queue. */ public Map<String, List<List<String>>> getRejectedJobsByEngine() { return rejectedJobBatchesByEngine; } /** * Jobs that have been acquired in previous cycles and are supposed to * be re-submitted for execution */ public Map<String, List<List<String>>> getAdditionalJobsByEngine() { return additionalJobBatchesByEngine; } public void setAcquisitionException(Exception e) { this.acquisitionException = e; } public Exception getAcquisitionException() { return acquisitionException; } public void setJobAdded(boolean isJobAdded) { this.isJobAdded = isJobAdded; } public boolean isJobAdded() { return isJobAdded; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobAcquisitionContext.java
1
请完成以下Java代码
public Set<Entry<String, Object>> entrySet() { Set<String> attrNames = keySet(); Set<Entry<String, Object>> entries = new HashSet<>(attrNames.size()); for (String attrName : attrNames) { Object value = this.session.getAttribute(attrName); entries.add(new AbstractMap.SimpleEntry<>(attrName, value)); } return Collections.unmodifiableSet(entries); } private class SessionValues extends AbstractCollection<Object> { @Override public Iterator<Object> iterator() { return new Iterator<Object>() { private Iterator<Entry<String, Object>> i = entrySet().iterator(); @Override public boolean hasNext() { return this.i.hasNext(); } @Override public Object next() { return this.i.next().getValue(); } @Override public void remove() { this.i.remove(); } }; }
@Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); } @Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请在Spring Boot框架中完成以下Java代码
public class MatchInv { @NonNull MatchInvId id; @NonNull InvoiceAndLineId invoiceAndLineId; @NonNull InOutAndLineId inoutLineId; @NonNull ClientAndOrgId clientAndOrgId; @NonNull SOTrx soTrx; @NonNull Instant dateTrx; @NonNull Instant dateAcct; boolean posted; @NonNull UserId updatedByUserId; @NonNull ProductId productId; @NonNull AttributeSetInstanceId asiId; @NonNull StockQtyAndUOMQty qty; @NonNull MatchInvType type; @Getter(AccessLevel.NONE) @Nullable MatchInvCostPart costPart; @Builder private MatchInv( @NonNull final MatchInvId id, @NonNull final InvoiceAndLineId invoiceAndLineId, @NonNull final InOutAndLineId inoutLineId, @NonNull final ClientAndOrgId clientAndOrgId, @NonNull final SOTrx soTrx, @NonNull final Instant dateTrx, @NonNull final Instant dateAcct, final boolean posted, @NonNull final UserId updatedByUserId, @NonNull final ProductId productId, @NonNull final AttributeSetInstanceId asiId, @NonNull final StockQtyAndUOMQty qty, @NonNull final MatchInvType type, @Nullable final MatchInvCostPart costPart) { this.id = id; this.invoiceAndLineId = invoiceAndLineId; this.inoutLineId = inoutLineId; this.clientAndOrgId = clientAndOrgId; this.soTrx = soTrx; this.dateAcct = dateAcct; this.dateTrx = dateTrx; this.posted = posted; this.updatedByUserId = updatedByUserId; this.productId = productId; this.asiId = asiId; this.qty = qty;
this.type = type; if (type.isCost()) { this.costPart = Check.assumeNotNull(costPart, "costPart shall be provided for Cost matching type"); } else { this.costPart = null; } } public InvoiceId getInvoiceId() {return invoiceAndLineId.getInvoiceId();} public InOutId getInOutId() {return inoutLineId.getInOutId();} public ClientId getClientId() {return clientAndOrgId.getClientId();} public OrgId getOrgId() {return clientAndOrgId.getOrgId();} @NonNull public MatchInvCostPart getCostPartNotNull() { if (type.isCost()) { return Check.assumeNotNull(costPart, "costPart is set"); } else { throw new AdempiereException("costPart not available when matching type is not Cost"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\MatchInv.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; }
public void setAge(int age) { this.age = age; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "Author{" + "id=" + id + ", name=" + name + ", genre=" + genre + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\entity\Author.java
1
请完成以下Java代码
public class ClusterApp2 { public static void main(String[] args) { // Load configuration Config config = ConfigFactory.load(); ActorSystem system = ActorSystem.create("ClusterSystem", config); // Create WorkerRouterActor with 5 workers ActorRef workerRouter = system.actorOf(WorkerRouterActor.props(5), "workerRouter"); // Create MasterActor ActorRef masterActor = system.actorOf(MasterActor.props(workerRouter), "masterActor"); // Log cluster membership Cluster cluster = Cluster.get(system); System.out.println("Cluster initialized with self member: " + cluster.selfAddress());
// Submit tasks masterActor.tell(new TaskMessage("Task 1"), ActorRef.noSender()); masterActor.tell(new TaskMessage("Task 2"), ActorRef.noSender()); masterActor.tell(new TaskMessage("Task 3"), ActorRef.noSender()); // Keep system alive for demonstration purposes try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } system.terminate(); } }
repos\springboot-demo-master\akka\src\main\java\com\et\akka\cluster\ClusterApp2.java
1
请在Spring Boot框架中完成以下Java代码
public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; public Post() { } public Post(String title) { this.title = title; } public Long getId() { return id; } public void setId(Long id) {
this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Post{" + "id=" + id + ", text='" + title + '\'' + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\detachedentity\entity\Post.java
2
请完成以下Java代码
public ResponseEntity<PageResult<S3Storage>> queryS3Storage(S3StorageQueryCriteria criteria, Pageable pageable){ return new ResponseEntity<>(s3StorageService.queryAll(criteria, pageable),HttpStatus.OK); } @PostMapping @ApiOperation("上传文件") public ResponseEntity<Object> uploadS3Storage(@RequestParam MultipartFile file){ S3Storage storage = s3StorageService.upload(file); Map<String,Object> map = new HashMap<>(3); map.put("id",storage.getId()); map.put("errno",0); map.put("data",new String[]{amzS3Config.getDomain() + "/" + storage.getFilePath()}); return new ResponseEntity<>(map,HttpStatus.OK); } @Log("下载文件") @ApiOperation("下载文件") @GetMapping(value = "/download/{id}") public ResponseEntity<Object> downloadS3Storage(@PathVariable Long id){ Map<String,Object> map = new HashMap<>(1); S3Storage storage = s3StorageService.getById(id); if (storage == null) {
map.put("message", "文件不存在或已被删除"); return new ResponseEntity<>(map, HttpStatus.NOT_FOUND); } // 仅适合公开文件访问,私有文件可以使用服务中的 privateDownload 方法 String url = amzS3Config.getDomain() + "/" + storage.getFilePath(); map.put("url", url); return new ResponseEntity<>(map,HttpStatus.OK); } @Log("删除多个文件") @DeleteMapping @ApiOperation("删除多个文件") @PreAuthorize("@el.check('storage:del')") public ResponseEntity<Object> deleteAllS3Storage(@RequestBody List<Long> ids) { s3StorageService.deleteAll(ids); return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\S3StorageController.java
1
请完成以下Java代码
public class SpringAsyncExecutor extends DefaultAsyncJobExecutor { protected TaskExecutor taskExecutor; protected SpringRejectedJobsHandler rejectedJobsHandler; public SpringAsyncExecutor() {} public SpringAsyncExecutor(TaskExecutor taskExecutor, SpringRejectedJobsHandler rejectedJobsHandler) { this.taskExecutor = taskExecutor; this.rejectedJobsHandler = rejectedJobsHandler; } public TaskExecutor getTaskExecutor() { return taskExecutor; } /** * Required spring injected {@link TaskExecutor} implementation that will be used to execute runnable jobs. * * @param taskExecutor */ public void setTaskExecutor(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public SpringRejectedJobsHandler getRejectedJobsHandler() { return rejectedJobsHandler; } /** * Required spring injected {@link SpringRejectedJobsHandler} implementation that will be used when jobs were rejected by the task executor. * * @param rejectedJobsHandler */
public void setRejectedJobsHandler(SpringRejectedJobsHandler rejectedJobsHandler) { this.rejectedJobsHandler = rejectedJobsHandler; } @Override public boolean executeAsyncJob(Job job) { try { taskExecutor.execute(new ExecuteAsyncRunnable((JobEntity) job, processEngineConfiguration)); return true; } catch (RejectedExecutionException e) { rejectedJobsHandler.jobRejected(this, job); return false; } } @Override protected void initAsyncJobExecutionThreadPool() { // Do nothing, using the Spring taskExecutor } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringAsyncExecutor.java
1
请完成以下Java代码
public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange exchange) { HttpMethod requestMethod = exchange.getRequest().getMethod(); return stream(config.getMethods()).anyMatch(httpMethod -> httpMethod == requestMethod); } @Override public String toString() { return String.format("Methods: %s", Arrays.toString(config.getMethods())); } }; }
public static class Config { private HttpMethod[] methods = new HttpMethod[0]; public HttpMethod[] getMethods() { return methods; } public void setMethods(HttpMethod... methods) { this.methods = methods; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\MethodRoutePredicateFactory.java
1
请完成以下Java代码
private ForecastLineRequest toForecastLineRequest(final @NotNull I_I_Forecast importRecord) { final I_C_UOM uom = uomDAO.getById(UomId.ofRepoId(importRecord.getC_UOM_ID())); return ForecastLineRequest.builder() .productId(ProductId.ofRepoId(importRecord.getM_Product_ID())) .quantity(Quantity.of(importRecord.getQty(), uom)) .activityId(ActivityId.ofRepoIdOrNull(importRecord.getC_Activity_ID())) .campaignId(CampaignId.ofRepoIdOrNull(importRecord.getC_Campaign_ID())) .projectId(ProjectId.ofRepoIdOrNull(importRecord.getC_Project_ID())) .quantityCalculated(Quantity.ofNullable(importRecord.getQtyCalculated(), uom)) .build(); } @Override protected String getTargetTableName() {return I_M_Forecast.Table_Name;} @Override protected void updateAndValidateImportRecordsImpl() { MForecastImportTableSqlUpdater.builder() .selection(getImportRecordsSelection()) .tableName(getImportTableName()) .build() .updateIForecast(); } @Override protected String getImportOrderBySql() {return ForecastHeaderKey.IMPORT_ORDER_BY;} @Override public Class<I_I_Forecast> getImportModelClass() {return I_I_Forecast.class;} @Override public String getImportTableName() {return I_I_Forecast.Table_Name;} @Override public I_I_Forecast retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException {
return new X_I_Forecast(ctx, rs, ITrx.TRXNAME_ThreadInherited); } @Value @Builder private static class ForecastHeaderKey { public static final String IMPORT_ORDER_BY = I_I_Forecast.COLUMNNAME_Name + ',' + I_I_Forecast.COLUMNNAME_DatePromised + ',' + I_I_Forecast.COLUMNNAME_BPValue + ',' + I_I_Forecast.COLUMNNAME_WarehouseValue + ',' + I_I_Forecast.COLUMNNAME_PriceList + ',' + I_I_Forecast.COLUMNNAME_ProductValue; @NonNull String name; @NonNull WarehouseId warehouseId; @Nullable PriceListId priceListId; @Nullable BPartnerId bpartnerId; @Nullable String externalId; @NonNull LocalDate datePromisedDay; public static ForecastHeaderKey of(final I_I_Forecast importRecord) { return ForecastHeaderKey.builder() .name(StringUtils.trimBlankToOptional(importRecord.getName()).orElseThrow(() -> new FillMandatoryException("Name"))) .warehouseId(WarehouseId.ofRepoId(importRecord.getM_Warehouse_ID())) .priceListId(PriceListId.ofRepoIdOrNull(importRecord.getM_PriceList_ID())) .bpartnerId(BPartnerId.ofRepoIdOrNull(importRecord.getC_BPartner_ID())) .externalId(StringUtils.trimBlankToNull(importRecord.getExternalId())) .datePromisedDay(importRecord.getDatePromised().toLocalDateTime().toLocalDate()) .build(); } } public static final class ForecastImportContext { @Nullable ForecastId forecastId; @Nullable ForecastImportProcess.ForecastHeaderKey forecastHeaderKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\impexp\ForecastImportProcess.java
1
请在Spring Boot框架中完成以下Java代码
public DecisionRequirementsDefinitionDto getDecisionRequirementsDefinition() { RepositoryService repositoryService = engine.getRepositoryService(); DecisionRequirementsDefinition definition = null; try { definition = repositoryService.getDecisionRequirementsDefinition(decisionRequirementsDefinitionId); } catch (NotFoundException e) { throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); } catch (NotValidException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e); } return DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(definition); } @Override public DecisionRequirementsDefinitionXmlDto getDecisionRequirementsDefinitionDmnXml() { InputStream decisionRequirementsModelInputStream = null; try { decisionRequirementsModelInputStream = engine.getRepositoryService().getDecisionRequirementsModel(decisionRequirementsDefinitionId); byte[] decisionRequirementsModel = IoUtil.readInputStream(decisionRequirementsModelInputStream, "decisionRequirementsModelDmnXml"); return DecisionRequirementsDefinitionXmlDto.create(decisionRequirementsDefinitionId, new String(decisionRequirementsModel, "UTF-8"));
} catch (NotFoundException e) { throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); } catch (NotValidException e) { throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); } catch (ProcessEngineException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e); } catch (UnsupportedEncodingException e) { throw new RestException(Status.INTERNAL_SERVER_ERROR, e); } finally { IoUtil.closeSilently(decisionRequirementsModelInputStream); } } @Override public Response getDecisionRequirementsDefinitionDiagram() { DecisionRequirementsDefinition definition = engine.getRepositoryService().getDecisionRequirementsDefinition(decisionRequirementsDefinitionId); InputStream decisionRequirementsDiagram = engine.getRepositoryService().getDecisionRequirementsDiagram(decisionRequirementsDefinitionId); if (decisionRequirementsDiagram == null) { return Response.noContent().build(); } else { String fileName = definition.getDiagramResourceName(); return Response.ok(decisionRequirementsDiagram).header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileName)) .type(ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix(fileName)).build(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\DecisionRequirementsDefinitionResourceImpl.java
2
请完成以下Java代码
protected void applyConfigOnEnginesAfterClasspathDiscovery() { var engineNames = getEngineNamesFoundInClasspath(); for (var engineName : engineNames) { executeConfigurationBeforeEngineCreation(engineName); } } protected List<String> getEngineNamesFoundInClasspath() { var engineFactories = getEngineFactories(); return engineFactories.stream() .map(ScriptEngineFactory::getEngineName) .collect(Collectors.toList()); } /** * Fetches the config logic of a given engine from the mappings and executes it in case it exists.
* * @param engineName the given engine name */ protected void executeConfigurationBeforeEngineCreation(String engineName) { var config = engineNameToInitLogicMappings.get(engineName); if (config != null) { config.run(); } } protected void disableGraalVMInterpreterOnlyModeWarnings() { System.setProperty("polyglot.engine.WarnInterpreterOnly", "false"); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\CamundaScriptEngineManager.java
1