instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private void print (String amt)
{
try
{
System.out.println(amt + " = " + getAmtInWords(amt));
}
catch (Exception e)
{
e.printStackTrace();
}
} // print
/**
* Test Print
* @param amt amount
*/
private void print (String amt, String currency)
{
try
{
System.out.println(amt + " = " + getAmtInWords(amt));
}
catch (Exception e)
{
e.printStackTrace();
}
} // print
/** | * Test
* @param args ignored
*/
public static void main (String[] args)
{
AmtInWords_TH aiw = new AmtInWords_TH();
// aiw.print (".23"); Error
// aiw.print ("0.23");
// aiw.print ("1.23");
// aiw.print ("11.45");
// aiw.print ("121.45");
aiw.print ("3,026.00");
aiw.print ("65341.78");
// aiw.print ("123451.89");
// aiw.print ("12234571.90");
// aiw.print ("123234571.90");
// aiw.print ("1,987,234,571.90");
// aiw.print ("11123234571.90");
// aiw.print ("123123234571.90");
// aiw.print ("2123123234571.90");
// aiw.print ("23,123,123,234,571.90");
// aiw.print ("100,000,000,000,000.90");
// aiw.print ("0.00");
} // main
} // AmtInWords_TH | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\AmtInWords_TH.java | 1 |
请完成以下Java代码 | public static String reverseTheOrderOfWords(String sentence) {
if (sentence == null) {
return null;
}
StringBuilder output = new StringBuilder();
String[] words = sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
output.append(words[i]);
output.append(" ");
}
return output.toString()
.trim();
}
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
public static String reverseUsingIntStreamRangeMethod(String str) {
if (str == null) {
return null;
}
char[] charArray = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> charArray[str.length() - i - 1])
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
} | public static String reverseUsingStreamOfMethod(String str) {
if (str == null) {
return null;
}
return Stream.of(str)
.map(string -> new StringBuilder(string).reverse())
.collect(Collectors.joining());
}
public static String reverseUsingCharsMethod(String str) {
if (str == null) {
return null;
}
return str.chars()
.mapToObj(c -> (char) c)
.reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2);
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms\src\main\java\com\baeldung\reverse\ReverseStringExamples.java | 1 |
请完成以下Java代码 | public void setTomb(String tomb) {
this.tomb = tomb;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public King getSuccessor() {
return successor;
}
public void setSuccessor(King successor) {
this.successor = successor;
}
public List<FatherAndSonRelation> getSons() {
return sons;
} | public void setSons(List<FatherAndSonRelation> sons) {
this.sons = sons;
}
/**
* 添加友谊的关系
* @param
*/
public void addRelation(FatherAndSonRelation fatherAndSonRelation){
if(this.sons == null){
this.sons = new ArrayList<>();
}
this.sons.add(fatherAndSonRelation);
}
} | repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\King.java | 1 |
请完成以下Java代码 | public void paint(Graphics g)
{
if (capture) {
//capture preview image
image = (BufferedImage)createImage(this.getWidth(),this.getHeight());
super.paint(image.createGraphics());
g.drawImage(image, 0, 0, null);
capture = false;
if (laf != null)
{
//reset to original setting
if (laf instanceof MetalLookAndFeel)
AdempierePLAF.setCurrentMetalTheme((MetalLookAndFeel)laf, theme);
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
}
laf = null;
theme = null;
}
} else { | //draw captured preview image
if (image != null)
g.drawImage(image, 0, 0, null);
}
}
/**
* Refresh look and feel preview, reset to original setting after
* refresh.
* @param currentLaf Current Look and feel
* @param currentTheme Current Theme
*/
void refresh(LookAndFeel currentLaf, MetalTheme currentTheme)
{
this.laf = currentLaf;
this.theme = currentTheme;
capture = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\PLAFEditorPanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getPathSegment() {
return pathSegment;
}
public void setPathSegment(Integer pathSegment) {
this.pathSegment = pathSegment;
}
public String getRequestParamName() {
return requestParamName;
}
public void setRequestParamName(String requestParamName) {
this.requestParamName = requestParamName;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<String> getSupportedVersions() {
return supportedVersions;
}
public void setSupportedVersions(List<String> supportedVersions) {
this.supportedVersions = supportedVersions;
} | @Override
public String toString() {
// @formatter:off
return new ToStringCreator(this)
.append("defaultVersion", defaultVersion)
.append("detectSupportedVersions", detectSupportedVersions)
.append("headerName", headerName)
.append("mediaType", mediaType)
.append("mediaTypeParamName", mediaTypeParamName)
.append("pathSegment", pathSegment)
.append("requestParamName", requestParamName)
.append("required", required)
.append("supportedVersions", supportedVersions)
.toString();
// @formatter:on
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\VersionProperties.java | 2 |
请完成以下Java代码 | public static ViewHeaderPropertiesProviderMap of(@NonNull final List<ViewHeaderPropertiesProvider> providers)
{
return !providers.isEmpty()
? new ViewHeaderPropertiesProviderMap(providers)
: EMPTY;
}
private static final ViewHeaderPropertiesProviderMap EMPTY = new ViewHeaderPropertiesProviderMap();
private final ImmutableMap<String, ViewHeaderPropertiesProvider> providersByTableName;
private final ViewHeaderPropertiesProvider genericProviders;
private ViewHeaderPropertiesProviderMap()
{
this.providersByTableName = ImmutableMap.of();
this.genericProviders = NullViewHeaderPropertiesProvider.instance;
}
private ViewHeaderPropertiesProviderMap(@NonNull final List<ViewHeaderPropertiesProvider> providers)
{
final ArrayList<ViewHeaderPropertiesProvider> genericProviders = new ArrayList<>();
final ArrayListMultimap<String, ViewHeaderPropertiesProvider> providersByTableName = ArrayListMultimap.create();
for (final ViewHeaderPropertiesProvider provider : providers)
{
final String appliesOnlyToTableName = provider.getAppliesOnlyToTableName();
if (Check.isBlank(appliesOnlyToTableName))
{
genericProviders.add(provider);
final Set<String> tableNames = ImmutableSet.copyOf(providersByTableName.keySet());
for (final String tableName : tableNames)
{
providersByTableName.put(tableName, provider);
}
}
else | {
if (!providersByTableName.containsKey(appliesOnlyToTableName))
{
providersByTableName.putAll(appliesOnlyToTableName, genericProviders);
}
providersByTableName.put(appliesOnlyToTableName, provider);
}
}
this.genericProviders = CompositeViewHeaderPropertiesProvider.of(genericProviders);
this.providersByTableName = providersByTableName.keySet()
.stream()
.collect(ImmutableMap.toImmutableMap(
tableName -> tableName,
tableName -> CompositeViewHeaderPropertiesProvider.of(providersByTableName.get(tableName))));
}
public ViewHeaderPropertiesProvider getProvidersByTableName(@Nullable final String tableName)
{
return tableName != null
? providersByTableName.getOrDefault(tableName, genericProviders)
: genericProviders;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewHeaderPropertiesProviderMap.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
/**
* 设置 名字.
*
* @param name 名字.
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取 密码.
*
* @return 密码.
*/
public String getPassword() {
return password;
}
/**
* 设置 密码.
*
* @param password 密码.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* 获取 md5密码盐.
*
* @return md5密码盐.
*/
public String getSalt() {
return salt;
}
/**
* 设置 md5密码盐.
*
* @param salt md5密码盐.
*/
public void setSalt(String salt) {
this.salt = salt;
}
/**
* 获取 联系电话.
*
* @return 联系电话.
*/
public String getPhone() {
return phone;
}
/**
* 设置 联系电话.
*
* @param phone 联系电话.
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* 获取 备注.
*
* @return 备注.
*/
public String getTips() {
return tips;
}
/**
* 设置 备注.
*
* @param tips 备注.
*/
public void setTips(String tips) {
this.tips = tips;
}
/**
* 获取 状态 1:正常 2:禁用.
*
* @return 状态 1:正常 2:禁用.
*/ | public Integer getState() {
return state;
}
/**
* 设置 状态 1:正常 2:禁用.
*
* @param state 状态 1:正常 2:禁用.
*/
public void setState(Integer state) {
this.state = state;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Manager.java | 1 |
请完成以下Java代码 | public class BankStatementImportFileAttachmentListener implements AttachmentListener
{
private static final Logger logger = LogManager.getLogger(BankStatementImportFileAttachmentListener.class);
private final BankStatementImportFileService bankStatementImportFileService = SpringContextHolder.instance.getBean(BankStatementImportFileService.class);
private final AttachmentEntryService attachmentEntryService = SpringContextHolder.instance.getBean(AttachmentEntryService.class);
@Override
@NonNull
public AttachmentListenerConstants.ListenerWorkStatus afterRecordLinked(
@NonNull final AttachmentEntry attachmentEntry,
@NonNull final TableRecordReference tableRecordReference)
{
final BankStatementImportFileId bankStatementImportFileId = tableRecordReference
.getIdAssumingTableName(I_C_BankStatement_Import_File.Table_Name, BankStatementImportFileId::ofRepoId);
bankStatementImportFileService.save(bankStatementImportFileService.getById(bankStatementImportFileId)
.toBuilder()
.filename(attachmentEntry.getFilename())
.build());
return AttachmentListenerConstants.ListenerWorkStatus.SUCCESS;
}
@Override | @NonNull
public AttachmentListenerConstants.ListenerWorkStatus beforeRecordLinked(
@NonNull final AttachmentEntry attachmentEntry,
@NonNull final TableRecordReference tableRecordReference)
{
Check.assume(tableRecordReference.getTableName().equals(I_C_BankStatement_Import_File.Table_Name), "This is only about C_BankStatement_Import_File!");
final boolean attachmentEntryMatch = attachmentEntryService.getByReferencedRecord(tableRecordReference)
.stream()
.map(AttachmentEntry::getId)
.allMatch(attachmentEntryId -> AttachmentEntryId.equals(attachmentEntryId, attachmentEntry.getId()));
if (!attachmentEntryMatch)
{
logger.debug("multiple attachments not allowed for tableRecord reference ={}; -> returning FAILURE", tableRecordReference.getTableName());
return AttachmentListenerConstants.ListenerWorkStatus.FAILURE;
}
return AttachmentListenerConstants.ListenerWorkStatus.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\importfile\listener\BankStatementImportFileAttachmentListener.java | 1 |
请完成以下Java代码 | public int getM_Securpharm_Action_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Action_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result getM_Securpharm_Productdata_Result()
{
return get_ValueAsPO(COLUMNNAME_M_Securpharm_Productdata_Result_ID, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result.class);
}
@Override
public void setM_Securpharm_Productdata_Result(de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result M_Securpharm_Productdata_Result)
{
set_ValueFromPO(COLUMNNAME_M_Securpharm_Productdata_Result_ID, de.metas.vertical.pharma.securpharm.model.I_M_Securpharm_Productdata_Result.class, M_Securpharm_Productdata_Result);
}
/** Set Securpharm Produktdaten Ergebnise.
@param M_Securpharm_Productdata_Result_ID Securpharm Produktdaten Ergebnise */
@Override
public void setM_Securpharm_Productdata_Result_ID (int M_Securpharm_Productdata_Result_ID)
{
if (M_Securpharm_Productdata_Result_ID < 1)
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, null);
else
set_Value (COLUMNNAME_M_Securpharm_Productdata_Result_ID, Integer.valueOf(M_Securpharm_Productdata_Result_ID));
}
/** Get Securpharm Produktdaten Ergebnise. | @return Securpharm Produktdaten Ergebnise */
@Override
public int getM_Securpharm_Productdata_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Productdata_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set TransaktionsID Server.
@param TransactionIDServer TransaktionsID Server */
@Override
public void setTransactionIDServer (java.lang.String TransactionIDServer)
{
set_Value (COLUMNNAME_TransactionIDServer, TransactionIDServer);
}
/** Get TransaktionsID Server.
@return TransaktionsID Server */
@Override
public java.lang.String getTransactionIDServer ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Action_Result.java | 1 |
请完成以下Java代码 | public boolean isDeploymentBinding() {
CallableElementBinding binding = getBinding();
return CallableElementBinding.DEPLOYMENT.equals(binding);
}
public boolean isVersionBinding() {
CallableElementBinding binding = getBinding();
return CallableElementBinding.VERSION.equals(binding);
}
public boolean isVersionTagBinding() {
CallableElementBinding binding = getBinding();
return CallableElementBinding.VERSION_TAG.equals(binding);
}
public Integer getVersion(VariableScope variableScope) {
Object result = versionValueProvider.getValue(variableScope);
if (result != null) {
if (result instanceof String) {
return Integer.valueOf((String) result);
} else if (result instanceof Integer) {
return (Integer) result;
} else {
throw new ProcessEngineException("It is not possible to transform '"+result+"' into an integer.");
}
}
return null;
}
public ParameterValueProvider getVersionValueProvider() {
return versionValueProvider;
}
public void setVersionValueProvider(ParameterValueProvider version) {
this.versionValueProvider = version;
}
public String getVersionTag(VariableScope variableScope) {
Object result = versionTagValueProvider.getValue(variableScope);
if (result != null) {
if (result instanceof String) {
return (String) result;
} else {
throw new ProcessEngineException("It is not possible to transform '"+result+"' into a string.");
}
} | return null;
}
public ParameterValueProvider getVersionTagValueProvider() {
return versionTagValueProvider;
}
public void setVersionTagValueProvider(ParameterValueProvider version) {
this.versionTagValueProvider = version;
}
public void setTenantIdProvider(ParameterValueProvider tenantIdProvider) {
this.tenantIdProvider = tenantIdProvider;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getDefinitionTenantId(VariableScope variableScope, String defaultTenantId) {
if (tenantIdProvider != null) {
return (String) tenantIdProvider.getValue(variableScope);
} else {
return defaultTenantId;
}
}
public ParameterValueProvider getTenantIdProvider() {
return tenantIdProvider;
}
/**
* @return true if any of the references that specify the callable element are non-literal and need to be resolved with
* potential side effects to determine the process or case definition that is to be called.
*/
public boolean hasDynamicReferences() {
return (tenantIdProvider != null && tenantIdProvider.isDynamic())
|| definitionKeyValueProvider.isDynamic()
|| versionValueProvider.isDynamic()
|| versionTagValueProvider.isDynamic();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\BaseCallableElement.java | 1 |
请完成以下Java代码 | public java.lang.String getDocStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocStatus);
}
/**
* PaymentRule AD_Reference_ID=195
* Reference name: _Payment Rule
*/
public static final int PAYMENTRULE_AD_Reference_ID=195;
/** Cash = B */
public static final String PAYMENTRULE_Cash = "B";
/** CreditCard = K */
public static final String PAYMENTRULE_CreditCard = "K";
/** DirectDeposit = T */
public static final String PAYMENTRULE_DirectDeposit = "T";
/** Check = S */
public static final String PAYMENTRULE_Check = "S";
/** OnCredit = P */
public static final String PAYMENTRULE_OnCredit = "P";
/** DirectDebit = D */
public static final String PAYMENTRULE_DirectDebit = "D";
/** Mixed = M */
public static final String PAYMENTRULE_Mixed = "M";
/** Rückerstattung = E */
public static final String PAYMENTRULE_Reimbursement = "E";
/** Verrechnung = F */
public static final String PAYMENTRULE_Settlement = "F";
/** Set Zahlungsweise.
@param PaymentRule
Wie die Rechnung bezahlt wird
*/
@Override
public void setPaymentRule (java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
/** Get Zahlungsweise.
@return Wie die Rechnung bezahlt wird
*/
@Override
public java.lang.String getPaymentRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaymentRule);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
} | /** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/**
* Status AD_Reference_ID=541011
* Reference name: C_Payment_Reservation_Status
*/
public static final int STATUS_AD_Reference_ID=541011;
/** WAITING_PAYER_APPROVAL = W */
public static final String STATUS_WAITING_PAYER_APPROVAL = "W";
/** APPROVED = A */
public static final String STATUS_APPROVED = "A";
/** VOIDED = V */
public static final String STATUS_VOIDED = "V";
/** COMPLETED = C */
public static final String STATUS_COMPLETED = "C";
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation.java | 1 |
请完成以下Java代码 | private Optional<I_C_DocType> getDocType(final I_GL_Journal glJournal)
{
return DocTypeId.optionalOfRepoId(glJournal.getC_DocType_ID())
.map(docTypeBL::getById);
}
@CalloutMethod(columnNames = I_GL_Journal.COLUMNNAME_DateDoc)
public void onDateDoc(final I_GL_Journal glJournal)
{
final Timestamp dateDoc = glJournal.getDateDoc();
if (dateDoc == null)
{
return;
}
glJournal.setDateAcct(dateDoc);
}
@CalloutMethod(columnNames = {
I_GL_Journal.COLUMNNAME_DateAcct,
I_GL_Journal.COLUMNNAME_C_Currency_ID,
I_GL_Journal.COLUMNNAME_C_ConversionType_ID })
public void updateCurrencyRate(final I_GL_Journal glJournal)
{
//
// Extract data from source Journal
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID());
if (currencyId == null)
{
// not set yet
return;
}
final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID());
final Instant dateAcct = glJournal.getDateAcct() != null ? glJournal.getDateAcct().toInstant() : SystemTime.asInstant();
final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID());
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(glJournal.getC_AcctSchema_ID());
final AcctSchema acctSchema = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId);
//
// Calculate currency rate
final BigDecimal currencyRate;
if (acctSchema != null)
{
currencyRate = Services.get(ICurrencyBL.class).getCurrencyRateIfExists(
currencyId,
acctSchema.getCurrencyId(), | dateAcct,
conversionTypeId,
adClientId,
adOrgId)
.map(CurrencyRate::getConversionRate)
.orElse(BigDecimal.ZERO);
}
else
{
currencyRate = BigDecimal.ONE;
}
//
glJournal.setCurrencyRate(currencyRate);
}
// Old/missing callouts
// "GL_Journal";"C_Period_ID";"org.compiere.model.CalloutGLJournal.period"
// "GL_Journal";"DateAcct";"org.compiere.model.CalloutGLJournal.period"
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_Journal.java | 1 |
请完成以下Java代码 | public List<HistoricJobLogDto> queryHistoricJobLogs(HistoricJobLogQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(objectMapper);
HistoricJobLogQuery query = queryDto.toQuery(processEngine);
List<HistoricJobLog> matchingHistoricJobLogs = QueryUtil.list(query, firstResult, maxResults);
List<HistoricJobLogDto> results = new ArrayList<HistoricJobLogDto>();
for (HistoricJobLog historicJobLog : matchingHistoricJobLogs) {
HistoricJobLogDto result = HistoricJobLogDto.fromHistoricJobLog(historicJobLog);
results.add(result);
}
return results;
}
@Override
public CountResultDto getHistoricJobLogsCount(UriInfo uriInfo) {
HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters()); | return queryHistoricJobLogsCount(queryDto);
}
@Override
public CountResultDto queryHistoricJobLogsCount(HistoricJobLogQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricJobLogQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricJobLogRestServiceImpl.java | 1 |
请完成以下Java代码 | public class LwM2MTransportBootstrapConfig implements LwM2MSecureServerConfig {
@Getter
@Value("${transport.lwm2m.bootstrap.id:}")
private Integer id;
@Getter
@Value("${transport.lwm2m.bootstrap.bind_address:}")
private String host;
@Getter
@Value("${transport.lwm2m.bootstrap.bind_port:}")
private Integer port;
@Getter
@Value("${transport.lwm2m.bootstrap.security.bind_address:}")
private String secureHost;
@Getter
@Value("${transport.lwm2m.bootstrap.security.bind_port:}") | private Integer securePort;
@Bean
@ConfigurationProperties(prefix = "transport.lwm2m.bootstrap.security.credentials")
public SslCredentialsConfig lwm2mBootstrapCredentials() {
return new SslCredentialsConfig("LWM2M Bootstrap DTLS Credentials", false);
}
@Autowired
@Qualifier("lwm2mBootstrapCredentials")
private SslCredentialsConfig credentialsConfig;
@Override
public SslCredentials getSslCredentials() {
return this.credentialsConfig.getCredentials();
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\config\LwM2MTransportBootstrapConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RpNotifyRecord getNotifyRecordById(String id) {
return rpNotifyRecordDao.getById(id);
}
/**
* 根据商户编号,商户订单号,通知类型获取通知记录
*
* @param merchantNo
* 商户编号
* @param merchantOrderNo
* 商户订单号
* @param notifyType
* 消息类型
* @return
*/
@Override
public RpNotifyRecord getNotifyByMerchantNoAndMerchantOrderNoAndNotifyType(String merchantNo,
String merchantOrderNo, String notifyType) {
return rpNotifyRecordDao.getNotifyByMerchantNoAndMerchantOrderNoAndNotifyType(merchantNo, merchantOrderNo,
notifyType);
}
@Override
public PageBean<RpNotifyRecord> queryNotifyRecordListPage(PageParam pageParam, Map<String, Object> paramMap) {
return rpNotifyRecordDao.listPage(pageParam, paramMap);
}
/**
* 创建消息通知
*
* @param rpNotifyRecord
*/ | @Override
public long createNotifyRecord(RpNotifyRecord rpNotifyRecord) {
return rpNotifyRecordDao.insert(rpNotifyRecord);
}
/**
* 修改消息通知
*
* @param rpNotifyRecord
*/
@Override
public void updateNotifyRecord(RpNotifyRecord rpNotifyRecord) {
rpNotifyRecordDao.update(rpNotifyRecord);
}
/**
* 创建消息通知记录
*
* @param rpNotifyRecordLog
* @return
*/
@Override
public long createNotifyRecordLog(RpNotifyRecordLog rpNotifyRecordLog) {
return rpNotifyRecordLogDao.insert(rpNotifyRecordLog);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\service\impl\RpNotifyServiceImpl.java | 2 |
请完成以下Java代码 | private void createShippingPackages(@NonNull final I_M_PickingSlot pickingSlot)
{
final List<I_M_HU> huRecords = huPickingSlotDAO.retrieveAllHUs(pickingSlot);
addLog("Found {} M_HUs in M_PickingSlot {}", huRecords.size(), pickingSlot.getPickingSlot());
for (final I_M_HU hu : huRecords)
{
// tasks 09033: take care of the HU that might still be open in the picking terminal
// we need to close it to prevent inconsistencies and to make sure that is has a C_BPartner_ID and C_BPartner_Location_ID.
if (pickingSlot.getM_HU_ID() == hu.getM_HU_ID())
{
logger.debug("Closing M_HU {} that is still assigned to M_PickingSlot {}", hu, pickingSlot);
final IQueueActionResult closeCurrentHUResult = huPickingSlotBL.closeCurrentHU(pickingSlot);
logger.debug("Result of IHUPickingSlotBL.closeCurrentHU(): {}", closeCurrentHUResult);
if (handlingUnitsBL.isDestroyed(hu))
{
addLog("Closing M_HU {} from M_PickingSlot {} destroyed the HU (probably because it was empty; skipping it)", hu, pickingSlot);
continue;
}
}
createShippingPackage(hu);
}
}
private void createShippingPackage(@NonNull final I_M_HU hu)
{
if (huPackageDAO.isHUAssignedToPackage(hu))
{ | addLog("M_HU {} is already assigned to a M_Package; => nothing to do", hu);
return;
}
final I_M_Package mpackage = huPackageBL.createM_Package(
CreatePackageForHURequest.builder()
.hu(hu)
.shipperId(shipperId)
.build()
);
final I_M_ShippingPackage shippingPackage = shipperTransportationBL.createShippingPackage(ShipperTransportationId.ofRepoId(shipperTransportation.getM_ShipperTransportation_ID()), mpackage);
if (shippingPackage == null)
{
addLog("Unable to create a M_ShippingPackage for M_ShipperTransportation {} and the newly created M_Package {}; => nothing to do",
shipperTransportation, mpackage);
return;
}
addLog("Created M_Package_ID={} and M_ShippingPackage_ID={} for @M_HU_ID@: {}", mpackage.getM_Package_ID(), shippingPackage.getM_ShippingPackage_ID(), hu.getValue());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\process\M_ShippingPackage_CreateFromPickingSlots.java | 1 |
请完成以下Java代码 | public I_Fact_Acct getFact_Acct() throws RuntimeException
{
return (I_Fact_Acct)MTable.get(getCtx(), I_Fact_Acct.Table_Name)
.getPO(getFact_Acct_ID(), get_TrxName()); }
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Level no.
@param LevelNo Level no */
public void setLevelNo (int LevelNo)
{
set_ValueNoCheck (COLUMNNAME_LevelNo, Integer.valueOf(LevelNo));
}
/** Get Level no.
@return Level no */
public int getLevelNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LevelNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name. | @param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_ValueNoCheck (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 Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_ReportStatement.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyUsageVariance(@NonNull final PPOrderBOMLineId orderBOMLineId)
{
final BigDecimal qtyUsageVariance = queryBL.createQueryBuilder(I_PP_Cost_Collector.class)
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_BOMLine_ID, orderBOMLineId)
.addInArrayFilter(I_PP_Cost_Collector.COLUMNNAME_DocStatus, X_PP_Cost_Collector.DOCSTATUS_Completed, X_PP_Cost_Collector.DOCSTATUS_Closed)
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_CostCollectorType, CostCollectorType.UsageVariance.getCode())
.addOnlyActiveRecordsFilter()
.create()
.aggregate(I_PP_Cost_Collector.COLUMNNAME_MovementQty, Aggregate.MAX, BigDecimal.class);
return qtyUsageVariance != null ? qtyUsageVariance : BigDecimal.ZERO;
}
@Override
public Duration getTotalSetupTimeReal(@NonNull final PPOrderRoutingActivity activity, @NonNull final CostCollectorType costCollectorType)
{
return computeDuration(activity, costCollectorType, I_PP_Cost_Collector.COLUMNNAME_SetupTimeReal);
}
@Override
public Duration getDurationReal(@NonNull final PPOrderRoutingActivity activity, @NonNull final CostCollectorType costCollectorType)
{
return computeDuration(activity, costCollectorType, I_PP_Cost_Collector.COLUMNNAME_DurationReal);
}
private Duration computeDuration(final PPOrderRoutingActivity activity, final CostCollectorType costCollectorType, final String durationColumnName)
{
BigDecimal duration = queryBL.createQueryBuilder(I_PP_Cost_Collector.class)
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, activity.getOrderId()) | .addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_Node_ID, activity.getId())
.addInArrayFilter(I_PP_Cost_Collector.COLUMNNAME_DocStatus, X_PP_Cost_Collector.DOCSTATUS_Completed, X_PP_Cost_Collector.DOCSTATUS_Closed)
.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_CostCollectorType, costCollectorType.getCode())
.create()
.aggregate(durationColumnName, Aggregate.SUM, BigDecimal.class);
if (duration == null)
{
duration = BigDecimal.ZERO;
}
final int durationInt = duration.setScale(0, RoundingMode.UP).intValueExact();
return Duration.of(durationInt, activity.getDurationUnit().getTemporalUnit());
}
@Override
public void save(@NonNull final I_PP_Cost_Collector cc)
{
saveRecord(cc);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\PPCostCollectorDAO.java | 1 |
请完成以下Java代码 | public CaseDefinitionResource getCaseDefinitionByKey(String caseDefinitionKey) {
CaseDefinition caseDefinition = getProcessEngine()
.getRepositoryService()
.createCaseDefinitionQuery()
.caseDefinitionKey(caseDefinitionKey)
.withoutTenantId()
.latestVersion()
.singleResult();
if (caseDefinition == null) {
String errorMessage = String.format("No matching case definition with key: %s and no tenant-id", caseDefinitionKey);
throw new RestException(Status.NOT_FOUND, errorMessage);
} else {
return getCaseDefinitionById(caseDefinition.getId());
}
}
@Override
public CaseDefinitionResource getCaseDefinitionByKeyAndTenantId(String caseDefinitionKey, String tenantId) {
CaseDefinition caseDefinition = getProcessEngine()
.getRepositoryService()
.createCaseDefinitionQuery()
.caseDefinitionKey(caseDefinitionKey)
.tenantIdIn(tenantId)
.latestVersion()
.singleResult();
if (caseDefinition == null) {
String errorMessage = String.format("No matching case definition with key: %s and tenant-id: %s", caseDefinitionKey, tenantId);
throw new RestException(Status.NOT_FOUND, errorMessage);
} else {
return getCaseDefinitionById(caseDefinition.getId());
}
} | @Override
public CaseDefinitionResource getCaseDefinitionById(String caseDefinitionId) {
return new CaseDefinitionResourceImpl(getProcessEngine(), caseDefinitionId, relativeRootResourcePath, getObjectMapper());
}
@Override
public List<CaseDefinitionDto> getCaseDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
CaseDefinitionQueryDto queryDto = new CaseDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
List<CaseDefinitionDto> definitions = new ArrayList<CaseDefinitionDto>();
ProcessEngine engine = getProcessEngine();
CaseDefinitionQuery query = queryDto.toQuery(engine);
List<CaseDefinition> matchingDefinitions = QueryUtil.list(query, firstResult, maxResults);
for (CaseDefinition definition : matchingDefinitions) {
CaseDefinitionDto def = CaseDefinitionDto.fromCaseDefinition(definition);
definitions.add(def);
}
return definitions;
}
@Override
public CountResultDto getCaseDefinitionsCount(UriInfo uriInfo) {
CaseDefinitionQueryDto queryDto = new CaseDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
ProcessEngine engine = getProcessEngine();
CaseDefinitionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseDefinitionRestServiceImpl.java | 1 |
请完成以下Java代码 | public ImmutableList<DDOrderMoveSchedule> dropTo(@NonNull final DDOrderDropToRequest request)
{
return DDOrderDropToCommand.builder()
.ppOrderSourceHUService(ppOrderSourceHUService)
.ddOrderLowLevelDAO(ddOrderLowLevelDAO)
.ddOrderMoveScheduleRepository(ddOrderMoveScheduleRepository)
.request(request)
.build()
.execute();
}
public void unpick(@NonNull final DDOrderMoveScheduleId scheduleId, @Nullable final HUQRCode unpickToTargetQRCode)
{
DDOrderUnpickCommand.builder()
.ddOrderMoveScheduleRepository(ddOrderMoveScheduleRepository)
.huqrCodesService(huqrCodesService)
.scheduleId(scheduleId)
.unpickToTargetQRCode(unpickToTargetQRCode)
.build()
.execute();
}
public Set<DDOrderId> retrieveDDOrderIdsInTransit(@NonNull final LocatorId inTransitLocatorId)
{
return ddOrderMoveScheduleRepository.retrieveDDOrderIdsInTransit(inTransitLocatorId);
} | public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId)
{
return ddOrderMoveScheduleRepository.queryInTransitSchedules(inTransitLocatorId).anyMatch();
}
public void printMaterialInTransitReport(
@NonNull final LocatorId inTransitLocatorId,
@NonNull String adLanguage)
{
MaterialInTransitReportCommand.builder()
.adLanguage(adLanguage)
.inTransitLocatorId(inTransitLocatorId)
.build()
.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleService.java | 1 |
请完成以下Java代码 | public void setDataFormat (final @Nullable java.lang.String DataFormat)
{
set_Value (COLUMNNAME_DataFormat, DataFormat);
}
@Override
public java.lang.String getDataFormat()
{
return get_ValueAsString(COLUMNNAME_DataFormat);
}
/**
* DataType AD_Reference_ID=541944
* Reference name: C_ScannableCode_Format_Part_DataType
*/
public static final int DATATYPE_AD_Reference_ID=541944;
/** ProductCode = PRODUCT_CODE */
public static final String DATATYPE_ProductCode = "PRODUCT_CODE";
/** WeightInKg = WEIGHT_KG */
public static final String DATATYPE_WeightInKg = "WEIGHT_KG";
/** LotNo = LOT */
public static final String DATATYPE_LotNo = "LOT";
/** BestBeforeDate = BEST_BEFORE_DATE */
public static final String DATATYPE_BestBeforeDate = "BEST_BEFORE_DATE";
/** Ignored = IGNORE */
public static final String DATATYPE_Ignored = "IGNORE";
/** Constant = CONSTANT */
public static final String DATATYPE_Constant = "CONSTANT";
/** ProductionDate = PRODUCTION_DATE */
public static final String DATATYPE_ProductionDate = "PRODUCTION_DATE";
@Override
public void setDataType (final java.lang.String DataType)
{
set_Value (COLUMNNAME_DataType, DataType);
}
@Override
public java.lang.String getDataType()
{
return get_ValueAsString(COLUMNNAME_DataType);
}
@Override
public void setDecimalPointPosition (final int DecimalPointPosition)
{
set_Value (COLUMNNAME_DecimalPointPosition, DecimalPointPosition);
} | @Override
public int getDecimalPointPosition()
{
return get_ValueAsInt(COLUMNNAME_DecimalPointPosition);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setEndNo (final int EndNo)
{
set_Value (COLUMNNAME_EndNo, EndNo);
}
@Override
public int getEndNo()
{
return get_ValueAsInt(COLUMNNAME_EndNo);
}
@Override
public void setStartNo (final int StartNo)
{
set_Value (COLUMNNAME_StartNo, StartNo);
}
@Override
public int getStartNo()
{
return get_ValueAsInt(COLUMNNAME_StartNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ScannableCode_Format_Part.java | 1 |
请完成以下Java代码 | public boolean hasTUs(final Properties ctx, final int bpartnerId, final int productId, final Date date)
{
final IHUPIItemProductDAO piItemProductDAO = Services.get(IHUPIItemProductDAO.class);
final IHUPIItemProductQuery queryVO = piItemProductDAO.createHUPIItemProductQuery();
queryVO.setC_BPartner_ID(bpartnerId);
queryVO.setM_Product_ID(productId);
queryVO.setDate(TimeUtil.asZonedDateTime(date));
queryVO.setAllowAnyProduct(false);
queryVO.setHU_UnitType(X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit);
return piItemProductDAO.matches(ctx, queryVO, ITrx.TRXNAME_None);
}
@Override
public void findM_HU_PI_Item_ProductForForecast(@NonNull final I_M_Forecast forecast, final ProductId productId, final Consumer<I_M_HU_PI_Item_Product> pipConsumer)
{
final IHUDocumentHandlerFactory huDocumentHandlerFactory = Services.get(IHUDocumentHandlerFactory.class);
final IHUPIItemProductDAO hupiItemProductDAO = Services.get(IHUPIItemProductDAO.class);
if (forecast.getC_BPartner_ID() <= 0 || forecast.getDatePromised() == null)
{
return;
}
final IHUDocumentHandler handler = huDocumentHandlerFactory.createHandler(I_M_Forecast.Table_Name);
if (null != handler && productId != null)
{
final I_M_HU_PI_Item_Product overridePip = handler.getM_HU_PI_ItemProductFor(forecast, productId);
// If we have a default price and it has an M_HU_PI_Item_Product, suggest it in quick entry.
if (null != overridePip && overridePip.getM_HU_PI_Item_Product_ID() > 0)
{
if (overridePip.isAllowAnyProduct())
{
pipConsumer.accept(null);
}
else
{
pipConsumer.accept(overridePip);
}
return; | }
}
//
// Try fetching best matching PIP
final I_M_HU_PI_Item_Product pip = hupiItemProductDAO.retrieveMaterialItemProduct(
productId,
BPartnerId.ofRepoIdOrNull(forecast.getC_BPartner_ID()),
TimeUtil.asZonedDateTime(forecast.getDatePromised()),
X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit,
true); // allowInfiniteCapacity = true
if (pip == null)
{
// nothing to do, product is not included in any Transport Units
return;
}
else if (pip.isAllowAnyProduct())
{
return;
}
else
{
pipConsumer.accept(pip);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\HUOrderBL.java | 1 |
请完成以下Java代码 | public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
} | public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public List<String> getFlowNodeIds() {
if(flowNodeIds == null) {
flowNodeIds = new ArrayList<String>();
}
return flowNodeIds;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\Lane.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void addRole(Role role) {
roles.add(role);
}
public List<Role> getRoles() {
return Collections.unmodifiableList(roles);
} | public String getId() {
return id;
}
void setId(String id) {
this.id = id;
}
String encrypt(String password) {
Objects.requireNonNull(password);
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, KEY);
final byte[] encryptedBytes = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
return new String(encryptedBytes, StandardCharsets.UTF_8);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// do nothing
return "";
}
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\dtopattern\domain\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PeriodRepo
{
private final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
private final CCache<Integer, I_C_Period> periodCache = CCache.newLRUCache(I_C_Period.Table_Name + "#by#C_Period_ID", 100, 60);
private final CCache<Integer, YearId> yearIdCache = CCache.newLRUCache(I_C_Year.Table_Name + "#by#C_Year_ID", 100, 60);
@NonNull
public Period getById(@NonNull final PeriodId periodId)
{
final I_C_Period record = getRecord(periodId.getRepoId());
return fromPO(record);
}
private Period fromPO(@NonNull final I_C_Period periodRecord)
{
final OrgId orgId = OrgId.ofRepoId(periodRecord.getAD_Org_ID());
final ZoneId zoneId = orgDAO.getTimeZone(orgId);
final Timestamp startDate = periodRecord.getStartDate();
final Timestamp endDate = periodRecord.getEndDate();
final PeriodId periodId = createPeriodId(periodRecord);
return new Period(periodId,
orgId,
TimeUtil.asZonedDateTime(startDate, zoneId),
TimeUtil.asZonedDateTime(endDate, zoneId));
}
/**
* To be used only by other repos, which need to get a period referenced by some other record!
*/
@NonNull | public PeriodId getPeriodId(final int periodRepoId)
{
final I_C_Period periodRecord = getRecord(periodRepoId);
return createPeriodId(periodRecord);
}
private PeriodId createPeriodId(final I_C_Period record)
{
final YearId yearId = getYearId(record.getC_Year_ID());
return PeriodId.ofRepoId(yearId, record.getC_Period_ID());
}
@NonNull
private I_C_Period getRecord(final int periodRepoId)
{
final I_C_Period periodRecord = periodCache.getOrLoad(periodRepoId, id -> InterfaceWrapperHelper.load(id, I_C_Period.class));
return Check.assumeNotNull(periodRecord, "Missing C_Period record for C_Period_ID={}", periodRepoId);
}
private YearId getYearId(final int yearRepoId)
{
return yearIdCache
.getOrLoad(yearRepoId,
id -> {
final I_C_Year yearRecord = InterfaceWrapperHelper.load(id, I_C_Year.class);
final CalendarId calendarId = CalendarId.ofRepoId(yearRecord.getC_Calendar_ID());
return YearId.ofRepoId(calendarId, yearRecord.getC_Year_ID());
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\PeriodRepo.java | 2 |
请完成以下Java代码 | public Optional<OrderCostDetail> getDetailByOrderLineIdIfExists(final OrderLineId orderLineId)
{
return details.stream()
.filter(detail -> OrderLineId.equals(detail.getOrderLineId(), orderLineId))
.findFirst();
}
public OrderCostDetail getDetailByOrderLineId(final OrderLineId orderLineId)
{
return getDetailByOrderLineIdIfExists(orderLineId)
.orElseThrow(() -> new AdempiereException("No cost detail found for " + orderLineId));
}
public void setCreatedOrderLineId(@Nullable final OrderLineId createdOrderLineId)
{
this.createdOrderLineId = createdOrderLineId;
}
public OrderCost copy(@NonNull final OrderCostCloneMapper mapper)
{
return toBuilder()
.id(null)
.orderId(mapper.getTargetOrderId(orderId)) | .createdOrderLineId(createdOrderLineId != null ? mapper.getTargetOrderLineId(createdOrderLineId) : null)
.details(details.stream()
.map(detail -> detail.copy(mapper))
.collect(ImmutableList.toImmutableList()))
.build();
}
public void updateOrderLineInfoIfApplies(
final OrderCostDetailOrderLinePart orderLineInfo,
@NonNull final Function<CurrencyId, CurrencyPrecision> currencyPrecisionProvider,
@NonNull final QuantityUOMConverter uomConverter)
{
final OrderCostDetail detail = getDetailByOrderLineIdIfExists(orderLineInfo.getOrderLineId()).orElse(null);
if (detail == null)
{
return;
}
detail.setOrderLineInfo(orderLineInfo);
updateCostAmount(currencyPrecisionProvider, uomConverter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCost.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ThingsboardMonitoringApplication {
private final List<BaseMonitoringService<?, ?>> monitoringServices;
private final MonitoringEntityService entityService;
private final NotificationService notificationService;
@Value("${monitoring.monitoring_rate_ms}")
private int monitoringRateMs;
ScheduledExecutorService scheduler = ThingsBoardExecutors.newSingleThreadScheduledExecutor("monitoring");
public static void main(String[] args) {
new SpringApplicationBuilder(ThingsboardMonitoringApplication.class)
.properties(Map.of("spring.config.name", "tb-monitoring"))
.run(args);
}
@EventListener(ApplicationReadyEvent.class)
public void startMonitoring() {
entityService.checkEntities();
monitoringServices.forEach(BaseMonitoringService::init);
for (int i = 0; i < monitoringServices.size(); i++) {
int initialDelay = (monitoringRateMs / monitoringServices.size()) * i;
BaseMonitoringService<?, ?> service = monitoringServices.get(i);
log.info("Scheduling initialDelay {}, fixedDelay {} for monitoring '{}' ", initialDelay, monitoringRateMs, service.getClass().getSimpleName());
scheduler.scheduleWithFixedDelay(service::runChecks, initialDelay, monitoringRateMs, TimeUnit.MILLISECONDS);
}
String publicDashboardUrl = entityService.getDashboardPublicLink();
notificationService.sendNotification(new InfoNotification(":rocket: <"+publicDashboardUrl+"|Monitoring> started"));
} | @EventListener(ContextClosedEvent.class)
public void onShutdown(ContextClosedEvent event) {
log.info("Shutting down monitoring service");
try {
var futures = notificationService.sendNotification(new InfoNotification(":warning: Monitoring is shutting down"));
for (Future<?> future : futures) {
future.get(5, TimeUnit.SECONDS);
}
} catch (Exception e) {
log.warn("Failed to send shutdown notification", e);
}
}
@PreDestroy
public void shutdownScheduler() {
scheduler.shutdown();
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\ThingsboardMonitoringApplication.java | 2 |
请完成以下Java代码 | public class AuthorizationObservationContext<T> extends Observation.Context {
// FIXME: Should we make this non-null?
private @Nullable Authentication authentication;
private final T object;
// FIXME: Should we make this non-null?
private @Nullable AuthorizationResult authorizationResult;
public AuthorizationObservationContext(T object) {
Assert.notNull(object, "object cannot be null");
this.object = object;
}
/**
* Get the observed {@link Authentication} for this authorization
*
* <p>
* Note that if the authorization did not require inspecting the
* {@link Authentication}, this will return {@code null}.
* @return any observed {@link Authentication}, {@code null} otherwise
*/
public @Nullable Authentication getAuthentication() {
return this.authentication;
}
/**
* Set the observed {@link Authentication} for this authorization
* @param authentication the observed {@link Authentication}
*/ | public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
/**
* Get the object for which access was requested
* @return the requested object
*/
public T getObject() {
return this.object;
}
/**
* Get the observed {@link AuthorizationResult}
* @return the observed {@link AuthorizationResult}
* @since 6.4
*/
public @Nullable AuthorizationResult getAuthorizationResult() {
return this.authorizationResult;
}
/**
* Set the observed {@link AuthorizationResult}
* @param authorizationResult the observed {@link AuthorizationResult}
* @since 6.4
*/
public void setAuthorizationResult(@Nullable AuthorizationResult authorizationResult) {
this.authorizationResult = authorizationResult;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\AuthorizationObservationContext.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();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
} | /** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Acct.java | 1 |
请完成以下Java代码 | private I_M_HU_PI_Item_Product getM_HU_PI_Item_ProductToUse(final I_M_HU hu, final ProductId productId)
{
if (tuPIItem == null)
{
return null;
}
final I_M_HU_PI_Item_Product piip = piipDAO.retrievePIMaterialItemProduct(
tuPIItem,
BPartnerId.ofRepoIdOrNull(hu.getC_BPartner_ID()),
productId,
SystemTime.asZonedDateTime());
return piip;
}
private void destroyIfEmptyStorage(@NonNull final IHUContext localHuContextCopy) | {
if (Adempiere.isUnitTestMode())
{
handlingUnitsBL.destroyIfEmptyStorage(localHuContextCopy, huToSplit); // in unit test mode, there won't be a commit
return;
}
// Destroy empty HUs from huToSplit
trxManager.getCurrentTrxListenerManagerOrAutoCommit()
.runAfterCommit(() -> trxManager
.runInNewTrx(() -> handlingUnitsBL
.destroyIfEmptyStorage(localHuContextCopy, huToSplit)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUSplitBuilderCoreEngine.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(long value) {
this.id = value;
}
public String getEmail() {
return email;
}
public void setEmail(String value) {
this.email = value;
}
public String getName() {
return name; | }
public void setName(String value) {
this.name = value;
}
public String getCity() {
return city;
}
public void setCity(String value) {
this.city = value;
}
} // class | repos\spring-boot-samples-master\spring-boot-hibernate-search\src\main\java\netgloo\models\User.java | 1 |
请完成以下Java代码 | public void setA_Asset_Reval_Index_ID (int A_Asset_Reval_Index_ID)
{
if (A_Asset_Reval_Index_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Asset_Reval_Index_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Asset_Reval_Index_ID, Integer.valueOf(A_Asset_Reval_Index_ID));
}
/** Get A_Asset_Reval_Index_ID.
@return A_Asset_Reval_Index_ID */
public int getA_Asset_Reval_Index_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Reval_Index_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Reval_Index_ID()));
}
/** Set A_Effective_Date.
@param A_Effective_Date A_Effective_Date */
public void setA_Effective_Date (Timestamp A_Effective_Date)
{
set_Value (COLUMNNAME_A_Effective_Date, A_Effective_Date);
}
/** Get A_Effective_Date.
@return A_Effective_Date */
public Timestamp getA_Effective_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Effective_Date);
}
/** A_Reval_Code AD_Reference_ID=53262 */
public static final int A_REVAL_CODE_AD_Reference_ID=53262;
/** Revaluation Code #1 = R01 */
public static final String A_REVAL_CODE_RevaluationCode1 = "R01";
/** Revaluation Code #2 = R02 */
public static final String A_REVAL_CODE_RevaluationCode2 = "R02";
/** Revaluation Code #3 = R03 */
public static final String A_REVAL_CODE_RevaluationCode3 = "R03";
/** Set A_Reval_Code.
@param A_Reval_Code A_Reval_Code */
public void setA_Reval_Code (String A_Reval_Code)
{ | set_Value (COLUMNNAME_A_Reval_Code, A_Reval_Code);
}
/** Get A_Reval_Code.
@return A_Reval_Code */
public String getA_Reval_Code ()
{
return (String)get_Value(COLUMNNAME_A_Reval_Code);
}
/** A_Reval_Multiplier AD_Reference_ID=53260 */
public static final int A_REVAL_MULTIPLIER_AD_Reference_ID=53260;
/** Factor = FAC */
public static final String A_REVAL_MULTIPLIER_Factor = "FAC";
/** Index = IND */
public static final String A_REVAL_MULTIPLIER_Index = "IND";
/** Set A_Reval_Multiplier.
@param A_Reval_Multiplier A_Reval_Multiplier */
public void setA_Reval_Multiplier (String A_Reval_Multiplier)
{
set_Value (COLUMNNAME_A_Reval_Multiplier, A_Reval_Multiplier);
}
/** Get A_Reval_Multiplier.
@return A_Reval_Multiplier */
public String getA_Reval_Multiplier ()
{
return (String)get_Value(COLUMNNAME_A_Reval_Multiplier);
}
/** Set A_Reval_Rate.
@param A_Reval_Rate A_Reval_Rate */
public void setA_Reval_Rate (BigDecimal A_Reval_Rate)
{
set_Value (COLUMNNAME_A_Reval_Rate, A_Reval_Rate);
}
/** Get A_Reval_Rate.
@return A_Reval_Rate */
public BigDecimal getA_Reval_Rate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Reval_Rate);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Reval_Index.java | 1 |
请完成以下Java代码 | public class ColumnName
{
private final String columnName;
private ColumnName(@NonNull final String columnName)
{
final String columnNameNorm = StringUtils.trimBlankToNull(columnName);
if (columnNameNorm == null)
{
throw new AdempiereException("Invalid column name: `" + columnName + "`");
}
this.columnName = columnNameNorm;
}
public static ColumnName ofString(@NonNull final String string)
{
return new ColumnName(string); | }
@Override
@Deprecated
public String toString()
{
return getAsString();
}
public String getAsString()
{
return columnName;
}
public boolean endsWith(@NonNull final String suffix)
{
return columnName.endsWith(suffix);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\ColumnName.java | 1 |
请完成以下Java代码 | public class LogEntry {
private LogLevel level;
private String message;
private LocalDateTime timestamp;
public LogLevel getLevel() {
return level;
}
public void setLevel(LogLevel level) {
this.level = level;
}
public String getMessage() { | return message;
}
public void setMessage(String message) {
this.message = message;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
} | repos\tutorials-master\text-processing-libraries-modules\antlr\src\main\java\com\baeldung\antlr\log\model\LogEntry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AppController {
@Autowired
ClassifyImageService classifyImageService;
@PostMapping(value = "/classify")
@CrossOrigin(origins = "*")
public ClassifyImageService.LabelWithProbability classifyImage(@RequestParam MultipartFile file) throws IOException {
checkImageContents(file);
return classifyImageService.classifyImage(file.getBytes());
}
@RequestMapping(value = "/")
public String index() {
return "index";
} | private void checkImageContents(MultipartFile file) {
MagicMatch match;
try {
match = Magic.getMagicMatch(file.getBytes());
} catch (Exception e) {
throw new RuntimeException(e);
}
String mimeType = match.getMimeType();
if (!mimeType.startsWith("image")) {
throw new IllegalArgumentException("Not an image type: " + mimeType);
}
}
} | repos\springboot-demo-master\Tensorflow\src\main\java\com\et\tf\api\AppController.java | 2 |
请完成以下Java代码 | public java.lang.String getOldValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_OldValue);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Redo.
@param Redo Redo */
@Override
public void setRedo (java.lang.String Redo)
{
set_Value (COLUMNNAME_Redo, Redo);
}
/** Get Redo.
@return Redo */
@Override
public java.lang.String getRedo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Redo);
} | /** Set Transaktion.
@param TrxName
Name of the transaction
*/
@Override
public void setTrxName (java.lang.String TrxName)
{
set_ValueNoCheck (COLUMNNAME_TrxName, TrxName);
}
/** Get Transaktion.
@return Name of the transaction
*/
@Override
public java.lang.String getTrxName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrxName);
}
/** Set Undo.
@param Undo Undo */
@Override
public void setUndo (java.lang.String Undo)
{
set_Value (COLUMNNAME_Undo, Undo);
}
/** Get Undo.
@return Undo */
@Override
public java.lang.String getUndo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Undo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog.java | 1 |
请完成以下Java代码 | public static class Message {
private final String summary;
private final String themeColor;
private final String title;
@Builder.Default
private final List<Section> sections = new ArrayList<>();
}
@Data
@Builder | public static class Section {
private final String activityTitle;
private final String activitySubtitle;
@Builder.Default
private final List<Fact> facts = new ArrayList<>();
}
public record Fact(String name, @Nullable String value) {
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MicrosoftTeamsNotifier.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@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 setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName() | {
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID)
{
if (PP_Product_BOMVersions_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID);
}
@Override
public int getPP_Product_BOMVersions_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOMVersions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LoginReq extends AbsReq {
/** 用户名 */
private String username;
/** 密码 */
private String password;
/** 手机号 */
private String phone;
/** 邮箱 */
private String mail;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} | public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
@Override
public String toString() {
return "LoginReq{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\LoginReq.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void onFailure(Throwable t) {
stats.incrementFailed();
if (callback != null)
callback.onFailure(t);
}
}
private class MsgPackCallback implements TbQueueCallback {
private final AtomicInteger msgCount;
private final TransportServiceCallback<Void> callback;
public MsgPackCallback(Integer msgCount, TransportServiceCallback<Void> callback) {
this.msgCount = new AtomicInteger(msgCount);
this.callback = callback;
}
@Override
public void onSuccess(TbQueueMsgMetadata metadata) {
if (msgCount.decrementAndGet() <= 0) {
DefaultTransportService.this.transportCallbackExecutor.submit(() -> callback.onSuccess(null));
}
}
@Override
public void onFailure(Throwable t) {
DefaultTransportService.this.transportCallbackExecutor.submit(() -> callback.onError(t));
}
}
private class ApiStatsProxyCallback<T> implements TransportServiceCallback<T> {
private final TenantId tenantId;
private final CustomerId customerId;
private final int dataPoints;
private final TransportServiceCallback<T> callback;
public ApiStatsProxyCallback(TenantId tenantId, CustomerId customerId, int dataPoints, TransportServiceCallback<T> callback) {
this.tenantId = tenantId;
this.customerId = customerId;
this.dataPoints = dataPoints;
this.callback = callback;
}
@Override
public void onSuccess(T msg) {
try {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_MSG_COUNT, 1);
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_DP_COUNT, dataPoints);
} finally {
callback.onSuccess(msg);
}
}
@Override | public void onError(Throwable e) {
callback.onError(e);
}
}
@Override
public ExecutorService getCallbackExecutor() {
return transportCallbackExecutor;
}
@Override
public boolean hasSession(TransportProtos.SessionInfoProto sessionInfo) {
return sessions.containsKey(toSessionId(sessionInfo));
}
@Override
public void createGaugeStats(String statsName, AtomicInteger number) {
statsFactory.createGauge(StatsType.TRANSPORT + "." + statsName, number);
statsMap.put(statsName, number);
}
@Scheduled(fixedDelayString = "${transport.stats.print-interval-ms:60000}")
public void printStats() {
if (statsEnabled && !statsMap.isEmpty()) {
String values = statsMap.entrySet().stream()
.map(kv -> kv.getKey() + " [" + kv.getValue() + "]").collect(Collectors.joining(", "));
log.info("Transport Stats: {}", values);
}
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportService.java | 2 |
请完成以下Java代码 | public void setRecordByTableRecordId(final String tableName, final int recordId)
{
final TableRecordReference record = TableRecordReference.of(tableName, recordId);
setRecords(Collections.singleton(record));
}
private void setRecords(final Collection<TableRecordReference> records)
{
_records = new HashSet<>(records);
// Reset selection
_selection_AD_Table_ID = null;
_selection_pinstanceId = null;
}
public void addRecords(final Collection<TableRecordReference> records)
{
if (_records == null)
{
_records = new HashSet<>(records);
}
else
{
_records.addAll(records);
}
_selection_AD_Table_ID = null;
_selection_pinstanceId = null;
_filters = null;
}
public void setRecordsBySelection(final Class<?> modelClass, @NonNull final PInstanceId pinstanceId)
{
_selection_AD_Table_ID = InterfaceWrapperHelper.getAdTableId(modelClass);
_selection_pinstanceId = pinstanceId;
_records = null;
_filters = null;
}
public <T> void setRecordsByFilter(final Class<T> modelClass, final IQueryFilter<T> filters)
{
_filters = null;
addRecordsByFilter(modelClass, filters);
} | public <T> void addRecordsByFilter(@NonNull final Class<T> modelClass, @NonNull final IQueryFilter<T> filters)
{
_records = null;
_selection_AD_Table_ID = null;
if (_filters == null)
{
_filters = new ArrayList<>();
}
_filters.add(LockRecordsByFilter.of(modelClass, filters));
}
public List<LockRecordsByFilter> getSelection_Filters()
{
return _filters;
}
public AdTableId getSelection_AD_Table_ID()
{
return _selection_AD_Table_ID;
}
public PInstanceId getSelection_PInstanceId()
{
return _selection_pinstanceId;
}
public Iterator<TableRecordReference> getRecordsIterator()
{
return _records == null ? null : _records.iterator();
}
public void addRecordByModel(final Object model)
{
final TableRecordReference record = TableRecordReference.of(model);
addRecords(Collections.singleton(record));
}
public void addRecordByModels(final Collection<?> models)
{
final Collection<TableRecordReference> records = convertModelsToRecords(models);
addRecords(records);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockRecords.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String findPreviousDecisionDefinitionId(String decisionDefinitionKey, Integer version, String tenantId) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("key", decisionDefinitionKey);
params.put("version", version);
params.put("tenantId", tenantId);
return (String) getDbEntityManager().selectOne("selectPreviousDecisionDefinitionId", params);
}
@SuppressWarnings("unchecked")
public List<DecisionDefinition> findDecisionDefinitionByDeploymentId(String deploymentId) {
return getDbEntityManager().selectList("selectDecisionDefinitionByDeploymentId", deploymentId);
}
protected void createDefaultAuthorizations(DecisionDefinition decisionDefinition) {
if(isAuthorizationEnabled()) {
ResourceAuthorizationProvider provider = getResourceAuthorizationProvider();
AuthorizationEntity[] authorizations = provider.newDecisionDefinition(decisionDefinition);
saveDefaultAuthorizations(authorizations);
}
}
protected void configureDecisionDefinitionQuery(DecisionDefinitionQueryImpl query) {
getAuthorizationManager().configureDecisionDefinitionQuery(query);
getTenantManager().configureQuery(query);
}
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
@Override
public DecisionDefinitionEntity findLatestDefinitionById(String id) {
return findDecisionDefinitionById(id);
}
@Override
public DecisionDefinitionEntity findLatestDefinitionByKey(String key) {
return findLatestDecisionDefinitionByKey(key); | }
@Override
public DecisionDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(DecisionDefinitionEntity.class, definitionId);
}
@Override
public DecisionDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return findLatestDecisionDefinitionByKeyAndTenantId(definitionKey, tenantId);
}
@Override
public DecisionDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return findDecisionDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId);
}
@Override
public DecisionDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) {
return findDecisionDefinitionByKeyVersionTagAndTenantId(definitionKey, definitionVersionTag, tenantId);
}
@Override
public DecisionDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return findDecisionDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionManager.java | 2 |
请完成以下Java代码 | public Builder withZoomButton(final boolean withZoomButton)
{
this.withZoomButton = withZoomButton;
return this;
}
/**
* Advice builder to create the buttons with text on them.
*/
public Builder withText()
{
return withText(true);
}
/**
* Advice builder to create the buttons without any text on them.
*
* NOTE: this is the default option anyway. You can call it just to explicitly state the obvious.
*/
public Builder withoutText()
{
return withText(false);
}
/**
* Advice builder to create the buttons with or without text on them.
* | * @param withText true if buttons shall have text on them
*/
public Builder withText(final boolean withText)
{
this.withText = withText;
return this;
}
public Builder withSmallButtons(final boolean withSmallButtons)
{
smallButtons = withSmallButtons;
return this;
}
}
} // ConfirmPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ConfirmPanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RpOrderResultQueryVo extends BaseEntity {
private static final long serialVersionUID = -6104194914044220447L;
private Date createTime;
/** 通知规则 */
private String notifyRule;
/** 最后一次通知时间 **/
private Date lastNotifyTime;
/** 通知次数 **/
private Integer notifyTimes;
/** 限制通知次数 **/
private Integer limitNotifyTimes;
/** 银行订单号 **/
private String bankOrderNo;
public RpOrderResultQueryVo() {
super();
}
public RpOrderResultQueryVo(Date createTime, String notifyRule, Date lastNotifyTime, Integer notifyTimes, Integer limitNotifyTimes,
String bankOrderNo, NotifyStatusEnum status) {
super();
this.createTime = createTime;
this.notifyRule = notifyRule;
this.lastNotifyTime = lastNotifyTime;
this.notifyTimes = notifyTimes;
this.limitNotifyTimes = limitNotifyTimes;
this.bankOrderNo = bankOrderNo;
super.setStatus(status.name());
}
/** 通知规则 */
public String getNotifyRule() {
return notifyRule;
}
/** 通知规则 */
public void setNotifyRule(String notifyRule) {
this.notifyRule = notifyRule;
}
/**
* 获取通知规则的Map<String, Integer>.
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<Integer, Integer> getNotifyRuleMap(){
return (Map) JSONObject.parseObject(getNotifyRule());
}
/** 最后一次通知时间 **/
public Date getLastNotifyTime() {
return lastNotifyTime; | }
/** 最后一次通知时间 **/
public void setLastNotifyTime(Date lastNotifyTime) {
this.lastNotifyTime = lastNotifyTime;
}
/** 通知次数 **/
public Integer getNotifyTimes() {
return notifyTimes;
}
/** 通知次数 **/
public void setNotifyTimes(Integer notifyTimes) {
this.notifyTimes = notifyTimes;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/** 限制通知次数 **/
public Integer getLimitNotifyTimes() {
return limitNotifyTimes;
}
/** 限制通知次数 **/
public void setLimitNotifyTimes(Integer limitNotifyTimes) {
this.limitNotifyTimes = limitNotifyTimes;
}
public String getBankOrderNo() {
return bankOrderNo;
}
public void setBankOrderNo(String bankOrderNo) {
this.bankOrderNo = bankOrderNo;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpOrderResultQueryVo.java | 2 |
请完成以下Java代码 | private void scanMetasfreshHome()
{
final File home = new File(Adempiere.getMetasfreshHome() + File.separator + "migration");
if (!home.exists() && !home.isDirectory())
{
logger.warn("No migration directory found (" + home + ")");
return;
}
logger.info("Processing migration files in directory: " + home.getAbsolutePath());
final File[] migrationFiles = home.listFiles(new FilenameFilter()
{
@Override
public boolean accept(final File dir, final String name)
{
return name.endsWith(".xml");
}
});
for (final File migrationFile : migrationFiles)
{
final XMLLoader loader = new XMLLoader(migrationFile.getAbsolutePath());
load(loader);
}
}
private void load(final XMLLoader loader)
{
loader.load(ITrx.TRXNAME_None);
for (Object o : loader.getObjects())
{
if (o instanceof I_AD_Migration)
{
final I_AD_Migration migration = (I_AD_Migration)o;
execute(migration);
}
else | {
logger.warn("Unhandled type " + o + " [SKIP]");
}
}
}
private void execute(I_AD_Migration migration)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(migration);
final int migrationId = migration.getAD_Migration_ID();
final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class);
final IMigrationExecutorContext migrationCtx = executorProvider.createInitialContext(ctx);
migrationCtx.setFailOnFirstError(true);
final IMigrationExecutor executor = executorProvider.newMigrationExecutor(migrationCtx, migrationId);
executor.setCommitLevel(IMigrationExecutor.CommitLevel.Batch);
executor.execute(IMigrationExecutor.Action.Apply);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\MigrationLoader.java | 1 |
请完成以下Java代码 | public java.lang.String getConfigurationLevel()
{
return get_ValueAsString(COLUMNNAME_ConfigurationLevel);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setIsSubcontracting (final boolean IsSubcontracting)
{
set_Value (COLUMNNAME_IsSubcontracting, IsSubcontracting);
}
@Override
public boolean isSubcontracting()
{
return get_ValueAsBoolean(COLUMNNAME_IsSubcontracting);
}
@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_WF_Node_Product_ID (final int PP_WF_Node_Product_ID)
{
if (PP_WF_Node_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Product_ID, PP_WF_Node_Product_ID);
}
@Override
public int getPP_WF_Node_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_WF_Node_Product_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSpecification (final @Nullable java.lang.String Specification)
{
set_Value (COLUMNNAME_Specification, Specification);
}
@Override
public java.lang.String getSpecification()
{
return get_ValueAsString(COLUMNNAME_Specification);
}
@Override
public void setYield (final @Nullable BigDecimal Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_WF_Node_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class PropertiesOtlpTracingConnectionDetails implements OtlpTracingConnectionDetails {
private final OtlpTracingProperties properties;
PropertiesOtlpTracingConnectionDetails(OtlpTracingProperties properties) {
this.properties = properties;
}
@Override
public String getUrl(Transport transport) {
Assert.state(transport == this.properties.getTransport(),
"Requested transport %s doesn't match configured transport %s".formatted(transport,
this.properties.getTransport()));
String endpoint = this.properties.getEndpoint();
Assert.state(endpoint != null, "'endpoint' must not be null");
return endpoint;
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean({ OtlpGrpcSpanExporter.class, OtlpHttpSpanExporter.class })
@ConditionalOnBean(OtlpTracingConnectionDetails.class)
@ConditionalOnEnabledTracingExport("otlp")
static class Exporters {
@Bean
@ConditionalOnProperty(name = "management.opentelemetry.tracing.export.otlp.transport", havingValue = "http",
matchIfMissing = true)
OtlpHttpSpanExporter otlpHttpSpanExporter(OtlpTracingProperties properties,
OtlpTracingConnectionDetails connectionDetails, ObjectProvider<MeterProvider> meterProvider,
ObjectProvider<OtlpHttpSpanExporterBuilderCustomizer> customizers) {
OtlpHttpSpanExporterBuilder builder = OtlpHttpSpanExporter.builder()
.setEndpoint(connectionDetails.getUrl(Transport.HTTP))
.setTimeout(properties.getTimeout())
.setConnectTimeout(properties.getConnectTimeout())
.setCompression(properties.getCompression().name().toLowerCase(Locale.ROOT));
properties.getHeaders().forEach(builder::addHeader);
meterProvider.ifAvailable(builder::setMeterProvider);
customizers.orderedStream().forEach((customizer) -> customizer.customize(builder)); | return builder.build();
}
@Bean
@ConditionalOnProperty(name = "management.opentelemetry.tracing.export.otlp.transport", havingValue = "grpc")
OtlpGrpcSpanExporter otlpGrpcSpanExporter(OtlpTracingProperties properties,
OtlpTracingConnectionDetails connectionDetails, ObjectProvider<MeterProvider> meterProvider,
ObjectProvider<OtlpGrpcSpanExporterBuilderCustomizer> customizers) {
OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder()
.setEndpoint(connectionDetails.getUrl(Transport.GRPC))
.setTimeout(properties.getTimeout())
.setConnectTimeout(properties.getConnectTimeout())
.setCompression(properties.getCompression().name().toLowerCase(Locale.ROOT));
properties.getHeaders().forEach(builder::addHeader);
meterProvider.ifAvailable(builder::setMeterProvider);
customizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
return builder.build();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\otlp\OtlpTracingConfigurations.java | 2 |
请完成以下Java代码 | public class TypeDeclaration implements Annotatable {
private final AnnotationContainer annotations = new AnnotationContainer();
private final String name;
private String extendedClassName;
private List<String> implementsClassNames = Collections.emptyList();
/**
* Creates a new instance.
* @param name the type name
*/
public TypeDeclaration(String name) {
this.name = name;
}
/**
* Extend the class with the given name.
* @param name the name of the class to extend
*/
public void extend(String name) {
this.extendedClassName = name;
}
/**
* Implement the given interfaces.
* @param names the names of the interfaces to implement
*/
public void implement(Collection<String> names) {
this.implementsClassNames = List.copyOf(names);
} | /**
* Implement the given interfaces.
* @param names the names of the interfaces to implement
*/
public void implement(String... names) {
this.implementsClassNames = List.of(names);
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
public String getName() {
return this.name;
}
public String getExtends() {
return this.extendedClassName;
}
public List<String> getImplements() {
return this.implementsClassNames;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\TypeDeclaration.java | 1 |
请完成以下Spring Boot application配置 | server.port=8082
spring.security.oauth2.client.registration.baeldung.client-id=SampleClientId
spring.security.oauth2.client.registration.baeldung.client-secret=secret
spring.security.oauth2.client.registration.baeldung.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.baeldung.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}
spring.security.oauth2.client.provider.baeldung.token-uri=http://localhost:8081/auth/oauth/token
s | pring.security.oauth2.client.provider.baeldung.authorization-uri=http://localhost:8081/auth/oauth/authorize
spring.security.oauth2.client.provider.baeldung.user-info-uri=http://localhost:8081/auth/user/me | repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\resources\application-oauth2-extractors-baeldung.properties | 2 |
请完成以下Java代码 | public class DySmsLimit {
// 1分钟内最大发短信数量(单一IP)
private static final int MAX_MESSAGE_PER_MINUTE = 5;
// 1分钟
private static final int MILLIS_PER_MINUTE = 60000;
// 一分钟内报警线最大短信数量,超了进黑名单(单一IP)
private static final int MAX_TOTAL_MESSAGE_PER_MINUTE = 20;
private static ConcurrentHashMap<String, Long> ipLastRequestTime = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, Integer> ipRequestCount = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, Boolean> ipBlacklist = new ConcurrentHashMap<>();
/**
* @param ip 请求发短信的IP地址
* @return
*/
public static boolean canSendSms(String ip) {
long currentTime = System.currentTimeMillis();
long lastRequestTime = ipLastRequestTime.getOrDefault(ip, 0L);
int requestCount = ipRequestCount.getOrDefault(ip, 0);
log.info("IP:{}, Msg requestCount:{} ", ip, requestCount);
if (ipBlacklist.getOrDefault(ip, false)) {
// 如果IP在黑名单中,则禁止发送短信
log.error("IP:{}, 进入黑名单,禁止发送请求短信!", ip);
return false;
}
if (currentTime - lastRequestTime >= MILLIS_PER_MINUTE) {
// 如果距离上次请求已经超过一分钟,则重置计数
ipRequestCount.put(ip, 1);
ipLastRequestTime.put(ip, currentTime);
return true;
} else {
// 如果距离上次请求不到一分钟
ipRequestCount.put(ip, requestCount + 1);
if (requestCount < MAX_MESSAGE_PER_MINUTE) {
// 如果请求次数小于5次,允许发送短信
return true;
} else if (requestCount >= MAX_TOTAL_MESSAGE_PER_MINUTE) {
// 如果请求次数超过报警线短信数量,将IP加入黑名单
ipBlacklist.put(ip, true);
return false;
} else {
log.error("IP:{}, 1分钟内请求短信超过5次,请稍后重试!", ip);
return false;
}
}
} | /**
* 图片二维码验证成功之后清空数量
*
* @param ip IP地址
*/
public static void clearSendSmsCount(String ip) {
long currentTime = System.currentTimeMillis();
ipRequestCount.put(ip, 0);
ipLastRequestTime.put(ip, currentTime);
}
// public static void main(String[] args) {
// String ip = "192.168.1.1";
// for (int i = 1; i < 50; i++) {
// if (canSendSms(ip)) {
// System.out.println("Send SMS successfully");
// } else {
// //System.out.println("Exceed SMS limit for IP " + ip);
// }
// }
//
// System.out.println(ipLastRequestTime);
// System.out.println(ipRequestCount);
// System.out.println(ipBlacklist);
// }
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DySmsLimit.java | 1 |
请完成以下Java代码 | public ScriptInfo getScriptInfo() {
return scriptInfo;
}
/**
* Sets the script info
*
* @see #getScriptInfo()
*/
@Override
public void setScriptInfo(ScriptInfo scriptInfo) {
this.scriptInfo = scriptInfo;
}
@Override
public FlowableListener clone() {
FlowableListener clone = new FlowableListener();
clone.setValues(this);
return clone;
}
public void setValues(FlowableListener otherListener) { | super.setValues(otherListener);
setEvent(otherListener.getEvent());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
if (otherListener.getScriptInfo() != null) {
setScriptInfo(otherListener.getScriptInfo().clone());
}
fieldExtensions = new ArrayList<>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
setOnTransaction(otherListener.getOnTransaction());
setCustomPropertiesResolverImplementationType(otherListener.getCustomPropertiesResolverImplementationType());
setCustomPropertiesResolverImplementation(otherListener.getCustomPropertiesResolverImplementation());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowableListener.java | 1 |
请完成以下Java代码 | public final class FieldUtils {
private FieldUtils() {
}
/**
* Attempts to locate the specified field on the class.
* @param clazz the class definition containing the field
* @param fieldName the name of the field to locate
* @return the Field (never null)
* @throws IllegalStateException if field could not be found
*/
public static Field getField(Class<?> clazz, String fieldName) throws IllegalStateException {
Assert.notNull(clazz, "Class required");
Assert.hasText(fieldName, "Field name required");
try {
return clazz.getDeclaredField(fieldName);
}
catch (NoSuchFieldException ex) {
// Try superclass
if (clazz.getSuperclass() != null) {
return getField(clazz.getSuperclass(), fieldName);
}
throw new IllegalStateException("Could not locate field '" + fieldName + "' on class " + clazz);
}
}
/**
* Returns the value of a (nested) field on a bean. Intended for testing.
* @param bean the object
* @param fieldName the field name, with "." separating nested properties
* @return the value of the nested field
*/
public static Object getFieldValue(Object bean, String fieldName) throws IllegalAccessException {
Assert.notNull(bean, "Bean cannot be null");
Assert.hasText(fieldName, "Field name required");
String[] nestedFields = StringUtils.tokenizeToStringArray(fieldName, ".");
Class<?> componentClass = bean.getClass();
Object value = bean;
for (String nestedField : nestedFields) {
Field field = getField(componentClass, nestedField);
field.setAccessible(true);
value = field.get(value);
if (value != null) {
componentClass = value.getClass();
}
}
return value;
} | public static @Nullable Object getProtectedFieldValue(String protectedField, Object object) {
Field field = FieldUtils.getField(object.getClass(), protectedField);
try {
field.setAccessible(true);
return field.get(object);
}
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
return null; // unreachable - previous line throws exception
}
}
public static void setProtectedFieldValue(String protectedField, Object object, Object newValue) {
Field field = FieldUtils.getField(object.getClass(), protectedField);
try {
field.setAccessible(true);
field.set(object, newValue);
}
catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\util\FieldUtils.java | 1 |
请完成以下Java代码 | public int getParentMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParentMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Position.
@param Position Position */
public void setPosition (String Position)
{
set_Value (COLUMNNAME_Position, Position);
}
/** Get Position.
@return Position */
public String getPosition ()
{
return (String)get_Value(COLUMNNAME_Position);
}
/** Set Sequence.
@param Sequence Sequence */
public void setSequence (BigDecimal Sequence)
{
set_Value (COLUMNNAME_Sequence, Sequence);
}
/** Get Sequence.
@return Sequence */
public BigDecimal getSequence ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence);
if (bd == null)
return Env.ZERO;
return bd;
} | /** Set Web Menu.
@param U_WebMenu_ID Web Menu */
public void setU_WebMenu_ID (int U_WebMenu_ID)
{
if (U_WebMenu_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID));
}
/** Get Web Menu.
@return Web Menu */
public int getU_WebMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_WebMenu.java | 1 |
请完成以下Java代码 | public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession(true);
// get authentication from session
Authentications authentications = AuthenticationUtil.getAuthsFromSession(session);
if (cacheTimeToLive != null) {
if (cacheTimeToLive > 0) {
ServletContext servletContext = request.getServletContext();
ServletContextUtil.setCacheTTLForLogin(cacheTimeToLive, servletContext);
}
AuthenticationUtil.updateCache(authentications, session, cacheTimeToLive);
}
Authentications.setCurrent(authentications);
try {
SecurityActions.runWithAuthentications((SecurityAction<Void>) () -> {
chain.doFilter(request, response);
return null;
}, authentications); | } finally {
Authentications.clearCurrent();
AuthenticationUtil.updateSession(req.getSession(false), authentications);
}
}
public void destroy() {
}
public Long getCacheTimeToLive() {
return cacheTimeToLive;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\AuthenticationFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultTbMobileAppService extends AbstractTbEntityService implements TbMobileAppService {
private final MobileAppService mobileAppService;
@Override
public MobileApp save(MobileApp mobileApp, User user) throws Exception {
ActionType actionType = mobileApp.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = mobileApp.getTenantId();
try {
MobileApp savedMobileApp = checkNotNull(mobileAppService.saveMobileApp(tenantId, mobileApp));
logEntityActionService.logEntityAction(tenantId, savedMobileApp.getId(), savedMobileApp, actionType, user);
return savedMobileApp;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.MOBILE_APP), mobileApp, actionType, user, e);
throw e;
}
} | @Override
public void delete(MobileApp mobileApp, User user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = mobileApp.getTenantId();
MobileAppId mobileAppId = mobileApp.getId();
try {
mobileAppService.deleteMobileAppById(tenantId, mobileAppId);
logEntityActionService.logEntityAction(tenantId, mobileAppId, mobileApp, actionType, user);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, mobileAppId, mobileApp, actionType, user, e);
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\mobile\DefaultTbMobileAppService.java | 2 |
请完成以下Java代码 | public void setContentTypeOptionsValue(String contentTypeOptionsValue) {
this.contentTypeOptionsValue = contentTypeOptionsValue;
}
public boolean isHstsDisabled() {
return hstsDisabled;
}
public void setHstsDisabled(boolean hstsDisabled) {
this.hstsDisabled = hstsDisabled;
}
public boolean isHstsIncludeSubdomainsDisabled() {
return hstsIncludeSubdomainsDisabled;
}
public void setHstsIncludeSubdomainsDisabled(boolean hstsIncludeSubdomainsDisabled) {
this.hstsIncludeSubdomainsDisabled = hstsIncludeSubdomainsDisabled;
}
public String getHstsValue() {
return hstsValue;
}
public void setHstsValue(String hstsValue) {
this.hstsValue = hstsValue;
}
public String getHstsMaxAge() {
return hstsMaxAge;
}
public void setHstsMaxAge(String hstsMaxAge) { | this.hstsMaxAge = hstsMaxAge;
}
@Override
public String toString() {
StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled)
.add("xssProtectionOption=" + xssProtectionOption)
.add("xssProtectionValue=" + xssProtectionValue)
.add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled)
.add("contentSecurityPolicyValue=" + contentSecurityPolicyValue)
.add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled)
.add("contentTypeOptionsValue=" + contentTypeOptionsValue)
.add("hstsDisabled=" + hstsDisabled)
.add("hstsMaxAge=" + hstsMaxAge)
.add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled)
.add("hstsValue=" + hstsValue);
return joinedString.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java | 1 |
请完成以下Java代码 | public class StringRedisSerializer implements RedisSerializer<Object> {
private final Charset charset;
private final String target = "\"";
private final String replacement = "";
public StringRedisSerializer() {
this(Charset.forName("UTF8"));
}
public StringRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!");
this.charset = charset;
} | @Override
public String deserialize(byte[] bytes) {
return (bytes == null ? null : new String(bytes, charset));
}
@Override
public byte[] serialize(Object object) {
String string = JSON.toJSONString(object);
if (string == null) {
return null;
}
string = string.replace(target, replacement);
return string.getBytes(charset);
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\serializer\StringRedisSerializer.java | 1 |
请完成以下Java代码 | public ProjectAccounts getAccounts(@NonNull final ProjectId projectId, @NonNull final AcctSchemaId acctSchemaId)
{
final ImmutableMap<AcctSchemaId, ProjectAccounts> map = cache.getOrLoad(projectId, this::retrieveAccounts);
final ProjectAccounts accounts = map.get(acctSchemaId);
if (accounts == null)
{
throw new AdempiereException("No Project accounts defined for " + projectId + " and " + acctSchemaId);
}
return accounts;
}
private ImmutableMap<AcctSchemaId, ProjectAccounts> retrieveAccounts(@NonNull final ProjectId projectId)
{
return queryBL.createQueryBuilder(I_C_Project_Acct.class)
.addOnlyActiveRecordsFilter() | .addEqualsFilter(I_C_Project_Acct.COLUMNNAME_C_Project_ID, projectId)
.create()
.stream()
.map(ProjectAccountsRepository::fromRecord)
.collect(ImmutableMap.toImmutableMap(ProjectAccounts::getAcctSchemaId, accounts -> accounts));
}
private static ProjectAccounts fromRecord(@NonNull final I_C_Project_Acct record)
{
return ProjectAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.PJ_Asset_Acct(Account.of(AccountId.ofRepoId(record.getPJ_Asset_Acct()), ProjectAccountType.PJ_Asset_Acct))
.PJ_WIP_Acct(Account.of(AccountId.ofRepoId(record.getPJ_WIP_Acct()), ProjectAccountType.PJ_WIP_Acct))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\ProjectAccountsRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderPayScheduleId implements RepoIdAware
{
@JsonCreator
public static OrderPayScheduleId ofRepoId(final int repoId)
{
return new OrderPayScheduleId(repoId);
}
@Nullable
public static OrderPayScheduleId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static Optional<OrderPayScheduleId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
int repoId;
private OrderPayScheduleId(final int repoId)
{ | this.repoId = Check.assumeGreaterThanZero(repoId, "C_OrderPaySchedule_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final OrderPayScheduleId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final OrderPayScheduleId id1, @Nullable final OrderPayScheduleId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\OrderPayScheduleId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class LongStringType extends SerializableType {
public static final String TYPE_NAME = "longString";
private final int minLength;
public LongStringType(int minLength) {
this(minLength, NoopVariableLengthVerifier.INSTANCE);
}
public LongStringType(int minLength, VariableLengthVerifier lengthVerifier) {
super(false, lengthVerifier);
this.minLength = minLength;
}
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value == null) {
valueFields.setCachedValue(null);
valueFields.setBytes(null); | return;
}
String textValue = (String) value;
lengthVerifier.verifyLength(textValue.length(), valueFields, this);
byte[] serializedValue = serialize(textValue, valueFields);
valueFields.setBytes(serializedValue);
valueFields.setCachedValue(textValue);
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return false;
}
if (String.class.isAssignableFrom(value.getClass())) {
String stringValue = (String) value;
return stringValue.length() >= minLength;
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\LongStringType.java | 2 |
请完成以下Java代码 | public Integer getCartId() {
return cartId;
}
public void setCartId(Integer cartId) {
this.cartId = cartId;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CartProductId)) return false;
CartProductId that = (CartProductId) o;
return Objects.equals(cartId, that.cartId) &&
Objects.equals(productId, that.productId);
}
@Override
public int hashCode() {
return Objects.hash(cartId, productId);
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\CartProductId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ValidationResult validate(Condition condition, Assertion assertion, ValidationContext context) {
// applications should validate their own OneTimeUse conditions
return ValidationResult.VALID;
}
});
conditions.add(new ProxyRestrictionConditionValidator());
subjects.add(new BearerSubjectConfirmationValidator() {
@NonNull
protected ValidationResult validateAddress(@NonNull SubjectConfirmation confirmation,
@NonNull Assertion assertion, @NonNull ValidationContext context, boolean required)
throws AssertionValidationException {
return ValidationResult.VALID;
}
@NonNull
protected ValidationResult validateAddress(@NonNull SubjectConfirmationData confirmationData,
@NonNull Assertion assertion, @NonNull ValidationContext context, boolean required)
throws AssertionValidationException {
// applications should validate their own addresses - gh-7514
return ValidationResult.VALID;
}
});
}
static final SAML20AssertionValidator attributeValidator = new SAML20AssertionValidator(conditions, subjects,
statements, null, null, null) {
@NonNull
@Override
protected ValidationResult validateSignature(Assertion token, ValidationContext context) {
return ValidationResult.VALID;
}
};
}
/**
* A tuple containing an OpenSAML {@link Response} and its associated authentication
* token.
*
* @since 5.4
*/
static class ResponseToken {
private final Saml2AuthenticationToken token;
private final Response response; | ResponseToken(Response response, Saml2AuthenticationToken token) {
this.token = token;
this.response = response;
}
Response getResponse() {
return this.response;
}
Saml2AuthenticationToken getToken() {
return this.token;
}
}
/**
* A tuple containing an OpenSAML {@link Assertion} and its associated authentication
* token.
*
* @since 5.4
*/
static class AssertionToken {
private final Saml2AuthenticationToken token;
private final Assertion assertion;
AssertionToken(Assertion assertion, Saml2AuthenticationToken token) {
this.token = token;
this.assertion = assertion;
}
Assertion getAssertion() {
return this.assertion;
}
Saml2AuthenticationToken getToken() {
return this.token;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\BaseOpenSamlAuthenticationProvider.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public BookstoreService(AuthorRepository authorRepository,
BookRepository bookRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
}
public void fetchAuthorById() {
Optional<Author> author = authorRepository.findById(1L);
if (author.isPresent()) {
getAuthorName(author.get());
} else {
System.out.println("Author with id 1 doesn't exist!");
}
}
@Transactional(readOnly = true)
public void fetchAuthorFromBook() {
Optional<Book> book = bookRepository.findByTitle("Mastering JSF 2.2");
if (book.isPresent()) {
Optional<Author> author = book.get().getAuthor();
if (author.isPresent()) {
getAuthorName(author.get());
} else {
System.out.println("Author of this book doesn't exist ... hmmm!");
}
} else { | System.out.println("This book 'Mastering JSF 2.2' doesn't exist!");
}
}
private void getAuthorName(Author author) {
Optional<String> name = author.getName();
if (name.isPresent()) {
System.out.println("Author name: " + name.get());
} else {
System.out.println("The author was found but he is anonymous!");
}
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootOptional\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public String getMemberNickname() {
return memberNickname;
}
public void setMemberNickname(String memberNickname) {
this.memberNickname = memberNickname;
}
public Integer getGetType() {
return getType;
}
public void setGetType(Integer getType) {
this.getType = getType;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getUseStatus() {
return useStatus;
}
public void setUseStatus(Integer useStatus) {
this.useStatus = useStatus;
}
public Date getUseTime() {
return useTime;
}
public void setUseTime(Date useTime) {
this.useTime = useTime;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOrderSn() {
return orderSn;
} | public void setOrderSn(String orderSn) {
this.orderSn = orderSn;
}
@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(", couponId=").append(couponId);
sb.append(", memberId=").append(memberId);
sb.append(", couponCode=").append(couponCode);
sb.append(", memberNickname=").append(memberNickname);
sb.append(", getType=").append(getType);
sb.append(", createTime=").append(createTime);
sb.append(", useStatus=").append(useStatus);
sb.append(", useTime=").append(useTime);
sb.append(", orderId=").append(orderId);
sb.append(", orderSn=").append(orderSn);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponHistory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:table.sql")
.build();
}
@Bean
public DataSourceTransactionManager txManager() {
return new DataSourceTransactionManager(dataSource);
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(TxIntegrationConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in); | System.out.print("Integration flow is running. Type q + <enter> to quit ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
} | repos\tutorials-master\spring-integration\src\main\java\com\baeldung\tx\TxIntegrationConfig.java | 2 |
请完成以下Java代码 | private static ImmutableSet<OLCandId> extractOLCandIds(final List<OLCand> olCands)
{
return olCands.stream().map(olCand -> OLCandId.ofRepoId(olCand.getId())).collect(ImmutableSet.toImmutableSet());
}
private void allocatePayments(final POSOrder posOrder)
{
trxManager.assertThreadInheritedTrxExists();
final I_C_Invoice invoice = getSingleInvoice(posOrder);
for (final POSPayment posPayment : posOrder.getPaymentsNotDeleted())
{
final I_C_Payment paymentReceipt;
if (posPayment.getPaymentReceiptId() != null)
{
paymentReceipt = paymentBL.getById(posPayment.getPaymentReceiptId());
}
else
{
paymentReceipt = createPaymentReceipt(posPayment, posOrder);
final PaymentId paymentReceiptId = PaymentId.ofRepoId(paymentReceipt.getC_Payment_ID());
posOrder.updatePaymentById(posPayment.getLocalIdNotNull(), payment -> payment.withPaymentReceipt(paymentReceiptId));
}
allocationBL.autoAllocateSpecificPayment(invoice, paymentReceipt, true);
}
}
private I_C_Invoice getSingleInvoice(final POSOrder posOrder)
{
final OrderId salesOrderId = posOrder.getSalesOrderId();
if (salesOrderId == null)
{
throw new AdempiereException("No sales order generated for " + posOrder);
}
final List<I_C_Invoice> invoices = invoiceDAO.getInvoicesForOrderIds(ImmutableList.of(salesOrderId));
if (invoices.isEmpty())
{
throw new AdempiereException("No invoices were generated for " + posOrder); | }
else if (invoices.size() > 1)
{
throw new AdempiereException("More than one invoice was generated for " + posOrder);
}
return invoices.get(0);
}
private I_C_Payment createPaymentReceipt(@NonNull final POSPayment posPayment, @NonNull POSOrder posOrder)
{
posPayment.assertNoPaymentReceipt();
return paymentBL.newInboundReceiptBuilder()
.adOrgId(posOrder.getOrgId())
.orgBankAccountId(posOrder.getCashbookId())
.bpartnerId(posOrder.getShipToCustomerId())
.payAmt(posPayment.getAmount().toBigDecimal())
.currencyId(posPayment.getAmount().getCurrencyId())
.tenderType(posPayment.getPaymentMethod().getTenderType())
.dateTrx(posOrder.getDate())
.createAndProcess();
// TODO: add the payment to bank statement
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\async\C_POSOrder_CreateInvoiceAndShipment.java | 1 |
请完成以下Java代码 | public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setProductValue (final java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setProjectValue (final @Nullable java.lang.String ProjectValue)
{
set_Value (COLUMNNAME_ProjectValue, ProjectValue);
}
@Override
public java.lang.String getProjectValue()
{
return get_ValueAsString(COLUMNNAME_ProjectValue);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override | public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated);
}
@Override
public BigDecimal getQtyCalculated()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM()
{
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setWarehouseValue (final java.lang.String WarehouseValue)
{
set_Value (COLUMNNAME_WarehouseValue, WarehouseValue);
}
@Override
public java.lang.String getWarehouseValue()
{
return get_ValueAsString(COLUMNNAME_WarehouseValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<Void> updateInfo(InstanceId id) {
return this.repository.computeIfPresent(id, (key, instance) -> this.doUpdateInfo(instance)).then();
}
protected Mono<Instance> doUpdateInfo(Instance instance) {
if (instance.getStatusInfo().isOffline() || instance.getStatusInfo().isUnknown()) {
return Mono.empty();
}
if (!instance.getEndpoints().isPresent(Endpoint.INFO)) {
return Mono.empty();
}
log.debug("Update info for {}", instance);
return this.instanceWebClient.instance(instance)
.get()
.uri(Endpoint.INFO)
.exchangeToMono((response) -> convertInfo(instance, response))
.log(log.getName(), Level.FINEST)
.onErrorResume((ex) -> Mono.just(convertInfo(instance, ex)))
.map(instance::withInfo);
} | protected Mono<Info> convertInfo(Instance instance, ClientResponse response) {
if (response.statusCode().is2xxSuccessful() && response.headers()
.contentType()
.filter((mt) -> mt.isCompatibleWith(MediaType.APPLICATION_JSON)
|| this.apiMediaTypeHandler.isApiMediaType(mt))
.isPresent()) {
return response.bodyToMono(RESPONSE_TYPE).map(Info::from).defaultIfEmpty(Info.empty());
}
log.info("Couldn't retrieve info for {}: {}", instance, response.statusCode());
return response.releaseBody().then(Mono.just(Info.empty()));
}
protected Info convertInfo(Instance instance, Throwable ex) {
log.warn("Couldn't retrieve info for {}", instance, ex);
return Info.empty();
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\InfoUpdater.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isBlockIfFull() {
return this.blockIfFull;
}
public void setBlockIfFull(boolean blockIfFull) {
this.blockIfFull = blockIfFull;
}
public Duration getBlockIfFullTimeout() {
return this.blockIfFullTimeout;
}
public void setBlockIfFullTimeout(Duration blockIfFullTimeout) {
this.blockIfFullTimeout = blockIfFullTimeout;
}
public Duration getIdleTimeout() {
return this.idleTimeout;
}
public void setIdleTimeout(Duration idleTimeout) {
this.idleTimeout = idleTimeout;
}
public int getMaxConnections() {
return this.maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public int getMaxSessionsPerConnection() {
return this.maxSessionsPerConnection;
} | public void setMaxSessionsPerConnection(int maxSessionsPerConnection) {
this.maxSessionsPerConnection = maxSessionsPerConnection;
}
public Duration getTimeBetweenExpirationCheck() {
return this.timeBetweenExpirationCheck;
}
public void setTimeBetweenExpirationCheck(Duration timeBetweenExpirationCheck) {
this.timeBetweenExpirationCheck = timeBetweenExpirationCheck;
}
public boolean isUseAnonymousProducers() {
return this.useAnonymousProducers;
}
public void setUseAnonymousProducers(boolean useAnonymousProducers) {
this.useAnonymousProducers = useAnonymousProducers;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsPoolConnectionFactoryProperties.java | 2 |
请完成以下Java代码 | default int getWindowNo()
{
return Env.WINDOW_None;
}
boolean hasFieldValue(String fieldName);
Object getFieldValue(String fieldName);
default int getFieldValueAsInt(final String fieldName, final int defaultValue)
{
final Object value = getFieldValue(fieldName);
return value != null ? (int)value : defaultValue;
}
@Nullable
default <T extends RepoIdAware> T getFieldValueAsRepoId(final String fieldName, final Function<Integer, T> idMapper)
{
final int id = getFieldValueAsInt(fieldName, -1);
if (id > 0)
{
return idMapper.apply(id);
}
else
{
return null;
}
}
static SourceDocument toSourceDocumentOrNull(final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof SourceDocument)
{
return (SourceDocument)obj;
}
final PO po = getPO(obj);
return new POSourceDocument(po);
}
}
@AllArgsConstructor
private static final class POSourceDocument implements SourceDocument
{
@NonNull
private final PO po;
@Override
public boolean hasFieldValue(final String fieldName) | {
return po.get_ColumnIndex(fieldName) >= 0;
}
@Override
public Object getFieldValue(final String fieldName)
{
return po.get_Value(fieldName);
}
}
@AllArgsConstructor
private static final class GridTabSourceDocument implements SourceDocument
{
@NonNull
private final GridTab gridTab;
@Override
public boolean hasFieldValue(final String fieldName)
{
return gridTab.getField(fieldName) != null;
}
@Override
public Object getFieldValue(final String fieldName)
{
return gridTab.getValue(fieldName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(@Nullable Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public @Nullable Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(@Nullable Duration readTimeout) {
this.readTimeout = readTimeout;
}
public Ssl getSsl() {
return this.ssl;
}
/**
* SSL configuration.
*/
@ConfigurationPropertiesSource
public static class Ssl { | /**
* SSL bundle to use.
*/
private @Nullable String bundle;
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\HttpClientSettingsProperties.java | 2 |
请完成以下Java代码 | public void updateById(TenantId tenantId, NotificationRequestId requestId, NotificationRequestStatus requestStatus, NotificationRequestStats stats) {
notificationRequestRepository.updateStatusAndStatsById(requestId.getId(), requestStatus, JacksonUtil.valueToTree(stats));
}
@Override
public boolean existsByTenantIdAndStatusAndTargetId(TenantId tenantId, NotificationRequestStatus status, NotificationTargetId targetId) {
return notificationRequestRepository.existsByTenantIdAndStatusAndTargetsContaining(tenantId.getId(), status, targetId.getId().toString());
}
@Override
public boolean existsByTenantIdAndStatusAndTemplateId(TenantId tenantId, NotificationRequestStatus status, NotificationTemplateId templateId) {
return notificationRequestRepository.existsByTenantIdAndStatusAndTemplateId(tenantId.getId(), status, templateId.getId());
}
@Override
public int removeAllByCreatedTimeBefore(long ts) {
return notificationRequestRepository.deleteAllByCreatedTimeBefore(ts);
}
@Override
public NotificationRequestInfo findInfoById(TenantId tenantId, NotificationRequestId id) {
NotificationRequestInfoEntity info = notificationRequestRepository.findInfoById(id.getId());
return info != null ? info.toData() : null;
}
@Override
public void removeByTenantId(TenantId tenantId) {
notificationRequestRepository.deleteByTenantId(tenantId.getId());
} | @Override
protected Class<NotificationRequestEntity> getEntityClass() {
return NotificationRequestEntity.class;
}
@Override
protected JpaRepository<NotificationRequestEntity, UUID> getRepository() {
return notificationRequestRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_REQUEST;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRequestDao.java | 1 |
请完成以下Java代码 | public CreditorReferenceType2 getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link CreditorReferenceType2 }
*
*/
public void setTp(CreditorReferenceType2 value) {
this.tp = value;
}
/**
* Gets the value of the ref property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getRef() {
return ref;
}
/**
* Sets the value of the ref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRef(String value) {
this.ref = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CreditorReferenceInformation2.java | 1 |
请完成以下Java代码 | public class SondertagBestellfenster {
@XmlElement(name = "Endezeit", required = true)
@XmlSchemaType(name = "time")
protected XMLGregorianCalendar endezeit;
@XmlElement(name = "Hauptbestellzeit", required = true)
@XmlSchemaType(name = "time")
protected XMLGregorianCalendar hauptbestellzeit;
/**
* Gets the value of the endezeit property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndezeit() {
return endezeit;
}
/**
* Sets the value of the endezeit property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndezeit(XMLGregorianCalendar value) {
this.endezeit = value;
}
/**
* Gets the value of the hauptbestellzeit property.
* | * @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getHauptbestellzeit() {
return hauptbestellzeit;
}
/**
* Sets the value of the hauptbestellzeit property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setHauptbestellzeit(XMLGregorianCalendar value) {
this.hauptbestellzeit = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\SondertagBestellfenster.java | 1 |
请完成以下Java代码 | public ProcessEngine getObject() throws Exception {
if (processEngine == null) {
initializeExpressionManager();
initializeTransactionExternallyManaged();
processEngine = (ProcessEngineImpl) processEngineConfiguration.buildProcessEngine();
}
return processEngine;
}
protected void initializeExpressionManager() {
if (processEngineConfiguration.getExpressionManager() == null && applicationContext != null) {
processEngineConfiguration.setExpressionManager(
new SpringExpressionManager(applicationContext, processEngineConfiguration.getBeans()));
}
}
protected void initializeTransactionExternallyManaged() {
if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringProcessEngineConfiguration engineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
processEngineConfiguration.setTransactionsExternallyManaged(true);
}
}
}
public Class<ProcessEngine> getObjectType() {
return ProcessEngine.class;
} | public boolean isSingleton() {
return true;
}
// getters and setters //////////////////////////////////////////////////////
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\ProcessEngineFactoryBean.java | 1 |
请完成以下Java代码 | public void setRenderedQRCode (final @Nullable java.lang.String RenderedQRCode)
{
set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode);
}
@Override
public java.lang.String getRenderedQRCode()
{
return get_ValueAsString(COLUMNNAME_RenderedQRCode);
}
@Override
public org.compiere.model.I_M_InventoryLine getReversalLine()
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class);
}
@Override
public void setReversalLine(final org.compiere.model.I_M_InventoryLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_InventoryLine.class, ReversalLine);
}
@Override
public void setReversalLine_ID (final int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID);
}
@Override
public int getReversalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_ReversalLine_ID);
}
@Override
public void setUPC (final @Nullable java.lang.String UPC) | {
throw new IllegalArgumentException ("UPC is virtual column"); }
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
throw new IllegalArgumentException ("Value is virtual column"); }
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InventoryLine.java | 1 |
请完成以下Java代码 | public final class GTIN
{
@NonNull private final String value;
private transient ExplainedOptional<EAN13> ean13Holder; // lazy
private GTIN(@NonNull final String value)
{
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm == null)
{
throw new AdempiereException("Invalid GTIN value: " + value);
}
this.value = valueNorm;
}
private GTIN(@NonNull final EAN13 ean13)
{
this.value = ean13.getAsString();
this.ean13Holder = ExplainedOptional.of(ean13);
}
@JsonCreator
public static GTIN ofString(@NonNull final String value)
{
return new GTIN(value);
}
public static GTIN ofNullableString(@Nullable final String value)
{
final String valueNorm = StringUtils.trimBlankToNull(value);
return valueNorm != null ? ofString(valueNorm) : null;
}
public static Optional<GTIN> optionalOfNullableString(@Nullable final String value) {return Optional.ofNullable(ofNullableString(value));}
public static GTIN ofEAN13(@NonNull final EAN13 ean13)
{
return new GTIN(ean13);
}
public static Optional<GTIN> ofScannedCode(@NonNull final ScannedCode scannedCode)
{
return optionalOfNullableString(scannedCode.getAsString());
}
@Override
@Deprecated
public String toString() {return getAsString();}
@JsonValue
public String getAsString() {return value;} | public ExplainedOptional<EAN13> toEAN13()
{
ExplainedOptional<EAN13> ean13Holder = this.ean13Holder;
if (ean13Holder == null)
{
ean13Holder = this.ean13Holder = EAN13.ofString(value);
}
return ean13Holder;
}
public boolean isMatching(final @NonNull EAN13ProductCode expectedProductCode)
{
final EAN13 ean13 = toEAN13().orElse(null);
return ean13 != null && ean13.isMatching(expectedProductCode);
}
public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode)
{
final EAN13 ean13 = toEAN13().orElse(null);
return ean13 != null && ean13.productCodeEndsWith(expectedProductCode);
}
/**
* @return true if fixed code (e.g. not a variable weight EAN13 etc)
*/
public boolean isFixed()
{
final EAN13 ean13 = toEAN13().orElse(null);
return ean13 == null || ean13.isFixed();
}
/**
* @return true if fixed code (e.g. not a variable weight EAN13 etc)
*/
public boolean isVariable()
{
final EAN13 ean13 = toEAN13().orElse(null);
return ean13 == null || ean13.isVariableWeight();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GTIN.java | 1 |
请完成以下Java代码 | protected MaterialCockpitView getView()
{
return MaterialCockpitView.cast(super.getView());
}
@Override
protected Stream<MaterialCockpitRow> streamSelectedRows()
{
return super.streamSelectedRows().map(MaterialCockpitRow::cast);
}
protected Set<Integer> getSelectedCockpitRecordIdsRecursively()
{
final MaterialCockpitView materialCockpitView = getView(); | return materialCockpitView.streamByIds(getSelectedRowIds())
.flatMap(row -> row.getAllIncludedCockpitRecordIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
protected Set<ProductId> getSelectedProductIdsRecursively()
{
final MaterialCockpitView materialCockpitView = getView();
return materialCockpitView.streamByIds(getSelectedRowIds())
.map(MaterialCockpitRow::getProductId)
.distinct()
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\process\MaterialCockpitViewBasedProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WarehouseRestController
{
@NonNull private final WarehouseService warehouseService;
@NonNull private final WarehouseRestService warehouseRestService;
private @NotNull String getAdLanguage() {return Env.getADLanguageOrBaseLanguage();}
@PutMapping("/{warehouseId}/outOfStockNotice")
public ResponseEntity<?> createShippingPackages(
@PathVariable("warehouseId") @NonNull final String warehouseId,
@RequestBody final JsonOutOfStockNoticeRequest request)
{
try
{
final JsonOutOfStockResponse response = warehouseService.handleOutOfStockRequest(warehouseId, request);
return ResponseEntity.ok(response);
}
catch (final Exception ex)
{
Loggables.addLog(ex.getLocalizedMessage(), ex);
return ResponseEntity.badRequest().body(JsonErrors.ofThrowable(ex, getAdLanguage()));
}
}
@Operation(summary = "Create or update warehouses.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully created or updated warehouse(s)"),
@ApiResponse(responseCode = "401", description = "You are not authorized to create or update the resource"),
@ApiResponse(responseCode = "403", description = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(responseCode = "422", description = "The request entity could not be processed")
})
@PutMapping("{orgCode}")
public ResponseEntity<JsonResponseUpsert> upsertWarehouses(
@Parameter(required = true, description = ORG_CODE_PARAMETER_DOC)
@PathVariable("orgCode") @Nullable final String orgCode, // may be null if called from other metasfresh-code | @RequestBody @NonNull final JsonRequestWarehouseUpsert request)
{
final JsonResponseUpsert responseUpsert = warehouseRestService.upsertWarehouses(orgCode, request);
return ResponseEntity.ok(responseUpsert);
}
@GetMapping("/resolveLocator")
@NonNull
public JsonResolveLocatorResponse resolveLocatorScannedCode(
@RequestParam("scannedBarcode") final String scannedBarcode)
{
try
{
return JsonResolveLocatorResponse.ok(warehouseRestService.resolveLocatorScannedCode(ScannedCode.ofString(scannedBarcode)));
}
catch (final Exception ex)
{
return JsonResolveLocatorResponse.error(ex, getAdLanguage());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\warehouse\WarehouseRestController.java | 2 |
请完成以下Java代码 | private String sendEMail(final MADBoilerPlate text, final MInOut io, final I_AD_User orderUser)
{
final Properties ctx = Env.getCtx();
MADBoilerPlate.sendEMail(new IEMailEditor()
{
@Override
public Object getBaseObject()
{
return io;
}
@Override
public int getAD_Table_ID()
{
return io.get_Table_ID();
}
@Override
public int getRecord_ID()
{
return io.get_ID();
}
@Override
public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final BoilerPlateContext attributesEffective = attributes.toBuilder()
.setSourceDocumentFromObject(io)
.build();
//
String message = text.getTextSnippetParsed(attributesEffective);
//
if (Check.isEmpty(message, true))
{
return null;
}
//
final StringTokenizer st = new StringTokenizer(toEmail, " ,;", false);
EMailAddress to = EMailAddress.ofString(st.nextToken());
MClient client = MClient.get(ctx, Env.getAD_Client_ID(ctx));
if (orderUser != null)
{
to = EMailAddress.ofString(orderUser.getEMail());
}
EMail email = client.createEMail(
to,
text.getName(),
message,
true);
if (email == null)
{
throw new AdempiereException("Cannot create email. Check log.");
}
while (st.hasMoreTokens()) | {
email.addTo(EMailAddress.ofString(st.nextToken()));
}
send(email);
return email;
}
}, false);
return "";
}
private void send(EMail email)
{
int maxRetries = p_SMTPRetriesNo > 0 ? p_SMTPRetriesNo : 0;
int count = 0;
do
{
final EMailSentStatus emailSentStatus = email.send();
count++;
if (emailSentStatus.isSentOK())
{
return;
}
// Timeout => retry
if (emailSentStatus.isSentConnectionError() && count < maxRetries)
{
log.warn("SMTP error: {} [ Retry {}/{} ]", emailSentStatus, count, maxRetries);
}
else
{
throw new EMailSendException(emailSentStatus);
}
}
while (true);
}
private void setNotified(I_M_PackageLine packageLine)
{
InterfaceWrapperHelper.getPO(packageLine).set_ValueOfColumn("IsSentMailNotification", true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\validator\ShipperTransportationMailNotification.java | 1 |
请完成以下Java代码 | public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return EMPTY_BYTE_ARRAY;
}
Kryo kryo = kryos.get();
kryo.setReferences(false);
kryo.register(clazz);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
Output output = new Output(baos)) {
kryo.writeClassAndObject(output, t);
output.flush();
return baos.toByteArray();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return EMPTY_BYTE_ARRAY;
} | @Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
Kryo kryo = kryos.get();
kryo.setReferences(false);
kryo.register(clazz);
try (Input input = new Input(bytes)) {
return (T) kryo.readClassAndObject(input);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\redis\serializer\KryoRedisSerializer.java | 1 |
请完成以下Java代码 | public boolean isOnlyChildExecutions() {
return onlyChildExecutions;
}
public boolean isOnlyProcessInstanceExecutions() {
return onlyProcessInstanceExecutions;
}
public boolean isOnlySubProcessExecutions() {
return onlySubProcessExecutions;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public boolean isWithJobException() {
return withJobException;
}
public String getLocale() {
return locale;
} | public boolean isNeedsProcessDefinitionOuterJoin() {
if (isNeedsPaging()) {
if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) {
// When using oracle, db2 or mssql we don't need outer join for the process definition join.
// It is not needed because the outer join order by is done by the row number instead
return false;
}
}
return hasOrderByForColumn(ProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName());
}
public List<List<String>> getSafeProcessInstanceIds() {
return safeProcessInstanceIds;
}
public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeProcessInstanceIds = safeProcessInstanceIds;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public abstract class AbstractESRPaymentStringParser implements IPaymentStringParser
{
private static final IMsgBL msgBL = Services.get(IMsgBL.class);
protected static final AdMessageKey ERR_WRONG_PAYMENT_DATE = AdMessageKey.of("ESR_Wrong_Payment_Date");
protected static final AdMessageKey ERR_WRONG_ACCOUNT_DATE = AdMessageKey.of("ESR_Wrong_Account_Date");
private static final AdMessageKey ERR_WRONG_NUMBER_FORMAT_AMOUNT = AdMessageKey.of("ESR_Wrong_Number_Format_Amount");
protected final BigDecimal extractAmountFromString(final String trxType, final String amountStringWithPosibleSpaces, final List<String> collectedErrors)
{
final String amountString = Util.replaceNonDigitCharsWithZero(amountStringWithPosibleSpaces); // 04551
BigDecimal amount = BigDecimal.ZERO;
try
{
amount = new BigDecimal(amountString)
.divide(Env.ONEHUNDRED, 2, RoundingMode.UNNECESSARY);
if (trxType.endsWith(ESRConstants.ESRTRXTYPE_REVERSE_LAST_DIGIT))
{
amount = amount.negate();
}
// Important: the imported amount doesn't need to match the invoices' amounts
}
catch (final NumberFormatException e)
{
final String wrongNumberFormatAmount = msgBL.getMsg(Env.getCtx(), ERR_WRONG_NUMBER_FORMAT_AMOUNT, new Object[] { amountString });
collectedErrors.add(wrongNumberFormatAmount);
}
return amount;
}
protected final BigDecimal extractAmountFromString(final String amountString,
final List<String> collectedErrors)
{
BigDecimal amount = BigDecimal.ZERO;
try | {
amount = NumberUtils.asBigDecimal(amountString);
}
catch (final NumberFormatException e)
{
final String wrongNumberFormatAmount = msgBL.getMsg(Env.getCtx(), ERR_WRONG_NUMBER_FORMAT_AMOUNT, new Object[] { amountString });
collectedErrors.add(wrongNumberFormatAmount);
}
return amount;
}
/**
*
* @param dateStr date string in format yyMMdd
* @param collectedErrors
* @return
*/
protected final Timestamp extractTimestampFromString(final String dateStr, final AdMessageKey failMessage, final List<String> collectedErrors)
{
final DateFormat df = new SimpleDateFormat("yyMMdd");
final Date date;
try
{
date = df.parse(dateStr);
return TimeUtil.asTimestamp(date);
}
catch (final ParseException e)
{
final String wrongDate = msgBL.getMsg(Env.getCtx(), failMessage, new Object[] { dateStr });
collectedErrors.add(wrongDate);
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\spi\impl\AbstractESRPaymentStringParser.java | 1 |
请完成以下Java代码 | private boolean endsWith(@NonNull final EAN13ProductCode expectedProductNo, @Nullable final BPartnerId bpartnerId)
{
final GS1ProductCodes bpartnerCodes = bpartnerId != null ? codesByBPartnerId.get(bpartnerId) : null;
return (bpartnerCodes != null && bpartnerCodes.endsWith(expectedProductNo))
|| defaultCodes.endsWith(expectedProductNo);
}
public boolean isValidProductNo(@NonNull final EAN13 ean13, @Nullable final BPartnerId bpartnerId)
{
final EAN13Prefix ean13Prefix = ean13.getPrefix();
final EAN13ProductCode ean13ProductNo = ean13.getProductNo();
// 28 - Variable-Weight barcodes
if (ean13Prefix.isVariableWeight())
{
return contains(ean13ProductNo, bpartnerId)
|| ean13ProductNo.isPrefixOf(productValue);
}
// 29 - Internal Use / Variable measure
else if (ean13Prefix.isInternalUseOrVariableMeasure())
{
return contains(ean13ProductNo, bpartnerId);
}
// Parse regular product codes for other prefixes
else | {
return endsWith(ean13ProductNo, bpartnerId);
}
}
public Optional<GS1ProductCodes> getEffectiveCodes(@Nullable final BPartnerId bpartnerId)
{
final GS1ProductCodes bpartnerCodes = bpartnerId != null ? codesByBPartnerId.get(bpartnerId) : null;
final GS1ProductCodes effectiveCodes = bpartnerCodes != null
? bpartnerCodes.fallbackTo(defaultCodes)
: defaultCodes;
return Optional.ofNullable(effectiveCodes.isEmpty() ? null : effectiveCodes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1ProductCodesCollection.java | 1 |
请完成以下Java代码 | void open() throws IOException {
synchronized (this.lock) {
if (this.referenceCount == 0) {
debug.log("Opening '%s'", this.path);
this.fileChannel = FileChannel.open(this.path, StandardOpenOption.READ);
this.buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
tracker.openedFileChannel(this.path);
}
this.referenceCount++;
debug.log("Reference count for '%s' incremented to %s", this.path, this.referenceCount);
}
}
void close() throws IOException {
synchronized (this.lock) {
if (this.referenceCount == 0) {
return;
}
this.referenceCount--;
if (this.referenceCount == 0) {
debug.log("Closing '%s'", this.path);
this.buffer = null;
this.bufferPosition = -1;
this.bufferSize = 0;
this.fileChannel.close();
tracker.closedFileChannel(this.path);
this.fileChannel = null;
if (this.randomAccessFile != null) {
this.randomAccessFile.close();
tracker.closedFileChannel(this.path);
this.randomAccessFile = null;
}
}
debug.log("Reference count for '%s' decremented to %s", this.path, this.referenceCount);
}
}
<E extends Exception> void ensureOpen(Supplier<E> exceptionSupplier) throws E {
synchronized (this.lock) {
if (this.referenceCount == 0) {
throw exceptionSupplier.get();
}
}
}
@Override | public String toString() {
return this.path.toString();
}
}
/**
* Internal tracker used to check open and closing of files in tests.
*/
interface Tracker {
Tracker NONE = new Tracker() {
@Override
public void openedFileChannel(Path path) {
}
@Override
public void closedFileChannel(Path path) {
}
};
void openedFileChannel(Path path);
void closedFileChannel(Path path);
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\FileDataBlock.java | 1 |
请完成以下Java代码 | public List<RefundConfig> getRefundConfigsToApplyForQuantity(@NonNull final BigDecimal qty)
{
final Predicate<RefundConfig> minQtyLessOrEqual = config -> config.getMinQty().compareTo(qty) <= 0;
return refundConfigs
.stream()
.filter(minQtyLessOrEqual)
.collect(ImmutableList.toImmutableList());
}
public RefundConfig getRefundConfigById(@NonNull final RefundConfigId refundConfigId)
{
for (RefundConfig refundConfig : refundConfigs)
{
if (refundConfig.getId().equals(refundConfigId))
{
return refundConfig;
}
}
Check.fail("This contract has no config with id={}; this={}", refundConfigId, this);
return null;
}
public RefundMode extractRefundMode()
{
return RefundConfigs.extractRefundMode(refundConfigs);
}
public Optional<RefundConfig> getRefundConfigToUseProfitCalculation()
{
return getRefundConfigs()
.stream()
.filter(RefundConfig::isUseInProfitCalculation)
.findFirst();
}
/**
* With this instance's {@code StartDate} as basis, the method returns the first date that is
* after or at the given {@code currentDate} and that is aligned with this instance's invoice schedule.
*/
public NextInvoiceDate computeNextInvoiceDate(@NonNull final LocalDate currentDate)
{ | final InvoiceSchedule invoiceSchedule = extractSingleElement(refundConfigs, RefundConfig::getInvoiceSchedule);
LocalDate date = invoiceSchedule.calculateNextDateToInvoice(startDate);
while (date.isBefore(currentDate))
{
final LocalDate nextDate = invoiceSchedule.calculateNextDateToInvoice(date);
Check.assume(nextDate.isAfter(date), // make sure not to get stuck in an endless loop
"For the given date={}, invoiceSchedule.calculateNextDateToInvoice needs to return a nextDate that is later; nextDate={}",
date, nextDate);
date = nextDate;
}
return new NextInvoiceDate(invoiceSchedule, date);
}
@Value
public static class NextInvoiceDate
{
InvoiceSchedule invoiceSchedule;
LocalDate dateToInvoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundContract.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AuthController {
private BladeRedis bladeRedis;
@PostMapping("token")
@Operation(summary = "获取认证token", description = "传入租户ID:tenantId,账号:account,密码:password")
public R<AuthInfo> token(@Parameter(description = "授权类型", required = true) @RequestParam(defaultValue = "password", required = false) String grantType,
@Parameter(description = "刷新令牌") @RequestParam(required = false) String refreshToken,
@Parameter(description = "租户ID", required = true) @RequestParam(defaultValue = "000000", required = false) String tenantId,
@Parameter(description = "账号") @RequestParam(required = false) String account,
@Parameter(description = "密码") @RequestParam(required = false) String password) {
String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);
TokenParameter tokenParameter = new TokenParameter();
tokenParameter.getArgs().set("tenantId", tenantId)
.set("account", account)
.set("password", password)
.set("grantType", grantType)
.set("refreshToken", refreshToken)
.set("userType", userType);
ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
UserInfo userInfo = granter.grant(tokenParameter);
if (userInfo == null || userInfo.getUser() == null || userInfo.getUser().getId() == null) {
return R.fail(TokenUtil.USER_NOT_FOUND);
} | return R.data(TokenUtil.createAuthInfo(userInfo));
}
@GetMapping("/captcha")
@Operation(summary = "获取验证码")
public R<Kv> captcha() {
SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
String verCode = specCaptcha.text().toLowerCase();
String key = UUID.randomUUID().toString();
// 存入redis并设置过期时间为30分钟
bladeRedis.setEx(CacheNames.CAPTCHA_KEY + key, verCode, 30L, TimeUnit.MINUTES);
// 将key和base64返回给前端
return R.data(Kv.init().set("key", key).set("image", specCaptcha.toBase64()));
}
@PostMapping("/logout")
@Operation(summary = "登出")
public R<Kv> logout() {
// 登出预留逻辑
return R.data(Kv.init().set("code", "200").set("msg", "操作成功"));
}
} | repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\controller\AuthController.java | 2 |
请完成以下Java代码 | public class CharacterWithHighestFrequency {
public static Character byStream(String input) {
return input.chars()
.mapToObj(x -> (char) x)
.collect(groupingBy(x -> x, counting()))
.entrySet()
.stream()
.max(comparingByValue())
.get()
.getKey();
}
public static Set<Character> byMap(String input) {
Map<Character, Integer> map = new HashMap<>();
for (char c : input.toCharArray()) {
map.compute(c, (character, count) -> count == null ? 1 : ++count);
}
int maxCount = map.values()
.stream()
.mapToInt(Integer::intValue)
.max()
.getAsInt(); | return map.keySet()
.stream()
.filter(c -> map.get(c) == maxCount)
.collect(toSet());
}
public static Set<Character> byBucket(String input) {
int[] buckets = new int[128];
int maxCount = 0;
for (char c : input.toCharArray()) {
buckets[c]++;
maxCount = Math.max(buckets[c], maxCount);
}
int finalMaxCount = maxCount;
return IntStream.range(0, 128)
.filter(c -> buckets[c] == finalMaxCount)
.mapToObj(i -> (char) i)
.collect(Collectors.toSet());
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-3\src\main\java\com\baeldung\charfreq\CharacterWithHighestFrequency.java | 1 |
请完成以下Java代码 | public void addInParameter(IOParameter inParameter) {
this.inParameters.add(inParameter);
}
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
@Override | public void addOutParameter(IOParameter outParameter) {
this.outParameters.add(outParameter);
}
@Override
public ExternalWorkerServiceTask clone() {
ExternalWorkerServiceTask clone = new ExternalWorkerServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ExternalWorkerServiceTask otherElement) {
super.setValues(otherElement);
setTopic(otherElement.getTopic());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ExternalWorkerServiceTask.java | 1 |
请完成以下Java代码 | private static InventoryAndLineId extractInventoryAndLineId(final I_M_InventoryLine_HU inventoryLineHU)
{
return InventoryAndLineId.ofRepoIds(inventoryLineHU.getM_Inventory_ID(), inventoryLineHU.getM_InventoryLine_ID());
}
public void updateInventoryLineByRecord(final I_M_InventoryLine inventoryLineRecord, UnaryOperator<InventoryLine> updater)
{
trxManager.runInThreadInheritedTrx(() -> newLoaderAndSaver().updateInventoryLineByRecord(inventoryLineRecord, updater));
}
public Inventory updateById(final InventoryId inventoryId, UnaryOperator<Inventory> updater)
{
return trxManager.callInThreadInheritedTrx(() -> newLoaderAndSaver().updateById(inventoryId, updater));
}
public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater)
{
trxManager.runInThreadInheritedTrx(() -> newLoaderAndSaver().updateByQuery(query, updater));
}
public Stream<InventoryReference> streamReferences(@NonNull final InventoryQuery query)
{
return newLoaderAndSaver().streamReferences(query);
}
public void setQtyCountToQtyBookForInventory(@NonNull final InventoryId inventoryId) | {
// update M_InventoryLine
final ICompositeQueryUpdater<org.compiere.model.I_M_InventoryLine> updaterInventoryLine = queryBL.createCompositeQueryUpdater(org.compiere.model.I_M_InventoryLine.class)
.addSetColumnFromColumn(org.compiere.model.I_M_InventoryLine.COLUMNNAME_QtyCount, ModelColumnNameValue.forColumnName(org.compiere.model.I_M_InventoryLine.COLUMNNAME_QtyBook));
queryBL.createQueryBuilder(org.compiere.model.I_M_InventoryLine.class)
.addEqualsFilter(org.compiere.model.I_M_InventoryLine.COLUMNNAME_M_Inventory_ID, inventoryId)
.create().update(updaterInventoryLine);
// update M_InventoryLine_HU
final ICompositeQueryUpdater<I_M_InventoryLine_HU> updaterInventoryLineHU = queryBL.createCompositeQueryUpdater(I_M_InventoryLine_HU.class)
.addSetColumnFromColumn(I_M_InventoryLine_HU.COLUMNNAME_QtyCount, ModelColumnNameValue.forColumnName(I_M_InventoryLine_HU.COLUMNNAME_QtyBook));
queryBL.createQueryBuilder(I_M_InventoryLine_HU.class)
.addEqualsFilter(I_M_InventoryLine_HU.COLUMNNAME_M_Inventory_ID, inventoryId)
.create().update(updaterInventoryLineHU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class ControllerAdviceBeanWrapper implements MessagingAdviceBean {
private final ControllerAdviceBean adviceBean;
private ControllerAdviceBeanWrapper(ControllerAdviceBean adviceBean) {
this.adviceBean = adviceBean;
}
@Override
public @Nullable Class<?> getBeanType() {
return this.adviceBean.getBeanType();
}
@Override
public Object resolveBean() {
return this.adviceBean.resolveBean(); | }
@Override
public boolean isApplicableToBeanType(Class<?> beanType) {
return this.adviceBean.isApplicableToBeanType(beanType);
}
@Override
public int getOrder() {
return this.adviceBean.getOrder();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketMessagingAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MessageEventHandler {
private final SocketIOServer server;
private static final Logger logger = LoggerFactory.getLogger(MessageEventHandler.class);
@Autowired
public MessageEventHandler(SocketIOServer server) {
this.server = server;
}
//添加connect事件,当客户端发起连接时调用
@OnConnect
public void onConnect(SocketIOClient client) {
if (client != null) {
String username = client.getHandshakeData().getSingleUrlParam("username");
String password = client.getHandshakeData().getSingleUrlParam("password");
String sessionId = client.getSessionId().toString();
logger.info("连接成功, username=" + username + ", password=" + password + ", sessionId=" + sessionId);
} else {
logger.error("客户端为空");
}
}
//添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息
@OnDisconnect
public void onDisconnect(SocketIOClient client) {
logger.info("客户端断开连接, sessionId=" + client.getSessionId().toString());
client.disconnect();
} | // 消息接收入口
@OnEvent(value = "chatevent")
public void onEvent(SocketIOClient client, AckRequest ackRequest, ChatMessage chat) {
logger.info("接收到客户端消息");
if (ackRequest.isAckRequested()) {
// send ack response with data to client
ackRequest.sendAckData("服务器回答chatevent, userName=" + chat.getUserName() + ",message=" + chat.getMessage());
}
}
// 登录接口
@OnEvent(value = "login")
public void onLogin(SocketIOClient client, AckRequest ackRequest, LoginRequest message) {
logger.info("接收到客户端登录消息");
if (ackRequest.isAckRequested()) {
// send ack response with data to client
ackRequest.sendAckData("服务器回答login", message.getCode(), message.getBody());
}
}
} | repos\SpringBootBucket-master\springboot-socketio\src\main\java\com\xncoding\jwt\handler\MessageEventHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getSurchargeAmt() {
return surchargeAmt;
}
/**
* Sets the value of the surchargeAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSurchargeAmt(BigDecimal value) {
this.surchargeAmt = value;
}
/**
* Gets the value of the taxBaseAmtWithSurchargeAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getTaxBaseAmtWithSurchargeAmt() {
return taxBaseAmtWithSurchargeAmt;
}
/**
* Sets the value of the taxBaseAmtWithSurchargeAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTaxBaseAmtWithSurchargeAmt(BigDecimal value) {
this.taxBaseAmtWithSurchargeAmt = value;
}
/**
* Gets the value of the taxAmtWithSurchargeAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getTaxAmtWithSurchargeAmt() {
return taxAmtWithSurchargeAmt; | }
/**
* Sets the value of the taxAmtWithSurchargeAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTaxAmtWithSurchargeAmt(BigDecimal value) {
this.taxAmtWithSurchargeAmt = value;
}
/**
* Gets the value of the isMainVAT property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIsMainVAT() {
return isMainVAT;
}
/**
* Sets the value of the isMainVAT property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIsMainVAT(String value) {
this.isMainVAT = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop901991VType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected String doIt()
{
final HuId huId = huTrxBL.createHUContextProcessorExecutor().call(this::createHU);
getView().addHUIdAndInvalidate(huId);
return MSG_OK;
}
private HuId createHU(@NonNull final IHUContext huContext)
{
final I_C_UOM productStockingUOM = productBL.getStockUOM(productId);
// final I_M_InOut referenceModel = getCustomerReturns(); // using customer returns just because we need to use a referenced model
final I_AD_PInstance referencedModel = Services.get(IADPInstanceDAO.class).getById(getPinstanceId());
final IHUProducerAllocationDestination destination;
HULoader.builder()
.source(new GenericAllocationSourceDestination(
new PlainProductStorage(productId, Quantity.of(1, productStockingUOM)),
referencedModel
))
.destination(destination = HUProducerDestination.ofVirtualPI()
.setHUStatus(X_M_HU.HUSTATUS_Shipped)
.setBPartnerId(customerId)
.setLocatorId(getLocatorId()))
.load(AllocationUtils.builder()
.setHUContext(huContext)
.setProduct(productId)
.setQuantity(Quantity.of(1, productStockingUOM))
.setDate(SystemTime.asZonedDateTime())
.setForceQtyAllocation(true)
.setFromReferencedModel(referencedModel)
.create());
final I_M_HU vhu = destination.getSingleCreatedHU()
.orElseThrow(() -> new AdempiereException("No HU created"));
final IAttributeStorage vhuAttributes = huContext.getHUAttributeStorageFactory()
.getAttributeStorage(vhu);
vhuAttributes.setValue(AttributeConstants.ATTR_SerialNo, serialNo);
if (vhuAttributes.hasAttribute(AttributeConstants.WarrantyStartDate))
{
vhuAttributes.setValue(AttributeConstants.WarrantyStartDate, warrantyStartDate);
}
vhuAttributes.saveChangesIfNeeded();
return HuId.ofRepoId(vhu.getM_HU_ID());
} | private LocatorId getLocatorId()
{
final I_M_InOut customerReturns = getCustomerReturns();
final WarehouseId warehouseId = WarehouseId.ofRepoId(customerReturns.getM_Warehouse_ID());
return warehouseBL.getOrCreateDefaultLocatorId(warehouseId);
}
private I_M_InOut getCustomerReturns()
{
I_M_InOut customerReturns = this._customerReturns;
if (customerReturns == null)
{
final HUsToReturnViewContext husToReturnViewContext = getHUsToReturnViewContext();
final InOutId customerReturnsId = husToReturnViewContext.getCustomerReturnsId();
customerReturns = this._customerReturns = inoutBL.getById(customerReturnsId);
}
return customerReturns;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\HUsToReturn_CreateShippedHU.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DatasourceConfig {
@Bean
public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) {
ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl());
Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);
if ( !StringUtil.isNullOrEmpty(properties.getUser())) {
ob = ob.option(USER, properties.getUser());
}
if ( !StringUtil.isNullOrEmpty(properties.getPassword())) {
ob = ob.option(PASSWORD, properties.getPassword());
}
return ConnectionFactories.get(ob.build());
}
@Bean
public CommandLineRunner initDatabase(ConnectionFactory cf) {
return (args) ->
Flux.from(cf.create())
.flatMap(c ->
Flux.from(c.createBatch()
.add("drop table if exists Account")
.add("create table Account(" +
"id IDENTITY(1,1)," + | "iban varchar(80) not null," +
"balance DECIMAL(18,2) not null)")
.add("insert into Account(iban,balance)" +
"values('BR430120980198201982',100.00)")
.add("insert into Account(iban,balance)" +
"values('BR430120998729871000',250.00)")
.execute())
.doFinally((st) -> c.close())
)
.log()
.blockLast();
}
} | repos\tutorials-master\persistence-modules\r2dbc\src\main\java\com\baeldung\examples\r2dbc\DatasourceConfig.java | 2 |
请完成以下Java代码 | public void exportToExternalSystemIfRequired(
@NonNull final TableRecordReference recordToExportReference,
@Nullable final Supplier<Optional<Set<IExternalSystemChildConfigId>>> additionalExternalSystemIdsProvider)
{
final ImmutableSet.Builder<IExternalSystemChildConfigId> externalSysChildConfigCollector = ImmutableSet.builder();
externalSysChildConfigCollector.addAll(getExternalSysConfigIdsFromExportAudit(recordToExportReference));
if (additionalExternalSystemIdsProvider != null)
{
additionalExternalSystemIdsProvider.get().ifPresent(externalSysChildConfigCollector::addAll);
}
externalSysChildConfigCollector.build().forEach(id -> exportToExternalSystem(id, recordToExportReference, null));
}
@NonNull
protected ImmutableSet<IExternalSystemChildConfigId> getExternalSysConfigIdsFromExportAudit(@NonNull final TableRecordReference tableRecordReference)
{
final Optional<DataExportAudit> dataExportAudit = dataExportAuditRepository.getByTableRecordReference(tableRecordReference);
if (!dataExportAudit.isPresent())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("No dataExportAudit found for tableRecordReference: {}! No action is performed!", tableRecordReference);
return ImmutableSet.of();
}
final DataExportAuditId dataExportAuditId = dataExportAudit.get().getId();
final ImmutableSet<IExternalSystemChildConfigId> externalSystemConfigIds = getExternalSystemConfigsToSyncWith(dataExportAuditId);
if (externalSystemConfigIds.isEmpty())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("No externalSystemConfigIds found for DataExportAuditId: {}! No action is performed!", dataExportAuditId);
}
return externalSystemConfigIds;
}
@NonNull
private ImmutableSet<IExternalSystemChildConfigId> getExternalSystemConfigsToSyncWith(@NonNull final DataExportAuditId dataExportAuditId)
{
return dataExportAuditLogRepository.getExternalSystemConfigIds(dataExportAuditId) | .stream()
.map(id -> externalSystemConfigRepo.getChildByParentIdAndType(ExternalSystemParentConfigId.ofRepoId(id), getExternalSystemType()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(IExternalSystemChildConfig::getId)
.collect(ImmutableSet.toImmutableSet());
}
protected abstract ExternalSystemType getExternalSystemType();
protected abstract Optional<JsonExternalSystemRequest> getExportExternalSystemRequest(
IExternalSystemChildConfigId externalSystemChildConfigId,
TableRecordReference recordReference,
PInstanceId pInstanceId);
protected abstract void runPreExportHook(TableRecordReference recordReferenceToExport);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\export\ExportToExternalSystemService.java | 1 |
请完成以下Java代码 | public String getCanonicalName() {
return "activity-init-stack-notify-listener-return";
}
protected ScopeImpl getScope(PvmExecutionImpl execution) {
ActivityImpl activity = execution.getActivity();
if (activity!=null) {
return activity;
} else {
PvmExecutionImpl parent = execution.getParent();
if (parent != null) {
return getScope(execution.getParent());
}
return execution.getProcessDefinition();
}
}
protected String getEventName() {
return ExecutionListener.EVENTNAME_START;
} | protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
super.eventNotificationsCompleted(execution);
ScopeInstantiationContext startContext = execution.getScopeInstantiationContext();
InstantiationStack instantiationStack = startContext.getInstantiationStack();
// if the stack has been instantiated
if (instantiationStack.getActivities().isEmpty()) {
// done
execution.disposeScopeInstantiationContext();
return;
}
else {
// else instantiate the activity stack further
execution.setActivity(null);
execution.performOperation(ACTIVITY_INIT_STACK_AND_RETURN);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInitStackNotifyListenerReturn.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JAXBElement<DQVAR1> createDQVAR1(DQVAR1 value) {
return new JAXBElement<DQVAR1>(_DQVAR1_QNAME, DQVAR1 .class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link TRAILR }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link TRAILR }{@code >}
*/
@XmlElementDecl(namespace = "", name = "TRAILR")
public JAXBElement<TRAILR> createTRAILR(TRAILR value) {
return new JAXBElement<TRAILR>(_TRAILR_QNAME, TRAILR.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link TAMOU1 }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link TAMOU1 }{@code >}
*/
@XmlElementDecl(namespace = "", name = "TAMOU1")
public JAXBElement<TAMOU1> createTAMOU1(TAMOU1 value) {
return new JAXBElement<TAMOU1>(_TAMOU1_QNAME, TAMOU1 .class, null, value);
} | /**
* Create an instance of {@link JAXBElement }{@code <}{@link TTAXI1 }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link TTAXI1 }{@code >}
*/
@XmlElementDecl(namespace = "", name = "TTAXI1")
public JAXBElement<TTAXI1> createTTAXI1(TTAXI1 value) {
return new JAXBElement<TTAXI1>(_TTAXI1_QNAME, TTAXI1 .class, null, value);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\ObjectFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class StoreOrdersResponseType {
protected byte[] parcellabelsPDF;
protected List<ShipmentResponse> shipmentResponses;
/**
* Gets the value of the parcellabelsPDF property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getParcellabelsPDF() {
return parcellabelsPDF;
}
/**
* Sets the value of the parcellabelsPDF property.
*
* @param value
* allowed object is
* byte[]
*/
public void setParcellabelsPDF(byte[] value) {
this.parcellabelsPDF = value;
}
/**
* Gets the value of the shipmentResponses 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 shipmentResponses property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getShipmentResponses().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ShipmentResponse }
*
*
*/
public List<ShipmentResponse> getShipmentResponses() {
if (shipmentResponses == null) {
shipmentResponses = new ArrayList<ShipmentResponse>();
}
return this.shipmentResponses;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\StoreOrdersResponseType.java | 2 |
请完成以下Java代码 | public class BindingImpl extends DmnModelElementInstanceImpl implements Binding {
protected static ChildElement<Parameter> parameterChild;
protected static ChildElement<Expression> expressionChild;
public BindingImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Parameter getParameter() {
return parameterChild.getChild(this);
}
public void setParameter(Parameter parameter) {
parameterChild.setChild(this, parameter);
}
public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
} | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Binding.class, DMN_ELEMENT_BINDING)
.namespaceUri(LATEST_DMN_NS)
.instanceProvider(new ModelTypeInstanceProvider<Binding>() {
public Binding newInstance(ModelTypeInstanceContext instanceContext) {
return new BindingImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterChild = sequenceBuilder.element(Parameter.class)
.required()
.build();
expressionChild = sequenceBuilder.element(Expression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\BindingImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.