instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class JsonAttachment
{
@ApiModelProperty( //
allowEmptyValue = false, //
value = "Reference in terms of the external system. Can reference multiple records (e.g. multiple order line candidates)\n"
+ "To be used in conjunction with <code>externalSystemCode</code>")
String externalReference;
@ApiModelProperty( //
value = "Identifier of the external system this attachment came from.\n"
+ "To be used in conjunction with <code>externalReference</code>")
String externalSystemCode;
@ApiModelProperty( //
allowEmptyValue = false, //
value = "ID assigned to the attachment data by metasfresh")
String attachmentId;
JsonAttachmentType type;
String filename;
@ApiModelProperty( //
allowEmptyValue = true, //
value = "MIME type of the binary data; `null` if the attachment's type is `URL`")
String mimeType;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
String url;
@JsonCreator | @Builder(toBuilder = true)
private JsonAttachment(
@JsonProperty("externalReference") @NonNull final String externalReference,
@JsonProperty("externalSystemCode") @NonNull final String externalSystemCode,
@JsonProperty("attachmentId") @NonNull final String attachmentId,
@JsonProperty("type") final @NonNull JsonAttachmentType type,
@JsonProperty("filename") @NonNull final String filename,
@JsonProperty("mimeType") @Nullable final String mimeType,
@JsonProperty("url") final String url)
{
this.externalReference = externalReference;
this.externalSystemCode = externalSystemCode;
this.attachmentId = attachmentId;
this.type = type;
this.filename = filename;
this.mimeType = mimeType;
this.url = url;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v1\response\JsonAttachment.java | 2 |
请完成以下Java代码 | public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final String filter = evalCtx.getFilter();
return labelsValuesLookupDataSource.findEntities(evalCtx, filter);
}
public Set<Object> normalizeStringIds(final Set<String> stringIds)
{
if (stringIds.isEmpty())
{
return ImmutableSet.of();
}
if (isLabelsValuesUseNumericKey())
{
return stringIds.stream()
.map(LabelsLookup::convertToInt)
.collect(ImmutableSet.toImmutableSet());
}
else
{
return ImmutableSet.copyOf(stringIds);
}
} | private static int convertToInt(final String stringId)
{
try
{
return Integer.parseInt(stringId);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting `" + stringId + "` to int.", ex);
}
}
public ColumnSql getSqlForFetchingValueIdsByLinkId(@NonNull final String tableNameOrAlias)
{
final String sql = "SELECT array_agg(" + labelsValueColumnName + ")"
+ " FROM " + labelsTableName
+ " WHERE " + labelsLinkColumnName + "=" + tableNameOrAlias + "." + linkColumnName
+ " AND IsActive='Y'";
return ColumnSql.ofSql(sql, tableNameOrAlias);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LabelsLookup.java | 1 |
请完成以下Java代码 | protected void createSnapshotsByParentIds(final Set<Integer> huIds)
{
query(I_M_HU_Item.class)
.addInArrayOrAllFilter(I_M_HU_Item.COLUMN_M_HU_ID, huIds)
.create()
.insertDirectlyInto(I_M_HU_Item_Snapshot.class)
.mapCommonColumns()
.mapColumnToConstant(I_M_HU_Item_Snapshot.COLUMNNAME_Snapshot_UUID, getSnapshotId())
.execute();
}
@Override
protected Map<Integer, I_M_HU_Item_Snapshot> retrieveModelSnapshotsByParent(final I_M_HU hu)
{
return query(I_M_HU_Item_Snapshot.class)
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_M_HU_ID, hu.getM_HU_ID())
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create()
.map(I_M_HU_Item_Snapshot.class, snapshot2ModelIdFunction);
}
@Override
protected Map<Integer, I_M_HU_Item> retrieveModelsByParent(final I_M_HU hu)
{
return query(I_M_HU_Item.class)
.addEqualsFilter(I_M_HU_Item.COLUMN_M_HU_ID, hu.getM_HU_ID())
.create()
.mapById(I_M_HU_Item.class);
}
@Override
protected I_M_HU_Item_Snapshot retrieveModelSnapshot(final I_M_HU_Item huItem)
{
return query(I_M_HU_Item_Snapshot.class)
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_M_HU_Item_ID, huItem.getM_HU_Item_ID())
.addEqualsFilter(I_M_HU_Item_Snapshot.COLUMN_Snapshot_UUID, getSnapshotId())
.create()
.firstOnlyNotNull(I_M_HU_Item_Snapshot.class); | }
@Override
protected void restoreChildrenFromSnapshots(I_M_HU_Item huItem)
{
final M_HU_SnapshotHandler includedHUSnapshotHandler = new M_HU_SnapshotHandler(this);
includedHUSnapshotHandler.restoreModelsFromSnapshotsByParent(huItem);
final M_HU_Item_Storage_SnapshotHandler huItemStorageSnapshotHandler = new M_HU_Item_Storage_SnapshotHandler(this);
huItemStorageSnapshotHandler.restoreModelsFromSnapshotsByParent(huItem);
}
@Override
protected void restoreModelWhenSnapshotIsMissing(final I_M_HU_Item model)
{
// shall not happen because we are NEVER deleting an HU Item
throw new HUException("Cannot restore " + model + " because snapshot is missing");
}
@Override
protected int getModelId(final I_M_HU_Item_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_Item_ID();
}
@Override
protected I_M_HU_Item getModel(I_M_HU_Item_Snapshot modelSnapshot)
{
return modelSnapshot.getM_HU_Item();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Item_SnapshotHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommentsController {
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
private List<CommentDTO> comments = null;
/**
* Public constructor to initialize the comments and handle the
* ParseException
*
* @throws ParseException
*/
public CommentsController() throws ParseException {
this.comments = Arrays.asList(new CommentDTO("task11", "comment on task11", formatter.parse("2015-04-23")),
new CommentDTO("task12", "comment on task12", formatter.parse("2015-05-12")),
new CommentDTO("task11", "new comment on task11", formatter.parse("2015-04-27")),
new CommentDTO("task21", "comment on task21", formatter.parse("2015-01-15")),
new CommentDTO("task22", "comment on task22", formatter.parse("2015-03-05")));
}
/**
* Get comments for specific taskid that is passed in the path. | *
* @param taskId
* @return
*/
@RequestMapping(value = "/{taskId}", method = RequestMethod.GET, headers = "Accept=application/json")
public List<CommentDTO> getCommentsByTaskId(@PathVariable("taskId") String taskId) {
List<CommentDTO> commentListToReturn = new ArrayList<CommentDTO>();
for (CommentDTO currentComment : comments) {
if (currentComment.getTaskId().equalsIgnoreCase(taskId)) {
commentListToReturn.add(currentComment);
}
}
return commentListToReturn;
}
} | repos\spring-boot-microservices-master\comments-webservice\src\main\java\com\rohitghatol\microservices\comments\apis\CommentsController.java | 2 |
请完成以下Java代码 | public ILogicExpression toConstantExpression(final boolean constantValue)
{
if (this.constantValue != null && this.constantValue == constantValue)
{
return this;
}
return new LogicTuple(constantValue, this);
}
@Override
public String getExpressionString()
{
return expressionStr;
}
@Override
public Set<CtxName> getParameters()
{
if (_parameters == null)
{
if (isConstant())
{
_parameters = ImmutableSet.of();
}
else
{
final Set<CtxName> result = new LinkedHashSet<>();
if (operand1 instanceof CtxName)
{
result.add((CtxName)operand1);
}
if (operand2 instanceof CtxName)
{
result.add((CtxName)operand2);
}
_parameters = ImmutableSet.copyOf(result);
}
}
return _parameters;
}
/**
* @return {@link CtxName} or {@link String}; never returns null
*/
public Object getOperand1()
{
return operand1;
}
/** | * @return {@link CtxName} or {@link String}; never returns null
*/
public Object getOperand2()
{
return operand2;
}
/**
* @return operator; never returns null
*/
public String getOperator()
{
return operator;
}
@Override
public String toString()
{
return getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return getExpressionString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicTuple.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMyRoles(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("#username == authentication.principal.username")
public String getMyRoles2(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser loadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
@PreFilter("filterObject != authentication.principal.username")
public String joinUsernames(List<String> usernames) {
return usernames.stream().collect(Collectors.joining(";"));
}
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames") | public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
}
@PostFilter("filterObject != authentication.principal.username")
public List<String> getAllUsernamesExceptCurrent() {
return userRoleRepository.getAllUsernames();
}
@IsViewer
public String getUsername4() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PreAuthorize("#username == authentication.principal.username")
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser securedLoadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\service\UserRoleService.java | 2 |
请完成以下Java代码 | public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDurationInMillis() {
return durationInMillis;
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
} | public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public void setProcessDefinitionVersion(Integer processDefinitionVersion) {
this.processDefinitionVersion = processDefinitionVersion;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricScopeInstanceEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void forwardToSubscriptionManagerService(TenantId tenantId, EntityId entityId,
Consumer<SubscriptionManagerService> toSubscriptionManagerService,
Supplier<TransportProtos.ToCoreMsg> toCore) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId);
if (currentPartitions.contains(tpi)) {
if (subscriptionManagerService.isPresent()) {
toSubscriptionManagerService.accept(subscriptionManagerService.get());
} else {
log.warn("Possible misconfiguration because subscriptionManagerService is null!");
}
} else {
TransportProtos.ToCoreMsg toCoreMsg = toCore.get();
clusterService.pushMsgToCore(tpi, entityId.getId(), toCoreMsg, null);
}
}
protected <T> void addWsCallback(ListenableFuture<T> saveFuture, Consumer<T> callback) {
addCallback(saveFuture, callback, wsCallBackExecutor);
}
protected <T> void addCallback(ListenableFuture<T> saveFuture, Consumer<T> callback, Executor executor) {
Futures.addCallback(saveFuture, new FutureCallback<>() { | @Override
public void onSuccess(@Nullable T result) {
callback.accept(result);
}
@Override
public void onFailure(Throwable t) {}
}, executor);
}
protected static Consumer<Throwable> safeCallback(FutureCallback<Void> callback) {
if (callback != null) {
return callback::onFailure;
} else {
return throwable -> {};
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\AbstractSubscriptionService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private PathPatternRequestMatcher.Builder getRequestMatcherBuilder() {
if (this.requestMatcherBuilder != null) {
return this.requestMatcherBuilder;
}
this.requestMatcherBuilder = this.context.getBeanProvider(PathPatternRequestMatcher.Builder.class)
.getIfUnique(() -> constructRequestMatcherBuilder(this.context));
return this.requestMatcherBuilder;
}
private PathPatternRequestMatcher.Builder constructRequestMatcherBuilder(ApplicationContext context) {
PathPatternRequestMatcherBuilderFactoryBean requestMatcherBuilder = new PathPatternRequestMatcherBuilderFactoryBean();
requestMatcherBuilder.setApplicationContext(context);
requestMatcherBuilder.setBeanFactory(context.getAutowireCapableBeanFactory());
requestMatcherBuilder.setBeanName(requestMatcherBuilder.toString());
return ThrowingSupplier.of(requestMatcherBuilder::getObject).get();
}
private boolean anyPathsDontStartWithLeadingSlash(String... patterns) {
for (String pattern : patterns) {
if (!pattern.startsWith("/")) {
return true;
}
}
return false;
}
/**
* <p>
* Match when the request URI matches one of {@code patterns}. See
* {@link org.springframework.web.util.pattern.PathPattern} for matching rules.
* </p>
* <p>
* If a specific {@link RequestMatcher} must be specified, use
* {@link #requestMatchers(RequestMatcher...)} instead
* </p>
* @param patterns the patterns to match on
* @return the object that is chained after creating the {@link RequestMatcher}.
* @since 5.8
*/
public C requestMatchers(String... patterns) {
return requestMatchers(null, patterns);
}
/**
* <p> | * Match when the {@link HttpMethod} is {@code method}
* </p>
* <p>
* If a specific {@link RequestMatcher} must be specified, use
* {@link #requestMatchers(RequestMatcher...)} instead
* </p>
* @param method the {@link HttpMethod} to use or {@code null} for any
* {@link HttpMethod}.
* @return the object that is chained after creating the {@link RequestMatcher}.
* @since 5.8
*/
public C requestMatchers(HttpMethod method) {
return requestMatchers(method, "/**");
}
/**
* Subclasses should implement this method for returning the object that is chained to
* the creation of the {@link RequestMatcher} instances.
* @param requestMatchers the {@link RequestMatcher} instances that were created
* @return the chained Object for the subclass which allows association of something
* else to the {@link RequestMatcher}
*/
protected abstract C chainRequestMatchers(List<RequestMatcher> requestMatchers);
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\AbstractRequestMatcherRegistry.java | 2 |
请完成以下Java代码 | public AbstractServiceConfiguration<S> setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
}
public FlowableEventDispatcher getEventDispatcher() {
return eventDispatcher;
}
public AbstractServiceConfiguration<S> setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
public List<FlowableEventListener> getEventListeners() {
return eventListeners;
}
public AbstractServiceConfiguration<S> setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners;
return this;
}
public Map<String, List<FlowableEventListener>> getTypedEventListeners() {
return typedEventListeners;
}
public AbstractServiceConfiguration<S> setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
public List<EventDispatchAction> getAdditionalEventDispatchActions() {
return additionalEventDispatchActions;
}
public AbstractServiceConfiguration<S> setAdditionalEventDispatchActions(List<EventDispatchAction> additionalEventDispatchActions) {
this.additionalEventDispatchActions = additionalEventDispatchActions;
return this;
} | public ObjectMapper getObjectMapper() {
return objectMapper;
}
public AbstractServiceConfiguration<S> setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public Clock getClock() {
return clock;
}
public AbstractServiceConfiguration<S> setClock(Clock clock) {
this.clock = clock;
return this;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public AbstractServiceConfiguration<S> setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
return this;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractServiceConfiguration.java | 1 |
请完成以下Java代码 | public class SSCC18AttributeValueGenerator extends AbstractAttributeValueGenerator
{
private final ISSCC18CodeBL sscc18CodeBL = Services.get(ISSCC18CodeBL.class);
private static final AtomicBoolean disabled = new AtomicBoolean(false);
public static IAutoCloseable temporaryDisableItIf(final boolean condition)
{
return condition ? temporaryDisableIt() : IAutoCloseable.NOP;
}
public static IAutoCloseable temporaryDisableIt()
{
final boolean disabledOld = disabled.getAndSet(true);
return () -> disabled.set(disabledOld);
}
@Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40;
}
@Override
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute) | {
return !disabled.get();
}
@Override
public String generateStringValue(
final Properties ctx_IGNORED,
@NonNull final IAttributeSet attributeSet,
final I_M_Attribute attribute_IGNORED)
{
final I_M_HU hu = Services.get(IHUAttributesBL.class).getM_HU(attributeSet);
// Just don't use the M_HU_ID as serial number. It introduced FUD as multiple packs can have the same HU and each pack needs an individual SSCC.
final SSCC18 sscc18 = sscc18CodeBL.generate(OrgId.ofRepoIdOrAny(hu.getAD_Org_ID()));
return sscc18.asString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attributes\sscc18\impl\SSCC18AttributeValueGenerator.java | 1 |
请完成以下Java代码 | public DmnDecisionTableResult evaluateDecisionTable(String decisionKey, DmnModelInstance dmnModelInstance, VariableContext variableContext) {
ensureNotNull("decisionKey", decisionKey);
List<DmnDecision> decisions = parseDecisions(dmnModelInstance);
for (DmnDecision decision : decisions) {
if (decisionKey.equals(decision.getKey())) {
return evaluateDecisionTable(decision, variableContext);
}
}
throw LOG.unableToFindDecisionWithKey(decisionKey);
}
public DmnDecisionResult evaluateDecision(DmnDecision decision, Map<String, Object> variables) {
ensureNotNull("decision", decision);
ensureNotNull("variables", variables);
return evaluateDecision(decision, Variables.fromMap(variables).asVariableContext());
}
public DmnDecisionResult evaluateDecision(DmnDecision decision, VariableContext variableContext) {
ensureNotNull("decision", decision);
ensureNotNull("variableContext", variableContext);
if (decision instanceof DmnDecisionImpl) {
DefaultDmnDecisionContext decisionContext = new DefaultDmnDecisionContext(dmnEngineConfiguration);
return decisionContext.evaluateDecision(decision, variableContext);
}
else {
throw LOG.decisionTypeNotSupported(decision);
}
}
public DmnDecisionResult evaluateDecision(String decisionKey, InputStream inputStream, Map<String, Object> variables) {
ensureNotNull("variables", variables);
return evaluateDecision(decisionKey, inputStream, Variables.fromMap(variables).asVariableContext());
}
public DmnDecisionResult evaluateDecision(String decisionKey, InputStream inputStream, VariableContext variableContext) {
ensureNotNull("decisionKey", decisionKey);
List<DmnDecision> decisions = parseDecisions(inputStream);
for (DmnDecision decision : decisions) {
if (decisionKey.equals(decision.getKey())) {
return evaluateDecision(decision, variableContext);
}
} | throw LOG.unableToFindDecisionWithKey(decisionKey);
}
public DmnDecisionResult evaluateDecision(String decisionKey, DmnModelInstance dmnModelInstance, Map<String, Object> variables) {
ensureNotNull("variables", variables);
return evaluateDecision(decisionKey, dmnModelInstance, Variables.fromMap(variables).asVariableContext());
}
public DmnDecisionResult evaluateDecision(String decisionKey, DmnModelInstance dmnModelInstance, VariableContext variableContext) {
ensureNotNull("decisionKey", decisionKey);
List<DmnDecision> decisions = parseDecisions(dmnModelInstance);
for (DmnDecision decision : decisions) {
if (decisionKey.equals(decision.getKey())) {
return evaluateDecision(decision, variableContext);
}
}
throw LOG.unableToFindDecisionWithKey(decisionKey);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnEngine.java | 1 |
请完成以下Java代码 | private boolean processAllocation()
{
if (m_alloc == null)
{
return true;
}
processPayment();
// Process It
if (m_alloc.processIt(IDocument.ACTION_Complete) && m_alloc.save())
{
m_alloc = null;
return true;
}
//
m_alloc = null;
return false;
} // processAllocation
/**
* Process Payment
*
* @return true if processed | */
private boolean processPayment()
{
if (m_payment == null)
{
return true;
}
// Process It
if (m_payment.processIt(IDocument.ACTION_Complete) && m_payment.save())
{
m_payment = null;
return true;
}
//
m_payment = null;
return false;
} // processPayment
} // InvoiceWriteOff | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\InvoiceWriteOff.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomWebSecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf(csrfSpec -> csrfSpec.disable())
.authorizeExchange(auth -> auth.pathMatchers(HttpMethod.GET,"/**")
.authenticated())
.httpBasic(httpBasicSpec -> httpBasicSpec.disable())
.addFilterAfter(authenticationWebFilter(), SecurityWebFiltersOrder.REACTOR_CONTEXT)
.build();
}
public AuthenticationWebFilter authenticationWebFilter() {
return new AuthenticationWebFilter(resolver());
}
public ReactiveAuthenticationManagerResolver<ServerWebExchange> resolver() {
return exchange -> {
if (exchange
.getRequest()
.getPath()
.subPath(0)
.value()
.startsWith("/employee")) {
return Mono.just(employeesAuthenticationManager());
}
return Mono.just(customersAuthenticationManager());
};
}
public ReactiveAuthenticationManager customersAuthenticationManager() {
return authentication -> customer(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication
.getPrincipal()
.toString())))
.map(b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), | authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
)
);
}
public ReactiveAuthenticationManager employeesAuthenticationManager() {
return authentication -> employee(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication
.getPrincipal()
.toString())))
.map(
b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
)
);
}
public Mono<String> customer(Authentication authentication) {
return Mono.justOrEmpty(authentication
.getPrincipal()
.toString()
.startsWith("customer") ? authentication
.getPrincipal()
.toString() : null);
}
public Mono<String> employee(Authentication authentication) {
return Mono.justOrEmpty(authentication
.getPrincipal()
.toString()
.startsWith("employee") ? authentication
.getPrincipal()
.toString() : null);
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-security\src\main\java\com\baeldung\reactive\authresolver\CustomWebSecurityConfig.java | 2 |
请完成以下Java代码 | public VariableInstanceQuery variableNameLike(String variableNameLike) {
wrappedVariableInstanceQuery.variableNameLike(variableNameLike);
return this;
}
@Override
public VariableInstanceQuery excludeTaskVariables() {
wrappedVariableInstanceQuery.excludeTaskVariables();
return this;
}
@Override
public VariableInstanceQuery excludeLocalVariables() {
wrappedVariableInstanceQuery.excludeLocalVariables();
return this;
}
@Override
public VariableInstanceQuery excludeVariableInitialization() {
wrappedVariableInstanceQuery.excludeVariableInitialization();
return this;
}
@Override
public VariableInstanceQuery variableValueEquals(String variableName, Object variableValue) {
wrappedVariableInstanceQuery.variableValueEquals(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) {
wrappedVariableInstanceQuery.variableValueNotEquals(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueLike(String variableName, String variableValue) {
wrappedVariableInstanceQuery.variableValueLike(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) {
wrappedVariableInstanceQuery.variableValueLikeIgnoreCase(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery orderByVariableName() {
wrappedVariableInstanceQuery.orderByVariableName();
return this;
} | @Override
public VariableInstanceQuery asc() {
wrappedVariableInstanceQuery.asc();
return this;
}
@Override
public VariableInstanceQuery desc() {
wrappedVariableInstanceQuery.desc();
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property) {
wrappedVariableInstanceQuery.orderBy(property);
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return wrappedVariableInstanceQuery.count();
}
@Override
public VariableInstance singleResult() {
return wrappedVariableInstanceQuery.singleResult();
}
@Override
public List<VariableInstance> list() {
return wrappedVariableInstanceQuery.list();
}
@Override
public List<VariableInstance> listPage(int firstResult, int maxResults) {
return wrappedVariableInstanceQuery.listPage(firstResult, maxResults);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void onGetAttributesResponse(GetAttributeResponseMsg getAttributesResponse) {
}
@Override
public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg attributeUpdateNotification) {
log.trace("[{}] Received attributes update notification to device", sessionId);
try {
snmpTransportContext.getSnmpTransportService().onAttributeUpdate(this, attributeUpdateNotification);
} catch (Exception e) {
snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.SHARED_ATTRIBUTES_SETTING.getLabel(), e);
}
}
@Override
public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) {
log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage());
if (sessionCloseNotification.getMessage().equals(DefaultTransportService.SESSION_EXPIRED_MESSAGE)) {
if (sessionTimeoutHandler != null) {
sessionTimeoutHandler.run();
} | }
}
@Override
public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg toDeviceRequest) {
log.trace("[{}] Received RPC command to device", sessionId);
try {
snmpTransportContext.getSnmpTransportService().onToDeviceRpcRequest(this, toDeviceRequest);
snmpTransportContext.getTransportService().process(getSessionInfo(), toDeviceRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY);
} catch (Exception e) {
snmpTransportContext.getTransportService().errorEvent(getTenantId(), getDeviceId(), SnmpCommunicationSpec.TO_DEVICE_RPC_REQUEST.getLabel(), e);
}
}
@Override
public void onToServerRpcResponse(ToServerRpcResponseMsg toServerResponse) {
}
} | repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\session\DeviceSessionContext.java | 1 |
请完成以下Java代码 | public class PrintStreamToStringUtil {
public static String usingByteArrayOutputStreamClass(String input) throws IOException {
if (input == null) {
return null;
}
String output;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
output = outputStream.toString();
}
return output;
}
public static String usingApacheCommonsIO(String input) {
if (input == null) {
return null;
}
org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
try (PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
}
return new String(outputStream.toByteArray());
}
public static String usingCustomOutputStream(String input) throws IOException {
if (input == null) {
return null;
} | String output;
try (CustomOutputStream outputStream = new CustomOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
output = outputStream.toString();
}
return output;
}
private static class CustomOutputStream extends OutputStream {
private StringBuilder stringBuilder = new StringBuilder();
@Override
public void write(int b) throws IOException {
this.stringBuilder.append((char) b);
}
@Override
public String toString() {
return this.stringBuilder.toString();
}
}
} | repos\tutorials-master\core-java-modules\core-java-io-conversions-2\src\main\java\com\baeldung\printstreamtostring\PrintStreamToStringUtil.java | 1 |
请完成以下Java代码 | public void setC_BankStatement_ID (final int C_BankStatement_ID)
{
if (C_BankStatement_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatement_ID, C_BankStatement_ID);
}
@Override
public int getC_BankStatement_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_ID);
}
@Override
public void setDateDoc (final @Nullable java.sql.Timestamp DateDoc)
{
set_ValueNoCheck (COLUMNNAME_DateDoc, DateDoc);
}
@Override
public java.sql.Timestamp getDateDoc()
{
return get_ValueAsTimestamp(COLUMNNAME_DateDoc);
}
@Override
public de.metas.payment.esr.model.I_ESR_Import getESR_Import()
{
return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class);
}
@Override | public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import)
{
set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import);
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_x_esr_import_in_c_bankstatement_v.java | 1 |
请完成以下Java代码 | public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Date getTime() {
return getCreateTime();
}
public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue); | }
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public static int count(String keyword, String srcText)
{
int count = 0;
int leng = srcText.length();
int j = 0;
for (int i = 0; i < leng; i++)
{
if (srcText.charAt(i) == keyword.charAt(j))
{
j++;
if (j == keyword.length())
{
count++;
j = 0;
}
}
else
{
i = i - j;// should rollback when not match
j = 0;
}
}
return count;
}
/**
* 简单好用的写String方式
*
* @param s
* @param out
* @throws IOException
*/
public static void writeString(String s, DataOutputStream out) throws IOException
{
out.writeInt(s.length());
for (char c : s.toCharArray())
{
out.writeChar(c);
}
}
/**
* 判断字符串是否为空(null和空格)
*
* @param cs
* @return
*/
public static boolean isBlank(CharSequence cs)
{
int strLen;
if (cs == null || (strLen = cs.length()) == 0)
{
return true;
}
for (int i = 0; i < strLen; i++)
{
if (!Character.isWhitespace(cs.charAt(i)))
{
return false;
}
}
return true;
}
public static String join(String delimiter, Collection<String> stringCollection)
{
StringBuilder sb = new StringBuilder(stringCollection.size() * (16 + delimiter.length()));
for (String str : stringCollection)
{
sb.append(str).append(delimiter);
} | return sb.toString();
}
public static String combine(String... termArray)
{
StringBuilder sbSentence = new StringBuilder();
for (String word : termArray)
{
sbSentence.append(word);
}
return sbSentence.toString();
}
public static String join(Iterable<? extends CharSequence> s, String delimiter)
{
Iterator<? extends CharSequence> iter = s.iterator();
if (!iter.hasNext()) return "";
StringBuilder buffer = new StringBuilder(iter.next());
while (iter.hasNext()) buffer.append(delimiter).append(iter.next());
return buffer.toString();
}
public static String combine(Sentence sentence)
{
StringBuilder sb = new StringBuilder(sentence.wordList.size() * 3);
for (IWord word : sentence.wordList)
{
sb.append(word.getValue());
}
return sb.toString();
}
public static String combine(List<Word> wordList)
{
StringBuilder sb = new StringBuilder(wordList.size() * 3);
for (IWord word : wordList)
{
sb.append(word.getValue());
}
return sb.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\TextUtility.java | 1 |
请完成以下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 getContent() { | return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
} | repos\tutorials-master\patterns-modules\vertical-slice-architecture\src\main\java\com\baeldung\hexagonal\persistence\entity\Article.java | 1 |
请完成以下Java代码 | private void logAfter(Log log, String prefix, Object result, Stopwatch stopwatch) {
// 判断是否是方法之前输出日志,不是就输出参数日志
if (!LogTypeEnum.PARAMETER.equals(log.value())) {
logger.info("【返回参数 {} 】:{} ,耗时:{} 毫秒", prefix, JSON.toJSONString(result), stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
}
/**
* 获取日志前缀对象
*
* @param log 日志注解对象
* @param method 注解日志的方法对象
* @return
*/
private String getPrefix(Log log, Method method) {
return prefixMap.computeIfAbsent(method.getDeclaringClass().getName() + "." + method.getName(), s -> {
// 日志格式:流水号 + 注解的日志前缀 + 请求地址 + 方法的全类名
StringBuilder sb = new StringBuilder();
sb.append(log.prefix());
sb.append(" ");
sb.append("/");
if (Objects.nonNull(RequestContextHolder.getRequestAttributes())) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
sb.append(request.getRequestURI());
}
sb.append(" ");
sb.append(":");
sb.append(method.getDeclaringClass().getName());
sb.append(".");
sb.append(method.getName());
sb.append("() ");
return sb.toString().replace("///", "/").replace("//", "/");
}); | }
public static Method getSpecificmethod(ProceedingJoinPoint pjp) {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
Method method = methodSignature.getMethod();
// The method may be on an interface, but we need attributes from the
// target class. If the target class is null, the method will be
// unchanged.
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
if (targetClass == null && pjp.getTarget() != null) {
targetClass = pjp.getTarget().getClass();
}
Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
// If we are dealing with method with generic parameters, find the
// original method.
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
return specificMethod;
}
/**
* 获取参数上的LogIgnore注解
*
* @param parameterAnnotation
* @return
*/
private boolean isLogIgnore(Annotation[] parameterAnnotation) {
for (Annotation annotation : parameterAnnotation) {
// 检查参数是否需要脱敏
if (annotation instanceof LogIgnore) {
return true;
}
}
return false;
}
} | repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\aspect\LogAspect.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setNotifyTimes(Integer notifyTimes) {
this.notifyTimes = notifyTimes;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/** 限制通知次数 **/
public Integer getLimitNotifyTimes() {
return limitNotifyTimes;
}
/** 限制通知次数 **/
public void setLimitNotifyTimes(Integer limitNotifyTimes) {
this.limitNotifyTimes = limitNotifyTimes;
}
/** 通知URL **/
public String getUrl() {
return url;
}
/** 通知URL **/
public void setUrl(String url) {
this.url = url == null ? null : url.trim(); | }
/** 商户编号 **/
public String getMerchantNo() {
return merchantNo;
}
/** 商户编号 **/
public void setMerchantNo(String merchantNo) {
this.merchantNo = merchantNo == null ? null : merchantNo.trim();
}
/** 商户订单号 **/
public String getMerchantOrderNo() {
return merchantOrderNo;
}
/** 商户订单号 **/
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim();
}
public String getNotifyType() {
return notifyType;
}
public void setNotifyType(String notifyType) {
this.notifyType = notifyType;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpNotifyRecord.java | 2 |
请完成以下Java代码 | public UIComponent getUIComponent(
final @NonNull WFProcess wfProcess,
final @NonNull WFActivity wfActivity,
final @NonNull JsonOpts jsonOpts)
{
return UserConfirmationSupportUtil.createUIComponent(
UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity)
.question(getQuestion(wfProcess, jsonOpts.getAdLanguage()))
.build());
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completePickingWFActivity)
{
final PickingJob pickingJob = getPickingJob(wfProcess);
return computeActivityState(pickingJob);
}
public static WFActivityStatus computeActivityState(final PickingJob pickingJob)
{
return pickingJob.getDocStatus().isCompleted() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED;
}
@Override
public WFProcess userConfirmed(final UserConfirmationRequest request) | {
request.getWfActivity().getWfActivityType().assertExpected(HANDLED_ACTIVITY_TYPE);
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJobRestService::complete
);
}
private String getQuestion(@NonNull final WFProcess wfProcess, @NonNull final String language)
{
final PickingJob pickingJob = wfProcess.getDocumentAs(PickingJob.class);
if (pickingJob.getProgress().isDone())
{
return msgBL.getMsg(language, ARE_YOU_SURE);
}
final PickingJobOptions options = pickingJobRestService.getPickingJobOptions(pickingJob.getCustomerId());
if (!options.isAllowCompletingPartialPickingJob())
{
return msgBL.getMsg(language, ARE_YOU_SURE);
}
return msgBL.getMsg(language, NOT_ALL_LINES_ARE_COMPLETED_WARNING);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\CompletePickingWFActivityHandler.java | 1 |
请完成以下Java代码 | private List<Method> findMatchingAnnotatedMethods(String parameterName) {
List<Method> result = new ArrayList<Method>();
Method[] methods = this.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
Annotation[] methodAnnotations = method.getAnnotations();
for (int j = 0; j < methodAnnotations.length; j++) {
Annotation annotation = methodAnnotations[j];
if (annotation instanceof CamundaQueryParam) {
CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation;
if (parameterAnnotation.value().equals(parameterName)) {
result.add(method);
}
}
}
}
return result; | }
private Class<? extends JacksonAwareStringToTypeConverter<?>> findAnnotatedTypeConverter(Method method) {
Annotation[] methodAnnotations = method.getAnnotations();
for (int j = 0; j < methodAnnotations.length; j++) {
Annotation annotation = methodAnnotations[j];
if (annotation instanceof CamundaQueryParam) {
CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation;
return parameterAnnotation.converter();
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AbstractSearchQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EmailVo sendEmail(String email, String key) {
EmailVo emailVo;
String content;
String redisKey = key + email;
// 如果不存在有效的验证码,就创建一个新的
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate("email.ftl");
String oldCode = redisUtils.get(redisKey, String.class);
if(oldCode == null){
String code = RandomUtil.randomNumbers (6);
// 存入缓存
if(!redisUtils.set(redisKey, code, expiration)){
throw new BadRequestException("服务异常,请联系网站负责人");
}
content = template.render(Dict.create().set("code",code));
// 存在就再次发送原来的验证码 | } else {
content = template.render(Dict.create().set("code",oldCode));
}
emailVo = new EmailVo(Collections.singletonList(email),"ELADMIN后台管理系统",content);
return emailVo;
}
@Override
public void validated(String key, String code) {
String value = redisUtils.get(key, String.class);
if(!code.equals(value)){
throw new BadRequestException("无效验证码");
} else {
redisUtils.del(key);
}
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\VerifyServiceImpl.java | 2 |
请完成以下Java代码 | public col setCharOff(int char_off)
{
addAttribute("charoff",Integer.toString(char_off));
return(this);
}
/**
Sets the charoff="" attribute.
@param char_off When present this attribute specifies the offset
of the first occurrence of the alignment character on each line.
*/
public col setCharOff(String char_off)
{
addAttribute("charoff",char_off);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public col addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table | @param element Adds an Element to the element.
*/
public col addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public col addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public col addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public col removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\col.java | 1 |
请完成以下Java代码 | private class ReceiptScheduleEffectiveDocumentLocation implements IDocumentLocationAdapter
{
private final I_M_ReceiptSchedule delegate;
private ReceiptScheduleEffectiveDocumentLocation(@NonNull final I_M_ReceiptSchedule delegate)
{
this.delegate = delegate;
}
@Override
public int getC_BPartner_ID()
{
return BPartnerId.toRepoId(getBPartnerEffectiveId(delegate));
}
@Override
public void setC_BPartner_ID(final int C_BPartner_ID)
{
}
@Override
public int getC_BPartner_Location_ID()
{
return getC_BPartner_Location_Effective_ID(delegate);
}
@Override
@Deprecated
public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID)
{
}
@Override
public int getC_BPartner_Location_Value_ID()
{
return -1;
}
@Override
public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID)
{
}
@Override
public int getAD_User_ID()
{
return BPartnerContactId.toRepoId(getBPartnerContactID(delegate)); | }
@Override
public void setAD_User_ID(final int AD_User_ID)
{
}
@Override
public String getBPartnerAddress()
{
return delegate.getBPartnerAddress_Override();
}
@Override
public void setBPartnerAddress(final String address)
{
delegate.setBPartnerAddress_Override(address);
}
}
@Override
public int updateDatePromisedOverrideAndPOReference(@NonNull final PInstanceId pinstanceId, @Nullable final LocalDate datePromisedOverride, @Nullable final String poReference)
{
if (datePromisedOverride == null && Check.isBlank(poReference))
{
throw new AdempiereException(MSG_DATEPROMISEDOVERRIDE_POREFERENCE_VALIDATION_ERROR)
.markAsUserValidationError();
}
final ICompositeQueryUpdater<I_M_ReceiptSchedule> updater = queryBL
.createCompositeQueryUpdater(I_M_ReceiptSchedule.class);
if (datePromisedOverride != null)
{
updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_DatePromised_Override, datePromisedOverride);
}
if (!Check.isBlank(poReference))
{
updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_POReference, poReference);
}
return queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.setOnlySelection(pinstanceId)
.create()
.update(updater);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleBL.java | 1 |
请完成以下Java代码 | public class Item {
private int id;
private String name;
private List<Detail> details;
public Item(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
} | repos\tutorials-master\spring-web-modules\spring-thymeleaf-2\src\main\java\com\baeldung\thymeleaf\pathvariables\Item.java | 1 |
请完成以下Java代码 | public byte[] getRouterlabel() {
return routerlabel;
}
/**
* Sets the value of the routerlabel property.
*
* @param value
* allowed object is
* byte[]
*/
public void setRouterlabel(byte[] value) {
this.routerlabel = value;
}
/**
* Gets the value of the routerlabelZebra property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getRouterlabelZebra() {
return routerlabelZebra;
} | /**
* Sets the value of the routerlabelZebra property.
*
* @param value
* allowed object is
* byte[]
*/
public void setRouterlabelZebra(byte[] value) {
this.routerlabelZebra = value;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Label.java | 1 |
请完成以下Java代码 | public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine)
{
set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine);
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM)
{
set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM);
}
@Override
public BigDecimal getQtyInvoicedInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderDetail.java | 1 |
请完成以下Java代码 | public void setC_Commission_Share(final de.metas.contracts.commission.model.I_C_Commission_Share C_Commission_Share)
{
set_ValueFromPO(COLUMNNAME_C_Commission_Share_ID, de.metas.contracts.commission.model.I_C_Commission_Share.class, C_Commission_Share);
}
@Override
public void setC_Commission_Share_ID (final int C_Commission_Share_ID)
{
if (C_Commission_Share_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Commission_Share_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Commission_Share_ID, C_Commission_Share_ID);
}
@Override
public int getC_Commission_Share_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Commission_Share_ID);
}
@Override
public void setC_Invoice_Candidate_Commission_ID (final int C_Invoice_Candidate_Commission_ID)
{
if (C_Invoice_Candidate_Commission_ID < 1)
set_Value (COLUMNNAME_C_Invoice_Candidate_Commission_ID, null);
else
set_Value (COLUMNNAME_C_Invoice_Candidate_Commission_ID, C_Invoice_Candidate_Commission_ID);
}
@Override
public int getC_Invoice_Candidate_Commission_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_Commission_ID);
}
/**
* Commission_Fact_State AD_Reference_ID=541042
* Reference name: C_Commission_Fact_State
*/
public static final int COMMISSION_FACT_STATE_AD_Reference_ID=541042;
/** FORECASTED = FORECASTED */
public static final String COMMISSION_FACT_STATE_FORECASTED = "FORECASTED";
/** INVOICEABLE = INVOICEABLE */
public static final String COMMISSION_FACT_STATE_INVOICEABLE = "INVOICEABLE";
/** INVOICED = INVOICED */
public static final String COMMISSION_FACT_STATE_INVOICED = "INVOICED";
/** SETTLED = SETTLED */
public static final String COMMISSION_FACT_STATE_SETTLED = "SETTLED";
/** TO_SETTLE = TO_SETTLE */
public static final String COMMISSION_FACT_STATE_TO_SETTLE = "TO_SETTLE";
@Override
public void setCommission_Fact_State (final java.lang.String Commission_Fact_State)
{
set_ValueNoCheck (COLUMNNAME_Commission_Fact_State, Commission_Fact_State);
}
@Override
public java.lang.String getCommission_Fact_State() | {
return get_ValueAsString(COLUMNNAME_Commission_Fact_State);
}
@Override
public void setCommissionFactTimestamp (final java.lang.String CommissionFactTimestamp)
{
set_ValueNoCheck (COLUMNNAME_CommissionFactTimestamp, CommissionFactTimestamp);
}
@Override
public java.lang.String getCommissionFactTimestamp()
{
return get_ValueAsString(COLUMNNAME_CommissionFactTimestamp);
}
@Override
public void setCommissionPoints (final BigDecimal CommissionPoints)
{
set_ValueNoCheck (COLUMNNAME_CommissionPoints, CommissionPoints);
}
@Override
public BigDecimal getCommissionPoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CommissionPoints);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Fact.java | 1 |
请完成以下Java代码 | public GridField getField()
{
return m_mField;
}
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("VAccount[")
.append(m_title)
.append(", value=").append(m_value)
.append("]");
return sb.toString();
} // toString
@Override
public void focusGained(FocusEvent e)
{
}
/**
* Mostly copied from {@link VLookup}, can't claim I really understand it.
*/
@Override
public void focusLost(FocusEvent e)
{
if (e.isTemporary())
{
return;
}
if (m_button == null // guarding against NPE (i.e. component was disposed in meantime)
|| !m_button.isEnabled()) // set by actionButton
{
return;
}
if (m_mAccount == null)
{
return;
}
// metas: begin: 02029: nerviges verhalten wenn man eine Maskeneingabe abbrechen will (2011082210000084)
// Check if toolbar Ignore button was pressed
if (e.getOppositeComponent() instanceof AbstractButton)
{
final AbstractButton b = (AbstractButton)e.getOppositeComponent();
if (APanel.CMD_Ignore.equals(b.getActionCommand()))
{
return;
}
}
// metas: end | if (m_text == null)
return; // arhipac: teo_sarca: already disposed
// Test Case: Open a window, click on account field that is mandatory but not filled, close the window and you will get an NPE
// TODO: integrate to trunk
// New text
String newText = m_text.getText();
if (newText == null)
newText = "";
// Actual text
String actualText = m_mAccount.getDisplay(m_value);
if (actualText == null)
actualText = "";
// If text was modified, try to resolve the valid combination
if (!newText.equals(actualText))
{
cmd_text();
}
}
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VAccount | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAccount.java | 1 |
请完成以下Java代码 | public Iterator<?> retrieveAllModelsWithMissingCandidates(final QueryLimit limit_IGNORED)
{
return Collections.emptyIterator();
}
@Override
public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request)
{
throw new IllegalStateException("Not supported");
}
@Override
public void invalidateCandidatesFor(final Object model)
{
final I_M_Inventory inventory = InterfaceWrapperHelper.create(model, I_M_Inventory.class);
invalidateCandidatesForInventory(inventory);
}
private void invalidateCandidatesForInventory(final I_M_Inventory inventory)
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
//
// Retrieve inventory line handlers
final Properties ctx = InterfaceWrapperHelper.getCtx(inventory);
final List<IInvoiceCandidateHandler> inventoryLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, I_M_InventoryLine.Table_Name);
for (final IInvoiceCandidateHandler handler : inventoryLineHandlers)
{
for (final I_M_InventoryLine line : inventoryDAO.retrieveLinesForInventoryId(inventoryId))
{
handler.invalidateCandidatesFor(line);
}
}
} | @Override
public String getSourceTable()
{
return I_M_Inventory.Table_Name;
}
@Override
public boolean isUserInChargeUserEditable()
{
return false;
}
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\M_Inventory_Handler.java | 1 |
请完成以下Java代码 | public Collection<String> getProduces() {
return Collections.unmodifiableCollection(this.produces);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
WebOperationRequestPredicate other = (WebOperationRequestPredicate) obj;
boolean result = true;
result = result && this.consumes.equals(other.consumes);
result = result && this.httpMethod == other.httpMethod;
result = result && this.canonicalPath.equals(other.canonicalPath);
result = result && this.produces.equals(other.produces);
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1; | result = prime * result + this.consumes.hashCode();
result = prime * result + this.httpMethod.hashCode();
result = prime * result + this.canonicalPath.hashCode();
result = prime * result + this.produces.hashCode();
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder(this.httpMethod + " to path '" + this.path + "'");
if (!CollectionUtils.isEmpty(this.consumes)) {
result.append(" consumes: ").append(StringUtils.collectionToCommaDelimitedString(this.consumes));
}
if (!CollectionUtils.isEmpty(this.produces)) {
result.append(" produces: ").append(StringUtils.collectionToCommaDelimitedString(this.produces));
}
return result.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebOperationRequestPredicate.java | 1 |
请完成以下Java代码 | public class Charges4 {
@XmlElement(name = "TtlChrgsAndTaxAmt")
protected ActiveOrHistoricCurrencyAndAmount ttlChrgsAndTaxAmt;
@XmlElement(name = "Rcrd")
protected List<ChargesRecord2> rcrd;
/**
* Gets the value of the ttlChrgsAndTaxAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getTtlChrgsAndTaxAmt() {
return ttlChrgsAndTaxAmt;
}
/**
* Sets the value of the ttlChrgsAndTaxAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlChrgsAndTaxAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlChrgsAndTaxAmt = value;
}
/**
* Gets the value of the rcrd 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 rcrd property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRcrd().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ChargesRecord2 }
*
*
*/
public List<ChargesRecord2> getRcrd() {
if (rcrd == null) {
rcrd = new ArrayList<ChargesRecord2>();
}
return this.rcrd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\Charges4.java | 1 |
请完成以下Java代码 | public static final TargetPOKeyPropertiesPartDescriptor createIfApplies(Method method, Cached annotation)
{
final String[] keyProperties = annotation.keyProperties();
if (keyProperties == null || keyProperties.length <= 0)
{
return null;
}
return new TargetPOKeyPropertiesPartDescriptor(ImmutableSet.copyOf(keyProperties));
}
private final Set<String> keyProperties;
private TargetPOKeyPropertiesPartDescriptor(final Set<String> keyProperties)
{
super();
Check.assumeNotEmpty(keyProperties, "keyProperties not empty");
this.keyProperties = keyProperties;
}
@Override
public void extractKeyParts(CacheKeyBuilder keyBuilder, Object targetObject, Object[] params)
{
//
// include specified property values into the key
for (final String keyProp : keyProperties)
{
if (targetObject instanceof PO)
{
final PO po = (PO)targetObject;
if (po.get_ColumnIndex(keyProp) < 0) | {
final String msg = "Invalid keyProperty '" + keyProp
+ "' for cached method " + targetObject.getClass() // + "." + constructorOrMethod.getName()
+ ". Target PO has no such column; PO=" + po;
throw new RuntimeException(msg);
}
final Object keyValue = po.get_Value(keyProp);
keyBuilder.add(keyValue);
}
else
{
final StringBuilder getMethodName = new StringBuilder("get");
getMethodName.append(keyProp.substring(0, 1).toUpperCase());
getMethodName.append(keyProp.substring(1));
try
{
final Method method = targetObject.getClass().getMethod(getMethodName.toString());
final Object keyValue = method.invoke(targetObject);
keyBuilder.add(keyValue);
}
catch (Exception e)
{
final String msg = "Invalid keyProperty '" + keyProp
+ "' for cached method " + targetObject.getClass().getName() // + "." + constructorOrMethod.getName()
+ ". Can't access getter method get" + keyProp + ". Exception " + e + "; message: " + e.getMessage();
throw new RuntimeException(msg, e);
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\TargetPOKeyPropertiesPartDescriptor.java | 1 |
请完成以下Java代码 | public class IntegerWrapperLookup extends Lookup {
private Integer[] elements;
private final int pivot = 2;
@Override
@Setup
public void prepare() {
int common = 1;
elements = new Integer[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@Override
@TearDown
public void clean() {
elements = null;
}
@Override
@Benchmark
@BenchmarkMode(Mode.AverageTime)
public int findPosition() { | int index = 0;
Integer pivotWrapper = pivot;
while (!pivotWrapper.equals(elements[index])) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return IntegerWrapperLookup.class.getSimpleName();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\IntegerWrapperLookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result list(@RequestParam Map<String, Object> params) {
if (ObjectUtils.isEmpty(params.get("page")) || ObjectUtils.isEmpty(params.get("limit"))) {
return ResultGenerator.genFailResult("参数异常!");
}
PageQueryUtil pageUtil = new PageQueryUtil(params);
return ResultGenerator.genSuccessResult(categoryService.getCategoryPage(pageUtil));
}
/**
* 详情
*/
@RequestMapping(value = "/categories/info/{id}", method = RequestMethod.GET)
@ResponseBody
public Result info(@PathVariable("id") Long id) {
NewsCategory newsCategory = categoryService.queryById(id);
return ResultGenerator.genSuccessResult(newsCategory);
}
/**
* 分类添加
*/
@RequestMapping(value = "/categories/save", method = RequestMethod.POST)
@ResponseBody
public Result save(@RequestParam("categoryName") String categoryName) {
if (!StringUtils.hasText(categoryName)) {
return ResultGenerator.genFailResult("参数异常!");
}
if (categoryService.saveCategory(categoryName)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("分类名称重复");
}
}
/** | * 分类修改
*/
@RequestMapping(value = "/categories/update", method = RequestMethod.POST)
@ResponseBody
public Result update(@RequestParam("categoryId") Long categoryId,
@RequestParam("categoryName") String categoryName) {
if (!StringUtils.hasText(categoryName)) {
return ResultGenerator.genFailResult("参数异常!");
}
if (categoryService.updateCategory(categoryId, categoryName)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("分类名称重复");
}
}
/**
* 分类删除
*/
@RequestMapping(value = "/categories/delete", method = RequestMethod.POST)
@ResponseBody
public Result delete(@RequestBody Integer[] ids) {
if (ids.length < 1) {
return ResultGenerator.genFailResult("参数异常!");
}
if (categoryService.deleteBatchByIds(ids)) {
return ResultGenerator.genSuccessResult();
} else {
return ResultGenerator.genFailResult("删除失败");
}
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\controller\admin\CategoryController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
return Objects.hash(authenticityVerification, fulfillmentProgram);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class Program {\n");
sb.append(" authenticityVerification: ").append(toIndentedString(authenticityVerification)).append("\n");
sb.append(" fulfillmentProgram: ").append(toIndentedString(fulfillmentProgram)).append("\n");
sb.append("}");
return sb.toString();
} | /**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\Program.java | 2 |
请完成以下Java代码 | public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
public boolean isNotStartableInTasklist() {
return isNotStartableInTasklist;
}
public boolean isStartablePermissionCheck() {
return startablePermissionCheck;
}
public void setProcessDefinitionCreatePermissionChecks(List<PermissionCheck> processDefinitionCreatePermissionChecks) {
this.processDefinitionCreatePermissionChecks = processDefinitionCreatePermissionChecks;
}
public List<PermissionCheck> getProcessDefinitionCreatePermissionChecks() {
return processDefinitionCreatePermissionChecks;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
public void addProcessDefinitionCreatePermissionCheck(CompositePermissionCheck processDefinitionCreatePermissionCheck) { | processDefinitionCreatePermissionChecks.addAll(processDefinitionCreatePermissionCheck.getAllPermissionChecks());
}
public List<String> getCandidateGroups() {
if (cachedCandidateGroups != null) {
return cachedCandidateGroups;
}
if(authorizationUserId != null) {
List<Group> groups = Context.getCommandContext()
.getReadOnlyIdentityProvider()
.createGroupQuery()
.groupMember(authorizationUserId)
.list();
cachedCandidateGroups = groups.stream().map(Group::getId).collect(Collectors.toList());
}
return cachedCandidateGroups;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | final class DataRedisHealth {
private DataRedisHealth() {
}
static Health.Builder up(Health.Builder builder, Properties info) {
builder.withDetail("version", info.getProperty("redis_version", "unknown"));
return builder.up();
}
static Health.Builder fromClusterInfo(Health.Builder builder, ClusterInfo clusterInfo) {
Long clusterSize = clusterInfo.getClusterSize();
if (clusterSize != null) {
builder.withDetail("cluster_size", clusterSize);
}
Long slotsOk = clusterInfo.getSlotsOk(); | if (slotsOk != null) {
builder.withDetail("slots_up", slotsOk);
}
Long slotsFail = clusterInfo.getSlotsFail();
if (slotsFail != null) {
builder.withDetail("slots_fail", slotsFail);
}
if ("fail".equalsIgnoreCase(clusterInfo.getState())) {
return builder.down();
}
else {
return builder.up();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\health\DataRedisHealth.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommonService_Service
extends Service
{
private final static URL COMMONSERVICE_WSDL_LOCATION;
private final static WebServiceException COMMONSERVICE_EXCEPTION;
private final static QName COMMONSERVICE_QNAME = new QName("http://model.webservice.xncoding.com/", "CommonService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://localhost:8092/services/CommonService?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
COMMONSERVICE_WSDL_LOCATION = url;
COMMONSERVICE_EXCEPTION = e;
}
public CommonService_Service() {
super(__getWsdlLocation(), COMMONSERVICE_QNAME);
}
public CommonService_Service(WebServiceFeature... features) {
super(__getWsdlLocation(), COMMONSERVICE_QNAME, features);
}
public CommonService_Service(URL wsdlLocation) {
super(wsdlLocation, COMMONSERVICE_QNAME);
}
public CommonService_Service(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, COMMONSERVICE_QNAME, features);
}
public CommonService_Service(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public CommonService_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { | super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns CommonService
*/
@WebEndpoint(name = "CommonServiceImplPort")
public CommonService getCommonServiceImplPort() {
return super.getPort(new QName("http://model.webservice.xncoding.com/", "CommonServiceImplPort"), CommonService.class);
}
/**
*
* @param features
* A list of {@link WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns CommonService
*/
@WebEndpoint(name = "CommonServiceImplPort")
public CommonService getCommonServiceImplPort(WebServiceFeature... features) {
return super.getPort(new QName("http://model.webservice.xncoding.com/", "CommonServiceImplPort"), CommonService.class, features);
}
private static URL __getWsdlLocation() {
if (COMMONSERVICE_EXCEPTION!= null) {
throw COMMONSERVICE_EXCEPTION;
}
return COMMONSERVICE_WSDL_LOCATION;
}
} | repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\CommonService_Service.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<UmsMenuNode> treeList() {
List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
List<UmsMenuNode> result = menuList.stream()
.filter(menu -> menu.getParentId().equals(0L))
.map(menu -> covertMenuNode(menu, menuList))
.collect(Collectors.toList());
return result;
}
@Override
public int updateHidden(Long id, Integer hidden) {
UmsMenu umsMenu = new UmsMenu();
umsMenu.setId(id);
umsMenu.setHidden(hidden);
return menuMapper.updateByPrimaryKeySelective(umsMenu); | }
/**
* 将UmsMenu转化为UmsMenuNode并设置children属性
*/
private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
UmsMenuNode node = new UmsMenuNode();
BeanUtils.copyProperties(menu, node);
List<UmsMenuNode> children = menuList.stream()
.filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
.map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
node.setChildren(children);
return node;
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsMenuServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UserRequest extends UserResponse {
protected boolean firstNameChanged;
protected boolean lastNameChanged;
protected boolean displayNameChanged;
protected boolean passwordChanged;
protected boolean emailChanged;
@Override
public void setEmail(String email) {
super.setEmail(email);
emailChanged = true;
}
@Override
public void setFirstName(String firstName) {
super.setFirstName(firstName);
firstNameChanged = true;
}
@Override
public void setLastName(String lastName) {
super.setLastName(lastName);
lastNameChanged = true;
}
@Override
public void setDisplayName(String displayName) {
super.setDisplayName(displayName);
displayNameChanged = true;
}
@Override
public void setPassword(String passWord) {
super.setPassword(passWord);
passwordChanged = true;
} | @JsonIgnore
public boolean isEmailChanged() {
return emailChanged;
}
@JsonIgnore
public boolean isFirstNameChanged() {
return firstNameChanged;
}
@JsonIgnore
public boolean isLastNameChanged() {
return lastNameChanged;
}
@JsonIgnore
public boolean isDisplayNameChanged() {
return displayNameChanged;
}
@JsonIgnore
public boolean isPasswordChanged() {
return passwordChanged;
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserRequest.java | 2 |
请完成以下Java代码 | public Builder setM_Product_ID(final int M_Product_ID)
{
this.M_Product_ID = M_Product_ID;
return this;
}
public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID;
return this;
}
public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID)
{
this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID;
return this;
}
public Builder setC_Flatrate_DataEntry_ID(int C_Flatrate_DataEntry_ID)
{
this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID;
return this;
}
public Builder setDate(final Date date)
{
this.date = date;
return this;
}
public Builder setQtyPromised(final BigDecimal qtyPromised, final BigDecimal qtyPromised_TU)
{
this.qtyPromised = qtyPromised;
this.qtyPromised_TU = qtyPromised_TU; | return this;
}
public Builder setQtyOrdered(final BigDecimal qtyOrdered, final BigDecimal qtyOrdered_TU)
{
this.qtyOrdered = qtyOrdered;
this.qtyOrdered_TU = qtyOrdered_TU;
return this;
}
public Builder setQtyDelivered(BigDecimal qtyDelivered)
{
this.qtyDelivered = qtyDelivered;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceChangeEvent.java | 1 |
请完成以下Java代码 | public String getExpressionString()
{
return expressionString;
}
@Override
public Set<CtxName> getParameters()
{
return ImmutableSet.of();
}
@Override
public String toString()
{
return toStringValue;
}
@Override
public String getFormatedExpressionString()
{
return expressionString;
}
@Override
public Boolean evaluate(final Evaluatee ctx, final boolean ignoreUnparsable)
{
return value;
}
@Override
public Boolean evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) | {
return value;
}
@Override
public LogicExpressionResult evaluateToResult(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
return value ? LogicExpressionResult.TRUE : LogicExpressionResult.FALSE;
}
@Override
public ILogicExpression evaluatePartial(final Evaluatee ctx)
{
return this;
}
@Override
public ILogicExpression negate() {return of(!value);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ConstantLogicExpression.java | 1 |
请完成以下Java代码 | public String toString() {
return "ManagementProperties [health=" + health + "]";
}
public static class Health {
private Camunda camunda = new Camunda();
/**
* @return the camunda
*/
public Camunda getCamunda() {
return camunda;
}
/**
* @param camunda the camunda to set
*/
public void setCamunda(Camunda camunda) {
this.camunda = camunda;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("camunda=" + camunda)
.toString();
}
public class Camunda {
private boolean enabled = true;
/**
* @return the enabled
*/
public boolean isEnabled() { | return enabled;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
.toString();
}
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\ManagementProperties.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public Date getTime() {
return time;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getGroupId() {
return groupId;
}
public String getTaskId() {
return taskId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getOperationType() {
return operationType;
}
public String getAssignerId() {
return assignerId;
}
public String getTenantId() {
return tenantId;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
} | public static HistoricIdentityLinkLogDto fromHistoricIdentityLink(HistoricIdentityLinkLog historicIdentityLink) {
HistoricIdentityLinkLogDto dto = new HistoricIdentityLinkLogDto();
fromHistoricIdentityLink(dto, historicIdentityLink);
return dto;
}
public static void fromHistoricIdentityLink(HistoricIdentityLinkLogDto dto,
HistoricIdentityLinkLog historicIdentityLink) {
dto.id = historicIdentityLink.getId();
dto.assignerId = historicIdentityLink.getAssignerId();
dto.groupId = historicIdentityLink.getGroupId();
dto.operationType = historicIdentityLink.getOperationType();
dto.taskId = historicIdentityLink.getTaskId();
dto.time = historicIdentityLink.getTime();
dto.type = historicIdentityLink.getType();
dto.processDefinitionId = historicIdentityLink.getProcessDefinitionId();
dto.processDefinitionKey = historicIdentityLink.getProcessDefinitionKey();
dto.userId = historicIdentityLink.getUserId();
dto.tenantId = historicIdentityLink.getTenantId();
dto.removalTime = historicIdentityLink.getRemovalTime();
dto.rootProcessInstanceId = historicIdentityLink.getRootProcessInstanceId();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogDto.java | 1 |
请完成以下Java代码 | public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() {
return DefaultGatewayObservationConvention.class;
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return LowCardinalityKeys.values();
}
@Override
public KeyName[] getHighCardinalityKeyNames() {
return HighCardinalityKeys.values();
}
};
@NonNullApi
enum LowCardinalityKeys implements KeyName {
/**
* Route ID.
*/
ROUTE_ID {
@Override
public String asString() {
return "spring.cloud.gateway.route.id";
}
},
/**
* HTTP Method.
*/
METHOD {
@Override
public String asString() {
return "http.method";
}
},
/**
* HTTP Status.
*/
STATUS {
@Override
public String asString() {
return "http.status_code";
} | },
/**
* HTTP URI taken from the Route.
*/
ROUTE_URI {
@Override
public String asString() {
return "spring.cloud.gateway.route.uri";
}
}
}
@NonNullApi
enum HighCardinalityKeys implements KeyName {
/**
* Full HTTP URI.
*/
URI {
@Override
public String asString() {
return "http.uri";
}
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\observation\GatewayDocumentedObservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Demo01Producer {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public SendResult syncSend(Integer id) {
// 创建 Demo01Message 消息
Demo01Message message = new Demo01Message();
message.setId(id);
// 同步发送消息
return rocketMQTemplate.syncSend(Demo01Message.TOPIC, message);
}
public void asyncSend(Integer id, SendCallback callback) {
// 创建 Demo01Message 消息 | Demo01Message message = new Demo01Message();
message.setId(id);
// 异步发送消息
rocketMQTemplate.asyncSend(Demo01Message.TOPIC, message, callback);
}
public void onewaySend(Integer id) {
// 创建 Demo01Message 消息
Demo01Message message = new Demo01Message();
message.setId(id);
// oneway 发送消息
rocketMQTemplate.sendOneWay(Demo01Message.TOPIC, message);
}
} | repos\SpringBoot-Labs-master\lab-31\lab-31-rocketmq-demo\src\main\java\cn\iocoder\springboot\lab31\rocketmqdemo\producer\Demo01Producer.java | 2 |
请完成以下Java代码 | UserRolePermissionsIncludesList getUserRolePermissionsIncluded()
{
Check.assumeNotNull(userRolePermissionsIncluded, "userRolePermissionsIncluded not null");
return userRolePermissionsIncluded;
}
public UserRolePermissionsBuilder setMenuInfo(final UserMenuInfo menuInfo)
{
this._menuInfo = menuInfo;
return this;
}
public UserMenuInfo getMenuInfo()
{
if (_menuInfo == null)
{
_menuInfo = findMenuInfo();
}
return _menuInfo;
}
private UserMenuInfo findMenuInfo() | {
final Role adRole = getRole();
final AdTreeId roleMenuTreeId = adRole.getMenuTreeId();
if (roleMenuTreeId != null)
{
return UserMenuInfo.of(roleMenuTreeId, adRole.getRootMenuId());
}
final I_AD_ClientInfo adClientInfo = getAD_ClientInfo();
final AdTreeId adClientMenuTreeId = AdTreeId.ofRepoIdOrNull(adClientInfo.getAD_Tree_Menu_ID());
if (adClientMenuTreeId != null)
{
return UserMenuInfo.of(adClientMenuTreeId, adRole.getRootMenuId());
}
// Fallback: when role has NO menu and there is no menu defined on AD_ClientInfo level - shall not happen
return UserMenuInfo.DEFAULT_MENU;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsBuilder.java | 1 |
请完成以下Java代码 | private void endOrCacheInflater(Inflater inflater) {
Deque<Inflater> inflaterCache = this.inflaterCache;
if (inflaterCache != null) {
synchronized (inflaterCache) {
if (this.inflaterCache == inflaterCache && inflaterCache.size() < INFLATER_CACHE_LIMIT) {
inflater.reset();
this.inflaterCache.add(inflater);
return;
}
}
}
inflater.end();
}
/**
* Called by the {@link Cleaner} to free resources.
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
releaseAll();
}
private void releaseAll() {
IOException exceptionChain = null;
exceptionChain = releaseInflators(exceptionChain);
exceptionChain = releaseInputStreams(exceptionChain);
exceptionChain = releaseZipContent(exceptionChain);
exceptionChain = releaseZipContentForManifest(exceptionChain);
if (exceptionChain != null) {
throw new UncheckedIOException(exceptionChain);
}
}
private IOException releaseInflators(IOException exceptionChain) {
Deque<Inflater> inflaterCache = this.inflaterCache;
if (inflaterCache != null) {
try {
synchronized (inflaterCache) {
inflaterCache.forEach(Inflater::end);
}
}
finally {
this.inflaterCache = null;
}
}
return exceptionChain;
}
private IOException releaseInputStreams(IOException exceptionChain) {
synchronized (this.inputStreams) {
for (InputStream inputStream : List.copyOf(this.inputStreams)) {
try { | inputStream.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
}
this.inputStreams.clear();
}
return exceptionChain;
}
private IOException releaseZipContent(IOException exceptionChain) {
ZipContent zipContent = this.zipContent;
if (zipContent != null) {
try {
zipContent.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
finally {
this.zipContent = null;
}
}
return exceptionChain;
}
private IOException releaseZipContentForManifest(IOException exceptionChain) {
ZipContent zipContentForManifest = this.zipContentForManifest;
if (zipContentForManifest != null) {
try {
zipContentForManifest.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
finally {
this.zipContentForManifest = null;
}
}
return exceptionChain;
}
private IOException addToExceptionChain(IOException exceptionChain, IOException ex) {
if (exceptionChain != null) {
exceptionChain.addSuppressed(ex);
return exceptionChain;
}
return ex;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\NestedJarFileResources.java | 1 |
请完成以下Java代码 | public CaseExecutionQuery caseInstanceVariableValueLessThanOrEqual(String name, Object value) {
addVariable(name, value, QueryOperator.LESS_THAN_OR_EQUAL, false);
return this;
}
public CaseExecutionQuery caseInstanceVariableValueLike(String name, String value) {
addVariable(name, value, QueryOperator.LIKE, false);
return this;
}
// order by ///////////////////////////////////////////
public CaseExecutionQuery orderByCaseExecutionId() {
orderBy(CaseExecutionQueryProperty.CASE_EXECUTION_ID);
return this;
}
public CaseExecutionQuery orderByCaseDefinitionKey() {
orderBy(new QueryOrderingProperty(QueryOrderingProperty.RELATION_CASE_DEFINITION,
CaseExecutionQueryProperty.CASE_DEFINITION_KEY));
return this;
}
public CaseExecutionQuery orderByCaseDefinitionId() {
orderBy(CaseExecutionQueryProperty.CASE_DEFINITION_ID);
return this;
}
public CaseExecutionQuery orderByTenantId() {
orderBy(CaseExecutionQueryProperty.TENANT_ID);
return this;
}
// results ////////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getCaseExecutionManager()
.findCaseExecutionCountByQueryCriteria(this);
}
public List<CaseExecution> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
List<CaseExecution> result = commandContext
.getCaseExecutionManager()
.findCaseExecutionsByQueryCriteria(this, page);
for (CaseExecution caseExecution : result) {
CaseExecutionEntity caseExecutionEntity = (CaseExecutionEntity) caseExecution;
// initializes the name, type and description
// of the activity on current case execution
caseExecutionEntity.getActivity();
}
return result;
}
// getters /////////////////////////////////////////////
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getActivityId() {
return activityId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
} | public String getBusinessKey() {
return businessKey;
}
public CaseExecutionState getState() {
return state;
}
public boolean isCaseInstancesOnly() {
return false;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public String getDeploymentId() {
return deploymentId;
}
public Boolean isRequired() {
return required;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public void setK_Topic_ID (int K_Topic_ID)
{
if (K_Topic_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, Integer.valueOf(K_Topic_ID));
}
/** Get Knowledge Topic.
@return Knowledge Topic
*/
public int getK_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_K_Type getK_Type() throws RuntimeException
{
return (I_K_Type)MTable.get(getCtx(), I_K_Type.Table_Name)
.getPO(getK_Type_ID(), get_TrxName()); }
/** Set Knowldge Type.
@param K_Type_ID
Knowledge Type
*/
public void setK_Type_ID (int K_Type_ID)
{
if (K_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Type_ID, Integer.valueOf(K_Type_ID));
}
/** Get Knowldge Type.
@return Knowledge Type
*/
public int getK_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Type_ID);
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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Topic.java | 1 |
请完成以下Java代码 | public void registerScriptScannerClass(final String fileExtension, final Class<? extends IScriptScanner> scannerClass)
{
final String fileExtensionNorm = normalizeFileExtension(fileExtension);
final Class<? extends IScriptScanner> scannerClassOld = scriptScannerClasses.put(fileExtensionNorm, scannerClass);
if (scannerClassOld != null)
{
logger.info("Unregistering scanner " + scannerClassOld + " for fileExtension=" + fileExtension);
}
logger.info("Registering scanner " + scannerClass + " for fileExtension=" + fileExtension);
}
@Override
public void registerScriptScannerClassesFor(final IScriptExecutorFactory scriptExecutorFactory)
{
for (final ScriptType scriptType : scriptExecutorFactory.getSupportedScriptTypes())
{
registerScriptScannerClass(scriptType.getFileExtension(), SingletonScriptScanner.class);
}
}
private static final String normalizeFileExtension(final String fileExtension)
{ | return fileExtension.trim().toLowerCase();
}
@Override
public void setScriptFactory(final IScriptFactory scriptFactory)
{
this.scriptFactory = scriptFactory;
}
@Override
public IScriptFactory getScriptFactoryToUse()
{
if (scriptFactory != null)
{
return scriptFactory;
}
return scriptFactoryDefault;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\ScriptScannerFactory.java | 1 |
请完成以下Java代码 | private byte[] getResourceBytes(Resource resource) {
return FileCopyUtils.copyToByteArray(resource.getInputStream());
}
@SneakyThrows
private SecretKey loadSecretKeyFromResource(Resource resource) {
byte[] secretKeyBytes = Base64.getDecoder().decode(getResourceBytes(resource));
return new SecretKeySpec(secretKeyBytes, "AES");
}
/**
* <p>generateSecretKey.</p>
*
* @return a {@link javax.crypto.SecretKey} object
*/
@SneakyThrows
public static SecretKey generateSecretKey() {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstanceStrong();
keyGenerator.init(AES_KEY_SIZE, random);
return keyGenerator.generateKey();
}
/**
* <p>generateBase64EncodedSecretKey.</p>
*
* @return a {@link java.lang.String} object
*/
@SneakyThrows
public static String generateBase64EncodedSecretKey() {
SecretKey key = generateSecretKey();
byte[] secretKeyBytes = key.getEncoded();
return Base64.getEncoder().encodeToString(secretKeyBytes);
}
/**
* <p>getAESKeyFromPassword.</p>
*
* @param password an array of {@link char} objects
* @param saltGenerator a {@link org.jasypt.salt.SaltGenerator} object
* @param iterations a int
* @param algorithm a {@link java.lang.String} object | * @return a {@link javax.crypto.SecretKey} object
*/
@SneakyThrows
public static SecretKey getAESKeyFromPassword(char[] password, SaltGenerator saltGenerator, int iterations, String algorithm){
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
KeySpec spec = new PBEKeySpec(password, saltGenerator.generateSalt(AES_KEY_PASSWORD_SALT_LENGTH), iterations, AES_KEY_SIZE);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
}
/**
* <p>Constructor for SimpleGCMByteEncryptor.</p>
*
* @param config a {@link com.ulisesbocchio.jasyptspringboot.encryptor.SimpleGCMConfig} object
*/
public SimpleGCMByteEncryptor(SimpleGCMConfig config) {
this.key = Singleton.from(this::loadSecretKey, config);
this.ivGenerator = Singleton.from(config::getActualIvGenerator);
this.algorithm = config.getAlgorithm();
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimpleGCMByteEncryptor.java | 1 |
请完成以下Java代码 | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@Override
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
@Override
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProcessDefinitionImpl that = (ProcessDefinitionImpl) o;
return (
version == that.version &&
Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(description, that.description) &&
Objects.equals(key, that.key) &&
Objects.equals(formKey, that.formKey)
);
}
@Override
public int hashCode() { | return Objects.hash(super.hashCode(), id, name, description, version, key, formKey);
}
@Override
public String toString() {
return (
"ProcessDefinition{" +
"id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", key='" +
key +
'\'' +
", description='" +
description +
'\'' +
", formKey='" +
formKey +
'\'' +
", version=" +
version +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessDefinitionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static PickingSlotSuggestion toPickingSlotSuggestion(
@NonNull final I_M_PickingSlot pickingSlot,
@NonNull final ImmutableMap<BPartnerLocationId, DocumentLocation> deliveryLocationsById,
@NonNull final PickingSlotQueuesSummary queues)
{
final PickingSlotIdAndCaption pickingSlotIdAndCaption = toPickingSlotIdAndCaption(pickingSlot);
final BPartnerLocationId deliveryLocationId = BPartnerLocationId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID(), pickingSlot.getC_BPartner_Location_ID());
final DocumentLocation deliveryLocation = deliveryLocationsById.get(deliveryLocationId);
return PickingSlotSuggestion.builder()
.pickingSlotIdAndCaption(pickingSlotIdAndCaption)
.deliveryLocation(deliveryLocation)
.countHUs(queues.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0))
.build(); | }
private static ImmutableSet<PickingSlotId> extractPickingSlotIds(final List<I_M_PickingSlot> pickingSlots)
{
return pickingSlots.stream()
.map(pickingSlot -> PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID()))
.collect(ImmutableSet.toImmutableSet());
}
private static PickingSlotIdAndCaption toPickingSlotIdAndCaption(@NonNull final I_M_PickingSlot record)
{
return PickingSlotIdAndCaption.of(PickingSlotId.ofRepoId(record.getM_PickingSlot_ID()), record.getPickingSlot());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\PickingJobSlotService.java | 2 |
请完成以下Java代码 | public void setA_Depreciation_Method_ID (int A_Depreciation_Method_ID)
{
if (A_Depreciation_Method_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Method_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Method_ID, Integer.valueOf(A_Depreciation_Method_ID));
}
/** Get Depreciation Calculation Type.
@return Depreciation Calculation Type */
public int getA_Depreciation_Method_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_Method_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Method_ID()));
}
/** Set DepreciationType.
@param DepreciationType DepreciationType */
public void setDepreciationType (String DepreciationType)
{
set_Value (COLUMNNAME_DepreciationType, DepreciationType);
}
/** Get DepreciationType.
@return DepreciationType */
public String getDepreciationType ()
{
return (String)get_Value(COLUMNNAME_DepreciationType);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
} | /** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Method.java | 1 |
请完成以下Java代码 | public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Long getId() {
return id;
}
public String getAuthor() {
return author;
}
@Override | public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
} | repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\Book.java | 1 |
请完成以下Java代码 | public int getFirstAD_User_ID()
{
getRecipients(false);
for (int i = 0; i < m_recipients.length; i++)
{
if (m_recipients[i].getAD_User_ID() != -1)
return m_recipients[i].getAD_User_ID();
}
return -1;
} // getFirstAD_User_ID
/**
* @return unique list of recipient users
*/
public Set<UserId> getRecipientUsers() {
MAlertRecipient[] recipients = getRecipients(false);
TreeSet<UserId> users = new TreeSet<>();
for (int i = 0; i < recipients.length; i++)
{
MAlertRecipient recipient = recipients[i];
if (recipient.getAD_User_ID() >= 0) // System == 0
{
users.add(UserId.ofRepoId(recipient.getAD_User_ID()));
}
final RoleId roleId = RoleId.ofRepoIdOrNull(recipient.getAD_Role_ID());
if (roleId != null) // SystemAdministrator == 0
{
final Set<UserId> allRoleUserIds = Services.get(IRoleDAO.class).retrieveUserIdsForRoleId(roleId);
users.addAll(allRoleUserIds);
}
}
return users;
} | /**
* String Representation
* @return info
*/
@Override
public String toString ()
{
StringBuffer sb = new StringBuffer ("MAlert[");
sb.append(get_ID())
.append("-").append(getName())
.append(",Valid=").append(isValid());
if (m_rules != null)
sb.append(",Rules=").append(m_rules.length);
if (m_recipients != null)
sb.append(",Recipients=").append(m_recipients.length);
sb.append ("]");
return sb.toString ();
} // toString
} // MAlert | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlert.java | 1 |
请完成以下Java代码 | public void setC_BPartner_Location(org.compiere.model.I_C_BPartner_Location C_BPartner_Location)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class, C_BPartner_Location);
}
/** Set Partner Location.
@param C_BPartner_Location_ID
Identifies the (ship to) address for this Business Partner
*/
@Override
public void setC_BPartner_Location_ID (int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID));
}
/** Get Partner Location.
@return Identifies the (ship to) address for this Business Partner
*/
@Override
public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Recurrent Payment.
@param C_RecurrentPayment_ID Recurrent Payment */
@Override
public void setC_RecurrentPayment_ID (int C_RecurrentPayment_ID)
{
if (C_RecurrentPayment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, Integer.valueOf(C_RecurrentPayment_ID));
}
/** Get Recurrent Payment.
@return Recurrent Payment */
@Override
public int getC_RecurrentPayment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPayment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPayment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ContactPerson
{
@NonNull String name;
@Nullable PhoneNumber phone;
@Nullable String emailAddress;
@Nullable String simplePhoneNumber;
@NonNull String languageCode;
@Builder
@Jacksonized
private ContactPerson(
@NonNull final String name,
@Nullable final PhoneNumber phone,
@Nullable final String simplePhoneNumber,
@Nullable final String emailAddress,
@Nullable final String languageCode)
{
this.name = name;
this.phone = phone;
this.simplePhoneNumber = simplePhoneNumber;
this.emailAddress = emailAddress;
this.languageCode = Check.isBlank(languageCode) ? Language.getBaseLanguage().getLanguageCode() : languageCode;
final boolean simplePhoneNumberIsEmpty = Check.isEmpty(simplePhoneNumber);
final boolean phoneIsEmpty = phone == null; | Check.errorUnless(
simplePhoneNumberIsEmpty || phoneIsEmpty,
"Its not allowed to specify both a simple phone number string and a PhoneNumber instance because they might be contradictory; simplePhoneNumber={}; phone={}",
simplePhoneNumber, phone);
}
@JsonIgnore
@Nullable
public String getPhoneAsStringOrNull()
{
if (phone != null)
{
return phone.getAsString();
}
else
return simplePhoneNumber;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\model\ContactPerson.java | 2 |
请完成以下Java代码 | public <T> Stream<T> streamByQuery(@NonNull final IQueryBuilder<I_M_HU> queryBuilder, @NonNull final Function<I_M_HU, T> mapper)
{
return queryBuilder
.create()
.iterateAndStream()
.map(mapper);
}
@Override
public void createTUPackingInstructions(final CreateTUPackingInstructionsRequest request)
{
CreateTUPackingInstructionsCommand.builder()
.handlingUnitsDAO(this)
.request(request)
.build()
.execute();
}
@Override
public Optional<I_M_HU_PI_Item> getTUPIItemForLUPIAndItemProduct(final BPartnerId bpartnerId, final @NonNull HuPackingInstructionsId luPIId, final @NonNull HUPIItemProductId piItemProductId)
{
final I_M_HU_PI_Version luPIVersion = retrievePICurrentVersionOrNull(luPIId);
if (luPIVersion == null || !luPIVersion.isActive() || !luPIVersion.isCurrent() || !X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit.equals(luPIVersion.getHU_UnitType()))
{
return Optional.empty();
}
return queryBL.createQueryBuilder(I_M_HU_PI_Item_Product.class)
.addOnlyActiveRecordsFilter() | .addEqualsFilter(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID, piItemProductId)
.andCollect(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_ID, I_M_HU_PI_Item.class)
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_ItemType, X_M_HU_PI_Item.ITEMTYPE_Material)
.addInArrayFilter(I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID, bpartnerId, null)
.addOnlyActiveRecordsFilter()
.andCollect(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID, I_M_HU_PI_Version.class)
.addEqualsFilter(I_M_HU_PI_Version.COLUMNNAME_HU_UnitType, X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit)
.addEqualsFilter(I_M_HU_PI_Version.COLUMNNAME_IsCurrent, true)
.addOnlyActiveRecordsFilter()
.andCollect(I_M_HU_PI_Version.COLUMNNAME_M_HU_PI_ID, I_M_HU_PI.class)
.andCollectChildren(I_M_HU_PI_Item.COLUMNNAME_Included_HU_PI_ID, I_M_HU_PI_Item.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_ItemType, X_M_HU_PI_Item.ITEMTYPE_HandlingUnit)
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID, luPIVersion.getM_HU_PI_Version_ID())
.orderBy(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID)
.create()
.firstOptional(I_M_HU_PI_Item.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsDAO.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCarrier_Product_ID (final int Carrier_Product_ID)
{
if (Carrier_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Product_ID, Carrier_Product_ID);
}
@Override
public int getCarrier_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Product_ID);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
} | @Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Product.java | 1 |
请完成以下Java代码 | public void validate() {
for (Validator<AbstractQuery<?, ?>> validator : validators) {
validate(validator);
}
}
public void validate(Validator<AbstractQuery<?, ?>> validator) {
validator.validate(this);
}
public void addValidator(Validator<AbstractQuery<?, ?>> validator) {
validators.add(validator);
}
public void removeValidator(Validator<AbstractQuery<?, ?>> validator) {
validators.remove(validator);
}
@SuppressWarnings("unchecked")
public List<String> listIds() {
this.resultType = ResultType.LIST_IDS;
List<String> ids = null;
if (commandExecutor != null) {
ids = (List<String>) commandExecutor.execute(this);
} else {
ids = evaluateExpressionsAndExecuteIdsList(Context.getCommandContext());
}
if (ids != null) {
QueryMaxResultsLimitUtil.checkMaxResultsLimit(ids.size());
}
return ids;
}
@SuppressWarnings("unchecked")
public List<ImmutablePair<String, String>> listDeploymentIdMappings() {
this.resultType = ResultType.LIST_DEPLOYMENT_ID_MAPPINGS;
List<ImmutablePair<String, String>> ids = null;
if (commandExecutor != null) {
ids = (List<ImmutablePair<String, String>>) commandExecutor.execute(this);
} else {
ids = evaluateExpressionsAndExecuteDeploymentIdMappingsList(Context.getCommandContext());
}
if (ids != null) {
QueryMaxResultsLimitUtil.checkMaxResultsLimit(ids.size());
}
return ids;
}
public List<String> evaluateExpressionsAndExecuteIdsList(CommandContext commandContext) { | validate();
evaluateExpressions();
return !hasExcludingConditions() ? executeIdsList(commandContext) : new ArrayList<>();
}
public List<String> executeIdsList(CommandContext commandContext) {
throw new UnsupportedOperationException("executeIdsList not supported by " + getClass().getCanonicalName());
}
public List<ImmutablePair<String, String>> evaluateExpressionsAndExecuteDeploymentIdMappingsList(CommandContext commandContext) {
validate();
evaluateExpressions();
return !hasExcludingConditions() ? executeDeploymentIdMappingsList(commandContext) : new ArrayList<>();
}
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
throw new UnsupportedOperationException("executeDeploymentIdMappingsList not supported by " + getClass().getCanonicalName());
}
protected void checkMaxResultsLimit() {
if (maxResultsLimitEnabled) {
QueryMaxResultsLimitUtil.checkMaxResultsLimit(maxResults);
}
}
public void enableMaxResultsLimit() {
maxResultsLimitEnabled = true;
}
public void disableMaxResultsLimit() {
maxResultsLimitEnabled = false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractQuery.java | 1 |
请完成以下Java代码 | public void dispose()
{
m_frame.dispose();
} // dispose
@Override
public void actionPerformed(final ActionEvent e)
{
try
{
actionPerformed0(e);
}
catch (final Exception ex)
{
log.warn("", ex);
statusBar.setStatusLine(ex.getLocalizedMessage(), true);
}
}
private void actionPerformed0(final ActionEvent e)
{
final ValueNamePair AD_Language = (ValueNamePair)cbLanguage.getSelectedItem();
if (AD_Language == null)
{
throw new AdempiereException("@LanguageSetupError@");
}
ValueNamePair AD_Table = (ValueNamePair)cbTable.getSelectedItem();
if (AD_Table == null)
{
return;
}
final boolean imp = e.getSource() == bImport;
final KeyNamePair AD_Client = (KeyNamePair)cbClient.getSelectedItem();
int AD_Client_ID = -1;
if (AD_Client != null)
{
AD_Client_ID = AD_Client.getKey();
}
final String startDir = Ini.getMetasfreshHome() + File.separator + "data";
final JFileChooser chooser = new JFileChooser(startDir);
chooser.setMultiSelectionEnabled(false);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
final int returnVal = imp ? chooser.showOpenDialog(panel) : chooser.showSaveDialog(panel);
if (returnVal != JFileChooser.APPROVE_OPTION)
{
return;
}
final String directory = chooser.getSelectedFile().getAbsolutePath();
//
statusBar.setStatusLine(directory);
panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
final TranslationImpExp t = TranslationImpExp.newInstance();
t.validateLanguage(AD_Language.getValue());
// All Tables
if (AD_Table.getValue().equals(""))
{
String msg = null;
for (int i = 1; i < cbTable.getItemCount(); i++)
{
AD_Table = cbTable.getItemAt(i);
msg = imp | ? t.importTrl(directory, AD_Client_ID, AD_Language.getValue(), AD_Table.getValue())
: t.exportTrl(directory, AD_Client_ID, AD_Language.getValue(), AD_Table.getValue());
}
if (msg == null || msg.length() == 0)
{
msg = (imp ? "Import" : "Export") + " Successful. [" + directory + "]";
}
statusBar.setStatusLine(directory);
}
else // single table
{
String msg = imp
? t.importTrl(directory, AD_Client_ID, AD_Language.getValue(), AD_Table.getValue())
: t.exportTrl(directory, AD_Client_ID, AD_Language.getValue(), AD_Table.getValue());
if (msg == null || msg.length() == 0)
{
msg = (imp ? "Import" : "Export") + " Successful. [" + directory + "]";
}
statusBar.setStatusLine(msg);
}
}
finally
{
panel.setCursor(Cursor.getDefaultCursor());
}
} // actionPerformed
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\i18n\VTranslationImpExpDialog.java | 1 |
请完成以下Java代码 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!hasBoundValueObject(beanName)) {
bind(ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName));
}
return bean;
}
private boolean hasBoundValueObject(String beanName) {
return BindMethod.VALUE_OBJECT.equals(BindMethodAttribute.get(this.registry, beanName));
}
private void bind(@Nullable ConfigurationPropertiesBean bean) {
if (bean == null) {
return;
}
Assert.state(bean.asBindTarget().getBindMethod() != BindMethod.VALUE_OBJECT,
"Cannot bind @ConfigurationProperties for bean '" + bean.getName()
+ "'. Ensure that @ConstructorBinding has not been applied to regular bean");
try {
this.binder.bind(bean);
}
catch (Exception ex) {
throw new ConfigurationPropertiesBindException(bean, ex);
} | }
/**
* Register a {@link ConfigurationPropertiesBindingPostProcessor} bean if one is not
* already registered.
* @param registry the bean definition registry
* @since 2.2.0
*/
public static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class)
.getBeanDefinition();
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(BEAN_NAME, definition);
}
ConfigurationPropertiesBinder.register(registry);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBindingPostProcessor.java | 1 |
请完成以下Java代码 | public void setT_Amount (final @Nullable BigDecimal T_Amount)
{
set_Value (COLUMNNAME_T_Amount, T_Amount);
}
@Override
public BigDecimal getT_Amount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Amount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Date (final @Nullable java.sql.Timestamp T_Date)
{
set_Value (COLUMNNAME_T_Date, T_Date);
}
@Override
public java.sql.Timestamp getT_Date()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Date);
}
@Override
public void setT_DateTime (final @Nullable java.sql.Timestamp T_DateTime)
{
set_Value (COLUMNNAME_T_DateTime, T_DateTime);
}
@Override
public java.sql.Timestamp getT_DateTime()
{
return get_ValueAsTimestamp(COLUMNNAME_T_DateTime);
}
@Override
public void setT_Integer (final int T_Integer)
{
set_Value (COLUMNNAME_T_Integer, T_Integer);
}
@Override
public int getT_Integer()
{
return get_ValueAsInt(COLUMNNAME_T_Integer);
}
@Override
public void setT_Number (final @Nullable BigDecimal T_Number)
{
set_Value (COLUMNNAME_T_Number, T_Number);
}
@Override
public BigDecimal getT_Number()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number);
return bd != null ? bd : BigDecimal.ZERO; | }
@Override
public void setT_Qty (final @Nullable BigDecimal T_Qty)
{
set_Value (COLUMNNAME_T_Qty, T_Qty);
}
@Override
public BigDecimal getT_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_Time (final @Nullable java.sql.Timestamp T_Time)
{
set_Value (COLUMNNAME_T_Time, T_Time);
}
@Override
public java.sql.Timestamp getT_Time()
{
return get_ValueAsTimestamp(COLUMNNAME_T_Time);
}
@Override
public void setTest_ID (final int Test_ID)
{
if (Test_ID < 1)
set_ValueNoCheck (COLUMNNAME_Test_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID);
}
@Override
public int getTest_ID()
{
return get_ValueAsInt(COLUMNNAME_Test_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java | 1 |
请完成以下Java代码 | public class TaxAmount1 {
@XmlElement(name = "Rate")
protected BigDecimal rate;
@XmlElement(name = "TaxblBaseAmt")
protected ActiveOrHistoricCurrencyAndAmount taxblBaseAmt;
@XmlElement(name = "TtlAmt")
protected ActiveOrHistoricCurrencyAndAmount ttlAmt;
@XmlElement(name = "Dtls")
protected List<TaxRecordDetails1> dtls;
/**
* Gets the value of the rate property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setRate(BigDecimal value) {
this.rate = value;
}
/**
* Gets the value of the taxblBaseAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getTaxblBaseAmt() {
return taxblBaseAmt;
}
/**
* Sets the value of the taxblBaseAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTaxblBaseAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.taxblBaseAmt = value;
}
/**
* Gets the value of the ttlAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/ | public ActiveOrHistoricCurrencyAndAmount getTtlAmt() {
return ttlAmt;
}
/**
* Sets the value of the ttlAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlAmt = value;
}
/**
* Gets the value of the dtls 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 dtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TaxRecordDetails1 }
*
*
*/
public List<TaxRecordDetails1> getDtls() {
if (dtls == null) {
dtls = new ArrayList<TaxRecordDetails1>();
}
return this.dtls;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxAmount1.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult<UmsAdmin> getItem(@PathVariable Long id) {
UmsAdmin admin = adminService.getItem(id);
return CommonResult.success(admin);
}
@ApiOperation("修改指定用户信息")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody UmsAdmin admin) {
int count = adminService.update(id, admin);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("修改指定用户密码")
@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
@ResponseBody
public CommonResult updatePassword(@Validated @RequestBody UpdateAdminPasswordParam updatePasswordParam) {
int status = adminService.updatePassword(updatePasswordParam);
if (status > 0) {
return CommonResult.success(status);
} else if (status == -1) {
return CommonResult.failed("提交参数不合法");
} else if (status == -2) {
return CommonResult.failed("找不到该用户");
} else if (status == -3) {
return CommonResult.failed("旧密码错误");
} else {
return CommonResult.failed();
}
}
@ApiOperation("删除指定用户信息")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = adminService.delete(id);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("修改帐号状态")
@RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST) | @ResponseBody
public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) {
UmsAdmin umsAdmin = new UmsAdmin();
umsAdmin.setStatus(status);
int count = adminService.update(id,umsAdmin);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("给用户分配角色")
@RequestMapping(value = "/role/update", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateRole(@RequestParam("adminId") Long adminId,
@RequestParam("roleIds") List<Long> roleIds) {
int count = adminService.updateRole(adminId, roleIds);
if (count >= 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("获取指定用户的角色")
@RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
List<UmsRole> roleList = adminService.getRoleList(adminId);
return CommonResult.success(roleList);
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsAdminController.java | 2 |
请完成以下Java代码 | public void setInstances(int instances) {
this.instances = instances;
}
public int getFailedJobs() {
return failedJobs;
}
public void setFailedJobs(int failedJobs) {
this.failedJobs = failedJobs;
}
public List<IncidentStatistics> getIncidentStatistics() {
return incidentStatistics;
}
public void setIncidentStatistics(List<IncidentStatistics> incidentStatistics) {
this.incidentStatistics = incidentStatistics;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[instances=" + instances
+ ", failedJobs=" + failedJobs
+ ", id=" + id | + ", deploymentId=" + deploymentId
+ ", description=" + description
+ ", historyLevel=" + historyLevel
+ ", category=" + category
+ ", hasStartFormKey=" + hasStartFormKey
+ ", diagramResourceName=" + diagramResourceName
+ ", key=" + key
+ ", name=" + name
+ ", resourceName=" + resourceName
+ ", revision=" + revision
+ ", version=" + version
+ ", suspensionState=" + suspensionState
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessDefinitionStatisticsEntity.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final InvoicingItem other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(product, other.product)
.append(qty, other.qty)
.append(uom, other.uom)
.isEqual();
}
@Override
public I_M_Product getM_Product()
{ | return product;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InvoicingItem.java | 1 |
请完成以下Java代码 | public VariableInstanceQuery orderByVariableName() {
wrappedVariableInstanceQuery.orderByVariableName();
return this;
}
@Override
public VariableInstanceQuery asc() {
wrappedVariableInstanceQuery.asc();
return this;
}
@Override
public VariableInstanceQuery desc() {
wrappedVariableInstanceQuery.desc();
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property) {
wrappedVariableInstanceQuery.orderBy(property);
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return wrappedVariableInstanceQuery.count();
} | @Override
public VariableInstance singleResult() {
return wrappedVariableInstanceQuery.singleResult();
}
@Override
public List<VariableInstance> list() {
return wrappedVariableInstanceQuery.list();
}
@Override
public List<VariableInstance> listPage(int firstResult, int maxResults) {
return wrappedVariableInstanceQuery.listPage(firstResult, maxResults);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public String getRegionNameLabel()
{
return regionNameLabel;
}
@SuppressWarnings("unused")
public boolean isHasRegions()
{
return hasRegions;
}
public int getSelectedRegionId()
{
final MRegion region = getSelectedItem();
if (region == null)
{
return -1;
}
return region.getC_Region_ID();
}
public void setSelectedRegionId(final int regionId)
{
if(regionId <= 0)
{
setSelectedItem(null);
return;
}
for (int i = 0, size = getSize(); i < size; i++)
{
final MRegion region = getElementAt(i);
if(region != null && region.getC_Region_ID() == regionId)
{
setSelectedItem(region);
}
}
}
}
/**
* Small class used to handle the components of a location part (e.g. the label and field of Address1)
*
* @author metas-dev <dev@metasfresh.com>
*
*/
private final class LocationPart
{
private final JLabel label;
private final JComponent field;
private final String partName;
private boolean enabledCustom = true;
private boolean enabledByCaptureSequence = false;
public LocationPart(final String partName, final String label, final JComponent field)
{
super();
this.partName = partName;
this.field = field;
this.field.setName(label);
this.label = new CLabel(Check.isEmpty(label) ? "" : msgBL.translate(Env.getCtx(), label));
this.label.setHorizontalAlignment(SwingConstants.RIGHT);
this.label.setLabelFor(field);
update();
}
public void setEnabledCustom(final boolean enabledCustom)
{
if (this.enabledCustom == enabledCustom)
{
return;
}
this.enabledCustom = enabledCustom;
update();
}
public void setEnabledByCaptureSequence(final LocationCaptureSequence captureSequence) | {
final boolean enabled = captureSequence.hasPart(partName);
setEnabledByCaptureSequence(enabled);
}
private void setEnabledByCaptureSequence(final boolean enabledByCaptureSequence)
{
if (this.enabledByCaptureSequence == enabledByCaptureSequence)
{
return;
}
this.enabledByCaptureSequence = enabledByCaptureSequence;
update();
}
private final void update()
{
final boolean enabled = enabledCustom && enabledByCaptureSequence;
label.setEnabled(enabled);
label.setVisible(enabled);
field.setEnabled(enabled);
field.setVisible(enabled);
}
public void setLabelText(final String labelText)
{
label.setText(labelText);
}
public JLabel getLabel()
{
return label;
}
public JComponent getField()
{
return field;
}
}
} // VLocationDialog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocationDialog.java | 1 |
请完成以下Java代码 | public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Manual.
@param IsManual
This is a manual process
*/
public void setIsManual (boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual));
}
/** Get Manual.
@return This is a manual process
*/
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
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());
}
/** Set SLA Criteria.
@param PA_SLA_Criteria_ID
Service Level Agreement Criteria
*/
public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID)
{
if (PA_SLA_Criteria_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID));
}
/** Get SLA Criteria.
@return Service Level Agreement Criteria
*/
public int getPA_SLA_Criteria_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Criteria.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuffer sb = new StringBuffer ("X_IMP_RequestHandlerType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Request handler type.
@param IMP_RequestHandlerType_ID Request handler type */
@Override
public void setIMP_RequestHandlerType_ID (int IMP_RequestHandlerType_ID)
{
if (IMP_RequestHandlerType_ID < 1) | set_ValueNoCheck (COLUMNNAME_IMP_RequestHandlerType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandlerType_ID, Integer.valueOf(IMP_RequestHandlerType_ID));
}
/** Get Request handler type.
@return Request handler type */
@Override
public int getIMP_RequestHandlerType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandlerType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\requesthandler\model\X_IMP_RequestHandlerType.java | 1 |
请完成以下Java代码 | public void scheduleDeleteSelections(@NonNull final Set<String> selectionIds)
{
SqlViewSelectionToDeleteHelper.scheduleDeleteSelections(selectionIds);
}
public static Set<DocumentId> retrieveRowIdsForLineIds(
@NonNull final SqlViewKeyColumnNamesMap keyColumnNamesMap,
final ViewId viewId,
final Set<Integer> lineIds)
{
final SqlAndParams sqlAndParams = SqlViewSelectionQueryBuilder.buildSqlSelectRowIdsForLineIds(keyColumnNamesMap, viewId.getViewId(), lineIds);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sqlAndParams.getSql(), ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlAndParams.getSqlParams());
rs = pstmt.executeQuery();
final ImmutableSet.Builder<DocumentId> rowIds = ImmutableSet.builder(); | while (rs.next())
{
final DocumentId rowId = keyColumnNamesMap.retrieveRowId(rs, "", false);
if (rowId != null)
{
rowIds.add(rowId);
}
}
return rowIds.build();
}
catch (final SQLException ex)
{
throw new DBException(ex, sqlAndParams.getSql(), sqlAndParams.getSqlParams());
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewRowIdsOrderedSelectionFactory.java | 1 |
请完成以下Java代码 | public String asString() {
return "messaging.rabbitmq.message.delivery_tag";
}
}
}
/**
* Default {@link RabbitListenerObservationConvention} for Rabbit listener key values.
*/
public static class DefaultRabbitListenerObservationConvention implements RabbitListenerObservationConvention {
/**
* A singleton instance of the convention.
*/
public static final DefaultRabbitListenerObservationConvention INSTANCE =
new DefaultRabbitListenerObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(RabbitMessageReceiverContext context) {
MessageProperties messageProperties = context.getCarrier().getMessageProperties();
String consumerQueue = Objects.requireNonNullElse(messageProperties.getConsumerQueue(), "");
return KeyValues.of(
RabbitListenerObservation.ListenerLowCardinalityTags.LISTENER_ID.asString(), | context.getListenerId(),
RabbitListenerObservation.ListenerLowCardinalityTags.DESTINATION_NAME.asString(),
consumerQueue);
}
@Override
public KeyValues getHighCardinalityKeyValues(RabbitMessageReceiverContext context) {
return KeyValues.of(RabbitListenerObservation.ListenerHighCardinalityTags.DELIVERY_TAG.asString(),
String.valueOf(context.getCarrier().getMessageProperties().getDeliveryTag()));
}
@Override
public String getContextualName(RabbitMessageReceiverContext context) {
return context.getSource() + " receive";
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitListenerObservation.java | 1 |
请完成以下Java代码 | public DeviceProfileId getDeviceProfileId() {
return deviceProfileId;
}
public void setDeviceProfileId(DeviceProfileId deviceProfileId) {
this.deviceProfileId = deviceProfileId;
}
@Schema(description = "JSON object with content specific to type of transport in the device profile.")
public DeviceData getDeviceData() {
if (deviceData != null) {
return deviceData;
} else {
if (deviceDataBytes != null) {
try {
deviceData = mapper.readValue(new ByteArrayInputStream(deviceDataBytes), DeviceData.class);
} catch (IOException e) {
log.warn("Can't deserialize device data: ", e);
return null;
}
return deviceData;
} else {
return null;
}
}
}
public void setDeviceData(DeviceData data) {
this.deviceData = data;
try {
this.deviceDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) { | log.warn("Can't serialize device data: ", e);
}
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getFirmwareId() {
return firmwareId;
}
public void setFirmwareId(OtaPackageId firmwareId) {
this.firmwareId = firmwareId;
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getSoftwareId() {
return softwareId;
}
public void setSoftwareId(OtaPackageId softwareId) {
this.softwareId = softwareId;
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Device.java | 1 |
请完成以下Java代码 | public void setTriggerEventType(String triggerEventType) {
this.triggerEventType = triggerEventType;
}
public boolean isSendSynchronously() {
return sendSynchronously;
}
public void setSendSynchronously(boolean sendSynchronously) {
this.sendSynchronously = sendSynchronously;
}
public List<IOParameter> getEventInParameters() {
return eventInParameters;
}
public void setEventInParameters(List<IOParameter> eventInParameters) {
this.eventInParameters = eventInParameters;
}
public List<IOParameter> getEventOutParameters() {
return eventOutParameters;
}
public void setEventOutParameters(List<IOParameter> eventOutParameters) {
this.eventOutParameters = eventOutParameters;
}
@Override
public SendEventServiceTask clone() {
SendEventServiceTask clone = new SendEventServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(SendEventServiceTask otherElement) {
super.setValues(otherElement); | setEventType(otherElement.getEventType());
setTriggerEventType(otherElement.getTriggerEventType());
setSendSynchronously(otherElement.isSendSynchronously());
eventInParameters = new ArrayList<>();
if (otherElement.getEventInParameters() != null && !otherElement.getEventInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventInParameters()) {
eventInParameters.add(parameter.clone());
}
}
eventOutParameters = new ArrayList<>();
if (otherElement.getEventOutParameters() != null && !otherElement.getEventOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getEventOutParameters()) {
eventOutParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\SendEventServiceTask.java | 1 |
请完成以下Java代码 | public class VehicleFactory {
/**
* Stores the already created vehicles.
*/
private static Map<Color, Vehicle> vehiclesCache = new HashMap<Color, Vehicle>();
/**
* Private constructor to prevent this class instantiation.
*/
private VehicleFactory() {
}
/**
* Returns a vehicle of the same color passed as argument. If that vehicle
* was already created by this factory, that vehicle is returned, otherwise
* a new one is created and returned. | *
* @param color
* the color of the vehicle to return
* @return a vehicle of the specified color
*/
public static Vehicle createVehicle(Color color) {
// Looks for the requested vehicle into the cache.
// If the vehicle doesn't exist, a new one is created.
Vehicle newVehicle = vehiclesCache.computeIfAbsent(color, newColor -> {
// Creates the new car.
Engine newEngine = new Engine();
return new Car(newEngine, newColor);
});
return newVehicle;
}
} | repos\tutorials-master\patterns-modules\design-patterns-creational-2\src\main\java\com\baeldung\flyweight\VehicleFactory.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_BOMAlternative[")
.append(get_ID()).append("]");
return sb.toString();
}
/** 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 Alternative Group.
@param M_BOMAlternative_ID
Product BOM Alternative Group
*/
public void setM_BOMAlternative_ID (int M_BOMAlternative_ID)
{
if (M_BOMAlternative_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, Integer.valueOf(M_BOMAlternative_ID));
}
/** Get Alternative Group.
@return Product BOM Alternative Group
*/
public int getM_BOMAlternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BOMAlternative_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); | }
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMAlternative.java | 1 |
请完成以下Java代码 | public class DLM_Partition_Config_Line
{
static final DLM_Partition_Config_Line INSTANCE = new DLM_Partition_Config_Line();
private DLM_Partition_Config_Line()
{
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteReferences(final I_DLM_Partition_Config_Line configLine)
{
Services.get(IQueryBL.class).createQueryBuilder(I_DLM_Partition_Config_Reference.class, configLine)
.addEqualsFilter(I_DLM_Partition_Config_Reference.COLUMN_DLM_Partition_Config_Line_ID, configLine.getDLM_Partition_Config_Line_ID())
.create()
.delete();
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = I_DLM_Partition_Config_Line.COLUMNNAME_DLM_Referencing_Table_ID)
public void updatePartitionerInterceptorOnChange(final I_DLM_Partition_Config_Line configLine)
{
if (configLine.getDLM_Referencing_Table_ID() <= 0)
{
return;
}
final ModelValidationEngine engine = ModelValidationEngine.get();
final I_DLM_Partition_Config_Line oldConfigLine = InterfaceWrapperHelper.createOld(configLine, I_DLM_Partition_Config_Line.class);
engine.removeModelChange(oldConfigLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
engine.addModelChange(configLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void updatePartitionerInterceptorOnNew(final I_DLM_Partition_Config_Line configLine) | {
if (configLine.getDLM_Referencing_Table_ID() <= 0)
{
return;
}
final ModelValidationEngine engine = ModelValidationEngine.get();
engine.addModelChange(configLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void updatePartitionerInterceptorOnDelete(final I_DLM_Partition_Config_Line configLine)
{
if (configLine.getDLM_Referencing_Table_ID() <= 0)
{
return;
}
final ModelValidationEngine engine = ModelValidationEngine.get();
engine.removeModelChange(configLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\DLM_Partition_Config_Line.java | 1 |
请完成以下Java代码 | public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : roles) { | authorities.add( new SimpleGrantedAuthority( role.getName() ) );
}
return authorities;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
} | repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\model\entity\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class BatchAutoConfiguration {
@Configuration(proxyBeanMethods = false)
static class SpringBootBatchDefaultConfiguration extends DefaultBatchConfiguration {
private final @Nullable TaskExecutor taskExecutor;
private final @Nullable JobParametersConverter jobParametersConverter;
SpringBootBatchDefaultConfiguration(@BatchTaskExecutor ObjectProvider<TaskExecutor> batchTaskExecutor,
ObjectProvider<JobParametersConverter> jobParametersConverter) {
this.taskExecutor = batchTaskExecutor.getIfAvailable();
this.jobParametersConverter = jobParametersConverter.getIfAvailable();
} | @Override
@Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal")
protected JobParametersConverter getJobParametersConverter() {
return (this.jobParametersConverter != null) ? this.jobParametersConverter
: super.getJobParametersConverter();
}
@Override
protected TaskExecutor getTaskExecutor() {
return (this.taskExecutor != null) ? this.taskExecutor : super.getTaskExecutor();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-batch\src\main\java\org\springframework\boot\batch\autoconfigure\BatchAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static List toList() {
TrxTypeEnum[] ary = TrxTypeEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list;
}
public static TrxTypeEnum getEnum(String name) {
TrxTypeEnum[] arry = TrxTypeEnum.values();
for (int i = 0; i < arry.length; i++) {
if (arry[i].name().equalsIgnoreCase(name)) {
return arry[i];
}
}
return null;
}
/**
* 取枚举的json字符串 | *
* @return
*/
public static String getJsonStr() {
TrxTypeEnum[] enums = TrxTypeEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (TrxTypeEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\enums\TrxTypeEnum.java | 2 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final I_DLM_Partition partitionDB = getProcessInfo().getRecord(I_DLM_Partition.class);
final ITrxManager trxManager = Services.get(ITrxManager.class);
try (final AutoCloseable customizer = connectionCustomizerService.registerTemporaryCustomizer(DLMConnectionCustomizer.seeThemAllCustomizer()))
{
trxManager.run("DLM_Partition_Destroy_ID_" + partitionDB.getDLM_Partition_ID(), // trxName prefix
true,
(TrxRunnable)localTrxName -> destroyPartitionWithinTrx(partitionDB));
}
return MSG_OK;
}
private void destroyPartitionWithinTrx(final I_DLM_Partition partitionDB)
{
final PlainContextAware ctx = PlainContextAware.newWithThreadInheritedTrx(getCtx());
final int updateCount = dlmService.directUpdateDLMColumn(
ctx,
partitionDB.getDLM_Partition_ID(), | IDLMAware.COLUMNNAME_DLM_Partition_ID, 0);
Loggables.addLog("Unassigned {} records from {}", updateCount, partitionDB);
partitionDB.setPartitionSize(0);
InterfaceWrapperHelper.save(partitionDB);
if (isClearWorkQueue)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final int deleteCount = queryBL.createQueryBuilder(I_DLM_Partition_Workqueue.class, ctx)
.addEqualsFilter(I_DLM_Partition_Workqueue.COLUMN_DLM_Partition_ID, partitionDB.getDLM_Partition_ID())
.create()
.deleteDirectly();
Loggables.addLog("Deleted {} {} records that referenced", deleteCount, I_DLM_Partition_Workqueue.Table_Name, partitionDB);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_Partition_Destroy.java | 1 |
请完成以下Java代码 | public String getUserNameAttributeName() {
return this.userNameAttributeName;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
OAuth2UserAuthority that = (OAuth2UserAuthority) obj;
if (!this.getAuthority().equals(that.getAuthority())) {
return false;
}
Map<String, Object> thatAttributes = that.getAttributes();
if (getAttributes().size() != thatAttributes.size()) {
return false;
}
for (Map.Entry<String, Object> e : getAttributes().entrySet()) {
String key = e.getKey();
Object value = convertURLIfNecessary(e.getValue());
if (value == null) {
if (!(thatAttributes.get(key) == null && thatAttributes.containsKey(key))) {
return false;
}
}
else {
Object thatValue = convertURLIfNecessary(thatAttributes.get(key));
if (!value.equals(thatValue)) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int result = this.getAuthority().hashCode(); | result = 31 * result;
for (Map.Entry<String, Object> e : getAttributes().entrySet()) {
Object key = e.getKey();
Object value = convertURLIfNecessary(e.getValue());
result += Objects.hashCode(key) ^ Objects.hashCode(value);
}
return result;
}
@Override
public String toString() {
return this.getAuthority();
}
/**
* @return {@code URL} converted to a string since {@code URL} shouldn't be used for
* equality/hashCode. For other instances the value is returned as is.
*/
private static Object convertURLIfNecessary(Object value) {
return (value instanceof URL) ? ((URL) value).toExternalForm() : value;
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\user\OAuth2UserAuthority.java | 1 |
请完成以下Java代码 | static class Sync extends AbstractQueuedSynchronizer {
// 我们定义状态标志位是1时表示获取到了锁,为0时表示没有获取到锁
@Override
protected boolean tryAcquire(int arg) {
// 获取锁有竞争所以需要使用CAS原子操作
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
// 只有获取到锁的线程才会解锁,所以这里没有竞争,直接使用setState方法在来改变同步状态
setState(0);
setExclusiveOwnerThread(null);
return true;
}
@Override
protected boolean isHeldExclusively() {
// 如果货物到锁,当前线程独占
return getState() == 1;
}
// 返回一个Condition,每个condition都包含了一个condition队列
Condition newCondition() {
return new ConditionObject();
}
}
// 仅需要将操作代理到Sync上即可
private final Sync sync = new Sync();
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryRelease(1);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(0); | }
@Override
public Condition newCondition() {
return sync.newCondition();
}
public static void main(String[] args) {
MutexLock lock = new MutexLock();
final User user = new User();
for (int i = 0; i < 100; i++) {
new Thread(() -> {
lock.lock();
try {
user.setAge(user.getAge() + 1);
System.out.println(user.getAge());
} finally {
lock.unlock();
}
}).start();
}
}
} | repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\MutexLock.java | 1 |
请完成以下Java代码 | public Properties getCtx()
{
return ctx;
}
@Override
public String getProcessingTag()
{
return processingTag;
}
@Override
public void close()
{
releaseTag(ctx, processingTag); | }
@Override
@NonNull
public Iterator<I_Fact_Acct_Log> iterator()
{
return retrieveForTag(ctx, processingTag);
}
@Override
public void deleteAll()
{
deleteAllForTag(ctx, processingTag);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\legacy\impl\LegacyFactAcctLogDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTHM(Boolean value) {
this.thm = value;
}
/**
* Gets the value of the nonReturnableContainer property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNonReturnableContainer() {
return nonReturnableContainer;
}
/**
* Sets the value of the nonReturnableContainer property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNonReturnableContainer(Boolean value) {
this.nonReturnableContainer = value; | }
/**
* Gets the value of the specialConditionCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecialConditionCode() {
return specialConditionCode;
}
/**
* Sets the value of the specialConditionCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialConditionCode(String value) {
this.specialConditionCode = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICListLineItemExtensionType.java | 2 |
请完成以下Java代码 | public class CustomStringArrayType implements UserType<String[]> {
@Override
public int getSqlType() {
return Types.ARRAY;
}
@Override
public Class<String[]> returnedClass() {
return String[].class;
}
@Override
public boolean equals(String[] x, String[] y) {
if (x instanceof String[] && y instanceof String[]) {
return Arrays.deepEquals(x, y);
} else {
return false;
}
}
@Override
public int hashCode(String[] x) {
return Arrays.hashCode(x);
}
@Override
public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Array array = rs.getArray(position);
return array != null ? (String[]) array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException {
if (st != null) {
if (value != null) {
Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value);
st.setArray(index, array);
} else { | st.setNull(index, Types.ARRAY);
}
}
}
@Override
public String[] deepCopy(String[] value) {
return value != null ? Arrays.copyOf(value, value.length) : null;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(String[] value) {
return value;
}
@Override
public String[] assemble(Serializable cached, Object owner) {
return (String[]) cached;
}
@Override
public String[] replace(String[] detached, String[] managed, Object owner) {
return detached;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\CustomStringArrayType.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_C_BPartner_ID.contentEquals(parameter.getColumnName()))
{
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(bankStatementLine.getC_BPartner_ID());
if (bpartnerId != null)
{
return bpartnerId;
}
}
return DEFAULT_VALUE_NOTAVAILABLE;
}
@ProcessParamLookupValuesProvider(parameterName = PARAM_C_Payment_ID, numericKey = true, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup, lookupTableName = I_C_Payment.Table_Name)
private LookupValuesList paymentLookupProvider()
{
if (bpartnerId == null)
{
return LookupValuesList.EMPTY;
}
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
final int limit = 20;
final Set<PaymentId> paymentIds = bankStatementPaymentBL.findEligiblePaymentIds(
bankStatementLine,
bpartnerId,
ImmutableSet.of(), // excludePaymentIds
limit);
return lookupDataSourceFactory.searchInTableLookup(I_C_Payment.Table_Name).findByIdsOrdered(paymentIds);
}
@Override
protected String doIt()
{
final I_C_BankStatement bankStatement = getSelectedBankStatement();
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
bankStatementLine.setC_BPartner_ID(bpartnerId.getRepoId());
if (paymentId != null)
{
bankStatementPaymentBL.linkSinglePayment(bankStatement, bankStatementLine, paymentId);
} | else
{
final Set<PaymentId> eligiblePaymentIds = bankStatementPaymentBL.findEligiblePaymentIds(
bankStatementLine,
bpartnerId,
ImmutableSet.of(), // excludePaymentIds
2 // limit
);
if (eligiblePaymentIds.isEmpty())
{
bankStatementPaymentBL.createSinglePaymentAndLink(bankStatement, bankStatementLine);
}
else if (eligiblePaymentIds.size() == 1)
{
PaymentId eligiblePaymentId = eligiblePaymentIds.iterator().next();
bankStatementPaymentBL.linkSinglePayment(bankStatement, bankStatementLine, eligiblePaymentId);
}
else
{
throw new FillMandatoryException(PARAM_C_Payment_ID);
}
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\C_BankStatement_ReconcileWithSinglePayment.java | 1 |
请完成以下Java代码 | public <R> R forProcessInstanceWritable(final DocumentId pinstanceId, final IDocumentChangesCollector changesCollector, @NonNull final Function<IProcessInstanceController, R> processor)
{
try (final IAutoCloseable ignored = getInstance(pinstanceId).lockForWriting())
{
final HUReportProcessInstance processInstance = getInstance(pinstanceId)
.copyReadWrite(changesCollector);
final R result = processor.apply(processInstance);
putInstance(processInstance);
return result;
}
}
@Override
public void cacheReset()
{
processDescriptors.reset();
instances.cleanUp();
}
private DocumentId nextPInstanceId()
{
return DocumentId.ofString(UUID.randomUUID().toString());
}
private static final class IndexedWebuiHUProcessDescriptors | {
private final ImmutableMap<ProcessId, WebuiHUProcessDescriptor> descriptorsByProcessId;
private IndexedWebuiHUProcessDescriptors(final List<WebuiHUProcessDescriptor> descriptors)
{
descriptorsByProcessId = Maps.uniqueIndex(descriptors, WebuiHUProcessDescriptor::getProcessId);
}
public WebuiHUProcessDescriptor getByProcessId(final ProcessId processId)
{
final WebuiHUProcessDescriptor descriptor = descriptorsByProcessId.get(processId);
if (descriptor == null)
{
throw new EntityNotFoundException("No HU process descriptor found for " + processId);
}
return descriptor;
}
public Collection<WebuiHUProcessDescriptor> getAll()
{
return descriptorsByProcessId.values();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\HUReportProcessInstancesRepository.java | 1 |
请完成以下Java代码 | private LookupValuesList getAll()
{
LookupValuesList all = this.all;
if (all == null)
{
all = this.all = ZoneId.getAvailableZoneIds()
.stream()
.map(TimeZoneLookupDescriptor::fromZoneIdToLookupValue)
.collect(LookupValuesList.collect());
}
return all;
}
private static StringLookupValue fromZoneIdToLookupValue(final String zoneIdStr)
{
final ZoneId zoneId = ZoneId.of(zoneIdStr);
final ITranslatableString displayName = TranslatableStrings.builder()
.appendTimeZone(zoneId, TextStyle.FULL_STANDALONE)
.append(" - ")
.append(zoneId.getId())
.build();
final ITranslatableString helpText = TranslatableStrings.empty();
return StringLookupValue.of(zoneIdStr, displayName, helpText);
}
@Override
public Optional<String> getLookupTableName()
{
return Optional.empty();
}
@Override
public boolean isNumericKey()
{
return false; | }
@Override
public Set<String> getDependsOnFieldNames()
{
return ImmutableSet.of();
}
@Override
@Nullable
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
return StringUtils.trimBlankToOptional(evalCtx.getIdToFilterAsString())
.map(zoneId -> getAll().getById(zoneId))
.orElse(null);
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int offset = evalCtx.getOffset(0);
final int limit = evalCtx.getLimit(50);
return getAll()
.filter(filter)
.pageByOffsetAndLimit(offset, limit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\TimeZoneLookupDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LineBuilder setTableName(final String tableName)
{
this.tableName = tableName;
return this;
}
public String getTableName()
{
return tableName;
}
/**
* Sets the primary key of the {@link I_DLM_Partition_Config_Line} records that already exists for the {@link PartitionerConfigLine} instances that we want to build.
* This information is important when a config is persisted because it determines if a {@link I_DLM_Partition_Config_Line} record shall be loaded and updated rather than inserted.
*
* @param dlm_Partition_Config_Line_ID
* @return
*/
public LineBuilder setDLM_Partition_Config_Line(final int dlm_Partition_Config_Line_ID)
{
this.dlm_Partition_Config_Line_ID = dlm_Partition_Config_Line_ID;
return this;
}
/**
* Convenience method to end the current line builder and start a new one.
*
* @return the new line builder, <b>not</b> this instance.
*/
public LineBuilder line(final String tableName)
{
return endLine().line(tableName);
}
public PartitionConfig.Builder endLine()
{
return parentBuilder;
}
public PartitionerConfigLine buildLine(final PartitionConfig parent)
{
buildLine = new PartitionerConfigLine(parent, tableName);
buildLine.setDLM_Partition_Config_Line_ID(dlm_Partition_Config_Line_ID);
return buildLine;
}
public PartitionerConfigReference.RefBuilder ref() | {
final PartitionerConfigReference.RefBuilder refBuilder = new PartitionerConfigReference.RefBuilder(this);
refBuilders.add(refBuilder);
return refBuilder;
}
public LineBuilder endRef()
{
final List<RefBuilder> distinctRefBuilders = refBuilders.stream()
// if a builder's ref was already persisted, then we want distinct to return that one
.sorted(Comparator.comparing(RefBuilder::getDLM_Partition_Config_Reference_ID).reversed())
.distinct()
.collect(Collectors.toList());
refBuilders.clear();
refBuilders.addAll(distinctRefBuilders);
parentBuilder.setChanged(true); // TODO: check if there was really any *new* reference
return this;
}
/**
* Invokes the {@link RefBuilder}s and creates an ordered list of {@link PartitionerConfigReference}s within the {@link PartitionerConfigLine} which this builder is building.
*
*/
public void buildRefs()
{
for (final PartitionerConfigReference.RefBuilder refBuilder : refBuilders)
{
final PartitionerConfigReference ref = refBuilder.build(buildLine);
buildLine.references.add(ref);
}
buildLine.references.sort(Comparator.comparing(PartitionerConfigReference::getReferencedTableName));
}
@Override
public String toString()
{
return "LineBuilder [parentBuilder=" + parentBuilder + ", DLM_Partition_Config_Line_ID=" + dlm_Partition_Config_Line_ID + ", tableName=" + tableName + ", refBuilders=" + refBuilders + ", buildLine=" + buildLine + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionerConfigLine.java | 2 |
请完成以下Java代码 | protected final void finalize() throws Throwable
{
// NOTE: to avoid memory leaks we need to programatically clear our internal state
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
logger.debug("Running finalize");
cache.invalidateAll();
}
}
public CCacheStats stats()
{
final CacheStats guavaStats = cache.stats();
return CCacheStats.builder()
.cacheId(cacheId) | .name(cacheName)
.labels(labels)
.config(config)
.debugAcquireStacktrace(debugAcquireStacktrace)
//
.size(cache.size())
.hitCount(guavaStats.hitCount())
.missCount(guavaStats.missCount())
.build();
}
private boolean isNoCache()
{
return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void newAuthor() {
Author author = new Author();
author.setName("Joana Nimar");
author.setAge(34);
author.setGenre("History");
// this will call @Pre/PostPersist callback
authorRepository.save(author); | }
@Transactional
public void selectUpdateDeleteAuthor() {
// this will call @PostLoad (the user is in persistent context)
Author author = authorRepository.findById(1L).orElseThrow();
// force update, so @Pre/PostUpdate will be called
author.setAge(35);
authorRepository.saveAndFlush(author);
// this will call @Pre/PostRemove callback
authorRepository.delete(author);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJpaCallbacks\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.