instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class JsonProduct
{
@ApiModelProperty( //
allowEmptyValue = false, //
dataType = "java.lang.Integer", //
value = "This translates to `M_Product.M_Product_ID`.")
@NonNull
ProductId id;
@ApiModelProperty("This translates to `M_Product.Value`.")
@NonNull
String productNo;
@NonNull
String name;
@Nullable
String description;
@ApiModelProperty(value = "This translates to `M_Product.UPC`.<br>Note that different bPartners may assign different EANs to the same product")
@Nullable
@JsonInclude(Include.NON_EMPTY)
String ean;
|
@ApiModelProperty("This translates to `M_Product.ExternalId`.")
@Nullable
@JsonInclude(Include.NON_EMPTY)
String externalId;
@ApiModelProperty("This is the `C_UOM.UOMSymbol` of the product's unit of measurement.")
@NonNull
String uom;
@NonNull
@Singular
List<JsonProductBPartner> bpartners;
@NonNull
JsonCreatedUpdatedInfo createdUpdatedInfo;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\response\JsonProduct.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Autowired
OAuth2ClientContext oauth2ClientContext;
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
// Configure spring security's authenticationManager with custom
// user details service
auth.userDetailsService(this.userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/user/**").authenticated()
.anyRequest().permitAll()
.and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
// .and()
// .formLogin().loginPage("/login").loginProcessingUrl("/login.do").defaultSuccessUrl("/user/info")
// .failureUrl("/login?err=1")
// .permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.permitAll()
.and().addFilterBefore(sso(), BasicAuthenticationFilter.class)
;
}
private Filter sso() {
OAuth2ClientAuthenticationProcessingFilter githubFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/github");
OAuth2RestTemplate githubTemplate = new OAuth2RestTemplate(github(), oauth2ClientContext);
githubFilter.setRestTemplate(githubTemplate);
githubFilter.setTokenServices(new UserInfoTokenServices(githubResource().getUserInfoUri(), github().getClientId()));
return githubFilter;
|
}
@Bean
@ConfigurationProperties("github.resource")
public ResourceServerProperties githubResource() {
return new ResourceServerProperties();
}
@Bean
@ConfigurationProperties("github.client")
public AuthorizationCodeResourceDetails github() {
return new AuthorizationCodeResourceDetails();
}
@Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(
OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
}
|
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\config\WebSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setExternalReferenceURL (final @Nullable java.lang.String ExternalReferenceURL)
{
set_Value (COLUMNNAME_ExternalReferenceURL, ExternalReferenceURL);
}
@Override
public java.lang.String getExternalReferenceURL()
{
return get_ValueAsString(COLUMNNAME_ExternalReferenceURL);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
/**
* ProjectType AD_Reference_ID=541118
* Reference name: ExternalProjectType
*/
public static final int PROJECTTYPE_AD_Reference_ID=541118;
/** Budget = Budget */
public static final String PROJECTTYPE_Budget = "Budget";
/** Development = Effort */
public static final String PROJECTTYPE_Development = "Effort";
@Override
public void setProjectType (final java.lang.String ProjectType)
{
|
set_Value (COLUMNNAME_ProjectType, ProjectType);
}
@Override
public java.lang.String getProjectType()
{
return get_ValueAsString(COLUMNNAME_ProjectType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setS_ExternalProjectReference_ID (final int S_ExternalProjectReference_ID)
{
if (S_ExternalProjectReference_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExternalProjectReference_ID, S_ExternalProjectReference_ID);
}
@Override
public int getS_ExternalProjectReference_ID()
{
return get_ValueAsInt(COLUMNNAME_S_ExternalProjectReference_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalProjectReference.java
| 2
|
请完成以下Java代码
|
protected void onAfterInit()
{
final IBankStatementDAO bankStatementDAO = Services.get(IBankStatementDAO.class);
// Register the Document Reposting Handler
final IDocumentRepostingSupplierService documentBL = Services.get(IDocumentRepostingSupplierService.class);
documentBL.registerSupplier(new BankStatementDocumentRepostingSupplier(bankStatementDAO));
final IPaySelectionBL paySelectionBL = Services.get(IPaySelectionBL.class);
final IBankStatementListenerService bankStatementListenerService = Services.get(IBankStatementListenerService.class);
final IImportProcessFactory importProcessFactory = Services.get(IImportProcessFactory.class);
bankStatementListenerService.addListener(new PaySelectionBankStatementListener(paySelectionBL));
importProcessFactory.registerImportProcess(I_I_Datev_Payment.class, DatevPaymentImportProcess.class);
importProcessFactory.registerImportProcess(I_I_BankStatement.class, BankStatementImportProcess.class);
}
@Override
protected void registerInterceptors(final IModelValidationEngine engine)
{
final IBankStatementBL bankStatementBL = Services.get(IBankStatementBL.class);
final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
final ICashStatementBL cashStatementBL = Services.get(ICashStatementBL.class);
final BankAccountService bankAccountService = SpringContextHolder.instance.getBean(BankAccountService.class);
|
// Bank statement:
{
engine.addModelValidator(new de.metas.banking.model.validator.C_BankStatementLine(bankStatementBL));
}
// de.metas.banking.payment sub-module (code moved from swat main validator)
{
engine.addModelValidator(new de.metas.banking.payment.modelvalidator.C_Payment(bankStatementBL, paymentBL, cashStatementBL)); // 04203
engine.addModelValidator(new de.metas.banking.payment.modelvalidator.C_PaySelection(bankAccountService)); // 04203
engine.addModelValidator(de.metas.banking.payment.modelvalidator.C_PaySelectionLine.instance); // 04203
engine.addModelValidator(de.metas.banking.payment.modelvalidator.C_Payment_Request.instance); // 08596
engine.addModelValidator(de.metas.banking.payment.modelvalidator.C_AllocationHdr.instance); // 08972
}
}
@Override
protected void registerCallouts(final IProgramaticCalloutProvider calloutsRegistry)
{
final IBankStatementBL bankStatementBL = Services.get(IBankStatementBL.class);
calloutsRegistry.registerAnnotatedCallout(new de.metas.banking.callout.C_BankStatement(bankStatementBL));
calloutsRegistry.registerAnnotatedCallout(de.metas.banking.payment.callout.C_PaySelectionLine.instance);
calloutsRegistry.registerAnnotatedCallout(new de.metas.banking.callout.C_BankStatementLine(bankStatementBL));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\validator\Banking.java
| 1
|
请完成以下Java代码
|
String computeAndAppendCheckDigit(@NonNull final String parcelNumberWithoutCheckDigit)
{
// See #3991;
Check.assumeNotEmpty(parcelNumberWithoutCheckDigit, "Parcel Number is empty");
Check.assume(StringUtils.isNumeric(parcelNumberWithoutCheckDigit), "Parcel Number must only contain digits but it is: " + parcelNumberWithoutCheckDigit);
final int checkDigit = computeCheckDigit(parcelNumberWithoutCheckDigit);
return parcelNumberWithoutCheckDigit + checkDigit;
}
private int computeCheckDigit(@NonNull final String parcelNumberWithoutCheckDigit)
{
int sumOdd = 0;
int sumEven = 0;
for (int i = 0; i < parcelNumberWithoutCheckDigit.length(); i++)
{
|
// odd
if (i % 2 == 0)
{
sumOdd += Integer.parseInt(Character.toString(parcelNumberWithoutCheckDigit.charAt(i)));
}
else
{
sumEven += Integer.parseInt(Character.toString(parcelNumberWithoutCheckDigit.charAt(i)));
}
}
int result = 3 * sumOdd + sumEven;
result = (10 - result % 10) % 10;
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\ParcelNumberGenerator.java
| 1
|
请完成以下Java代码
|
public List<HistoricProcessInstance> findHistoricProcessInstanceIdsByQueryCriteria(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
return dataManager.findHistoricProcessInstanceIdsByQueryCriteria(historicProcessInstanceQuery);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricProcessInstancesByNativeQuery(parameterMap);
}
@Override
public List<HistoricProcessInstance> findHistoricProcessInstancesBySuperProcessInstanceId(String historicProcessInstanceId) {
return dataManager.findHistoricProcessInstancesBySuperProcessInstanceId(historicProcessInstanceId);
}
@Override
public List<String> findHistoricProcessInstanceIdsBySuperProcessInstanceIds(Collection<String> superProcessInstanceIds) {
return dataManager.findHistoricProcessInstanceIdsBySuperProcessInstanceIds(superProcessInstanceIds);
}
@Override
public List<String> findHistoricProcessInstanceIdsByProcessDefinitionId(String processDefinitionId) {
return dataManager.findHistoricProcessInstanceIdsByProcessDefinitionId(processDefinitionId);
}
@Override
public long findHistoricProcessInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricProcessInstanceCountByNativeQuery(parameterMap);
}
|
@Override
public void deleteHistoricProcessInstances(HistoricProcessInstanceQueryImpl historicProcessInstanceQuery) {
dataManager.deleteHistoricProcessInstances(historicProcessInstanceQuery);
}
@Override
public void bulkDeleteHistoricProcessInstances(Collection<String> processInstanceIds) {
dataManager.bulkDeleteHistoricProcessInstances(processInstanceIds);
}
protected HistoryManager getHistoryManager() {
return engineConfiguration.getHistoryManager();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public State nextState(Character character)
{
return nextState(character, false);
}
/**
* 按照character转移,任何节点转移失败会返回null
* @param character
* @return
*/
public State nextStateIgnoreRootState(Character character)
{
return nextState(character, true);
}
public State addState(Character character)
{
State nextState = nextStateIgnoreRootState(character);
if (nextState == null)
{
nextState = new State(this.depth + 1);
this.success.put(character, nextState);
}
return nextState;
}
public Collection<State> getStates()
{
return this.success.values();
}
public Collection<Character> getTransitions()
{
|
return this.success.keySet();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("State{");
sb.append("depth=").append(depth);
sb.append(", emits=").append(emits);
sb.append(", success=").append(success.keySet());
sb.append(", failure=").append(failure);
sb.append('}');
return sb.toString();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\ahocorasick\trie\State.java
| 1
|
请完成以下Java代码
|
public Class<? extends BaseElement> getBpmnElementType() {
return SendTask.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_TASK_SEND;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
SendTask sendTask = new SendTask();
BpmnXMLUtil.addXMLLocation(sendTask, xtr);
sendTask.setType(xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TYPE));
if ("##WebService".equals(xtr.getAttributeValue(null, ATTRIBUTE_TASK_IMPLEMENTATION))) {
sendTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE);
sendTask.setOperationRef(
parseOperationRef(xtr.getAttributeValue(null, ATTRIBUTE_TASK_OPERATION_REF), model)
);
}
parseChildElements(getXMLElementName(), sendTask, model, xtr);
return sendTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
SendTask sendTask = (SendTask) element;
if (StringUtils.isNotEmpty(sendTask.getType())) {
writeQualifiedAttribute(ATTRIBUTE_TYPE, sendTask.getType(), xtw);
}
}
@Override
protected boolean writeExtensionChildElements(
BaseElement element,
boolean didWriteExtensionStartElement,
XMLStreamWriter xtw
) throws Exception {
SendTask sendTask = (SendTask) element;
didWriteExtensionStartElement = FieldExtensionExport.writeFieldExtensions(
sendTask.getFieldExtensions(),
didWriteExtensionStartElement,
xtw
);
|
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {}
protected String parseOperationRef(String operationRef, BpmnModel model) {
String result = null;
if (StringUtils.isNotEmpty(operationRef)) {
int indexOfP = operationRef.indexOf(':');
if (indexOfP != -1) {
String prefix = operationRef.substring(0, indexOfP);
String resolvedNamespace = model.getNamespace(prefix);
result = resolvedNamespace + ":" + operationRef.substring(indexOfP + 1);
} else {
result = model.getTargetNamespace() + ":" + operationRef;
}
}
return result;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\SendTaskXMLConverter.java
| 1
|
请完成以下Java代码
|
class UrlJarFile extends JarFile {
private final UrlJarManifest manifest;
private final Consumer<JarFile> closeAction;
UrlJarFile(File file, Runtime.Version version, Consumer<JarFile> closeAction) throws IOException {
super(file, true, ZipFile.OPEN_READ, version);
// Registered only for test cleanup since parent class is JarFile
Cleaner.instance.register(this, null);
this.manifest = new UrlJarManifest(super::getManifest);
this.closeAction = closeAction;
}
@Override
public ZipEntry getEntry(String name) {
return UrlJarEntry.of(super.getEntry(name), this.manifest);
|
}
@Override
public Manifest getManifest() throws IOException {
return this.manifest.get();
}
@Override
public void close() throws IOException {
if (this.closeAction != null) {
this.closeAction.accept(this);
}
super.close();
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarFile.java
| 1
|
请完成以下Java代码
|
public final class RetryTopicBeanNames {
private RetryTopicBeanNames() {
}
/**
* The bean name of an internally managed retry topic configuration support, if
* needed.
*/
public static final String DEFAULT_RETRY_TOPIC_CONFIG_SUPPORT_BEAN_NAME =
"org.springframework.kafka.retrytopic.internalRetryTopicConfigurationSupport";
/**
* The bean name of the internally managed retry topic configurer.
*/
public static final String RETRY_TOPIC_CONFIGURER_BEAN_NAME =
"org.springframework.kafka.retrytopic.internalRetryTopicConfigurer";
/**
* The bean name of the internally managed destination topic resolver.
*/
public static final String DESTINATION_TOPIC_RESOLVER_BEAN_NAME =
"org.springframework.kafka.retrytopic.internalDestinationTopicResolver";
|
/**
* The bean name of the internally managed listener container factory.
*/
public static final String DEFAULT_LISTENER_CONTAINER_FACTORY_BEAN_NAME =
"defaultRetryTopicListenerContainerFactory";
/**
* The bean name of the internally managed listener container factory.
*/
public static final String DEFAULT_KAFKA_TEMPLATE_BEAN_NAME =
"defaultRetryTopicKafkaTemplate";
/**
* The bean name of the internally registered scheduler wrapper, if needed.
*/
public static final String DEFAULT_SCHEDULER_WRAPPER_BEAN_NAME =
"defaultRetryTopicSchedulerWrapper";
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicBeanNames.java
| 1
|
请完成以下Java代码
|
public class JarTool {
private Manifest manifest = new Manifest();
public void addToManifest(String key, String value) {
manifest.getMainAttributes()
.put(new Attributes.Name(key), value);
}
public void addDirectoryEntry(JarOutputStream target, String parentPath, File dir) throws IOException {
String remaining = "";
if (parentPath.endsWith(File.separator))
remaining = dir.getAbsolutePath()
.substring(parentPath.length());
else
remaining = dir.getAbsolutePath()
.substring(parentPath.length() + 1);
String name = remaining.replace("\\", "/");
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(dir.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
public void addFile(JarOutputStream target, String rootPath, String source) throws IOException {
BufferedInputStream in = null;
String remaining = "";
if (rootPath.endsWith(File.separator))
remaining = source.substring(rootPath.length());
else
remaining = source.substring(rootPath.length() + 1);
String name = remaining.replace("\\", "/");
JarEntry entry = new JarEntry(name);
entry.setTime(new File(source).lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
|
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
in.close();
}
public JarOutputStream openJar(String jarFile) throws IOException {
JarOutputStream target = new JarOutputStream(new FileOutputStream(jarFile), manifest);
return target;
}
public void setMainClass(String mainFQCN) {
if (mainFQCN != null && !mainFQCN.equals(""))
manifest.getMainAttributes()
.put(Attributes.Name.MAIN_CLASS, mainFQCN);
}
public void startManifest() {
manifest.getMainAttributes()
.put(Attributes.Name.MANIFEST_VERSION, "1.0");
}
}
|
repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\createjar\JarTool.java
| 1
|
请完成以下Java代码
|
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getAverage() {
return average;
}
public void setAverage(Double average) {
this.average = average;
}
public Date getMyDate() {
return myDate;
}
public void setMyDate(Date myDate) {
this.myDate = myDate;
|
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
|
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\convListVal\ConvListVal.java
| 1
|
请完成以下Java代码
|
public void setM_PricingSystem_ID (int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID));
}
/** Get Preise.
@return Preise */
public int getM_PricingSystem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
|
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PricingSystem.java
| 1
|
请完成以下Java代码
|
public void setBinaryData (byte[] BinaryData)
{
set_Value (COLUMNNAME_BinaryData, BinaryData);
}
/** Get Binärwert.
@return Binary Data
*/
@Override
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Fehler.
@param IsError
An Error occured in the execution
*/
@Override
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return An Error occured in the execution
*/
@Override
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenz.
@param Reference
Reference for this record
*/
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Reference for this record
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
/** Set Zusammenfassung.
@param Summary
Textual summary of this request
|
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Zusammenfassung.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerLog.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MovieService {
private final Logger logger = LoggerFactory.getLogger(MovieService.class);
private static List<Movie> moviesData;
static {
moviesData = new ArrayList<>();
Movie m1 = new Movie("MovieABC");
moviesData.add(m1);
Movie m2 = new Movie("MovieDEF");
moviesData.add(m2);
}
public Movie get(String name) {
Movie movie = null;
for (Movie m : moviesData) {
if (name.equalsIgnoreCase(m.getName())) {
movie = m;
logger.info("Found movie with name {} : {} ", name, movie);
}
}
|
return movie;
}
public void add(Movie movie) {
if (get(movie.getName()) == null) {
moviesData.add(movie);
logger.info("Added new movie - {}", movie.getName());
}
}
public void addAll(List<Movie> movies) {
for (Movie movie : movies) {
add(movie);
}
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\validation\listvalidation\service\MovieService.java
| 2
|
请完成以下Java代码
|
public int getAD_Sequence_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Sequence_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
|
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID)
{
if (PP_ComponentGenerator_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID);
}
@Override
public int getPP_ComponentGenerator_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator.java
| 1
|
请完成以下Java代码
|
private String getFieldValue(@NonNull final String field, @NonNull final String adLanguage)
{
final ITranslatableString value = fieldValues.get(field);
return value != null
? StringUtils.trimBlankToNull(value.translate(adLanguage))
: null;
}
private Comparable<?> getFieldComparingKey(@NonNull final String field, @NonNull final String adLanguage)
{
final Comparable<?> cmp = comparingKeys.get(field);
if (cmp != null)
{
return cmp;
}
return getFieldValue(field, adLanguage);
}
public static Comparator<WorkflowLauncherCaption> orderBy(@NonNull final String adLanguage, @NonNull final List<OrderBy> orderBys)
{
//
// Order by each given field
Comparator<WorkflowLauncherCaption> result = null;
for (final OrderBy orderBy : orderBys)
{
final Comparator<WorkflowLauncherCaption> cmp = toComparator(adLanguage, orderBy);
result = result != null
? result.thenComparing(cmp)
: cmp;
}
// Last, order by complete caption
final Comparator<WorkflowLauncherCaption> completeCaptionComparator = toCompleteCaptionComparator(adLanguage);
result = result != null
? result.thenComparing(completeCaptionComparator)
: completeCaptionComparator;
return result;
}
private static Comparator<WorkflowLauncherCaption> toComparator(@NonNull final String adLanguage, @NonNull final OrderBy orderBy)
{
final String field = orderBy.getField();
final Function<WorkflowLauncherCaption, Comparable<?>> keyExtractor = caption -> caption.getFieldComparingKey(field, adLanguage);
//noinspection unchecked
Comparator<Comparable<?>> keyComparator = (Comparator<Comparable<?>>)Comparator.naturalOrder();
if (!orderBy.isAscending())
{
keyComparator = keyComparator.reversed();
}
keyComparator = Comparator.nullsLast(keyComparator);
return Comparator.comparing(keyExtractor, keyComparator);
}
private static Comparator<WorkflowLauncherCaption> toCompleteCaptionComparator(@NonNull final String adLanguage)
|
{
final Function<WorkflowLauncherCaption, String> keyExtractor = caption -> caption.translate(adLanguage);
Comparator<String> keyComparator = Comparator.nullsLast(Comparator.naturalOrder());
return Comparator.comparing(keyExtractor, keyComparator);
}
//
//
//
@Value
@Builder
public static class OrderBy
{
@NonNull String field;
@Builder.Default boolean ascending = true;
public static OrderBy descending(@NonNull final ReferenceListAwareEnum field)
{
return descending(field.getCode());
}
public static OrderBy descending(@NonNull final String field)
{
return builder().field(field).ascending(false).build();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLauncherCaption.java
| 1
|
请完成以下Java代码
|
public static void setSuspensionState(ExecutionEntity executionEntity, SuspensionState state) {
if (executionEntity.getSuspensionState() == state.getStateCode()) {
throw new ActivitiException(
"Cannot set suspension state '" +
state +
"' for " +
executionEntity +
"': already in state '" +
state +
"'."
);
}
executionEntity.setSuspensionState(state.getStateCode());
dispatchStateChangeEvent(executionEntity, state);
}
public static void setSuspensionState(TaskEntity taskEntity, SuspensionState state) {
if (taskEntity.getSuspensionState() == state.getStateCode()) {
throw new ActivitiException(
"Cannot set suspension state '" +
state +
"' for " +
taskEntity +
"': already in state '" +
state +
"'."
);
}
|
taskEntity.setSuspensionState(state.getStateCode());
dispatchStateChangeEvent(taskEntity, state);
}
protected static void dispatchStateChangeEvent(Object entity, SuspensionState state) {
if (Context.getCommandContext() != null && Context.getCommandContext().getEventDispatcher().isEnabled()) {
ActivitiEventType eventType = null;
if (state == SuspensionState.ACTIVE) {
eventType = ActivitiEventType.ENTITY_ACTIVATED;
} else {
eventType = ActivitiEventType.ENTITY_SUSPENDED;
}
Context.getCommandContext()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(eventType, entity));
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\SuspensionState.java
| 1
|
请完成以下Java代码
|
public java.lang.String getSOCreditStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus);
}
/** Set Suchname.
@param Suchname
Alphanumeric identifier of the entity
*/
@Override
public void setSuchname (final java.lang.String Suchname)
{
set_Value (COLUMNNAME_Suchname, Suchname);
}
/** Get Suchname.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getSuchname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Suchname);
}
/** Set Titel.
@param Title
Bezeichnung für diesen Eintrag
*/
@Override
public void setTitle (final java.lang.String Title)
{
set_ValueNoCheck (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Bezeichnung für diesen Eintrag
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
/** Set Offener Saldo.
@param TotalOpenBalance
Gesamt der offenen Beträge in primärer Buchführungswährung
*/
@Override
public void setTotalOpenBalance (final BigDecimal TotalOpenBalance)
{
set_Value (COLUMNNAME_TotalOpenBalance, TotalOpenBalance);
}
/** Get Offener Saldo.
@return Gesamt der offenen Beträge in primärer Buchführungswährung
*/
@Override
public BigDecimal getTotalOpenBalance ()
{
final BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalOpenBalance);
if (bd == null)
{
return BigDecimal.ZERO;
}
return bd;
}
/** Set V_BPartnerCockpit_ID.
@param V_BPartnerCockpit_ID V_BPartnerCockpit_ID */
@Override
public void setV_BPartnerCockpit_ID (final int V_BPartnerCockpit_ID)
{
|
if (V_BPartnerCockpit_ID < 1)
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, null);
}
else
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, Integer.valueOf(V_BPartnerCockpit_ID));
}
}
/** Get V_BPartnerCockpit_ID.
@return V_BPartnerCockpit_ID */
@Override
public int getV_BPartnerCockpit_ID ()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_V_BPartnerCockpit_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/** Set Suchschlüssel.
@param value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setvalue (final java.lang.String value)
{
set_Value (COLUMNNAME_value, value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getvalue ()
{
return (java.lang.String)get_Value(COLUMNNAME_value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_V_BPartnerCockpit.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CollapserDemoController {
private Logger logger = LoggerFactory.getLogger(CollapserDemoController.class);
@Autowired
private CollapserDemoService collapserDemoService;
@GetMapping("/test")
public void test() throws ExecutionException, InterruptedException {
logger.info("[test][准备获取用户信息]");
Future<String> user01 = collapserDemoService.getUserFuture(1);
Future<String> user02 = collapserDemoService.getUserFuture(2);
logger.info("[test][提交获取用户信息]");
logger.info("[test][user({}) 的结果为({})]", 1, user01.get());
logger.info("[test][user({}) 的结果为({})]", 2, user02.get());
|
}
@GetMapping("/test_02")
public void test02() throws ExecutionException, InterruptedException {
logger.info("[test][准备获取用户信息]");
Future<String> user01 = collapserDemoService.getUserFuture(2);
Future<String> user02 = collapserDemoService.getUserFuture(1);
logger.info("[test][提交获取用户信息]");
logger.info("[test][user({}) 的结果为({})]", 1, user01.get());
logger.info("[test][user({}) 的结果为({})]", 2, user02.get());
}
}
|
repos\SpringBoot-Labs-master\labx-23\labx-23-scn-hystrix-actuator\src\main\java\cn\iocoder\springcloud\labx23\hystrixdemo\controller\CollapserDemoController.java
| 2
|
请完成以下Java代码
|
private void updateFromPreviousAddress()
{
final Instant now = SystemTime.asInstant();
final Map<Integer, I_C_BPartner_Location> newLocations = queryBL.createQueryBuilder(I_C_BPartner_Location.class)
.addCompareFilter(I_C_BPartner_Location.COLUMNNAME_ValidFrom, CompareQueryFilter.Operator.LESS_OR_EQUAL, now)
.addOnlyActiveRecordsFilter()
.addNotNull(I_C_BPartner_Location.COLUMNNAME_Previous_ID)
.orderBy(I_C_BPartner_Location.COLUMNNAME_ValidFrom)
.create()
.map(I_C_BPartner_Location.class, I_C_BPartner_Location::getC_BPartner_Location_ID);
final Map<Integer, Integer> oldLocToNewLoc = newLocations.values()
.stream()
.collect(Collectors.toMap(I_C_BPartner_Location::getPrevious_ID, I_C_BPartner_Location::getC_BPartner_Location_ID));
final List<BPartnerLocationId> partnerLocationIdsToDeactivate = newLocations.values()
.stream()
.map(loc -> BPartnerLocationId.ofRepoId(loc.getC_BPartner_ID(), loc.getPrevious_ID()))
.collect(Collectors.toList());
final Map<Integer, I_C_BPartner_Location> locationsToDeactivate = queryBL.createQueryBuilder(I_C_BPartner_Location.class)
.addInArrayFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_Location_ID, partnerLocationIdsToDeactivate)
.addOnlyActiveRecordsFilter()
.create()
.map(I_C_BPartner_Location.class, I_C_BPartner_Location::getC_BPartner_Location_ID);
if (Check.isEmpty(locationsToDeactivate.keySet()))
{
// nothing to do
return;
}
locationsToDeactivate.forEach((oldLocId, location) -> replaceLocation(location, newLocations.get(oldLocToNewLoc.get(oldLocId))));
}
private void replaceLocation(final I_C_BPartner_Location oldLocation, final I_C_BPartner_Location newLocation)
{
final BPartnerLocationId oldBPLocationId = BPartnerLocationId.ofRepoId(oldLocation.getC_BPartner_ID(), oldLocation.getC_BPartner_Location_ID());
final LocationId oldLocationId = LocationId.ofRepoId(oldLocation.getC_Location_ID());
final BPartnerLocationId newBPLocationId = BPartnerLocationId.ofRepoId(newLocation.getC_BPartner_ID(), newLocation.getC_BPartner_Location_ID());
final LocationId newLocationId = LocationId.ofRepoId(newLocation.getC_Location_ID());
|
logDeactivation(oldBPLocationId, newBPLocationId);
BPartnerLocationReplaceCommand.builder()
.oldLocationId(oldLocationId)
.oldBPLocationId(oldBPLocationId)
.oldLocation(oldLocation)
.newBPLocationId(newBPLocationId)
.newLocationId(newLocationId)
.newLocation(newLocation)
.build()
.execute();
}
@VisibleForTesting
protected void logDeactivation(final BPartnerLocationId oldBPLocationId, final BPartnerLocationId newBPLocationId)
{
addLog("Business Partner Location {} was deactivated because it's being replaced by {}.",
oldBPLocationId.getRepoId(), newBPLocationId.getRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\process\C_BPartner_Location_UpdateFromPreviousAddress.java
| 1
|
请完成以下Java代码
|
public void setMeta_Content (String Meta_Content)
{
set_Value (COLUMNNAME_Meta_Content, Meta_Content);
}
/** Get Meta Content Type.
@return Defines the type of content i.e. "text/html; charset=UTF-8"
*/
public String getMeta_Content ()
{
return (String)get_Value(COLUMNNAME_Meta_Content);
}
/** Set Meta Copyright.
@param Meta_Copyright
Contains Copyright information for the content
*/
public void setMeta_Copyright (String Meta_Copyright)
{
set_Value (COLUMNNAME_Meta_Copyright, Meta_Copyright);
}
/** Get Meta Copyright.
@return Contains Copyright information for the content
*/
public String getMeta_Copyright ()
{
return (String)get_Value(COLUMNNAME_Meta_Copyright);
}
/** Set Meta Publisher.
@param Meta_Publisher
Meta Publisher defines the publisher of the content
*/
public void setMeta_Publisher (String Meta_Publisher)
{
set_Value (COLUMNNAME_Meta_Publisher, Meta_Publisher);
}
/** Get Meta Publisher.
@return Meta Publisher defines the publisher of the content
*/
public String getMeta_Publisher ()
{
return (String)get_Value(COLUMNNAME_Meta_Publisher);
}
|
/** Set Meta RobotsTag.
@param Meta_RobotsTag
RobotsTag defines how search robots should handle this content
*/
public void setMeta_RobotsTag (String Meta_RobotsTag)
{
set_Value (COLUMNNAME_Meta_RobotsTag, Meta_RobotsTag);
}
/** Get Meta RobotsTag.
@return RobotsTag defines how search robots should handle this content
*/
public String getMeta_RobotsTag ()
{
return (String)get_Value(COLUMNNAME_Meta_RobotsTag);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java
| 1
|
请完成以下Java代码
|
private void createDetailLines()
{
StringBuffer sql = new StringBuffer (s_insert);
// (AD_PInstance_ID, Fact_Acct_ID,
sql.append("SELECT ").append(getPinstanceId().getRepoId()).append(",Fact_Acct_ID,");
// AD_Client_ID, AD_Org_ID, Created,CreatedBy, Updated,UpdatedBy,
sql.append(getAD_Client_ID()).append(",AD_Org_ID,Created,CreatedBy, Updated,UpdatedBy,");
// C_AcctSchema_ID, Account_ID, DateTrx, AccountValue, DateAcct, C_Period_ID,
sql.append("C_AcctSchema_ID, Account_ID, null, DateTrx, DateAcct, C_Period_ID,");
// AD_Table_ID, Record_ID, Line_ID,
sql.append("AD_Table_ID, Record_ID, Line_ID,");
// GL_Category_ID, GL_Budget_ID, C_Tax_ID, M_Locator_ID, PostingType,
sql.append("GL_Category_ID, GL_Budget_ID, C_Tax_ID, M_Locator_ID, PostingType,");
// C_Currency_ID, AmtSourceDr, AmtSourceCr, AmtSourceBalance,
sql.append("C_Currency_ID, AmtSourceDr,AmtSourceCr, AmtSourceDr-AmtSourceCr,");
// AmtAcctDr, AmtAcctCr, AmtAcctBalance, C_UOM_ID, Qty,
sql.append(" AmtAcctDr,AmtAcctCr, AmtAcctDr-AmtAcctCr, C_UOM_ID,Qty,");
// M_Product_ID, C_BPartner_ID, AD_OrgTrx_ID, C_LocFrom_ID,C_LocTo_ID,
sql.append ("M_Product_ID, C_BPartner_ID, AD_OrgTrx_ID, C_LocFrom_ID,C_LocTo_ID,");
// C_SalesRegion_ID, C_Project_ID, C_Campaign_ID, C_Activity_ID,
sql.append ("C_SalesRegion_ID, C_Project_ID, C_Campaign_ID, C_Activity_ID,");
// User1_ID, User2_ID, A_Asset_ID, Description)
sql.append ("User1_ID, User2_ID, A_Asset_ID, Description");
//
sql.append(" FROM Fact_Acct WHERE AD_Client_ID=").append(getAD_Client_ID())
.append (" AND ").append(m_parameterWhere)
.append(" AND DateAcct >= ").append(DB.TO_DATE(p_DateAcct_From, DisplayType.Date))
.append(" AND TRUNC(DateAcct) <= ").append(DB.TO_DATE(p_DateAcct_To, DisplayType.Date));
//
int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), get_TrxName());
|
if (no == 0)
log.debug(sql.toString());
log.debug("#" + no + " (Account_ID=" + p_Account_ID + ")");
// Update AccountValue
String sql2 = "UPDATE T_TrialBalance tb SET AccountValue = "
+ "(SELECT Value FROM C_ElementValue ev WHERE ev.C_ElementValue_ID=tb.Account_ID) "
+ "WHERE tb.Account_ID IS NOT NULL";
no = DB.executeUpdateAndSaveErrorOnFail(sql2, get_TrxName());
if (no > 0)
log.debug("Set AccountValue #" + no);
} // createDetailLines
} // TrialBalance
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\TrialBalance.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PickingCandidateId implements RepoIdAware
{
@JsonCreator
public static PickingCandidateId ofRepoId(final int repoId)
{
return new PickingCandidateId(repoId);
}
@Nullable
public static PickingCandidateId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<PickingCandidateId> ids)
{
if (ids.isEmpty())
{
return ImmutableSet.of();
}
return ids.stream().map(PickingCandidateId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
int repoId;
private PickingCandidateId(final int pickingCandidateRepoId)
{
repoId = Check.assumeGreaterThanZero(pickingCandidateRepoId, "pickingCandidateRepoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
|
}
public static int toRepoId(@Nullable final PickingCandidateId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(final PickingCandidateId o1, final PickingCandidateId o2)
{
return Objects.equals(o1, o2);
}
public TableRecordReference toTableRecordReference()
{
return TableRecordReference.of(I_M_Picking_Candidate.Table_Name, getRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidateId.java
| 2
|
请完成以下Java代码
|
public class DataSourceCachePool {
/** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */
private static Map<String, DruidDataSource> dbSources = new HashMap<>();
private static RedisTemplate<String, Object> redisTemplate;
private static RedisTemplate<String, Object> getRedisTemplate() {
if (redisTemplate == null) {
redisTemplate = (RedisTemplate<String, Object>) SpringContextUtils.getBean("redisTemplate");
}
return redisTemplate;
}
/**
* 获取多数据源缓存
*
* @param dbKey
* @return
*/
public static DynamicDataSourceModel getCacheDynamicDataSourceModel(String dbKey) {
String redisCacheKey = CacheConstant.SYS_DYNAMICDB_CACHE + dbKey;
if (getRedisTemplate().hasKey(redisCacheKey)) {
return (DynamicDataSourceModel) getRedisTemplate().opsForValue().get(redisCacheKey);
}
CommonAPI commonApi = SpringContextUtils.getBean(CommonAPI.class);
DynamicDataSourceModel dbSource = commonApi.getDynamicDbSourceByCode(dbKey);
if (dbSource != null) {
getRedisTemplate().opsForValue().set(redisCacheKey, dbSource);
}
return dbSource;
}
public static DruidDataSource getCacheBasicDataSource(String dbKey) {
return dbSources.get(dbKey);
}
/**
* put 数据源缓存
*
* @param dbKey
* @param db
*/
public static void putCacheBasicDataSource(String dbKey, DruidDataSource db) {
dbSources.put(dbKey, db);
}
/**
* 清空数据源缓存
*/
public static void cleanAllCache() {
//关闭数据源连接
|
for(Map.Entry<String, DruidDataSource> entry : dbSources.entrySet()){
String dbkey = entry.getKey();
DruidDataSource druidDataSource = entry.getValue();
if(druidDataSource!=null && druidDataSource.isEnable()){
druidDataSource.close();
}
//清空redis缓存
getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbkey);
}
//清空缓存
dbSources.clear();
}
public static void removeCache(String dbKey) {
//关闭数据源连接
DruidDataSource druidDataSource = dbSources.get(dbKey);
if(druidDataSource!=null && druidDataSource.isEnable()){
druidDataSource.close();
}
//清空redis缓存
getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbKey);
//清空缓存
dbSources.remove(dbKey);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\dynamic\db\DataSourceCachePool.java
| 1
|
请完成以下Java代码
|
public static class Essence extends LdapUserDetailsImpl.Essence {
public Essence() {
}
public Essence(DirContextOperations ctx) {
super(ctx);
setCn(ctx.getStringAttributes("cn"));
setGivenName(ctx.getStringAttribute("givenName"));
setSn(ctx.getStringAttribute("sn"));
setDescription(ctx.getStringAttribute("description"));
setTelephoneNumber(ctx.getStringAttribute("telephoneNumber"));
Object password = ctx.getObjectAttribute("userPassword");
if (password != null) {
setPassword(LdapUtils.convertPasswordToString(password));
}
}
public Essence(Person copyMe) {
super(copyMe);
setGivenName(copyMe.givenName);
setSn(copyMe.sn);
setDescription(copyMe.getDescription());
setTelephoneNumber(copyMe.getTelephoneNumber());
((Person) this.instance).cn = new ArrayList<>(copyMe.cn);
}
@Override
protected LdapUserDetailsImpl createTarget() {
return new Person();
}
public void setGivenName(String givenName) {
((Person) this.instance).givenName = givenName;
}
public void setSn(String sn) {
|
((Person) this.instance).sn = sn;
}
public void setCn(String[] cn) {
((Person) this.instance).cn = Arrays.asList(cn);
}
public void addCn(String value) {
((Person) this.instance).cn.add(value);
}
public void setTelephoneNumber(String tel) {
((Person) this.instance).telephoneNumber = tel;
}
public void setDescription(String desc) {
((Person) this.instance).description = desc;
}
@Override
public LdapUserDetails createUserDetails() {
Person p = (Person) super.createUserDetails();
Assert.notNull(p.cn, "person.sn cannot be null");
Assert.notEmpty(p.cn, "person.cn cannot be empty");
// TODO: Check contents for null entries
return p;
}
}
}
|
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\Person.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Boolean getAsyncCount() {
return Boolean.valueOf(getProperty("asyncCount"));
}
public void setAsyncCount(Boolean asyncCount) {
setProperty("asyncCount", asyncCount.toString());
}
public String getCountSqlParser() {
return getProperty("countSqlParser");
}
public void setCountSqlParser(String countSqlParser) {
setProperty("countSqlParser", countSqlParser);
}
public String getOrderBySqlParser() {
return getProperty("orderBySqlParser");
}
public void setOrderBySqlParser(String orderBySqlParser) {
setProperty("orderBySqlParser", orderBySqlParser);
}
|
public String getSqlServerSqlParser() {
return getProperty("sqlServerSqlParser");
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
setProperty("sqlServerSqlParser", sqlServerSqlParser);
}
public void setBannerEnabled(Boolean bannerEnabled) {
setProperty("banner",bannerEnabled.toString());
}
public Boolean getBannerEnabled() {
return Boolean.valueOf(getProperty("banner"));
}
}
|
repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperProperties.java
| 2
|
请完成以下Java代码
|
public void setRefundBase (java.lang.String RefundBase)
{
set_Value (COLUMNNAME_RefundBase, RefundBase);
}
/** Get Vergütung basiert auf.
@return Vergütung basiert auf */
@Override
public java.lang.String getRefundBase ()
{
return (java.lang.String)get_Value(COLUMNNAME_RefundBase);
}
/**
* RefundInvoiceType AD_Reference_ID=540863
* Reference name: RefundInvoiceType
*/
public static final int REFUNDINVOICETYPE_AD_Reference_ID=540863;
/** Invoice = Invoice */
public static final String REFUNDINVOICETYPE_Invoice = "Invoice";
/** Creditmemo = Creditmemo */
public static final String REFUNDINVOICETYPE_Creditmemo = "Creditmemo";
/** Set Rückvergütung per.
@param RefundInvoiceType Rückvergütung per */
@Override
public void setRefundInvoiceType (java.lang.String RefundInvoiceType)
{
set_Value (COLUMNNAME_RefundInvoiceType, RefundInvoiceType);
}
/** Get Rückvergütung per.
@return Rückvergütung per */
@Override
public java.lang.String getRefundInvoiceType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RefundInvoiceType);
}
/**
* RefundMode AD_Reference_ID=540903
* Reference name: RefundMode
*/
public static final int REFUNDMODE_AD_Reference_ID=540903;
/** Tiered = T */
public static final String REFUNDMODE_Tiered = "T";
/** Accumulated = A */
public static final String REFUNDMODE_Accumulated = "A";
/** Set Staffel-Modus.
@param RefundMode Staffel-Modus */
@Override
public void setRefundMode (java.lang.String RefundMode)
{
set_Value (COLUMNNAME_RefundMode, RefundMode);
}
/** Get Staffel-Modus.
|
@return Staffel-Modus */
@Override
public java.lang.String getRefundMode ()
{
return (java.lang.String)get_Value(COLUMNNAME_RefundMode);
}
/** Set Rückvergütung %.
@param RefundPercent Rückvergütung % */
@Override
public void setRefundPercent (java.math.BigDecimal RefundPercent)
{
set_Value (COLUMNNAME_RefundPercent, RefundPercent);
}
/** Get Rückvergütung %.
@return Rückvergütung % */
@Override
public java.math.BigDecimal getRefundPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RefundPercent);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_RefundConfig.java
| 1
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setId(Integer id) {
this.id = id;
}
public void setFirstName(String firstName) {
|
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
}
|
repos\springboot-demo-master\GraphQL\src\main\java\com\et\graphql\model\Author.java
| 1
|
请完成以下Java代码
|
public Element setLang (String lang)
{
addAttribute ("lang", lang);
addAttribute ("xml:lang", lang);
return this;
}
/**
* Adds an Element to the element.
*
* @param hashcode
* name of element for hash table
* @param element
* Adds an Element to the element.
*/
public applet addElement (String hashcode, Element element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param hashcode
* name of element for hash table
* @param element
* Adds an Element to the element.
*/
public applet addElement (String hashcode, String element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Add an element to the element
*
* @param element
* a string representation of the element
|
*/
public applet addElement (String element)
{
addElementToRegistry (element);
return (this);
}
/**
* Add an element to the element
*
* @param element
* an element to add
*/
public applet addElement (Element element)
{
addElementToRegistry (element);
return (this);
}
/**
* Removes an Element from the element.
*
* @param hashcode
* the name of the element to be removed.
*/
public applet removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\applet.java
| 1
|
请完成以下Java代码
|
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
if (!Ini.isSwingClient())
return null;
//
// UI
boolean changed = false;
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
ValueNamePair laf = getLookByName(sysConfigBL.getValue(SYSCONFIG_UILookFeel, Env.getAD_Client_ID(Env.getCtx())));
ValueNamePair theme = getThemeByName(sysConfigBL.getValue(SYSCONFIG_UITheme, Env.getAD_Client_ID(Env.getCtx())));
if (laf != null && theme != null)
{
String clazz = laf.getValue();
String currentLaf = UIManager.getLookAndFeel().getClass().getName();
if (!Check.isEmpty(clazz) && !currentLaf.equals(clazz))
{
// laf changed
AdempierePLAF.setPLAF(laf, theme, true);
AEnv.updateUI();
changed = true;
}
else
{
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalTheme currentTheme = MetalLookAndFeel.getCurrentTheme();
String themeClass = currentTheme.getClass().getName();
String sTheme = theme.getValue();
if (sTheme != null && sTheme.length() > 0 && !sTheme.equals(themeClass))
{
ValueNamePair plaf = ValueNamePair.of(
UIManager.getLookAndFeel().getClass().getName(),
UIManager.getLookAndFeel().getName());
AdempierePLAF.setPLAF(plaf, theme, true);
AEnv.updateUI();
changed = true;
}
}
}
}
//
if (changed)
Ini.saveProperties();
//
// Make sure the UIDefauls from sysconfig were loaded
SysConfigUIDefaultsRepository.ofCurrentLookAndFeelId()
.loadAllFromSysConfigTo(UIManager.getDefaults());
return null;
}
@Override
public String modelChange(PO po, int type) throws Exception
{
if (InterfaceWrapperHelper.isInstanceOf(po, I_AD_SysConfig.class) && (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE))
{
final I_AD_SysConfig cfg = InterfaceWrapperHelper.create(po, I_AD_SysConfig.class);
final String name = cfg.getName();
if (name.equals(SYSCONFIG_UILookFeel))
{
if (getLookByName(cfg.getValue()) == null)
{
throw new AdempiereException("@NotFound@ " + cfg.getValue());
}
}
|
else if (name.equals(SYSCONFIG_UITheme))
{
if (getThemeByName(cfg.getValue()) == null)
{
throw new AdempiereException("@NotFound@ " + cfg.getValue());
}
}
}
return null;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
private static ValueNamePair getLookByName(String name)
{
if (Check.isEmpty(name, true))
return null;
for (ValueNamePair vnp : AdempierePLAF.getPLAFs())
{
if (vnp.getName().equals(name))
return vnp;
}
return null;
}
private static ValueNamePair getThemeByName(String name)
{
if (Check.isEmpty(name, true))
return null;
for (ValueNamePair vnp : AdempierePLAF.getThemes())
{
if (vnp.getName().equals(name))
return vnp;
}
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\model\IniDefaultsValidator.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class Remoteip {
/**
* Internal proxies that are to be trusted. Can be set as a comma separate list of
* CIDR or as a regular expression.
*/
private String internalProxies = "192.168.0.0/16, 172.16.0.0/12, 169.254.0.0/16, fc00::/7, "
+ "10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, fe80::/10, ::1/128";
/**
* Header that holds the incoming protocol, usually named "X-Forwarded-Proto".
*/
private @Nullable String protocolHeader;
/**
* Value of the protocol header indicating whether the incoming request uses SSL.
*/
private String protocolHeaderHttpsValue = "https";
/**
* Name of the HTTP header from which the remote host is extracted.
*/
private String hostHeader = "X-Forwarded-Host";
/**
* Name of the HTTP header used to override the original port value.
*/
private String portHeader = "X-Forwarded-Port";
/**
* Name of the HTTP header from which the remote IP is extracted. For instance,
* 'X-FORWARDED-FOR'.
*/
private @Nullable String remoteIpHeader;
/**
* Regular expression defining proxies that are trusted when they appear in the
* "remote-ip-header" header.
*/
private @Nullable String trustedProxies;
public String getInternalProxies() {
return this.internalProxies;
}
public void setInternalProxies(String internalProxies) {
this.internalProxies = internalProxies;
}
public @Nullable String getProtocolHeader() {
return this.protocolHeader;
}
public void setProtocolHeader(@Nullable String protocolHeader) {
this.protocolHeader = protocolHeader;
}
public String getProtocolHeaderHttpsValue() {
return this.protocolHeaderHttpsValue;
}
public String getHostHeader() {
return this.hostHeader;
}
public void setHostHeader(String hostHeader) {
|
this.hostHeader = hostHeader;
}
public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) {
this.protocolHeaderHttpsValue = protocolHeaderHttpsValue;
}
public String getPortHeader() {
return this.portHeader;
}
public void setPortHeader(String portHeader) {
this.portHeader = portHeader;
}
public @Nullable String getRemoteIpHeader() {
return this.remoteIpHeader;
}
public void setRemoteIpHeader(@Nullable String remoteIpHeader) {
this.remoteIpHeader = remoteIpHeader;
}
public @Nullable String getTrustedProxies() {
return this.trustedProxies;
}
public void setTrustedProxies(@Nullable String trustedProxies) {
this.trustedProxies = trustedProxies;
}
}
/**
* When to use APR.
*/
public enum UseApr {
/**
* Always use APR and fail if it's not available.
*/
ALWAYS,
/**
* Use APR if it is available.
*/
WHEN_AVAILABLE,
/**
* Never use APR.
*/
NEVER
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\TomcatServerProperties.java
| 2
|
请完成以下Java代码
|
public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseIntermediateSignalCatchEventDefinition(Element signalEventDefinition, ActivityImpl signalActivity) {
// start and end event listener are set by parseIntermediateCatchEvent()
}
@Override
public void parseBoundarySignalEventDefinition(Element signalEventDefinition, boolean interrupting, ActivityImpl signalActivity) {
// start and end event listener are set by parseBoundaryEvent()
}
@Override
public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseCompensateEventDefinition(Element compensateEventDefinition, ActivityImpl compensationActivity) {
}
@Override
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
}
@Override
public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) {
addStartEventListener(activity);
addEndEventListener(activity);
|
}
@Override
public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) {
}
@Override
public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) {
}
@Override
public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) {
}
@Override
public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) {
}
@Override
public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) {
}
public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) {
}
@Override
public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) {
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventParseListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ITemplateResolver javascriptTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/js/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
return resolver;
}
private ITemplateResolver plainTemplateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/txt/");
resolver.setCacheable(false);
resolver.setTemplateMode(TemplateMode.TEXT);
return resolver;
}
@Bean
@Description("Spring Message Resolver")
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
|
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**", "/css/**")
.addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/");
}
@Override
@Description("Custom Conversion Service")
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new NameFormatter());
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getReferenceCodeQualifier() {
return referenceCodeQualifier;
}
/**
* Sets the value of the referenceCodeQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceCodeQualifier(String value) {
this.referenceCodeQualifier = value;
}
/**
* Gets the value of the referenceNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the referenceNumberDate property.
*
* @return
* possible object is
|
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getReferenceNumberDate() {
return referenceNumberDate;
}
/**
* Sets the value of the referenceNumberDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setReferenceNumberDate(XMLGregorianCalendar value) {
this.referenceNumberDate = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ReferenceType.java
| 2
|
请完成以下Java代码
|
public Boolean getType() {
return this.type;
}
public void setType(Boolean type) {
this.type = type;
}
public InvalidDependencyInformation getDependencies() {
return this.dependencies;
}
public void triggerInvalidDependencies(List<String> dependencies) {
this.dependencies = new InvalidDependencyInformation(dependencies);
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid)
.add("javaVersion=" + this.javaVersion)
.add("language=" + this.language)
.add("configurationFileFormat=" + this.configurationFileFormat)
.add("packaging=" + this.packaging)
.add("type=" + this.type)
.add("dependencies=" + this.dependencies)
.add("message='" + this.message + "'")
.toString();
}
}
/**
* Invalid dependencies information.
*/
public static class InvalidDependencyInformation {
private boolean invalid = true;
private final List<String> values;
|
public InvalidDependencyInformation(List<String> values) {
this.values = values;
}
public boolean isInvalid() {
return this.invalid;
}
public List<String> getValues() {
return this.values;
}
@Override
public String toString() {
return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString();
}
}
}
|
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
| 1
|
请完成以下Java代码
|
public class TbCoapMessageObserver implements MessageObserver {
private final int msgId;
private final Consumer<Integer> onAcknowledge;
private final Consumer<Integer> onTimeout;
@Override
public boolean isInternal() {
return false;
}
@Override
public void onRetransmission() {
}
@Override
public void onResponse(Response response) {
}
@Override
public void onAcknowledgement() {
onAcknowledge.accept(msgId);
}
@Override
public void onReject() {
}
@Override
public void onTimeout() {
if (onTimeout != null) {
onTimeout.accept(msgId);
}
}
@Override
public void onCancel() {
}
@Override
public void onReadyToSend() {
}
@Override
public void onConnecting() {
}
@Override
public void onDtlsRetransmission(int flight) {
}
|
@Override
public void onSent(boolean retransmission) {
}
@Override
public void onSendError(Throwable error) {
}
@Override
public void onResponseHandlingError(Throwable cause) {
}
@Override
public void onContextEstablished(EndpointContext endpointContext) {
}
@Override
public void onTransferComplete() {
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\TbCoapMessageObserver.java
| 1
|
请完成以下Java代码
|
public void setReadWrite (boolean rw)
{
this.setEnabled(rw);
} // setReadWrite
/**
* Set Label For
* @param c component
*/
@Override
public void setLabelFor (Component c)
{
//reset old if any
if (getLabelFor() != null && getLabelFor() instanceof JTextComponent)
{
((JTextComponent)getLabelFor()).setFocusAccelerator('\0');
}
super.setLabelFor(c);
if (c.getName() == null)
c.setName(getName());
//workaround for focus accelerator issue
if (c instanceof JTextComponent)
{
if (m_savedMnemonic > 0)
{
((JTextComponent)c).setFocusAccelerator(m_savedMnemonic);
|
}
}
} // setLabelFor
/**
* @return Returns the savedMnemonic.
*/
public char getSavedMnemonic ()
{
return m_savedMnemonic;
} // getSavedMnemonic
/**
* @param savedMnemonic The savedMnemonic to set.
*/
public void setSavedMnemonic (char savedMnemonic)
{
m_savedMnemonic = savedMnemonic;
} // getSavedMnemonic
} // CLabel
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CLabel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTaxExemption() {
return taxExemption;
}
/**
* Sets the value of the taxExemption property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTaxExemption(String value) {
this.taxExemption = value;
}
/**
* Element used to aggregate certain tax information.Gets the value of the item 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 item property.
|
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getItem().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ItemType }
*
*
*/
public List<ItemType> getItem() {
if (item == null) {
item = new ArrayList<ItemType>();
}
return this.item;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\VATType.java
| 2
|
请完成以下Java代码
|
/* package */ class AnnotatedModelInterceptorDisabler
{
public static AnnotatedModelInterceptorDisabler get()
{
return INSTANCE;
}
private final static AnnotatedModelInterceptorDisabler INSTANCE = new AnnotatedModelInterceptorDisabler();
final static String SYS_CONFIG_NAME_PREFIX = "InterceptorEnabled_";
private final ExtendedMemorizingSupplier<Set<String>> disabledPointcutIdsSupplier = ExtendedMemorizingSupplier.of(AnnotatedModelInterceptorDisabler::retrieveDisabledPointcutIds);
@VisibleForTesting
AnnotatedModelInterceptorDisabler()
{
// Make sure our cache it's invalidated when AD_SysConfig records are changed
CacheMgt.get().addCacheResetListener(I_AD_SysConfig.Table_Name, request -> invalidateCache());
}
/**
* Invalidates disabled pointcuts cache.
*
* @return 1
*/
@VisibleForTesting
int invalidateCache()
{
disabledPointcutIdsSupplier.forget();
return 1;
}
/**
* Returns a message that tells an admin how to disable the given {@code pointcut}.
*/
static String createHowtoDisableMessage(@NonNull final Pointcut pointcut)
{
final String pointcutId = pointcut.getPointcutId();
return String.format("Model interceptor method %s threw an exception.\nYou can disable this method with SysConfig %s='N' (with AD_Client_ID and AD_Org_ID=0!)",
pointcutId, createDisabledSysConfigKey(pointcutId));
|
}
private static String createDisabledSysConfigKey(@NonNull final String pointcutId)
{
return SYS_CONFIG_NAME_PREFIX + pointcutId;
}
private static ImmutableSet<String> retrieveDisabledPointcutIds()
{
final boolean removePrefix = true;
return Services.get(ISysConfigBL.class)
.getValuesForPrefix(SYS_CONFIG_NAME_PREFIX, removePrefix, ClientAndOrgId.SYSTEM)
.entrySet()
.stream()
.filter(entry -> !DisplayType.toBoolean(entry.getValue())) // =Y
.map(Entry::getKey)
.collect(ImmutableSet.toImmutableSet());
}
public boolean isDisabled(@NonNull final Pointcut pointcut)
{
final String pointcutId = pointcut.getPointcutId();
return disabledPointcutIdsSupplier.get().contains(pointcutId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\AnnotatedModelInterceptorDisabler.java
| 1
|
请完成以下Java代码
|
public class TbRedisLwM2MModelConfigStore implements TbLwM2MModelConfigStore {
private static final String MODEL_EP = "MODEL#EP#";
private final RedisConnectionFactory connectionFactory;
@Override
public List<LwM2MModelConfig> getAll() {
try (var connection = connectionFactory.getConnection()) {
List<LwM2MModelConfig> configs = new ArrayList<>();
ScanOptions scanOptions = ScanOptions.scanOptions().count(100).match(MODEL_EP + "*").build();
List<Cursor<byte[]>> scans = new ArrayList<>();
if (connection instanceof RedisClusterConnection) {
((RedisClusterConnection) connection).clusterGetNodes().forEach(node -> {
scans.add(((RedisClusterConnection) connection).scan(node, scanOptions));
});
} else {
scans.add(connection.scan(scanOptions));
}
scans.forEach(scan -> {
scan.forEachRemaining(key -> {
byte[] element = connection.get(key);
configs.add(JacksonUtil.fromBytes(element, LwM2MModelConfig.class));
});
});
return configs;
}
}
@Override
|
public void put(LwM2MModelConfig modelConfig) {
byte[] clientSerialized = JacksonUtil.writeValueAsBytes(modelConfig);
try (var connection = connectionFactory.getConnection()) {
connection.getSet(getKey(modelConfig.getEndpoint()), clientSerialized);
}
}
@Override
public void remove(String endpoint) {
try (var connection = connectionFactory.getConnection()) {
connection.del(getKey(endpoint));
}
}
private byte[] getKey(String endpoint) {
return (MODEL_EP + endpoint).getBytes();
}
}
|
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbRedisLwM2MModelConfigStore.java
| 1
|
请完成以下Java代码
|
public class JessWithData {
public static final String RULES_BONUS_FILE = "bonus.clp";
private static Logger log = Logger.getLogger("JessWithData");
public static void main(String[] args) throws JessException {
Rete engine = new Rete();
engine.reset();
engine.batch(RULES_BONUS_FILE);
prepareData(engine);
engine.run();
checkResults(engine);
}
|
private static void checkResults(Rete engine) {
Iterator results = engine.getObjects(new Filter.ByClass(Answer.class));
while (results.hasNext()) {
Answer answer = (Answer) results.next();
log.info(answer.toString());
}
}
private static void prepareData(Rete engine) throws JessException {
Question question = new Question("Can I have a bonus?", -5);
log.info(question.toString());
engine.add(question);
}
}
|
repos\tutorials-master\rule-engines-modules\jess\src\main\java\com\baeldung\rules\jess\JessWithData.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
protected void writeToValueFields(SpinValue value, ValueFields valueFields, byte[] serializedValue) {
valueFields.setByteArrayValue(serializedValue);
}
protected void updateTypedValue(SpinValue value, String serializedStringValue) {
SpinValueImpl spinValue = (SpinValueImpl) value;
spinValue.setValueSerialized(serializedStringValue);
spinValue.setSerializationDataFormat(serializationDataFormat);
}
protected boolean canSerializeValue(Object value) {
if (value instanceof Spin<?>) {
Spin<?> wrapper = (Spin<?>) value;
return wrapper.getDataFormatName().equals(serializationDataFormat);
}
return false;
}
protected byte[] serializeToByteArray(Object deserializedObject) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter outWriter = new OutputStreamWriter(out, Context.getProcessEngineConfiguration().getDefaultCharset());
BufferedWriter bufferedWriter = new BufferedWriter(outWriter);
try {
Spin<?> wrapper = (Spin<?>) deserializedObject;
wrapper.writeToWriter(bufferedWriter);
return out.toByteArray();
}
finally {
IoUtil.closeSilently(out);
|
IoUtil.closeSilently(outWriter);
IoUtil.closeSilently(bufferedWriter);
}
}
protected Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(object);
InputStreamReader inReader = new InputStreamReader(bais, Context.getProcessEngineConfiguration().getDefaultCharset());
BufferedReader bufferedReader = new BufferedReader(inReader);
try {
Object wrapper = dataFormat.getReader().readInput(bufferedReader);
return dataFormat.createWrapperInstance(wrapper);
}
finally{
IoUtil.closeSilently(bais);
IoUtil.closeSilently(inReader);
IoUtil.closeSilently(bufferedReader);
}
}
protected boolean isSerializationTextBased() {
return true;
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinValueSerializer.java
| 1
|
请完成以下Java代码
|
Book saveOrUpdate(@RequestBody Book newBook, @PathVariable Long id) {
return repository.findById(id)
.map(x -> {
x.setName(newBook.getName());
x.setAuthor(newBook.getAuthor());
x.setPrice(newBook.getPrice());
return repository.save(x);
})
.orElseGet(() -> {
newBook.setId(id);
return repository.save(newBook);
});
}
// update author only
@PatchMapping("/books/{id}")
Book patch(@RequestBody Map<String, String> update, @PathVariable Long id) {
return repository.findById(id)
.map(x -> {
String author = update.get("author");
if (!StringUtils.isEmpty(author)) {
x.setAuthor(author);
// better create a custom method to update a value = :newValue where id = :id
return repository.save(x);
} else {
throw new BookUnSupportedFieldPatchException(update.keySet());
|
}
})
.orElseGet(() -> {
throw new BookNotFoundException(id);
});
}
@DeleteMapping("/books/{id}")
void deleteBook(@PathVariable Long id) {
repository.deleteById(id);
}
}
|
repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\BookController.java
| 1
|
请完成以下Java代码
|
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Supervisor.
@return Supervisor for this user/organization - used for escalation and approval
*/
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Job.java
| 1
|
请完成以下Java代码
|
public static void exceptionWithAddExact() {
int value = Integer.MAX_VALUE-1;
for(int i = 0; i < 4; i++) {
System.out.println(value);
value = Math.addExact(value, 1);
}
}
public static int addExact(int x, int y) {
int r = x + y;
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("int overflow");
}
return r;
}
public static void demonstrateUnderflow() {
for(int i = 1073; i <= 1076; i++) {
System.out.println("2^" + i + " = " + Math.pow(2, -i));
}
}
|
public static double powExact(double base, double exponent)
{
if(base == 0.0) {
return 0.0;
}
double result = Math.pow(base, exponent);
if(result == Double.POSITIVE_INFINITY ) {
throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY");
} else if(result == Double.NEGATIVE_INFINITY) {
throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY");
} else if(Double.compare(-0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in negative zero");
} else if(Double.compare(+0.0f, result) == 0) {
throw new ArithmeticException("Double overflow resulting in positive zero");
}
return result;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-math\src\main\java\com\baeldung\overflow\Overflow.java
| 1
|
请完成以下Java代码
|
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_Value (COLUMNNAME_C_AcctSchema_ID, null);
else
set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Accounting Schema.
@return Rules for accounting
*/
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Date From.
@param DateFrom
Starting date for a range
*/
public void setDateFrom (Timestamp DateFrom)
{
set_Value (COLUMNNAME_DateFrom, DateFrom);
}
/** Get Date From.
@return Starting date for a range
*/
public Timestamp getDateFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Date To.
@param DateTo
End date of a date range
*/
public void setDateTo (Timestamp DateTo)
{
set_Value (COLUMNNAME_DateTo, DateTo);
}
/** Get Date To.
@return End date of a date range
*/
public Timestamp getDateTo ()
{
return (Timestamp)get_Value(COLUMNNAME_DateTo);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
|
/** Set GL Fund.
@param GL_Fund_ID
General Ledger Funds Control
*/
public void setGL_Fund_ID (int GL_Fund_ID)
{
if (GL_Fund_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID));
}
/** Get GL Fund.
@return General Ledger Funds Control
*/
public int getGL_Fund_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Fund.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JXlsExporter setResourceBundle(final ResourceBundle resourceBundle)
{
this._resourceBundle = resourceBundle;
return this;
}
private ResourceBundle getResourceBundle()
{
if (_resourceBundle != null)
{
return _resourceBundle;
}
if (!Check.isEmpty(_templateResourceName, true))
{
String baseName = null;
try
{
final int dotIndex = _templateResourceName.lastIndexOf('.');
baseName = dotIndex <= 0 ? _templateResourceName : _templateResourceName.substring(0, dotIndex);
return ResourceBundle.getBundle(baseName, getLocale(), getLoader());
}
catch (final MissingResourceException e)
{
logger.debug("No resource found for {}", baseName);
}
}
return null;
|
}
public Map<String, String> getResourceBundleAsMap()
{
final ResourceBundle bundle = getResourceBundle();
if (bundle == null)
{
return ImmutableMap.of();
}
return ResourceBundleMapWrapper.of(bundle);
}
public JXlsExporter setProperty(@NonNull final String name, @NonNull final Object value)
{
Check.assumeNotEmpty(name, "name not empty");
_properties.put(name, value);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JXlsExporter.java
| 2
|
请完成以下Java代码
|
public String getValidValue() {
return validValue;
}
/**
* Sets the value of the validValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValidValue(String value) {
this.validValue = value;
}
/**
* Gets the value of the recordId property.
*
* @return
* possible object is
* {@link BigInteger }
|
*
*/
public BigInteger getRecordId() {
return recordId;
}
/**
* Sets the value of the recordId property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setRecordId(BigInteger value) {
this.recordId = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\ErrorType.java
| 1
|
请完成以下Java代码
|
public @NonNull String getHandledTableName()
{
return I_PP_Order.Table_Name;
}
@Override
public StandardDocumentReportType getStandardDocumentReportType()
{
return StandardDocumentReportType.MANUFACTURING_ORDER;
}
@Override
public @NonNull DocumentReportInfo getDocumentReportInfo(
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse)
{
final PPOrderId manufacturingOrderId = recordRef.getIdAssumingTableName(I_PP_Order.Table_Name, PPOrderId::ofRepoId);
final I_PP_Order manufacturingOrder = ppOrderBL.getById(manufacturingOrderId);
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(manufacturingOrder.getC_BPartner_ID());
final I_C_BPartner bpartner = bpartnerId == null? null: util.getBPartnerById(bpartnerId);
final DocTypeId docTypeId = extractDocTypeId(manufacturingOrder);
final I_C_DocType docType = util.getDocTypeById(docTypeId);
final ClientId clientId = ClientId.ofRepoId(manufacturingOrder.getAD_Client_ID());
final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers(
() -> adPrintFormatToUseId,
() -> bpartnerId == null ? null :
util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null),
() -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()),
() -> util.getDefaultPrintFormats(clientId).getManufacturingOrderPrintFormatId());
if (printFormatId == null)
{
throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@");
}
final Language language = bpartner == null ? null : util.getBPartnerLanguage(bpartner).orElse(null);
final BPPrintFormatQuery bpPrintFormatQuery = bpartnerId == null ? null : BPPrintFormatQuery.builder()
.adTableId(recordRef.getAdTableId())
.bpartnerId(bpartnerId)
.bPartnerLocationId(null)
|
.docTypeId(docTypeId)
.onlyCopiesGreaterZero(true)
.build();
return DocumentReportInfo.builder()
.recordRef(TableRecordReference.of(I_PP_Order.Table_Name, manufacturingOrderId))
.reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId))
.copies(util.getDocumentCopies(docType, bpPrintFormatQuery))
.documentNo(manufacturingOrder.getDocumentNo())
.bpartnerId(bpartnerId)
.docTypeId(docTypeId)
.language(language)
.build();
}
private DocTypeId extractDocTypeId(@NonNull final I_PP_Order manufacturingOrder)
{
return DocTypeId.optionalOfRepoId(manufacturingOrder.getC_DocType_ID())
.orElseThrow(() -> new AdempiereException("No document type set"));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\ManufacturingOrderDocumentReportAdvisor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Flux<User> getUserByAge(@PathVariable Integer from, @PathVariable Integer to) {
return userService.getUserByAge(from, to);
}
@GetMapping(value = "/stream/age/{from}/{to}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByAgeStream(@PathVariable Integer from, @PathVariable Integer to) {
return userService.getUserByAge(from, to);
}
/**
* 根据用户名查找
*/
@GetMapping("/name/{name}")
public Flux<User> getUserByName(@PathVariable String name) {
return userService.getUserByName(name);
}
@GetMapping(value = "/stream/name/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByNameStream(@PathVariable String name) {
return userService.getUserByName(name);
}
/**
* 根据用户描述模糊查找
*/
@GetMapping("/description/{description}")
public Flux<User> getUserByDescription(@PathVariable String description) {
return userService.getUserByDescription(description);
}
@GetMapping(value = "/stream/description/{description}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByDescriptionStream(@PathVariable String description) {
return userService.getUserByDescription(description);
|
}
/**
* 根据多个检索条件查询
*/
@GetMapping("/condition")
public Flux<User> getUserByCondition(int size, int page, User user) {
return userService.getUserByCondition(size, page, user);
}
@GetMapping("/condition/count")
public Mono<Long> getUserByConditionCount(User user) {
return userService.getUserByConditionCount(user);
}
}
|
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\controller\UserController.java
| 2
|
请完成以下Java代码
|
public void apply(String userId, UserAddressRemovedEvent event) {
Address address = new Address(event.getCity(), event.getState(), event.getPostCode());
UserAddress userAddress = readRepository.getUserAddress(userId);
if (userAddress != null) {
Set<Address> addresses = userAddress.getAddressByRegion()
.get(address.getState());
if (addresses != null)
addresses.remove(address);
readRepository.addUserAddress(userId, userAddress);
}
}
public void apply(String userId, UserContactAddedEvent event) {
Contact contact = new Contact(event.getContactType(), event.getContactDetails());
UserContact userContact = Optional.ofNullable(readRepository.getUserContact(userId))
.orElse(new UserContact());
Set<Contact> contacts = Optional.ofNullable(userContact.getContactByType()
.get(contact.getType()))
.orElse(new HashSet<>());
contacts.add(contact);
userContact.getContactByType()
|
.put(contact.getType(), contacts);
readRepository.addUserContact(userId, userContact);
}
public void apply(String userId, UserContactRemovedEvent event) {
Contact contact = new Contact(event.getContactType(), event.getContactDetails());
UserContact userContact = readRepository.getUserContact(userId);
if (userContact != null) {
Set<Contact> contacts = userContact.getContactByType()
.get(contact.getType());
if (contacts != null)
contacts.remove(contact);
readRepository.addUserContact(userId, userContact);
}
}
}
|
repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\escqrs\projectors\UserProjector.java
| 1
|
请完成以下Java代码
|
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private transient Address address; // not an serializable object
private Person person;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
|
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeObject(address.getHouseNumber());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
Integer houseNumber = (Integer) ois.readObject();
Address a = new Address();
a.setHouseNumber(houseNumber);
this.setAddress(a);
}
}
|
repos\tutorials-master\core-java-modules\core-java-serialization\src\main\java\com\baeldung\serialization\Employee.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
|
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
|
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\jdo\xml\Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onParameterChanged(@NonNull final String parameterName)
{
if (PARAM_M_Product_ID.equals(parameterName))
{
final ProductId sparePartId = this.sparePartId;
if (sparePartId != null)
{
final Quantity qty = getSparePartsCalculation().computeQtyOfSparePartsRequiredNet(sparePartId, uomConversionBL).orElse(null);
this.qtyBD = qty != null ? qty.toBigDecimal() : null;
this.uomId = qty != null ? qty.getUomId() : null;
}
}
}
@Override
protected String doIt()
{
final InOutId customerReturnId = getCustomerReturnId();
final Quantity qtyReturned = getQtyReturned();
repairCustomerReturnsService.prepareAddSparePartsToCustomerReturn()
.customerReturnId(customerReturnId)
.productId(sparePartId)
.qtyReturned(qtyReturned)
.build();
return MSG_OK;
}
private Quantity getQtyReturned()
|
{
if (qtyBD == null)
{
throw new FillMandatoryException("Qty");
}
if (uomId == null)
{
throw new FillMandatoryException("C_UOM_ID");
}
final I_C_UOM uom = uomDAO.getById(uomId);
return Quantity.of(qtyBD, uom);
}
private SparePartsReturnCalculation getSparePartsCalculation()
{
SparePartsReturnCalculation sparePartsCalculation = _sparePartsCalculation;
if (sparePartsCalculation == null)
{
sparePartsCalculation = _sparePartsCalculation = repairCustomerReturnsService.getSparePartsCalculation(getCustomerReturnId());
}
return sparePartsCalculation;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\CustomerReturns_AddSpareParts.java
| 2
|
请完成以下Java代码
|
private boolean findACandidate(Class<?> payloadClass, InvocableHandlerMethod handler, Method method,
Annotation[][] parameterAnnotations) {
boolean foundCandidate = false;
for (int i = 0; i < parameterAnnotations.length; i++) {
MethodParameter methodParameter = new MethodParameter(method, i);
if ((methodParameter.getParameterAnnotations().length == 0
|| !methodParameter.hasParameterAnnotation(Header.class))
&& methodParameter.getParameterType().isAssignableFrom(payloadClass)) {
if (foundCandidate) {
throw new AmqpException("Ambiguous payload parameter for " + method.toGenericString());
}
if (this.validator != null) {
this.payloadMethodParameters.put(handler, methodParameter);
}
foundCandidate = true;
}
}
return foundCandidate;
}
/**
* Return a string representation of the method that will be invoked for this payload.
* @param payload the payload.
* @return the method name.
*/
public String getMethodNameFor(Object payload) {
InvocableHandlerMethod handlerForPayload = null;
try {
handlerForPayload = getHandlerForPayload(payload.getClass());
}
catch (Exception e) {
// NOSONAR
}
return handlerForPayload == null ? "no match" : handlerForPayload.getMethod().toGenericString();
}
/**
* Return the method that will be invoked for this payload.
* @param payload the payload.
* @return the method.
* @since 2.0
*/
public Method getMethodFor(Object payload) {
return getHandlerForPayload(payload.getClass()).getMethod();
}
public boolean hasDefaultHandler() {
return this.defaultHandler != null;
}
public @Nullable InvocationResult getInvocationResultFor(Object result, Object inboundPayload) {
InvocableHandlerMethod handler = findHandlerForPayload(inboundPayload.getClass());
if (handler != null) {
return new InvocationResult(result, this.handlerSendTo.get(handler),
handler.getMethod().getGenericReturnType(), handler.getBean(), handler.getMethod());
}
return null;
}
|
private static final class PayloadValidator extends PayloadMethodArgumentResolver {
PayloadValidator(Validator validator) {
super(new MessageConverter() { // Required but never used
@Override
public @Nullable Message<?> toMessage(Object payload, @Nullable MessageHeaders headers) {
return null;
}
@Override
public @Nullable Object fromMessage(Message<?> message, Class<?> targetClass) {
return null;
}
}, validator);
}
@Override
public void validate(Message<?> message, MethodParameter parameter, Object target) { // NOSONAR - public
super.validate(message, parameter, target);
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\DelegatingInvocableHandler.java
| 1
|
请完成以下Java代码
|
public void setMRP_Exclude (final @Nullable java.lang.String MRP_Exclude)
{
set_Value (COLUMNNAME_MRP_Exclude, MRP_Exclude);
}
@Override
public java.lang.String getMRP_Exclude()
{
return get_ValueAsString(COLUMNNAME_MRP_Exclude);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public org.compiere.model.I_S_Resource getPP_Plant()
{
return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant)
{
set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant);
}
@Override
public void setPP_Plant_ID (final int PP_Plant_ID)
{
if (PP_Plant_ID < 1)
set_Value (COLUMNNAME_PP_Plant_ID, null);
else
set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID);
}
@Override
public int getPP_Plant_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Plant_ID);
}
@Override
public void setReplenishmentClass (final @Nullable java.lang.String ReplenishmentClass)
{
set_Value (COLUMNNAME_ReplenishmentClass, ReplenishmentClass);
}
@Override
public java.lang.String getReplenishmentClass()
|
{
return get_ValueAsString(COLUMNNAME_ReplenishmentClass);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JsonSettings getSettings()
{
final Map<String, String> map = sysConfigBL.getValuesForPrefix(SYSCONFIG_SETTINGS_PREFIX, true, Env.getClientAndOrgId());
return JsonSettings.ofMap(map);
}
@PostMapping("/errors")
public void logErrors(@RequestBody @NonNull final JsonError error)
{
error.getErrors().stream()
.map(WorkflowRestController::toInsertRemoteIssueRequest)
.forEach(errorManager::insertRemoteIssue);
}
private static InsertRemoteIssueRequest toInsertRemoteIssueRequest(final JsonErrorItem jsonErrorItem)
{
return InsertRemoteIssueRequest.builder()
.issueCategory(jsonErrorItem.getIssueCategory())
.issueSummary(StringUtils.trimBlankToOptional(jsonErrorItem.getMessage()).orElse("Error"))
.sourceClassName(jsonErrorItem.getSourceClassName())
.sourceMethodName(jsonErrorItem.getSourceMethodName())
.stacktrace(jsonErrorItem.getStackTrace())
.orgId(RestUtils.retrieveOrgIdOrDefault(jsonErrorItem.getOrgCode()))
|
.frontendUrl(jsonErrorItem.getFrontendUrl())
.build();
}
@GetMapping("/trolley")
public JsonGetCurrentTrolleyResponse getCurrentTrolley()
{
return trolleyService.getCurrent(Env.getLoggedUserId())
.map(JsonGetCurrentTrolleyResponse::ofQRCode)
.orElse(JsonGetCurrentTrolleyResponse.EMPTY);
}
@PostMapping("/trolley")
public JsonGetCurrentTrolleyResponse setCurrentTrolley(@NonNull @RequestBody JsonSetCurrentTrolley request)
{
final LocatorQRCode locatorQRCode = trolleyService.setCurrent(Env.getLoggedUserId(), request.getScannedCode());
return JsonGetCurrentTrolleyResponse.ofQRCode(locatorQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\controller\v2\WorkflowRestController.java
| 2
|
请完成以下Java代码
|
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
|
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Buyer.java
| 1
|
请完成以下Java代码
|
protected DmnExpressionImpl transformLiteralExpression(LiteralExpression literalExpression) {
DmnElementTransformHandler<LiteralExpression, DmnExpressionImpl> handler = handlerRegistry.getHandler(LiteralExpression.class);
return handler.handleElement(this, literalExpression);
}
protected DmnVariableImpl transformVariable(Variable variable) {
DmnElementTransformHandler<Variable, DmnVariableImpl> handler = handlerRegistry.getHandler(Variable.class);
return handler.handleElement(this, variable);
}
// listeners ////////////////////////////////////////////////////////////////
protected void notifyTransformListeners(Decision decision, DmnDecision dmnDecision) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecision(decision, dmnDecision);
}
}
protected void notifyTransformListeners(Input input, DmnDecisionTableInputImpl dmnInput) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionTableInput(input, dmnInput);
}
}
protected void notifyTransformListeners(Definitions definitions, DmnDecisionRequirementsGraphImpl dmnDecisionRequirementsGraph) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionRequirementsGraph(definitions, dmnDecisionRequirementsGraph);
}
}
protected void notifyTransformListeners(Output output, DmnDecisionTableOutputImpl dmnOutput) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionTableOutput(output, dmnOutput);
|
}
}
protected void notifyTransformListeners(Rule rule, DmnDecisionTableRuleImpl dmnRule) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionTableRule(rule, dmnRule);
}
}
// context //////////////////////////////////////////////////////////////////
public DmnModelInstance getModelInstance() {
return modelInstance;
}
public Object getParent() {
return parent;
}
public DmnDecision getDecision() {
return decision;
}
public DmnDataTypeTransformerRegistry getDataTypeTransformerRegistry() {
return dataTypeTransformerRegistry;
}
public DmnHitPolicyHandlerRegistry getHitPolicyHandlerRegistry() {
return hitPolicyHandlerRegistry;
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DefaultDmnTransform.java
| 1
|
请完成以下Java代码
|
public void example3_labels() {
// For loops without labels
for(int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (checkSomeCondition()) {
break;
}
}
}
outterLoop: for(int i = 0; i < 10; i++) {
innerLoop: for (int j = 0; j < 10; j++) {
if (checkSomeCondition()) {
break outterLoop;
}
}
}
}
public void example4_ternaryOperator() {
// Original way using if/else
int x;
if(checkSomeCondition()) {
x = 1;
}
else {
x = 2;
}
// Using ternary operator
x = checkSomeCondition() ? 1 : 2;
// Using with other statements
boolean remoteCallResult = callRemoteApi();
LOG.info(String.format(
"The result of the remote API call %s successful",
remoteCallResult ? "was" : "was not"
));
}
public void example5_methodReferences() {
// Original way without lambdas and method references
List<String> names = Arrays.asList("ross", "joey", "chandler");
List<String> upperCaseNames = new ArrayList<>();
for(String name : names) {
upperCaseNames.add(name.toUpperCase());
}
// Using method reference with stream map operation
List<String> petNames = Arrays.asList("ross", "joey", "chandler");
List<String> petUpperCaseNames = petNames
.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Method reference with stream filter
List<Animal> pets = Arrays.asList(new Cat(), new Dog(), new Parrot());
List<Animal> onlyDogs = pets
.stream()
.filter(Dog.class::isInstance)
.collect(Collectors.toList());
|
// Method reference with constructors
Set<Animal> onlyDogsSet = pets
.stream()
.filter(Dog.class::isInstance)
.collect(Collectors.toCollection(TreeSet::new));
}
public void example6_asserttion() {
// Original way without assertions
Connection conn = getConnection();
if(conn == null) {
throw new RuntimeException("Connection is null");
}
// Using assert keyword
assert getConnection() != null : "Connection is null";
}
private boolean checkSomeCondition() {
return new Random().nextBoolean();
}
private boolean callRemoteApi() {
return new Random().nextBoolean();
}
private Connection getConnection() {
return null;
}
private static interface Animal {
}
private static class Dog implements Animal {
}
private static class Cat implements Animal {
}
private static class Parrot implements Animal {
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-operators-2\src\main\java\com\baeldung\colonexamples\ColonExamples.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setValue(String value) {
this.value = value;
}
/**
* Used to identify the type of further information. Currently, the following identification types are used:
* AdditionalInternalDestination ... Additional destination, mostly provided in a LOC+159 segment
* DUNS ... DUNS-number
* FiscalNumber ... fiscal number of party
* GLN ... Global Location Number/ILN
* IssuedBySupplier ... ID given by supplier
* IssuedByCustomer ... ID given by customer
* Location ... physical location
* Odette ... ID assigned by ODETTE
* PlantCode ... plant code
* StorageLocation ... storage within location
* StorageCell ... most fine-grained location id (actual shelf / storage bin)
* TribunalPlaceRegistrationNumber ... Tribunal place registration number (GS1 Code)
* UnloadingPoint ... unloading point
* ZZZ ... mutually defined ID by both parties
*
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getIdentificationType() {
return identificationType;
}
/**
* Sets the value of the identificationType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdentificationType(String value) {
this.identificationType = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\FurtherIdentificationType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DeploymentResourceResource extends BaseDeploymentResource {
@Autowired
protected CmmnRestResponseFactory restResponseFactory;
@Autowired
protected ContentTypeResolver contentTypeResolver;
@Autowired
protected CmmnRepositoryService repositoryService;
@ApiOperation(value = "Get a deployment resource", tags = { "Deployment" }, notes = "Replace ** by ResourceId")
/*
* @ApiImplicitParams({
*
* @ApiImplicitParam(name = "resourceId", dataType = "string", value =
* "The id of the resource to get. Make sure you URL-encode the resourceId in case it contains forward slashes. Eg: use diagrams%2Fmy-case.cmmn.xml instead of diagrams/Fmy-case.cmmn.xml."
* , paramType = "path") })
*/
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates both deployment and resource have been found and the resource has been returned."),
@ApiResponse(code = 404, message = "Indicates the requested deployment was not found or there is no resource with the given id present in the deployment. The status-description contains additional information.")
})
@GetMapping(value = "/cmmn-repository/deployments/{deploymentId}/resources/**", produces = "application/json")
public DeploymentResourceResponse getDeploymentResource(@ApiParam(name = "deploymentId") @PathVariable("deploymentId") String deploymentId, HttpServletRequest request) {
// The ** is needed because the name of the resource can actually contain forward slashes.
// For example org/flowable/model.cmmn. The number of forward slashes is unknown.
// Using ** means that everything should get matched.
// See also https://stackoverflow.com/questions/31421061/how-to-handle-requests-that-includes-forward-slashes/42403361#42403361
// Check if deployment exists
CmmnDeployment deployment = getCmmnDeployment(deploymentId);
String pathInfo = request.getPathInfo();
|
String resourceName = pathInfo.replace("/cmmn-repository/deployments/" + deployment.getId() + "/resources/", "");
List<String> resourceList = repositoryService.getDeploymentResourceNames(deployment.getId());
if (resourceList.contains(resourceName)) {
// Build resource representation
String contentType = contentTypeResolver.resolveContentType(resourceName);
DeploymentResourceResponse response = restResponseFactory.createDeploymentResourceResponse(deploymentId, resourceName, contentType);
return response;
} else {
// Resource not found in deployment
throw new FlowableObjectNotFoundException("Could not find a resource with id '" + resourceName + "' in deployment '" + deploymentId + "'.");
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DeploymentResourceResource.java
| 2
|
请完成以下Java代码
|
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
|
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
}
|
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\api\CommonPage.java
| 1
|
请完成以下Java代码
|
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getProxyEndpoint() {
|
return proxyEndpoint;
}
public void setProxyEndpoint(String proxyEndpoint) {
this.proxyEndpoint = proxyEndpoint;
}
public String getLocalFileBaseDirectory() {
return localFileBaseDirectory;
}
public void setLocalFileBaseDirectory(String localFileBaseDirectory) {
this.localFileBaseDirectory = localFileBaseDirectory;
}
}
|
repos\tutorials-master\aws-modules\s3proxy\src\main\java\com\baeldung\s3proxy\StorageProperties.java
| 1
|
请完成以下Java代码
|
public boolean isLatest() {
return latest;
}
public boolean isOnlyInbound() {
return onlyInbound;
}
public boolean isOnlyOutbound() {
return onlyOutbound;
}
public String getImplementation() {
return implementation;
}
public Date getCreateTime() {
return createTime;
}
public Date getCreateTimeAfter() {
return createTimeAfter;
}
public Date getCreateTimeBefore() {
return createTimeBefore;
}
|
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\ChannelDefinitionQueryImpl.java
| 1
|
请完成以下Java代码
|
public class TasklistApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(JacksonConfigurator.class);
classes.add(JacksonJsonProvider.class);
classes.add(ExceptionHandler.class);
classes.add(RestExceptionHandler.class);
addPluginResourceClasses(classes);
return classes;
}
|
private void addPluginResourceClasses(Set<Class<?>> classes) {
List<TasklistPlugin> plugins = getTasklistPlugins();
for (TasklistPlugin plugin : plugins) {
classes.addAll(plugin.getResourceClasses());
}
}
private List<TasklistPlugin> getTasklistPlugins() {
return Tasklist.getRuntimeDelegate().getAppPluginRegistry().getPlugins();
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\tasklist\impl\web\TasklistApplication.java
| 1
|
请完成以下Java代码
|
default void addListener(int index, Listener<K, V> listener) {
}
/**
* Add a listener.
* @param listener the listener.
*/
default void addListener(Listener<K, V> listener) {
}
/**
* Get the current list of listeners.
* @return the listeners.
*/
default List<Listener<K, V>> getListeners() {
return Collections.emptyList();
}
/**
* Listener for share consumer lifecycle events.
*
* @param <K> the key type.
* @param <V> the value type.
*/
|
interface Listener<K, V> {
/**
* A new consumer was created.
* @param id the consumer id (factory bean name and client.id separated by a period).
* @param consumer the consumer.
*/
default void consumerAdded(String id, ShareConsumer<K, V> consumer) {
}
/**
* An existing consumer was removed.
* @param id the consumer id (factory bean name and client.id separated by a period).
* @param consumer the consumer.
*/
default void consumerRemoved(@Nullable String id, ShareConsumer<K, V> consumer) {
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ShareConsumerFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static String getAuthorName(User user) {
List<String> parts = new ArrayList<>();
if (StringUtils.isNotBlank(user.getFirstName())) {
parts.add(user.getFirstName());
}
if (StringUtils.isNotBlank(user.getLastName())) {
parts.add(user.getLastName());
}
if (parts.isEmpty()) {
parts.add(user.getName());
}
return String.join(" ", parts);
}
private ToVersionControlServiceMsg.Builder newRequestProto(PendingGitRequest<?> request, RepositorySettings settings) {
var tenantId = request.getTenantId();
var requestId = request.getRequestId();
var builder = ToVersionControlServiceMsg.newBuilder()
.setNodeId(serviceInfoProvider.getServiceId())
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
|
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setRequestIdMSB(requestId.getMostSignificantBits())
.setRequestIdLSB(requestId.getLeastSignificantBits());
RepositorySettings vcSettings = settings;
if (vcSettings == null && request.requiresSettings()) {
vcSettings = entitiesVersionControlService.getVersionControlSettings(tenantId);
}
if (vcSettings != null) {
builder.setVcSettings(ProtoUtils.toProto(vcSettings));
} else if (request.requiresSettings()) {
throw new RuntimeException("No entity version control settings provisioned!");
}
return builder;
}
private CommitRequestMsg.Builder buildCommitRequest(CommitGitRequest commit) {
return CommitRequestMsg.newBuilder().setTxId(commit.getTxId().toString());
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\DefaultGitVersionControlQueueService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DemoController {
@Autowired
private OrderProperties orderProperties;
/**
* 测试 @ConfigurationProperties 注解的配置属性类
*/
@GetMapping("/test01")
public OrderProperties test01() {
return orderProperties;
}
@Value(value = "${order.pay-timeout-seconds}")
private Integer payTimeoutSeconds;
|
@Value(value = "${order.create-frequency-seconds}")
private Integer createFrequencySeconds;
/**
* 测试 @Value 注解的属性
*/
@GetMapping("/test02")
public Map<String, Object> test02() {
Map<String, Object> result = new HashMap<>();
result.put("payTimeoutSeconds", payTimeoutSeconds);
result.put("createFrequencySeconds", createFrequencySeconds);
return result;
}
}
|
repos\SpringBoot-Labs-master\labx-09-spring-cloud-apollo\labx-09-sc-apollo-demo\src\main\java\cn\iocoder\springcloud\labx09\apollodemo\controller\DemoController.java
| 2
|
请完成以下Java代码
|
public int getCapacity() {
return capacity;
}
public ThrottleGatewayFilter setCapacity(int capacity) {
this.capacity = capacity;
return this;
}
public int getRefillTokens() {
return refillTokens;
}
public ThrottleGatewayFilter setRefillTokens(int refillTokens) {
this.refillTokens = refillTokens;
return this;
}
public int getRefillPeriod() {
return refillPeriod;
}
public ThrottleGatewayFilter setRefillPeriod(int refillPeriod) {
this.refillPeriod = refillPeriod;
return this;
}
public TimeUnit getRefillUnit() {
return refillUnit;
}
|
public ThrottleGatewayFilter setRefillUnit(TimeUnit refillUnit) {
this.refillUnit = refillUnit;
return this;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
TokenBucket tokenBucket = getTokenBucket();
// TODO: get a token bucket for a key
log.debug("TokenBucket capacity: " + tokenBucket.getCapacity());
boolean consumed = tokenBucket.tryConsume();
if (consumed) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-sample\src\main\java\org\springframework\cloud\gateway\sample\ThrottleGatewayFilter.java
| 1
|
请完成以下Java代码
|
public int getC_BPartner_ID()
{
return bpartnerId;
}
@Override
public IMaterialTrackingQuery setC_BPartner_ID(final int bpartnerId)
{
this.bpartnerId = bpartnerId;
return this;
}
@Override
public int getM_Product_ID()
{
return productId;
}
@Override
public IMaterialTrackingQuery setM_Product_ID(final int productId)
{
this.productId = productId;
return this;
}
@Override
public Boolean getProcessed()
{
return processed;
}
@Override
public IMaterialTrackingQuery setProcessed(final Boolean processed)
{
this.processed = processed;
return this;
}
@Override
public IMaterialTrackingQuery setWithLinkedDocuments(final List<?> linkedModels)
{
if (linkedModels == null || linkedModels.isEmpty())
{
withLinkedDocuments = Collections.emptyList();
}
else
{
withLinkedDocuments = new ArrayList<>(linkedModels);
}
return this;
}
@Override
public List<?> getWithLinkedDocuments()
{
return withLinkedDocuments;
}
@Override
public IMaterialTrackingQuery setOnMoreThanOneFound(final OnMoreThanOneFound onMoreThanOneFound)
{
Check.assumeNotNull(onMoreThanOneFound, "onMoreThanOneFound not null");
this.onMoreThanOneFound = onMoreThanOneFound;
return this;
}
@Override
public OnMoreThanOneFound getOnMoreThanOneFound()
{
return onMoreThanOneFound;
}
|
@Override
public IMaterialTrackingQuery setCompleteFlatrateTerm(final Boolean completeFlatrateTerm)
{
this.completeFlatrateTerm = completeFlatrateTerm;
return this;
}
@Override
public Boolean getCompleteFlatrateTerm()
{
return completeFlatrateTerm;
}
@Override
public IMaterialTrackingQuery setLot(final String lot)
{
this.lot = lot;
return this;
}
@Override
public String getLot()
{
return lot;
}
@Override
public IMaterialTrackingQuery setReturnReadOnlyRecords(boolean returnReadOnlyRecords)
{
this.returnReadOnlyRecords = returnReadOnlyRecords;
return this;
}
@Override
public boolean isReturnReadOnlyRecords()
{
return returnReadOnlyRecords;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingQuery.java
| 1
|
请完成以下Java代码
|
public static String toGlobalQRCodeJsonString(final PickingSlotQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final PickingSlotQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
public static PickingSlotQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static PickingSlotQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
|
if (!GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()))
{
throw new AdempiereException("Invalid QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
}
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\qrcode\PickingSlotQRCodeJsonConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getReason() {
return this.reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getReplacement() {
return this.replacement;
}
public void setReplacement(String replacement) {
this.replacement = replacement;
}
public String getSince() {
return this.since;
}
public void setSince(String since) {
this.since = since;
}
public String getLevel() {
return this.level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
|
}
ItemDeprecation other = (ItemDeprecation) o;
return nullSafeEquals(this.reason, other.reason) && nullSafeEquals(this.replacement, other.replacement)
&& nullSafeEquals(this.level, other.level) && nullSafeEquals(this.since, other.since);
}
@Override
public int hashCode() {
int result = nullSafeHashCode(this.reason);
result = 31 * result + nullSafeHashCode(this.replacement);
result = 31 * result + nullSafeHashCode(this.level);
result = 31 * result + nullSafeHashCode(this.since);
return result;
}
@Override
public String toString() {
return "ItemDeprecation{reason='" + this.reason + '\'' + ", replacement='" + this.replacement + '\''
+ ", level='" + this.level + '\'' + ", since='" + this.since + '\'' + '}';
}
private boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
return o1.equals(o2);
}
private int nullSafeHashCode(Object o) {
return (o != null) ? o.hashCode() : 0;
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\ItemDeprecation.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UserService {
private UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public void createUser(String userId, String firstName, String lastName) {
User user = new User(userId, firstName, lastName);
repository.addUser(userId, user);
}
public void updateUser(String userId, Set<Contact> contacts, Set<Address> addresses) throws Exception {
User user = repository.getUser(userId);
if (user == null)
throw new Exception("User does not exist.");
user.setContacts(contacts);
user.setAddresses(addresses);
repository.addUser(userId, user);
}
|
public Set<Contact> getContactByType(String userId, String contactType) throws Exception {
User user = repository.getUser(userId);
if (user == null)
throw new Exception("User does not exit.");
Set<Contact> contacts = user.getContacts();
return contacts.stream()
.filter(c -> c.getType()
.equals(contactType))
.collect(Collectors.toSet());
}
public Set<Address> getAddressByRegion(String userId, String state) throws Exception {
User user = repository.getUser(userId);
if (user == null)
throw new Exception("User does not exist.");
Set<Address> addresses = user.getAddresses();
return addresses.stream()
.filter(a -> a.getState()
.equals(state))
.collect(Collectors.toSet());
}
}
|
repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\crud\service\UserService.java
| 2
|
请完成以下Java代码
|
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
}
|
public void setBooks(List<Book> books) {
this.books = books;
}
@PreRemove
private void authorRemove() {
deleted = true;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootSoftDeletes\src\main\java\com\bookstore\entity\Author.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<City> findCityById(@PathVariable("id") Long id) {
String key = "city_" + id;
ValueOperations<String, City> operations = redisTemplate.opsForValue();
boolean hasKey = redisTemplate.hasKey(key);
City city = operations.get(key);
if (!hasKey) {
return Mono.create(monoSink -> monoSink.success(null));
}
return Mono.create(monoSink -> monoSink.success(city));
}
@PostMapping()
public Mono<City> saveCity(@RequestBody City city) {
String key = "city_" + city.getId();
|
ValueOperations<String, City> operations = redisTemplate.opsForValue();
operations.set(key, city, 60, TimeUnit.SECONDS);
return Mono.create(monoSink -> monoSink.success(city));
}
@DeleteMapping(value = "/{id}")
public Mono<Long> deleteCity(@PathVariable("id") Long id) {
String key = "city_" + id;
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
}
return Mono.create(monoSink -> monoSink.success(id));
}
}
|
repos\springboot-learning-example-master\springboot-webflux-6-redis\src\main\java\org\spring\springboot\webflux\controller\CityWebFluxController.java
| 2
|
请完成以下Java代码
|
public Account getAccount(@NonNull final I_Fact_Acct factAcct)
{
final AccountDimension accountDimension = IFactAcctBL.extractAccountDimension(factAcct);
@NonNull final AccountId accountId = accountDAO.getOrCreateOutOfTrx(accountDimension);
return Account.ofId(accountId).withAccountConceptualName(FactAcctDAO.extractAccountConceptualName(factAcct));
}
@Override
public Optional<Money> getAcctBalance(@NonNull final List<FactAcctQuery> queries)
{
final List<I_Fact_Acct> factLines = factAcctDAO.list(queries);
if (factLines.isEmpty())
{
return Optional.empty();
}
final AcctSchemaId acctSchemaId = factLines.stream()
.map(factLine -> AcctSchemaId.ofRepoId(factLine.getC_AcctSchema_ID()))
.distinct()
|
.collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Mixing multiple Accounting Schemas when summing amounts is not allowed")));
final CurrencyId acctCurrencyId = Services.get(IAcctSchemaBL.class).getAcctCurrencyId(acctSchemaId);
final BigDecimal acctBalanceBD = factLines.stream()
.map(factLine -> factLine.getAmtAcctDr().subtract(factLine.getAmtAcctCr()))
.reduce(BigDecimal::add)
.orElse(BigDecimal.ZERO);
return Optional.of(Money.of(acctBalanceBD, acctCurrencyId));
}
@Override
public Stream<I_Fact_Acct> stream(@NonNull final FactAcctQuery query)
{
return factAcctDAO.stream(query);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\acct\api\impl\FactAcctBL.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Textbaustein.
@param AD_BoilerPlate_ID Textbaustein */
@Override
public void setAD_BoilerPlate_ID (int AD_BoilerPlate_ID)
{
if (AD_BoilerPlate_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BoilerPlate_ID, Integer.valueOf(AD_BoilerPlate_ID));
}
/** Get Textbaustein.
@return Textbaustein */
@Override
public int getAD_BoilerPlate_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_BoilerPlate_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Process getJasperProcess() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setJasperProcess(org.compiere.model.I_AD_Process JasperProcess)
{
set_ValueFromPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class, JasperProcess);
}
/** Set Jasper Process.
@param JasperProcess_ID
The Jasper Process used by the printengine if any process defined
*/
@Override
public void setJasperProcess_ID (int JasperProcess_ID)
{
if (JasperProcess_ID < 1)
set_Value (COLUMNNAME_JasperProcess_ID, null);
else
set_Value (COLUMNNAME_JasperProcess_ID, Integer.valueOf(JasperProcess_ID));
}
/** Get Jasper Process.
@return The Jasper Process used by the printengine if any process defined
*/
@Override
public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
|
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Betreff.
@param Subject
Mail Betreff
*/
@Override
public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Betreff.
@return Mail Betreff
*/
@Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
/** Set Text.
@param TextSnippet Text */
@Override
public void setTextSnippet (java.lang.String TextSnippet)
{
set_Value (COLUMNNAME_TextSnippet, TextSnippet);
}
/** Get Text.
@return Text */
@Override
public java.lang.String getTextSnippet ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextSnippet);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDiscount(final String discount)
{
this.discount = discount;
}
public Date getDiscountDate()
{
return discountDate;
}
public void setDiscountDate(final Date discountDate)
{
this.discountDate = discountDate;
}
public String getDiscountDays()
{
return discountDays;
}
public void setDiscountDays(final String discountDays)
{
this.discountDays = discountDays;
}
public String getRate()
{
return rate;
}
public void setRate(final String rate)
{
this.rate = rate;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode());
result = prime * result + (discount == null ? 0 : discount.hashCode());
result = prime * result + (discountDate == null ? 0 : discountDate.hashCode());
result = prime * result + (discountDays == null ? 0 : discountDays.hashCode());
result = prime * result + (rate == null ? 0 : rate.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Cctop140V other = (Cctop140V)obj;
if (cInvoiceID == null)
{
if (other.cInvoiceID != null)
{
return false;
}
}
else if (!cInvoiceID.equals(other.cInvoiceID))
{
return false;
}
if (discount == null)
{
if (other.discount != null)
{
return false;
}
}
else if (!discount.equals(other.discount))
{
return false;
}
if (discountDate == null)
{
if (other.discountDate != null)
|
{
return false;
}
}
else if (!discountDate.equals(other.discountDate))
{
return false;
}
if (discountDays == null)
{
if (other.discountDays != null)
{
return false;
}
}
else if (!discountDays.equals(other.discountDays))
{
return false;
}
if (rate == null)
{
if (other.rate != null)
{
return false;
}
}
else if (!rate.equals(other.rate))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "Cctop140V [cInvoiceID=" + cInvoiceID + ", discount=" + discount + ", discountDate=" + discountDate + ", discountDays=" + discountDays + ", rate=" + rate + "]";
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop140V.java
| 2
|
请完成以下Java代码
|
public PIAttributes retrievePIAttributesByIds(@NonNull final Set<Integer> piAttributeIds)
{
if (piAttributeIds.isEmpty())
{
return PIAttributes.EMPTY;
}
List<I_M_HU_PI_Attribute> piAttributesList = loadByIdsOutOfTrx(piAttributeIds, I_M_HU_PI_Attribute.class);
return PIAttributes.of(piAttributesList);
}
@Override
public boolean isTemplateAttribute(final I_M_HU_PI_Attribute huPIAttribute)
{
logger.trace("Checking if {} is a template attribute", huPIAttribute);
//
// If the PI attribute is from template then it's a template attribute
final HuPackingInstructionsVersionId piVersionId = HuPackingInstructionsVersionId.ofRepoId(huPIAttribute.getM_HU_PI_Version_ID());
if (piVersionId.isTemplate())
{
if (!huPIAttribute.isActive())
{
logger.trace("Considering {} NOT a template attribute because even if it is direct template attribute it's INACTIVE", huPIAttribute);
return false;
}
else
{
logger.trace("Considering {} a template attribute because it is direct template attribute", huPIAttribute);
return true;
}
}
|
//
// Get the Template PI attributes and search if this attribute is defined there.
final AttributeId attributeId = AttributeId.ofRepoId(huPIAttribute.getM_Attribute_ID());
final Properties ctx = InterfaceWrapperHelper.getCtx(huPIAttribute);
final PIAttributes templatePIAttributes = retrieveDirectPIAttributes(ctx, HuPackingInstructionsVersionId.TEMPLATE);
if (templatePIAttributes.hasActiveAttribute(attributeId))
{
logger.trace("Considering {} a template attribute because we found M_Attribute_ID={} in template attributes", huPIAttribute, attributeId);
return true;
}
//
// Not a template attribute
logger.trace("Considering {} NOT a template attribute", huPIAttribute);
return false;
}
@Override
public void deleteByVersionId(@NonNull final HuPackingInstructionsVersionId versionId)
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_M_HU_PI_Attribute.class)
.addEqualsFilter(I_M_HU_PI_Attribute.COLUMN_M_HU_PI_Version_ID, versionId)
.create()
.delete();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUPIAttributesDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SwaggerConfig {
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.xiaolyuh.controller";
private static final String VERSION = "1.0.0";
@Value("${swagger.enable:false}")
private boolean swaggerEnable;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// 分组信息
.groupName("默认分组")
.enable(swaggerEnable)
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
// 可以根据url路径设置哪些请求加入文档,这里可以配置不需要显示的文档
.paths(PathSelectors.any())
//paths: 这里是控制哪些路径的api会被显示出来,比如下方的参数就是除了/user以外的其它路径都会生成api文档
// .paths((String a) ->
// !a.equals("/user"))
.build();
}
private ApiInfo apiInfo() {
|
return new ApiInfoBuilder()
//设置文档的标题
.title("用户信息文档")
// 设置文档的描述
.description("文档描述信息或者特殊说明信息")
// 设置文档的版本信息-> 1.0.0 Version information
.version(VERSION)
// 设置文档的License信息->1.3 License information
.termsOfServiceUrl("http://www.baidu.com")
// 设置联系人
.contact(new Contact("汪雨浩", "http://www.baidu.com", "xxx@163.com"))
.build();
}
}
|
repos\spring-boot-student-master\spring-boot-student-swagger\src\main\java\com\xiaolyuh\config\SwaggerConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getRespondByDate()
{
return respondByDate;
}
public void setRespondByDate(String respondByDate)
{
this.respondByDate = respondByDate;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
EvidenceRequest evidenceRequest = (EvidenceRequest)o;
return Objects.equals(this.evidenceId, evidenceRequest.evidenceId) &&
Objects.equals(this.evidenceType, evidenceRequest.evidenceType) &&
Objects.equals(this.lineItems, evidenceRequest.lineItems) &&
Objects.equals(this.requestDate, evidenceRequest.requestDate) &&
Objects.equals(this.respondByDate, evidenceRequest.respondByDate);
}
@Override
public int hashCode()
{
return Objects.hash(evidenceId, evidenceType, lineItems, requestDate, respondByDate);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class EvidenceRequest {\n");
sb.append(" evidenceId: ").append(toIndentedString(evidenceId)).append("\n");
sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" requestDate: ").append(toIndentedString(requestDate)).append("\n");
|
sb.append(" respondByDate: ").append(toIndentedString(respondByDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\EvidenceRequest.java
| 2
|
请完成以下Java代码
|
public EventLogId saveEvent(
@NonNull final Event event,
@NonNull final Topic eventBusTopic)
{
final String eventString = JacksonJsonEventSerializer.instance.toString(event);
final I_AD_EventLog eventLogRecord = newInstanceOutOfTrx(I_AD_EventLog.class);
eventLogRecord.setEvent_UUID(event.getUuid().toString());
eventLogRecord.setEventTime(Timestamp.from(event.getWhen()));
eventLogRecord.setEventData(eventString);
eventLogRecord.setEventTopicName(eventBusTopic.getName());
eventLogRecord.setEventTypeName(eventBusTopic.getType().toString());
eventLogRecord.setEventName(event.getEventName());
final TableRecordReference sourceRecordReference = event.getSourceRecordReference();
if (sourceRecordReference != null)
{
eventLogRecord.setAD_Table_ID(sourceRecordReference.getAD_Table_ID());
eventLogRecord.setRecord_ID(sourceRecordReference.getRecord_ID());
}
|
save(eventLogRecord);
return EventLogId.ofRepoId(eventLogRecord.getAD_EventLog_ID());
}
public void saveEventLogEntries(@NonNull final Collection<EventLogEntry> eventLogEntries)
{
if (eventLogEntries.isEmpty())
{
return;
}
// Save each entry
eventLogsRepository.saveLogs(eventLogEntries);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogService.java
| 1
|
请完成以下Java代码
|
public class RecordDRGType
extends RecordServiceType
{
@XmlAttribute(name = "tariff_type", required = true)
protected String tariffType;
@XmlAttribute(name = "cost_fraction")
@XmlJavaTypeAdapter(Adapter1 .class)
protected BigDecimal costFraction;
/**
* Gets the value of the tariffType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTariffType() {
return tariffType;
}
/**
* Sets the value of the tariffType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTariffType(String value) {
this.tariffType = value;
}
/**
* Gets the value of the costFraction property.
|
*
* @return
* possible object is
* {@link String }
*
*/
public BigDecimal getCostFraction() {
if (costFraction == null) {
return new Adapter1().unmarshal("1.0");
} else {
return costFraction;
}
}
/**
* Sets the value of the costFraction property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCostFraction(BigDecimal value) {
this.costFraction = 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\RecordDRGType.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: spring-boot-admin-sample-eureka
profiles:
active:
- secure
# tag::configuration-eureka[]
eureka: #<1>
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health
metadata-map:
startup: ${random.int} #needed to trigger info and endpoint update after restart
client:
registryFetchIntervalSeconds: 5
serviceUrl:
defaultZone: ${EUREKA_SERVICE
|
_URL:http://localhost:8761}/eureka/
management:
endpoints:
web:
exposure:
include: "*" #<2>
endpoint:
health:
show-details: ALWAYS
# end::configuration-eureka[]
|
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-eureka\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getSubjectId() {
return subjectId;
}
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getRecommendStatus() {
return recommendStatus;
}
public void setRecommendStatus(Integer recommendStatus) {
this.recommendStatus = recommendStatus;
}
public Integer getSort() {
return sort;
}
|
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", subjectId=").append(subjectId);
sb.append(", subjectName=").append(subjectName);
sb.append(", recommendStatus=").append(recommendStatus);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeRecommendSubject.java
| 1
|
请完成以下Java代码
|
private static String toSqlValue(final Object value, final List<Object> sqlParams)
{
if (sqlParams != null)
{
sqlParams.add(value);
return "?";
}
if (value == null)
{
return "NULL";
}
else if (value instanceof String)
{
return DB.TO_STRING((String)value);
}
else if (value instanceof java.util.Date)
{
final java.util.Date date = (java.util.Date)value;
final String dateAsString = TimeUtil.asTimestamp(date).toString(); // date string (JDBC format)
return " TIMESTAMP " + DB.TO_STRING(dateAsString);
}
else
{
return value.toString();
}
}
/**
* In case the given code is instanceof Timestamp, truncate it by the given truncValue.
* In case the truncValue is null, leave it as it is
*
* @param code
* @param truncValue optional truncate type
* @return
*/
private static java.util.Date truncDate(final java.util.Date date, final String truncValue)
{
if (truncValue == null)
{
// do not truncate
return date;
}
if (date == null)
{
return null;
}
return TimeUtil.trunc(date, truncValue);
}
/**
* Get String Representation
*
* @return info
*/
@Override
public String toString()
{
return getSQL(null);
}
public boolean isJoinAnd()
{
return joinAnd;
}
public String getColumnName()
{
return columnName;
}
/* package */void setColumnName(final String columnName)
{
this.columnName = columnName;
}
/**
* Get Info Name
*
* @return Info Name
*/
public String getInfoName()
{
return infoName;
} // getInfoName
public Operator getOperator()
{
return operator;
}
/**
|
* Get Info Operator
*
* @return info Operator
*/
public String getInfoOperator()
{
return operator == null ? null : operator.getCaption();
} // getInfoOperator
/**
* Get Display with optional To
*
* @return info display
*/
public String getInfoDisplayAll()
{
if (infoDisplayTo == null)
{
return infoDisplay;
}
StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
}
public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java
| 1
|
请完成以下Java代码
|
public static boolean isPermutationWithMap(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
Map<Character, Integer> charsMap = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
charsMap.merge(s1.charAt(i), 1, Integer::sum);
}
for (int i = 0; i < s2.length(); i++) {
if (!charsMap.containsKey(s2.charAt(i)) || charsMap.get(s2.charAt(i)) == 0) {
return false;
}
charsMap.merge(s2.charAt(i), -1, Integer::sum);
}
return true;
}
public static boolean isPermutationInclusion(String s1, String s2) {
int ns1 = s1.length(), ns2 = s2.length();
if (ns1 < ns2) {
return false;
|
}
int[] s1Count = new int[26];
int[] s2Count = new int[26];
for (char ch : s2.toCharArray()) {
s2Count[ch - 'a']++;
}
for (int i = 0; i < ns1; ++i) {
s1Count[s1.charAt(i) - 'a']++;
if (i >= ns2) {
s1Count[s1.charAt(i - ns2) - 'a']--;
}
if (Arrays.equals(s2Count, s1Count)) {
return true;
}
}
return false;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-9\src\main\java\com\baeldung\algorithms\permutation\StringPermutation.java
| 1
|
请完成以下Java代码
|
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append(getExecutionEntity().getId());
if (getExecutionEntity().getActivityId() != null) {
strb.append(" : " + getExecutionEntity().getActivityId());
}
if (getExecutionEntity().getParentId() != null) {
strb.append(", parent id " + getExecutionEntity().getParentId());
}
if (getExecutionEntity().isProcessInstanceType()) {
strb.append(" (process instance)");
}
strb.append(System.lineSeparator());
if (children != null) {
for (ExecutionTreeNode childNode : children) {
childNode.internalToString(strb, "", true);
}
}
return strb.toString();
}
protected void internalToString(StringBuilder strb, String prefix, boolean isTail) {
strb.append(
prefix +
(isTail ? "└── " : "├── ") +
getExecutionEntity().getId() +
" : " +
getCurrentFlowElementId() +
", parent id " +
getExecutionEntity().getParentId() +
(getExecutionEntity().isActive() ? " (active)" : " (not active)") +
(getExecutionEntity().isScope() ? " (scope)" : "") +
(getExecutionEntity().isMultiInstanceRoot() ? " (multi instance root)" : "") +
(getExecutionEntity().isEnded() ? " (ended)" : "") +
System.lineSeparator()
|
);
if (children != null) {
for (int i = 0; i < children.size() - 1; i++) {
children.get(i).internalToString(strb, prefix + (isTail ? " " : "│ "), false);
}
if (children.size() > 0) {
children.get(children.size() - 1).internalToString(strb, prefix + (isTail ? " " : "│ "), true);
}
}
}
protected String getCurrentFlowElementId() {
FlowElement flowElement = getExecutionEntity().getCurrentFlowElement();
if (flowElement instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
return sequenceFlow.getSourceRef() + " -> " + sequenceFlow.getTargetRef();
} else if (flowElement != null) {
return flowElement.getId() + " (" + flowElement.getClass().getSimpleName();
} else {
return "";
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTreeNode.java
| 1
|
请完成以下Java代码
|
public final class ESRRegularLineParser extends AbstractESRPaymentStringParser
{
public static final transient ESRRegularLineParser instance = new ESRRegularLineParser();
private ESRRegularLineParser()
{
super();
}
@Override
public PaymentString parse(@NonNull final String paymentText) throws IndexOutOfBoundsException
{
final List<String> collectedErrors = new ArrayList<>();
//
// First 3 digits: transaction type
final String trxType = paymentText.substring(0, 3);
final String postAccountNo = paymentText.substring(3, 12);
final String amountStringWithPosibleSpaces = paymentText.substring(39, 49);
final BigDecimal amount = extractAmountFromString(trxType, amountStringWithPosibleSpaces, collectedErrors);
if (!trxType.endsWith(ESRConstants.ESRTRXTYPE_REVERSE_LAST_DIGIT))
{
Check.assume(trxType.endsWith(ESRConstants.ESRTRXTYPE_CREDIT_MEMO_LAST_DIGIT) || trxType.endsWith(ESRConstants.ESRTRXTYPE_CORRECTION_LAST_DIGIT),
"The file contains a line with unsupported transaction type '" + trxType + "'");
}
final String paymentDateStr = paymentText.substring(59, 65);
final Timestamp paymentDate = extractTimestampFromString(paymentDateStr, ERR_WRONG_PAYMENT_DATE, collectedErrors);
final String accountDateStr = paymentText.substring(65, 71);
final Timestamp accountDate = extractTimestampFromString(accountDateStr, ERR_WRONG_ACCOUNT_DATE, collectedErrors);
|
final String esrReferenceNoComplete = paymentText.substring(12, 39);
final InvoiceReferenceNo invoiceReferenceNo = InvoiceReferenceNos.parse(esrReferenceNoComplete);
final PaymentString paymentString = PaymentString.builder()
.collectedErrors(collectedErrors)
.rawPaymentString(paymentText)
.postAccountNo(postAccountNo)
.innerAccountNo(invoiceReferenceNo.getBankAccount())
.amount(amount)
.referenceNoComplete(esrReferenceNoComplete)
.paymentDate(paymentDate)
.accountDate(accountDate)
.orgValue(invoiceReferenceNo.getOrg())
.build();
final IPaymentStringDataProvider dataProvider = new ESRPaymentStringDataProvider(paymentString);
paymentString.setDataProvider(dataProvider);
return paymentString;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\spi\impl\ESRRegularLineParser.java
| 1
|
请完成以下Java代码
|
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStartDay (final int StartDay)
{
set_Value (COLUMNNAME_StartDay, StartDay);
}
@Override
public int getStartDay()
{
|
return get_ValueAsInt(COLUMNNAME_StartDay);
}
@Override
public void setStartMonth (final int StartMonth)
{
set_Value (COLUMNNAME_StartMonth, StartMonth);
}
@Override
public int getStartMonth()
{
return get_ValueAsInt(COLUMNNAME_StartMonth);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount_Line.java
| 1
|
请完成以下Java代码
|
public List<AccountDTO> safeJpaFindAccountsByCustomerId(String customerId, String orderBy) {
SingularAttribute<Account,?> orderByAttribute = VALID_JPA_COLUMNS_FOR_ORDER_BY.get(orderBy);
if ( orderByAttribute == null) {
throw new IllegalArgumentException("Nice try!");
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Account> cq = cb.createQuery(Account.class);
Root<Account> root = cq.from(Account.class);
cq.select(root)
.where(cb.equal(root.get(Account_.customerId), customerId))
.orderBy(cb.asc(root.get(orderByAttribute)));
TypedQuery<Account> q = em.createQuery(cq);
return q.getResultList()
.stream()
.map(a -> AccountDTO.builder()
.accNumber(a.getAccNumber())
.balance(a.getBalance())
.branchId(a.getAccNumber())
.customerId(a.getCustomerId())
.build())
.collect(Collectors.toList());
}
/**
* Invalid placeholder usage example
*
* @param tableName
|
* @return
*/
public Long wrongCountRecordsByTableName(String tableName) {
try (Connection c = dataSource.getConnection(); PreparedStatement p = c.prepareStatement("select count(*) from ?")) {
p.setString(1, tableName);
ResultSet rs = p.executeQuery();
rs.next();
return rs.getLong(1);
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
/**
* Invalid placeholder usage example - JPA
*
* @param tableName
* @return
*/
public Long wrongJpaCountRecordsByTableName(String tableName) {
String jql = "select count(*) from :tableName";
TypedQuery<Long> q = em.createQuery(jql, Long.class)
.setParameter("tableName", tableName);
return q.getSingleResult();
}
}
|
repos\tutorials-master\security-modules\sql-injection-samples\src\main\java\com\baeldung\examples\security\sql\AccountDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public JXlsExporter setTemplate(final InputStream template)
{
this._template = template;
return this;
}
private IXlsDataSource getDataSource()
{
Check.assumeNotNull(_dataSource, "dataSource not null");
return _dataSource;
}
public JXlsExporter setDataSource(final IXlsDataSource dataSource)
{
this._dataSource = dataSource;
return this;
}
public JXlsExporter setResourceBundle(final ResourceBundle resourceBundle)
{
this._resourceBundle = resourceBundle;
return this;
}
private ResourceBundle getResourceBundle()
{
if (_resourceBundle != null)
{
return _resourceBundle;
}
if (!Check.isEmpty(_templateResourceName, true))
{
String baseName = null;
try
{
final int dotIndex = _templateResourceName.lastIndexOf('.');
baseName = dotIndex <= 0 ? _templateResourceName : _templateResourceName.substring(0, dotIndex);
return ResourceBundle.getBundle(baseName, getLocale(), getLoader());
}
|
catch (final MissingResourceException e)
{
logger.debug("No resource found for {}", baseName);
}
}
return null;
}
public Map<String, String> getResourceBundleAsMap()
{
final ResourceBundle bundle = getResourceBundle();
if (bundle == null)
{
return ImmutableMap.of();
}
return ResourceBundleMapWrapper.of(bundle);
}
public JXlsExporter setProperty(@NonNull final String name, @NonNull final Object value)
{
Check.assumeNotEmpty(name, "name not empty");
_properties.put(name, value);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JXlsExporter.java
| 2
|
请完成以下Java代码
|
public static void main(String[] args) {
SpringApplication.run(EmbedRatpackStreamsApp.class, args);
}
public static class RandomBytesPublisher implements Publisher<ByteBuf> {
private int bufCount;
private int bufSize;
private Random rnd = new Random();
RandomBytesPublisher(int bufCount, int bufSize) {
this.bufCount = bufCount;
this.bufSize = bufSize;
}
@Override
public void subscribe(Subscriber<? super ByteBuf> s) {
s.onSubscribe(new Subscription() {
private boolean cancelled = false;
private boolean recurse;
private long requested = 0;
@Override
public void request(long n) {
if ( bufCount == 0 ) {
s.onComplete();
return;
}
|
requested += n;
if ( recurse ) {
return;
}
recurse = true;
try {
while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) {
byte[] data = new byte[bufSize];
rnd.nextBytes(data);
ByteBuf buf = Unpooled.wrappedBuffer(data);
s.onNext(buf);
}
}
finally {
recurse = false;
}
}
@Override
public void cancel() {
cancelled = true;
}
});
}
}
}
|
repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\spring\EmbedRatpackStreamsApp.java
| 1
|
请完成以下Java代码
|
private void writeStackTraceElement(PrintWriter writer, StackTraceElement element, ThreadInfo info,
List<MonitorInfo> lockedMonitors, boolean firstElement) {
writer.printf("\tat %s%n", element.toString());
LockInfo lockInfo = info.getLockInfo();
if (firstElement && lockInfo != null) {
if (element.getClassName().equals(Object.class.getName()) && element.getMethodName().equals("wait")) {
writer.printf("\t- waiting on %s%n", format(lockInfo));
}
else {
String lockOwner = info.getLockOwnerName();
if (lockOwner != null) {
writer.printf("\t- waiting to lock %s owned by \"%s\" t@%d%n", format(lockInfo), lockOwner,
info.getLockOwnerId());
}
else {
writer.printf("\t- parking to wait for %s%n", format(lockInfo));
}
}
}
writeMonitors(writer, lockedMonitors);
}
private String format(LockInfo lockInfo) {
return String.format("<%x> (a %s)", lockInfo.getIdentityHashCode(), lockInfo.getClassName());
}
private void writeMonitors(PrintWriter writer, List<MonitorInfo> lockedMonitorsAtCurrentDepth) {
for (MonitorInfo lockedMonitor : lockedMonitorsAtCurrentDepth) {
writer.printf("\t- locked %s%n", format(lockedMonitor));
}
|
}
private void writeLockedOwnableSynchronizers(PrintWriter writer, ThreadInfo info) {
writer.println(" Locked ownable synchronizers:");
LockInfo[] lockedSynchronizers = info.getLockedSynchronizers();
if (lockedSynchronizers == null || lockedSynchronizers.length == 0) {
writer.println("\t- None");
}
else {
for (LockInfo lockedSynchronizer : lockedSynchronizers) {
writer.printf("\t- Locked %s%n", format(lockedSynchronizer));
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\PlainTextThreadDumpFormatter.java
| 1
|
请完成以下Java代码
|
public Map<String, CommandCounter> getCommands() {
return commands;
}
public String getCamundaIntegration() {
return camundaIntegration;
}
public void setCamundaIntegration(String camundaIntegration) {
this.camundaIntegration = camundaIntegration;
}
public LicenseKeyDataImpl getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataImpl licenseKey) {
this.licenseKey = licenseKey;
}
public synchronized Set<String> getWebapps() {
return webapps;
}
public synchronized void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
public void markOccurrence(String name) {
markOccurrence(name, 1);
}
public void markOccurrence(String name, long times) {
CommandCounter counter = commands.get(name);
if (counter == null) {
synchronized (commands) {
if (counter == null) {
counter = new CommandCounter(name);
commands.put(name, counter);
|
}
}
}
counter.mark(times);
}
public synchronized void addWebapp(String webapp) {
if (!webapps.contains(webapp)) {
webapps.add(webapp);
}
}
public void clearCommandCounts() {
commands.clear();
}
public void clear() {
commands.clear();
licenseKey = null;
applicationServer = null;
webapps.clear();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsRegistry.java
| 1
|
请完成以下Java代码
|
protected HazelcastConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new HazelcastDockerComposeConnectionDetails(source.getRunningService());
}
/**
* {@link HazelcastConnectionDetails} backed by a {@code hazelcast}
* {@link RunningService}.
*/
static class HazelcastDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements HazelcastConnectionDetails {
private final String host;
private final int port;
private final HazelcastEnvironment environment;
HazelcastDockerComposeConnectionDetails(RunningService service) {
super(service);
|
this.host = service.host();
this.port = service.ports().get(DEFAULT_PORT);
this.environment = new HazelcastEnvironment(service.env());
}
@Override
public ClientConfig getClientConfig() {
ClientConfig config = new ClientConfig();
if (this.environment.getClusterName() != null) {
config.setClusterName(this.environment.getClusterName());
}
config.getNetworkConfig().addAddress(this.host + ":" + this.port);
return config;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\docker\compose\HazelcastDockerComposeConnectionDetailsFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_EDGE;
EdgeId edgeId = edge.getId();
try {
Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId));
logEntityActionService.logEntityAction(tenantId, deviceId, savedDevice, savedDevice.getCustomerId(),
actionType, user, deviceId.toString(), edgeId.toString(), edge.getName());
return savedDevice;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE),
actionType, user, e, deviceId.toString(), edgeId.toString());
throw e;
}
}
@Override
public Device unassignDeviceFromEdge(Device device, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE;
|
TenantId tenantId = device.getTenantId();
DeviceId deviceId = device.getId();
EdgeId edgeId = edge.getId();
try {
Device savedDevice = checkNotNull(deviceService.unassignDeviceFromEdge(tenantId, deviceId, edgeId));
logEntityActionService.logEntityAction(tenantId, deviceId, savedDevice, savedDevice.getCustomerId(),
actionType, user, deviceId.toString(), edgeId.toString(), edge.getName());
return savedDevice;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.DEVICE),
actionType, user, e, deviceId.toString(), edgeId.toString());
throw e;
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\device\DefaultTbDeviceService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
boolean isEraseCredentialsAfterAuthentication() {
return false;
}
}
public static final class ChildAuthenticationManagerFactoryBean implements FactoryBean<AuthenticationManager> {
private final ProviderManager delegate;
private AuthenticationEventPublisher authenticationEventPublisher = new DefaultAuthenticationEventPublisher();
private boolean eraseCredentialsAfterAuthentication = true;
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
public ChildAuthenticationManagerFactoryBean(List<AuthenticationProvider> providers,
AuthenticationManager parent) {
this.delegate = new ProviderManager(providers, parent);
}
@Override
public AuthenticationManager getObject() throws Exception {
this.delegate.setAuthenticationEventPublisher(this.authenticationEventPublisher);
this.delegate.setEraseCredentialsAfterAuthentication(this.eraseCredentialsAfterAuthentication);
if (!this.observationRegistry.isNoop()) {
return new ObservationAuthenticationManager(this.observationRegistry, this.delegate);
}
return this.delegate;
}
@Override
public Class<?> getObjectType() {
return AuthenticationManager.class;
}
public void setEraseCredentialsAfterAuthentication(boolean eraseCredentialsAfterAuthentication) {
this.eraseCredentialsAfterAuthentication = eraseCredentialsAfterAuthentication;
}
public void setAuthenticationEventPublisher(AuthenticationEventPublisher authenticationEventPublisher) {
this.authenticationEventPublisher = authenticationEventPublisher;
}
public void setObservationRegistry(ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
}
|
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
public static final class FilterChainDecoratorFactory
implements FactoryBean<FilterChainProxy.FilterChainDecorator> {
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
@Override
public FilterChainProxy.FilterChainDecorator getObject() throws Exception {
if (this.observationRegistry.isNoop()) {
return new FilterChainProxy.VirtualFilterChainDecorator();
}
return new ObservationFilterChainDecorator(this.observationRegistry);
}
@Override
public Class<?> getObjectType() {
return FilterChainProxy.FilterChainDecorator.class;
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpSecurityBeanDefinitionParser.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.