instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public ManualActivationRule getManualActivationRule() {
return manualActivationRuleChild.getChild(this);
}
public void setManualActivationRule(ManualActivationRule manualActivationRule) {
manualActivationRuleChild.setChild(this, manualActivationRule);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemControl.class, CMMN_ELEMENT_PLAN_ITEM_CONTROL)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemControl>() {
public PlanItemControl newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanItemControlImpl(instanceContext);
}
}); | SequenceBuilder sequenceBuilder = typeBuilder.sequence();
repetitionRuleChild = sequenceBuilder.element(RepetitionRule.class)
.build();
requiredRuleChild = sequenceBuilder.element(RequiredRule.class)
.build();
manualActivationRuleChild = sequenceBuilder.element(ManualActivationRule.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemControlImpl.java | 1 |
请完成以下Java代码 | public String getTrxName()
{
return trxName;
}
@Override
public boolean isPrinted(@NonNull final I_C_Printing_Queue item)
{
if (persistPrintedFlag)
{
return super.isPrinted(item);
}
else
{
return temporaryPrinted; | }
}
@Override
public void markPrinted(@NonNull final I_C_Printing_Queue item)
{
if (persistPrintedFlag)
{
super.markPrinted(item);
}
else
{
temporaryPrinted = true;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\SingletonPrintingQueueSource.java | 1 |
请完成以下Java代码 | private BigDecimal computeConvertedAmt()
{
return Services.get(ICurrencyBL.class).convert(
getOpenAmt(),
CurrencyId.ofRepoId(getC_CurrencyFrom_ID()),
CurrencyId.ofRepoId(getC_CurrencyTo_ID()),
ClientId.ofRepoId(getAD_Client_ID()),
OrgId.ofRepoId(getAD_Org_ID()));
}
/**
* After Save
*
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
updateEntry();
return success;
} // afterSave
/**
* After Delete
*
* @param success success
* @return success | */
@Override
protected boolean afterDelete(boolean success)
{
updateEntry();
return success;
} // afterDelete
/**
* Update Entry.
* Calculate/update Amt/Qty
*/
private void updateEntry()
{
// we do not count the fee line as an item, but it sum it up.
String sql = "UPDATE C_DunningRunEntry e "
+ "SET Amt=COALESCE((SELECT SUM(ConvertedAmt)+SUM(FeeAmt)+SUM(InterestAmt)"
+ " FROM C_DunningRunLine l "
+ "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID), 0), "
+ "QTY=(SELECT COUNT(*)"
+ " FROM C_DunningRunLine l "
+ "WHERE e.C_DunningRunEntry_ID=l.C_DunningRunEntry_ID "
+ " AND (NOT C_Invoice_ID IS NULL OR NOT C_Payment_ID IS NULL))"
+ " WHERE C_DunningRunEntry_ID=" + getC_DunningRunEntry_ID();
DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
} // updateEntry
} // MDunningRunLine | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDunningRunLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProcessingIndicator() {
return processingIndicator;
}
/**
* Sets the value of the processingIndicator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProcessingIndicator(String value) {
this.processingIndicator = value;
}
/**
* Gets the value of the criticalStockCode property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getCriticalStockCode() {
return criticalStockCode;
}
/**
* Sets the value of the criticalStockCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCriticalStockCode(String value) {
this.criticalStockCode = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\IndicatorsType.java | 2 |
请完成以下Java代码 | public byte[] encrypt(byte[] byteArray) {
return encrypt(byteArray, this.publicKey, this.algorithm, this.salt, this.gcm);
}
@Override
public byte[] decrypt(byte[] encryptedByteArray) {
if (!canDecrypt()) {
throw new IllegalStateException("Encryptor is not configured for decryption");
}
return decrypt(encryptedByteArray, this.privateKey, this.algorithm, this.salt, this.gcm);
}
private static byte[] encrypt(byte[] text, PublicKey key, RsaAlgorithm alg, String salt, boolean gcm) {
byte[] random = KeyGenerators.secureRandom(16).generateKey();
BytesEncryptor aes = gcm ? Encryptors.stronger(new String(Hex.encode(random)), salt)
: Encryptors.standard(new String(Hex.encode(random)), salt);
try {
final Cipher cipher = Cipher.getInstance(alg.getJceName());
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] secret = cipher.doFinal(random);
ByteArrayOutputStream result = new ByteArrayOutputStream(text.length + 20);
writeInt(result, secret.length);
result.write(secret);
result.write(aes.encrypt(text));
return result.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot encrypt", ex);
}
}
private static void writeInt(ByteArrayOutputStream result, int length) throws IOException {
byte[] data = new byte[2];
data[0] = (byte) ((length >> 8) & 0xFF);
data[1] = (byte) (length & 0xFF);
result.write(data);
}
private static int readInt(ByteArrayInputStream result) throws IOException {
byte[] b = new byte[2];
result.read(b);
return ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);
}
private static byte[] decrypt(byte[] text, @Nullable PrivateKey key, RsaAlgorithm alg, String salt, boolean gcm) {
ByteArrayInputStream input = new ByteArrayInputStream(text);
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
int length = readInt(input);
byte[] random = new byte[length];
input.read(random);
final Cipher cipher = Cipher.getInstance(alg.getJceName()); | cipher.init(Cipher.DECRYPT_MODE, key);
String secret = new String(Hex.encode(cipher.doFinal(random)));
byte[] buffer = new byte[text.length - random.length - 2];
input.read(buffer);
BytesEncryptor aes = gcm ? Encryptors.stronger(secret, salt) : Encryptors.standard(secret, salt);
output.write(aes.decrypt(buffer));
return output.toByteArray();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot decrypt", ex);
}
}
private static boolean isHex(String input) {
try {
Hex.decode(input);
return true;
}
catch (Exception ex) {
return false;
}
}
public boolean canDecrypt() {
return this.privateKey != null;
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaSecretEncryptor.java | 1 |
请完成以下Java代码 | public boolean pushCurrentValueFromMdc() {
if (isNotBlank(mdcName)) {
String mdcValue = MdcAccess.get(mdcName);
deque.addFirst(mdcValue != null ? mdcValue : NULL_VALUE);
return true;
} else {
return false;
}
}
public void removeCurrentValue() {
deque.removeFirst();
updateMdcWithCurrentValue();
}
public void clearMdcProperty() {
if (isNotBlank(mdcName)) {
MdcAccess.remove(mdcName);
}
}
public void updateMdcWithCurrentValue() {
if (isNotBlank(mdcName)) {
String currentValue = getCurrentValue();
if (isNull(currentValue)) {
MdcAccess.remove(mdcName);
} else {
MdcAccess.put(mdcName, currentValue);
}
}
}
}
protected static class ProcessDataSections {
/**
* Keeps track of when we added values to which stack (as we do not add
* a new value to every stack with every update, but only changed values)
*/
protected Deque<List<ProcessDataStack>> sections = new ArrayDeque<>();
protected boolean currentSectionSealed = true;
/**
* Adds a stack to the current section. If the current section is already sealed,
* a new section is created.
*/
public void addToCurrentSection(ProcessDataStack stack) { | List<ProcessDataStack> currentSection;
if (currentSectionSealed) {
currentSection = new ArrayList<>();
sections.addFirst(currentSection);
currentSectionSealed = false;
} else {
currentSection = sections.peekFirst();
}
currentSection.add(stack);
}
/**
* Pops the current section and removes the
* current values from the referenced stacks (including updates
* to the MDC)
*/
public void popCurrentSection() {
List<ProcessDataStack> section = sections.pollFirst();
if (section != null) {
section.forEach(ProcessDataStack::removeCurrentValue);
}
currentSectionSealed = true;
}
/**
* After a section is sealed, a new section will be created
* with the next call to {@link #addToCurrentSection(ProcessDataStack)}
*/
public void sealCurrentSection() {
currentSectionSealed = true;
}
public int size() {
return sections.size();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\ProcessDataContext.java | 1 |
请完成以下Java代码 | public void setProduct_id(Long product_id) {
this.product_id = product_id;
}
public ResultDTO(Long customer_id, Long order_id, Long product_id, String customerName, String customerEmail, LocalDate orderDate, String productName, Double productPrice) {
this.customer_id = customer_id;
this.order_id = order_id;
this.product_id = product_id;
this.customerName = customerName;
this.customerEmail = customerEmail;
this.orderDate = orderDate;
this.productName = productName;
this.productPrice = productPrice;
}
private String customerName;
private String customerEmail;
private LocalDate orderDate;
private String productName;
private Double productPrice;
public Long getCustomer_id() {
return customer_id;
}
public void setCustoemr_id(Long custoemr_id) {
this.customer_id = custoemr_id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public Long getOrder_id() {
return order_id;
} | public void setOrder_id(Long order_id) {
this.order_id = order_id;
}
public LocalDate getOrderDate() {
return orderDate;
}
public void setOrderDate(LocalDate orderDate) {
this.orderDate = orderDate;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getProductPrice() {
return productPrice;
}
public void setProductPrice(Double productPrice) {
this.productPrice = productPrice;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO.java | 1 |
请完成以下Java代码 | protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected DmnEngineConfiguration getDmnEngineConfiguration() {
return dmnEngineConfiguration;
}
protected DmnDeploymentEntityManager getDeploymentEntityManager() {
return getDmnEngineConfiguration().getDeploymentEntityManager(); | }
protected DecisionEntityManager getDecisionTableEntityManager() {
return getDmnEngineConfiguration().getDecisionEntityManager();
}
protected HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager() {
return getDmnEngineConfiguration().getHistoricDecisionExecutionEntityManager();
}
protected DmnResourceEntityManager getResourceEntityManager() {
return getDmnEngineConfiguration().getResourceEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public boolean isSOTrx()
{
final I_C_Order order = getOrder();
return order.isSOTrx();
}
@Override
public I_C_Country getC_Country()
{
final I_C_Order order = getOrder();
final BPartnerLocationAndCaptureId bpLocationId = OrderDocumentLocationAdapterFactory
.locationAdapter(order)
.getBPartnerLocationAndCaptureIdIfExists()
.orElse(null);
if (bpLocationId == null)
{
return null; | }
final CountryId countryId = Services.get(IBPartnerBL.class).getCountryId(bpLocationId);
return Services.get(ICountryDAO.class).getById(countryId);
}
private I_C_Order getOrder()
{
final I_C_Order order = orderLine.getC_Order();
if (order == null)
{
throw new AdempiereException("Order not set for" + orderLine);
}
return order;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\OrderLineCountryAware.java | 1 |
请完成以下Java代码 | public PrintService getPrintService()
{
return printService;
}
public void setPrintService(final PrintService printService)
{
this.printService = printService;
}
public PrintPackage getPrintPackage()
{
return printPackage;
}
public PrintPackageInfo getPrintPackageInfo()
{
return printPackageInfo;
}
public PrintRequestAttributeSet getAttributes()
{
return attributes;
}
public String getPrintJobName()
{
return printJobName;
}
public void setPrintJobName(final String printJobName)
{
this.printJobName = printJobName;
} | public Printable getPrintable()
{
return printable;
}
public void setPrintable(final Printable printable)
{
this.printable = printable;
}
public int getNumPages()
{
return numPages;
}
public void setNumPages(final int numPages)
{
this.numPages = numPages;
}
@Override
public String toString()
{
return "PrintPackageRequest ["
+ "printPackage=" + printPackage
+ ", printPackageInfo=" + printPackageInfo
+ ", attributes=" + attributes
+ ", printService=" + printService
+ ", printJobName=" + printJobName
+ ", printable=" + printable
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintPackageRequest.java | 1 |
请完成以下Java代码 | public class StartSubProcessInstanceAfterContext extends AbstractStartProcessInstanceAfterContext {
protected ExecutionEntity callActivityExecution;
protected List<IOParameter> inParameters;
public StartSubProcessInstanceAfterContext() {
}
public StartSubProcessInstanceAfterContext(ExecutionEntity processInstance, ExecutionEntity childExecution, Map<String, Object> variables,
Map<String, Object> transientVariables, ExecutionEntity callActivityExecution, List<IOParameter> inParameters,
FlowElement initialFlowElement, Process process, ProcessDefinition processDefinition) {
super(processInstance, childExecution, variables, transientVariables, initialFlowElement, process, processDefinition);
this.callActivityExecution = callActivityExecution;
this.inParameters = inParameters;
} | public ExecutionEntity getCallActivityExecution() {
return callActivityExecution;
}
public void setCallActivityExecution(ExecutionEntity callActivityExecution) {
this.callActivityExecution = callActivityExecution;
}
public List<IOParameter> getInParameters() {
return inParameters;
}
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\StartSubProcessInstanceAfterContext.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final List<I_MD_Stock_From_HUs_V> huBasedDataRecords = retrieveHuData();
addLog("Retrieved {} MD_Stock_From_HUs_V records", huBasedDataRecords.size());
createAndHandleDataUpdateRequests(huBasedDataRecords);
addLog("Created and handled DataUpdateRequests for all MD_Stock_From_HUs_V records");
return MSG_OK;
}
private List<I_MD_Stock_From_HUs_V> retrieveHuData()
{
addLog("Performing a select for Records to correct on MD_Stock_From_HUs_V");
return queryBL
.createQueryBuilder(I_MD_Stock_From_HUs_V.class)
.addNotEqualsFilter(I_MD_Stock_From_HUs_V.COLUMNNAME_QtyOnHandChange, ZERO)
.create()
.list();
}
private void createAndHandleDataUpdateRequests(
@NonNull final List<I_MD_Stock_From_HUs_V> huBasedDataRecords)
{
final ResetStockPInstanceId resetStockPInstanceId = ResetStockPInstanceId.ofPInstanceId(getProcessInfo().getPinstanceId());
final StockChangeSourceInfo info = StockChangeSourceInfo.ofResetStockPInstanceId(resetStockPInstanceId);
for (final I_MD_Stock_From_HUs_V huBasedDataRecord : huBasedDataRecords)
{
final StockDataUpdateRequest dataUpdateRequest = createDataUpdatedRequest(
huBasedDataRecord,
info);
addLog("Handling corrective dataUpdateRequest={}", dataUpdateRequest);
dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest); | }
}
private StockDataUpdateRequest createDataUpdatedRequest(
@NonNull final I_MD_Stock_From_HUs_V huBasedDataRecord,
@NonNull final StockChangeSourceInfo stockDataUpdateRequestSourceInfo)
{
final StockDataRecordIdentifier recordIdentifier = toStockDataRecordIdentifier(huBasedDataRecord);
final ProductId productId = ProductId.ofRepoId(huBasedDataRecord.getM_Product_ID());
final Quantity qtyInStorageUOM = Quantitys.of(huBasedDataRecord.getQtyOnHandChange(), UomId.ofRepoId(huBasedDataRecord.getC_UOM_ID()));
final Quantity qtyInProductUOM = uomConversionBL.convertToProductUOM(qtyInStorageUOM, productId);
return StockDataUpdateRequest.builder()
.identifier(recordIdentifier)
.onHandQtyChange(qtyInProductUOM.toBigDecimal())
.sourceInfo(stockDataUpdateRequestSourceInfo)
.build();
}
private static StockDataRecordIdentifier toStockDataRecordIdentifier(@NonNull final I_MD_Stock_From_HUs_V huBasedDataRecord)
{
return StockDataRecordIdentifier.builder()
.clientId(ClientId.ofRepoId(huBasedDataRecord.getAD_Client_ID()))
.orgId(OrgId.ofRepoId(huBasedDataRecord.getAD_Org_ID()))
.warehouseId(WarehouseId.ofRepoId(huBasedDataRecord.getM_Warehouse_ID()))
.productId(ProductId.ofRepoId(huBasedDataRecord.getM_Product_ID()))
.storageAttributesKey(AttributesKey.ofString(huBasedDataRecord.getAttributesKey()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\process\MD_Stock_Update_From_M_HUs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void resumeJob(JobForm form) throws SchedulerException {
scheduler.resumeJob(JobKey.jobKey(form.getJobClassName(), form.getJobGroupName()));
}
/**
* 重新配置定时任务
*
* @param form 表单参数 {@link JobForm}
* @throws Exception 异常
*/
@Override
public void cronJob(JobForm form) throws Exception {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName());
// 表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(form.getCronExpression());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
// 根据Cron表达式构建一个Trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
// 按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
} catch (SchedulerException e) {
log.error("【定时任务】更新失败!", e); | throw new Exception("【定时任务】创建失败!");
}
}
/**
* 查询定时任务列表
*
* @param currentPage 当前页
* @param pageSize 每页条数
* @return 定时任务列表
*/
@Override
public PageInfo<JobAndTrigger> list(Integer currentPage, Integer pageSize) {
PageHelper.startPage(currentPage, pageSize);
List<JobAndTrigger> list = jobMapper.list();
return new PageInfo<>(list);
}
} | repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\service\impl\JobServiceImpl.java | 2 |
请完成以下Java代码 | public class CaseXmlConverter extends BaseCmmnXmlConverter {
@Override
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_CASE;
}
@Override
public boolean hasChildElements() {
return true;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
Case caze = new Case();
caze.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
caze.setInitiatorVariableName(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_INITIATOR_VARIABLE_NAME));
String candidateUsersString = CmmnXmlUtil.getAttributeValue(CmmnXmlConstants.ATTRIBUTE_CASE_CANDIDATE_USERS, xtr);
if (StringUtils.isNotEmpty(candidateUsersString)) {
List<String> candidateUsers = CmmnXmlUtil.parseDelimitedList(candidateUsersString);
caze.setCandidateStarterUsers(candidateUsers);
}
String candidateGroupsString = CmmnXmlUtil.getAttributeValue(CmmnXmlConstants.ATTRIBUTE_CASE_CANDIDATE_GROUPS, xtr); | if (StringUtils.isNotEmpty(candidateGroupsString)) {
List<String> candidateGroups = CmmnXmlUtil.parseDelimitedList(candidateGroupsString);
caze.setCandidateStarterGroups(candidateGroups);
}
if ("true".equals(xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE, CmmnXmlConstants.ATTRIBUTE_IS_ASYNCHRONOUS))) {
caze.setAsync(true);
}
conversionHelper.getCmmnModel().addCase(caze);
conversionHelper.setCurrentCase(caze);
return caze;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CaseXmlConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class UserValuePreferencesBuilder
{
public static Collector<I_AD_Preference, ?, ImmutableMap<Optional<AdWindowId>, IUserValuePreferences>> byWindowIdCollector()
{
return Collectors.collectingAndThen(
Collectors.groupingBy((I_AD_Preference adPreference) -> extractAdWindowId(adPreference), collector()) // downstream collector: AD_Window_ID->IUserValuePreferences
, ImmutableMap::copyOf // finisher
);
}
public static Collector<I_AD_Preference, UserValuePreferencesBuilder, IUserValuePreferences> collector()
{
return Collector.of(
UserValuePreferencesBuilder::new // supplier
, UserValuePreferencesBuilder::add // accumulator
, (l, r) -> l.addAll(r) // combiner
, UserValuePreferencesBuilder::build // finisher
, Collector.Characteristics.UNORDERED // characteristics
);
}
private static Optional<AdWindowId> extractAdWindowId(final I_AD_Preference adPreference)
{
return AdWindowId.optionalOfRepoId(adPreference.getAD_Window_ID());
}
private Optional<AdWindowId> adWindowIdOptional;
private final Map<String, IUserValuePreference> name2value = new HashMap<>();
private UserValuePreferencesBuilder()
{
super();
}
public UserValuePreferences build()
{
if (isEmpty())
{
return UserValuePreferences.EMPTY;
}
return new UserValuePreferences(this);
}
public boolean isEmpty() | {
return name2value.isEmpty();
}
public UserValuePreferencesBuilder add(final I_AD_Preference adPreference)
{
final Optional<AdWindowId> currentWindowId = extractAdWindowId(adPreference);
if (isEmpty())
{
adWindowIdOptional = currentWindowId;
}
else if (!adWindowIdOptional.equals(currentWindowId))
{
throw new IllegalArgumentException("Preference " + adPreference + "'s AD_Window_ID=" + currentWindowId + " is not matching builder's AD_Window_ID=" + adWindowIdOptional);
}
final String attributeName = adPreference.getAttribute();
final String attributeValue = adPreference.getValue();
name2value.put(attributeName, UserValuePreference.of(adWindowIdOptional, attributeName, attributeValue));
return this;
}
public UserValuePreferencesBuilder addAll(final UserValuePreferencesBuilder fromBuilder)
{
if (fromBuilder == null || fromBuilder.isEmpty())
{
return this;
}
if (!isEmpty() && !adWindowIdOptional.equals(fromBuilder.adWindowIdOptional))
{
throw new IllegalArgumentException("Builder " + fromBuilder + "'s AD_Window_ID=" + fromBuilder.adWindowIdOptional + " is not matching builder's AD_Window_ID=" + adWindowIdOptional);
}
name2value.putAll(fromBuilder.name2value);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\ValuePreferenceBL.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SysAppVersionController{
@Autowired
private RedisUtil redisUtil;
/**
* APP缓存前缀
*/
private String APP3_VERSION = "app3:version";
/**
* app3版本信息
* @return
*/
@Operation(summary="app版本")
@GetMapping(value = "/app3version")
public Result<SysAppVersion> app3Version(@RequestParam(name="key", required = false)String appKey) throws Exception {
Object appConfig = redisUtil.get(APP3_VERSION + appKey);
if (oConvertUtils.isNotEmpty(appConfig)) {
try {
SysAppVersion sysAppVersion = (SysAppVersion)appConfig;
return Result.OK(sysAppVersion);
} catch (Exception e) {
log.error(e.toString(),e);
return Result.error("app版本信息获取失败:" + e.getMessage());
}
}
return Result.OK(); | }
/**
* 保存APP3
*
* @param sysAppVersion
* @return
*/
@RequiresRoles({"admin"})
@Operation(summary="app系统配置-保存")
@PostMapping(value = "/saveVersion")
public Result<?> saveVersion(@RequestBody SysAppVersion sysAppVersion) {
String id = sysAppVersion.getId();
redisUtil.set(APP3_VERSION + id,sysAppVersion);
return Result.OK();
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysAppVersionController.java | 2 |
请完成以下Java代码 | public Timestamp getEndDate()
{
return m_EndDate;
}
/**
* Get Start Date
* @return start date
*/
public Timestamp getStartDate()
{
return m_StartDate;
}
/**
* Get Year Start Date
* @return year start date
*/
public Timestamp getYearStartDate()
{ | return m_YearStartDate;
}
/**
* Get natural balance dateacct filter
* @param alias table name or alias name
* @return is balance sheet a/c and <= end or BETWEEN start AND end
*/
public String getNaturalWhere(String alias) {
String yearWhere = getYearWhere();
String totalWhere = getTotalWhere();
String bs = " EXISTS (SELECT C_ElementValue_ID FROM C_ElementValue WHERE C_ElementValue_ID = " + alias + ".Account_ID AND AccountType NOT IN ('R', 'E'))";
String full = totalWhere + " AND ( " + bs + " OR TRUNC(" + alias + ".DateAcct) " + yearWhere + " ) ";
return full;
}
} // FinReportPeriod | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\report\FinReportPeriod.java | 1 |
请完成以下Java代码 | public final class OAuth2ProtectedResourceMetadataClaimNames {
/**
* {@code resource} - the {@code URL} the protected resource asserts as its resource
* identifier
*/
public static final String RESOURCE = "resource";
/**
* {@code authorization_servers} - a list of {@code issuer} identifier {@code URL}'s,
* for authorization servers that can be used with this protected resource
*/
public static final String AUTHORIZATION_SERVERS = "authorization_servers";
/**
* {@code scopes_supported} - a list of {@code scope} values supported, that are used
* in authorization requests to request access to this protected resource
*/
public static final String SCOPES_SUPPORTED = "scopes_supported";
/**
* {@code bearer_methods_supported} - a list of the supported methods for sending an
* OAuth 2.0 bearer token to the protected resource. Defined values are "header",
* "body" and "query".
*/
public static final String BEARER_METHODS_SUPPORTED = "bearer_methods_supported"; | /**
* {@code resource_name} - the name of the protected resource intended for display to
* the end user
*/
public static final String RESOURCE_NAME = "resource_name";
/**
* {@code tls_client_certificate_bound_access_tokens} - {@code true} to indicate
* protected resource support for mutual-TLS client certificate-bound access tokens
*/
public static final String TLS_CLIENT_CERTIFICATE_BOUND_ACCESS_TOKENS = "tls_client_certificate_bound_access_tokens";
private OAuth2ProtectedResourceMetadataClaimNames() {
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\OAuth2ProtectedResourceMetadataClaimNames.java | 1 |
请完成以下Java代码 | public Collection<ModelElementType> getTypes() {
return new ArrayList<ModelElementType>(typesByName.values());
}
public ModelElementType getType(Class<? extends ModelElementInstance> instanceClass) {
return typesByClass.get(instanceClass);
}
public ModelElementType getTypeForName(String typeName) {
return getTypeForName(null, typeName);
}
public ModelElementType getTypeForName(String namespaceUri, String typeName) {
return typesByName.get(ModelUtil.getQName(namespaceUri, typeName));
}
/**
* Registers a {@link ModelElementType} in this {@link Model}.
*
* @param modelElementType the element type to register
* @param instanceType the instance class of the type to register
*/
public void registerType(ModelElementType modelElementType, Class<? extends ModelElementInstance> instanceType) {
QName qName = ModelUtil.getQName(modelElementType.getTypeNamespace(), modelElementType.getTypeName());
typesByName.put(qName, modelElementType);
typesByClass.put(instanceType, modelElementType);
}
public String getModelName() {
return modelName;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((modelName == null) ? 0 : modelName.hashCode());
return result;
}
@Override | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ModelImpl other = (ModelImpl) obj;
if (modelName == null) {
if (other.modelName != null) {
return false;
}
} else if (!modelName.equals(other.modelName)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelImpl.java | 1 |
请完成以下Java代码 | public Object getCredentials() {
return "";
}
@Override
public Object getPrincipal() {
return principalName;
}
};
}
/**
* Sets the {@code Principal} (to be) associated to the authorized client.
* @param principal the {@code Principal} (to be) associated to the authorized
* client
* @return the {@link Builder}
*/
public Builder principal(Authentication principal) {
this.principal = principal;
return this;
}
/**
* Provides a {@link Consumer} access to the attributes associated to the request.
* @param attributesConsumer a {@link Consumer} of the attributes associated to
* the request
* @return the {@link Builder}
*/
public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
attributesConsumer.accept(this.attributes);
return this;
}
/**
* Sets an attribute associated to the request.
* @param name the name of the attribute
* @param value the value of the attribute
* @return the {@link Builder} | */
public Builder attribute(String name, Object value) {
if (this.attributes == null) {
this.attributes = new HashMap<>();
}
this.attributes.put(name, value);
return this;
}
/**
* Builds a new {@link OAuth2AuthorizeRequest}.
* @return a {@link OAuth2AuthorizeRequest}
*/
public OAuth2AuthorizeRequest build() {
Assert.notNull(this.principal, "principal cannot be null");
OAuth2AuthorizeRequest authorizeRequest = new OAuth2AuthorizeRequest();
if (this.authorizedClient != null) {
authorizeRequest.clientRegistrationId = this.authorizedClient.getClientRegistration()
.getRegistrationId();
authorizeRequest.authorizedClient = this.authorizedClient;
}
else {
authorizeRequest.clientRegistrationId = this.clientRegistrationId;
}
authorizeRequest.principal = this.principal;
authorizeRequest.attributes = Collections.unmodifiableMap(CollectionUtils.isEmpty(this.attributes)
? Collections.emptyMap() : new LinkedHashMap<>(this.attributes));
return authorizeRequest;
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\OAuth2AuthorizeRequest.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
} | public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
} | repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\quarkus-project\src\main\java\com\baeldung\quarkus_project\ZipCode.java | 1 |
请完成以下Java代码 | public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true; | }
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootEnableLazyLoadNoTrans\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderEntryPK pk = (OrderEntryPK) o;
return Objects.equals(orderId, pk.orderId) && Objects.equals(productId, pk.productId);
}
@Override
public int hashCode() {
return Objects.hash(orderId, productId);
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\pojo\OrderEntryPK.java | 1 |
请完成以下Java代码 | public CallActivity clone() {
CallActivity clone = new CallActivity();
clone.setValues(this);
return clone;
}
public void setValues(CallActivity otherElement) {
super.setValues(otherElement);
setCalledElement(otherElement.getCalledElement());
setCalledElementType(otherElement.getCalledElementType());
setBusinessKey(otherElement.getBusinessKey());
setInheritBusinessKey(otherElement.isInheritBusinessKey());
setInheritVariables(otherElement.isInheritVariables());
setSameDeployment(otherElement.isSameDeployment());
setUseLocalScopeForOutParameters(otherElement.isUseLocalScopeForOutParameters());
setCompleteAsync(otherElement.isCompleteAsync());
setFallbackToDefaultTenant(otherElement.getFallbackToDefaultTenant());
inParameters = new ArrayList<>(); | if (otherElement.getInParameters() != null && !otherElement.getInParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getInParameters()) {
inParameters.add(parameter.clone());
}
}
outParameters = new ArrayList<>();
if (otherElement.getOutParameters() != null && !otherElement.getOutParameters().isEmpty()) {
for (IOParameter parameter : otherElement.getOutParameters()) {
outParameters.add(parameter.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\CallActivity.java | 1 |
请完成以下Java代码 | public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
}
public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
public PizzaStatusEnum getStatus() {
return status;
}
public void setStatus(PizzaStatusEnum status) {
this.status = status;
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days"); | }
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
}
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatusEnum.DELIVERED);
}
}
public int getDeliveryTimeInDays() {
switch (status) {
case ORDERED: return 5;
case READY: return 2;
case DELIVERED: return 0;
}
return 0;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\enums\Pizza.java | 1 |
请完成以下Java代码 | public CostAmount toZero()
{
if (isZero())
{
return this;
}
else
{
return new CostAmount(value.toZero(), sourceValue != null ? sourceValue.toZero() : null);
}
}
public Money toMoney()
{
return value;
}
@Nullable | public Money toSourceMoney()
{
return sourceValue;
}
public BigDecimal toBigDecimal() {return value.toBigDecimal();}
public boolean compareToEquals(@NonNull final CostAmount other)
{
return this.value.compareTo(other.value) == 0;
}
public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmount... costAmounts)
{
return CurrencyId.getCommonCurrencyIdOfAll(CostAmount::getCurrencyId, "Amount", costAmounts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmount.java | 1 |
请完成以下Java代码 | private void putBack(E value)
{
// shall not happen
if (hasNextValue)
{
throw new IllegalStateException("Only one value is allowed to be put back");
}
hasNextValue = true;
nextValue = value;
}
@Override
public Spliterator<List<E>> trySplit()
{
return null;
}
@Override
public long estimateSize()
{
return Long.MAX_VALUE;
}
@Override
public int characteristics()
{
return source.characteristics();
}
private static final class GroupCollector<E>
{
private final Object classifierValue; | private final ImmutableList.Builder<E> items = ImmutableList.builder();
public GroupCollector(final Object classifierValue)
{
this.classifierValue = classifierValue;
}
public boolean isMatchingClassifier(final Object classifierValueToMatch)
{
return Objects.equals(this.classifierValue, classifierValueToMatch);
}
public void collect(final E item)
{
items.add(item);
}
public List<E> finish()
{
return items.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GroupByClassifierSpliterator.java | 1 |
请完成以下Java代码 | public I_C_Currency getC_Currency() throws RuntimeException
{
return (I_C_Currency)MTable.get(getCtx(), I_C_Currency.Table_Name)
.getPO(getC_Currency_ID(), get_TrxName()); }
/** Set Currency.
@param C_Currency_ID
The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID));
}
/** Get Currency.
@return The Currency for this record
*/
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Project Cycle.
@param C_Cycle_ID
Identifier for this Project Reporting Cycle
*/
public void setC_Cycle_ID (int C_Cycle_ID)
{
if (C_Cycle_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, Integer.valueOf(C_Cycle_ID));
}
/** Get Project Cycle.
@return Identifier for this Project Reporting Cycle
*/
public int getC_Cycle_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription () | {
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cycle.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, ModuleConfig> getModules() {
return modules;
}
public void setModules(Map<String, ModuleConfig> modules) {
this.modules = modules;
}
public Map<String, RegistryConfig> getRegistries() {
return registries;
}
public void setRegistries(Map<String, RegistryConfig> registries) {
this.registries = registries;
}
public Map<String, ProtocolConfig> getProtocols() {
return protocols;
}
public void setProtocols(Map<String, ProtocolConfig> protocols) {
this.protocols = protocols;
}
public Map<String, MonitorConfig> getMonitors() {
return monitors;
}
public void setMonitors(Map<String, MonitorConfig> monitors) {
this.monitors = monitors;
}
public Map<String, ProviderConfig> getProviders() {
return providers;
}
public void setProviders(Map<String, ProviderConfig> providers) {
this.providers = providers;
}
public Map<String, ConsumerConfig> getConsumers() {
return consumers;
}
public void setConsumers(Map<String, ConsumerConfig> consumers) {
this.consumers = consumers;
}
public Map<String, ConfigCenterBean> getConfigCenters() {
return configCenters;
}
public void setConfigCenters(Map<String, ConfigCenterBean> configCenters) {
this.configCenters = configCenters;
}
public Map<String, MetadataReportConfig> getMetadataReports() {
return metadataReports;
}
public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) {
this.metadataReports = metadataReports; | }
static class Config {
/**
* Indicates multiple properties binding from externalized configuration or not.
*/
private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE;
/**
* The property name of override Dubbo config
*/
private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE;
public boolean isOverride() {
return override;
}
public void setOverride(boolean override) {
this.override = override;
}
public boolean isMultiple() {
return multiple;
}
public void setMultiple(boolean multiple) {
this.multiple = multiple;
}
}
static class Scan {
/**
* The basePackages to scan , the multiple-value is delimited by comma
*
* @see EnableDubbo#scanBasePackages()
*/
private Set<String> basePackages = new LinkedHashSet<>();
public Set<String> getBasePackages() {
return basePackages;
}
public void setBasePackages(Set<String> basePackages) {
this.basePackages = basePackages;
}
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboConfigurationProperties.java | 2 |
请完成以下Java代码 | public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
@Override
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricProcessInstanceEntity[id=").append(getId())
.append(", definition=").append(getProcessDefinitionId());
if (superProcessInstanceId != null) { | sb.append(", superProcessInstanceId=").append(superProcessInstanceId);
}
if (referenceId != null) {
sb.append(", referenceId=").append(referenceId)
.append(", referenceType=").append(referenceType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public void setRelation(User User, Long roleId, String fieldName) {
// not for many-to-many
}
@Override
public void setRelations(User user, Iterable<Long> roleIds, String fieldName) {
final Set<Role> roles = new HashSet<Role>();
roles.addAll(roleRepository.findAllById(roleIds));
user.setRoles(roles);
userRepository.save(user);
}
@Override
public void addRelations(User user, Iterable<Long> roleIds, String fieldName) {
final Set<Role> roles = user.getRoles();
roles.addAll(roleRepository.findAllById(roleIds));
user.setRoles(roles);
userRepository.save(user);
}
@Override
public void removeRelations(User user, Iterable<Long> roleIds, String fieldName) {
final Set<Role> roles = user.getRoles();
roles.removeAll(roleRepository.findAllById(roleIds));
user.setRoles(roles);
userRepository.save(user);
}
@Override
public Role findOneTarget(Long sourceId, String fieldName, QuerySpec querySpec) {
// not for many-to-many
return null;
} | @Override
public ResourceList<Role> findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) {
final Optional<User> userOptional = userRepository.findById(sourceId);
User user = userOptional.isPresent() ? userOptional.get() : new User();
return querySpec.apply(user.getRoles());
}
@Override
public Class<User> getSourceResourceClass() {
return User.class;
}
@Override
public Class<Role> getTargetResourceClass() {
return Role.class;
}
} | repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\katharsis\UserToRoleRelationshipRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InitializrWebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/info", "/actuator/info");
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentTypeStrategy(new CommandLineContentNegotiationStrategy());
}
/**
* A command-line aware {@link ContentNegotiationStrategy} that forces the media type
* to "text/plain" for compatible agents.
*/
private static final class CommandLineContentNegotiationStrategy implements ContentNegotiationStrategy {
private final UrlPathHelper urlPathHelper = new UrlPathHelper();
@Override
public List<MediaType> resolveMediaTypes(NativeWebRequest request) {
String path = this.urlPathHelper
.getPathWithinApplication(request.getNativeRequest(HttpServletRequest.class));
if (!StringUtils.hasText(path) || !path.equals("/")) { // Only care about "/"
return MEDIA_TYPE_ALL_LIST;
} | String userAgent = request.getHeader(HttpHeaders.USER_AGENT);
if (userAgent != null) {
Agent agent = Agent.fromUserAgent(userAgent);
if (agent != null) {
if (AgentId.CURL.equals(agent.getId()) || AgentId.HTTPIE.equals(agent.getId())) {
return Collections.singletonList(MediaType.TEXT_PLAIN);
}
}
}
return Collections.singletonList(MediaType.APPLICATION_JSON);
}
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\autoconfigure\InitializrWebConfig.java | 2 |
请完成以下Java代码 | public void setC_ScannableCode_Format_ID (final int C_ScannableCode_Format_ID)
{
if (C_ScannableCode_Format_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ScannableCode_Format_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ScannableCode_Format_ID, C_ScannableCode_Format_ID);
}
@Override
public int getC_ScannableCode_Format_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ScannableCode_Format_ID);
}
@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 setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ScannableCode_Format.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handleEvent(@NonNull final PPOrderCandidateCreatedEvent event)
{
handleMaterialDispoProductionDetail(event);
}
private void handleMaterialDispoProductionDetail(@NonNull final PPOrderCandidateCreatedEvent event)
{
final MaterialDispoGroupId groupId = event.getPpOrderCandidate().getPpOrderData().getMaterialDispoGroupId();
final SimulatedQueryQualifier simulatedQueryQualifier = event.getPpOrderCandidate().isSimulated()
? SimulatedQueryQualifier.ONLY_SIMULATED
: SimulatedQueryQualifier.EXCLUDE_SIMULATED;
final CandidatesQuery query = CandidatesQuery.builder()
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PRODUCTION) | .groupId(groupId)
.materialDescriptorQuery(PPOrderHandlerUtils.createMaterialDescriptorQuery(event.getPpOrderCandidate().getPpOrderData().getProductDescriptor()))
.simulatedQueryQualifier(simulatedQueryQualifier)
.build();
final Candidate headerCandidate = createHeaderCandidate(event, query);
createLineCandidates(event, groupId, headerCandidate);
}
@Override
protected boolean isMaterialTrackingDeferredForThisEventType()
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ppordercandidate\PPOrderCandidateCreatedEventHandler.java | 2 |
请完成以下Java代码 | public void error(int WIndowNo, String AD_Message)
{
logger.warn("" + AD_Message);
}
@Override
public void error(int WIndowNo, String AD_Message, String message)
{
logger.error("" + AD_Message + ": " + message);
}
@Override
public void download(byte[] data, String contentType, String filename)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void downloadNow(InputStream content, String contentType, String filename)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public String getClientInfo()
{
// implementation basically copied from SwingClientUI
final String javaVersion = System.getProperty("java.version");
return new StringBuilder("!! NO UI REGISTERED YET !!, java.version=").append(javaVersion).toString();
}
@Override
public void showWindow(Object model)
{
throw new UnsupportedOperationException("Not implemented: ClientUI.showWindow()");
} | @Override
public IClientUIInvoker invoke()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void showURL(String url)
{
System.err.println("Showing URL is not supported on server side: " + url);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\impl\ClientUI.java | 1 |
请完成以下Java代码 | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); | }
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Product.java | 1 |
请完成以下Java代码 | void contractExpectsWrongParameterType(List<Integer> integers) {
}
@Contract("_, _ -> new")
void contractExpectsMoreParametersThanMethodHas(String s) {
}
@Contract("_ -> _; null -> !null")
String secondContractClauseNotReachable(String s) {
return "";
}
@Contract("_ -> true")
void contractExpectsWrongReturnType(String s) {
}
// NB: the following examples demonstrate how to use the mutates attribute of the annotation
// This attribute is currently experimental and could be changed or removed in the future
@Contract(mutates = "param")
void incrementArrayFirstElement(Integer[] integers) {
if (integers.length > 0) {
integers[0] = integers[0] + 1;
}
} | @Contract(pure = true, mutates = "param")
void impossibleToMutateParamInPureFunction(List<String> strings) {
if (strings != null) {
strings.forEach(System.out::println);
}
}
@Contract(mutates = "param3")
void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) {
}
@Contract(mutates = "param")
void impossibleToMutableImmutableType(String s) {
}
@Contract(mutates = "this")
static void impossibleToMutateThisInStaticMethod() {
}
} | repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java | 1 |
请完成以下Java代码 | public void onError(Session session, Throwable t) {
log.warn("【系统 WebSocket】消息出现错误");
t.printStackTrace();
}
//==========【系统 WebSocket接受、推送消息等方法 —— 具体服务节点推送ws消息】========================================================================================
//==========【采用redis发布订阅模式——推送消息】========================================================================================
/**
* 后台发送消息到redis
*
* @param message
*/
public void sendMessage(String message) {
//log.debug("【系统 WebSocket】广播消息:" + message);
BaseMap baseMap = new BaseMap();
baseMap.put("userId", "");
baseMap.put("message", message);
jeecgRedisClient.sendMessage(WebSocket.REDIS_TOPIC_NAME, baseMap);
}
/**
* 此为单点消息 redis
* | * @param userId
* @param message
*/
public void sendMessage(String userId, String message) {
BaseMap baseMap = new BaseMap();
baseMap.put("userId", userId);
baseMap.put("message", message);
jeecgRedisClient.sendMessage(WebSocket.REDIS_TOPIC_NAME, baseMap);
}
/**
* 此为单点消息(多人) redis
*
* @param userIds
* @param message
*/
public void sendMessage(String[] userIds, String message) {
for (String userId : userIds) {
sendMessage(userId, message);
}
}
//=======【采用redis发布订阅模式——推送消息】==========================================================================================
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\websocket\WebSocket.java | 1 |
请完成以下Java代码 | public class M_HU_SyncTo_GRS_HTTP extends M_HU_SyncTo_ExternalSystem
{
private final ExportHUToGRSService exportHUToGRSService = SpringContextHolder.instance.getBean(ExportHUToGRSService.class);
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
private static final String PARAM_EXTERNAL_SYSTEM_CONFIG_GRSSIGNUM_ID = I_ExternalSystem_Config_GRSSignum.COLUMNNAME_ExternalSystem_Config_GRSSignum_ID;
@Param(parameterName = PARAM_EXTERNAL_SYSTEM_CONFIG_GRSSIGNUM_ID)
private int externalSystemConfigGRSSignumId;
@Override
protected ExternalSystemType getExternalSystemType()
{
return ExternalSystemType.GRSSignum;
}
@Override
protected Set<I_M_HU> getHUsToExport()
{
return streamSelectedRows()
.map(HUEditorRow::cast)
.filter(Objects::nonNull)
.map(HUEditorRow::getHuId)
.filter(Objects::nonNull)
.map(handlingUnitsBL::getTopLevelParent)
.collect(ImmutableSet.toImmutableSet()); | }
@Override
protected IExternalSystemChildConfigId getExternalSystemChildConfigId()
{
return ExternalSystemGRSSignumConfigId.ofRepoId(externalSystemConfigGRSSignumId);
}
@Override
protected String getExternalSystemParam()
{
return PARAM_EXTERNAL_SYSTEM_CONFIG_GRSSIGNUM_ID;
}
@Override
protected ExportHUToExternalSystemService getExportToHUExternalSystem()
{
return exportHUToGRSService;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\M_HU_SyncTo_GRS_HTTP.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public Integer getVersion() {
return version;
}
public Integer getVersionGt() {
return versionGt;
}
public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() {
return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getAuthorizationUserId() { | return authorizationUserId;
}
public boolean isAuthorizationGroupsSet() {
return authorizationGroupsSet;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public boolean isIncludeAuthorization() {
return authorizationUserId != null || (authorizationGroups != null && !authorizationGroups.isEmpty());
}
public List<List<String>> getSafeAuthorizationGroups() {
return safeAuthorizationGroups;
}
public void setSafeAuthorizationGroups(List<List<String>> safeAuthorizationGroups) {
this.safeAuthorizationGroups = safeAuthorizationGroups;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CaseDefinitionQueryImpl.java | 2 |
请完成以下Java代码 | public void propertyChange(PropertyChangeEvent evt)
{
log.info(evt.toString());
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
/**
* ActionListener - start dialog and set value
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
JFileChooser fc = new JFileChooser("");
fc.setMultiSelectionEnabled(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int option = 0;
boolean save = m_data != null;
if (save)
option = fc.showSaveDialog(this);
else
option = fc.showOpenDialog(this);
if (option != JFileChooser.APPROVE_OPTION)
return;
File file = fc.getSelectedFile();
if (file == null)
return;
//
log.info(file.toString());
try
{
if (save)
{
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = (byte[])m_data;
os.write(buffer);
os.flush();
os.close();
log.info("Save to " + file + " #" + buffer.length);
}
else // load
{
FileInputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*8]; // 8kB
int length = -1;
while ((length = is.read(buffer)) != -1)
os.write(buffer, 0, length);
is.close();
byte[] data = os.toByteArray();
m_data = data;
log.info("Load from " + file + " #" + data.length);
os.close();
}
} | catch (Exception ex)
{
log.warn("Save=" + save, ex);
}
try
{
fireVetoableChange(m_columnName, null, m_data);
}
catch (PropertyVetoException pve) {}
} // actionPerformed
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField
*/
public void setField (GridField mField)
{
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VBinary | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VBinary.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setHelperDialect(String helperDialect) {
setProperty("helperDialect", helperDialect);
}
public Boolean getAutoRuntimeDialect() {
return Boolean.valueOf(getProperty("autoRuntimeDialect"));
}
public void setAutoRuntimeDialect(Boolean autoRuntimeDialect) {
setProperty("autoRuntimeDialect", autoRuntimeDialect.toString());
}
public Boolean getAutoDialect() {
return Boolean.valueOf(getProperty("autoDialect"));
}
public void setAutoDialect(Boolean autoDialect) {
setProperty("autoDialect", autoDialect.toString());
}
public Boolean getCloseConn() {
return Boolean.valueOf(getProperty("closeConn"));
}
public void setCloseConn(Boolean closeConn) {
setProperty("closeConn", closeConn.toString());
}
public String getParams() {
return getProperty("params");
}
public void setParams(String params) {
setProperty("params", params);
}
public Boolean getDefaultCount() {
return Boolean.valueOf(getProperty("defaultCount"));
}
public void setDefaultCount(Boolean defaultCount) {
setProperty("defaultCount", defaultCount.toString());
}
public String getDialectAlias() {
return getProperty("dialectAlias");
}
public void setDialectAlias(String dialectAlias) {
setProperty("dialectAlias", dialectAlias);
} | public String getAutoDialectClass() {
return getProperty("autoDialectClass");
}
public void setAutoDialectClass(String autoDialectClass) {
setProperty("autoDialectClass", autoDialectClass);
}
public Boolean getAsyncCount() {
return Boolean.valueOf(getProperty("asyncCount"));
}
public void setAsyncCount(Boolean asyncCount) {
setProperty("asyncCount", asyncCount.toString());
}
public String getCountSqlParser() {
return getProperty("countSqlParser");
}
public void setCountSqlParser(String countSqlParser) {
setProperty("countSqlParser", countSqlParser);
}
public String getOrderBySqlParser() {
return getProperty("orderBySqlParser");
}
public void setOrderBySqlParser(String orderBySqlParser) {
setProperty("orderBySqlParser", orderBySqlParser);
}
public String getSqlServerSqlParser() {
return getProperty("sqlServerSqlParser");
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
setProperty("sqlServerSqlParser", sqlServerSqlParser);
}
public void setBannerEnabled(Boolean bannerEnabled) {
setProperty("banner",bannerEnabled.toString());
}
public Boolean getBannerEnabled() {
return Boolean.valueOf(getProperty("banner"));
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperProperties.java | 2 |
请完成以下Java代码 | public void updateNextLocation(final I_C_BPartner_Location bpLocation)
{
if (bpLocation.getPrevious_ID() > 0)
{
final BPartnerLocationId oldBPLocationId = BPartnerLocationId.ofRepoId(bpLocation.getC_BPartner_ID(), bpLocation.getPrevious_ID());
final BPartnerLocationId newBPLocationId = BPartnerLocationId.ofRepoId(bpLocation.getC_BPartner_ID(), bpLocation.getC_BPartner_Location_ID());
BPartnerLocationReplaceCommand.builder()
.oldBPLocationId(oldBPLocationId)
.newBPLocationId(newBPLocationId)
.newLocation(bpLocation)
.saveNewLocation(false) // because it will be saved after validator is triggered
.build()
.execute();
}
}
/** | * Prevents that a (the preceeding) location is terminated in the past.
* This is done by preventing that the current location's validFrom is set int he past.
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_C_BPartner_Location.COLUMNNAME_ValidFrom })
@CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_ValidFrom })
public void noTerminationInPast(final I_C_BPartner_Location bpLocation)
{
final Timestamp validFrom = bpLocation.getValidFrom();
if (validFrom != null && validFrom.before(Env.getDate()))
{
throw new AdempiereException("@AddressTerminatedInThePast@")
.appendParametersToMessage()
.setParameter("C_BPartner_Location.ValidFrom", validFrom)
.setParameter("Env.getDate()",Env.getDate())
.setParameter("C_BPartner_Location", bpLocation);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\interceptor\C_BPartner_Location.java | 1 |
请完成以下Java代码 | public void setSerNo (String SerNo)
{
set_ValueNoCheck (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
set_ValueNoCheck (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Version No. | @param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Delivery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addPricingRuleApplied(@NonNull final IPricingRule rule)
{
rulesApplied.add(rule);
}
@Override
public List<IPricingAttribute> getPricingAttributes()
{
return pricingAttributes;
}
@Override
public void addPricingAttributes(final Collection<IPricingAttribute> pricingAttributesToAdd)
{
if (pricingAttributesToAdd == null || pricingAttributesToAdd.isEmpty())
{
return;
}
pricingAttributes.addAll(pricingAttributesToAdd);
}
/**
* Supposed to be called by the pricing engine.
* <p>
* task https://github.com/metasfresh/metasfresh/issues/4376
*/
public void updatePriceScales()
{
priceStd = scaleToPrecision(priceStd);
priceLimit = scaleToPrecision(priceLimit);
priceList = scaleToPrecision(priceList);
}
@Nullable
private BigDecimal scaleToPrecision(@Nullable final BigDecimal priceToRound) | {
if (priceToRound == null || precision == null)
{
return priceToRound;
}
return precision.round(priceToRound);
}
@Override
public boolean isCampaignPrice()
{
return campaignPrice;
}
@Override
public IPricingResult setLoggableMessages(@NonNull final ImmutableList<String> loggableMessages)
{
this.loggableMessages = loggableMessages;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingResult.java | 2 |
请完成以下Java代码 | public String getName() {
return "Stopping process applications";
}
public void performOperationStep(DeploymentOperation operationContext) {
final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer();
List<JmxManagedProcessApplication> processApplicationsReferences = serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_APPLICATION);
for (JmxManagedProcessApplication processApplication : processApplicationsReferences) {
stopProcessApplication(processApplication.getProcessApplicationReference());
}
}
/**
* <p> Stops a process application. Exceptions are logged but not re-thrown).
*
* @param processApplicationReference
*/
protected void stopProcessApplication(ProcessApplicationReference processApplicationReference) { | try {
// unless the user has overridden the stop behavior,
// this causes the process application to remove its services
// (triggers nested undeployment operation)
ProcessApplicationInterface processApplication = processApplicationReference.getProcessApplication();
processApplication.undeploy();
}
catch(Throwable t) {
LOG.exceptionWhileStopping("Process Application", processApplicationReference.getName(), t);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\StopProcessApplicationsStep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static ConditionOutcome match() {
return match(ConditionMessage.empty());
}
/**
* Create a new {@link ConditionOutcome} instance for 'match'. For more consistent
* messages consider using {@link #match(ConditionMessage)}.
* @param message the message
* @return the {@link ConditionOutcome}
*/
public static ConditionOutcome match(String message) {
return new ConditionOutcome(true, message);
}
/**
* Create a new {@link ConditionOutcome} instance for 'match'.
* @param message the message
* @return the {@link ConditionOutcome}
*/
public static ConditionOutcome match(ConditionMessage message) {
return new ConditionOutcome(true, message);
}
/**
* Create a new {@link ConditionOutcome} instance for 'no match'. For more consistent
* messages consider using {@link #noMatch(ConditionMessage)}.
* @param message the message
* @return the {@link ConditionOutcome}
*/
public static ConditionOutcome noMatch(String message) {
return new ConditionOutcome(false, message);
}
/**
* Create a new {@link ConditionOutcome} instance for 'no match'.
* @param message the message
* @return the {@link ConditionOutcome}
*/
public static ConditionOutcome noMatch(ConditionMessage message) {
return new ConditionOutcome(false, message);
}
/**
* Return {@code true} if the outcome was a match.
* @return {@code true} if the outcome matches
*/
public boolean isMatch() {
return this.match;
}
/**
* Return an outcome message or {@code null}.
* @return the message or {@code null}
*/
public @Nullable String getMessage() {
return this.message.isEmpty() ? null : this.message.toString();
}
/**
* Return an outcome message.
* @return the message
*/
public ConditionMessage getConditionMessage() {
return this.message; | }
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() == obj.getClass()) {
ConditionOutcome other = (ConditionOutcome) obj;
return (this.match == other.match && ObjectUtils.nullSafeEquals(this.message, other.message));
}
return super.equals(obj);
}
@Override
public int hashCode() {
return Boolean.hashCode(this.match) * 31 + ObjectUtils.nullSafeHashCode(this.message);
}
@Override
public String toString() {
return (this.message != null) ? this.message.toString() : "";
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionOutcome.java | 2 |
请完成以下Java代码 | public int getPropertyAsInt(final String name, final int defaultValue)
{
final Object value = get(name);
if (value == null)
{
return defaultValue;
}
else if (value instanceof Number)
{
return ((Number)value).intValue();
}
else if (value instanceof String)
{
try
{
return Integer.parseInt(value.toString());
}
catch (final NumberFormatException e)
{
throw new RuntimeException("Property " + name + " has invalid integer value: " + value);
}
}
else
{
throw new RuntimeException("Property " + name + " cannot be converted to integer: " + value + " (class=" + value.getClass() + ")");
}
}
/**
*
* @param name
* @param interfaceClazz
* @return instance of given class/interface; never returns <code>null</code>
*/
public <T> T getInstance(final String name, final Class<T> interfaceClazz)
{
final Object value = get(name);
if (value == null)
{
throw new RuntimeException("No class of " + interfaceClazz + " found for property " + name);
}
else if (value instanceof String)
{
final String classname = value.toString();
return Util.getInstance(classname, interfaceClazz);
}
else if (value instanceof Class)
{
final Class<?> clazz = (Class<?>)value;
if (interfaceClazz.isAssignableFrom(clazz))
{
try
{
@SuppressWarnings("unchecked")
final T obj = (T)clazz.newInstance();
return obj;
}
catch (final Exception e)
{
throw new RuntimeException(e);
}
}
else
{
throw new RuntimeException("Invalid object " + value + " for property " + name + " (expected class: " + interfaceClazz + ")");
}
}
else if (interfaceClazz.isAssignableFrom(value.getClass()))
{
@SuppressWarnings("unchecked")
final T obj = (T)value;
return obj;
}
else
{
throw new RuntimeException("Invalid object " + value + " for property " + name + " (expected class: " + interfaceClazz + ")");
}
} | public <T> T get(final String name)
{
if (props.containsKey(name))
{
@SuppressWarnings("unchecked")
final T value = (T)props.get(name);
return value;
}
// Check other sources
for (final IContext source : sources)
{
final String valueStr = source.getProperty(name);
if (valueStr != null)
{
@SuppressWarnings("unchecked")
final T value = (T)valueStr;
return value;
}
}
// Check defaults
@SuppressWarnings("unchecked")
final T value = (T)defaults.get(name);
return value;
}
@Override
public String toString()
{
return "Context["
+ "sources=" + sources
+ ", properties=" + props
+ ", defaults=" + defaults
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\Context.java | 1 |
请完成以下Java代码 | public final class FacetCategory implements IFacetCategory
{
public static final Builder builder()
{
return new Builder();
}
private final String displayName;
private final boolean collapsed;
private final boolean eagerRefresh;
private FacetCategory(final Builder builder)
{
super();
Check.assumeNotEmpty(builder.displayName, "displayName not empty");
this.displayName = builder.displayName;
this.collapsed = builder.collapsed;
this.eagerRefresh = builder.eagerRefresh;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public String getDisplayName()
{
return displayName;
}
@Override
public boolean isCollapsed()
{
return collapsed;
}
@Override
public boolean isEagerRefresh()
{
return eagerRefresh;
} | public static class Builder
{
private String displayName;
private boolean collapsed = false;
private boolean eagerRefresh = false;
private Builder()
{
super();
}
public FacetCategory build()
{
return new FacetCategory(this);
}
public Builder setDisplayName(final String displayName)
{
this.displayName = displayName;
return this;
}
public Builder setDisplayNameAndTranslate(final String displayName)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final Properties ctx = Env.getCtx();
this.displayName = msgBL.translate(ctx, displayName);
return this;
}
public Builder setCollapsed(final boolean collapsed)
{
this.collapsed = collapsed;
return this;
}
public Builder setEagerRefresh()
{
this.eagerRefresh = true;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCategory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CouchbaseProperties {
private final List<String> bootstrapHosts;
private final String bucketName;
private final String bucketPassword;
private final int port;
public CouchbaseProperties(@Value("${spring.couchbase.bootstrap-hosts}") final List<String> bootstrapHosts, @Value("${spring.couchbase.bucket.name}") final String bucketName, @Value("${spring.couchbase.bucket.password}") final String bucketPassword,
@Value("${spring.couchbase.port}") final int port) {
this.bootstrapHosts = Collections.unmodifiableList(bootstrapHosts);
this.bucketName = bucketName;
this.bucketPassword = bucketPassword;
this.port = port;
}
public List<String> getBootstrapHosts() { | return bootstrapHosts;
}
public String getBucketName() {
return bucketName;
}
public String getBucketPassword() {
return bucketPassword;
}
public int getPort() {
return port;
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-data-couchbase\src\main\java\com\baeldung\couchbase\configuration\CouchbaseProperties.java | 2 |
请完成以下Java代码 | public List<Map.Entry<K, Float>> nearest(Vector vector)
{
return nearest(vector, 10);
}
/**
* 查询与词语最相似的词语
*
* @param key 词语
* @return 键值对列表, 键是相似词语, 值是相似度, 按相似度降序排列
*/
public List<Map.Entry<K, Float>> nearest(K key)
{
return nearest(key, 10);
}
/**
* 执行查询最相似的对象(子类通过query方法决定如何解析query,然后通过此方法执行查询)
*
* @param query 查询语句(或者说一个对象的内容)
* @param size 需要返回前多少个对象
* @return
*/
final List<Map.Entry<K, Float>> queryNearest(String query, int size)
{
if (query == null || query.length() == 0)
{
return Collections.emptyList();
}
try
{
return nearest(query(query), size);
}
catch (Exception e)
{
return Collections.emptyList();
}
}
/**
* 查询抽象文本对应的向量。此方法应当保证返回单位向量。
*
* @param query | * @return
*/
public abstract Vector query(String query);
/**
* 模型中的词向量总数(词表大小)
*
* @return
*/
public int size()
{
return storage.size();
}
/**
* 模型中的词向量维度
*
* @return
*/
public int dimension()
{
if (storage == null || storage.isEmpty())
{
return 0;
}
return storage.values().iterator().next().size();
}
/**
* 删除元素
*
* @param key
* @return
*/
public Vector remove(K key)
{
return storage.remove(key);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\AbstractVectorModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
} | public String getId() {
return id;
}
public String getLockOwner() {
return lockOwner;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java | 2 |
请完成以下Java代码 | public HttpServletRequest getRequest() {
return this.request;
}
/**
* Gets the response to write to.
* @return the response to write to. Cannot be null.
*/
public HttpServletResponse getResponse() {
return this.response;
}
/**
* The value to be written. This value may be modified by the
* {@link CookieSerializer} before written to the cookie. However, the value must
* be the same as the original when it is read back in.
* @return the value to be written
*/
public String getCookieValue() {
return this.cookieValue;
}
/** | * Get the cookie max age. The default is -1 which signals to delete the cookie
* when the browser is closed, or 0 if cookie value is empty.
* @return the cookie max age
*/
public int getCookieMaxAge() {
return this.cookieMaxAge;
}
/**
* Set the cookie max age.
* @param cookieMaxAge the cookie max age
*/
public void setCookieMaxAge(int cookieMaxAge) {
this.cookieMaxAge = cookieMaxAge;
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\CookieSerializer.java | 1 |
请完成以下Java代码 | public void remove(String id) {
cache.remove(id);
}
@Override
public void clear() {
cache.clear();
}
@Override
public Collection<ProcessDefinitionInfoCacheObject> getAll() {
return cache.values();
}
@Override
public int size() {
return cache.size();
}
protected ProcessDefinitionInfoCacheObject retrieveProcessDefinitionInfoCacheObject(String processDefinitionId, CommandContext commandContext) {
ProcessDefinitionInfoEntityManager infoEntityManager = CommandContextUtil.getProcessDefinitionInfoEntityManager(commandContext);
ObjectMapper objectMapper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getObjectMapper();
ProcessDefinitionInfoCacheObject cacheObject = null;
if (cache.containsKey(processDefinitionId)) {
cacheObject = cache.get(processDefinitionId);
} else {
cacheObject = new ProcessDefinitionInfoCacheObject();
cacheObject.setRevision(0);
cacheObject.setInfoNode(objectMapper.createObjectNode());
}
ProcessDefinitionInfoEntity infoEntity = infoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinitionId); | if (infoEntity != null && infoEntity.getRevision() != cacheObject.getRevision()) {
cacheObject.setRevision(infoEntity.getRevision());
if (infoEntity.getInfoJsonId() != null) {
byte[] infoBytes = infoEntityManager.findInfoJsonById(infoEntity.getInfoJsonId());
try {
ObjectNode infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
cacheObject.setInfoNode(infoNode);
} catch (Exception e) {
throw new FlowableException("Error reading json info node for process definition " + processDefinitionId, e);
}
}
} else if (infoEntity == null) {
cacheObject.setRevision(0);
cacheObject.setInfoNode(objectMapper.createObjectNode());
}
return cacheObject;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\deploy\ProcessDefinitionInfoCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void initializeBeansInLayers(List<Set<String>> layers, ConfigurableListableBeanFactory beanFactory) {
for (Set<String> layer : layers) {
// Beans of the same layer can be initialized in parallel
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (String beanName : layer) {
// only load beans that wrote by yourself
if (shouldLoadBean(beanName)) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
beanFactory.getBean(beanName); // init Bean
} catch (Exception e) {
System.err.println("Failed to initialize bean: " + beanName);
e.printStackTrace();
}
}, executorService); | futures.add(future);
}
}
//Wait for all beans in the current layer to be initialized before initializing the next layer.
CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allOf.join(); // make sure to be done on current layer
}
}
private boolean shouldLoadBean(String beanName) {
return beanName.startsWith("helloWorldController")
||beanName.startsWith("serviceOne")
||beanName.startsWith("serviceTwo")
||beanName.startsWith("serviceThree");
}
} | repos\springboot-demo-master\dag\src\main\java\com\et\config\DAGBeanInitializer.java | 2 |
请完成以下Java代码 | public void run() {
this.originalSecurityContext = this.securityContextHolderStrategy.getContext();
try {
this.securityContextHolderStrategy.setContext(this.delegateSecurityContext);
this.delegate.run();
}
finally {
SecurityContext emptyContext = this.securityContextHolderStrategy.createEmptyContext();
if (emptyContext.equals(this.originalSecurityContext)) {
this.securityContextHolderStrategy.clearContext();
}
else {
this.securityContextHolderStrategy.setContext(this.originalSecurityContext);
}
this.originalSecurityContext = null;
}
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
if (!this.explicitSecurityContextProvided) {
this.delegateSecurityContext = this.securityContextHolderStrategy.getContext();
}
}
@Override
public String toString() {
return this.delegate.toString();
}
/**
* Factory method for creating a {@link DelegatingSecurityContextRunnable}.
* @param delegate the original {@link Runnable} that will be delegated to after
* establishing a {@link SecurityContext} on the {@link SecurityContextHolder}. Cannot | * have null.
* @param securityContext the {@link SecurityContext} to establish before invoking the
* delegate {@link Runnable}. If null, the current {@link SecurityContext} from the
* {@link SecurityContextHolder} will be used.
* @return
*/
public static Runnable create(Runnable delegate, @Nullable SecurityContext securityContext) {
Assert.notNull(delegate, "delegate cannot be null");
return (securityContext != null) ? new DelegatingSecurityContextRunnable(delegate, securityContext)
: new DelegatingSecurityContextRunnable(delegate);
}
static Runnable create(Runnable delegate, @Nullable SecurityContext securityContext,
SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(delegate, "delegate cannot be null");
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
DelegatingSecurityContextRunnable runnable = (securityContext != null)
? new DelegatingSecurityContextRunnable(delegate, securityContext)
: new DelegatingSecurityContextRunnable(delegate);
runnable.setSecurityContextHolderStrategy(securityContextHolderStrategy);
return runnable;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\concurrent\DelegatingSecurityContextRunnable.java | 1 |
请完成以下Java代码 | public String getStartUserId() {
return startUserId;
}
public String getAssignee() {
return assignee;
}
public String getCompletedBy() {
return completedBy;
}
public String getReferenceId() {
return referenceId;
}
public String getReferenceType() {
return referenceType;
}
public boolean isEnded() {
return ended;
}
public boolean isNotEnded() {
return notEnded;
}
public String getEntryCriterionId() {
return entryCriterionId;
}
public String getExitCriterionId() {
return exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public String getExtraValue() {
return extraValue;
}
public String getInvolvedUser() {
return involvedUser;
}
public Collection<String> getInvolvedGroups() {
return involvedGroups;
}
public boolean isOnlyStages() {
return onlyStages;
}
public String getTenantId() {
return tenantId;
} | public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public boolean isIncludeLocalVariables() {
return includeLocalVariables;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds;
}
public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeCaseInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getCaseInstanceIds() {
return caseInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricPlanItemInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEncrypted() {
return this.encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
public TrustStrategy getTrustStrategy() {
return this.trustStrategy;
}
public void setTrustStrategy(TrustStrategy trustStrategy) {
this.trustStrategy = trustStrategy;
}
public @Nullable File getCertFile() {
return this.certFile;
}
public void setCertFile(@Nullable File certFile) {
this.certFile = certFile;
}
public boolean isHostnameVerificationEnabled() {
return this.hostnameVerificationEnabled;
}
public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) {
this.hostnameVerificationEnabled = hostnameVerificationEnabled;
}
public enum TrustStrategy {
/** | * Trust all certificates.
*/
TRUST_ALL_CERTIFICATES,
/**
* Trust certificates that are signed by a trusted certificate.
*/
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES,
/**
* Trust certificates that can be verified through the local system store.
*/
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private String createRegistrationToken() {
var body = new LinkedMultiValueMap<String,String>();
body.put( "grant_type", List.of("client_credentials"));
body.put( "scope", registrationDetails.registrationScopes());
var headers = new HttpHeaders();
headers.setBasicAuth(registrationDetails.registrationUsername(), registrationDetails.registrationPassword());
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
var request = new RequestEntity<>(
body,
headers,
HttpMethod.POST,
registrationDetails.tokenEndpoint());
var result = registrationClient.exchange(request, ObjectNode.class);
if ( !result.getStatusCode().is2xxSuccessful()) {
throw new RuntimeException("Failed to create registration token: code=" + result.getStatusCode());
}
return result.getBody().get("access_token").asText();
}
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
@Override
public Iterator<ClientRegistration> iterator() {
return registrations
.values()
.iterator();
} | public void doRegistrations() {
staticClients.forEach((key, value) -> findByRegistrationId(key));
}
public record RegistrationDetails(
URI registrationEndpoint,
String registrationUsername,
String registrationPassword,
List<String> registrationScopes,
List<String> grantTypes,
List<String> redirectUris,
URI tokenEndpoint
) {
}
// Type-safe RestTemplate
public static class RegistrationRestTemplate extends RestTemplate {
}
} | repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-dynamic-client\src\main\java\com\baeldung\spring\security\dynreg\client\service\DynamicClientRegistrationRepository.java | 2 |
请完成以下Java代码 | public class UserCheckLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false) != null) {
response.sendRedirect(request.getContextPath() + "/user-check/home");
return;
}
String referer = (String) request.getAttribute("origin");
request.setAttribute("origin", referer);
UserCheckFilter.forward(request, response, "/login.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = request.getParameter("name");
String pass = request.getParameter("password");
User user = User.DB.get(key);
if (user == null || !user.getPassword()
.equals(pass)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
request.setAttribute("origin", request.getParameter("origin"));
request.setAttribute("error", "invalid login");
UserCheckFilter.forward(request, response, "/login.jsp"); | return;
}
user.getLogins()
.add(new Date());
HttpSession session = request.getSession();
session.setAttribute("user", user);
String origin = request.getParameter("origin");
if (origin == null || origin.contains("login"))
origin = "./";
response.sendRedirect(origin);
}
} | repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\user\check\UserCheckLoginServlet.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (PARAMNAME_QTY_TO_RESERVE.equals(parameter.getColumnName()))
{
final SalesOrderLine salesOrderLine = WEBUI_C_OrderLineSO_Util.retrieveSalesOrderLine(getView(), salesOrderLineRepository).get();
final ProductId productId = salesOrderLine.getProductId();
final Quantity orderedQty = salesOrderLine.getOrderedQty();
final Quantity reservedQty = huReservationService
.retrieveReservedQty(salesOrderLine.getId().getOrderLineId())
.orElse(orderedQty.toZero());
final Quantity reservedQtyInSalesOrderUOM = uomConversionBL.convertQuantityTo(
reservedQty,
UOMConversionContext.of(productId),
orderedQty.getUomId());
final Quantity requiredQty = orderedQty
.subtract(salesOrderLine.getDeliveredQty())
.subtract(reservedQtyInSalesOrderUOM);
final Quantity reservableQty = retrieveReservableQuantity(productId);
final Quantity reservableQtyInSalesOrderUOM = uomConversionBL.convertQuantityTo(
reservableQty,
UOMConversionContext.of(productId),
orderedQty.getUomId());
return requiredQty.min(reservableQtyInSalesOrderUOM).toBigDecimal();
}
return null;
}
private Quantity retrieveReservableQuantity(@NonNull final ProductId productId)
{
final RetrieveHUsQtyRequest request = WEBUI_C_OrderLineSO_Util.createHuQuantityRequest(
streamSelectedHUIds(Select.ALL), productId); | return huReservationService.retrieveReservableQty(request);
}
@Override
protected String doIt()
{
final SalesOrderLine salesOrderLine = WEBUI_C_OrderLineSO_Util.retrieveSalesOrderLine(getView(), salesOrderLineRepository).get();
final ImmutableList<HuId> selectedHuIds = streamSelectedHUIds(Select.ALL)
.collect(ImmutableList.toImmutableList());
if (selectedHuIds.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final Quantity qtyToReserve = Quantity.of(qtyToReserveBD, salesOrderLine.getOrderedQty().getUOM());
final ReserveHUsRequest reservationRequest = ReserveHUsRequest
.builder()
.huIds(selectedHuIds)
.productId(salesOrderLine.getProductId())
.qtyToReserve(qtyToReserve)
.documentRef(HUReservationDocRef.ofSalesOrderLineId(salesOrderLine.getId().getOrderLineId()))
.build();
huReservationService.makeReservation(reservationRequest);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\hu\reservation\process\WEBUI_C_OrderLineSO_Make_HUReservation.java | 1 |
请完成以下Java代码 | public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return olCandEffectiveValuesBL.getEffectiveUomId(olCand).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId)
{
values.setUomId(UomId.ofRepoIdOrNull(uomId));
// NOTE: uom is mandatory
// we assume orderLine's UOM is correct
if (uomId > 0)
{
olCand.setPrice_UOM_Internal_ID(uomId);
}
}
@Override
public BigDecimal getQtyTU()
{
return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand));
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
values.setQtyTU(qtyPacks); | }
@Override
public int getC_BPartner_ID()
{
final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand);
return BPartnerId.toRepoId(bpartnerId);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
olCand.setC_BPartner_Override_ID(partnerId);
values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId));
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OLCandHUPackingAware.java | 1 |
请完成以下Java代码 | public boolean isCellEditable(EventObject anEvent)
{
return m_select;
} // isCellEditable
/**
* Sets an initial value for the editor. This will cause the editor to
* stopEditing and lose any partially edited value if the editor is editing
* when this method is called.
* Returns the component that should be added to the client's Component hierarchy.
* Once installed in the client's hierarchy this component
* will then be able to draw and receive user input.
*/
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int col)
{
log.debug("Value=" + value + ", row=" + row + ", col=" + col);
m_rid = (Object[])value;
if (m_rid == null || m_rid[1] == null)
m_cb.setSelected(false);
else
{
Boolean sel = (Boolean)m_rid[1];
m_cb.setSelected(sel.booleanValue());
}
return m_cb;
} // getTableCellEditorComponent
/**
* The editing cell should be selected or not
*/
@Override | public boolean shouldSelectCell(EventObject anEvent)
{
return m_select;
} // shouldSelectCell
/**
* Returns the value contained in the editor
*/
@Override
public Object getCellEditorValue()
{
log.debug("" + m_cb.isSelected());
if (m_rid == null)
return null;
m_rid[1] = Boolean.valueOf(m_cb.isSelected());
return m_rid;
} // getCellEditorValue
} // VRowIDEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VRowIDEditor.java | 1 |
请完成以下Java代码 | public static ProcessEngineInfo getProcessEngineInfo(String processEngineName) {
return processEngineInfosByName.get(processEngineName);
}
public static ProcessEngine getDefaultProcessEngine() {
return getProcessEngine(NAME_DEFAULT);
}
/**
* obtain a process engine by name.
*
* @param processEngineName
* is the name of the process engine or null for the default process engine.
*/
public static ProcessEngine getProcessEngine(String processEngineName) {
if (!isInitialized()) {
init();
}
return processEngines.get(processEngineName);
}
/**
* retries to initialize a process engine that previously failed.
*/
public static ProcessEngineInfo retry(String resourceUrl) {
log.debug("retying initializing of resource {}", resourceUrl);
try {
return initProcessEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new ActivitiIllegalArgumentException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to process engine to application clients in a managed server environment.
*/
public static Map<String, ProcessEngine> getProcessEngines() {
return processEngines;
}
/**
* closes all process engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) { | Map<String, ProcessEngine> engines = new HashMap<String, ProcessEngine>(processEngines);
processEngines = new HashMap<String, ProcessEngine>();
for (String processEngineName : engines.keySet()) {
ProcessEngine processEngine = engines.get(processEngineName);
try {
processEngine.close();
} catch (Exception e) {
log.error(
"exception while closing {}",
(processEngineName == null
? "the default process engine"
: "process engine " + processEngineName),
e
);
}
}
processEngineInfosByName.clear();
processEngineInfosByResourceUrl.clear();
processEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
ProcessEngines.isInitialized = isInitialized;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngines.java | 1 |
请完成以下Java代码 | public Headers getHeaders() {
return this.headers;
}
/**
* Set the headers.
* @param headers the headers.
*/
public void setHeaders(@Nullable Headers headers) {
this.headers = headers;
}
/**
* Get the data that failed deserialization (value or key).
* @return the data. | */
public byte[] getData() {
return this.data; // NOSONAR array reference
}
/**
* True if deserialization of the key failed, otherwise deserialization of the value
* failed.
* @return true for the key.
*/
public boolean isKey() {
return this.isKey;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DeserializationException.java | 1 |
请完成以下Java代码 | public static String pubkTrimNewLines(String input) {
return input.replaceAll("-----BEGIN PUBLIC KEY-----", "")
.replaceAll("\n", "")
.replaceAll("\r", "")
.replaceAll("-----END PUBLIC KEY-----", "");
}
public static String prikTrimNewLines(String input) {
return input.replaceAll("-----BEGIN EC PRIVATE KEY-----", "")
.replaceAll("\n", "")
.replaceAll("\r", "")
.replaceAll("-----END EC PRIVATE KEY-----", "");
}
public static String getSha3Hash(String data) {
String trimmedData = certTrimNewLines(data);
byte[] dataBytes = trimmedData.getBytes();
SHA3Digest md = new SHA3Digest(256);
md.reset();
md.update(dataBytes, 0, dataBytes.length);
byte[] hashedBytes = new byte[256 / 8];
md.doFinal(hashedBytes, 0); | String sha3Hash = ByteUtils.toHexString(hashedBytes);
return sha3Hash;
}
public static String getSha3Hash(String delim, String... tokens) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String token : tokens) {
if (token != null && !token.isEmpty()) {
if (first) {
first = false;
} else {
sb.append(delim);
}
sb.append(token);
}
}
return getSha3Hash(sb.toString());
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\EncryptionUtil.java | 1 |
请完成以下Java代码 | final class RecordChangeLogLoader
{
public static RecordChangeLogLoader ofAdTableId(final int adTableId)
{
return new RecordChangeLogLoader(adTableId);
}
private final POInfo poInfo;
private RecordChangeLogLoader(final int adTableId)
{
Check.assumeGreaterThanZero(adTableId, "adTableId");
poInfo = POInfo.getPOInfo(adTableId);
Check.assumeNotNull(poInfo, "poInfo is not null for adTableId={}", adTableId);
}
public RecordChangeLog getByRecordId(@NonNull final ComposedRecordId recordId)
{
final RecordChangeLog.RecordChangeLogBuilder changeLogsBuilder = RecordChangeLog.builder()
.tableName(poInfo.getTableName())
.recordId(recordId);
loadRecordSummary(changeLogsBuilder, recordId);
final List<RecordChangeLogEntry> logEntries = retrieveLogEntries(recordId);
changeLogsBuilder.entries(logEntries);
return changeLogsBuilder.build();
}
public RecordChangeLog getSummaryByRecordId(@NonNull final ComposedRecordId recordId)
{
final RecordChangeLog.RecordChangeLogBuilder changeLogsBuilder = RecordChangeLog.builder()
.tableName(poInfo.getTableName())
.recordId(recordId);
loadRecordSummary(changeLogsBuilder, recordId);
return changeLogsBuilder.build();
} | private void loadRecordSummary(final RecordChangeLog.RecordChangeLogBuilder changeLogsBuilder, final ComposedRecordId recordId)
{
DB.forFirstRowIfAny(
"SELECT Created, CreatedBy, Updated, UpdatedBy FROM " + poInfo.getTableName() + " WHERE " + poInfo.getSqlWhereClauseByKeys(),
recordId.getKeysAsList(poInfo.getKeyColumnNames()),
rs -> changeLogsBuilder.createdByUserId(UserId.ofRepoIdOrNull(rs.getInt("CreatedBy")))
.createdTimestamp(rs.getTimestamp("Created").toInstant())
.lastChangedByUserId(UserId.ofRepoIdOrNull(rs.getInt("UpdatedBy")))
.lastChangedTimestamp(rs.getTimestamp("Updated").toInstant()));
}
private List<RecordChangeLogEntry> retrieveLogEntries(@NonNull final ComposedRecordId recordId)
{
if (!recordId.isSingleKey())
{
return ImmutableList.of();
}
final int singleRecordId = recordId.getSingleRecordId().orElse(-1);
final TableRecordReference recordRef = TableRecordReference.of(poInfo.getAD_Table_ID(), singleRecordId);
final ImmutableListMultimap<TableRecordReference, RecordChangeLogEntry> //
logEntries = RecordChangeLogEntryLoader.retrieveLogEntries(LogEntriesQuery.of(recordRef));
return (logEntries.get(recordRef));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogLoader.java | 1 |
请完成以下Java代码 | public class DocLine_Cash extends DocLine<Doc_Cash>
{
/**
* Constructor
* @param line cash line
* @param doc header
*/
public DocLine_Cash (I_C_CashLine line, Doc_Cash doc)
{
super (InterfaceWrapperHelper.getPO(line), doc);
m_CashType = line.getCashType();
m_C_BP_BankAccount_ID = BankAccountId.ofRepoIdOrNull(line.getC_BP_BankAccount_ID());
m_C_Invoice_ID = line.getC_Invoice_ID();
//
if (m_C_Invoice_ID > 0)
{
I_C_Invoice invoice = line.getC_Invoice();
setBPartnerId(BPartnerId.ofRepoId(invoice.getC_BPartner_ID()));
}
//
m_Amount = line.getAmount();
m_DiscountAmt = line.getDiscountAmt();
m_WriteOffAmt = line.getWriteOffAmt();
setAmount(m_Amount);
} // DocLine_Cash
/** Cash Type */
private String m_CashType = "";
// AD_Reference_ID=217
/** Charge - C */
public static final String CASHTYPE_CHARGE = "C";
/** Difference - D */
public static final String CASHTYPE_DIFFERENCE = "D";
/** Expense - E */
public static final String CASHTYPE_EXPENSE = "E";
/** Onvoice - I */
public static final String CASHTYPE_INVOICE = "I";
/** Receipt - R */
public static final String CASHTYPE_RECEIPT = "R";
/** Transfer - T */
public static final String CASHTYPE_TRANSFER = "T";
// References
private BankAccountId m_C_BP_BankAccount_ID = null;
private int m_C_Invoice_ID = 0;
// Amounts
private BigDecimal m_Amount = BigDecimal.ZERO;
private BigDecimal m_DiscountAmt = BigDecimal.ZERO;
private BigDecimal m_WriteOffAmt = BigDecimal.ZERO;
/**
* Get Cash Type
* @return cash type
*/
public String getCashType()
{
return m_CashType;
} // getCashType
/**
* Get Bank Account
* @return Bank Account
*/
public BankAccountId getC_BP_BankAccount_ID() | {
return m_C_BP_BankAccount_ID;
} // getC_BP_BankAccount_ID
/**
* Get Invoice
* @return C_Invoice_ID
*/
public int getC_Invoice_ID()
{
return m_C_Invoice_ID;
} // getC_Invoice_ID
/**
* Get Amount
* @return Payment Amount
*/
public BigDecimal getAmount()
{
return m_Amount;
}
/**
* Get Discount
* @return Discount Amount
*/
public BigDecimal getDiscountAmt()
{
return m_DiscountAmt;
}
/**
* Get WriteOff
* @return Write-Off Amount
*/
public BigDecimal getWriteOffAmt()
{
return m_WriteOffAmt;
}
} // DocLine_Cash | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Cash.java | 1 |
请完成以下Java代码 | public class DynamicDataSource extends HikariDataSource {
@Override
public Connection getConnection() throws SQLException {
// 获取当前数据源 id
Long id = DatasourceConfigContextHolder.getCurrentDatasourceConfig();
// 根据当前id获取数据源
HikariDataSource datasource = DatasourceHolder.INSTANCE.getDatasource(id);
if (null == datasource) {
datasource = initDatasource(id);
}
return datasource.getConnection();
}
/**
* 初始化数据源
*
* @param id 数据源id
* @return 数据源
*/
private HikariDataSource initDatasource(Long id) {
HikariDataSource dataSource = new HikariDataSource();
// 判断是否是默认数据源
if (DatasourceHolder.DEFAULT_ID.equals(id)) {
// 默认数据源根据 application.yml 配置的生成
DataSourceProperties properties = SpringUtil.getBean(DataSourceProperties.class);
dataSource.setJdbcUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername()); | dataSource.setPassword(properties.getPassword());
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
} else {
// 不是默认数据源,通过缓存获取对应id的数据源的配置
DatasourceConfig datasourceConfig = DatasourceConfigCache.INSTANCE.getConfig(id);
if (datasourceConfig == null) {
throw new RuntimeException("无此数据源");
}
dataSource.setJdbcUrl(datasourceConfig.buildJdbcUrl());
dataSource.setUsername(datasourceConfig.getUsername());
dataSource.setPassword(datasourceConfig.getPassword());
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
}
// 将创建的数据源添加到数据源管理器中,绑定当前线程
DatasourceHolder.INSTANCE.addDatasource(id, dataSource);
return dataSource;
}
} | repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\datasource\DynamicDataSource.java | 1 |
请完成以下Java代码 | private static final JLabel createURLLabel(final String urlStr)
{
final JLabel labelURL = new JLabel();
labelURL.setForeground(Color.blue);
labelURL.setHorizontalAlignment(SwingConstants.CENTER);
labelURL.setHorizontalTextPosition(SwingConstants.CENTER);
labelURL.setCursor(new Cursor(Cursor.HAND_CURSOR));
labelURL.setText(urlStr);
labelURL.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(final MouseEvent e)
{
Services.get(IClientUI.class).showURL(urlStr);
}
}); | return labelURL;
}
/**
* ActionListener
* @param e event
*/
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals(ConfirmPanel.A_OK))
dispose();
} // actionPerformed
} // AboutBox | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AboutBox.java | 1 |
请完成以下Java代码 | protected void updateAndValidateImportRecordsImpl()
{
final ImportRecordsSelection selection = getImportRecordsSelection();
RepelnishmentImportTableSqlUpdater.updateReplenishmentImportTable(selection);
}
@Override
protected String getImportOrderBySql()
{
return I_I_Replenish.COLUMNNAME_ProductValue;
}
@Override
public I_I_Replenish retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException
{
return new X_I_Replenish(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
/*
* @param isInsertOnly ignored. This import is only for updates.
*/
@Override
protected ImportRecordResult importRecord(
@NonNull final IMutable<Object> state_NOTUSED,
@NonNull final I_I_Replenish importRecord,
final boolean isInsertOnly_NOTUSED)
{
if (ReplenishImportHelper.isValidRecordForImport(importRecord))
{
return importReplenish(importRecord);
}
else
{
throw new AdempiereException(MSG_NoValidRecord);
} | }
private ImportRecordResult importReplenish(@NonNull final I_I_Replenish importRecord)
{
final ImportRecordResult replenishImportResult;
final I_M_Replenish replenish;
if (importRecord.getM_Replenish_ID() <= 0)
{
replenish = ReplenishImportHelper.createNewReplenish(importRecord);
replenishImportResult = ImportRecordResult.Inserted;
}
else
{
replenish = ReplenishImportHelper.uppdateReplenish(importRecord);
replenishImportResult = ImportRecordResult.Updated;
}
InterfaceWrapperHelper.save(replenish);
importRecord.setM_Replenish_ID(replenish.getM_Replenish_ID());
InterfaceWrapperHelper.save(importRecord);
return replenishImportResult;
}
@Override
protected void markImported(@NonNull final I_I_Replenish importRecord)
{
importRecord.setI_IsImported(X_I_Replenish.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishmentImportProcess.java | 1 |
请完成以下Java代码 | public void setAlgorithm(SecretKeyFactoryAlgorithm secretKeyFactoryAlgorithm) {
if (secretKeyFactoryAlgorithm == null) {
throw new IllegalArgumentException("secretKeyFactoryAlgorithm cannot be null");
}
String algorithmName = secretKeyFactoryAlgorithm.name();
try {
SecretKeyFactory.getInstance(algorithmName);
this.algorithm = algorithmName;
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalArgumentException("Invalid algorithm '" + algorithmName + "'.", ex);
}
if (this.overrideHashWidth) {
this.hashWidth = SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1.equals(secretKeyFactoryAlgorithm) ? 160
: SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256.equals(secretKeyFactoryAlgorithm) ? 256 : 512;
}
}
/**
* Sets if the resulting hash should be encoded as Base64. The default is false which
* means it will be encoded in Hex.
* @param encodeHashAsBase64 true if encode as Base64, false if should use Hex
* (default)
*/
public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
this.encodeHashAsBase64 = encodeHashAsBase64;
}
@Override
protected String encodeNonNullPassword(String rawPassword) {
byte[] salt = this.saltGenerator.generateKey();
byte[] encoded = encodedNonNullPassword(rawPassword, salt);
return encodedNonNullPassword(encoded);
}
private String encodedNonNullPassword(byte[] bytes) {
if (this.encodeHashAsBase64) {
return Base64.getEncoder().encodeToString(bytes);
}
return String.valueOf(Hex.encode(bytes));
}
@Override
protected boolean matchesNonNull(String rawPassword, String encodedPassword) {
byte[] digested = decode(encodedPassword);
byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength());
return MessageDigest.isEqual(digested, encodedNonNullPassword(rawPassword, salt));
}
private byte[] decode(String encodedBytes) {
if (this.encodeHashAsBase64) {
return Base64.getDecoder().decode(encodedBytes);
}
return Hex.decode(encodedBytes);
} | private byte[] encodedNonNullPassword(CharSequence rawPassword, byte[] salt) {
try {
PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(),
EncodingUtils.concatenate(salt, this.secret), this.iterations, this.hashWidth);
SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm);
return EncodingUtils.concatenate(salt, skf.generateSecret(spec).getEncoded());
}
catch (GeneralSecurityException ex) {
throw new IllegalStateException("Could not create hash", ex);
}
}
/**
* The Algorithm used for creating the {@link SecretKeyFactory}
*
* @since 5.0
*/
public enum SecretKeyFactoryAlgorithm {
PBKDF2WithHmacSHA1, PBKDF2WithHmacSHA256, PBKDF2WithHmacSHA512
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Pbkdf2PasswordEncoder.java | 1 |
请完成以下Java代码 | public boolean isReadOnly(Bindings bindings, ELContext context) {
ValueExpression expression = bindings.getVariable(index);
if (expression != null) {
return expression.isReadOnly(context);
}
context.setPropertyResolved(false);
boolean result = context.getELResolver().isReadOnly(context, null, name);
if (!context.isPropertyResolved()) {
throw new PropertyNotFoundException(LocalMessages.get("error.identifier.property.notfound", name));
}
return result;
}
protected Method getMethod(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
Object value = eval(bindings, context);
if (value == null) {
throw new MethodNotFoundException(LocalMessages.get("error.identifier.method.notfound", name));
}
if (value instanceof Method) {
Method method = (Method)value;
if (returnType != null && !returnType.isAssignableFrom(method.getReturnType())) {
throw new MethodNotFoundException(LocalMessages.get("error.identifier.method.notfound", name));
}
if (!Arrays.equals(method.getParameterTypes(), paramTypes)) {
throw new MethodNotFoundException(LocalMessages.get("error.identifier.method.notfound", name));
}
return method;
}
throw new MethodNotFoundException(LocalMessages.get("error.identifier.method.notamethod", name, value.getClass()));
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
Method method = getMethod(bindings, context, returnType, paramTypes);
return new MethodInfo(method.getName(), method.getReturnType(), paramTypes);
}
public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] params) {
Method method = getMethod(bindings, context, returnType, paramTypes);
try {
return method.invoke(null, params);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.identifier.method.access", name)); | } catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e));
} catch (InvocationTargetException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e.getCause()));
}
}
@Override
public String toString() {
return name;
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
} | repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\AstIdentifier.java | 1 |
请完成以下Java代码 | protected void executeSchemaUpdate(List<SchemaManager> schemaManagers, String databaseSchemaUpdate) {
LOGGER.debug("Executing schema management with setting {} from engine {}", databaseSchemaUpdate, engineScopeType);
if (AbstractEngineConfiguration.DB_SCHEMA_UPDATE_DROP_CREATE.equals(databaseSchemaUpdate)) {
// The drop is executed in the reverse order
ListIterator<SchemaManager> listIterator = schemaManagers.listIterator(schemaManagers.size());
while (listIterator.hasPrevious()) {
SchemaManager schemaManager = listIterator.previous();
try {
schemaManager.schemaDrop();
} catch (RuntimeException e) {
// ignore
}
}
} | if (AbstractEngineConfiguration.DB_SCHEMA_UPDATE_CREATE_DROP.equals(databaseSchemaUpdate)
|| AbstractEngineConfiguration.DB_SCHEMA_UPDATE_DROP_CREATE.equals(databaseSchemaUpdate)
|| AbstractEngineConfiguration.DB_SCHEMA_UPDATE_CREATE.equals(databaseSchemaUpdate)) {
schemaManagers.forEach(SchemaManager::schemaCreate);
} else if (AbstractEngineConfiguration.DB_SCHEMA_UPDATE_FALSE.equals(databaseSchemaUpdate)) {
schemaManagers.forEach(SchemaManager::schemaCheckVersion);
} else if (AbstractEngineConfiguration.DB_SCHEMA_UPDATE_TRUE.equals(databaseSchemaUpdate)) {
schemaManagers.forEach(SchemaManager::schemaUpdate);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\SchemaOperationsEngineBuild.java | 1 |
请完成以下Java代码 | public class AnimalBadPractice {
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public synchronized void setName(String name) {
this.name = name;
}
public void setOwner(String owner) { | synchronized(this) {
this.owner = owner;
}
}
public AnimalBadPractice() {
}
public AnimalBadPractice(String name, String owner) {
this.name = name;
this.owner = owner;
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\synchronizationbadpractices\AnimalBadPractice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AppDefinitionResponse getAppDefinition(@ApiParam(name = "appDefinitionId") @PathVariable String appDefinitionId) {
AppDefinition appDefinition = appRepositoryService.getAppDefinition(appDefinitionId);
if (appDefinition == null) {
throw new FlowableObjectNotFoundException("Could not find an app definition with id '" + appDefinitionId);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessAppDefinitionInfoById(appDefinition);
}
return appRestResponseFactory.createAppDefinitionResponse(appDefinition);
}
@ApiOperation(value = "Execute actions for an app definition", tags = { "App Definitions" },
notes = "Execute actions for an app definition (Update category)")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates action has been executed for the specified app definition. (category altered)"),
@ApiResponse(code = 400, message = "Indicates no category was defined in the request body."),
@ApiResponse(code = 404, message = "Indicates the requested app definition was not found.")
})
@PutMapping(value = "/app-repository/app-definitions/{appDefinitionId}", produces = "application/json")
public AppDefinitionResponse executeAppDefinitionAction(
@ApiParam(name = "appDefinitionId") @PathVariable String appDefinitionId,
@ApiParam(required = true) @RequestBody AppDefinitionActionRequest actionRequest) {
if (actionRequest == null) {
throw new FlowableIllegalArgumentException("No action found in request body.");
} | AppDefinition appDefinition = appRepositoryService.getAppDefinition(appDefinitionId);
if (appDefinition == null) {
throw new FlowableObjectNotFoundException("Could not find an app definition with id '" + appDefinitionId + "'.", AppDefinition.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessAppDefinitionInfoById(appDefinition);
}
if (actionRequest.getCategory() != null) {
// Update of category required
appRepositoryService.setAppDefinitionCategory(appDefinition.getId(), actionRequest.getCategory());
// No need to re-fetch the AppDefinition entity, just update category in response
AppDefinitionResponse response = appRestResponseFactory.createAppDefinitionResponse(appDefinition);
response.setCategory(actionRequest.getCategory());
return response;
}
throw new FlowableIllegalArgumentException("Invalid action: '" + actionRequest.getAction() + "'.");
}
} | repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDefinitionResource.java | 2 |
请完成以下Java代码 | public void setA_Depreciation_Table_Code (String A_Depreciation_Table_Code)
{
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Table_Code, A_Depreciation_Table_Code);
}
/** Get Depreciation Code.
@return Depreciation Code */
public String getA_Depreciation_Table_Code ()
{
return (String)get_Value(COLUMNNAME_A_Depreciation_Table_Code);
}
/** Set A_Depreciation_Table_Detail_ID.
@param A_Depreciation_Table_Detail_ID A_Depreciation_Table_Detail_ID */
public void setA_Depreciation_Table_Detail_ID (int A_Depreciation_Table_Detail_ID)
{
if (A_Depreciation_Table_Detail_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Table_Detail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Depreciation_Table_Detail_ID, Integer.valueOf(A_Depreciation_Table_Detail_ID));
}
/** Get A_Depreciation_Table_Detail_ID.
@return A_Depreciation_Table_Detail_ID */
public int getA_Depreciation_Table_Detail_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_Table_Detail_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Depreciation_Table_Detail_ID()));
}
/** Set Period/Yearly.
@param A_Period Period/Yearly */
public void setA_Period (int A_Period)
{
set_Value (COLUMNNAME_A_Period, Integer.valueOf(A_Period));
}
/** Get Period/Yearly.
@return Period/Yearly */
public int getA_Period ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Period);
if (ii == null)
return 0;
return ii.intValue();
} | /** A_Table_Rate_Type AD_Reference_ID=53255 */
public static final int A_TABLE_RATE_TYPE_AD_Reference_ID=53255;
/** Amount = AM */
public static final String A_TABLE_RATE_TYPE_Amount = "AM";
/** Rate = RT */
public static final String A_TABLE_RATE_TYPE_Rate = "RT";
/** Set Type.
@param A_Table_Rate_Type Type */
public void setA_Table_Rate_Type (String A_Table_Rate_Type)
{
set_ValueNoCheck (COLUMNNAME_A_Table_Rate_Type, A_Table_Rate_Type);
}
/** Get Type.
@return Type */
public String getA_Table_Rate_Type ()
{
return (String)get_Value(COLUMNNAME_A_Table_Rate_Type);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Detail.java | 1 |
请完成以下Java代码 | public IAttributeStorage getAttributeStorage(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.getAttributeStorage(model);
}
@Override
public IAttributeStorage getAttributeStorageIfHandled(final Object model)
{
final IAttributeStorageFactory delegate = getDelegate();
return delegate.getAttributeStorageIfHandled(model);
}
@Override
public final IHUAttributesDAO getHUAttributesDAO()
{ // TODO tbp: this exception is false: this.huAttributesDAO is NOT NULL!
throw new HUException("No IHUAttributesDAO found on " + this);
}
@Override
public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
{
this.huAttributesDAO = huAttributesDAO;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUAttributesDAO(huAttributesDAO);
}
}
@Override
public IHUStorageDAO getHUStorageDAO() | {
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
//
// Update factory if is instantiated
if (factory != null)
{
factory.setHUStorageFactory(huStorageFactory);
}
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
return huStorageFactory;
}
@Override
public void flush()
{
final IHUAttributesDAO huAttributesDAO = this.huAttributesDAO;
if (huAttributesDAO != null)
{
huAttributesDAO.flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\ClassAttributeStorageFactory.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {
}
@Override
public String getExecutionId() {
return null;
}
// non-supported (v6)
@Override
public String getScopeId() {
return null;
}
@Override
public String getSubScopeId() {
return null;
}
@Override
public String getScopeType() {
return null;
}
@Override
public void setScopeId(String scopeId) { | }
@Override
public void setSubScopeId(String subScopeId) {
}
@Override
public void setScopeType(String scopeType) {
}
@Override
public String getScopeDefinitionId() {
return null;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
}
@Override
public String getMetaInfo() {
return null;
}
@Override
public void setMetaInfo(String metaInfo) {
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java | 1 |
请完成以下Java代码 | public int read() throws IOException {
return inputStream.read();
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override
public synchronized void mark(int readlimit) {
inputStream.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
inputStream.reset();
}
@Override | public boolean markSupported() {
return inputStream.markSupported();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return EmptyBodyFilter.this.getReader(this.getInputStream());
}
};
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\filter\EmptyBodyFilter.java | 1 |
请完成以下Java代码 | public class OrderGroupCompensationUtils
{
public static void assertCompensationLine(final I_C_OrderLine groupOrderLine)
{
if (!groupOrderLine.isGroupCompensationLine())
{
throw new AdempiereException("Order line " + groupOrderLine.getLine() + " shall be a compensation line");
}
}
public static void assertInGroup(final I_C_OrderLine orderLine)
{
if (!isInGroup(orderLine))
{
throw new AdempiereException("Order line " + orderLine.getLine() + " shall be part of a compensation group");
}
}
public static void assertNotInGroup(final I_C_OrderLine orderLine)
{
if (isInGroup(orderLine))
{
throw new AdempiereException("Order line " + orderLine.getLine() + " shall NOT be part of a compensation group");
}
}
public static boolean isInGroup(final I_C_OrderLine orderLine)
{
return orderLine.getC_Order_CompensationGroup_ID() > 0;
}
public static boolean isNotInGroup(final I_C_OrderLine orderLine)
{
return !isInGroup(orderLine);
}
public static BigDecimal adjustAmtByCompensationType(@NonNull final BigDecimal compensationAmt, @NonNull final GroupCompensationType compensationType)
{
if (compensationType == GroupCompensationType.Discount)
{
return compensationAmt.negate();
} | else if (compensationType == GroupCompensationType.Surcharge)
{
return compensationAmt;
}
else
{
throw new AdempiereException("Unknown compensationType: " + compensationType);
}
}
public static boolean isGeneratedLine(final I_C_OrderLine orderLine)
{
final GroupTemplateLineId groupSchemaLineId = extractGroupTemplateLineId(orderLine);
return isGeneratedLine(groupSchemaLineId);
}
@Nullable
public static GroupTemplateLineId extractGroupTemplateLineId(@NonNull final I_C_OrderLine orderLine)
{
return GroupTemplateLineId.ofRepoIdOrNull(orderLine.getC_CompensationGroup_SchemaLine_ID());
}
public static boolean isGeneratedLine(@Nullable final GroupTemplateLineId groupSchemaLineId)
{
return groupSchemaLineId != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\OrderGroupCompensationUtils.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isEnded() {
return ended;
}
public void setEnded(boolean ended) { | this.ended = ended;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public boolean isCurrent() {
return current;
}
public void setCurrent(boolean current) {
this.current = current;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\StageResponse.java | 1 |
请完成以下Java代码 | public class ServiceLevelSEPA {
@XmlElement(name = "Cd", required = true)
protected String cd;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd; | }
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\ServiceLevelSEPA.java | 1 |
请完成以下Java代码 | public Object getValue(ELContext context, Object base, Object property) {
if (base == null) {
// according to javadoc, can only be a String
String key = (String) property;
if (applicationContext.containsBean(key)) {
context.setPropertyResolved(true);
return applicationContext.getBean(key);
}
}
return null;
}
public boolean isReadOnly(ELContext context, Object base, Object property) {
return true;
}
public void setValue(ELContext context, Object base, Object property, Object value) {
if (base == null) {
String key = (String) property;
if (applicationContext.containsBean(key)) {
throw new ActivitiException(
"Cannot set value of '" + | property +
"', it resolves to a bean defined in the Spring application-context."
);
}
}
}
public Class<?> getCommonPropertyType(ELContext context, Object arg) {
return Object.class;
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object arg) {
return null;
}
public Class<?> getType(ELContext context, Object arg1, Object arg2) {
return Object.class;
}
} | repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\ApplicationContextElResolver.java | 1 |
请完成以下Java代码 | public IInvoiceCandInvalidUpdater setTaggedWithNoTag()
{
assertNotExecuted();
icTagger.setTaggedWithNoTag();
return this;
}
@Override
public IInvoiceCandInvalidUpdater setTaggedWithAnyTag()
{
assertNotExecuted();
icTagger.setTaggedWithAnyTag();
return this;
}
@Override
public IInvoiceCandInvalidUpdater setLimit(final int limit)
{
assertNotExecuted();
icTagger.setLimit(limit);
return this;
}
@Override
public IInvoiceCandInvalidUpdater setRecomputeTagToUse(final InvoiceCandRecomputeTag tag)
{
assertNotExecuted();
icTagger.setRecomputeTag(tag);
return this;
}
@Override
public IInvoiceCandInvalidUpdater setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds)
{
assertNotExecuted();
icTagger.setOnlyInvoiceCandidateIds(onlyInvoiceCandidateIds);
return this;
}
private int getItemsPerBatch()
{
return sysConfigBL.getIntValue(SYSCONFIG_ItemsPerBatch, DEFAULT_ItemsPerBatch);
}
/**
* IC update result.
*
* @author metas-dev <dev@metasfresh.com>
*/
private static final class ICUpdateResult
{
private int countOk = 0;
private int countErrors = 0;
public void addInvoiceCandidate()
{
countOk++;
}
public void incrementErrorsCount()
{
countErrors++;
} | @Override
public String toString()
{
return getSummary();
}
public String getSummary()
{
return "Updated " + countOk + " invoice candidates, " + countErrors + " errors";
}
}
/**
* IC update exception handler
*/
private final class ICTrxItemExceptionHandler extends FailTrxItemExceptionHandler
{
private final ICUpdateResult result;
public ICTrxItemExceptionHandler(@NonNull final ICUpdateResult result)
{
this.result = result;
}
/**
* Resets the given IC to its old values, and sets an error flag in it.
*/
@Override
public void onItemError(final Throwable e, final Object item)
{
result.incrementErrorsCount();
final I_C_Invoice_Candidate ic = InterfaceWrapperHelper.create(item, I_C_Invoice_Candidate.class);
// gh #428: don't discard changes that were already made, because they might include a change of QtyInvoice.
// in that case, a formerly Processed IC might need to be flagged as unprocessed.
// if we discard all changes in this case, then we will have IsError='Y' and also an error message in the IC,
// but the user will probably ignore it, because the IC is still flagged as processed.
invoiceCandBL.setError(ic, e);
// invoiceCandBL.discardChangesAndSetError(ic, e);
invoiceCandDAO.save(ic);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandInvalidUpdater.java | 1 |
请完成以下Java代码 | public static void setUp() {
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
databaseName = "baeldung";
collectionName = "pet";
database = mongoClient.getDatabase(databaseName);
collection = database.getCollection(collectionName);
}
}
public static void addFieldToExistingBsonFilter() {
Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
Bson newFilter = and(existingFilter, gt("age", 5));
FindIterable<Document> documents = collection.find(newFilter);
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void addFieldToExistingBsonFilterUsingBsonDocument() {
Bson existingFilter = eq("type", "Dog");
BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
Bson newFilter = gt("age", 5);
BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
existingBsonDocument.append("age", newBsonDocument.get("age")); | FindIterable<Document> documents = collection.find(existingBsonDocument);
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void main(String args[]) {
setUp();
addFieldToExistingBsonFilter();
addFieldToExistingBsonFilterUsingBsonDocument();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\insert\InsertFieldIntoFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@OneToMany
@Cascade(CascadeType.ALL)
private List<Article> articles;
public Author(String name) {
this.name = name;
} | public Author() {
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
public void addArticles(List<Article> articles) {
this.articles = articles;
articles.forEach(article -> article.setAuthor(this));
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions-2\src\main\java\com\baeldung\hibernate\exception\persistentobject\entity\Author.java | 2 |
请完成以下Java代码 | public static void sendHTMLTextWithEmbeddedImageEmail() {
String htmlContent = "<h1>This is an email with HTML content</h1>" + "<p>This email body contains additional information and formatting.</p>" +
"<img src=\"cid:company_logo\" alt=\"Company Logo\">";
Email email = EmailBuilder.startingBlank()
.from("sender@example.com")
.to("recipient@example.com")
.withSubject("Email with HTML and Embedded Image!")
.withHTMLText(htmlContent)
.withEmbeddedImage("company_logo", new FileDataSource("path/to/company_logo.png"))
.buildEmail();
sendEmail(email);
}
public static void replyingToEmail(Email receivedEmail) {
EmailBuilder.replyingTo(receivedEmail)
.from("sender@example.com")
.prependText("This is a Reply Email. Original email included below:")
.buildEmail();
}
public static void forwardingEmail(Email receivedEmail) {
Email email = EmailBuilder.forwarding(receivedEmail)
.from("sender@example.com")
.prependText("This is an Forward Email. See below email:")
.buildEmail();
}
public static void handleExceptionWhenSendingEmail() {
try {
sendPlainTextEmail();
System.out.println("Email sent successfully!");
} catch (MailException e) {
System.err.println("Error: " + e.getMessage());
}
}
public static void setCustomHeaderWhenSendingEmail() {
Email email = EmailBuilder.startingBlank()
.from("sender@example.com")
.to("recipient@example.com")
.withSubject("Email with Custom Header")
.withPlainText("This is an important message.")
.withHeader("X-Priority", "1")
.buildEmail();
sendEmail(email);
}
private static void sendEmailWithDeliveryReadRecipient() {
Email email = EmailBuilder.startingBlank()
.from("sender@example.com") | .to("recipient@example.com")
.withSubject("Email with Delivery/Read Receipt Configured!")
.withPlainText("This is an email sending with delivery/read receipt.")
.withDispositionNotificationTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO))
.withReturnReceiptTo(new Recipient("name", "address@domain.com", Message.RecipientType.TO))
.buildEmail();
sendEmail(email);
}
private static void sendEmail(Email email) {
Mailer mailer = MailerBuilder.withSMTPServer("smtp.example.com", 25, "username", "password")
.withMaximumEmailSize(1024 * 1024 * 5) // 5 Megabytes
.buildMailer();
boolean validate = mailer.validate(email);
if (validate) {
mailer.sendMail(email);
} else {
System.out.println("Invalid email address.");
}
}
} | repos\tutorials-master\libraries-io\src\main\java\com\baeldung\java\io\simplemail\SimpleMailExample.java | 1 |
请完成以下Java代码 | public static String usingSplitMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
String[] results = text.split("(?<=\\G.{" + length + "})");
return results[0];
}
public static String usingPattern(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Optional<String> result = Pattern.compile(".{1," + length + "}")
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : EMPTY;
}
public static String usingCodePointsMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
return text.codePoints()
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
} | public static String usingLeftMethod(String text, int length) {
return StringUtils.left(text, length);
}
public static String usingTruncateMethod(String text, int length) {
return StringUtils.truncate(text, length);
}
public static String usingSplitter(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Iterable<String> parts = Splitter.fixedLength(length)
.split(text);
return parts.iterator()
.next();
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\truncate\TruncateString.java | 1 |
请完成以下Java代码 | public String getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTp(String value) {
this.tp = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id; | }
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = 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\AlternateSecurityIdentification2.java | 1 |
请完成以下Java代码 | public boolean isNull(final Object model, final String columnName)
{
final Document document = DocumentInterfaceWrapper.getDocument(model);
final IDocumentFieldView field = document.getFieldViewOrNull(columnName);
if(field == null)
{
return true;
}
final Object value = field.getValue();
return value == null;
}
@Override
public <T> T getDynAttribute(final @NonNull Object model, final String attributeName)
{
return DocumentInterfaceWrapper.getDocument(model).getDynAttribute(attributeName);
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return DocumentInterfaceWrapper.getDocument(model).setDynAttribute(attributeName, value);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
if (strict)
{ | return null;
}
final Document document = DocumentInterfaceWrapper.getDocument(model);
if (document == null)
{
throw new AdempiereException("Cannot extract " + Document.class + " from " + model);
}
final String tableName = document.getEntityDescriptor().getTableName();
final boolean checkCache = false;
@SuppressWarnings("unchecked")
final T po = (T)TableModelLoader.instance.getPO(document.getCtx(), tableName, document.getDocumentIdAsInt(), checkCache, ITrx.TRXNAME_ThreadInherited);
return po;
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
return DocumentInterfaceWrapper.getDocument(model).asEvaluatee();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentInterfaceWrapperHelper.java | 1 |
请完成以下Java代码 | public void doStart() {
List<ProcessDefinition> processDefinitions = converter.from(
repositoryService.createProcessDefinitionQuery().latestVersion().list()
);
List<ProcessDeployedEvent> processDeployedEvents = new ArrayList<>();
for (ProcessDefinition processDefinition : processDefinitions) {
try (InputStream inputStream = repositoryService.getProcessModel(processDefinition.getId())) {
String xmlModel = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
ProcessDeployedEventImpl processDeployedEvent = new ProcessDeployedEventImpl(
processDefinition,
xmlModel
);
processDeployedEvents.add(processDeployedEvent);
for (ProcessRuntimeEventListener<ProcessDeployedEvent> listener : listeners) {
listener.onEvent(processDeployedEvent);
}
} catch (IOException e) {
throw new ActivitiException( | "Error occurred while getting process model '" + processDefinition.getId() + "' : ",
e
);
}
}
if (!processDeployedEvents.isEmpty()) {
eventPublisher.publishEvent(new ProcessDeployedEvents(processDeployedEvents));
}
}
@Override
public void doStop() {
// nothing
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\ProcessDeployedEventProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReactiveUploadService {
private final WebClient webClient;
private static final String EXTERNAL_UPLOAD_URL = "http://localhost:8080/external/upload";
public ReactiveUploadService(final WebClient webClient) {
this.webClient = webClient;
}
public Mono<HttpStatusCode> uploadPdf(final Resource resource) {
final URI url = UriComponentsBuilder.fromHttpUrl(EXTERNAL_UPLOAD_URL).build().toUri();
Mono<HttpStatusCode> httpStatusMono = webClient.post()
.uri(url)
.contentType(MediaType.APPLICATION_PDF)
.body(BodyInserters.fromResource(resource))
.exchangeToMono(response -> {
if (response.statusCode().equals(HttpStatus.OK)) {
return response.bodyToMono(HttpStatus.class).thenReturn(response.statusCode());
} else {
throw new ServiceException("Error uploading file");
}
});
return httpStatusMono;
}
public Mono<HttpStatusCode> uploadMultipart(final MultipartFile multipartFile) {
final URI url = UriComponentsBuilder.fromHttpUrl(EXTERNAL_UPLOAD_URL).build().toUri(); | final MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("file", multipartFile.getResource());
Mono<HttpStatusCode> httpStatusMono = webClient.post()
.uri(url)
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(builder.build()))
.exchangeToMono(response -> {
if (response.statusCode().equals(HttpStatus.OK)) {
return response.bodyToMono(HttpStatus.class).thenReturn(response.statusCode());
} else {
throw new ServiceException("Error uploading file");
}
});
return httpStatusMono;
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-client-2\src\main\java\com\baeldung\service\ReactiveUploadService.java | 2 |
请完成以下Java代码 | public static IPricingResult getPreviouslyCalculatedPricingResultOrNull(@NonNull final I_C_OLCand olCand)
{
return DYNATTR_OLCAND_PRICEVALIDATOR_PRICING_RESULT.getValue(olCand);
}
/**
* Validates the UOM conversion; we will need convertToProductUOM in order to get the QtyOrdered in the order line.
*/
private void validateUOM(@NonNull final I_C_OLCand olCand)
{
final ProductId productId = olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand);
final I_C_UOM targetUOMRecord = olCandEffectiveValuesBL.getC_UOM_Effective(olCand);
if (uomsDAO.isUOMForTUs(UomId.ofRepoId(targetUOMRecord.getC_UOM_ID())))
{
if (olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand).signum() <= 0)
{
throw new AdempiereException(ERR_ITEM_CAPACITY_NOT_FOUND);
}
return;
} | final BigDecimal convertedQty = uomConversionBL.convertToProductUOM(
productId,
targetUOMRecord,
olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand));
if (convertedQty == null)
{
final String productName = productBL.getProductName(productId);
final String productValue = productBL.getProductValue(productId);
final String productX12de355 = productBL.getStockUOM(productId).getX12DE355();
final String targetX12de355 = targetUOMRecord.getX12DE355();
throw new AdempiereException(MSG_NO_UOM_CONVERSION, productValue + "_" + productName, productX12de355, targetX12de355).markAsUserValidationError();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\DefaultOLCandValidator.java | 1 |
请完成以下Java代码 | public void onAfterQuery(final ICalloutRecord calloutRecord)
{
updateFacets(calloutRecord);
}
@Override
public void onRefreshAll(final ICalloutRecord calloutRecord)
{
// NOTE: we are not updating the facets on refresh all because following case would fail:
// Case: user is pressing the "Refresh" toolbar button to refresh THE content of the grid,
// but user is not expecting to have all it's facets reset.
// updateFacets(gridTab);
}
/**
* Retrieve facets from current grid tab rows and add them to window side panel
*
* @param calloutRecord
*/ | private void updateFacets(final ICalloutRecord calloutRecord)
{
//
// If user asked to approve for invoicing some ICs, the grid will be asked to refresh all,
// but in this case we don't want to reset current facets and recollect them
if (action_CreatePurchaseOrders.isRunning())
{
return;
}
//
// Collect the facets from current grid tab rows and fully update the facets pool.
gridTabFacetExecutor.collectFacetsAndResetPool();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\callout\PMM_PurchaseCandidate_TabCallout.java | 1 |
请完成以下Java代码 | public TopicSubscriptionBuilder includeExtensionProperties(boolean includeExtensionProperties) {
this.includeExtensionProperties = includeExtensionProperties;
return this;
}
public TopicSubscription open() {
if (topicName == null) {
throw LOG.topicNameNullException();
}
if (lockDuration != null && lockDuration <= 0L) {
throw LOG.lockDurationIsNotGreaterThanZeroException(lockDuration);
}
if (externalTaskHandler == null) {
throw LOG.externalTaskHandlerNullException();
}
TopicSubscriptionImpl subscription = new TopicSubscriptionImpl(topicName, lockDuration, externalTaskHandler, topicSubscriptionManager, variableNames, businessKey);
if (processDefinitionId != null) {
subscription.setProcessDefinitionId(processDefinitionId);
}
if (processDefinitionIds != null) {
subscription.setProcessDefinitionIdIn(processDefinitionIds);
}
if (processDefinitionKey != null) {
subscription.setProcessDefinitionKey(processDefinitionKey);
}
if (processDefinitionKeys != null) {
subscription.setProcessDefinitionKeyIn(processDefinitionKeys);
}
if (withoutTenantId) {
subscription.setWithoutTenantId(withoutTenantId);
}
if (tenantIds != null) {
subscription.setTenantIdIn(tenantIds);
}
if(processDefinitionVersionTag != null) {
subscription.setProcessDefinitionVersionTag(processDefinitionVersionTag);
}
if (processVariables != null) {
subscription.setProcessVariables(processVariables); | }
if (localVariables) {
subscription.setLocalVariables(localVariables);
}
if(includeExtensionProperties) {
subscription.setIncludeExtensionProperties(includeExtensionProperties);
}
topicSubscriptionManager.subscribe(subscription);
return subscription;
}
protected void ensureNotNull(Object tenantIds, String parameterName) {
if (tenantIds == null) {
throw LOG.passNullValueParameter(parameterName);
}
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\topic\impl\TopicSubscriptionBuilderImpl.java | 1 |
请完成以下Java代码 | public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
}
@Override
public int getDerivedVersion() {
return derivedVersion;
}
@Override
public void setDerivedVersion(int derivedVersion) {
this.derivedVersion = derivedVersion;
}
@Override
public String getEngineVersion() {
return engineVersion;
} | @Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
@Override
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public void setMedicalAidPositionNumber (final @Nullable String MedicalAidPositionNumber)
{
set_Value (COLUMNNAME_MedicalAidPositionNumber, MedicalAidPositionNumber);
}
@Override
public String getMedicalAidPositionNumber()
{
return get_ValueAsString(COLUMNNAME_MedicalAidPositionNumber);
}
/**
* PurchaseRating AD_Reference_ID=541279
* Reference name: PurchaseRating
*/
public static final int PURCHASERATING_AD_Reference_ID=541279;
/** A = A */
public static final String PURCHASERATING_A = "A";
/** B = B */
public static final String PURCHASERATING_B = "B";
/** C = C */
public static final String PURCHASERATING_C = "C";
/** D = D */
public static final String PURCHASERATING_D = "D";
/** E = E */
public static final String PURCHASERATING_E = "E";
/** F = F */ | public static final String PURCHASERATING_F = "F";
/** G = G */
public static final String PURCHASERATING_G = "G";
@Override
public void setPurchaseRating (final @Nullable String PurchaseRating)
{
set_Value (COLUMNNAME_PurchaseRating, PurchaseRating);
}
@Override
public String getPurchaseRating()
{
return get_ValueAsString(COLUMNNAME_PurchaseRating);
}
@Override
public void setSize (final @Nullable String Size)
{
set_Value (COLUMNNAME_Size, Size);
}
@Override
public String getSize()
{
return get_ValueAsString(COLUMNNAME_Size);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaArticle.java | 1 |
请完成以下Java代码 | 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 Window Internal Name.
@param WindowInternalName Window Internal Name */
@Override
public void setWindowInternalName (java.lang.String WindowInternalName)
{
set_Value (COLUMNNAME_WindowInternalName, WindowInternalName);
}
/** Get Window Internal Name.
@return Window Internal Name */
@Override
public java.lang.String getWindowInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_WindowInternalName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_I_DataEntry_Record.java | 1 |
请完成以下Java代码 | public void setC_Country_ID (final int C_Country_ID)
{
if (C_Country_ID < 1)
set_Value (COLUMNNAME_C_Country_ID, null);
else
set_Value (COLUMNNAME_C_Country_ID, C_Country_ID);
}
@Override
public int getC_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Country_ID);
}
@Override
public void setC_TaxCategory_ID (final int C_TaxCategory_ID)
{
if (C_TaxCategory_ID < 1)
set_Value (COLUMNNAME_C_TaxCategory_ID, null);
else
set_Value (COLUMNNAME_C_TaxCategory_ID, C_TaxCategory_ID);
}
@Override
public int getC_TaxCategory_ID()
{
return get_ValueAsInt(COLUMNNAME_C_TaxCategory_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Product_TaxCategory_ID (final int M_Product_TaxCategory_ID)
{
if (M_Product_TaxCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_TaxCategory_ID, M_Product_TaxCategory_ID);
}
@Override
public int getM_Product_TaxCategory_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_TaxCategory_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_TaxCategory.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.