instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class InputSetImpl extends BaseElementImpl implements InputSet {
protected static Attribute<String> nameAttribute;
protected static ElementReferenceCollection<DataInput, DataInputRefs> dataInputDataInputRefsCollection;
protected static ElementReferenceCollection<DataInput, OptionalInputRefs> optionalInputRefsCollection;
protected static ElementReferenceCollection<DataInput, WhileExecutingInputRefs> whileExecutingInputRefsCollection;
protected static ElementReferenceCollection<OutputSet, OutputSetRefs> outputSetOutputSetRefsCollection;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InputSet.class, BPMN_ELEMENT_INPUT_SET)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<InputSet>() {
public InputSet newInstance(ModelTypeInstanceContext instanceContext) {
return new InputSetImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute("name")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataInputDataInputRefsCollection = sequenceBuilder.elementCollection(DataInputRefs.class)
.idElementReferenceCollection(DataInput.class)
.build();
optionalInputRefsCollection = sequenceBuilder.elementCollection(OptionalInputRefs.class)
.idElementReferenceCollection(DataInput.class)
.build();
whileExecutingInputRefsCollection = sequenceBuilder.elementCollection(WhileExecutingInputRefs.class)
.idElementReferenceCollection(DataInput.class)
.build();
outputSetOutputSetRefsCollection = sequenceBuilder.elementCollection(OutputSetRefs.class)
.idElementReferenceCollection(OutputSet.class)
.build(); | typeBuilder.build();
}
public InputSetImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Collection<DataInput> getDataInputs() {
return dataInputDataInputRefsCollection.getReferenceTargetElements(this);
}
public Collection<DataInput> getOptionalInputs() {
return optionalInputRefsCollection.getReferenceTargetElements(this);
}
public Collection<DataInput> getWhileExecutingInput() {
return whileExecutingInputRefsCollection.getReferenceTargetElements(this);
}
public Collection<OutputSet> getOutputSets() {
return outputSetOutputSetRefsCollection.getReferenceTargetElements(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\InputSetImpl.java | 1 |
请完成以下Java代码 | private IWorkpackageLogsRepository getLogsRepository()
{
return SpringContextHolder.instance.getBean(IWorkpackageLogsRepository.class);
}
@Override
public IQueueProcessor createAsynchronousQueueProcessor(final I_C_Queue_Processor config, final IWorkPackageQueue queue)
{
final IWorkpackageLogsRepository logsRepository = getLogsRepository();
return new ThreadPoolQueueProcessor(config, queue, logsRepository);
}
private IQueueProcessorEventDispatcher queueProcessorEventDispatcher = new DefaultQueueProcessorEventDispatcher();
@Override | public IQueueProcessorEventDispatcher getQueueProcessorEventDispatcher()
{
return queueProcessorEventDispatcher;
}
@Override
public IQueueProcessor createAsynchronousQueueProcessor(@NonNull final QueuePackageProcessorId packageProcessorId)
{
final I_C_Queue_Processor queueProcessorConfig = queueProcessorDescriptorIndex.getQueueProcessor(packageProcessorId);
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForPackageProcessing(queueProcessorConfig);
return createAsynchronousQueueProcessor(queueProcessorConfig, queue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorFactory.java | 1 |
请完成以下Java代码 | public String getCodingLine1() {
return codingLine1;
}
/**
* Sets the value of the codingLine1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine1(String value) {
this.codingLine1 = value;
}
/**
* Gets the value of the codingLine2 property.
*
* @return | * possible object is
* {@link String }
*
*/
public String getCodingLine2() {
return codingLine2;
}
/**
* Sets the value of the codingLine2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodingLine2(String value) {
this.codingLine2 = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EsrRedType.java | 1 |
请完成以下Java代码 | public final class SecurityContextCallableProcessingInterceptor implements CallableProcessingInterceptor {
private @Nullable volatile SecurityContext securityContext;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* Create a new {@link SecurityContextCallableProcessingInterceptor} that uses the
* {@link SecurityContext} from the {@link SecurityContextHolder} at the time
* {@link #beforeConcurrentHandling(NativeWebRequest, Callable)} is invoked.
*/
public SecurityContextCallableProcessingInterceptor() {
}
/**
* Creates a new {@link SecurityContextCallableProcessingInterceptor} with the
* specified {@link SecurityContext}.
* @param securityContext the {@link SecurityContext} to set on the
* {@link SecurityContextHolder} in {@link #preProcess(NativeWebRequest, Callable)}.
* Cannot be null.
* @throws IllegalArgumentException if {@link SecurityContext} is null.
*/
public SecurityContextCallableProcessingInterceptor(SecurityContext securityContext) {
Assert.notNull(securityContext, "securityContext cannot be null");
setSecurityContext(securityContext);
}
@Override
public <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) {
if (this.securityContext == null) { | setSecurityContext(this.securityContextHolderStrategy.getContext());
}
}
@Override
public <T> void preProcess(NativeWebRequest request, Callable<T> task) {
if (this.securityContext != null) {
this.securityContextHolderStrategy.setContext(this.securityContext);
}
}
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, @Nullable Object concurrentResult) {
this.securityContextHolderStrategy.clearContext();
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
private void setSecurityContext(SecurityContext securityContext) {
this.securityContext = securityContext;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\request\async\SecurityContextCallableProcessingInterceptor.java | 1 |
请完成以下Java代码 | public CountResultDto getHistoricDetailsCount(UriInfo uriInfo) {
HistoricDetailQueryDto queryDto = new HistoricDetailQueryDto(objectMapper, uriInfo.getQueryParameters());
HistoricDetailQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
private List<HistoricDetailDto> executeHistoricDetailQuery(HistoricDetailQuery query, Integer firstResult,
Integer maxResults, boolean deserializeObjectValues) {
query.disableBinaryFetching(); | if (!deserializeObjectValues) {
query.disableCustomObjectDeserialization();
}
List<HistoricDetail> queryResult = QueryUtil.list(query, firstResult, maxResults);
List<HistoricDetailDto> result = new ArrayList<HistoricDetailDto>();
for (HistoricDetail historicDetail : queryResult) {
HistoricDetailDto dto = HistoricDetailDto.fromHistoricDetail(historicDetail);
result.add(dto);
}
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricDetailRestServiceImpl.java | 1 |
请完成以下Java代码 | public void setEmail(String email) {
this.email = email;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getRegTime() {
return regTime;
}
public void setRegTime(String regTime) { | this.regTime = regTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", nickname='" + nickname + '\'' +
", regTime='" + regTime + '\'' +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 4-2 课:Spring Boot 和 Redis 常用操作\spring-boot-redis\src\main\java\com\neo\model\User.java | 1 |
请完成以下Java代码 | public class CustomUserDetails extends User {
private final String firstName;
private final String lastName;
private final String email;
private CustomUserDetails(Builder builder) {
super(builder.username, builder.password, builder.authorities);
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.email = builder.email;
}
public String getLastName() {
return this.lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getEmail() {
return email;
}
@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;
CustomUserDetails that = (CustomUserDetails) o;
return firstName.equals(that.firstName) && lastName.equals(that.lastName) && email.equals(that.email);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), firstName, lastName, email);
}
public static class Builder { | private String firstName;
private String lastName;
private String email;
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public Builder withFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder withLastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder withEmail(String email) {
this.email = email;
return this;
}
public Builder withUsername(String username) {
this.username = username;
return this;
}
public Builder withPassword(String password) {
this.password = password;
return this;
}
public Builder withAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
return this;
}
public CustomUserDetails build() {
return new CustomUserDetails(this);
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-thymeleaf\src\main\java\com\baeldung\customuserdetails\CustomUserDetails.java | 1 |
请完成以下Java代码 | protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
final String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/homepage";
} else if (isAdmin) {
return "/console";
} else { | throw new IllegalStateException();
}
}
/**
* Removes temporary authentication-related data which may have been stored in the session
* during the authentication process.
*/
protected final void clearAuthenticationAttributes(final HttpServletRequest request) {
final HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java | 1 |
请完成以下Java代码 | public ResponseEntity createReceipts(@RequestBody final JsonCreateReceiptsRequest jsonCreateReceiptsRequest)
{
try
{
final JsonCreateReceiptsResponse receiptsResponse = trxManager.callInNewTrx(() -> createReceipts_0(jsonCreateReceiptsRequest));
return ResponseEntity.ok(receiptsResponse);
}
catch (final Exception ex)
{
log.error(ex.getMessage(), ex);
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return ResponseEntity.unprocessableEntity()
.body(JsonErrors.ofThrowable(ex, adLanguage));
}
}
private JsonCreateReceiptsResponse createReceipts_0(@NonNull final JsonCreateReceiptsRequest jsonCreateReceiptsRequest)
{
final List<InOutId> createdReceiptIds = jsonCreateReceiptsRequest.getJsonCreateReceiptInfoList().isEmpty()
? ImmutableList.of()
: receiptService.updateReceiptCandidatesAndGenerateReceipts(jsonCreateReceiptsRequest);
final List<InOutId> createdReturnIds = jsonCreateReceiptsRequest.getJsonCreateCustomerReturnInfoList().isEmpty()
? ImmutableList.of()
: customerReturnRestService.handleReturns(jsonCreateReceiptsRequest.getJsonCreateCustomerReturnInfoList());
return toJsonCreateReceiptsResponse(createdReceiptIds, createdReturnIds);
}
@NonNull
private JsonCreateReceiptsResponse toJsonCreateReceiptsResponse(@NonNull final List<InOutId> receiptIds, @NonNull final List<InOutId> returnIds)
{
final List<JsonMetasfreshId> jsonReceiptIds = receiptIds | .stream()
.map(InOutId::getRepoId)
.map(JsonMetasfreshId::of)
.collect(ImmutableList.toImmutableList());
final List<JsonMetasfreshId> jsonReturnIds = returnIds
.stream()
.map(InOutId::getRepoId)
.map(JsonMetasfreshId::of)
.collect(ImmutableList.toImmutableList());
return JsonCreateReceiptsResponse.builder()
.createdReceiptIdList(jsonReceiptIds)
.createdReturnIdList(jsonReturnIds)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\ReceiptRestController.java | 1 |
请完成以下Java代码 | public List<NameCountryEntity> getCountry() {
return country;
}
public void setCountry(List<NameCountryEntity> country) {
this.country = country;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameCountriesEntity other = (NameCountriesEntity) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name)) | return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
return true;
}
@Override
public String toString() {
return "NameCountriesModel [name=" + name + ", country=" + country + "]";
}
} | repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameCountriesEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfiguration {
@Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user1 = User
.withUsername("user")
.password(passwordEncoder().encode("baeldung"))
.roles("tenant_1")
.build();
UserDetails user2 = User
.withUsername("admin")
.password(passwordEncoder().encode("baeldung"))
.roles("tenant_2")
.build();
return new InMemoryUserDetailsManager(user1, user2);
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
} | @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
final AuthenticationManager authenticationManager = authenticationManager(http.getSharedObject(AuthenticationConfiguration.class));
http
.authorizeHttpRequests(authorize ->
authorize.requestMatchers("/login").permitAll().anyRequest().authenticated())
.sessionManagement(securityContext -> securityContext.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new LoginFilter("/login", authenticationManager), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf(csrf -> csrf.disable())
.headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.httpBasic(Customizer.withDefaults());
return http.build();
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\multitenant\security\SecurityConfiguration.java | 2 |
请完成以下Java代码 | public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) {
ActivitiEntityWithVariablesEvent eventWithVariables = (ActivitiEntityWithVariablesEvent) event;
ExecutionEntity processInstanceEntity = (ExecutionEntity) eventWithVariables.getEntity();
Map<String, Object> data = new HashMap<String, Object>();
putInMapIfNotNull(data, Fields.ID, processInstanceEntity.getId());
putInMapIfNotNull(data, Fields.BUSINESS_KEY, processInstanceEntity.getBusinessKey());
putInMapIfNotNull(data, Fields.PROCESS_DEFINITION_ID, processInstanceEntity.getProcessDefinitionId());
putInMapIfNotNull(data, Fields.NAME, processInstanceEntity.getName());
putInMapIfNotNull(data, Fields.CREATE_TIME, timeStamp);
if (eventWithVariables.getVariables() != null && !eventWithVariables.getVariables().isEmpty()) {
Map<String, Object> variableMap = new HashMap<String, Object>();
for (Object variableName : eventWithVariables.getVariables().keySet()) {
putInMapIfNotNull(
variableMap,
(String) variableName,
eventWithVariables.getVariables().get(variableName) | );
}
putInMapIfNotNull(data, Fields.VARIABLES, variableMap);
}
return createEventLogEntry(
TYPE,
processInstanceEntity.getProcessDefinitionId(),
processInstanceEntity.getId(),
null,
null,
data
);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\handler\ProcessInstanceStartedEventHandler.java | 1 |
请完成以下Java代码 | public static class Fact {
private final String name;
private final String value;
}
}
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class ActionCard {
@JsonProperty("@type")
private String type; // ActionCard, OpenUri
private String name;
private List<Input> inputs; // for ActionCard
private List<Action> actions; // for ActionCard
private List<Target> targets;
@Data
public static class Input {
@JsonProperty("@type")
private String type; // TextInput, DateInput, MultichoiceInput
private String id;
private boolean isMultiple;
private String title;
private boolean isMultiSelect;
@Data
public static class Choice {
private final String display;
private final String value; | }
}
@Data
public static class Action {
@JsonProperty("@type")
private final String type; // HttpPOST
private final String name;
private final String target; // url
}
@Data
public static class Target {
private final String os;
private final String uri;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\TeamsMessageCard.java | 1 |
请完成以下Java代码 | protected boolean afterDelete (boolean success)
{
if (success)
{
updateHeader();
//
Object ii = get_ValueOld("S_ResourceAssignment_ID");
if (ii instanceof Integer)
{
int old_S_ResourceAssignment_ID = ((Integer)ii).intValue();
// Deleted Assignment
if (old_S_ResourceAssignment_ID != 0)
{
MResourceAssignment ra = new MResourceAssignment (getCtx(),
old_S_ResourceAssignment_ID, get_TrxName());
ra.delete(false);
}
}
}
return success;
} // afterDelete | /**
* Update Header.
* Set Approved Amount
*/
private void updateHeader()
{
String sql = "UPDATE S_TimeExpense te"
+ " SET ApprovalAmt = "
+ "(SELECT SUM(Qty*ConvertedAmt) FROM S_TimeExpenseLine tel "
+ "WHERE te.S_TimeExpense_ID=tel.S_TimeExpense_ID) "
+ "WHERE S_TimeExpense_ID=" + getS_TimeExpense_ID();
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
} // updateHeader
} // MTimeExpenseLine | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MTimeExpenseLine.java | 1 |
请完成以下Java代码 | public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Node_ID. | @param Node_ID Node_ID */
@Override
public void setNode_ID (int Node_ID)
{
if (Node_ID < 0)
set_Value (COLUMNNAME_Node_ID, null);
else
set_Value (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID));
}
/** Get Node_ID.
@return Node_ID */
@Override
public int getNode_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Node_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_AD_TreeBar.java | 1 |
请完成以下Java代码 | public void setStopEditing(boolean stopediting)
{
m_stopediting = stopediting;
}
private VLookupAutoCompleter lookupAutoCompleter = null;
// metas-2009_0021_AP1_CR054: begin
/**
* @return true if enabled
*/
public boolean enableLookupAutocomplete()
{
if (lookupAutoCompleter != null)
{
return true; // auto-complete already initialized
}
final Lookup lookup = getLookup();
if (lookup instanceof MLookup && lookup.getDisplayType() == DisplayType.Search)
{
final MLookup mlookup = (MLookup)lookup;
final MLookupInfo lookupInfo = mlookup.getLookupInfo();
// FIXME: check what happens when lookup changes
lookupAutoCompleter = new VLookupAutoCompleter(this.m_text, this, lookupInfo);
return true;
}
return false;
}
// metas-2009_0021_AP1_CR054: end
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(MouseListener l)
{
m_text.addMouseListener(l);
m_button.addMouseListener(l);
m_combo.getEditor().getEditorComponent().addMouseListener(l); // popup
}
private boolean isRowLoading()
{
if (m_mField == null)
{
return false;
}
final String rowLoadingStr = Env.getContext(Env.getCtx(), m_mField.getWindowNo(), m_mField.getVO().TabNo, GridTab.CTX_RowLoading);
return "Y".equals(rowLoadingStr);
}
/* package */IValidationContext getValidationContext()
{
final GridField gridField = m_mField; | // In case there is no GridField set (e.g. VLookup was created from a custom swing form)
if (gridField == null)
{
return IValidationContext.DISABLED;
}
final IValidationContext evalCtx = Services.get(IValidationRuleFactory.class).createValidationContext(gridField);
// In case grid field validation context could not be created, disable validation
// NOTE: in most of the cases when we reach this point is when we are in a custom form which used GridFields to create the lookups
// but those custom fields does not have a GridTab
// e.g. de.metas.paymentallocation.form.PaymentAllocationForm
if (evalCtx == null)
{
return IValidationContext.DISABLED;
}
return evalCtx;
}
@Override
public void addFocusListener(final FocusListener l)
{
getEditorComponent().addFocusListener(l);
}
@Override
public void removeFocusListener(FocusListener l)
{
getEditorComponent().removeFocusListener(l);
}
public void setInfoWindowEnabled(final boolean enabled)
{
this.infoWindowEnabled = enabled;
if (m_button != null)
{
m_button.setVisible(enabled);
}
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // VLookup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookup.java | 1 |
请完成以下Java代码 | private final IAttributeValue toAttributeValue(final I_M_HU_Attribute huAttribute, final I_M_HU_PI_Attribute piAttribute)
{
return new HUAttributeValue(this, huAttribute, piAttribute, isSaveOnChange());
}
protected final IHandlingUnitsDAO getHandlingUnitsDAO()
{
return handlingUnitsDAO;
}
@Override
public void updateHUTrxAttribute(@NonNull final MutableHUTransactionAttribute huTrxAttribute, @NonNull final IAttributeValue fromAttributeValue)
{
assertNotDisposed();
//
// Set M_HU
final I_M_HU hu = getM_HU();
huTrxAttribute.setReferencedObject(hu);
//
// Set HU related fields
//
// NOTE: we assume given "attributeValue" was created by "toAttributeValue"
if (fromAttributeValue instanceof HUAttributeValue)
{
final HUAttributeValue attributeValueImpl = (HUAttributeValue)fromAttributeValue;
final I_M_HU_PI_Attribute piAttribute = attributeValueImpl.getM_HU_PI_Attribute();
huTrxAttribute.setPiAttributeId(piAttribute != null ? HuPackingInstructionsAttributeId.ofRepoId(piAttribute.getM_HU_PI_Attribute_ID()) : null);
final I_M_HU_Attribute huAttribute = attributeValueImpl.getM_HU_Attribute();
huTrxAttribute.setHuAttribute(huAttribute);
}
else
{
throw new AdempiereException("Attribute value " + fromAttributeValue + " is not valid for this storage (" + this + ")");
}
}
@Override
public final UOMType getQtyUOMTypeOrNull()
{
final I_M_HU hu = getM_HU();
final IHUStorageDAO huStorageDAO = getHUStorageDAO();
return huStorageDAO.getC_UOMTypeOrNull(hu);
}
@Override
public final BigDecimal getStorageQtyOrZERO() | {
final IHUStorageFactory huStorageFactory = getAttributeStorageFactory().getHUStorageFactory();
final IHUStorage storage = huStorageFactory.getStorage(getM_HU());
final BigDecimal fullStorageQty = storage.getQtyForProductStorages().toBigDecimal();
return fullStorageQty;
}
@Override
public final boolean isVirtual()
{
return handlingUnitsBL.isVirtual(getM_HU());
}
@Override
public Optional<WarehouseId> getWarehouseId()
{
final I_M_HU hu = getM_HU();
if (hu == null)
{
return Optional.empty();
}
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu);
return Optional.ofNullable(warehouseId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractHUAttributeStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = -6212297506742428406L;
private RawAccessJwtToken rawAccessToken;
private SecurityUser securityUser;
public AbstractJwtAuthenticationToken(RawAccessJwtToken unsafeToken) {
super(null);
this.rawAccessToken = unsafeToken;
this.setAuthenticated(false);
}
public AbstractJwtAuthenticationToken(SecurityUser securityUser) {
super(securityUser.getAuthorities());
this.eraseCredentials();
this.securityUser = securityUser;
super.setAuthenticated(true);
}
@Override
public void setAuthenticated(boolean authenticated) {
if (authenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false); | }
@Override
public Object getCredentials() {
return rawAccessToken;
}
@Override
public Object getPrincipal() {
return this.securityUser;
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
this.rawAccessToken = null;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\AbstractJwtAuthenticationToken.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class TaskActionRequest extends RestActionRequest {
public static final String ACTION_COMPLETE = "complete";
public static final String ACTION_CLAIM = "claim";
public static final String ACTION_DELEGATE = "delegate";
public static final String ACTION_RESOLVE = "resolve";
protected String assignee;
protected String formDefinitionId;
protected String outcome;
protected List<RestVariable> variables;
protected List<RestVariable> transientVariables;
public void setAssignee(String assignee) {
this.assignee = assignee;
}
@ApiModelProperty(value = "If action is claim or delegate, you can use this parameter to set the assignee associated ", example = "userWhoClaims/userToDelegateTo")
public String getAssignee() {
return assignee;
}
@ApiModelProperty(value = "Required when completing a task with a form", example = "12345")
public String getFormDefinitionId() {
return formDefinitionId;
}
public void setFormDefinitionId(String formDefinitionId) {
this.formDefinitionId = formDefinitionId;
}
@ApiModelProperty(value = "Optional outcome value when completing a task with a form", example = "accepted/rejected")
public String getOutcome() {
return outcome;
}
public void setOutcome(String outcome) { | this.outcome = outcome;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
@ApiModelProperty(value = "If action is complete, you can use this parameter to set variables ")
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getVariables() {
return variables;
}
@ApiModelProperty(value = "If action is complete, you can use this parameter to set transient variables ")
public List<RestVariable> getTransientVariables() {
return transientVariables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public void setTransientVariables(List<RestVariable> transientVariables) {
this.transientVariables = transientVariables;
}
@Override
@ApiModelProperty(value = "Action to perform: Either complete, claim, delegate or resolve", example = "complete", required = true)
public String getAction() {
return super.getAction();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskActionRequest.java | 2 |
请完成以下Java代码 | public Class<? extends BaseElement> getHandledType() {
return SignalEventDefinition.class;
}
protected void executeParse(BpmnParse bpmnParse, SignalEventDefinition signalDefinition) {
Signal signal = null;
if (bpmnParse.getBpmnModel().containsSignalId(signalDefinition.getSignalRef())) {
signal = bpmnParse.getBpmnModel().getSignal(signalDefinition.getSignalRef());
}
if (bpmnParse.getCurrentFlowElement() instanceof IntermediateCatchEvent) {
IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) bpmnParse.getCurrentFlowElement();
intermediateCatchEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createIntermediateCatchSignalEventActivityBehavior(
intermediateCatchEvent,
signalDefinition,
signal
) | );
} else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) {
BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement();
boundaryEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createBoundarySignalEventActivityBehavior(
boundaryEvent,
signalDefinition,
signal,
boundaryEvent.isCancelActivity()
)
);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SignalEventDefinitionParseHandler.java | 1 |
请完成以下Java代码 | public void setAttribute(String name, Object value) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.setAttribute(name, value);
if (value != oldValue) {
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue)
.valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
if (value instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
}
@Override
public void removeAttribute(String name) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.removeAttribute(name);
if (oldValue instanceof HttpSessionBindingListener) { | try {
((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
@Override
public void invalidate() {
checkState();
this.invalidated = true;
}
@Override
public boolean isNew() {
checkState();
return !this.old;
}
void markNotNew() {
this.old = true;
}
private void checkState() {
if (this.invalidated) {
throw new IllegalStateException("The HttpSession has already be invalidated.");
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HttpSessionAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public Date getLastUpdatedTime() {
return lastUpdatedTime;
}
@Override
public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
@Override
public Date getTime() {
return createTime;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
} | @Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
@Override
public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@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\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java | 2 |
请完成以下Java代码 | public Optional<MobileApplicationId> getApplicationId() {return getByPathAsString("applicationId").map(MobileApplicationId::ofNullableString);}
public Optional<String> getDeviceId() {return getByPathAsString("device", "deviceId");}
public Optional<String> getTabId() {return getByPathAsString("device", "tabId");}
public Optional<String> getUserAgent() {return getByPathAsString("device", "userAgent");}
public Optional<String> getByPathAsString(final String... path)
{
return getByPath(path).map(Object::toString);
}
public Optional<Object> getByPath(final String... path)
{
Object currentValue = properties;
for (final String pathElement : path)
{
if (!(currentValue instanceof Map))
{
//throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties);
return Optional.empty();
}
//noinspection unchecked
final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null);
if (value == null)
{
return Optional.empty();
}
else
{
currentValue = value; | }
}
return Optional.of(currentValue);
}
private static Optional<Object> getByKey(final Map<String, Object> map, final String key)
{
return map.entrySet()
.stream()
.filter(e -> e.getKey().equalsIgnoreCase(key))
.map(Map.Entry::getValue)
.filter(Objects::nonNull)
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java | 1 |
请完成以下Java代码 | public static WarehouseId ofRepoId(final int repoId)
{
if (repoId == MAIN.repoId)
{
return MAIN;
}
else
{
return new WarehouseId(repoId);
}
}
@Nullable
public static WarehouseId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<WarehouseId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final WarehouseId warehouseId)
{
return warehouseId != null ? warehouseId.getRepoId() : -1;
}
public static Set<Integer> toRepoIds(final Collection<WarehouseId> warehouseIds)
{
return warehouseIds.stream() | .map(WarehouseId::toRepoId)
.filter(id -> id > 0)
.collect(ImmutableSet.toImmutableSet());
}
int repoId;
private WarehouseId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_Warehouse_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final WarehouseId id1, @Nullable final WarehouseId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\WarehouseId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(CalculatedField calculatedField, SecurityUser user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = calculatedField.getTenantId();
CalculatedFieldId calculatedFieldId = calculatedField.getId();
try {
calculatedFieldService.deleteCalculatedField(tenantId, calculatedFieldId);
logEntityActionService.logEntityAction(tenantId, calculatedFieldId, calculatedField, actionType, user, calculatedFieldId.toString());
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.CALCULATED_FIELD), actionType, user, e, calculatedFieldId.toString());
throw e;
}
}
private void checkForEntityChange(CalculatedField oldCalculatedField, CalculatedField newCalculatedField) {
if (!oldCalculatedField.getEntityId().equals(newCalculatedField.getEntityId())) {
throw new IllegalArgumentException("Changing the calculated field target entity after initialization is prohibited."); | }
}
private void checkEntity(TenantId tenantId, EntityId entityId, CalculatedFieldType type) {
EntityType entityType = entityId.getEntityType();
Set<CalculatedFieldType> supportedTypes = CalculatedField.SUPPORTED_ENTITIES.get(entityType);
if (supportedTypes == null || supportedTypes.isEmpty()) {
throw new IllegalArgumentException("Entity type '" + entityType + "' does not support calculated fields");
} else if (type != null && !supportedTypes.contains(type)) {
throw new IllegalArgumentException("Entity type '" + entityType + "' does not support '" + type + "' calculated fields");
} else if (entityService.fetchEntity(tenantId, entityId).isEmpty()) {
throw new IllegalArgumentException(entityType.getNormalName() + " with id [" + entityId.getId() + "] does not exist.");
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\cf\DefaultTbCalculatedFieldService.java | 2 |
请完成以下Java代码 | private static boolean equalsConstantTime(String expected, @Nullable String actual) {
if (expected == actual) {
return true;
}
if (expected == null || actual == null) {
return false;
}
// Encode after ensure that the string is not null
byte[] expectedBytes = Utf8.encode(expected);
byte[] actualBytes = Utf8.encode(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher { | private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
@Override
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
@Override
public String toString() {
return "IsNotHttpMethod " + this.allowedMethods;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\CsrfFilter.java | 1 |
请完成以下Java代码 | public abstract class CmmnElementImpl extends CmmnModelElementInstanceImpl implements CmmnElement {
protected static Attribute<String> idAttribute;
protected static ChildElement<ExtensionElements> extensionElementsChild;
// cmmn 1.0
@Deprecated
protected static Attribute<String> descriptionAttribute;
// cmmn 1.1
protected static ChildElementCollection<Documentation> documentationCollection;
public CmmnElementImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getId() {
return idAttribute.getValue(this);
}
public void setId(String id) {
idAttribute.setValue(this, id);
}
public String getDescription() {
return descriptionAttribute.getValue(this);
}
public void setDescription(String description) {
descriptionAttribute.setValue(this, description);
}
public Collection<Documentation> getDocumentations() {
return documentationCollection.get(this);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
protected boolean isCmmn11() {
return CmmnModelConstants.CMMN11_NS.equals(getDomElement().getNamespaceURI()); | }
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CmmnElement.class, CMMN_ELEMENT)
.abstractType()
.namespaceUri(CMMN11_NS);
idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID)
.idAttribute()
.build();
descriptionAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DESCRIPTION)
.namespace(CMMN10_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
documentationCollection = sequenceBuilder.elementCollection(Documentation.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CmmnElementImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SourceHUsCollection getByProductId(@NonNull final ProductId productId)
{
switch (issueStrategy)
{
case AssignedHUsOnly:
return retrieveActiveSourceHusForHus(productId);
case DEFAULT:
return retrieveActiveSourceHusFromWarehouse(productId);
default:
throw new AdempiereException("Unknown issue strategy!");
}
}
private ImmutableSet<WarehouseId> getIssueFromWarehouseIds()
{
return ppOrderBOMBL.getIssueFromWarehouseIds(manufacturingWarehouseId);
}
private @NonNull ImmutableSet<HuId> getPPOrderSourceHUIds()
{
if (_ppOrderSourceHUIds == null)
{
_ppOrderSourceHUIds = ppOrderSourceHUService.getSourceHUIds(ppOrderId);
}
return _ppOrderSourceHUIds;
}
@NonNull
private SourceHUsCollection retrieveActiveSourceHusFromWarehouse(@NonNull final ProductId productId)
{
final List<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveMatchingSourceHuMarkers(
SourceHUsService.MatchingSourceHusQuery.builder()
.productId(productId)
.warehouseIds(getIssueFromWarehouseIds())
.build()
);
final List<I_M_HU> hus = handlingUnitsDAO.getByIds(extractHUIdsFromSourceHUs(sourceHUs));
return SourceHUsCollection.builder()
.husThatAreFlaggedAsSource(ImmutableList.copyOf(hus))
.sourceHUs(sourceHUs)
.build();
}
@NonNull
private SourceHUsCollection retrieveActiveSourceHusForHus(@NonNull final ProductId productId)
{ | final ImmutableList<I_M_HU> activeHUsMatchingProduct = handlingUnitsDAO.createHUQueryBuilder()
.setOnlyActiveHUs(true)
.setAllowEmptyStorage()
.addOnlyHUIds(getPPOrderSourceHUIds())
.addOnlyWithProductId(productId)
.createQuery()
.listImmutable(I_M_HU.class);
final ImmutableList<I_M_Source_HU> sourceHUs = sourceHUsService.retrieveSourceHuMarkers(extractHUIdsFromHUs(activeHUsMatchingProduct));
return SourceHUsCollection.builder()
.husThatAreFlaggedAsSource(activeHUsMatchingProduct)
.sourceHUs(sourceHUs)
.build();
}
private static ImmutableSet<HuId> extractHUIdsFromSourceHUs(final Collection<I_M_Source_HU> sourceHUs)
{
return sourceHUs.stream().map(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID())).collect(ImmutableSet.toImmutableSet());
}
private static ImmutableSet<HuId> extractHUIdsFromHUs(final Collection<I_M_HU> hus)
{
return hus.stream().map(I_M_HU::getM_HU_ID).map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\SourceHUsCollectionProvider.java | 2 |
请完成以下Java代码 | default List<String> getScopes() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.SCOPE);
}
/**
* Returns the type of the token {@code (token_type)}, for example {@code bearer}.
* @return the type of the token, for example {@code bearer}.
*/
@Nullable
default String getTokenType() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.TOKEN_TYPE);
}
/**
* Returns a timestamp {@code (exp)} indicating when the token expires
* @return a timestamp indicating when the token expires
*/
@Nullable
default Instant getExpiresAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.EXP);
}
/**
* Returns a timestamp {@code (iat)} indicating when the token was issued
* @return a timestamp indicating when the token was issued
*/
@Nullable
default Instant getIssuedAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.IAT);
}
/**
* Returns a timestamp {@code (nbf)} indicating when the token is not to be used
* before
* @return a timestamp indicating when the token is not to be used before
*/
@Nullable
default Instant getNotBefore() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.NBF);
}
/** | * Returns usually a machine-readable identifier {@code (sub)} of the resource owner
* who authorized the token
* @return usually a machine-readable identifier of the resource owner who authorized
* the token
*/
@Nullable
default String getSubject() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.SUB);
}
/**
* Returns the intended audience {@code (aud)} for the token
* @return the intended audience for the token
*/
@Nullable
default List<String> getAudience() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.AUD);
}
/**
* Returns the issuer {@code (iss)} of the token
* @return the issuer of the token
*/
@Nullable
default URL getIssuer() {
return getClaimAsURL(OAuth2TokenIntrospectionClaimNames.ISS);
}
/**
* Returns the identifier {@code (jti)} for the token
* @return the identifier for the token
*/
@Nullable
default String getId() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.JTI);
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2TokenIntrospectionClaimAccessor.java | 1 |
请完成以下Java代码 | public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {}
@Override
public String getId() {
return null;
}
@Override
public void setId(String id) {}
@Override
public boolean isInserted() {
return false;
}
@Override
public void setInserted(boolean inserted) {}
@Override
public boolean isUpdated() {
return false;
}
@Override
public void setUpdated(boolean updated) {}
@Override
public boolean isDeleted() {
return false;
}
@Override
public void setDeleted(boolean deleted) {}
@Override
public Object getPersistentState() {
return null;
}
@Override
public void setRevision(int revision) {}
@Override
public int getRevision() {
return 0;
}
@Override
public int getRevisionNext() {
return 0;
}
@Override
public void setName(String name) {}
@Override
public void setProcessInstanceId(String processInstanceId) {}
@Override
public void setExecutionId(String executionId) {} | @Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {}
@Override
public String getExecutionId() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final OrgId orgId = OrgId.ofRepoId(toOrgId);
final PInstanceId pinstanceId = getPinstanceId();
final ImmutableList<I_C_DocType> docTypes = docTypeBL.retrieveForSelection(pinstanceId);
for (final I_C_DocType docType : docTypes)
{
docTypeBL.cloneToOrg(docType, orgId);
}
return "@Copied@=" + docTypes.size();
}
@Override
@RunOutOfTrx
protected void prepare()
{
if (createSelection() <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
private int createSelection()
{
final IQueryBuilder<I_C_DocType> queryBuilder = createDocTypesQueryBuilder();
final PInstanceId adPInstanceId = getPinstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); | DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
return queryBuilder
.create()
.createSelection(adPInstanceId);
}
@NonNull
private IQueryBuilder<I_C_DocType> createDocTypesQueryBuilder()
{
final IQueryFilter<I_C_DocType> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
.createQueryBuilder(I_C_DocType.class, getCtx(), ITrx.TRXNAME_None)
.filter(userSelectionFilter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\process\C_DocType_Clone_Selection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class H2ConsoleAutoConfiguration {
private static final Log logger = LogFactory.getLog(H2ConsoleAutoConfiguration.class);
private final H2ConsoleProperties properties;
H2ConsoleAutoConfiguration(H2ConsoleProperties properties) {
this.properties = properties;
}
@Bean
ServletRegistrationBean<JakartaWebServlet> h2Console() {
String path = this.properties.getPath();
String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
ServletRegistrationBean<JakartaWebServlet> registration = new ServletRegistrationBean<>(new JakartaWebServlet(),
urlMapping);
configureH2ConsoleSettings(registration, this.properties.getSettings());
return registration;
}
@Bean
H2ConsoleLogger h2ConsoleLogger(ObjectProvider<DataSource> dataSources) {
return new H2ConsoleLogger(dataSources, this.properties.getPath());
}
private void configureH2ConsoleSettings(ServletRegistrationBean<JakartaWebServlet> registration,
Settings settings) {
if (settings.isTrace()) {
registration.addInitParameter("trace", "");
}
if (settings.isWebAllowOthers()) {
registration.addInitParameter("webAllowOthers", "");
}
if (settings.getWebAdminPassword() != null) {
registration.addInitParameter("webAdminPassword", settings.getWebAdminPassword());
}
}
static class H2ConsoleLogger {
H2ConsoleLogger(ObjectProvider<DataSource> dataSources, String path) {
if (logger.isInfoEnabled()) {
ClassLoader classLoader = getClass().getClassLoader();
withThreadContextClassLoader(classLoader, () -> log(getConnectionUrls(dataSources), path));
}
}
private void withThreadContextClassLoader(ClassLoader classLoader, Runnable action) {
ClassLoader previous = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader); | action.run();
}
finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
private List<String> getConnectionUrls(ObjectProvider<DataSource> dataSources) {
return dataSources.orderedStream(ObjectProvider.UNFILTERED)
.map(this::getConnectionUrl)
.filter(Objects::nonNull)
.toList();
}
private @Nullable String getConnectionUrl(DataSource dataSource) {
try (Connection connection = dataSource.getConnection()) {
return "'" + connection.getMetaData().getURL() + "'";
}
catch (Exception ex) {
return null;
}
}
private void log(List<String> urls, String path) {
if (!urls.isEmpty()) {
logger.info(LogMessage.format("H2 console available at '%s'. %s available at %s", path,
(urls.size() > 1) ? "Databases" : "Database", String.join(", ", urls)));
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-h2console\src\main\java\org\springframework\boot\h2console\autoconfigure\H2ConsoleAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Money getAmountToAllocateInitial()
{
return purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getPayAmt().negate();
}
@Override
public Money getAmountToAllocate()
{
return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().negate();
}
@Override
public void addAllocatedAmt(final Money allocatedAmtToAdd)
{
purchaseInvoicePayableDoc.addAllocatedAmounts(AllocationAmounts.ofPayAmt(allocatedAmtToAdd.negate()));
}
/**
* Check only the payAmt as that's the only value we are allocating. see {@link PurchaseInvoiceAsInboundPaymentDocumentWrapper#addAllocatedAmt(Money)}
*/
@Override
public boolean isFullyAllocated()
{
return purchaseInvoicePayableDoc.getAmountsToAllocate().getPayAmt().isZero();
}
/**
* Computes projected over under amt taking into account discount.
*
* @implNote for purchase invoices used as inbound payment, the discount needs to be subtracted from the open amount.
*/
@Override
public Money calculateProjectedOverUnderAmt(final Money amountToAllocate)
{
final Money discountAmt = purchaseInvoicePayableDoc.getAmountsToAllocateInitial().getDiscountAmt();
final Money openAmtWithDiscount = purchaseInvoicePayableDoc.getOpenAmtInitial().subtract(discountAmt);
final Money remainingOpenAmtWithDiscount = openAmtWithDiscount.subtract(purchaseInvoicePayableDoc.getTotalAllocatedAmount());
final Money adjustedAmountToAllocate = amountToAllocate.negate();
return remainingOpenAmtWithDiscount.subtract(adjustedAmountToAllocate);
}
@Override
public boolean canPay(@NonNull final PayableDocument payable)
{
// A purchase invoice can compensate only on a sales invoice
if (payable.getType() != PayableDocumentType.Invoice)
{
return false;
}
if (!payable.getSoTrx().isSales())
{ | return false;
}
// if currency differs, do not allow payment
return CurrencyId.equals(payable.getCurrencyId(), purchaseInvoicePayableDoc.getCurrencyId());
}
@Override
public CurrencyId getCurrencyId()
{
return purchaseInvoicePayableDoc.getCurrencyId();
}
@Override
public LocalDate getDate()
{
return purchaseInvoicePayableDoc.getDate();
}
@Override
public PaymentCurrencyContext getPaymentCurrencyContext()
{
return PaymentCurrencyContext.builder()
.paymentCurrencyId(purchaseInvoicePayableDoc.getCurrencyId())
.currencyConversionTypeId(purchaseInvoicePayableDoc.getCurrencyConversionTypeId())
.build();
}
@Override
public Money getPaymentDiscountAmt()
{
return purchaseInvoicePayableDoc.getAmountsToAllocate().getDiscountAmt();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PurchaseInvoiceAsInboundPaymentDocumentWrapper.java | 2 |
请完成以下Java代码 | public class ResourceNameUtil {
public static final String[] DMN_RESOURCE_SUFFIXES = new String[] { "dmn.xml", "dmn" };
public static final String[] DIAGRAM_SUFFIXES = new String[] { "png", "jpg", "gif", "svg" };
public static String stripDmnFileSuffix(String dmnFileResource) {
for (String suffix : DMN_RESOURCE_SUFFIXES) {
if (dmnFileResource.endsWith(suffix)) {
return dmnFileResource.substring(0, dmnFileResource.length() - suffix.length());
}
}
return dmnFileResource;
}
public static String getDecisionRequirementsDiagramResourceName(String dmnFileResource, String decisionKey, String diagramSuffix) {
String dmnFileResourceBase = stripDmnFileSuffix(dmnFileResource);
return dmnFileResourceBase + decisionKey + "." + diagramSuffix;
}
/**
* Finds the name of a resource for the diagram for a decision definition. Assumes that the decision definition's key and (DMN) resource name are already set.
*
* @return name of an existing resource, or null if no matching image resource is found in the resources.
*/
public static String getDecisionRequirementsDiagramResourceNameFromDeployment(
DecisionEntity decisionDefinition, Map<String, EngineResource> resources) {
if (StringUtils.isEmpty(decisionDefinition.getResourceName())) {
throw new IllegalStateException("Provided decision definition must have its resource name set.");
}
String dmnResourceBase = stripDmnFileSuffix(decisionDefinition.getResourceName());
String key = decisionDefinition.getKey(); | for (String diagramSuffix : DIAGRAM_SUFFIXES) {
String possibleName = dmnResourceBase + key + "." + diagramSuffix;
if (resources.containsKey(possibleName)) {
return possibleName;
}
possibleName = dmnResourceBase + diagramSuffix;
if (resources.containsKey(possibleName)) {
return possibleName;
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\ResourceNameUtil.java | 1 |
请完成以下Java代码 | public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPassword() { | return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
} | repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\entities\Person.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunningWork(runnable);
} else {
return scheduleShortRunningWork(runnable);
}
}
protected boolean scheduleShortRunningWork(Runnable runnable) {
EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
try {
EnhancedQueueExecutor.execute(runnable);
return true;
} catch (Exception e) {
// we must be able to schedule this
log.log(Level.WARNING, "Cannot schedule long running work.", e);
}
return false;
}
protected boolean scheduleLongRunningWork(Runnable runnable) {
final EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
boolean rejected = false;
try { | EnhancedQueueExecutor.execute(runnable);
} catch (RejectedExecutionException e) {
rejected = true;
} catch (Exception e) {
// if it fails for some other reason, log a warning message
long now = System.currentTimeMillis();
// only log every 60 seconds to prevent log flooding
if((now-lastWarningLogged) >= (60*1000)) {
log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e);
} else {
log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e);
}
}
return !rejected;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FooController {
private static final Logger logger = LoggerFactory.getLogger(FooController.class);
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private IFooService service;
public FooController() {
super();
}
// read - one
@GetMapping(value = "/{id}")
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
try {
final Foo resourceById = RestPreconditions.checkFound(service.findById(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}
catch (MyResourceNotFoundException exc) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Foo Not Found", exc);
}
} | // write
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) {
Preconditions.checkNotNull(resource);
final Foo foo = service.create(resource);
final Long idOfCreatedResource = foo.getId();
eventPublisher.publishEvent(new ResourceCreatedEvent(this, response, idOfCreatedResource));
return foo;
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest-2\src\main\java\com\baeldung\hateoas\web\controller\FooController.java | 2 |
请完成以下Java代码 | public java.lang.String getCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Code);
}
/** 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);
}
/**
* Type AD_Reference_ID=540047
* Reference name: AD_BoilerPlate_VarType
*/
public static final int TYPE_AD_Reference_ID=540047;
/** SQL = S */
public static final String TYPE_SQL = "S";
/** Rule Engine = R */
public static final String TYPE_RuleEngine = "R";
/** Set Type.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Type. | @return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java | 1 |
请完成以下Java代码 | public class ResolveTaskCmd extends NeedsActiveTaskCmd<Void> {
private static final long serialVersionUID = 1L;
protected Map<String, Object> variables;
protected Map<String, Object> transientVariables;
public ResolveTaskCmd(String taskId, Map<String, Object> variables) {
super(taskId);
this.variables = variables;
}
public ResolveTaskCmd(String taskId, Map<String, Object> variables, Map<String, Object> transientVariables) {
this(taskId, variables);
this.transientVariables = transientVariables;
}
@Override
protected Void execute(CommandContext commandContext, TaskEntity task) {
if (variables != null) { | task.setVariables(variables);
}
if (transientVariables != null) {
task.setTransientVariables(transientVariables);
}
task.resolve();
return null;
}
@Override
protected String getSuspendedTaskException() {
return "Cannot resolve a suspended task";
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\ResolveTaskCmd.java | 1 |
请完成以下Java代码 | public String toPermissionsKeyString()
{
String permissionsKeyStr = _permissionsKeyStr;
if (permissionsKeyStr == null)
{
_permissionsKeyStr = permissionsKeyStr = toPermissionsKeyString(roleId, userId, clientId, date);
}
return permissionsKeyStr;
}
public static long normalizeDate(final Instant date)
{
return normalizeDate(TimeUtil.asDate(date));
} | public static long normalizeDate(final Date date)
{
final long dateDayMillis = TimeUtil.truncToMillis(date, TimeUtil.TRUNC_DAY);
// Make sure we are we are caching only on day level, else would make no sense,
// and performance penalty would be quite big
// (i.e. retrieve and load and aggregate the whole shit everything we need to check something in permissions)
if (date == null || date.getTime() != dateDayMillis)
{
logger.warn("For performance purpose, make sure you providing a date which is truncated on day level: {}", date);
}
return dateDayMillis;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserRolePermissionsKey.java | 1 |
请完成以下Java代码 | public void refreshApplications() {
publisher.publishEvent(new RefreshInstancesEvent(this));
}
@GetMapping(path = "/applications/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity<Application>> application(@PathVariable("name") String name) {
return registry.getApplication(name).map(ResponseEntity::ok).defaultIfEmpty(ResponseEntity.notFound().build());
}
@GetMapping(path = "/applications", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<Application>> applicationsStream() {
return registry.getApplicationStream()
.map((application) -> ServerSentEvent.builder(application).build())
.mergeWith(ping());
} | @DeleteMapping(path = "/applications/{name}")
public Mono<ResponseEntity<Void>> unregister(@PathVariable("name") String name) {
log.debug("Unregister application with name '{}'", name);
return registry.deregister(name)
.collectList()
.map((deregistered) -> !deregistered.isEmpty() ? ResponseEntity.noContent().build()
: ResponseEntity.notFound().build());
}
@SuppressWarnings("unchecked")
private static <T> Flux<ServerSentEvent<T>> ping() {
return (Flux<ServerSentEvent<T>>) (Flux) PING_FLUX;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\ApplicationsController.java | 1 |
请完成以下Java代码 | protected Void executeCmd(CommandContext commandContext) {
ensureNotNull("user", user);
ensureWhitelistedResourceId(commandContext, "User", user.getId());
if (user instanceof UserEntity) {
validateUserEntity(commandContext);
}
IdentityOperationResult operationResult = commandContext
.getWritableIdentityProvider()
.saveUser(user);
commandContext.getOperationLogManager().logUserOperation(operationResult, user.getId());
return null; | }
private void validateUserEntity(CommandContext commandContext) {
if(shouldCheckPasswordPolicy(commandContext)) {
if(!((UserEntity) user).checkPasswordAgainstPolicy()) {
throw new ProcessEngineException("Password does not match policy");
}
}
}
protected boolean shouldCheckPasswordPolicy(CommandContext commandContext) {
return ((UserEntity) user).hasNewPassword() && !skipPasswordPolicy
&& commandContext.getProcessEngineConfiguration().isEnablePasswordPolicy();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SaveUserCmd.java | 1 |
请完成以下Java代码 | public static List<MSearchDefinition> getForCode(String transactionCode) throws SQLException {
List<MSearchDefinition> list = new ArrayList<MSearchDefinition>();
String sql = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
sql = "SELECT AD_SearchDefinition_ID FROM AD_SearchDefinition WHERE IsActive = 'Y' ";
if (transactionCode != null) {
sql += "AND UPPER(TransactionCode) = ?";
pstmt = DB.prepareStatement(sql, null);
pstmt.setString(1, transactionCode.toUpperCase());
} else {
sql += "AND IsDefault = 'Y'";
pstmt = DB.prepareStatement(sql, null);
}
if (pstmt != null) {
rs = pstmt.executeQuery();
while (rs.next()) {
MSearchDefinition msd = new MSearchDefinition(Env.getCtx(), rs.getInt(1), null);
if (msd.isActive()) {
list.add(msd);
}
}
}
DB.close(rs, pstmt);
return list;
}
public static boolean isValidTransactionCode(String transactionCode) throws SQLException {
boolean found = false; | if (transactionCode != null) {
String sql = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
sql = "SELECT AD_SearchDefinition_ID FROM AD_SearchDefinition WHERE UPPER(TransactionCode) = ? AND IsActive = 'Y'";
pstmt = DB.prepareStatement(sql, null);
pstmt.setString(1, transactionCode.toUpperCase());
if (pstmt != null) {
rs = pstmt.executeQuery();
while (rs.next()) {
found = true;
}
}
DB.close(rs, pstmt);
}
return found;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSearchDefinition.java | 1 |
请完成以下Java代码 | public class ResourceFinder {
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceFinder.class);
private ResourcePatternResolver resourceLoader;
public ResourceFinder(ResourcePatternResolver resourceLoader) {
this.resourceLoader = resourceLoader;
}
public List<Resource> discoverResources(ResourceFinderDescriptor resourceFinderDescriptor) throws IOException {
List<Resource> resources = new ArrayList<>();
if (resourceFinderDescriptor.shouldLookUpResources()) {
for (String suffix : resourceFinderDescriptor.getLocationSuffixes()) {
String path = resourceFinderDescriptor.getLocationPrefix() + suffix;
resources.addAll(asList(resourceLoader.getResources(path)));
} | if (resources.isEmpty()) {
LOGGER.info(resourceFinderDescriptor.getMsgForEmptyResources());
} else {
resourceFinderDescriptor.validate(resources);
List<String> foundResources = resources
.stream()
.map(Resource::getFilename)
.collect(Collectors.toList());
LOGGER.info(resourceFinderDescriptor.getMsgForResourcesFound(foundResources));
}
}
return resources;
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-resource-finder\src\main\java\org\activiti\spring\resources\ResourceFinder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ObservationRegistryConfigurer {
private final ObjectProvider<ObservationRegistryCustomizer<?>> customizers;
private final ObjectProvider<ObservationPredicate> observationPredicates;
private final ObjectProvider<GlobalObservationConvention<?>> observationConventions;
private final ObjectProvider<ObservationHandler<?>> observationHandlers;
private final ObjectProvider<ObservationHandlerGroup> observationHandlerGroups;
private final ObjectProvider<ObservationFilter> observationFilters;
ObservationRegistryConfigurer(ObjectProvider<ObservationRegistryCustomizer<?>> customizers,
ObjectProvider<ObservationPredicate> observationPredicates,
ObjectProvider<GlobalObservationConvention<?>> observationConventions,
ObjectProvider<ObservationHandler<?>> observationHandlers,
ObjectProvider<ObservationHandlerGroup> observationHandlerGroups,
ObjectProvider<ObservationFilter> observationFilters) {
this.customizers = customizers;
this.observationPredicates = observationPredicates;
this.observationConventions = observationConventions;
this.observationHandlers = observationHandlers;
this.observationHandlerGroups = observationHandlerGroups;
this.observationFilters = observationFilters;
}
void configure(ObservationRegistry registry) {
registerObservationPredicates(registry);
registerGlobalObservationConventions(registry);
registerHandlers(registry);
registerFilters(registry);
customize(registry);
}
private void registerHandlers(ObservationRegistry registry) {
ObservationHandlerGroups groups = new ObservationHandlerGroups(this.observationHandlerGroups.stream().toList());
List<ObservationHandler<?>> orderedHandlers = this.observationHandlers.orderedStream().toList();
groups.register(registry.observationConfig(), orderedHandlers); | }
private void registerObservationPredicates(ObservationRegistry registry) {
this.observationPredicates.orderedStream().forEach(registry.observationConfig()::observationPredicate);
}
private void registerGlobalObservationConventions(ObservationRegistry registry) {
this.observationConventions.orderedStream().forEach(registry.observationConfig()::observationConvention);
}
private void registerFilters(ObservationRegistry registry) {
this.observationFilters.orderedStream().forEach(registry.observationConfig()::observationFilter);
}
@SuppressWarnings("unchecked")
private void customize(ObservationRegistry registry) {
LambdaSafe.callbacks(ObservationRegistryCustomizer.class, this.customizers.orderedStream().toList(), registry)
.withLogger(ObservationRegistryConfigurer.class)
.invoke((customizer) -> customizer.customize(registry));
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationRegistryConfigurer.java | 2 |
请完成以下Java代码 | public int getAD_User_PrinterMatchingConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_PrinterMatchingConfig_ID);
}
@Override
public void setConfigHostKey (java.lang.String ConfigHostKey)
{
set_Value (COLUMNNAME_ConfigHostKey, ConfigHostKey);
}
@Override
public java.lang.String getConfigHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_ConfigHostKey);
}
@Override
public void setIsSharedPrinterConfig (boolean IsSharedPrinterConfig)
{
set_Value (COLUMNNAME_IsSharedPrinterConfig, Boolean.valueOf(IsSharedPrinterConfig));
}
@Override
public boolean isSharedPrinterConfig()
{
return get_ValueAsBoolean(COLUMNNAME_IsSharedPrinterConfig);
}
@Override
public org.compiere.model.I_C_Workplace getC_Workplace()
{
return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class);
}
@Override
public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace) | {
set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Config.java | 1 |
请完成以下Java代码 | public String getDeploymentName() {
return deploymentName;
}
public void setDeploymentName(String deploymentName) {
this.deploymentName = deploymentName;
}
public Resource[] getDeploymentResources() {
return deploymentResources;
}
public void setDeploymentResources(Resource[] deploymentResources) {
this.deploymentResources = deploymentResources;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public String getDeploymentMode() {
return deploymentMode;
}
public void setDeploymentMode(String deploymentMode) {
this.deploymentMode = deploymentMode;
} | /**
* Gets the {@link AutoDeploymentStrategy} for the provided mode. This method may be overridden to implement custom deployment strategies if required, but implementors should take care not to return
* <code>null</code>.
*
* @param mode
* the mode to get the strategy for
* @return the deployment strategy to use for the mode. Never <code>null</code>
*/
protected AutoDeploymentStrategy getAutoDeploymentStrategy(final String mode) {
AutoDeploymentStrategy result = defaultAutoDeploymentStrategy;
for (final AutoDeploymentStrategy strategy : deploymentStrategies) {
if (strategy.handlesMode(mode)) {
result = strategy;
break;
}
}
return result;
}
} | repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime; | }
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public static AttachmentDto fromAttachment(Attachment attachment) {
AttachmentDto dto = new AttachmentDto();
dto.id = attachment.getId();
dto.name = attachment.getName();
dto.type = attachment.getType();
dto.description = attachment.getDescription();
dto.taskId = attachment.getTaskId();
dto.url = attachment.getUrl();
dto.createTime = attachment.getCreateTime();
dto.removalTime = attachment.getRemovalTime();
dto.rootProcessInstanceId = attachment.getRootProcessInstanceId();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\AttachmentDto.java | 1 |
请完成以下Java代码 | public class ProcessVariables {
private static final Logger LOGGER = LoggerFactory.getLogger(ProcessVariables.class);
@Inject
private BusinessProcess businessProcess;
@Inject
private ProcessVariableMap processVariableMap;
protected String getVariableName(InjectionPoint ip) {
String variableName = ip.getAnnotated().getAnnotation(ProcessVariable.class).value();
if (variableName.length() == 0) {
variableName = ip.getMember().getName();
}
return variableName;
}
@Produces
@ProcessVariable
protected Object getProcessVariable(InjectionPoint ip) { | String processVariableName = getVariableName(ip);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Getting process variable '{}' from ProcessInstance[{}].", processVariableName, businessProcess.getProcessInstanceId());
}
return businessProcess.getVariable(processVariableName);
}
@Produces
@Named
protected Map<String, Object> processVariables() {
return processVariableMap;
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\ProcessVariables.java | 1 |
请完成以下Java代码 | public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public boolean isFailed() {
return failed;
}
@Override
public void setFailed(boolean failed) {
this.failed = failed;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getExecutionJson() {
return executionJson;
}
@Override
public void setExecutionJson(String executionJson) {
this.executionJson = executionJson;
}
@Override
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) { | this.decisionKey = decisionKey;
}
@Override
public String getDecisionName() {
return decisionName;
}
public void setDecisionName(String decisionName) {
this.decisionName = decisionName;
}
@Override
public String getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(String decisionVersion) {
this.decisionVersion = decisionVersion;
}
@Override
public String toString() {
return "HistoricDecisionExecutionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\HistoricDecisionExecutionEntityImpl.java | 1 |
请完成以下Java代码 | protected void prepare()
{
}
@Override
protected String doIt() throws Exception
{
expireLocks();
updateCCM_Bundle_Status();
return "Ok";
}
private int expireLocks()
{
final String sql = "UPDATE "+I_R_Group_Prospect.Table_Name+" SET "
+" "+I_R_Group_Prospect.COLUMNNAME_Locked+"=?"
+","+I_R_Group_Prospect.COLUMNNAME_LockedBy+"=?"
+","+I_R_Group_Prospect.COLUMNNAME_LockedDate+"=?"
+" WHERE "
+" "+I_R_Group_Prospect.COLUMNNAME_AD_Client_ID+"=?"
+" AND "+I_R_Group_Prospect.COLUMNNAME_Locked+"=?"
+" AND addDays("+I_R_Group_Prospect.COLUMNNAME_LockedDate+",?) > getDate()"
;
int expireDays = (int)Math.round( (double)MRGroupProspect.LOCK_EXPIRE_MIN / (double)60 + 0.5 );
int count = DB.executeUpdateAndThrowExceptionOnFail(sql,
new Object[]{false, null, null, getAD_Client_ID(), true, expireDays},
get_TrxName());
addLog("Unlocked #"+count); | return count;
}
private void updateCCM_Bundle_Status()
{
int[] ids = new Query(getCtx(), X_R_Group.Table_Name, null, get_TrxName())
//.setOnlyActiveRecords(true) // check all bundles
.setClient_ID()
.getIDs();
int count = 0;
for (int R_Group_ID : ids)
{
boolean updated = BundleUtil.updateCCM_Bundle_Status(R_Group_ID, get_TrxName());
if (updated)
count++;
}
addLog("@Updated@ @CCM_Bundle_Status@ #"+count);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\process\CallCenterDailyMaintenance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OtherFilePreviewImpl implements FilePreview {
@Override
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
return this.notSupportedFile(model, fileAttribute, "系统还不支持该格式文件的在线预览");
}
/**
* 通用的预览失败,导向到不支持的文件响应页面
*
* @return 页面
*/
public String notSupportedFile(Model model, FileAttribute fileAttribute, String errMsg) {
return this.notSupportedFile(model, fileAttribute.getSuffix(), errMsg);
}
/**
* 通用的预览失败,导向到不支持的文件响应页面
* | * @return 页面
*/
public String notSupportedFile(Model model, String errMsg) {
return this.notSupportedFile(model, "未知", errMsg);
}
/**
* 通用的预览失败,导向到不支持的文件响应页面
*
* @return 页面
*/
public String notSupportedFile(Model model, String fileType, String errMsg) {
model.addAttribute("fileType", KkFileUtils.htmlEscape(fileType));
model.addAttribute("msg", KkFileUtils.htmlEscape(errMsg));
return NOT_SUPPORTED_FILE_PAGE;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\impl\OtherFilePreviewImpl.java | 2 |
请完成以下Java代码 | public class InEnumValidator implements ConstraintValidator<InEnum, Integer> {
/**
* 值数组
*/
private Set<Integer> values;
@Override
public void initialize(InEnum annotation) {
IntArrayValuable[] values = annotation.value().getEnumConstants();
if (values.length == 0) {
this.values = Collections.emptySet();
} else {
this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toSet());
}
} | @Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
// 校验通过
if (values.contains(value)) {
return true;
}
// 校验不通过,自定义提示语句(因为,注解上的 value 是枚举类,无法获得枚举类的实际值)
context.disableDefaultConstraintViolation(); // 禁用默认的 message 的值
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()
.replaceAll("\\{value}", values.toString())).addConstraintViolation(); // 重新添加错误提示语句
return false;
}
} | repos\SpringBoot-Labs-master\lab-22\lab-22-validation-01\src\main\java\cn\iocoder\springboot\lab22\validation\core\validator\InEnumValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTruststore() {
return this.truststore;
}
public void setTruststore(String truststore) {
this.truststore = truststore;
}
public KeyStoreProperties getTruststoreConfig() {
return this.truststoreConfig;
}
public boolean isWebRequireAuthentication() {
return this.webRequireAuthentication;
}
public void setWebRequireAuthentication(boolean webRequireAuthentication) {
this.webRequireAuthentication = webRequireAuthentication;
}
public static class KeyStoreProperties {
private String password;
private String type;
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
}
public static class SslCertificateProperties {
@NestedConfigurationProperty
private SslCertificateAliasProperties alias = new SslCertificateAliasProperties();
public SslCertificateAliasProperties getAlias() {
return this.alias;
}
}
public static class SslCertificateAliasProperties {
private String all;
private String cluster;
private String defaultAlias;
private String gateway;
private String jmx;
private String locator;
private String server;
private String web;
public String getAll() {
return this.all;
}
public void setAll(String all) { | this.all = all;
}
public String getCluster() {
return this.cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getDefaultAlias() {
return this.defaultAlias;
}
public void setDefaultAlias(String defaultAlias) {
this.defaultAlias = defaultAlias;
}
public String getGateway() {
return this.gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
}
public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
}
public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ImmutableList<I_PP_Order_BOMLine> getOrderBOMLines(@NonNull final PPOrderId ppOrderId) {return ImmutableList.copyOf(ppOrderBOMBL.getOrderBOMLines(ppOrderId));}
@NonNull
public ZonedDateTime getDateStartSchedule(@NonNull final I_PP_Order ppOrder)
{
return InstantAndOrgId.ofTimestamp(ppOrder.getDateStartSchedule(), ppOrder.getAD_Org_ID()).toZonedDateTime(orgDAO::getTimeZone);
}
public PPOrderQuantities getQuantities(@NonNull final I_PP_Order order) {return ppOrderBOMBL.getQuantities(order);}
public OrderBOMLineQuantities getQuantities(@NonNull final I_PP_Order_BOMLine orderBOMLine) {return ppOrderBOMBL.getQuantities(orderBOMLine);}
public ImmutableListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> getIssueSchedules(@NonNull final PPOrderId ppOrderId)
{
return Multimaps.index(ppOrderIssueScheduleService.getByOrderId(ppOrderId), PPOrderIssueSchedule::getPpOrderBOMLineId);
}
public ImmutableAttributeSet getImmutableAttributeSet(final AttributeSetInstanceId asiId)
{
return asiBL.getImmutableAttributeSetById(asiId);
}
public Optional<HuId> getHuIdByQRCodeIfExists(@NonNull final HUQRCode qrCode)
{
return huQRCodeService.getHuIdByQRCodeIfExists(qrCode);
}
public void assignQRCodeForReceiptHU(@NonNull final HUQRCode qrCode, @NonNull final HuId huId)
{
final boolean ensureSingleAssignment = true;
huQRCodeService.assign(qrCode, huId, ensureSingleAssignment);
}
public HUQRCode getFirstQRCodeByHuId(@NonNull final HuId huId)
{
return huQRCodeService.getFirstQRCodeByHuId(huId);
}
public Quantity getHUCapacity(
@NonNull final HuId huId,
@NonNull final ProductId productId,
@NonNull final I_C_UOM uom)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
return handlingUnitsBL
.getStorageFactory() | .getStorage(hu)
.getQuantity(productId, uom);
}
@NonNull
public ValidateLocatorInfo getValidateSourceLocatorInfo(final @NonNull PPOrderId ppOrderId)
{
final ImmutableList<LocatorInfo> sourceLocatorList = getSourceLocatorIds(ppOrderId)
.stream()
.map(locatorId -> {
final String caption = getLocatorName(locatorId);
return LocatorInfo.builder()
.id(locatorId)
.caption(caption)
.qrCode(LocatorQRCode.builder()
.locatorId(locatorId)
.caption(caption)
.build())
.build();
})
.collect(ImmutableList.toImmutableList());
return ValidateLocatorInfo.ofSourceLocatorList(sourceLocatorList);
}
@NonNull
public Optional<UomId> getCatchWeightUOMId(@NonNull final ProductId productId)
{
return productBL.getCatchUOMId(productId);
}
@NonNull
private ImmutableSet<LocatorId> getSourceLocatorIds(@NonNull final PPOrderId ppOrderId)
{
final ImmutableSet<HuId> huIds = sourceHUService.getSourceHUIds(ppOrderId);
return handlingUnitsBL.getLocatorIds(huIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobLoaderAndSaverSupportingServices.java | 2 |
请完成以下Java代码 | public static VariableService getVariableService(CommandContext commandContext) {
VariableService variableService = null;
VariableServiceConfiguration variableServiceConfiguration = getVariableServiceConfiguration(commandContext);
if (variableServiceConfiguration != null) {
variableService = variableServiceConfiguration.getVariableService();
}
return variableService;
}
// IDM ENGINE
public static IdmEngineConfigurationApi getIdmEngineConfiguration() {
return getIdmEngineConfiguration(getCommandContext());
}
public static IdmEngineConfigurationApi getIdmEngineConfiguration(CommandContext commandContext) {
return (IdmEngineConfigurationApi) commandContext.getEngineConfigurations().get(EngineConfigurationConstants.KEY_IDM_ENGINE_CONFIG);
}
public static IdmIdentityService getIdmIdentityService() {
IdmIdentityService identityService = null;
IdmEngineConfigurationApi idmEngineConfiguration = getIdmEngineConfiguration();
if (idmEngineConfiguration != null) {
identityService = idmEngineConfiguration.getIdmIdentityService();
}
return identityService;
}
public static IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return getIdentityLinkServiceConfiguration(getCommandContext());
}
public static IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration(CommandContext commandContext) {
return getAppEngineConfiguration(commandContext).getIdentityLinkServiceConfiguration();
}
public static IdentityLinkService getIdentityLinkService() {
return getIdentityLinkService(getCommandContext());
}
public static IdentityLinkService getIdentityLinkService(CommandContext commandContext) {
return getIdentityLinkServiceConfiguration(commandContext).getIdentityLinkService(); | }
public static VariableServiceConfiguration getVariableServiceConfiguration() {
return getVariableServiceConfiguration(getCommandContext());
}
public static VariableServiceConfiguration getVariableServiceConfiguration(CommandContext commandContext) {
return getAppEngineConfiguration(commandContext).getVariableServiceConfiguration();
}
public static DbSqlSession getDbSqlSession() {
return getDbSqlSession(getCommandContext());
}
public static DbSqlSession getDbSqlSession(CommandContext commandContext) {
return commandContext.getSession(DbSqlSession.class);
}
public static EntityCache getEntityCache() {
return getEntityCache(getCommandContext());
}
public static EntityCache getEntityCache(CommandContext commandContext) {
return commandContext.getSession(EntityCache.class);
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\util\CommandContextUtil.java | 1 |
请完成以下Java代码 | public static DocumentSaveStatus notSavedJustCreated()
{
return STATUS_NotSavedJustCreated;
}
public static DocumentSaveStatus savedJustLoaded()
{
return STATUS_SavedJustLoaded;
}
private static final DocumentSaveStatus STATUS_Saved = builder().hasChangesToBeSaved(false).isPresentInDatabase(true).error(false).build();
private static final DocumentSaveStatus STATUS_Deleted = builder().hasChangesToBeSaved(false).isPresentInDatabase(false).deleted(true).error(false).build();
private static final DocumentSaveStatus STATUS_NotSavedJustCreated = builder().hasChangesToBeSaved(true).isPresentInDatabase(false).error(false).reason(TranslatableStrings.anyLanguage("new")).build();
private static final DocumentSaveStatus STATUS_SavedJustLoaded = builder().hasChangesToBeSaved(false).isPresentInDatabase(true).error(false).reason(TranslatableStrings.anyLanguage("just loaded")).build();
private final boolean hasChangesToBeSaved;
private final boolean isPresentInDatabase;
private final boolean deleted;
private final boolean error;
@Nullable private final ITranslatableString reason;
@Nullable private final transient Exception exception;
private final boolean saved; // computed
@Builder
private DocumentSaveStatus(
final boolean hasChangesToBeSaved,
final boolean isPresentInDatabase,
final boolean deleted,
final boolean error,
@Nullable final ITranslatableString reason,
@Nullable final Exception exception)
{
this.hasChangesToBeSaved = hasChangesToBeSaved;
this.isPresentInDatabase = isPresentInDatabase;
this.deleted = deleted;
this.error = error;
this.reason = !TranslatableStrings.isBlank(reason) ? reason : null;
this.exception = exception;
this.saved = !this.hasChangesToBeSaved && this.isPresentInDatabase && !this.error && !this.deleted;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("saved", saved ? true : null)
.add("presentInDatabase", isPresentInDatabase ? true : null)
.add("deleted", deleted ? true : null)
.add("hasChangesToBeSaved", hasChangesToBeSaved ? true : null)
.add("error", error ? true : null)
.add("reason", reason)
.toString();
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isSavedOrDeleted() | {
return isSaved() || isDeleted();
}
public DocumentSaveStatus throwIfError()
{
if (!error)
{
return this;
}
if (exception != null)
{
throw AdempiereException.wrapIfNeeded(exception);
}
else
{
throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Error"));
}
}
public void throwIfNotSavedNorDelete()
{
if (isSavedOrDeleted())
{
return;
}
if (exception != null)
{
throw AdempiereException.wrapIfNeeded(exception);
}
else
{
throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Not saved"));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentSaveStatus.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure(AbstractEngineConfiguration engineConfiguration) {
if (idmEngineConfiguration == null) {
idmEngineConfiguration = new StandaloneIdmEngineConfiguration();
}
initialiseCommonProperties(engineConfiguration, idmEngineConfiguration);
initEngine();
initServiceConfigurations(engineConfiguration, idmEngineConfiguration);
}
@Override
protected IdmEngine buildEngine() {
return idmEngineConfiguration.buildEngine();
}
@Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
} | @Override
protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
}
public IdmEngineConfiguration getIdmEngineConfiguration() {
return idmEngineConfiguration;
}
public IdmEngineConfigurator setIdmEngineConfiguration(IdmEngineConfiguration idmEngineConfiguration) {
this.idmEngineConfiguration = idmEngineConfiguration;
return this;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine-configurator\src\main\java\org\flowable\idm\engine\configurator\IdmEngineConfigurator.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalReferenceDispatchMessageProcessor implements Processor
{
@Override
public void process(final Exchange exchange) throws Exception
{
final JsonExternalReferenceLookupResponse jsonExternalReferenceLookupResponse = exchange.getIn().getBody(JsonExternalReferenceLookupResponse.class);
final ExportExternalReferenceRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_EXTERNAL_REFERENCE_CONTEXT, ExportExternalReferenceRouteContext.class);
final String payload = JsonObjectMapperHolder.sharedJsonObjectMapper()
.writeValueAsString(jsonExternalReferenceLookupResponse);
final JsonRabbitMQHttpMessage jsonRabbitMQHttpMessage = JsonRabbitMQHttpMessage.builder()
.routingKey(routeContext.getRoutingKey())
.jsonRabbitMQProperties(getDefaultRabbitMQProperties())
.payload(payload)
.payloadEncoding(RABBIT_MQ_PAYLOAD_ENCODING)
.build(); | final DispatchMessageRequest dispatchMessageRequest = DispatchMessageRequest.builder()
.url(routeContext.getRemoteUrl())
.authToken(routeContext.getAuthToken())
.message(jsonRabbitMQHttpMessage)
.build();
exchange.getIn().setBody(dispatchMessageRequest);
}
@NonNull
private JsonRabbitMQProperties getDefaultRabbitMQProperties()
{
return JsonRabbitMQProperties.builder()
.delivery_mode(RABBITMQ_PROPS_PERSISTENT_DELIVERY_MODE)
.header(RABBITMQ_HEADERS_SUBJECT, RABBITMQ_HEADERS_METASFRESH_EXTERNAL_REFERENCE_SYNC)
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-rabbitmq\src\main\java\de\metas\camel\externalsystems\rabbitmq\externalreference\processor\ExternalReferenceDispatchMessageProcessor.java | 2 |
请完成以下Java代码 | public String toString()
{
final ToStringHelper toStringHelper = MoreObjects.toStringHelper(this)
.add("timing", timing)
.add("active", active)
.add("invokeMethodJustOnce", invokeMethodJustOnce)
.add("registerWeakly", registerWeakly);
if (additionalToStringInfo != null)
{
toStringHelper.add("additionalToStringInfo", additionalToStringInfo.get());
}
return toStringHelper.toString();
}
/**
* Deactivate this listener, so that it won't be invoked any further.
* <p>
* Method can be called when this listener shall be ignored from now on.<br>
* Useful for example if the after-commit code shall be invoked only <b>once</b>, even if there are multiple commits.
*/
public void deactivate()
{
active = false;
}
/**
* @return <code>true</code>, unless {@link #deactivate()} has been called at least once. from there on, it always returns <code>false</code>.
*/
public boolean isActive()
{
return active;
}
}
default RegisterListenerRequest newEventListener(@NonNull final TrxEventTiming timing)
{
return new RegisterListenerRequest(this, timing);
}
/**
* This method shall only be called by the framework. Instead, call {@link #newEventListener(TrxEventTiming)}
* and be sure to call {@link RegisterListenerRequest#registerHandlingMethod(EventHandlingMethod)} at the end.
*/
void registerListener(RegisterListenerRequest listener);
boolean canRegisterOnTiming(TrxEventTiming timing); | default void runAfterCommit(@NonNull final Runnable runnable)
{
newEventListener(TrxEventTiming.AFTER_COMMIT)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> runnable.run());
}
default void runBeforeCommit(@NonNull final Runnable runnable)
{
newEventListener(TrxEventTiming.BEFORE_COMMIT)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> runnable.run());
}
default void runAfterRollback(@NonNull final Runnable runnable)
{
newEventListener(TrxEventTiming.AFTER_ROLLBACK)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> runnable.run());
}
default void runAfterClose(@NonNull final Consumer<ITrx> runnable)
{
newEventListener(TrxEventTiming.AFTER_CLOSE)
.invokeMethodJustOnce(true)
.registerHandlingMethod(runnable::accept);
}
/**
* This method shall only be called by the framework.
*/
void fireBeforeCommit(ITrx trx);
/**
* This method shall only be called by the framework.
*/
void fireAfterCommit(ITrx trx);
/**
* This method shall only be called by the framework.
*/
void fireAfterRollback(ITrx trx);
/**
* This method shall only be called by the framework.
*/
void fireAfterClose(ITrx trx);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\ITrxListenerManager.java | 1 |
请完成以下Java代码 | public void setPosition(long[] position) {
this.position = position;
}
/**
* Sets the {@link #speed}.
*
* @param speed
* the new {@link #speed}
*/
public void setSpeed(long[] speed) {
this.speed = speed;
}
/**
* Sets the {@link #fitness}.
*
* @param fitness
* the new {@link #fitness}
*/
public void setFitness(double fitness) {
this.fitness = fitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
temp = Double.doubleToLongBits(fitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(position);
result = prime * result + Arrays.hashCode(speed);
return result;
}
/* | * (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
return false;
if (!Arrays.equals(position, other.position))
return false;
if (!Arrays.equals(speed, other.speed))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Particle.java | 1 |
请完成以下Java代码 | /* package */class CompositeAggregationKeyValueHandler implements IAggregationKeyValueHandler<Object>
{
/**
* IMPORTANT:</b> we need the handlers to have a fixed ordering. We use their class names to achieve this.
*/
public final Set<IAggregationKeyValueHandler<Object>> aggregationKeyValueHandlers = new TreeSet<IAggregationKeyValueHandler<Object>>(new Comparator<IAggregationKeyValueHandler<Object>>()
{
@Override
public int compare(final IAggregationKeyValueHandler<Object> o1, final IAggregationKeyValueHandler<Object> o2)
{
// note: we won't add null handlers to the set, but just to be sure we explicitly avoid an NPE
final String o1ClassName = o1 == null ? "<null>" : o1.getClass().getName();
final String o2ClassName = o2 == null ? "<null>" : o2.getClass().getName();
return new CompareToBuilder().append(o1ClassName, o2ClassName).build();
}
});
public void registerAggregationKeyValueHandler(final IAggregationKeyValueHandler<Object> aggregationKeyValueHandler)
{
if (aggregationKeyValueHandler == null)
{
return; // nothing to do (should not happen)
} | aggregationKeyValueHandlers.add(aggregationKeyValueHandler);
}
@Override
public List<Object> getValues(@NonNull final Object model)
{
final List<Object> values = new ArrayList<Object>();
for (final IAggregationKeyValueHandler<Object> aggregationKeyValueHandler : aggregationKeyValueHandlers)
{
final List<Object> aggregationKeyValues = aggregationKeyValueHandler.getValues(model);
values.addAll(aggregationKeyValues);
}
return values;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\agg\key\impl\CompositeAggregationKeyValueHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class JwtConverterConfiguration {
private final OAuth2ResourceServerProperties.Jwt properties;
JwtConverterConfiguration(OAuth2ResourceServerProperties properties) {
this.properties = properties.getJwt();
}
@Bean
JwtAuthenticationConverter getJwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
PropertyMapper map = PropertyMapper.get();
map.from(this.properties.getAuthorityPrefix()).to(grantedAuthoritiesConverter::setAuthorityPrefix);
map.from(this.properties.getAuthoritiesClaimDelimiter())
.to(grantedAuthoritiesConverter::setAuthoritiesClaimDelimiter);
map.from(this.properties.getAuthoritiesClaimName())
.to(grantedAuthoritiesConverter::setAuthoritiesClaimName);
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
map.from(this.properties.getPrincipalClaimName()).to(jwtAuthenticationConverter::setPrincipalClaimName);
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return jwtAuthenticationConverter;
}
}
private static class JwtConverterPropertiesCondition extends AnyNestedCondition {
JwtConverterPropertiesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authority-prefix") | static class OnAuthorityPrefix {
}
@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.principal-claim-name")
static class OnPrincipalClaimName {
}
@ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-name")
static class OnAuthoritiesClaimName {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\servlet\OAuth2ResourceServerJwtConfiguration.java | 2 |
请完成以下Java代码 | public class PasswordPolicyRuleDto {
protected String placeholder;
protected Map<String, String> parameter;
// transformers
public PasswordPolicyRuleDto(PasswordPolicyRule rule) {
this.placeholder = rule.getPlaceholder();
this.parameter = rule.getParameters();
}
// getters / setters
public String getPlaceholder() {
return placeholder; | }
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
public Map<String, String> getParameter() {
return parameter;
}
public void setParameter(Map<String, String> parameter) {
this.parameter = parameter;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\PasswordPolicyRuleDto.java | 1 |
请完成以下Java代码 | public StreamObserver<Stock> clientSideStreamingGetStatisticsOfStocks(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
int count;
double price = 0.0;
StringBuffer sb = new StringBuffer();
@Override
public void onNext(Stock stock) {
count++;
price = +fetchStockPriceBid(stock);
sb.append(":")
.append(stock.getTickerSymbol());
}
@Override
public void onCompleted() {
responseObserver.onNext(StockQuote.newBuilder()
.setPrice(price / count)
.setDescription("Statistics-" + sb.toString())
.build());
responseObserver.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.warn("error:{}", t.getMessage());
}
};
}
@Override
public StreamObserver<Stock> bidirectionalStreamingGetListsStockQuotes(final StreamObserver<StockQuote> responseObserver) {
return new StreamObserver<Stock>() {
@Override
public void onNext(Stock request) {
for (int i = 1; i <= 5; i++) {
StockQuote stockQuote = StockQuote.newBuilder()
.setPrice(fetchStockPriceBid(request)) | .setOfferNumber(i)
.setDescription("Price for stock:" + request.getTickerSymbol())
.build();
responseObserver.onNext(stockQuote);
}
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
@Override
public void onError(Throwable t) {
logger.warn("error:{}", t.getMessage());
}
};
}
}
private static double fetchStockPriceBid(Stock stock) {
return stock.getTickerSymbol()
.length()
+ ThreadLocalRandom.current()
.nextDouble(-0.1d, 0.1d);
}
} | repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\streaming\StockServer.java | 1 |
请完成以下Java代码 | public void merge(ConfigurableEnvironment parent) {
for (PropertySource<?> ps : parent.getPropertySources()) {
if (!this.getPropertySources().contains(ps.getName())) {
this.getPropertySources().addLast(ps);
}
}
super.merge(parent);
}
/** {@inheritDoc} */
@Override
public MutablePropertySources getPropertySources() {
return this.encryptablePropertySources;
}
/** {@inheritDoc} */
@Override
public MutablePropertySources getOriginalPropertySources() { | return super.getPropertySources();
}
/** {@inheritDoc} */
@Override
public void setEncryptablePropertySources(MutablePropertySources propertySources) {
this.encryptablePropertySources = propertySources;
((MutableConfigurablePropertyResolver)this.getPropertyResolver()).setPropertySources(propertySources);
}
/** {@inheritDoc} */
@Override
protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
return EnvironmentInitializer.createPropertyResolver(propertySources);
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\environment\StandardEncryptableEnvironment.java | 1 |
请完成以下Java代码 | public static PickingJobLineId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PickingJobLineId(repoId) : null;
}
@NonNull
@JsonCreator
public static PickingJobLineId ofString(@NonNull final String string)
{
try
{
return ofRepoId(Integer.parseInt(string));
}
catch (final Exception ex)
{
throw new AdempiereException("Invalid id string: `" + string + "`", ex);
}
}
@Nullable | public static PickingJobLineId ofNullableString(@Nullable final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
return stringNorm != null ? ofString(stringNorm) : null;
}
public String getAsString() {return String.valueOf(getRepoId());}
public static boolean equals(@Nullable final PickingJobLineId id1, @Nullable final PickingJobLineId id2) {return Objects.equals(id1, id2);}
public TableRecordReference toTableRecordReference()
{
return TableRecordReference.of(I_M_Picking_Job_Line.Table_Name, repoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobLineId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String get(String k) {
return null;
}
@Override
public boolean enabled() {
return obtain(GraphiteProperties::isEnabled, GraphiteConfig.super::enabled);
}
@Override
public Duration step() {
return obtain(GraphiteProperties::getStep, GraphiteConfig.super::step);
}
@Override
public TimeUnit rateUnits() {
return obtain(GraphiteProperties::getRateUnits, GraphiteConfig.super::rateUnits);
}
@Override
public TimeUnit durationUnits() {
return obtain(GraphiteProperties::getDurationUnits, GraphiteConfig.super::durationUnits);
}
@Override
public String host() {
return obtain(GraphiteProperties::getHost, GraphiteConfig.super::host);
}
@Override | public int port() {
return obtain(GraphiteProperties::getPort, GraphiteConfig.super::port);
}
@Override
public GraphiteProtocol protocol() {
return obtain(GraphiteProperties::getProtocol, GraphiteConfig.super::protocol);
}
@Override
public boolean graphiteTagsEnabled() {
return obtain(GraphiteProperties::getGraphiteTagsEnabled, GraphiteConfig.super::graphiteTagsEnabled);
}
@Override
public String[] tagsAsPrefix() {
return obtain(GraphiteProperties::getTagsAsPrefix, GraphiteConfig.super::tagsAsPrefix);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\graphite\GraphitePropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public void setContext(CaseFileItem caseFileItem) {
contextRefAttribute.setReferenceTargetElement(this, caseFileItem);
}
public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression condition) {
conditionChild.setChild(this, condition);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(RequiredRule.class, CMMN_ELEMENT_REQUIRED_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<RequiredRule>() {
public RequiredRule newInstance(ModelTypeInstanceContext instanceContext) {
return new RequiredRuleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) | .build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionChild = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\RequiredRuleImpl.java | 1 |
请完成以下Java代码 | public Iterable<Golfer> getPlayers() {
return Collections.unmodifiableSet(this.players);
}
public boolean isFinished() {
for (Pairing pairing : this) {
if (pairing.getHole() < 18) {
return false;
}
}
return true;
}
public GolfTournament at(GolfCourse golfCourse) {
Assert.notNull(golfCourse, "Golf Course must not be null");
this.golfCourse = golfCourse;
return this;
}
public GolfTournament buildPairings() {
Assert.notEmpty(this.players,
() -> String.format("No players are registered for this golf tournament [%s]", getName()));
Assert.isTrue(this.players.size() % 2 == 0,
() -> String.format("An even number of players must register to play this golf tournament [%s]; currently at [%d]",
getName(), this.players.size()));
List<Golfer> playersToPair = new ArrayList<>(this.players);
Collections.shuffle(playersToPair);
for (int index = 0, size = playersToPair.size(); index < size; index += 2) {
this.pairings.add(Pairing.of(playersToPair.get(index), playersToPair.get(index + 1)));
}
return this;
}
@Override
public Iterator<GolfTournament.Pairing> iterator() {
return Collections.unmodifiableList(this.pairings).iterator();
}
public GolfTournament play() {
Assert.state(this.golfCourse != null, "No golf course was declared");
Assert.state(!this.players.isEmpty(), "Golfers must register to play before the golf tournament is played");
Assert.state(!this.pairings.isEmpty(), "Pairings must be formed before the golf tournament is played");
Assert.state(!isFinished(), () -> String.format("Golf tournament [%s] has already been played", getName()));
return this; | }
public GolfTournament register(Golfer... players) {
return register(Arrays.asList(ArrayUtils.nullSafeArray(players, Golfer.class)));
}
public GolfTournament register(Iterable<Golfer> players) {
StreamSupport.stream(CollectionUtils.nullSafeIterable(players).spliterator(), false)
.filter(Objects::nonNull)
.forEach(this.players::add);
return this;
}
@Getter
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor(staticName = "of")
public static class Pairing {
private final AtomicBoolean signedScorecard = new AtomicBoolean(false);
@NonNull
private final Golfer playerOne;
@NonNull
private final Golfer playerTwo;
public synchronized void setHole(int hole) {
this.playerOne.setHole(hole);
this.playerTwo.setHole(hole);
}
public synchronized int getHole() {
return getPlayerOne().getHole();
}
public boolean in(@NonNull Golfer golfer) {
return this.playerOne.equals(golfer) || this.playerTwo.equals(golfer);
}
public synchronized int nextHole() {
return getHole() + 1;
}
public synchronized boolean signScorecard() {
return getHole() >= 18
&& this.signedScorecard.compareAndSet(false, true);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\GolfTournament.java | 1 |
请完成以下Java代码 | public void createFruit(
@NotNull(message = "Fruit name must not be null") @FormParam("name") String name,
@NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) {
Fruit fruit = new Fruit(name, colour);
SimpleStorageService.storeFruit(fruit);
}
@PUT
@Path("/update")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void updateFruit(@SerialNumber @FormParam("serial") String serial) {
Fruit fruit = new Fruit();
fruit.setSerial(serial);
SimpleStorageService.storeFruit(fruit);
}
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
public void createFruit(@Valid Fruit fruit) {
SimpleStorageService.storeFruit(fruit);
}
@POST
@Path("/created")
@Consumes(MediaType.APPLICATION_JSON)
public Response createNewFruit(@Valid Fruit fruit) {
String result = "Fruit saved : " + fruit;
return Response.status(Response.Status.CREATED.getStatusCode())
.entity(result) | .build();
}
@GET
@Valid
@Produces(MediaType.APPLICATION_JSON)
@Path("/search/{name}")
public Fruit findFruitByName(@PathParam("name") String name) {
return SimpleStorageService.findByName(name);
}
@GET
@Produces(MediaType.TEXT_HTML)
@Path("/exception")
@Valid
public Fruit exception() {
Fruit fruit = new Fruit();
fruit.setName("a");
fruit.setColour("b");
return fruit;
}
} | repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\rest\FruitResource.java | 1 |
请完成以下Java代码 | public ComplexGateway newInstance(ModelTypeInstanceContext instanceContext) {
return new ComplexGatewayImpl(instanceContext);
}
});
defaultAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_DEFAULT)
.idAttributeReference(SequenceFlow.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
activationConditionChild = sequenceBuilder.element(ActivationCondition.class)
.build();
typeBuilder.build();
}
public ComplexGatewayImpl(ModelTypeInstanceContext context) {
super(context);
}
@Override
public ComplexGatewayBuilder builder() {
return new ComplexGatewayBuilder((BpmnModelInstance) modelInstance, this); | }
public SequenceFlow getDefault() {
return defaultAttribute.getReferenceTargetElement(this);
}
public void setDefault(SequenceFlow defaultFlow) {
defaultAttribute.setReferenceTargetElement(this, defaultFlow);
}
public ActivationCondition getActivationCondition() {
return activationConditionChild.getChild(this);
}
public void setActivationCondition(ActivationCondition activationCondition) {
activationConditionChild.setChild(this, activationCondition);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ComplexGatewayImpl.java | 1 |
请完成以下Java代码 | protected final PaymentsToReconcileView getView()
{
return PaymentsToReconcileView.cast(super.getView());
}
@Override
protected final PaymentToReconcileRow getSingleSelectedRow()
{
return PaymentToReconcileRow.cast(super.getSingleSelectedRow());
}
@Override
protected final Stream<PaymentToReconcileRow> streamSelectedRows()
{
return super.streamSelectedRows()
.map(PaymentToReconcileRow::cast);
}
protected final List<PaymentToReconcileRow> getSelectedPaymentToReconcileRows()
{
return streamSelectedRows()
.collect(ImmutableList.toImmutableList());
}
protected ViewId getBanksStatementReconciliationViewId()
{
return getView().getBankStatementViewId();
}
protected final BankStatementReconciliationView getBanksStatementReconciliationView()
{
final ViewId bankStatementViewId = getBanksStatementReconciliationViewId();
final IViewsRepository viewsRepo = getViewsRepo();
return BankStatementReconciliationView.cast(viewsRepo.getView(bankStatementViewId));
}
protected final void invalidateBankStatementReconciliationView()
{ | invalidateView(getBanksStatementReconciliationViewId());
}
protected final BankStatementLineRow getSingleSelectedBankStatementRowOrNull()
{
final ViewRowIdsSelection selection = getParentViewRowIdsSelection();
if (selection == null || selection.isEmpty())
{
return null;
}
final ImmutableList<BankStatementLineRow> rows = getBanksStatementReconciliationView()
.streamByIds(selection)
.collect(ImmutableList.toImmutableList());
return rows.size() == 1 ? rows.get(0) : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\process\PaymentsToReconcileViewBasedProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDefaultAlias() {
return this.defaultAlias;
}
public void setDefaultAlias(String defaultAlias) {
this.defaultAlias = defaultAlias;
}
public String getGateway() {
return this.gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
}
public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
} | public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java | 2 |
请完成以下Java代码 | public String getUsername() {
return this.username;
}
@Override
public void setUsername(String username) {
this.username = username;
}
@Override
public char[] getPassword() {
return this.password;
}
@Override
public void setPassword(char[] password) {
this.password = password;
}
@Override
public Object getPrincipal() {
return this.getUsername();
}
@Override
public Object getCredentials() {
return this.getPassword();
}
@Override
public String getHost() {
return this.host;
} | @Override
public void setHost(String host) {
this.host = host;
}
@Override
public boolean isRememberMe() {
return this.rememberMe;
}
@Override
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void clear() {
super.clear();
this.accessToken = null;
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\credentials\ThirdPartySupportedToken.java | 1 |
请完成以下Java代码 | public class ReplicationHelper
{
public static final String MSG_XMLInvalidContext = "XMLInvalidContext";
/**
* Method sets the given context values to the given context.
*
* @param ctx the context to be updated
* @param name the name of the context value to be updated
* @param value the actual new value
* @param overwrite if <code>true</code> then the given <code>value</code> is set, even if there is already a different value. Otherwise, a {@link ReplicationException} is thrown.
* @throws ReplicationException if the name is already set to a different value.
*/
public static void setReplicationCtx(final Properties ctx,
final String name,
final Object value,
final boolean overwrite)
{
if (value instanceof Integer)
{
final Integer valueInt = (Integer)value;
final Integer valueOldInt = Env.containsKey(ctx, name) ? Env.getContextAsInt(ctx, name) : null;
if (Objects.equals(valueInt, valueOldInt))
{
// nothing to do
return;
}
else if (overwrite || valueOldInt == null)
{
Env.setContext(ctx, name, valueInt);
}
else
{
throw new ReplicationException(MSG_XMLInvalidContext)
.setParameter("AttributeName", name)
.setParameter("Value", valueInt)
.setParameter("ValueOld", valueOldInt);
}
}
else if (value instanceof Timestamp)
{
final Timestamp valueTS = (Timestamp)value;
final Timestamp valueOldTS = Env.containsKey(ctx, name) ? Env.getContextAsDate(ctx, name) : null;
if (Objects.equals(valueTS, valueOldTS)) | {
// nothing to do
return;
}
else if (overwrite || valueOldTS == null)
{
Env.setContext(ctx, name, valueTS);
}
else
{
throw new ReplicationException(MSG_XMLInvalidContext)
.setParameter("AttributeName", name)
.setParameter("Value", valueTS)
.setParameter("ValueOld", valueOldTS);
}
}
else
{
final String valueStr = value == null ? null : value.toString();
final String valueOldStr = Env.containsKey(ctx, name) ? Env.getContext(ctx, name) : null;
if (Objects.equals(valueStr, valueOldStr))
{
// nothing to do
return;
}
else if (overwrite || valueOldStr == null)
{
Env.setContext(ctx, name, valueStr);
}
else
{
throw new ReplicationException(MSG_XMLInvalidContext)
.setParameter("AttributeName", name)
.setParameter("Value", valueStr)
.setParameter("ValueOld", valueOldStr);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\ReplicationHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public boolean isCompletable() {
return completable;
}
public void setCompletable(boolean completable) {
this.completable = completable;
}
public String getEntryCriterionId() {
return entryCriterionId;
}
public void setEntryCriterionId(String entryCriterionId) {
this.entryCriterionId = entryCriterionId;
}
public String getExitCriterionId() {
return exitCriterionId;
}
public void setExitCriterionId(String exitCriterionId) {
this.exitCriterionId = exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
} | public String getCompletedBy() {
return completedBy;
}
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | protected IPrintJobLinesAggregator createPrintJobLinesAggregator(
@NonNull final IPrintPackageCtx printPackageCtx,
@NonNull final I_C_Print_Job_Instructions jobInstructions)
{
return new PrintJobLinesAggregator(printingDataFactory, printPackageCtx, jobInstructions);
}
@Override
public IPrintPackageCtx createEmptyInitialCtx()
{
return new PrintPackageCtx();
}
@Override
public IPrintPackageCtx createInitialCtx(@NonNull final Properties ctx)
{
final PrintPackageCtx printCtx = new PrintPackageCtx();
final MFSession session = Services.get(ISessionBL.class).getCurrentSession(ctx);
if (session == null) | {
throw new AdempiereException("The given ctx has no session.")
.appendParametersToMessage()
.setParameter("ctx", ctx);
}
logger.debug("Session: {}", session);
final String hostKey = session.getOrCreateHostKey(ctx);
Check.assumeNotEmpty(hostKey, "{} has a hostKey", session);
printCtx.setHostKey(hostKey);
logger.debug("Print package context: {}", printCtx);
return printCtx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintPackageBL.java | 1 |
请完成以下Java代码 | public class ListInfo
{
static Builder builder()
{
return new Builder();
}
private final int adReferenceId;
private final String name;
private final ImmutableList<ListItemInfo> items;
private ListInfo(final Builder builder)
{
super();
this.adReferenceId = builder.adReferenceId;
Check.assumeNotEmpty(builder.name, "name not empty");
this.name = builder.name;
this.items = builder.items.build();
// Check.assumeNotEmpty(items, "items not empty"); // allow empty list
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
public int getAD_Reference_ID()
{
return adReferenceId;
}
public String getName()
{
return name;
}
public List<ListItemInfo> getItems()
{
return items;
}
public static class Builder
{
private Integer adReferenceId;
private String name;
private ImmutableList.Builder<ListItemInfo> items = ImmutableList.builder();
private Builder()
{
super();
} | public ListInfo build()
{
return new ListInfo(this);
}
public Builder setAD_Reference_ID(final int adReferenceId)
{
this.adReferenceId = adReferenceId;
return this;
}
public Builder setName(String name)
{
this.name = name;
return this;
}
public Builder addItem(final String value, final String name, final String valueName)
{
final ListItemInfo item = new ListItemInfo(value, name, valueName);
items.add(item);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\modelgen\ListInfo.java | 1 |
请完成以下Java代码 | public String toString()
{
// IMPORTANT: this is how it will be displayed to user
return caption;
}
@Override
public int hashCode()
{
return Objects.hashCode(value);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof DocActionItem)
{
final DocActionItem other = (DocActionItem)obj; | return Objects.equal(value, other.value);
}
else
{
return false;
}
}
@Override
public String getValue()
{
return value;
}
@Override
public String getDescription()
{
return description;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\AbstractDocumentBL.java | 1 |
请完成以下Java代码 | public void onMessage(@PathParam("username") String username, String message) {
logger.info("发送消息:"+message);
sendMessageAll("用户[" + username + "] : " + message);
}
@OnClose
public void onClose(@PathParam("username") String username, Session session) {
//当前的Session 移除
ONLINE_USER_SESSIONS.remove(username);
//并且通知其他人当前用户已经离开聊天室了
sendMessageAll("用户[" + username + "] 已经离开聊天室了!");
try {
session.close();
} catch (IOException e) {
logger.error("onClose error",e); | }
}
@OnError
public void onError(Session session, Throwable throwable) {
try {
session.close();
} catch (IOException e) {
logger.error("onError excepiton",e);
}
logger.info("Throwable msg "+throwable.getMessage());
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-10 课: 使用 Spring Boot WebSocket 创建聊天室\spring-boot-websocket\src\main\java\com\neo\ChatRoomServerEndpoint.java | 1 |
请完成以下Java代码 | public static MSV3StockAvailabilityUpdatedEvent ofSingle(
@NonNull final MSV3StockAvailability msv3StockAvailability,
@NonNull final MSV3EventVersion eventVersion)
{
return builder()
.eventVersion(eventVersion)
.item(msv3StockAvailability)
.deleteAllOtherItems(false)
.build();
}
private final String id;
private final List<MSV3StockAvailability> items;
private final boolean deleteAllOtherItems;
/**
* The items of events with lower versions are discarded if the msv3-server was already updated based on an event with a higher version.
* Multiple events may have the same version. | */
private MSV3EventVersion eventVersion;
@JsonCreator
@Builder
private MSV3StockAvailabilityUpdatedEvent(
@JsonProperty("id") final String id,
@JsonProperty("items") @Singular final List<MSV3StockAvailability> items,
@JsonProperty("deleteAllOtherItems") final boolean deleteAllOtherItems,
@JsonProperty("eventVersion") @NonNull final MSV3EventVersion eventVersion)
{
this.id = id != null ? id : UUID.randomUUID().toString();
this.items = items != null ? ImmutableList.copyOf(items) : ImmutableList.of();
this.deleteAllOtherItems = deleteAllOtherItems;
this.eventVersion = eventVersion;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\protocol\MSV3StockAvailabilityUpdatedEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InfinispanCacheService {
public static final String CACHE_NAME = "demoCache";
@Inject
EmbeddedCacheManager cacheManager;
private Cache<String, String> demoCache;
@PostConstruct
void init() {
Configuration cacheConfig = new ConfigurationBuilder()
.clustering().cacheMode(CacheMode.LOCAL)
.memory().maxCount(10)
.expiration().lifespan(600, TimeUnit.MILLISECONDS)
.persistence().passivation(true).build();
demoCache = cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache(CACHE_NAME, cacheConfig);
}
public void put(String key, String value) {
demoCache.put(key, value);
} | public String get(String key) {
return demoCache.get(key);
}
public void bulkPut(Map<String, String> entries) {
demoCache.putAll(entries);
}
public int size() {
return demoCache.size();
}
public void clear() {
demoCache.clear();
}
public boolean isPassivationEnabled() {
return cacheManager.getCacheConfiguration(CACHE_NAME).persistence().passivation();
}
public void stop() {
cacheManager.stop();
}
} | repos\tutorials-master\quarkus-modules\quarkus-infinispan-embedded\src\main\java\com\baeldung\quarkus\infinispan\InfinispanCacheService.java | 2 |
请完成以下Java代码 | public static void checkJavaSerialization(String variableName, TypedValue value) {
if (isJavaSerializationProhibited(value)) {
throw CORE_LOGGER.javaSerializationProhibitedException(variableName);
}
}
public static void setVariables(Map<String, ?> variables,
SetVariableFunction setVariableFunction) {
if (variables != null) {
for (String variableName : variables.keySet()) {
Object value = null;
if (variables instanceof VariableMap) {
value = ((VariableMap) variables).getValueTyped(variableName);
} else {
value = variables.get(variableName);
}
setVariableFunction.apply(variableName, value);
}
}
}
public static void setVariablesByBatchId(Map<String, ?> variables, String batchId) {
setVariables(variables, (name, value) -> setVariableByBatchId(batchId, name, value));
}
public static void setVariableByBatchId(String batchId, String variableName, Object variableValue) {
TypedValue variableTypedValue = Variables.untypedValue(variableValue);
boolean isTransient = variableTypedValue.isTransient();
if (isTransient) {
throw CMD_LOGGER.exceptionSettingTransientVariablesAsyncNotSupported(variableName);
} | checkJavaSerialization(variableName, variableTypedValue);
VariableInstanceEntity variableInstance =
VariableInstanceEntity.createAndInsert(variableName, variableTypedValue);
variableInstance.setVariableScopeId(batchId);
variableInstance.setBatchId(batchId);
}
public static Map<String, ?> findBatchVariablesSerialized(String batchId, CommandContext commandContext) {
List<VariableInstanceEntity> variableInstances = commandContext.getVariableInstanceManager()
.findVariableInstancesByBatchId(batchId);
return variableInstances.stream().collect(variablesCollector());
}
protected static Collector<VariableInstanceEntity, ?, Map<String, TypedValue>> variablesCollector() {
return Collectors.toMap(VariableInstanceEntity::getName, VariableUtil::getSerializedValue);
}
protected static TypedValue getSerializedValue(VariableInstanceEntity variableInstanceEntity) {
return variableInstanceEntity.getTypedValue(false);
}
@FunctionalInterface
public interface SetVariableFunction {
void apply(String variableName, Object variableValue);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\VariableUtil.java | 1 |
请完成以下Java代码 | public String getPstCd() {
return pstCd;
}
/**
* Sets the value of the pstCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPstCd(String value) {
this.pstCd = value;
}
/**
* Gets the value of the twnNm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTwnNm() {
return twnNm;
}
/**
* Sets the value of the twnNm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTwnNm(String value) {
this.twnNm = value;
}
/**
* Gets the value of the ctrySubDvsn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCtrySubDvsn() {
return ctrySubDvsn;
}
/**
* Sets the value of the ctrySubDvsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtrySubDvsn(String value) {
this.ctrySubDvsn = value;
}
/**
* Gets the value of the ctry property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCtry() {
return ctry;
} | /**
* Sets the value of the ctry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtry(String value) {
this.ctry = value;
}
/**
* Gets the value of the adrLine 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 adrLine property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdrLine().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAdrLine() {
if (adrLine == null) {
adrLine = new ArrayList<String>();
}
return this.adrLine;
}
} | 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\PostalAddress6.java | 1 |
请完成以下Java代码 | public List<MissingAuthorization> getMissingAuthorizations() {
return Collections.unmodifiableList(missingAuthorizations);
}
/**
* Generate exception message from the missing authorizations.
*
* @param userId to use
* @param missingAuthorizations to use
* @return The prepared exception message
*/
private static String generateExceptionMessage(String userId, List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("The user with id '");
sBuilder.append(userId);
sBuilder.append("' does not have one of the following permissions: ");
sBuilder.append(generateMissingAuthorizationsList(missingAuthorizations));
return sBuilder.toString();
}
/**
* Generate a String containing a list of missing authorizations.
*
* @param missingAuthorizations
*/
public static String generateMissingAuthorizationsList(List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
boolean first = true;
for(MissingAuthorization missingAuthorization: missingAuthorizations) {
if (!first) {
sBuilder.append(" or ");
} else { | first = false;
}
sBuilder.append(generateMissingAuthorizationMessage(missingAuthorization));
}
return sBuilder.toString();
}
/**
* Generated exception message for the missing authorization.
*
* @param exceptionInfo to use
*/
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) {
StringBuilder builder = new StringBuilder();
String permissionName = exceptionInfo.getViolatedPermissionName();
String resourceType = exceptionInfo.getResourceType();
String resourceId = exceptionInfo.getResourceId();
builder.append("'");
builder.append(permissionName);
builder.append("' permission on resource '");
builder.append((resourceId != null ? (resourceId+"' of type '") : "" ));
builder.append(resourceType);
builder.append("'");
return builder.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\AuthorizationException.java | 1 |
请完成以下Java代码 | public class AdempiereThemeInnova extends org.adempiere.plaf.AdempiereTheme
{
/**
* Adempiere default Theme Blue Metal
*/
public AdempiereThemeInnova()
{
setDefault();
s_theme = this;
s_name = NAME;
} // AdempiereThemeBlueMetal
/** Name */
public static final String NAME = "Adempiere Theme";
/**
* Set Defaults
*/
@Override
public void setDefault()
{
/** Blue 51,51,102 */
primary0 = new ColorUIResource(103, 152, 203);
/** Blue 102, 102, 153 */
// protected static ColorUIResource primary1;
primary1 = new ColorUIResource(101, 138, 187);
/** Blue 153, 153, 204 */
primary2 = new ColorUIResource(103, 152, 203);
/** Blue 204, 204, 255 */
primary3 = new ColorUIResource(233, 238, 245); //
/** Black */
// secondary0 = new ColorUIResource(0, 0, 0);
/** Gray 102, 102, 102 */
// protected static ColorUIResource secondary1;
secondary1 = new ColorUIResource(190, 179, 153);
/** Gray 153, 153, 153 */
// protected static ColorUIResource secondary2;
secondary2 = new ColorUIResource(246, 239, 224);
/** BlueGray 214, 224, 234 - background */
// protected static ColorUIResource secondary3;
secondary3 = new ColorUIResource(251, 248, 241);
/** White */
// secondary4 = new ColorUIResource(255, 255, 255);
/** Black */ | black = BLACK;
/** White */
white = WHITE;
/** Background for mandatory fields */
mandatory = new ColorUIResource(233, 238, 245); // blueish
/** Background for fields in error 180,220,143 */
error = new ColorUIResource(220, 241, 203); // green ;
/** Background for inactive fields */
inactive = new ColorUIResource(241, 239, 222);// 241,239,222
/** Background for info fields */
info = new ColorUIResource(251, 248, 251); // somewhat white
/** Foreground Text OK */
txt_ok = new ColorUIResource(0, 153, 255); // blue ;
/** Foreground Text Error */
txt_error = new ColorUIResource(255, 0, 51); // red ;
/** Black */
// secondary0 = new ColorUIResource(0, 0, 0);
/** Control font */
controlFont = null;
_getControlTextFont();
/** System font */
systemFont = null;
_getSystemTextFont();
/** User font */
userFont = null;
_getUserTextFont();
/** Small font */
smallFont = null;
_getSubTextFont();
/** Window Title font */
windowFont = null;
_getWindowTitleFont();
/** Menu font */
menuFont = null;
_getMenuTextFont();
} // setDefault
} // AdempiereThemeBlueMetal | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempiereThemeInnova.java | 1 |
请完成以下Java代码 | /* package */abstract class AbstractLockAutoCloseable implements ILockAutoCloseable
{
private final ILock lock;
public AbstractLockAutoCloseable(final ILock lock)
{
super();
Check.assumeNotNull(lock, "lock not null");
this.lock = lock;
}
@Override
public final String toString()
{
return ObjectUtils.toString(this);
}
@Override
public final ILock getLock()
{
return lock;
}
@Override
public final void close()
{
// If lock was already closed, there is nothing to do
if (lock.isClosed())
{ | return;
}
closeImpl();
}
/** Actual lock closing logic */
protected abstract void closeImpl();
protected final void closeNow()
{
lock.close();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\AbstractLockAutoCloseable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserRepositoryCustomImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<User> findUserByEmails(Set<String> emails) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> user = query.from(User.class);
Path<String> emailPath = user.get("email");
List<Predicate> predicates = new ArrayList<>();
for (String email : emails) {
predicates.add(cb.like(emailPath, email));
}
query.select(user) | .where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query)
.getResultList();
}
@Override
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
Stream<User> allUsersStream = allUsers.stream();
for (java.util.function.Predicate<User> predicate : predicates) {
allUsersStream = allUsersStream.filter(predicate);
}
return allUsersStream.collect(Collectors.toList());
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\daos\user\UserRepositoryCustomImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class ConfigChangeNotice extends BaseModel {
private Date noticeTime;
private String appid;
private ChangeType type;
private String value;
public ConfigChangeNotice() {
this.noticeTime = new Date();
}
public ConfigChangeNotice(String appid, ChangeType type, String value) {
this();
this.appid = appid;
this.type = type;
this.value = value;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public ChangeType getType() {
return type;
}
public void setType(ChangeType type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) { | this.value = value;
}
public Date getNoticeTime() {
return noticeTime;
}
public void setNoticeTime(Date noticeTime) {
this.noticeTime = noticeTime;
}
@Override
public String toString() {
return "ConfigChangeNotice{" +
"noticeTime=" + noticeTime +
", appid='" + appid + '\'' +
", type=" + type +
", value='" + value + '\'' +
'}';
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\config\ConfigChangeNotice.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void saveData(PmsRole pmsRole) {
pmsRoleDao.insert(pmsRole);
}
/**
* 修改pmsOperator
*/
public void updateData(PmsRole pmsRole) {
pmsRoleDao.update(pmsRole);
}
/**
* 根据id获取数据pmsOperator
*
* @param id
* @return
*/
public PmsRole getDataById(Long id) {
return pmsRoleDao.getById(id);
}
/**
* 分页查询pmsOperator
*
* @param pageParam
* @param ActivityVo
* PmsOperator
* @return
*/
public PageBean listPage(PageParam pageParam, PmsRole pmsRole) {
Map<String, Object> paramMap = new HashMap<String, Object>(); // 业务条件查询参数
paramMap.put("roleName", pmsRole.getRoleName()); // 角色名称(模糊查询)
return pmsRoleDao.listPage(pageParam, paramMap);
}
/**
* 获取所有角色列表,以供添加操作员时选择.
*
* @return roleList .
*/
public List<PmsRole> listAllRole() {
return pmsRoleDao.listAll();
}
/**
* 判断此权限是否关联有角色
*
* @param permissionId
* @return | */
public List<PmsRole> listByPermissionId(Long permissionId) {
return pmsRoleDao.listByPermissionId(permissionId);
}
/**
* 根据角色名或者角色编号查询角色
*
* @param roleName
* @param roleCode
* @return
*/
public PmsRole getByRoleNameOrRoleCode(String roleName, String roleCode) {
return pmsRoleDao.getByRoleNameOrRoleCode(roleName, roleCode);
}
/**
* 删除
*
* @param roleId
*/
public void delete(Long roleId) {
pmsRoleDao.delete(roleId);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsRoleServiceImpl.java | 2 |
请完成以下Java代码 | protected CaseDefinition findNewLatestCaseDefinitionAfterRemovalOf(CaseDefinition caseDefinitionToBeRemoved) {
// The case definition is not necessarily the one with 'version -1' (some versions could have been deleted)
// Hence, the following logic
CaseDefinitionQuery query = getCaseDefinitionEntityManager().createCaseDefinitionQuery();
query.caseDefinitionKey(caseDefinitionToBeRemoved.getKey());
if (caseDefinitionToBeRemoved.getTenantId() != null
&& !CmmnEngineConfiguration.NO_TENANT_ID.equals(caseDefinitionToBeRemoved.getTenantId())) {
query.caseDefinitionTenantId(caseDefinitionToBeRemoved.getTenantId());
} else {
query.caseDefinitionWithoutTenantId();
}
if (caseDefinitionToBeRemoved.getVersion() > 0) {
query.caseDefinitionVersionLowerThan(caseDefinitionToBeRemoved.getVersion());
}
query.orderByCaseDefinitionVersion().desc();
List<CaseDefinition> caseDefinitions = query.listPage(0, 1);
if (caseDefinitions != null && caseDefinitions.size() > 0) {
return caseDefinitions.get(0);
}
return null;
}
@Override
public CmmnDeploymentEntity findLatestDeploymentByName(String deploymentName) {
return dataManager.findLatestDeploymentByName(deploymentName);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return dataManager.getDeploymentResourceNames(deploymentId);
} | @Override
public CmmnDeploymentQuery createDeploymentQuery() {
return new CmmnDeploymentQueryImpl(engineConfiguration.getCommandExecutor());
}
@Override
public List<CmmnDeployment> findDeploymentsByQueryCriteria(CmmnDeploymentQuery deploymentQuery) {
return dataManager.findDeploymentsByQueryCriteria((CmmnDeploymentQueryImpl) deploymentQuery);
}
@Override
public long findDeploymentCountByQueryCriteria(CmmnDeploymentQuery deploymentQuery) {
return dataManager.findDeploymentCountByQueryCriteria((CmmnDeploymentQueryImpl) deploymentQuery);
}
protected CmmnResourceEntityManager getCmmnResourceEntityManager() {
return engineConfiguration.getCmmnResourceEntityManager();
}
protected CaseDefinitionEntityManager getCaseDefinitionEntityManager() {
return engineConfiguration.getCaseDefinitionEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) {
Assert.notNull(relayStateResolver, "relayStateResolver cannot be null");
this.delegate.setRelayStateResolver(relayStateResolver);
}
public static final class LogoutRequestParameters {
private final HttpServletRequest request;
private final RelyingPartyRegistration registration;
private final Authentication authentication;
private final LogoutRequest logoutRequest;
public LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration,
Authentication authentication, LogoutRequest logoutRequest) {
this.request = request;
this.registration = registration;
this.authentication = authentication;
this.logoutRequest = logoutRequest;
}
LogoutRequestParameters(BaseOpenSamlLogoutRequestResolver.LogoutRequestParameters parameters) {
this(parameters.getRequest(), parameters.getRelyingPartyRegistration(), parameters.getAuthentication(), | parameters.getLogoutRequest());
}
public HttpServletRequest getRequest() {
return this.request;
}
public RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
public Authentication getAuthentication() {
return this.authentication;
}
public LogoutRequest getLogoutRequest() {
return this.logoutRequest;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestResolver.java | 2 |
请完成以下Java代码 | private void writeCCFile(final I_AD_Archive archive)
{
final Object model = archiveDAO.retrieveReferencedModel(archive, Object.class);
if (model == null)
{
// No model attached?
// we shouldn't reach this point
throw new AdempiereException("@NotFound@ @AD_Archive_ID@ @Record_ID@");
}
final ICCAbleDocument document = ccAbleDocumentFactoryService.createCCAbleDocument(model);
Check.assumeNotNull(document, "ccDocument not null");
//
// Get Document Outbound Configuration
final DocOutboundConfig config = docOutboundConfigService.retrieveConfigForModel(model);
if (config == null)
{
throw new AdempiereException("@NotFound@ @C_Doc_Outbound_Config@ (" + model + ")");
}
final String ccPath = config.getCcPath();
if (Check.isEmpty(ccPath, true))
{
// Doc Outbound config does not have CC Path set
// we shouldn't reach this point
throw new AdempiereException("@NotFound@ @CCPath@: " + config);
}
final File ccPathDir = new File(ccPath);
if (!ccPathDir.exists() && !ccPathDir.mkdirs())
{
throw new AdempiereException("Cannot create directory: " + ccPathDir);
}
final String filename = document.getFileName();
Check.assumeNotEmpty(filename, "filename shall not be empty for {}", document);
final String filenameFixed = FileUtil.stripIllegalCharacters(filename);
Check.assumeNotEmpty(filenameFixed, "filename shall be valid: {}", filename);
final File ccFile = new File(ccPathDir, filenameFixed);
copyArchiveToFile(archive, ccFile);
}
private void copyArchiveToFile(final I_AD_Archive archive, final File file)
{
final IArchiveStorage archiveStorage = archiveStorageFactory.getArchiveStorage(archive);
final InputStream data = archiveStorage.getBinaryDataAsStream(archive); | OutputStream out = null;
try
{
out = new FileOutputStream(file, false); // append=false
final int bufferSize = 1024 * 4;
final OutputStream outBuffer = new BufferedOutputStream(out, bufferSize);
IOStreamUtils.copy(outBuffer, data);
}
catch (final FileNotFoundException e)
{
throw new AdempiereException("@CCFileCreationError@ " + file, e);
}
catch (final SecurityException e)
{
throw new AdempiereException("@CCFileWriteAccessDenied@ " + file, e);
}
finally
{
IOStreamUtils.close(out, data);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\async\spi\impl\DocOutboundCCWorkpackageProcessor.java | 1 |
请完成以下Java代码 | public static byte[] createRandomStringInByte(int size) {
Random random = new Random();
byte[] data = new byte[size];
for (int n = 0; n < data.length; n++) {
char randomChar;
int choice = random.nextInt(2); // 0 for uppercase, 1 for lowercase
if (choice == 0) {
randomChar = (char) ('A' + random.nextInt(26)); // 'A' to 'Z'
} else {
randomChar = (char) ('a' + random.nextInt(26)); // 'a' to 'z'
}
data[n] = (byte) randomChar;
}
return data;
} | public File getFile() {
return file;
}
public List<String> getDataList() {
return dataList;
}
public static String getString(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
IOUtils.copy(inputStream, byteArrayOutputStream);
return byteArrayOutputStream.toString(DEFAULT_ENCODING);
}
} | repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\zip\ZipSampleFileStore.java | 1 |
请完成以下Java代码 | public PageData<RuleChain> findAutoAssignToEdgeRuleChainsByTenantId(UUID tenantId, PageLink pageLink) {
log.debug("Try to find auto assign to edge rule chains by tenantId [{}]", tenantId);
return DaoUtil.toPageData(ruleChainRepository
.findAutoAssignByTenantId(
tenantId,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public Collection<RuleChain> findByTenantIdAndTypeAndName(TenantId tenantId, RuleChainType type, String name) {
return DaoUtil.convertDataList(ruleChainRepository.findByTenantIdAndTypeAndName(tenantId.getId(), type, name));
}
@Override
public List<RuleChain> findRuleChainsByTenantIdAndIds(UUID tenantId, List<UUID> ruleChainIds) {
return DaoUtil.convertDataList(ruleChainRepository.findRuleChainsByTenantIdAndIdIn(tenantId, ruleChainIds));
}
@Override
public Long countByTenantId(TenantId tenantId) {
return ruleChainRepository.countByTenantId(tenantId.getId());
}
@Override
public RuleChain findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(ruleChainRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public PageData<RuleChain> findByTenantId(UUID tenantId, PageLink pageLink) {
return findRuleChainsByTenantId(tenantId, pageLink);
}
@Override
public RuleChainId getExternalIdByInternal(RuleChainId internalId) {
return Optional.ofNullable(ruleChainRepository.getExternalIdById(internalId.getId()))
.map(RuleChainId::new).orElse(null);
}
@Override
public RuleChain findDefaultEntityByTenantId(UUID tenantId) {
return findRootRuleChainByTenantIdAndType(tenantId, RuleChainType.CORE);
} | @Override
public PageData<RuleChain> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findRuleChainsByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) {
return ruleChainRepository.findRuleChainsByTenantIdAndResource(tenantId.getId(), reference, PageRequest.of(0, limit));
}
@Override
public List<EntityInfo> findByResource(String reference, int limit) {
return ruleChainRepository.findRuleChainsByResource(reference, PageRequest.of(0, limit));
}
@Override
public List<RuleChainFields> findNextBatch(UUID id, int batchSize) {
return ruleChainRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.RULE_CHAIN;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\rule\JpaRuleChainDao.java | 1 |
请完成以下Java代码 | public void setHeaderValue(HeaderValue headerValue) {
Assert.notNull(headerValue, "headerValue cannot be null");
this.headerValue = headerValue;
updateDelegate();
}
/**
* The value of the x-xss-protection header. One of: "0", "1", "1; mode=block"
*
* @author Daniel Garnier-Moiroux
* @since 5.8
*/
public enum HeaderValue {
DISABLED("0"), ENABLED("1"), ENABLED_MODE_BLOCK("1; mode=block");
private final String value;
HeaderValue(String value) {
this.value = value;
} | @Override
public String toString() {
return this.value;
}
}
private void updateDelegate() {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(X_XSS_PROTECTION, this.headerValue.toString());
this.delegate = builder.build();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\XXssProtectionServerHttpHeadersWriter.java | 1 |
请完成以下Java代码 | public void setIdClassMapping(Map<String, Class<?>> idClassMapping) {
this.idClassMapping.putAll(idClassMapping);
createReverseMap();
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
protected @Nullable ClassLoader getClassLoader() {
return this.classLoader;
}
protected void addHeader(Headers headers, String headerName, Class<?> clazz) {
if (this.classIdMapping.containsKey(clazz)) {
headers.add(new RecordHeader(headerName, this.classIdMapping.get(clazz)));
}
else {
headers.add(new RecordHeader(headerName, clazz.getName().getBytes(StandardCharsets.UTF_8)));
}
}
protected String retrieveHeader(Headers headers, String headerName) {
String classId = retrieveHeaderAsString(headers, headerName);
if (classId == null) {
throw new MessageConversionException(
"failed to convert Message content. Could not resolve " + headerName + " in header");
}
return classId;
}
protected @Nullable String retrieveHeaderAsString(Headers headers, String headerName) {
Header header = headers.lastHeader(headerName);
if (header != null) {
String classId = null;
if (header.value() != null) {
classId = new String(header.value(), StandardCharsets.UTF_8);
}
return classId;
}
return null;
}
private void createReverseMap() {
this.classIdMapping.clear(); | for (Map.Entry<String, Class<?>> entry : this.idClassMapping.entrySet()) {
String id = entry.getKey();
Class<?> clazz = entry.getValue();
this.classIdMapping.put(clazz, id.getBytes(StandardCharsets.UTF_8));
}
}
public Map<String, Class<?>> getIdClassMapping() {
return Collections.unmodifiableMap(this.idClassMapping);
}
/**
* Configure the TypeMapper to use default key type class.
* @param isKey Use key type headers if true
* @since 2.1.3
*/
public void setUseForKey(boolean isKey) {
if (isKey) {
setClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CLASSID_FIELD_NAME);
setContentClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_CONTENT_CLASSID_FIELD_NAME);
setKeyClassIdFieldName(AbstractJavaTypeMapper.KEY_DEFAULT_KEY_CLASSID_FIELD_NAME);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\mapping\AbstractJavaTypeMapper.java | 1 |
请完成以下Java代码 | public void setLogoWeb_ID (int LogoWeb_ID)
{
if (LogoWeb_ID < 1)
set_Value (COLUMNNAME_LogoWeb_ID, null);
else
set_Value (COLUMNNAME_LogoWeb_ID, Integer.valueOf(LogoWeb_ID));
}
/** Get Logo Web.
@return Logo Web */
@Override
public int getLogoWeb_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LogoWeb_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_ProductFreight() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_ProductFreight(org.compiere.model.I_M_Product M_ProductFreight)
{
set_ValueFromPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class, M_ProductFreight);
} | /** Set Produkt für Fracht.
@param M_ProductFreight_ID Produkt für Fracht */
@Override
public void setM_ProductFreight_ID (int M_ProductFreight_ID)
{
if (M_ProductFreight_ID < 1)
set_Value (COLUMNNAME_M_ProductFreight_ID, null);
else
set_Value (COLUMNNAME_M_ProductFreight_ID, Integer.valueOf(M_ProductFreight_ID));
}
/** Get Produkt für Fracht.
@return Produkt für Fracht */
@Override
public int getM_ProductFreight_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductFreight_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_AD_ClientInfo.java | 1 |
请完成以下Java代码 | public List<Fact> createFacts(final AcctSchema as)
{
// Other Acct Schema
if (!AcctSchemaId.equals(as.getId(), acctSchemaId))
{
return ImmutableList.of();
}
// create Fact Header
final Fact fact = new Fact(this, as, postingType);
if (services.getSysConfigBooleanValue(SYSCONFIG_DisableFactAcctTrxChecking, false))
{
fact.setFactTrxLinesStrategy(null);
}
else
{
fact.setFactTrxLinesStrategy(Doc_GLJournal_FactTrxStrategy.instance);
}
// GLJ
if (DocBaseType.GLJournal.equals(getDocBaseType()))
{
// account DR CR
for (final DocLine_GLJournal line : getDocLines())
{
if (line.getAcctSchemaId() != null && !AcctSchemaId.equals(line.getAcctSchemaId(), as.getId()))
{
continue;
}
final CurrencyConversionContext currencyConversionCtx = createCurrencyConversionContext(
line,
as.getCurrencyId());
fact.createLine()
.setDocLine(line)
.setAccount(line.getAccount())
.setAmtSource(line.getCurrencyId(), line.getAmtSourceDr(), line.getAmtSourceCr())
.setCurrencyConversionCtx(currencyConversionCtx)
.locatorId(line.getLocatorId())
.buildAndAdd();
} // for all lines
} | else
{
throw newPostingException()
.setAcctSchema(as)
.setDetailMessage("DocumentType unknown: " + getDocBaseType());
}
//
return ImmutableList.of(fact);
} // createFact
private CurrencyConversionContext createCurrencyConversionContext(
@NonNull final DocLine_GLJournal line,
@NonNull final CurrencyId acctSchemaCurrencyId)
{
CurrencyConversionContext currencyConversionCtx = currencyBL.createCurrencyConversionContext(
line.getDateAcct(),
line.getCurrencyConversionTypeId(),
line.getClientId());
final BigDecimal fixedCurrencyRate = line.getFixedCurrencyRate();
if (fixedCurrencyRate != null && fixedCurrencyRate.signum() != 0)
{
currencyConversionCtx = currencyConversionCtx.withFixedConversionRate(FixedConversionRate.builder()
.fromCurrencyId(line.getCurrencyId())
.toCurrencyId(acctSchemaCurrencyId)
.multiplyRate(fixedCurrencyRate)
.build());
}
return currencyConversionCtx;
}
} // Doc_GLJournal | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_GLJournal.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.