instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class JavaCompilerUtils {
private final JavaCompiler compiler;
private final StandardJavaFileManager standardFileManager;
private final Path outputDirectory;
private static final Logger logger = LoggerFactory.getLogger(JavaCompilerUtils.class);
public JavaCompilerUtils(Path outputDirectory) throws IOException {
this.outputDirectory = outputDirectory;
this.compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new IllegalStateException("Java compiler not available. Ensure you're using JDK, not JRE.");
}
this.standardFileManager = compiler.getStandardFileManager(null, null, StandardCharsets.UTF_8);
if (!Files.exists(outputDirectory)) {
Files.createDirectories(outputDirectory);
}
standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(outputDirectory.toFile()));
}
public boolean compileFile(Path sourceFile) {
if (!Files.exists(sourceFile)) {
throw new IllegalArgumentException("Source file does not exist: " + sourceFile);
}
try {
Iterable<? extends JavaFileObject> compilationUnits =
standardFileManager.getJavaFileObjectsFromFiles(Collections.singletonList(sourceFile.toFile()));
return compile(compilationUnits);
} catch (Exception e) {
logger.error("Compilation failed: ", e);
return false;
}
}
public boolean compileFromString(String className, String sourceCode) { | JavaFileObject sourceObject = new InMemoryJavaFile(className, sourceCode);
return compile(Collections.singletonList(sourceObject));
}
private boolean compile(Iterable<? extends JavaFileObject> compilationUnits) {
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
JavaCompiler.CompilationTask task = compiler.getTask(
null,
standardFileManager,
diagnostics,
null,
null,
compilationUnits
);
boolean success = task.call();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
logger.debug(diagnostic.getMessage(null));
}
return success;
}
public void runClass(String className, String... args) throws Exception {
try (URLClassLoader classLoader = new URLClassLoader(new URL[]{outputDirectory.toUri().toURL()})) {
Class<?> loadedClass = classLoader.loadClass(className);
loadedClass.getMethod("main", String[].class).invoke(null, (Object) args);
}
}
public Path getOutputDirectory() {
return outputDirectory;
}
} | repos\tutorials-master\core-java-modules\core-java-compiler\src\main\java\com\baeldung\compilerapi\JavaCompilerUtils.java | 1 |
请完成以下Java代码 | public PageData<ApiKeyInfo> findApiKeysByUserId(TenantId tenantId, UserId userId, PageLink pageLink) {
log.trace("Executing findApiKeysByUserId [{}][{}]", tenantId, userId);
validateId(userId, id -> INCORRECT_USER_ID + id);
return apiKeyInfoDao.findByUserId(tenantId, userId, pageLink);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findApiKeyById(tenantId, new ApiKeyId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(apiKeyDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public void deleteApiKey(TenantId tenantId, ApiKey apiKey, boolean force) {
UUID apiKeyId = apiKey.getUuidId();
validateId(apiKeyId, id -> INCORRECT_API_KEY_ID + id);
apiKeyDao.removeById(tenantId, apiKeyId);
publishEvictEvent(new ApiKeyEvictEvent(apiKey.getValue()));
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteApiKeysByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
Set<String> values = apiKeyDao.deleteByTenantId(tenantId);
values.forEach(value -> publishEvictEvent(new ApiKeyEvictEvent(value)));
}
@Override
public void deleteByUserId(TenantId tenantId, UserId userId) {
log.trace("Executing deleteApiKeysByUserId, tenantId [{}]", tenantId); | validateId(userId, id -> INCORRECT_USER_ID + id);
Set<String> values = apiKeyDao.deleteByUserId(tenantId, userId);
values.forEach(value -> publishEvictEvent(new ApiKeyEvictEvent(value)));
}
@Override
public ApiKey findApiKeyByValue(String value) {
log.trace("Executing findApiKeyByValue [{}]", value);
var cacheKey = ApiKeyCacheKey.of(value);
return cache.getAndPutInTransaction(cacheKey, () -> apiKeyDao.findByValue(value), true);
}
private String generateApiKeySecret() {
return prefix + StringUtils.generateSafeToken(Math.min(valueBytesSize, MAX_API_KEY_VALUE_LENGTH));
}
@Override
public EntityType getEntityType() {
return EntityType.API_KEY;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\pat\ApiKeyServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
} | @Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java | 2 |
请完成以下Java代码 | public Object getNextValue()
{
int minutes = ((Integer)getValue()).intValue();
minutes += m_snapSize;
if (minutes >= 60)
minutes -= 60;
//
int steps = minutes / m_snapSize;
return steps * m_snapSize;
} // getNextValue
/**
* Return previous full step value
*
* @return previous snap value
*/
@Override | public Object getPreviousValue()
{
int minutes = ((Integer)getValue()).intValue();
minutes -= m_snapSize;
if (minutes < 0)
minutes += 60;
//
int steps = minutes / m_snapSize;
if (minutes % m_snapSize != 0)
steps++;
if (steps * m_snapSize > 59)
steps = 0;
return steps * m_snapSize;
} // getNextValue
} // MinuteModel
} // Calendar | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Calendar.java | 1 |
请完成以下Java代码 | private I_AD_Migration getCreateMigration(final IMigrationLoggerContext mctx, final String entityType)
{
String entityTypeActual = entityType;
if (entityTypeActual == null)
{
entityTypeActual = getDefaultEntityType();
}
final String key = entityTypeActual;
I_AD_Migration migration = mctx.getMigration(key);
if (migration == null
|| !migration.isActive()) // migration was closed, open another one
{
migration = createMigration(Env.getCtx(), entityTypeActual);
mctx.putMigration(key, migration);
}
return migration;
}
protected I_AD_Migration createMigration(final Properties ctx, final String entityType)
{
// this record shall be created out of transaction since it will accessible in more then one transaction
final String trxName = null;
final I_AD_Migration migration = InterfaceWrapperHelper.create(ctx, I_AD_Migration.class, trxName);
migration.setEntityType(entityType);
Services.get(IMigrationBL.class).setSeqNo(migration);
setName(migration);
InterfaceWrapperHelper.save(migration);
return migration;
}
protected void setName(final I_AD_Migration migration)
{
final String name = Services.get(ISysConfigBL.class).getValue("DICTIONARY_ID_COMMENTS"); | migration.setName(name);
}
protected String getDefaultEntityType()
{
boolean dict = Ini.isPropertyBool(Ini.P_ADEMPIERESYS);
return dict ? "D" : "U";
}
protected IMigrationLoggerContext getSessionMigrationLoggerContext(final MFSession session)
{
final String key = getClass().getCanonicalName();
IMigrationLoggerContext mctx = session.getTransientProperty(key);
if (mctx == null)
{
mctx = new SessionMigrationLoggerContext();
session.putTransientProperty(key, mctx);
}
return mctx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\impl\MigrationLogger.java | 1 |
请完成以下Java代码 | public void addTreeCheckingListener(TreeCheckingListener tsl) {
this.checkingModel.addTreeCheckingListener(tsl);
}
/**
* Removes a <code>TreeChecking</code> listener.
*
* @param tsl the <code>TreeChckingListener</code> to remove
*/
public void removeTreeCheckingListener(TreeCheckingListener tsl) {
this.checkingModel.removeTreeCheckingListener(tsl);
}
/**
* Expand completely a tree
*/
public void expandAll() {
expandSubTree(getPathForRow(0));
}
private void expandSubTree(TreePath path) {
expandPath(path);
Object node = path.getLastPathComponent();
int childrenNumber = getModel().getChildCount(node); | TreePath[] childrenPath = new TreePath[childrenNumber];
for (int childIndex = 0; childIndex < childrenNumber; childIndex++) {
childrenPath[childIndex] = path.pathByAddingChild(getModel().getChild(node, childIndex));
expandSubTree(childrenPath[childIndex]);
}
}
/**
* @return a string representation of the tree, including the checking,
* enabling and greying sets.
*/
@Override
public String toString() {
String retVal = super.toString();
TreeCheckingModel tcm = getCheckingModel();
if (tcm != null) {
return retVal + "\n" + tcm.toString();
}
return retVal;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\CheckboxTree.java | 1 |
请完成以下Java代码 | protected IShipmentScheduleSegment createSegmentForInOutLine(final int bPartnerId, final @NonNull I_M_InOutLine inoutLine)
{
final ShipmentScheduleSegmentBuilder storageSegmentBuilder = ShipmentScheduleSegments.builder();
storageSegmentBuilder
.productId(inoutLine.getM_Product_ID())
.locatorId(inoutLine.getM_Locator_ID())
.attributeSetInstanceId(inoutLine.getM_AttributeSetInstance_ID());
final List<I_M_HU> husForInOutLine = huAssignmentDAO.retrieveTopLevelHUsForModel(inoutLine);
if (husForInOutLine.isEmpty())
{
storageSegmentBuilder.bpartnerId(0); // don't restrict to any partner
}
for (final I_M_HU hu : husForInOutLine)
{
storageSegmentBuilder.bpartnerId(hu.getC_BPartner_ID());
}
return storageSegmentBuilder.build();
}
@Override
protected IShipmentScheduleSegment createSegmentForShipmentSchedule(final @NonNull I_M_ShipmentSchedule schedule)
{
boolean maybeCanRestrictToCertainPartners = false; // we will set this to true if there is any TU assigned to the shipment schedule
final ShipmentScheduleSegmentBuilder storageSegmentBuilder = ShipmentScheduleSegments.builder();
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoId(schedule.getM_ShipmentSchedule_ID());
final List<I_M_ShipmentSchedule_QtyPicked> pickedNotDeliveredRecords = shipmentScheduleAllocDAO.retrieveNotOnShipmentLineRecords(shipmentScheduleId, I_M_ShipmentSchedule_QtyPicked.class);
for (final I_M_ShipmentSchedule_QtyPicked pickedNotDeliveredRecord : pickedNotDeliveredRecords) | {
if (pickedNotDeliveredRecord.getM_TU_HU_ID() > 0)
{
maybeCanRestrictToCertainPartners = true;
// note that the C_BPartner_ID might still be 0. If any one of several IDs is 0, then there won't be a restriction.
final I_M_HU tu = pickedNotDeliveredRecord.getM_TU_HU();
storageSegmentBuilder.bpartnerId(tu.getC_BPartner_ID());
}
}
if (!maybeCanRestrictToCertainPartners)
{
// we are sure that we didn't find any C_BPartner_ID. Add one 0 explicitly (required by the logic in ShipmentScheduleDAO).
storageSegmentBuilder.bpartnerId(0); //
}
// finalize the builder and create the segment
return storageSegmentBuilder
.productId(schedule.getM_Product_ID())
.warehouseId(shipmentScheduleEffectiveBL.getWarehouseId(schedule))
.attributeSetInstanceId(schedule.getM_AttributeSetInstance_ID())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\HUShipmentScheduleInvalidateBL.java | 1 |
请完成以下Java代码 | public static String htmlEscape(String input) {
if (StringUtils.hasText(input)) {
//input = input.replaceAll("\\{", "%7B").replaceAll("}", "%7D").replaceAll("\\\\", "%5C");
String htmlStr = HtmlUtils.htmlEscape(input, "UTF-8");
//& -> &
return htmlStr.replace("&", "&");
}
return input;
}
/**
* 通过文件名获取文件后缀
*
* @param fileName 文件名称
* @return 文件后缀
*/
public static String suffixFromFileName(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
}
/**
* 根据文件路径删除文件
*
* @param filePath 绝对路径
*/
public static void deleteFileByPath(String filePath) {
File file = new File(filePath);
if (file.exists() && !file.delete()) {
LOGGER.warn("压缩包源文件删除失败:{}!", filePath);
}
}
/**
* 删除目录及目录下的文件
*
* @param dir 要删除的目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String dir) {
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator)) {
dir = dir + File.separator;
}
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
LOGGER.info("删除目录失败:" + dir + "不存在!");
return false;
}
boolean flag = true;
// 删除文件夹中的所有文件包括子目录 | File[] files = dirFile.listFiles();
for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = KkFileUtils.deleteFileByName(files[i].getAbsolutePath());
if (!flag) {
break;
}
} else if (files[i].isDirectory()) {
// 删除子目录
flag = KkFileUtils.deleteDirectory(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
}
if (!dirFile.delete() || !flag) {
LOGGER.info("删除目录失败!");
return false;
}
return true;
}
/**
* 判断文件是否允许上传
*
* @param file 文件扩展名
* @return 是否允许上传
*/
public static boolean isAllowedUpload(String file) {
String fileType = suffixFromFileName(file);
for (String type : ConfigConstants.getProhibit()) {
if (type.equals(fileType)){
return false;
}
}
return !ObjectUtils.isEmpty(fileType);
}
/**
* 判断文件是否存在
*
* @param filePath 文件路径
* @return 是否存在 true:存在,false:不存在
*/
public static boolean isExist(String filePath) {
File file = new File(filePath);
return file.exists();
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\utils\KkFileUtils.java | 1 |
请完成以下Java代码 | public BigDecimal getPastDue91_Plus ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDue91_Plus);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Past Due.
@param PastDueAmt Past Due */
public void setPastDueAmt (BigDecimal PastDueAmt)
{
set_Value (COLUMNNAME_PastDueAmt, PastDueAmt);
}
/** Get Past Due.
@return Past Due */
public BigDecimal getPastDueAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PastDueAmt);
if (bd == null)
return Env.ZERO; | return bd;
}
/** Set Statement date.
@param StatementDate
Date of the statement
*/
public void setStatementDate (Timestamp StatementDate)
{
set_Value (COLUMNNAME_StatementDate, StatementDate);
}
/** Get Statement date.
@return Date of the statement
*/
public Timestamp getStatementDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StatementDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Aging.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void registerStompEndpoints(@NonNull final StompEndpointRegistry registry)
{
registry.addEndpoint("/stomp")
.setAllowedOriginPatterns("http://*", "https://*")
.withSockJS();
}
@Override
public void configureMessageBroker(@NonNull final MessageBrokerRegistry config)
{
// use the /topic prefix for outgoing Websocket communication
config.enableSimpleBroker(topicNamePrefixes.toArray(new String[0]));
logger.info("configureMessageBroker: topicNamePrefixes={}", topicNamePrefixes);
// use the /app prefix for others
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void configureClientOutboundChannel(@NonNull final ChannelRegistration registration)
{
//
// IMPORTANT: make sure we are using only one thread for sending outbound messages.
// If not, it might be that the messages will not be sent in the right order,
// and that's important for things like WS notifications API.
// ( thanks to http://stackoverflow.com/questions/29689838/sockjs-receive-stomp-messages-from-spring-websocket-out-of-order )
registration.taskExecutor()
.corePoolSize(1)
.maxPoolSize(1);
}
@Override
public void configureClientInboundChannel(final ChannelRegistration registration)
{
registration.interceptors(new LoggingChannelInterceptor());
// NOTE: atm we don't care if the inbound messages arrived in the right order
// When and If we would care we would restrict the taskExecutor()'s corePoolSize to ONE.
// see: configureClientOutboundChannel().
}
@Override
public boolean configureMessageConverters(final List<MessageConverter> messageConverters)
{
final MappingJackson2MessageConverter jsonConverter = new MappingJackson2MessageConverter();
jsonConverter.setObjectMapper(JsonObjectMapperHolder.sharedJsonObjectMapper());
messageConverters.add(jsonConverter);
return true; | }
private static class LoggingChannelInterceptor implements ChannelInterceptor
{
private static final Logger logger = LogManager.getLogger(LoggingChannelInterceptor.class);
@Override
public void afterSendCompletion(final @NonNull Message<?> message, final @NonNull MessageChannel channel, final boolean sent, final Exception ex)
{
if (!sent)
{
logger.warn("Failed sending: message={}, channel={}, sent={}", message, channel, sent, ex);
}
}
@Override
public void afterReceiveCompletion(final Message<?> message, final @NonNull MessageChannel channel, final Exception ex)
{
if (ex != null)
{
logger.warn("Failed receiving: message={}, channel={}", message, channel, ex);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\config\WebsocketConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static PPOrderBOMLineId extractOrderBOMLineId(@NonNull final I_PP_Order_BOMLine record)
{
return PPOrderBOMLineId.ofRepoId(record.getPP_Order_BOMLine_ID());
}
private List<I_M_HU> splitOutCUsFromSourceHUs(@NonNull final ProductId productId, @NonNull final Quantity qtyCU)
{
final SourceHUsCollection sourceHUsCollection = getSourceHUsCollectionProvider().getByProductId(productId);
if (sourceHUsCollection.isEmpty())
{
return ImmutableList.of();
}
return HUTransformService.builder()
.emptyHUListener(
EmptyHUListener.doBeforeDestroyed(hu -> sourceHUsCollection
.getSourceHU(HuId.ofRepoId(hu.getM_HU_ID()))
.ifPresent(sourceHUsService::snapshotSourceHU),
"Create snapshot of source-HU before it is destroyed")
)
.build()
.husToNewCUs(
HUsToNewCUsRequest.builder()
.sourceHUs(sourceHUsCollection.getHusThatAreFlaggedAsSource())
.productId(productId)
.qtyCU(qtyCU)
.build()
)
.getNewCUs();
} | private void createIssueSchedule(final I_PP_Order_Qty ppOrderQtyRecord)
{
final Quantity qtyIssued = Quantitys.of(ppOrderQtyRecord.getQty(), UomId.ofRepoId(ppOrderQtyRecord.getC_UOM_ID()));
issueScheduleService.createSchedule(
PPOrderIssueScheduleCreateRequest.builder()
.ppOrderId(ppOrderId)
.ppOrderBOMLineId(PPOrderBOMLineId.ofRepoId(ppOrderQtyRecord.getPP_Order_BOMLine_ID()))
.seqNo(SeqNo.ofInt(0))
.productId(ProductId.ofRepoId(ppOrderQtyRecord.getM_Product_ID()))
.qtyToIssue(qtyIssued)
.issueFromHUId(HuId.ofRepoId(ppOrderQtyRecord.getM_HU_ID()))
.issueFromLocatorId(warehouseDAO.getLocatorIdByRepoId(ppOrderQtyRecord.getM_Locator_ID()))
.isAlternativeIssue(true)
.qtyIssued(qtyIssued)
.build()
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\issue_what_was_received\IssueWhatWasReceivedCommand.java | 2 |
请完成以下Java代码 | public String toString ()
{
StringBuffer sb = new StringBuffer ("MReport[")
.append(get_ID()).append(" - ").append(getName());
if (getDescription() != null)
sb.append("(").append(getDescription()).append(")");
sb.append(" - C_AcctSchema_ID=").append(getC_AcctSchema_ID())
.append(", C_Calendar_ID=").append(getC_Calendar_ID());
sb.append ("]");
return sb.toString ();
} // toString
/**
* Get Column Set
* @return Column Set | */
public MReportColumnSet getColumnSet()
{
return m_columnSet;
}
/**
* Get Line Set
* @return Line Set
*/
public MReportLineSet getLineSet()
{
return m_lineSet;
}
} // MReport | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String getUOMCode(@Nullable final String unitId)
{
if (unitId == null)
{
processLogger.logMessage("Shopware unit id is null, fallback to default UOM: PCE ! ProductId: " + product.getId(),
routeContext.getPInstanceId());
return DEFAULT_PRODUCT_UOM;
}
if (routeContext.getUomMappings().isEmpty())
{
processLogger.logMessage("No UOM mappings found in the route context, fallback to default UOM: PCE ! ProductId: " + product.getId(),
routeContext.getPInstanceId());
return DEFAULT_PRODUCT_UOM;
}
final String externalCode = routeContext.getShopwareUomInfoProvider().getCode(unitId); | if (externalCode == null)
{
processLogger.logMessage("No externalCode found for unit id: " + unitId + ", fallback to default UOM: PCE ! ProductId: " + product.getId(),
routeContext.getPInstanceId());
return DEFAULT_PRODUCT_UOM;
}
final JsonUOM jsonUOM = routeContext.getUomMappings().get(externalCode);
if (jsonUOM == null)
{
processLogger.logMessage("No UOM mapping found for externalCode: " + externalCode + " ! fallback to default UOM: PCE ! ProductId: " + product.getId(),
routeContext.getPInstanceId());
return DEFAULT_PRODUCT_UOM;
}
return jsonUOM.getCode();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\ProductUpsertRequestProducer.java | 2 |
请完成以下Java代码 | public class X_ExternalSystem_Other_ConfigParameter extends org.compiere.model.PO implements I_ExternalSystem_Other_ConfigParameter, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1879854408L;
/** Standard Constructor */
public X_ExternalSystem_Other_ConfigParameter (final Properties ctx, final int ExternalSystem_Other_ConfigParameter_ID, @Nullable final String trxName)
{
super (ctx, ExternalSystem_Other_ConfigParameter_ID, trxName);
}
/** Load Constructor */
public X_ExternalSystem_Other_ConfigParameter (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public I_ExternalSystem_Config getExternalSystem_Config()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class);
}
@Override
public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override | public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setExternalSystem_Other_ConfigParameter_ID (final int ExternalSystem_Other_ConfigParameter_ID)
{
if (ExternalSystem_Other_ConfigParameter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID, ExternalSystem_Other_ConfigParameter_ID);
}
@Override
public int getExternalSystem_Other_ConfigParameter_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Other_ConfigParameter_ID);
}
@Override
public void setName (final String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Other_ConfigParameter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void putCancelQuit(List<String> userIds, Integer tenantId) {
userTenantMapper.putCancelQuit(userIds, tenantId);
}
@Override
public Integer userTenantIzExist(String userId, Integer tenantId) {
return userTenantMapper.userTenantIzExist(userId,tenantId);
}
@Override
public IPage<SysTenant> getTenantPageListByUserId(Page<SysTenant> page, String userId, List<String> userTenantStatus,SysUserTenantVo sysUserTenantVo) {
return page.setRecords(userTenantMapper.getTenantPageListByUserId(page,userId,userTenantStatus,sysUserTenantVo));
}
@CacheEvict(value={CacheConstant.SYS_USERS_CACHE}, allEntries=true)
@Override
public void agreeJoinTenant(String userId, Integer tenantId) {
userTenantMapper.agreeJoinTenant(userId,tenantId);
} | @Override
public void refuseJoinTenant(String userId, Integer tenantId) {
userTenantMapper.refuseJoinTenant(userId,tenantId);
}
@Override
public SysUserTenant getUserTenantByTenantId(String userId, Integer tenantId) {
return userTenantMapper.getUserTenantByTenantId(userId,tenantId);
}
@Override
public Long getUserCount(Integer tenantId, String tenantStatus) {
return userTenantMapper.getUserCount(tenantId,tenantStatus);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysUserTenantServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String addUI() {
return "pay/product/add";
}
/**
* 函数功能说明 : 保存
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("pay:product:add")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Model model, RpPayProduct rpPayProduct, DwzAjax dwz) {
rpPayProductService.createPayProduct(rpPayProduct.getProductCode(), rpPayProduct.getProductName());
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 : 删除
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("pay:product:delete")
@RequestMapping(value = "/delete", method ={RequestMethod.POST, RequestMethod.GET})
public String delete(Model model, DwzAjax dwz, @RequestParam("productCode") String productCode) {
rpPayProductService.deletePayProduct(productCode);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 : 查找带回
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/lookupList", method ={RequestMethod.POST, RequestMethod.GET})
public String lookupList(RpPayProduct rpPayProduct, PageParam pageParam, Model model) {
//查询已生效数据
rpPayProduct.setAuditStatus(PublicEnum.YES.name());
PageBean pageBean = rpPayProductService.listPage(pageParam, rpPayProduct);
model.addAttribute("pageBean", pageBean); | model.addAttribute("pageParam", pageParam);
model.addAttribute("rpPayProduct", rpPayProduct);
return "pay/product/lookupList";
}
/**
* 函数功能说明 : 审核
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("pay:product:add")
@RequestMapping(value = "/audit", method ={RequestMethod.POST, RequestMethod.GET})
public String audit(Model model, DwzAjax dwz, @RequestParam("productCode") String productCode
, @RequestParam("auditStatus") String auditStatus) {
rpPayProductService.audit(productCode, auditStatus);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\PayProductController.java | 2 |
请完成以下Java代码 | private final boolean isEmpty()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
final String text = textComponent.getText();
return Check.isEmpty(text, false);
}
private void doCopy()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.copy();
}
private void doCut()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
} | textComponent.cut();
}
private void doPaste()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.paste();
}
private void doSelectAll()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
// NOTE: we need to request focus first because it seems in some case the code below is not working when the component does not have the focus.
textComponent.requestFocus();
textComponent.selectAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JComboBoxCopyPasteSupportEditor.java | 1 |
请完成以下Java代码 | private static String executeJar(String createJarCommand) {
executeCommand(COMPILE_COMMAND);
executeCommand(createJarCommand);
return executeCommand(EXECUTE_JAR_COMMAND);
}
private static String executeCommand(String command) {
String output = null;
try {
output = collectOutput(runProcess(command));
} catch (Exception ex) {
System.out.println(ex);
}
return output;
}
private static String collectOutput(Process process) throws IOException {
StringBuffer output = new StringBuffer(); | BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = outputReader.readLine()) != null) {
output.append(line + "\n");
}
return output.toString();
}
private static Process runProcess(String command) throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER));
builder.directory(new File(WORK_PATH).getAbsoluteFile());
builder.redirectErrorStream(true);
Process process = builder.start();
process.waitFor();
return process;
}
} | repos\tutorials-master\core-java-modules\core-java-jar\src\main\java\com\baeldung\manifest\ExecuteJarFile.java | 1 |
请完成以下Java代码 | public void setGiftPointNew(Integer giftPointNew) {
this.giftPointNew = giftPointNew;
}
public Integer getUsePointLimitOld() {
return usePointLimitOld;
}
public void setUsePointLimitOld(Integer usePointLimitOld) {
this.usePointLimitOld = usePointLimitOld;
}
public Integer getUsePointLimitNew() {
return usePointLimitNew;
}
public void setUsePointLimitNew(Integer usePointLimitNew) {
this.usePointLimitNew = usePointLimitNew;
}
public String getOperateMan() {
return operateMan;
}
public void setOperateMan(String operateMan) {
this.operateMan = operateMan;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", priceOld=").append(priceOld);
sb.append(", priceNew=").append(priceNew);
sb.append(", salePriceOld=").append(salePriceOld);
sb.append(", salePriceNew=").append(salePriceNew);
sb.append(", giftPointOld=").append(giftPointOld);
sb.append(", giftPointNew=").append(giftPointNew);
sb.append(", usePointLimitOld=").append(usePointLimitOld);
sb.append(", usePointLimitNew=").append(usePointLimitNew);
sb.append(", operateMan=").append(operateMan);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductOperateLog.java | 1 |
请完成以下Java代码 | public Dimension getFromRecord(@NonNull final I_M_ForecastLine record)
{
return Dimension.builder()
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.campaignId(record.getC_Campaign_ID())
.activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.userElementString1(record.getUserElementString1())
.userElementString2(record.getUserElementString2())
.userElementString3(record.getUserElementString3())
.userElementString4(record.getUserElementString4())
.userElementString5(record.getUserElementString5())
.userElementString6(record.getUserElementString6())
.userElementString7(record.getUserElementString7())
.build();
} | @Override
public void updateRecord(final I_M_ForecastLine record, final Dimension from)
{
record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId()));
record.setC_Campaign_ID(from.getCampaignId());
record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId()));
record.setUserElementString1(from.getUserElementString1());
record.setUserElementString2(from.getUserElementString2());
record.setUserElementString3(from.getUserElementString3());
record.setUserElementString4(from.getUserElementString4());
record.setUserElementString5(from.getUserElementString5());
record.setUserElementString6(from.getUserElementString6());
record.setUserElementString7(from.getUserElementString7());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\ForecastLineDimensionFactory.java | 1 |
请完成以下Java代码 | public class StaticHeadersWriter implements HeaderWriter {
private final List<Header> headers;
/**
* Creates a new instance
* @param headers the {@link Header} instances to use
*/
public StaticHeadersWriter(List<Header> headers) {
Assert.notEmpty(headers, "headers cannot be null or empty");
this.headers = headers;
}
/**
* Creates a new instance with a single header
* @param headerName the name of the header
* @param headerValues the values for the header
*/
public StaticHeadersWriter(String headerName, String... headerValues) {
this(Collections.singletonList(new Header(headerName, headerValues)));
} | @Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
for (Header header : this.headers) {
if (!response.containsHeader(header.getName())) {
for (String value : header.getValues()) {
response.addHeader(header.getName(), value);
}
}
}
}
@Override
public String toString() {
return getClass().getName() + " [headers=" + this.headers + "]";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\StaticHeadersWriter.java | 1 |
请完成以下Java代码 | public List<String> getTags() {
return tags;
}
/**
* Sets the {@link #tags}.
*
* @param tags
* the new {@link #tags}
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Post other = (Post) obj;
if (author == null) {
if (other.author != null) | return false;
} else if (!author.equals(other.author))
return false;
if (tags == null) {
if (other.tags != null)
return false;
} else if (!tags.equals(other.tags))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Post [title=" + title + ", author=" + author + ", tags=" + tags + "]";
}
} | repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\tagging\Post.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Class<? extends T> candidate = getComponentType(annotationClass(), context, metadata);
return determineOutcome(candidate, context.getEnvironment());
}
@SuppressWarnings("unchecked")
protected Class<? extends T> getComponentType(Class<?> annotationClass, ConditionContext context,
AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(annotationClass.getName());
if (attributes != null && attributes.containsKey("value")) {
Class<?> target = (Class<?>) attributes.get("value");
if (target != defaultValueClass()) {
return (Class<? extends T>) target;
}
}
Assert.state(metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName()),
getClass().getSimpleName() + " must be used on @Bean methods when the value is not specified");
MethodMetadata methodMetadata = (MethodMetadata) metadata;
try {
return (Class<? extends T>) ClassUtils.forName(methodMetadata.getReturnTypeName(),
context.getClassLoader());
}
catch (Throwable ex) {
throw new IllegalStateException("Failed to extract component class for "
+ methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(), ex);
}
} | private ConditionOutcome determineOutcome(Class<? extends T> componentClass, PropertyResolver resolver) {
String key = PREFIX + normalizeComponentName(componentClass) + SUFFIX;
ConditionMessage.Builder messageBuilder = forCondition(annotationClass().getName(), componentClass.getName());
if ("false".equalsIgnoreCase(resolver.getProperty(key))) {
return ConditionOutcome.noMatch(messageBuilder.because("bean is not available"));
}
return ConditionOutcome.match();
}
protected abstract String normalizeComponentName(Class<? extends T> componentClass);
protected abstract Class<?> annotationClass();
protected abstract Class<? extends T> defaultValueClass();
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\conditional\OnEnabledComponent.java | 2 |
请完成以下Java代码 | public I_GL_Journal getGL_Journal() throws RuntimeException
{
return (I_GL_Journal)MTable.get(getCtx(), I_GL_Journal.Table_Name)
.getPO(getGL_Journal_ID(), get_TrxName()); }
/** Set Journal.
@param GL_Journal_ID
General Ledger Journal
*/
public void setGL_Journal_ID (int GL_Journal_ID)
{
if (GL_Journal_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Journal_ID, Integer.valueOf(GL_Journal_ID));
}
/** Get Journal.
@return General Ledger Journal
*/
public int getGL_Journal_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_GL_Journal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recognized Amount.
@param RecognizedAmt Recognized Amount */
public void setRecognizedAmt (BigDecimal RecognizedAmt)
{
set_ValueNoCheck (COLUMNNAME_RecognizedAmt, RecognizedAmt);
}
/** Get Recognized Amount.
@return Recognized Amount */
public BigDecimal getRecognizedAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RecognizedAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition_Run.java | 1 |
请完成以下Java代码 | public void setQty(final BigDecimal qty)
{
infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_Qty_CU, rowIndexModel, qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_Qty_CU);
return qty;
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
throw new UnsupportedOperationException();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final KeyNamePair huPiItemProductKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_M_HU_PI_Item_Product_ID);
if (huPiItemProductKNP == null)
{
return -1;
}
final int piItemProductId = huPiItemProductKNP.getKey();
if (piItemProductId <= 0)
{
return -1;
}
return piItemProductId;
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_QtyPacks);
return qty;
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_QtyPacks, rowIndexModel, qtyPacks);
}
@Override
public int getC_UOM_ID()
{
return Services.get(IProductBL.class).getStockUOMId(getM_Product_ID()).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId) | {
throw new UnsupportedOperationException();
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
throw new UnsupportedOperationException();
}
@Override
public int getC_BPartner_ID()
{
final KeyNamePair bpartnerKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_C_BPartner_ID);
return bpartnerKNP != null ? bpartnerKNP.getKey() : -1;
}
@Override
public boolean isInDispute()
{
// there is no InDispute flag to be considered
return false;
}
@Override
public void setInDispute(final boolean inDispute)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareInfoWindowAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PickingJobCreateRepoRequest.Step createStepRequest_PickFromHU(final @NonNull PickingPlanLine planLine)
{
final ProductId productId = planLine.getProductId();
final Quantity qtyToPick = planLine.getQty();
final PickFromHU pickFromHU = Objects.requireNonNull(planLine.getPickFromHU());
final PickingJobCreateRepoRequest.StepPickFrom mainPickFrom = PickingJobCreateRepoRequest.StepPickFrom.builder()
.pickFromLocatorId(pickFromHU.getLocatorId())
.pickFromHUId(extractTopLevelCUIfNeeded(pickFromHU.getTopLevelHUId(), productId, qtyToPick))
.build();
final ImmutableSet<PickingJobCreateRepoRequest.StepPickFrom> pickFromAlternatives = pickFromHU.getAlternatives()
.stream()
.map(alt -> PickingJobCreateRepoRequest.StepPickFrom.builder()
.pickFromLocatorId(alt.getLocatorId())
.pickFromHUId(alt.getHuId())
.build())
.collect(ImmutableSet.toImmutableSet());
return PickingJobCreateRepoRequest.Step.builder()
.scheduleId(planLine.getSourceDocumentInfo().getScheduleId())
.salesOrderLineId(Objects.requireNonNull(planLine.getSourceDocumentInfo().getSalesOrderLineId()))
.productId(productId)
.qtyToPick(qtyToPick)
.mainPickFrom(mainPickFrom)
.pickFromAlternatives(pickFromAlternatives)
.packToSpec(planLine.getSourceDocumentInfo().getPackToSpec())
.build(); | }
/**
* If the given HU is a top level CU, and it has the storage quantity greater than the qty we have to pick,
* then split out a top level CU for the qty we have to pick.
* <p>
* Why do we do this?
* We do this because when we reserve the HU/Qty, the reservation service is splitting out the reserved Qty and tries to keep the CU under the same HU,
* but in this case our CU is a top level one, so we will end up with a new top level CU which is not our <code>pickFromHUId</code>.
* The <code>pickFromHUId</code> will remain there but with qtyToPick less quantity which might not be enough for picking.
* <p>
* In this case we will deliberately split out a new CU, and we will use it for picking.
*/
private HuId extractTopLevelCUIfNeeded(
@NonNull final HuId pickFromHUId,
@NonNull final ProductId productId,
@NonNull final Quantity qtyToPick)
{
return huService.extractTopLevelCUIfNeeded(pickFromHUId, productId, qtyToPick);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobCreateCommand.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Optional<User> login(Email email, String rawPassword) {
return userRepository.findFirstByEmail(email)
.filter(user -> user.matchesPassword(rawPassword, passwordEncoder));
}
@Override
@Transactional(readOnly = true)
public Optional<User> findById(long id) {
return userRepository.findById(id);
}
@Override
public Optional<User> findByUsername(UserName userName) {
return userRepository.findFirstByProfileUserName(userName);
}
@Transactional | public User updateUser(long id, UserUpdateRequest request) {
final var user = userRepository.findById(id).orElseThrow(NoSuchElementException::new);
request.getEmailToUpdate()
.ifPresent(user::changeEmail);
request.getUserNameToUpdate()
.ifPresent(user::changeName);
request.getPasswordToUpdate()
.map(rawPassword -> Password.of(rawPassword, passwordEncoder))
.ifPresent(user::changePassword);
request.getImageToUpdate()
.ifPresent(user::changeImage);
request.getBioToUpdate()
.ifPresent(user::changeBio);
return userRepository.save(user);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\UserService.java | 2 |
请完成以下Java代码 | public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Konferenz.
@param IsConference Konferenz */
@Override
public void setIsConference (boolean IsConference)
{
set_Value (COLUMNNAME_IsConference, Boolean.valueOf(IsConference)); | }
/** Get Konferenz.
@return Konferenz */
@Override
public boolean isConference ()
{
Object oo = get_Value(COLUMNNAME_IsConference);
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_AD_User_SortPref_Hdr.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static UserDetailsImpl build(User user) {
return new UserDetailsImpl(user.getId(), user.getUsername(), user.getPassword());
}
public Long getId() {
return id;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() { | return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\userservice\UserDetailsImpl.java | 2 |
请完成以下Java代码 | public Iterator<I_PP_Order> retrieveAllModelsWithMissingCandidates(@NonNull final QueryLimit limit)
{
return dao.retrievePPOrdersWithMissingICs(limit);
}
/**
* Does nothing.
*/
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
// nothing to do; the value won't change
}
/**
* <ul>
* <li>QtyDelivered := QtyOrdered
* <li>DeliveryDate := DateOrdered
* <li>M_InOut_ID: untouched
* </ul>
*
* @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate)
*/
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially
ic.setQtyDeliveredInUOM(ic.getQtyEntered());
ic.setDeliveryDate(ic.getDateOrdered());
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
// nothing to do; the value won't change
} | /**
* @return {@link OnInvalidateForModelAction#RECREATE_ASYNC}.
*/
@Override
public final OnInvalidateForModelAction getOnInvalidateForModelAction()
{
return OnInvalidateForModelAction.RECREATE_ASYNC;
}
/* package */boolean isInvoiceable(final Object model)
{
final I_PP_Order ppOrder = InterfaceWrapperHelper.create(model, I_PP_Order.class);
return dao.isInvoiceable(ppOrder);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\PP_Order_MaterialTracking_Handler.java | 1 |
请完成以下Java代码 | public List<HistoricMilestoneInstance> executeList(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstancesByQueryCriteria(this);
}
@Override
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public Date getReachedBefore() { | return reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricMilestoneInstanceQueryImpl.java | 1 |
请完成以下Java代码 | private QuickInputDescriptor getQuickInputEntityDescriptorOrNull(final QuickInputDescriptorKey key)
{
return descriptors.getOrLoad(key, this::createQuickInputDescriptorOrNull);
}
private QuickInputDescriptor createQuickInputDescriptorOrNull(final QuickInputDescriptorKey key)
{
final IQuickInputDescriptorFactory quickInputDescriptorFactory = getQuickInputDescriptorFactory(key);
if (quickInputDescriptorFactory == null)
{
return null;
}
return quickInputDescriptorFactory.createQuickInputDescriptor(
key.getDocumentType(),
key.getDocumentTypeId(),
key.getIncludedTabId(),
key.getSoTrx());
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final QuickInputDescriptorKey key)
{
return getQuickInputDescriptorFactory(
//
// factory for included document:
IQuickInputDescriptorFactory.MatchingKey.includedDocument(
key.getDocumentType(),
key.getDocumentTypeId(),
key.getIncludedTableName().orElse(null)),
//
// factory for table:
IQuickInputDescriptorFactory.MatchingKey.ofTableName(key.getIncludedTableName().orElse(null)));
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final IQuickInputDescriptorFactory.MatchingKey... matchingKeys)
{
for (final IQuickInputDescriptorFactory.MatchingKey matchingKey : matchingKeys)
{
final IQuickInputDescriptorFactory factory = getQuickInputDescriptorFactory(matchingKey);
if (factory != null)
{
return factory;
}
} | return null;
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final IQuickInputDescriptorFactory.MatchingKey matchingKey)
{
final ImmutableList<IQuickInputDescriptorFactory> matchingFactories = factories.get(matchingKey);
if (matchingFactories.isEmpty())
{
return null;
}
if (matchingFactories.size() > 1)
{
logger.warn("More than one factory found for {}. Using the first one.", matchingFactories);
}
return matchingFactories.get(0);
}
@lombok.Builder
@lombok.Value
private static class QuickInputDescriptorKey
{
@NonNull DocumentType documentType;
@NonNull DocumentId documentTypeId;
@NonNull Optional<String> includedTableName;
@NonNull DetailId includedTabId;
@NonNull Optional<SOTrx> soTrx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputDescriptorFactoryService.java | 1 |
请完成以下Java代码 | public class HttpBasicServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String DEFAULT_REALM = "Realm";
private static String WWW_AUTHENTICATE_FORMAT = "Basic realm=\"%s\"";
private String headerValue = createHeaderValue(DEFAULT_REALM);
@Override
public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
return Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().set(WWW_AUTHENTICATE, this.headerValue); | });
}
/**
* Sets the realm to be used
* @param realm the realm. Default is "Realm"
*/
public void setRealm(String realm) {
this.headerValue = createHeaderValue(realm);
}
private static String createHeaderValue(String realm) {
Assert.notNull(realm, "realm cannot be null");
return String.format(WWW_AUTHENTICATE_FORMAT, realm);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\HttpBasicServerAuthenticationEntryPoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TestServiceImpl implements TestService {
private static final Logger LOGGER = LoggerFactory.getLogger(TestServiceImpl.class);
@Autowired
private JestClient jestClient;
@Override
public void saveEntity(Entity entity) {
Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
try {
jestClient.execute(index);
LOGGER.info("ES 插入完成");
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
}
}
/**
* 批量保存内容到ES
*/
@Override
public void saveEntity(List<Entity> entityList) {
Bulk.Builder bulk = new Bulk.Builder();
for(Entity entity : entityList) {
Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
bulk.addAction(index);
}
try { | jestClient.execute(bulk.build());
LOGGER.info("ES 插入完成");
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
}
}
/**
* 在ES中搜索内容
*/
@Override
public List<Entity> searchEntity(String searchContent){
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//searchSourceBuilder.query(QueryBuilders.queryStringQuery(searchContent));
//searchSourceBuilder.field("name");
searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));
Search search = new Search.Builder(searchSourceBuilder.toString())
.addIndex(Entity.INDEX_NAME).addType(Entity.TYPE).build();
try {
JestResult result = jestClient.execute(search);
return result.getSourceAsObjectList(Entity.class);
} catch (IOException e) {
LOGGER.error(e.getMessage());
e.printStackTrace();
}
return null;
}
} | repos\Spring-Boot-In-Action-master\springboot_es_demo\src\main\java\com\hansonwang99\springboot_es_demo\service\impl\TestServiceImpl.java | 2 |
请完成以下Java代码 | public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public ContractDropshipLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new ContractDropshipLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Flatrate_Term.class));
}
@Override
public I_C_Flatrate_Term getWrappedRecord() | {
return delegate;
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId dropshipLocationId, final @Nullable BPartnerContactId dropshipContactId)
{
setDropShip_BPartner_ID(dropshipLocationId.getBpartnerRepoId());
setDropShip_Location_ID(dropshipLocationId.getBPartnerLocationRepoId());
setDropShip_Location_Value_ID(dropshipLocationId.getLocationCaptureRepoId());
setDropShip_User_ID(dropshipContactId == null ? -1 : dropshipContactId.getRepoId());
}
public void setFrom(final @NonNull BPartnerLocationAndCaptureId dropshipLocationId)
{
setDropShip_BPartner_ID(dropshipLocationId.getBpartnerRepoId());
setDropShip_Location_ID(dropshipLocationId.getBPartnerLocationRepoId());
setDropShip_Location_Value_ID(dropshipLocationId.getLocationCaptureRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\location\adapter\ContractDropshipLocationAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Flux<Article> findNewestArticlesFilteredBy(@Nullable String tag,
@Nullable String authorId,
@Nullable User favoritedBy,
int limit,
int offset) {
var query = new Query()
.skip(offset)
.limit(limit)
.with(ArticleRepository.NEWEST_ARTICLE_SORT);
ofNullable(favoritedBy)
.ifPresent(user -> query.addCriteria(isFavoriteArticleByUser(user)));
ofNullable(tag)
.ifPresent(it -> query.addCriteria(tagsContains(it)));
ofNullable(authorId)
.ifPresent(it -> query.addCriteria(authorIdEquals(it))); | return mongoTemplate.find(query, Article.class);
}
private Criteria authorIdEquals(String it) {
return where(Article.AUTHOR_ID_FIELD_NAME).is(it);
}
private Criteria tagsContains(String it) {
return where(Article.TAGS_FIELD_NAME).all(it);
}
private Criteria isFavoriteArticleByUser(User it) {
return where(Article.ID_FIELD_NAME).in(it.getFavoriteArticleIds());
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\repository\ArticleManualRepository.java | 2 |
请完成以下Java代码 | public class BusinessRulesCollection
{
public final static BusinessRulesCollection EMPTY = new BusinessRulesCollection(ImmutableList.of());
@NonNull private final ImmutableList<BusinessRule> list;
@NonNull private final ImmutableMap<BusinessRuleId, BusinessRule> byId;
@NonNull private final ImmutableListMultimap<AdTableId, BusinessRuleAndTriggers> byTriggerTableId;
BusinessRulesCollection(List<BusinessRule> list)
{
this.list = ImmutableList.copyOf(list);
this.byId = Maps.uniqueIndex(list, BusinessRule::getId);
this.byTriggerTableId = indexByTriggerTableId(list);
}
private static ImmutableListMultimap<AdTableId, BusinessRuleAndTriggers> indexByTriggerTableId(final List<BusinessRule> list)
{
final HashMap<AdTableId, HashMap<BusinessRuleId, BusinessRuleAndTriggersBuilder>> buildersByTriggerTableId = new HashMap<>();
for (final BusinessRule rule : list)
{
for (final BusinessRuleTrigger trigger : rule.getTriggers())
{
buildersByTriggerTableId.computeIfAbsent(trigger.getTriggerTableId(), triggerTableId -> new HashMap<>())
.computeIfAbsent(rule.getId(), ruleId -> BusinessRuleAndTriggers.builderFrom(rule))
.trigger(trigger);
}
}
final ImmutableListMultimap.Builder<AdTableId, BusinessRuleAndTriggers> result = ImmutableListMultimap.builder();
buildersByTriggerTableId.forEach((triggerTableId, ruleBuilders) -> ruleBuilders.values()
.stream().map(BusinessRuleAndTriggersBuilder::build)
.forEach(ruleAndTriggers -> result.put(triggerTableId, ruleAndTriggers))
);
return result.build();
}
public static BusinessRulesCollection ofList(List<BusinessRule> list) | {
return !list.isEmpty() ? new BusinessRulesCollection(list) : EMPTY;
}
public ImmutableSet<AdTableId> getTriggerTableIds() {return byTriggerTableId.keySet();}
public ImmutableList<BusinessRuleAndTriggers> getByTriggerTableId(@NonNull final AdTableId triggerTableId) {return this.byTriggerTableId.get(triggerTableId);}
public BusinessRule getById(@NonNull final BusinessRuleId id)
{
final BusinessRule rule = getByIdOrNull(id);
if (rule == null)
{
throw new AdempiereException("No rule found for id=" + id);
}
return rule;
}
@Nullable
public BusinessRule getByIdOrNull(@Nullable final BusinessRuleId id)
{
return id == null ? null : byId.get(id);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\model\BusinessRulesCollection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static final class PropertiesLiquibaseConnectionDetails implements LiquibaseConnectionDetails {
private final LiquibaseProperties properties;
PropertiesLiquibaseConnectionDetails(LiquibaseProperties properties) {
this.properties = properties;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable String getJdbcUrl() {
return this.properties.getUrl();
}
@Override
public @Nullable String getDriverClassName() {
String driverClassName = this.properties.getDriverClassName(); | return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName();
}
}
@FunctionalInterface
interface SpringLiquibaseCustomizer {
/**
* Customize the given {@link SpringLiquibase} instance.
* @param springLiquibase the instance to configure
*/
void customize(SpringLiquibase springLiquibase);
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java | 2 |
请完成以下Spring Boot application配置 | spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
destinations:
queues:
NYSE:
exchange: nyse
routing-key: NYSE
IBOV:
exchange: ibov
routing- | key: IBOV
topics:
weather:
exchange: alerts
routing-key: WEATHER | repos\tutorials-master\spring-reactive-modules\spring-webflux-amqp\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getApprovedScopes() {
return approvedScopes;
}
public void setApprovedScopes(String approvedScopes) {
this.approvedScopes = approvedScopes;
}
public String getRedirectUri() { | return redirectUri;
}
public void setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
}
public LocalDateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(LocalDateTime expirationDate) {
this.expirationDate = expirationDate;
}
} | repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\model\AuthorizationCode.java | 1 |
请完成以下Java代码 | private int changeFieldLength(final int adColumnId, final String columnName, final int length, final String tableName)
{
int rowsEffected = -1;
final String selectSql = "SELECT FieldLength FROM AD_Column WHERE AD_Column_ID=" + adColumnId;
final String alterSql = "ALTER TABLE " + tableName + " MODIFY " + columnName + " NVARCHAR2(" + length + ") ";
final String updateSql = "UPDATE AD_Column SET FieldLength=" + length + " WHERE AD_Column_ID=" + adColumnId;
PreparedStatement selectStmt = null;
ResultSet rs = null;
try
{
selectStmt = DB.prepareStatement(selectSql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE, ITrx.TRXNAME_ThreadInherited);
rs = selectStmt.executeQuery();
if (rs.next())
{
// Change the column size physically.
DB.executeUpdateAndThrowExceptionOnFail(alterSql, ITrx.TRXNAME_ThreadInherited);
// Change the column size in AD. | DB.executeUpdateAndThrowExceptionOnFail(updateSql, ITrx.TRXNAME_ThreadInherited);
}
}
catch (final SQLException ex)
{
throw new DBException(ex, selectSql);
}
finally
{
DB.close(rs, selectStmt);
}
// Update number of rows effected.
rowsEffected++;
return rowsEffected;
} // changeFieldLength
} // EncryptionTest | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\ColumnEncryption.java | 1 |
请完成以下Java代码 | protected String getImportOrderBySql()
{
return I_I_Datev_Payment.COLUMNNAME_C_BPartner_ID;
}
@Override
public I_I_Datev_Payment retrieveImportRecord(final Properties ctx, final ResultSet rs) throws SQLException
{
return new X_I_Datev_Payment(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
@Override
protected ImportRecordResult importRecord(@NonNull final IMutable<Object> state,
@NonNull final I_I_Datev_Payment importRecord,
final boolean isInsertOnly) throws Exception
{
return importDatevPayment(importRecord, isInsertOnly);
}
private ImportRecordResult importDatevPayment(@NonNull final I_I_Datev_Payment importRecord, final boolean isInsertOnly)
{
final ImportRecordResult schemaImportResult;
final boolean paymentExists = importRecord.getC_Payment_ID() > 0;
if (paymentExists && isInsertOnly)
{
// do not update
return ImportRecordResult.Nothing;
}
final I_C_Payment payment;
if (!paymentExists)
{
payment = createNewPayment(importRecord);
schemaImportResult = ImportRecordResult.Inserted;
}
else
{
payment = importRecord.getC_Payment();
schemaImportResult = ImportRecordResult.Updated;
}
ModelValidationEngine.get().fireImportValidate(this, importRecord, payment,
IImportInterceptor.TIMING_AFTER_IMPORT);
InterfaceWrapperHelper.save(payment); | importRecord.setC_Payment_ID(payment.getC_Payment_ID());
InterfaceWrapperHelper.save(importRecord);
return schemaImportResult;
}
private I_C_Payment createNewPayment(@NonNull final I_I_Datev_Payment importRecord)
{
final LocalDate date = TimeUtil.asLocalDate(importRecord.getDateTrx());
final IPaymentBL paymentsService = Services.get(IPaymentBL.class);
return paymentsService.newBuilderOfInvoice(importRecord.getC_Invoice())
//.receipt(importRecord.isReceipt())
.adOrgId(OrgId.ofRepoId(importRecord.getAD_Org_ID()))
.bpartnerId(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()))
.payAmt(importRecord.getPayAmt())
.discountAmt(importRecord.getDiscountAmt())
.tenderType(TenderType.DirectDeposit)
.dateAcct(date)
.dateTrx(date)
.description("Import for debitorId/creditorId" + importRecord.getBPartnerValue())
.createAndProcess();
}
@Override
protected void markImported(@NonNull final I_I_Datev_Payment importRecord)
{
importRecord.setI_IsImported(X_I_Datev_Payment.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impexp\DatevPaymentImportProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BatchPartResource extends BatchPartBaseResource {
@Autowired
protected RestResponseFactory restResponseFactory;
@Autowired
protected ProcessEngineConfigurationImpl processEngineConfiguration;
@ApiOperation(value = "Get a single batch part", tags = { "Batch parts" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the batch part exists and is returned."),
@ApiResponse(code = 404, message = "Indicates the requested batch part does not exist.")
})
@GetMapping(value = "/management/batch-parts/{batchPartId}", produces = "application/json")
public BatchPartResponse getBatchPart(@ApiParam(name = "batchPartId") @PathVariable String batchPartId) {
BatchPart batchPart = getBatchPartById(batchPartId);
return restResponseFactory.createBatchPartResponse(batchPart);
}
@ApiOperation(value = "Get the batch part document", tags = { "Batches" }) | @ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the requested batch part was found and the batch part document has been returned. The response contains the raw batch part document and always has a Content-type of application/json."),
@ApiResponse(code = 404, message = "Indicates the requested batch part was not found or the job does not have a batch part document. Status-description contains additional information about the error.")
})
@GetMapping("/management/batch-parts/{batchPartId}/batch-part-document")
public String getBatchPartDocument(@ApiParam(name = "batchPartId") @PathVariable String batchPartId, HttpServletResponse response) {
BatchPart batchPart = getBatchPartById(batchPartId);
String batchPartDocument = managementService.getBatchPartDocument(batchPartId);
if (batchPartDocument == null) {
throw new FlowableObjectNotFoundException("Batch part with id '" + batchPart.getId() + "' does not have a batch part document.", String.class);
}
response.setContentType("application/json");
return batchPartDocument;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchPartResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private String computeBPartnerNameToExport(@NonNull final JsonResponseBPartner jsonResponseBPartner)
{
final String bpartnerName = Stream.of(jsonResponseBPartner.getName(),
jsonResponseBPartner.getName2(),
jsonResponseBPartner.getName3())
.filter(Check::isNotBlank)
.collect(Collectors.joining(" "));
if (Check.isBlank(bpartnerName))
{
throw new RuntimeException("BPartner with metasfreshId: " + jsonResponseBPartner.getMetasfreshId().getValue() + " missing name information!");
}
return bpartnerName;
}
@NonNull
private static List<JsonVendorContact> toJsonBPartnerContact(@NonNull final List<JsonResponseContact> contacts)
{
return contacts.stream()
.map(contact -> JsonVendorContact.builder()
.metasfreshId(contact.getMetasfreshId())
.firstName(contact.getFirstName())
.lastName(contact.getLastName())
.email(contact.getEmail())
.fax(contact.getFax())
.greeting(contact.getGreeting())
.title(contact.getTitle())
.phone(contact.getPhone())
.phone2(contact.getPhone2())
.contactRoles(toContactRoles(contact.getRoles()))
.position(contact.getPosition() == null ? null : contact.getPosition().getName())
.build())
.collect(ImmutableList.toImmutableList());
}
@Nullable
private static List<String> toContactRoles(@Nullable final List<JsonResponseContactRole> roles) | {
if (Check.isEmpty(roles))
{
return null;
}
return roles.stream()
.map(JsonResponseContactRole::getName)
.collect(ImmutableList.toImmutableList());
}
@NonNull
private static JsonVendor.JsonVendorBuilder initVendorWithLocationFields(@NonNull final JsonResponseLocation jsonResponseLocation)
{
return JsonVendor.builder()
.address1(jsonResponseLocation.getAddress1())
.address2(jsonResponseLocation.getAddress2())
.address3(jsonResponseLocation.getAddress3())
.address4(jsonResponseLocation.getAddress4())
.postal(jsonResponseLocation.getPostal())
.city(jsonResponseLocation.getCity())
.countryCode(jsonResponseLocation.getCountryCode())
.gln(jsonResponseLocation.getGln());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\ExportVendorProcessor.java | 2 |
请完成以下Java代码 | protected void handleOrderByCreateTimeConfig(ExternalTaskClientBuilder builder) {
String orderByCreateTime = clientConfiguration.getOrderByCreateTime();
if (STRING_ORDER_BY_ASC_VALUE.equals(orderByCreateTime)) {
builder.orderByCreateTime().asc();
return;
}
if (STRING_ORDER_BY_DESC_VALUE.equals(orderByCreateTime)) {
builder.orderByCreateTime().desc();
return;
}
throw new SpringExternalTaskClientException("Invalid value " + clientConfiguration.getOrderByCreateTime()
+ ". Please use either \"asc\" or \"desc\" value for configuring \"orderByCreateTime\" on the client");
}
protected boolean isOrderByCreateTimeEnabled() {
return clientConfiguration.getOrderByCreateTime() != null;
}
protected boolean isUseCreateTimeEnabled() {
return Boolean.TRUE.equals(clientConfiguration.getUseCreateTime());
}
protected void checkForCreateTimeMisconfiguration() {
if (isUseCreateTimeEnabled() && isOrderByCreateTimeEnabled()) {
throw new SpringExternalTaskClientException(
"Both \"useCreateTime\" and \"orderByCreateTime\" are enabled. Please use one or the other");
}
}
@Autowired(required = false)
public void setRequestInterceptors(List<ClientRequestInterceptor> requestInterceptors) {
if (requestInterceptors != null) {
this.requestInterceptors.addAll(requestInterceptors);
LOG.requestInterceptorsFound(this.requestInterceptors.size());
}
}
@Autowired(required = false)
public void setClientBackoffStrategy(BackoffStrategy backoffStrategy) {
this.backoffStrategy = backoffStrategy;
LOG.backoffStrategyFound();
}
@Override
public Class<ExternalTaskClient> getObjectType() {
return ExternalTaskClient.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
}
public ClientConfiguration getClientConfiguration() {
return clientConfiguration;
} | public void setClientConfiguration(ClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
public List<ClientRequestInterceptor> getRequestInterceptors() {
return requestInterceptors;
}
protected void close() {
if (client != null) {
client.stop();
}
}
@Autowired(required = false)
protected void setPropertyConfigurer(PropertySourcesPlaceholderConfigurer configurer) {
PropertySources appliedPropertySources = configurer.getAppliedPropertySources();
propertyResolver = new PropertySourcesPropertyResolver(appliedPropertySources);
}
protected String resolve(String property) {
if (propertyResolver == null) {
return property;
}
if (property != null) {
return propertyResolver.resolvePlaceholders(property);
} else {
return null;
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientFactory.java | 1 |
请完成以下Java代码 | public void invalidateView(final ViewId viewId)
{
getViewsStorageFor(viewId).invalidateView(viewId);
logger.trace("Invalided view {}", viewId);
}
@Override
public void invalidateView(final IView view)
{
invalidateView(view.getViewId());
}
@Override
public void notifyRecordsChangedAsync(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
async.execute(() -> notifyRecordsChangedNow(recordRefs));
}
@Override
public void notifyRecordsChangedNow(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
try (final IAutoCloseable ignored = ViewChangesCollector.currentOrNewThreadLocalCollector())
{
for (final IViewsIndexStorage viewsIndexStorage : viewsIndexStorages.values())
{
notifyRecordsChangedNow(recordRefs, viewsIndexStorage);
}
notifyRecordsChangedNow(recordRefs, defaultViewsIndexStorage);
}
}
private void notifyRecordsChangedNow(
@NonNull final TableRecordReferenceSet recordRefs,
@NonNull final IViewsIndexStorage viewsIndexStorage)
{
final ImmutableList<IView> views = viewsIndexStorage.getAllViews();
if (views.isEmpty()) | {
return;
}
final MutableInt notifiedCount = MutableInt.zero();
for (final IView view : views)
{
try
{
final boolean watchedByFrontend = isWatchedByFrontend(view.getViewId());
view.notifyRecordsChanged(recordRefs, watchedByFrontend);
notifiedCount.incrementAndGet();
}
catch (final Exception ex)
{
logger.warn("Failed calling notifyRecordsChanged on view={} with recordRefs={}. Ignored.", view, recordRefs, ex);
}
}
logger.debug("Notified {} views in {} about changed records: {}", notifiedCount, viewsIndexStorage, recordRefs);
}
@lombok.Value(staticConstructor = "of")
private static class ViewFactoryKey
{
WindowId windowId;
JSONViewDataType viewType;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewsRepository.java | 1 |
请完成以下Java代码 | public MaterialDescriptor withQuantity(@NonNull final BigDecimal quantity)
{
final MaterialDescriptor result = MaterialDescriptor.builder()
.quantity(quantity)
.date(this.date)
.productDescriptor(this)
.warehouseId(this.warehouseId)
.locatorId(this.locatorId)
.customerId(this.customerId)
.build();
return result.asssertMaterialDescriptorComplete();
}
public MaterialDescriptor withDate(@NonNull final Instant date)
{
final MaterialDescriptor result = MaterialDescriptor.builder()
.date(date)
.productDescriptor(this)
.warehouseId(this.warehouseId)
.locatorId(this.locatorId)
.customerId(this.customerId)
.quantity(this.quantity)
.build();
return result.asssertMaterialDescriptorComplete();
}
public MaterialDescriptor withProductDescriptor(final ProductDescriptor productDescriptor)
{
final MaterialDescriptor result = MaterialDescriptor.builder()
.productDescriptor(productDescriptor)
.date(this.date)
.warehouseId(this.warehouseId)
.locatorId(this.locatorId)
.customerId(this.customerId)
.quantity(this.quantity)
.build();
return result.asssertMaterialDescriptorComplete(); | }
public MaterialDescriptor withCustomerId(@Nullable final BPartnerId customerId)
{
final MaterialDescriptor result = MaterialDescriptor.builder()
.warehouseId(this.warehouseId)
.locatorId(this.locatorId)
.date(this.date)
.productDescriptor(this)
.customerId(customerId)
.quantity(this.quantity)
.build();
return result.asssertMaterialDescriptorComplete();
}
public MaterialDescriptor withStorageAttributes(
@NonNull final AttributesKey storageAttributesKey,
final int attributeSetInstanceId)
{
final ProductDescriptor newProductDescriptor = ProductDescriptor
.forProductAndAttributes(
getProductId(),
storageAttributesKey,
attributeSetInstanceId);
return withProductDescriptor(newProductDescriptor);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\MaterialDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getHANDLINGINSTRCODE() {
return handlinginstrcode;
}
/**
* Sets the value of the handlinginstrcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHANDLINGINSTRCODE(String value) {
this.handlinginstrcode = value;
}
/**
* Gets the value of the handlinginstrdesc property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHANDLINGINSTRDESC() {
return handlinginstrdesc;
}
/**
* Sets the value of the handlinginstrdesc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHANDLINGINSTRDESC(String value) {
this.handlinginstrdesc = value;
}
/**
* Gets the value of the hazardousmatcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHAZARDOUSMATCODE() {
return hazardousmatcode;
}
/**
* Sets the value of the hazardousmatcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHAZARDOUSMATCODE(String value) {
this.hazardousmatcode = value; | }
/**
* Gets the value of the hazardousmatname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHAZARDOUSMATNAME() {
return hazardousmatname;
}
/**
* Sets the value of the hazardousmatname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHAZARDOUSMATNAME(String value) {
this.hazardousmatname = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PHAND1.java | 2 |
请完成以下Java代码 | public static Supplier<ICalloutInstance> supplier(final String methodNameFQ)
{
Check.assumeNotEmpty(methodNameFQ, "methodNameFQ not empty");
final String classname;
final String methodName;
final int methodStartIdx = methodNameFQ.lastIndexOf('.');
if (methodStartIdx != -1) // no class
{
classname = methodNameFQ.substring(0, methodStartIdx);
methodName = methodNameFQ.substring(methodStartIdx + 1);
}
else
{
throw new CalloutInitException("Invalid callout: " + methodNameFQ);
}
if (Check.isEmpty(classname, true))
{
throw new CalloutInitException("Invalid classname for " + methodNameFQ);
}
if (Check.isEmpty(methodName, true))
{
throw new CalloutInitException("Invalid methodName for " + methodNameFQ);
}
final String id = MethodNameCalloutInstance.class.getSimpleName() + "-" + methodNameFQ.trim();
return () -> {
try
{
final org.compiere.model.Callout legacyCallout = Util.getInstance(org.compiere.model.Callout.class, classname);
return new MethodNameCalloutInstance(id, legacyCallout, methodName);
}
catch (final Exception e)
{
throw new CalloutInitException("Cannot load callout class for " + methodNameFQ, e);
}
};
}
private final String id;
private final org.compiere.model.Callout legacyCallout;
private final String methodName;
private MethodNameCalloutInstance(final String id, final org.compiere.model.Callout legacyCallout, final String methodName)
{
super();
this.id = id;
Check.assumeNotNull(legacyCallout, "Parameter legacyCallout is not null");
this.legacyCallout = legacyCallout;
Check.assumeNotNull(methodName, "Parameter methodName is not null");
this.methodName = methodName;
}
@Override
public String getId()
{
return id;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("id", id)
.toString();
}
@Override
public int hashCode()
{ | return Objects.hash(id);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final MethodNameCalloutInstance other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return id.equals(other.id);
}
@Override
public void execute(final ICalloutExecutor executor, final ICalloutField field)
{
try
{
legacyCallout.start(methodName, field);
}
catch (final CalloutException e)
{
throw e.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
catch (final Exception e)
{
throw CalloutExecutionException.wrapIfNeeded(e)
.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
}
@VisibleForTesting
public org.compiere.model.Callout getLegacyCallout()
{
return legacyCallout;
}
public String getMethodName()
{
return methodName;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\MethodNameCalloutInstance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class JacksonConfiguration {
@Bean
@ConditionalOnSingleCandidate(ObjectMapper.class)
ClusterEnvironmentBuilderCustomizer jacksonClusterEnvironmentBuilderCustomizer(ObjectMapper objectMapper) {
return new JacksonClusterEnvironmentBuilderCustomizer(
objectMapper.copy().registerModule(new JsonValueModule()));
}
}
private static final class JacksonClusterEnvironmentBuilderCustomizer
implements ClusterEnvironmentBuilderCustomizer, Ordered {
private final ObjectMapper objectMapper;
private JacksonClusterEnvironmentBuilderCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(Builder builder) {
builder.jsonSerializer(JacksonJsonSerializer.create(this.objectMapper));
}
@Override
public int getOrder() {
return 0;
}
}
/**
* Condition that matches when {@code spring.couchbase.connection-string} has been
* configured or there is a {@link CouchbaseConnectionDetails} bean.
*/
static final class CouchbaseCondition extends AnyNestedCondition {
CouchbaseCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty("spring.couchbase.connection-string")
private static final class CouchbaseUrlCondition {
}
@ConditionalOnBean(CouchbaseConnectionDetails.class)
private static final class CouchbaseConnectionDetailsCondition {
}
}
/**
* Adapts {@link CouchbaseProperties} to {@link CouchbaseConnectionDetails}.
*/
static final class PropertiesCouchbaseConnectionDetails implements CouchbaseConnectionDetails {
private final CouchbaseProperties properties;
private final @Nullable SslBundles sslBundles;
PropertiesCouchbaseConnectionDetails(CouchbaseProperties properties, @Nullable SslBundles sslBundles) {
this.properties = properties;
this.sslBundles = sslBundles; | }
@Override
public String getConnectionString() {
String connectionString = this.properties.getConnectionString();
Assert.state(connectionString != null, "'connectionString' must not be null");
return connectionString;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getEnv().getSsl();
if (!ssl.getEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return SslBundle.systemDefault();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseAutoConfiguration.java | 2 |
请完成以下Java代码 | public class EncryptableConfigurationPropertySourcesPropertySource extends PropertySource<Iterable<ConfigurationPropertySource>>
implements EncryptablePropertySource<Iterable<ConfigurationPropertySource>> {
private final PropertySource<Iterable<ConfigurationPropertySource>> delegate;
/**
* <p>Constructor for EncryptableConfigurationPropertySourcesPropertySource.</p>
*
* @param delegate a {@link org.springframework.core.env.PropertySource} object
*/
public EncryptableConfigurationPropertySourcesPropertySource(PropertySource<Iterable<ConfigurationPropertySource>> delegate) {
super(delegate.getName(), Iterables.filter(delegate.getSource(), configurationPropertySource -> !configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)));
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override
public PropertySource<Iterable<ConfigurationPropertySource>> getDelegate() {
return delegate;
}
/** {@inheritDoc} */
@Override
public void refresh() {
}
/** {@inheritDoc} */
@Override
public Object getProperty(String name) {
ConfigurationProperty configurationProperty = findConfigurationProperty(name);
return (configurationProperty != null) ? configurationProperty.getValue() : null;
}
/** {@inheritDoc} */
@Override
public Origin getOrigin(String name) {
return Origin.from(findConfigurationProperty(name)); | }
private ConfigurationProperty findConfigurationProperty(String name) {
try {
return findConfigurationProperty(ConfigurationPropertyName.of(name));
}
catch (InvalidConfigurationPropertyNameException ex) {
// simulate non-exposed version of ConfigurationPropertyName.of(name, nullIfInvalid)
if(ex.getInvalidCharacters().size() == 1 && ex.getInvalidCharacters().get(0).equals('.')) {
return null;
}
throw ex;
}
}
private ConfigurationProperty findConfigurationProperty(ConfigurationPropertyName name) {
if (name == null) {
return null;
}
for (ConfigurationPropertySource configurationPropertySource : getSource()) {
if (!configurationPropertySource.getUnderlyingSource().getClass().equals(EncryptableConfigurationPropertySourcesPropertySource.class)) {
ConfigurationProperty configurationProperty = configurationPropertySource.getConfigurationProperty(name);
if (configurationProperty != null) {
return configurationProperty;
}
}
}
return null;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableConfigurationPropertySourcesPropertySource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class FreeMarkerAutoConfiguration {
private static final Log logger = LogFactory.getLog(FreeMarkerAutoConfiguration.class);
private final ApplicationContext applicationContext;
private final FreeMarkerProperties properties;
FreeMarkerAutoConfiguration(ApplicationContext applicationContext, FreeMarkerProperties properties) {
this.applicationContext = applicationContext;
this.properties = properties;
checkTemplateLocationExists();
}
private void checkTemplateLocationExists() {
if (logger.isWarnEnabled() && this.properties.isCheckTemplateLocation()) {
List<TemplateLocation> locations = getLocations();
if (locations.stream().noneMatch(this::locationExists)) {
String suffix = (locations.size() == 1) ? "" : "s";
logger.warn("Cannot find template location" + suffix + ": " + locations
+ " (please add some templates, " + "check your FreeMarker configuration, or set "
+ "spring.freemarker.check-template-location=false)");
}
} | }
private List<TemplateLocation> getLocations() {
List<TemplateLocation> locations = new ArrayList<>();
for (String templateLoaderPath : this.properties.getTemplateLoaderPath()) {
TemplateLocation location = new TemplateLocation(templateLoaderPath);
locations.add(location);
}
return locations;
}
private boolean locationExists(TemplateLocation location) {
return location.exists(this.applicationContext);
}
} | repos\spring-boot-4.0.1\module\spring-boot-freemarker\src\main\java\org\springframework\boot\freemarker\autoconfigure\FreeMarkerAutoConfiguration.java | 2 |
请完成以下Java代码 | public final class MixedMoney
{
public static final MixedMoney EMPTY = new MixedMoney(ImmutableMap.of());
@NonNull private final ImmutableMap<CurrencyId, Money> map;
private MixedMoney(@NonNull final Map<CurrencyId, Money> map)
{
this.map = ImmutableMap.copyOf(map);
}
public static Collector<Money, ?, MixedMoney> collectAndSum()
{
return GuavaCollectors.collectUsingListAccumulator(MixedMoney::sumOf);
}
public static MixedMoney sumOf(@NonNull final Collection<Money> collection)
{
if (collection.isEmpty())
{
return MixedMoney.EMPTY;
}
final HashMap<CurrencyId, Money> map = new HashMap<>();
for (final Money money : collection)
{
map.compute(money.getCurrencyId(), (currencyId, currentMoney) -> currentMoney == null ? money : currentMoney.add(money));
}
return new MixedMoney(map);
} | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(map.values())
.toString();
}
public Optional<Money> toNoneOrSingleValue()
{
if (map.isEmpty())
{
return Optional.empty();
}
else if (map.size() == 1)
{
return map.values().stream().findFirst();
}
else
{
throw new AdempiereException("Expected none or single value but got many: " + map.values());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\MixedMoney.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
// see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/
return getClass().hashCode();
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java | 2 |
请完成以下Java代码 | protected final List<PaymentToReconcileRow> getSelectedPaymentToReconcileRows()
{
return streamSelectedRows()
.collect(ImmutableList.toImmutableList());
}
protected ViewId getBanksStatementReconciliationViewId()
{
return getView().getBankStatementViewId();
}
protected final BankStatementReconciliationView getBanksStatementReconciliationView()
{
final ViewId bankStatementViewId = getBanksStatementReconciliationViewId();
final IViewsRepository viewsRepo = getViewsRepo();
return BankStatementReconciliationView.cast(viewsRepo.getView(bankStatementViewId));
}
protected final void invalidateBankStatementReconciliationView()
{
invalidateView(getBanksStatementReconciliationViewId());
} | protected final BankStatementLineRow getSingleSelectedBankStatementRowOrNull()
{
final ViewRowIdsSelection selection = getParentViewRowIdsSelection();
if (selection == null || selection.isEmpty())
{
return null;
}
final ImmutableList<BankStatementLineRow> rows = getBanksStatementReconciliationView()
.streamByIds(selection)
.collect(ImmutableList.toImmutableList());
return rows.size() == 1 ? rows.get(0) : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\process\PaymentsToReconcileViewBasedProcess.java | 1 |
请完成以下Java代码 | private static Percent extractPercentage(final I_C_CompensationGroup_SchemaLine schemaLinePO)
{
final BigDecimal percentageBD = schemaLinePO.getCompleteOrderDiscount();
return percentageBD != null && percentageBD.signum() != 0
? Percent.of(percentageBD)
: null;
}
private GroupMatcher createGroupMatcher(
final I_C_CompensationGroup_SchemaLine compensationLineRecord,
final List<I_C_CompensationGroup_SchemaLine> allCompensationLineRecords)
{
final GroupTemplateCompensationLineType type = GroupTemplateCompensationLineType.ofNullableCode(compensationLineRecord.getType());
if (type == null)
{ | return GroupMatchers.ALWAYS;
}
else
{
final GroupMatcherFactory groupMatcherFactory = groupMatcherFactoriesByType.get(type);
if (groupMatcherFactory == null)
{
throw new AdempiereException("No " + GroupMatcherFactory.class + " found for type=" + type)
.setParameter("schemaLine", compensationLineRecord);
}
return groupMatcherFactory.createPredicate(compensationLineRecord, allCompensationLineRecords);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupTemplateRepository.java | 1 |
请完成以下Java代码 | public double doubleValue() {
return (double)sum();
}
/**
* Serialization proxy, used to avoid reference to the non-public
* Striped64 superclass in serialized forms.
* @serial include
*/
private static class SerializationProxy implements Serializable {
private static final long serialVersionUID = 7249069246863182397L;
/**
* The current value returned by sum().
* @serial
*/
private final long value;
SerializationProxy(LongAdder a) {
value = a.sum();
}
/**
* Return a {@code LongAdder} object with initial state
* held by this proxy.
*
* @return a {@code LongAdder} object with initial state
* held by this proxy.
*/
private Object readResolve() {
LongAdder a = new LongAdder();
a.base = value;
return a;
}
} | /**
* Returns a
* <a href="../../../../serialized-form.html#java.util.concurrent.atomic.LongAdder.SerializationProxy">
* SerializationProxy</a>
* representing the state of this instance.
*
* @return a {@link SerializationProxy}
* representing the state of this instance
*/
private Object writeReplace() {
return new SerializationProxy(this);
}
/**
* @param s the stream
* @throws java.io.InvalidObjectException always
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.InvalidObjectException {
throw new java.io.InvalidObjectException("Proxy required");
}
} | repos\tutorials-master\jmh\src\main\java\com\baeldung\falsesharing\LongAdder.java | 1 |
请完成以下Java代码 | public boolean isEnabled() {return sysConfigBL.getBooleanValue(SYSCONFIG_Enabled, true);}
@Override
public void schedule(@NonNull final DocumentPostRequest request)
{
schedule(DocumentPostMultiRequest.of(request));
}
@Override
public void schedule(@NonNull DocumentPostMultiRequest requests)
{
if (!isEnabled())
{
userNotificationsHolder.get().notifyPostingError("Accounting module is disabled", requests);
return;
}
postingBusServiceHolder.get().sendAfterCommit(requests);
}
@Override
public void postAfterCommit(@NonNull final DocumentPostMultiRequest requests)
{
trxManager.accumulateAndProcessAfterCommit(
"DocumentPostRequests.toPostNow",
requests.toSet(),
this::postNow
);
}
private void postNow(@NonNull final List<DocumentPostRequest> requests)
{
requests.forEach(this::postNow);
}
private void postNow(@NonNull final DocumentPostRequest request)
{ | // TODO check Profiles.isProfileActive(Profiles.PROFILE_AccountingService) ... maybe not
// TODO check if disabled? maybe not....
logger.debug("Posting directly: {}", this);
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
try (final IAutoCloseable ignored = Env.switchContext(ctx))
{
final List<AcctSchema> acctSchemas = acctSchemaDAO.getAllByClient(request.getClientId());
final Doc<?> doc = acctDocRegistryHolder.get().get(acctSchemas, request.getRecord());
doc.post(request.isForce(), true);
documentPostingLogServiceHolder.get().logPostingOK(request);
}
catch (final Exception ex)
{
final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex);
documentPostingLogServiceHolder.get().logPostingError(request, metasfreshException);
if (request.getOnErrorNotifyUserId() != null)
{
userNotificationsHolder.get().notifyPostingError(request.getOnErrorNotifyUserId(), request.getRecord(), metasfreshException);
}
}
}
//
//
// ----------
//
//
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\impl\PostingService.java | 1 |
请完成以下Java代码 | public class UserRequest
implements Serializable
{
private final static long serialVersionUID = -1L;
protected int id;
@XmlElement(required = true)
protected String name;
/**
* Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
* | */
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
} | repos\tutorials-master\xml-modules\jaxb\src\main\java\com\baeldung\jaxb\gen\UserRequest.java | 1 |
请完成以下Java代码 | default boolean isNoResult(final Object result)
{
return result == null
|| Util.same(result, EMPTY_RESULT);
}
@Override
default boolean isNullExpression()
{
return false;
}
/**
* Resolves all variables which available and returns a new string expression.
*
* @param ctx
* @return string expression with all available variables resolved.
* @throws ExpressionEvaluationException
*/
default IStringExpression resolvePartial(final Evaluatee ctx) throws ExpressionEvaluationException
{
final String expressionStr = evaluate(ctx, OnVariableNotFound.Preserve);
return StringExpressionCompiler.instance.compile(expressionStr);
}
/**
* Turns this expression in an expression which caches it's evaluation results.
* If this expression implements {@link ICachedStringExpression} it will be returned directly without any wrapping. | *
* @return cached expression
*/
default ICachedStringExpression caching()
{
return CachedStringExpression.wrapIfPossible(this);
}
/**
* @return same as {@link #toString()} but the whole string representation will be on one line (new lines are stripped)
*/
default String toOneLineString()
{
return toString()
.replace("\r", "")
.replace("\n", "");
}
default CompositeStringExpression.Builder toComposer()
{
return composer().append(this);
}
@Override
String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\IStringExpression.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getMchId() {
return mchId;
}
public void setMchId(String mchId) {
this.mchId = mchId;
}
public String getDeviceInfo() {
return deviceInfo;
}
public void setDeviceInfo(String deviceInfo) {
this.deviceInfo = deviceInfo;
}
public String getNonceStr() {
return nonceStr;
}
public void setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
}
public String getOutTradeNo() {
return outTradeNo;
}
public void setOutTradeNo(String outTradeNo) {
this.outTradeNo = outTradeNo;
}
public String getFeeType() {
return feeType;
}
public void setFeeType(String feeType) {
this.feeType = feeType;
}
public Integer getTotalFee() {
return totalFee;
}
public void setTotalFee(Integer totalFee) {
this.totalFee = totalFee;
}
public String getSpbillCreateIp() {
return spbillCreateIp;
}
public void setSpbillCreateIp(String spbillCreateIp) {
this.spbillCreateIp = spbillCreateIp;
}
public String getTimeStart() {
return timeStart;
}
public void setTimeStart(String timeStart) {
this.timeStart = timeStart;
}
public String getTimeExpire() {
return timeExpire;
}
public void setTimeExpire(String timeExpire) {
this.timeExpire = timeExpire;
} | public String getGoodsTag() {
return goodsTag;
}
public void setGoodsTag(String goodsTag) {
this.goodsTag = goodsTag;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public WeiXinTradeTypeEnum getTradeType() {
return tradeType;
}
public void setTradeType(WeiXinTradeTypeEnum tradeType) {
this.tradeType = tradeType;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getLimitPay() {
return limitPay;
}
public void setLimitPay(String limitPay) {
this.limitPay = limitPay;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\weixinpay\WeiXinPrePay.java | 2 |
请完成以下Java代码 | protected String doIt()
{
final List<I_C_OrderLine> selectedOrderLines = getSelectedOrderLines();
Check.assumeNotEmpty(selectedOrderLines, "selectedOrderLines is not empty");
final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = extractOrderLineIdsByGroupTemplate(selectedOrderLines);
if (orderLineIdsByGroupTemplate.isEmpty())
{
throw new AdempiereException("Nothing to group"); // TODO trl
}
final List<Group> groups = orderLineIdsByGroupTemplate.asMap()
.entrySet()
.stream()
.map(e -> createGroup(e.getKey(), e.getValue()))
.collect(ImmutableList.toImmutableList());
final OrderId orderId = OrderGroupRepository.extractOrderIdFromGroups(groups);
groupsRepo.renumberOrderLinesForOrderId(orderId);
return MSG_OK;
}
private ListMultimap<GroupTemplate, OrderLineId> extractOrderLineIdsByGroupTemplate(final List<I_C_OrderLine> orderLines)
{
final List<I_C_OrderLine> orderLinesSorted = orderLines.stream()
.sorted(Comparator.comparing(I_C_OrderLine::getLine))
.collect(ImmutableList.toImmutableList());
final ListMultimap<GroupTemplate, OrderLineId> orderLineIdsByGroupTemplate = LinkedListMultimap.create();
for (final I_C_OrderLine orderLine : orderLinesSorted)
{
final GroupTemplate groupTemplate = extractGroupTemplate(orderLine);
if (groupTemplate == null)
{
continue;
} | orderLineIdsByGroupTemplate.put(groupTemplate, OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID()));
}
return orderLineIdsByGroupTemplate;
}
@Nullable
private GroupTemplate extractGroupTemplate(final I_C_OrderLine orderLine)
{
final ProductId productId = ProductId.ofRepoIdOrNull(orderLine.getM_Product_ID());
if (productId == null)
{
return null;
}
final IProductDAO productsRepo = Services.get(IProductDAO.class);
final ProductCategoryId productCategoryId = productsRepo.retrieveProductCategoryByProductId(productId);
final I_M_Product_Category productCategory = productsRepo.getProductCategoryById(productCategoryId, I_M_Product_Category.class);
final GroupTemplateId groupTemplateId = GroupTemplateId.ofRepoIdOrNull(productCategory.getC_CompensationGroup_Schema_ID());
if (groupTemplateId == null)
{
return null;
}
return groupTemplateRepo.getById(groupTemplateId);
}
private Group createGroup(final GroupTemplate groupTemplate, final Collection<OrderLineId> orderLineIds)
{
return groupsRepo.prepareNewGroup()
.groupTemplate(groupTemplate)
.createGroup(orderLineIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\C_Order_CreateCompensationMultiGroups.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomerEditor extends VerticalLayout implements KeyNotifier {
private final CustomerRepository repository;
/**
* The currently edited customer
*/
private Customer customer;
/* Fields to edit properties in Customer entity */
TextField firstName = new TextField("First name");
TextField lastName = new TextField("Last name");
/* Action buttons */
Button save = new Button("Save", VaadinIcon.CHECK.create());
Button cancel = new Button("Cancel");
Button delete = new Button("Delete", VaadinIcon.TRASH.create());
HorizontalLayout actions = new HorizontalLayout(save, cancel, delete);
Binder<Customer> binder = new Binder<>(Customer.class);
private ChangeHandler changeHandler;
@Autowired
public CustomerEditor(CustomerRepository repository) {
this.repository = repository;
add(firstName, lastName, actions);
// bind using naming convention
binder.bindInstanceFields(this);
// Configure and style components
setSpacing(true);
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
addKeyPressListener(Key.ENTER, e -> save());
// wire action buttons to save, delete and reset
save.addClickListener(e -> save());
delete.addClickListener(e -> delete());
cancel.addClickListener(e -> editCustomer(customer));
setVisible(false);
}
void delete() {
repository.delete(customer);
changeHandler.onChange();
}
void save() {
repository.save(customer);
changeHandler.onChange();
} | public interface ChangeHandler {
void onChange();
}
public final void editCustomer(Customer c) {
if (c == null) {
setVisible(false);
return;
}
final boolean persisted = c.getId() != null;
if (persisted) {
// Find fresh entity for editing
// In a more complex app, you might want to load
// the entity/DTO with lazy loaded relations for editing
customer = repository.findById(c.getId()).get();
}
else {
customer = c;
}
cancel.setVisible(persisted);
// Bind customer properties to similarly named fields
// Could also use annotation or "manual binding" or programmatically
// moving values from fields to entities before saving
binder.setBean(customer);
setVisible(true);
// Focus first name initially
firstName.focus();
}
public void setChangeHandler(ChangeHandler h) {
// ChangeHandler is notified when either save or delete
// is clicked
changeHandler = h;
}
} | repos\springboot-demo-master\vaadin\src\main\java\com\et\vaadin\view\CustomerEditor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class UUISelection
{
int size;
String uuid;
Instant time;
}
public <T, ET extends T> TypedSqlQuery<ET> createUUIDSelectionQuery(
@NonNull final IContextAware ctx,
@NonNull final Class<ET> clazz,
@NonNull final String querySelectionUUID)
{
final String tableName = InterfaceWrapperHelper.getTableName(clazz);
final POInfo poInfo = POInfo.getPOInfo(tableName);
final String keyColumnName = poInfo.getKeyColumnName();
final String keyColumnNameFQ = tableName + "." + keyColumnName;
//
// Build the query used to retrieve models by querying the selection.
// NOTE: we are using LEFT OUTER JOIN instead of INNER JOIN because
// * methods like hasNext() are comparing the rowsFetched counter with rowsCount to detect if we reached the end of the selection (optimization).
// * POBufferedIterator is using LIMIT/OFFSET clause for fetching the next page and eliminating rows from here would fuck the paging if one record was deleted in meantime.
// So we decided to load everything here, and let the hasNext() method to deal with the case when the record is really missing.
final String selectionSqlFrom = "(SELECT "
+ I_T_Query_Selection.COLUMNNAME_UUID + " as ZZ_UUID"
+ ", " + I_T_Query_Selection.COLUMNNAME_Record_ID + " as ZZ_Record_ID" | + ", " + I_T_Query_Selection.COLUMNNAME_Line + " as " + SELECTION_LINE_ALIAS
+ " FROM " + I_T_Query_Selection.Table_Name
+ ") s "
+ "\n LEFT OUTER JOIN " + tableName + " ON (" + keyColumnNameFQ + "=s.ZZ_Record_ID)";
final String selectionWhereClause = "s.ZZ_UUID=?";
final String selectionOrderBy = "s." + SELECTION_LINE_ALIAS;
return new TypedSqlQuery<>(
ctx.getCtx(),
clazz,
selectionWhereClause,
ctx.getTrxName())
.setParameters(querySelectionUUID)
.setSqlFrom(selectionSqlFrom)
.setOrderBy(selectionOrderBy);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\QuerySelectionHelper.java | 2 |
请完成以下Java代码 | public class ParticipantImpl extends BaseElementImpl implements Participant {
protected static Attribute<String> nameAttribute;
protected static AttributeReference<Process> processRefAttribute;
protected static ElementReferenceCollection<Interface, InterfaceRef> interfaceRefCollection;
protected static ElementReferenceCollection<EndPoint, EndPointRef> endPointRefCollection;
protected static ChildElement<ParticipantMultiplicity> participantMultiplicityChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Participant.class, BPMN_ELEMENT_PARTICIPANT)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<Participant>() {
public Participant newInstance(ModelTypeInstanceContext instanceContext) {
return new ParticipantImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
processRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_PROCESS_REF)
.qNameAttributeReference(Process.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
interfaceRefCollection = sequenceBuilder.elementCollection(InterfaceRef.class)
.qNameElementReferenceCollection(Interface.class)
.build();
endPointRefCollection = sequenceBuilder.elementCollection(EndPointRef.class)
.qNameElementReferenceCollection(EndPoint.class)
.build();
participantMultiplicityChild = sequenceBuilder.element(ParticipantMultiplicity.class)
.build();
typeBuilder.build();
} | public ParticipantImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Process getProcess() {
return processRefAttribute.getReferenceTargetElement(this);
}
public void setProcess(Process process) {
processRefAttribute.setReferenceTargetElement(this, process);
}
public Collection<Interface> getInterfaces() {
return interfaceRefCollection.getReferenceTargetElements(this);
}
public Collection<EndPoint> getEndPoints() {
return endPointRefCollection.getReferenceTargetElements(this);
}
public ParticipantMultiplicity getParticipantMultiplicity() {
return participantMultiplicityChild.getChild(this);
}
public void setParticipantMultiplicity(ParticipantMultiplicity participantMultiplicity) {
participantMultiplicityChild.setChild(this, participantMultiplicity);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ParticipantImpl.java | 1 |
请完成以下Java代码 | public final class DelegatingRequestMatcherHeaderWriter implements HeaderWriter {
private final RequestMatcher requestMatcher;
private final HeaderWriter delegateHeaderWriter;
/**
* Creates a new instance
* @param requestMatcher the {@link RequestMatcher} to use. If returns true, the
* delegateHeaderWriter will be invoked.
* @param delegateHeaderWriter the {@link HeaderWriter} to invoke if the
* {@link RequestMatcher} returns true.
*/
public DelegatingRequestMatcherHeaderWriter(RequestMatcher requestMatcher, HeaderWriter delegateHeaderWriter) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
Assert.notNull(delegateHeaderWriter, "delegateHeaderWriter cannot be null");
this.requestMatcher = requestMatcher;
this.delegateHeaderWriter = delegateHeaderWriter;
} | @Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (this.requestMatcher.matches(request)) {
this.delegateHeaderWriter.writeHeaders(request, response);
}
}
@Override
public String toString() {
return getClass().getName() + " [requestMatcher=" + this.requestMatcher + ", delegateHeaderWriter="
+ this.delegateHeaderWriter + "]";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\DelegatingRequestMatcherHeaderWriter.java | 1 |
请完成以下Java代码 | public int getConfirmQueryRecords()
{
return constraint.getConfirmQueryRecords();
}
/**
* Converts the given <code>maxQueryRecords</code> restriction to an actual number of rows.
*
* If there was NO maximum number of rows configured, then ZERO will be returned.
*
* @return maximum number of rows allowed to be presented to a user in a window.
*/
public int resolve(final GridTabMaxRows maxQueryRecords)
{
// Case: we were asked to use the default
if (maxQueryRecords != null && maxQueryRecords.isDefault())
{
return getMaxQueryRecords();
}
// Case: we were asked to not enforce at all
else if (maxQueryRecords == null || maxQueryRecords.isNoRestriction())
{
return 0;
}
// Case: we got a specific maximum number of records we shall display
else
{
return maxQueryRecords.getMaxRows();
}
}
public static class Builder
{
private IUserRolePermissions userRolePermissions;
private GridTab gridTab;
private Integer maxQueryRecordsPerTab = null;
private Builder()
{
super();
}
public final GridTabMaxRowsRestrictionChecker build()
{
return new GridTabMaxRowsRestrictionChecker(this);
}
public Builder setUserRolePermissions(final IUserRolePermissions userRolePermissions)
{
this.userRolePermissions = userRolePermissions;
return this;
} | private WindowMaxQueryRecordsConstraint getConstraint()
{
return getUserRolePermissions()
.getConstraint(WindowMaxQueryRecordsConstraint.class)
.orElse(WindowMaxQueryRecordsConstraint.DEFAULT);
}
private IUserRolePermissions getUserRolePermissions()
{
if (userRolePermissions != null)
{
return userRolePermissions;
}
return Env.getUserRolePermissions();
}
public Builder setAD_Tab(final GridTab gridTab)
{
this.gridTab = gridTab;
return this;
}
public Builder setMaxQueryRecordsPerTab(final int maxQueryRecordsPerTab)
{
this.maxQueryRecordsPerTab = maxQueryRecordsPerTab;
return this;
}
private int getMaxQueryRecordsPerTab()
{
if (maxQueryRecordsPerTab != null)
{
return maxQueryRecordsPerTab;
}
else if (gridTab != null)
{
return gridTab.getMaxQueryRecords();
}
return 0;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\GridTabMaxRowsRestrictionChecker.java | 1 |
请完成以下Java代码 | private ViewRowIdsOrderedSelection create()
{
return huEditorViewRepository.createSelection(viewEvaluationCtx, viewId, filters, orderBys, filterConverterCtx);
}
public ViewRowIdsOrderedSelection get()
{
return defaultSelectionRef.computeIfNull(this::create);
}
/**
* @return true if selection was really changed
*/
public boolean change(@NonNull final UnaryOperator<ViewRowIdsOrderedSelection> mapper)
{
final ViewRowIdsOrderedSelection defaultSelectionOld = defaultSelectionRef.getValue(); | defaultSelectionRef.computeIfNull(this::create); // make sure it's not null (might be null if it was invalidated)
final ViewRowIdsOrderedSelection defaultSelectionNew = defaultSelectionRef.compute(mapper);
return !ViewRowIdsOrderedSelection.equals(defaultSelectionOld, defaultSelectionNew);
}
public void delete()
{
defaultSelectionRef.computeIfNotNull(defaultSelection -> {
huEditorViewRepository.deleteSelection(defaultSelection);
return null;
});
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_HighVolume.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Class<? extends BatchEntity> getManagedEntityClass() {
return BatchEntityImpl.class;
}
@Override
public BatchEntity create() {
return new BatchEntityImpl();
}
@Override
@SuppressWarnings("unchecked")
public List<Batch> findBatchesBySearchKey(String searchKey) {
HashMap<String, Object> params = new HashMap<>();
params.put("searchKey", searchKey);
params.put("searchKey2", searchKey);
return getDbSqlSession().selectList("selectBatchesBySearchKey", params);
}
@Override
@SuppressWarnings("unchecked")
public List<Batch> findAllBatches() {
return getDbSqlSession().selectList("selectAllBatches");
}
@Override
@SuppressWarnings("unchecked")
public List<Batch> findBatchesByQueryCriteria(BatchQueryImpl batchQuery) {
return getDbSqlSession().selectList("selectBatchByQueryCriteria", batchQuery, getManagedEntityClass());
}
@Override
public long findBatchCountByQueryCriteria(BatchQueryImpl batchQuery) {
return (Long) getDbSqlSession().selectOne("selectBatchCountByQueryCriteria", batchQuery); | }
@Override
public void deleteBatches(BatchQueryImpl batchQuery) {
getDbSqlSession().delete("bulkDeleteBytesForBatches", batchQuery, getManagedEntityClass());
getDbSqlSession().delete("bulkDeleteBatchPartsForBatches", batchQuery, getManagedEntityClass());
getDbSqlSession().delete("bulkDeleteBatches", batchQuery, getManagedEntityClass());
}
@Override
protected IdGenerator getIdGenerator() {
return batchServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\data\impl\MybatisBatchDataManager.java | 2 |
请完成以下Java代码 | public String getModelTableNameOrNull(final Object model)
{
if (model == null)
{
return null;
}
final IInterfaceWrapperHelper helper = getHelperThatCanHandleOrNull(model);
if (helper == null)
{
return null;
}
return helper.getModelTableNameOrNull(model);
}
@Override
public boolean isNew(final Object model)
{
Check.assumeNotNull(model, "model not null");
return getHelperThatCanHandle(model)
.isNew(model);
}
@Override
public <T> T getValue(
@NonNull final Object model,
@NonNull final String columnName,
final boolean throwExIfColumnNotFound, final boolean useOverrideColumnIfAvailable)
{
return getHelperThatCanHandle(model)
.getValue(model, columnName, throwExIfColumnNotFound, useOverrideColumnIfAvailable);
}
@Override
public boolean isValueChanged(final Object model, final String columnName)
{
return getHelperThatCanHandle(model)
.isValueChanged(model, columnName);
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{
return getHelperThatCanHandle(model)
.isValueChanged(model, columnNames);
}
@Override
public boolean isNull(final Object model, final String columnName)
{
if (model == null)
{
return true;
}
return getHelperThatCanHandle(model)
.isNull(model, columnName);
}
@Nullable
@Override
public <T> T getDynAttribute(@NonNull final Object model, @NonNull final String attributeName)
{
return getHelperThatCanHandle(model)
.getDynAttribute(model, attributeName);
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return getHelperThatCanHandle(model)
.setDynAttribute(model, attributeName, value); | }
@Nullable
@Override
public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier)
{
return getHelperThatCanHandle(model).computeDynAttributeIfAbsent(model, attributeName, supplier);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
if (model == null)
{
return null;
}
// Short-circuit: model is already a PO instance
if (model instanceof PO)
{
@SuppressWarnings("unchecked") final T po = (T)model;
return po;
}
return getHelperThatCanHandle(model)
.getPO(model, strict);
}
@Override
public Evaluatee getEvaluatee(final Object model)
{
if (model == null)
{
return null;
}
else if (model instanceof Evaluatee)
{
final Evaluatee evaluatee = (Evaluatee)model;
return evaluatee;
}
return getHelperThatCanHandle(model)
.getEvaluatee(model);
}
@Override
public boolean isCopy(@NonNull final Object model)
{
return getHelperThatCanHandle(model).isCopy(model);
}
@Override
public boolean isCopying(@NonNull final Object model)
{
return getHelperThatCanHandle(model).isCopying(model);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\CompositeInterfaceWrapperHelper.java | 1 |
请完成以下Java代码 | public ConfirmPanel build()
{
return new ConfirmPanel(this);
}
public Builder withCancelButton(final boolean withCancelButton)
{
this.withCancelButton = withCancelButton;
return this;
}
public Builder withNewButton(final boolean withNewButton)
{
this.withNewButton = withNewButton;
return this;
}
public Builder withRefreshButton()
{
return withRefreshButton(true);
}
public Builder withRefreshButton(final boolean withRefreshButton)
{
this.withRefreshButton = withRefreshButton;
return this;
}
public Builder withResetButton(final boolean withResetButton)
{
this.withResetButton = withResetButton;
return this;
}
public Builder withCustomizeButton(final boolean withCustomizeButton)
{
this.withCustomizeButton = withCustomizeButton;
return this;
}
public Builder withHistoryButton(final boolean withHistoryButton)
{
this.withHistoryButton = withHistoryButton;
return this;
}
public Builder withZoomButton(final boolean withZoomButton)
{
this.withZoomButton = withZoomButton;
return this; | }
/**
* Advice builder to create the buttons with text on them.
*/
public Builder withText()
{
return withText(true);
}
/**
* Advice builder to create the buttons without any text on them.
*
* NOTE: this is the default option anyway. You can call it just to explicitly state the obvious.
*/
public Builder withoutText()
{
return withText(false);
}
/**
* Advice builder to create the buttons with or without text on them.
*
* @param withText true if buttons shall have text on them
*/
public Builder withText(final boolean withText)
{
this.withText = withText;
return this;
}
public Builder withSmallButtons(final boolean withSmallButtons)
{
smallButtons = withSmallButtons;
return this;
}
}
} // ConfirmPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ConfirmPanel.java | 1 |
请完成以下Java代码 | public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
final SavedRequest savedRequest = this.requestCache.getRequest(request, response);
final String redirectUrl = (savedRequest != null) ? savedRequest.getRedirectUrl()
: request.getContextPath() + "/";
this.requestCache.removeRequest(request, response);
this.converter.write(new AuthenticationSuccess(redirectUrl), MediaType.APPLICATION_JSON,
new ServletServerHttpResponse(response));
}
/**
* A response object used to write the JSON response for successful authentication.
*
* NOTE: We should be careful about writing {@link Authentication} or
* {@link Authentication#getPrincipal()} to the response since it contains
* credentials.
*/
public static final class AuthenticationSuccess { | private final String redirectUrl;
private AuthenticationSuccess(String redirectUrl) {
this.redirectUrl = redirectUrl;
}
public String getRedirectUrl() {
return this.redirectUrl;
}
public boolean isAuthenticated() {
return true;
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\HttpMessageConverterAuthenticationSuccessHandler.java | 1 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.requiresLogout.matches(exchange)
.filter((result) -> result.isMatch())
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.map((result) -> exchange)
.flatMap(this::flatMapAuthentication)
.flatMap((authentication) -> {
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
return logout(webFilterExchange, authentication);
});
}
private Mono<Authentication> flatMapAuthentication(ServerWebExchange exchange) {
return exchange.getPrincipal().cast(Authentication.class).defaultIfEmpty(this.anonymousAuthenticationToken);
}
private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) {
logger.debug(LogMessage.format("Logging out user '%s' and transferring to logout destination", authentication));
return this.logoutHandler.logout(webFilterExchange, authentication)
.then(this.logoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication))
.contextWrite(ReactiveSecurityContextHolder.clearContext());
}
/**
* Sets the {@link ServerLogoutSuccessHandler}. The default is
* {@link RedirectServerLogoutSuccessHandler}. | * @param logoutSuccessHandler the handler to use
*/
public void setLogoutSuccessHandler(ServerLogoutSuccessHandler logoutSuccessHandler) {
Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null");
this.logoutSuccessHandler = logoutSuccessHandler;
}
/**
* Sets the {@link ServerLogoutHandler}. The default is
* {@link SecurityContextServerLogoutHandler}.
* @param logoutHandler The handler to use
*/
public void setLogoutHandler(ServerLogoutHandler logoutHandler) {
Assert.notNull(logoutHandler, "logoutHandler must not be null");
this.logoutHandler = logoutHandler;
}
public void setRequiresLogoutMatcher(ServerWebExchangeMatcher requiresLogoutMatcher) {
Assert.notNull(requiresLogoutMatcher, "requiresLogoutMatcher must not be null");
this.requiresLogout = requiresLogoutMatcher;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\logout\LogoutWebFilter.java | 1 |
请完成以下Java代码 | private void doLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication();
this.handlers.logout(request, response, auth);
}
/**
* 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;
}
public void setLogoutHandlers(LogoutHandler[] handlers) {
this.handlers = new CompositeLogoutHandler(handlers);
}
/**
* Set list of {@link LogoutHandler}
* @param handlers list of {@link LogoutHandler}
* @since 5.2.0
*/
public void setLogoutHandlers(List<LogoutHandler> handlers) {
this.handlers = new CompositeLogoutHandler(handlers);
}
/**
* Sets the {@link RedirectStrategy} used with
* {@link #ConcurrentSessionFilter(SessionRegistry, String)}
* @param redirectStrategy the {@link RedirectStrategy} to use
* @deprecated use
* {@link #ConcurrentSessionFilter(SessionRegistry, SessionInformationExpiredStrategy)}
* instead.
*/
@Deprecated
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy; | }
/**
* A {@link SessionInformationExpiredStrategy} that writes an error message to the
* response body.
*
* @author Rob Winch
* @since 4.2
*/
private static final class ResponseBodySessionInformationExpiredStrategy
implements SessionInformationExpiredStrategy {
@Override
public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
HttpServletResponse response = event.getResponse();
response.getWriter()
.print("This session has been expired (possibly due to multiple concurrent "
+ "logins being attempted as the same user).");
response.flushBuffer();
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\ConcurrentSessionFilter.java | 1 |
请完成以下Java代码 | public class JdkProxySourceClassUtil {
private static Logger logger = LoggerFactory.getLogger(JdkProxySourceClassUtil.class);
private JdkProxySourceClassUtil() {
}
/**
* @param proxyClassName 代理类名称($proxy4)
* @param aClass 目标类对象
*/
public static void writeClassToDisk(String proxyClassName, Class aClass) {
String path = ".\\" + proxyClassName + ".class";
writeClassToDisk(path, proxyClassName, aClass);
}
/**
* @param path 输出路径
* @param proxyClassName 代理类名称($proxy4)
* @param aClass 目标类对象
*/
public static void writeClassToDisk(String path, String proxyClassName, Class aClass) {
byte[] classFile = ProxyGenerator.generateProxyClass(proxyClassName, new Class[]{aClass}); | FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(classFile);
fos.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
} | repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\mybatis\JdkProxySourceClassUtil.java | 1 |
请完成以下Java代码 | public Float getLifeexpectancy() {
return lifeexpectancy;
}
public void setLifeexpectancy(Float lifeexpectancy) {
this.lifeexpectancy = lifeexpectancy;
}
public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold;
}
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname;
}
public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
}
public String getGovernmentform() {
return governmentform; | }
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
} | repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_ChargeType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Charge Type.
@param C_ChargeType_ID Charge Type */
public void setC_ChargeType_ID (int C_ChargeType_ID)
{
if (C_ChargeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, Integer.valueOf(C_ChargeType_ID));
}
/** Get Charge Type.
@return Charge Type */
public int getC_ChargeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_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 Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp () | {
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType.java | 1 |
请完成以下Java代码 | public void setStatusDB(final String text)
{
setStatusDB(text, null);
} // setStatusDB
/**
* Set Status DB Info
*
* @param no no
*/
public void setStatusDB(final int no)
{
setStatusDB(String.valueOf(no), null);
} // setStatusDB
/**
* Set Info Line
*
* @param text text
*/
@Override
public void setInfo(final String text)
{
infoLine.setVisible(true);
infoLine.setText(text);
} // setInfo
/**
* Show {@link RecordInfo} dialog
*/
private void showRecordInfo()
{
if (m_dse == null)
{
return;
}
final int adTableId = m_dse.getAdTableId();
final ComposedRecordId recordId = m_dse.getRecordId();
if (adTableId <= 0 || recordId == null)
{ | return;
}
if (!Env.getUserRolePermissions().isShowPreference())
{
return;
}
//
final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId);
AEnv.showCenterScreen(info);
}
public void removeBorders()
{
statusLine.setBorder(BorderFactory.createEmptyBorder());
statusDB.setBorder(BorderFactory.createEmptyBorder());
infoLine.setBorder(BorderFactory.createEmptyBorder());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java | 1 |
请完成以下Java代码 | private static HashSet<Integer> collectValueIfPositive(@Nullable HashSet<Integer> collector, int value)
{
if (value <= 0)
{
return collector;
}
if (collector == null)
{
collector = new HashSet<>();
}
collector.add(value);
return collector;
}
private static int singleElementOrZero(@Nullable HashSet<Integer> collection) | {
if (collection == null)
{
return 0;
}
if (collection.size() != 1)
{
return 0;
}
final Integer element = collection.iterator().next();
return element != null ? element : 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\Dimension.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PemSslBundleProperties extends SslBundleProperties {
/**
* Keystore properties.
*/
private final Store keystore = new Store();
/**
* Truststore properties.
*/
private final Store truststore = new Store();
public Store getKeystore() {
return this.keystore;
}
public Store getTruststore() {
return this.truststore;
}
/**
* Store properties.
*/
public static class Store {
/**
* Type of the store to create, e.g. JKS.
*/
private @Nullable String type;
/**
* Location or content of the certificate or certificate chain in PEM format.
*/
private @Nullable String certificate;
/**
* Location or content of the private key in PEM format.
*/
private @Nullable String privateKey;
/**
* Password used to decrypt an encrypted private key.
*/
private @Nullable String privateKeyPassword;
/**
* Whether to verify that the private key matches the public key.
*/ | private boolean verifyKeys;
public @Nullable String getType() {
return this.type;
}
public void setType(@Nullable String type) {
this.type = type;
}
public @Nullable String getCertificate() {
return this.certificate;
}
public void setCertificate(@Nullable String certificate) {
this.certificate = certificate;
}
public @Nullable String getPrivateKey() {
return this.privateKey;
}
public void setPrivateKey(@Nullable String privateKey) {
this.privateKey = privateKey;
}
public @Nullable String getPrivateKeyPassword() {
return this.privateKeyPassword;
}
public void setPrivateKeyPassword(@Nullable String privateKeyPassword) {
this.privateKeyPassword = privateKeyPassword;
}
public boolean isVerifyKeys() {
return this.verifyKeys;
}
public void setVerifyKeys(boolean verifyKeys) {
this.verifyKeys = verifyKeys;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\PemSslBundleProperties.java | 2 |
请完成以下Java代码 | /* package */class ICNetAmtToInvoiceChecker implements IAggregator<BigDecimal, I_C_Invoice_Candidate>
{
private static final String SYSCONFIG_FailIfNetAmtToInvoiceChecksumNotMatch = "de.metas.invoicecandidate.api.impl.ICNetAmtToInvoiceChecker.FailIfNetAmtToInvoiceChecksumNotMatch";
// Parameters
private BigDecimal _netAmtToInvoiceExpected = null;
// Status
private BigDecimal _netAmtToInvoice = BigDecimal.ZERO;
private int _countInvoiceCandidates = 0;
public ICNetAmtToInvoiceChecker setNetAmtToInvoiceExpected(final BigDecimal netAmtToInvoiceExpected)
{
this._netAmtToInvoiceExpected = netAmtToInvoiceExpected;
return this;
}
@Override
public void add(@NonNull final I_C_Invoice_Candidate ic)
{
final BigDecimal icLineNetAmt = ic.getNetAmtToInvoice();
_netAmtToInvoice = _netAmtToInvoice.add(icLineNetAmt);
_countInvoiceCandidates++;
}
@Override
public BigDecimal getValue()
{
return _netAmtToInvoice;
}
/**
* Asserts aggregated net amount to invoice equals with given expected value (if set).
*
* The expected amount is set using {@link #setNetAmtToInvoiceExpected(BigDecimal)}.
*
* @see #assertExpectedNetAmtToInvoice(BigDecimal)
*/
public void assertExpectedNetAmtToInvoiceIfSet()
{
if (_netAmtToInvoiceExpected == null)
{
return;
}
assertExpectedNetAmtToInvoice(_netAmtToInvoiceExpected);
}
/**
* Asserts aggregated net amount to invoice equals with given expected value.
*
* If it's not equal, an error message will be logged to {@link ILoggable}.
*
* @throws AdempiereException if the checksums are not equal and {@link #isFailIfNetAmtToInvoiceChecksumNotMatch()}.
*/ | public void assertExpectedNetAmtToInvoice(@NonNull final BigDecimal netAmtToInvoiceExpected)
{
Check.assume(netAmtToInvoiceExpected.signum() != 0, "netAmtToInvoiceExpected != 0");
final BigDecimal netAmtToInvoiceActual = getValue();
if (netAmtToInvoiceExpected.compareTo(netAmtToInvoiceActual) != 0)
{
final String errmsg = "NetAmtToInvoice checksum not match"
+ "\n Expected: " + netAmtToInvoiceExpected
+ "\n Actual: " + netAmtToInvoiceActual
+ "\n Invoice candidates count: " + _countInvoiceCandidates;
Loggables.addLog(errmsg);
if (isFailIfNetAmtToInvoiceChecksumNotMatch())
{
throw new AdempiereException(errmsg);
}
}
}
/**
* @return true if we shall fail if the net amount to invoice checksum does not match.
*/
public final boolean isFailIfNetAmtToInvoiceChecksumNotMatch()
{
final boolean failIfNetAmtToInvoiceChecksumNotMatchDefault = true;
return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_FailIfNetAmtToInvoiceChecksumNotMatch, failIfNetAmtToInvoiceChecksumNotMatchDefault);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ICNetAmtToInvoiceChecker.java | 1 |
请完成以下Java代码 | private HUEditorRowAttributesProvider getAttributesProviderOrNull()
{
return attributesProvider;
}
public Builder setAttributesProvider(@Nullable final HUEditorRowAttributesProvider attributesProvider)
{
this.attributesProvider = attributesProvider;
return this;
}
public Builder addIncludedRow(@NonNull final HUEditorRow includedRow)
{
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<HUEditorRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
public Builder setReservedForOrderLine(@Nullable final OrderLineId orderLineId)
{
orderLineReservation = orderLineId;
huReserved = orderLineId != null;
return this;
}
public Builder setClearanceStatus(@Nullable final JSONLookupValue clearanceStatusLookupValue)
{
clearanceStatus = clearanceStatusLookupValue;
return this;
}
public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate)
{
this.customProcessApplyPredicate = processApplyPredicate;
return this;
}
@Nullable
private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate()
{
return this.customProcessApplyPredicate;
} | /**
* @param currentRow the row that is currently constructed using this builder
*/
private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow)
{
final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder();
for (final HUEditorRow includedRow : buildIncludedRows())
{
includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations());
}
if (orderLineReservation != null)
{
includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow);
}
return includedOrderLineReservationsBuilder.build();
}
}
@lombok.Builder
@lombok.Value
public static class HUEditorRowHierarchy
{
@NonNull HUEditorRow cuRow;
@Nullable
HUEditorRow parentRow;
@Nullable
HUEditorRow topLevelRow;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java | 1 |
请完成以下Java代码 | public DmnEvaluationException noScriptEngineFoundForLanguage(String expressionLanguage) {
return new DmnEvaluationException(exceptionMessage(
"003",
"Unable to find script engine for expression language '{}'.", expressionLanguage)
);
}
public DmnEngineException decisionTypeNotSupported(DmnDecision decision) {
return new DmnEngineException(exceptionMessage(
"004",
"Decision type '{}' not supported by DMN engine.", decision.getClass())
);
}
public DmnEngineException invalidValueForTypeDefinition(String typeName, Object value) {
return new DmnEngineException(exceptionMessage(
"005",
"Invalid value '{}' for clause with type '{}'.", value, typeName)
);
}
public void unsupportedTypeDefinitionForClause(String typeName) {
logWarn(
"006",
"Unsupported type '{}' for clause. Values of this clause will not transform into another type.", typeName
);
}
public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionRuleResult ruleResult) {
return new DmnDecisionResultException(exceptionMessage(
"007",
"Unable to get single decision rule result entry as it has more than one entry '{}'", ruleResult)
);
}
public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionTableResult decisionResult) {
return new DmnDecisionResultException(exceptionMessage(
"008",
"Unable to get single decision rule result as it has more than one rule result '{}'", decisionResult)
);
}
public DmnTransformException unableToFindAnyDecisionTable() {
return new DmnTransformException(exceptionMessage(
"009",
"Unable to find any decision table in model.")
);
} | public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionResultEntries result) {
return new DmnDecisionResultException(exceptionMessage(
"010",
"Unable to get single decision result entry as it has more than one entry '{}'", result)
);
}
public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionResult decisionResult) {
return new DmnDecisionResultException(exceptionMessage(
"011",
"Unable to get single decision result as it has more than one result '{}'", decisionResult)
);
}
public DmnEngineException decisionLogicTypeNotSupported(DmnDecisionLogic decisionLogic) {
return new DmnEngineException(exceptionMessage(
"012",
"Decision logic type '{}' not supported by DMN engine.", decisionLogic.getClass())
);
}
public DmnEngineException decisionIsNotADecisionTable(DmnDecision decision) {
return new DmnEngineException(exceptionMessage(
"013",
"The decision '{}' is not implemented as decision table.", decision)
);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnEngineLogger.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: mall-admin
profiles:
active: dev #默认为开发环境
servlet:
multipart:
enabled: true #开启文件上传
max-file-size: 10MB #限制文件上传大小为10M
mvc:
pathmatch:
matching-strategy: ant_path_matcher
mybatis:
mapper-locations:
- classpath:dao/*.xml
- classpath*:com/**/mapper/*.xml
jwt:
tokenHeader: Authorization #JWT存储的请求头
secret: mall-admin-secret #JWT加解密使用的密钥
expiration: 604800 #JWT的超期限时间(60*60*24*7)
tokenHead: 'Bearer ' #JWT负载中拿到开头
redis:
database: mall
key:
admin: 'ums:admin'
resourceList: 'ums:resourceList'
expire:
common: 86400 # 24小时
secure:
ignored:
urls: #安全路径白名单
- /swagger-ui/
- /swagger-resources/**
- /**/v2/api-docs
- /**/*.html
- /**/*.js
- /**/*.css
- /**/*.png
- /**/*.map
- /favicon.ico
- /actuator/**
- /druid/**
- /admin/login
- /admin/register
- /admin/info
- /admin/logout |
- /minio/upload
aliyun:
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com # oss对外服务的访问域名
accessKeyId: test # 访问身份验证中用到用户标识
accessKeySecret: test # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
bucketName: macro-oss # oss的存储空间
policy:
expire: 300 # 签名有效期(S)
maxSize: 10 # 上传文件大小(M)
callback: http://39.98.190.128:8080/aliyun/oss/callback # 文件上传成功后的回调地址
dir:
prefix: mall/images/ # 上传文件夹路径前缀 | repos\mall-master\mall-admin\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public String toString()
{
StringBuilder sb = new StringBuilder("AdempiereServerMgr[");
sb.append("Servers=").append(m_servers.size())
.append(",ContextSize=").append(_ctx.size())
.append(",Started=").append(m_start)
.append("]");
return sb.toString();
} // toString
/**
* Get Description
*
* @return description
*/
public String getDescription()
{
return "1.4";
} // getDescription
/**
* Get Number Servers
*
* @return no of servers
*/
public String getServerCount()
{
int noRunning = 0;
int noStopped = 0; | for (int i = 0; i < m_servers.size(); i++)
{
AdempiereServer server = m_servers.get(i);
if (server.isAlive())
noRunning++;
else
noStopped++;
}
String info = String.valueOf(m_servers.size())
+ " - Running=" + noRunning
+ " - Stopped=" + noStopped;
return info;
} // getServerCount
/**
* Get start date
*
* @return start date
*/
public Timestamp getStartTime()
{
return new Timestamp(m_start.getTime());
} // getStartTime
} // AdempiereServerMgr | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AdempiereServerMgr.java | 1 |
请完成以下Java代码 | public boolean applies(final IPricingContext pricingCtx, final IPricingResult result)
{
return includedPricingRules.applies(pricingCtx, result);
}
/**
* Iterates the ctx's {@code pricingCtx}'s priceList's PLVs from a PLV to its respective base-PLV
* and applies the sub-pricing-rules until a price is found or all PLvs were tried.
*/
@Override
public void calculate(final IPricingContext pricingCtx, final IPricingResult result)
{
final ZonedDateTime date = extractPriceDate(pricingCtx);
final HashSet<PriceListVersionId> seenPriceListVersionIds = new HashSet<>();
PriceListVersionId currentPriceListVersionId = getPriceListVersionIdEffective(pricingCtx, date);
do
{
if (currentPriceListVersionId != null && !seenPriceListVersionIds.add(currentPriceListVersionId))
{
// loop detected, we already tried to compute using that price list version
break;
}
final IEditablePricingContext pricingCtxEffective = pricingCtx.copy();
pricingCtxEffective.setPriceListVersionId(currentPriceListVersionId);
includedPricingRules.calculate(pricingCtxEffective, result);
if (result.isCalculated())
{
return;
}
currentPriceListVersionId = getBasePriceListVersionId(currentPriceListVersionId, date);
}
while (currentPriceListVersionId != null);
}
@Nullable | private PriceListVersionId getPriceListVersionIdEffective(final IPricingContext pricingCtx, @NonNull final ZonedDateTime date)
{
final I_M_PriceList_Version contextPLV = pricingCtx.getM_PriceList_Version();
if (contextPLV != null)
{
return contextPLV.isActive() ? PriceListVersionId.ofRepoId(contextPLV.getM_PriceList_Version_ID()) : null;
}
final I_M_PriceList_Version plv = priceListDAO.retrievePriceListVersionOrNull(
pricingCtx.getPriceListId(),
date,
null // processed
);
return plv != null && plv.isActive() ? PriceListVersionId.ofRepoId(plv.getM_PriceList_Version_ID()) : null;
}
@Nullable
private PriceListVersionId getBasePriceListVersionId(@Nullable final PriceListVersionId priceListVersionId, @NonNull final ZonedDateTime date)
{
if (priceListVersionId == null)
{
return null;
}
return priceListDAO.getBasePriceListVersionIdForPricingCalculationOrNull(priceListVersionId, date);
}
@NonNull
private static ZonedDateTime extractPriceDate(@NonNull final IPricingContext pricingCtx)
{
return pricingCtx.getPriceDate().atStartOfDay(SystemTime.zoneId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\PriceListVersionPricingRule.java | 1 |
请完成以下Java代码 | public void suspend() {
}
@Override
public void resume() {
}
@Override
public void flush() {
}
@Override
public void beforeCommit(boolean readOnly) {
}
@Override
public void beforeCompletion() {
} | @Override
public void afterCommit() {
}
@Override
public void afterCompletion(int status) {
}
@Override
public int getOrder() {
return transactionSynchronizationAdapterOrder;
}
}
} | repos\flowable-engine-main\modules\flowable-spring-common\src\main\java\org\flowable\common\spring\SpringTransactionContext.java | 1 |
请完成以下Java代码 | public B credentials(@Nullable Object credentials) {
Assert.isInstanceOf(Jwt.class, credentials, "credentials must be of type Jwt");
return token((Jwt) credentials);
}
/**
* Use this {@code token} as the token, principal, and credentials. Also sets the
* {@code name} to {@link Jwt#getSubject}.
* @param token the token to use
* @return the {@link Builder} for further configurations
*/
@Override
public B token(Jwt token) {
super.principal(token);
super.credentials(token);
return super.token(token).name(token.getSubject());
}
/**
* The name to use. | * @param name the name to use
* @return the {@link Builder} for further configurations
*/
public B name(String name) {
this.name = name;
return (B) this;
}
@Override
public JwtAuthenticationToken build() {
return new JwtAuthenticationToken(this);
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtAuthenticationToken.java | 1 |
请完成以下Java代码 | public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return HUQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
private static String extractPrintableTopText(final HUQRCode qrCode)
{
final StringBuilder result = new StringBuilder();
final HUQRCodeProductInfo product = qrCode.getProduct().orElse(null);
if (product != null)
{
result.append(product.getCode());
result.append(" - ");
result.append(product.getName());
}
for (final HUQRCodeAttribute attribute : qrCode.getAttributes())
{
final String displayValue = StringUtils.trimBlankToNull(attribute.getValueRendered());
if (displayValue != null)
{
if (result.length() > 0)
{
result.append(", ");
}
result.append(displayValue);
}
}
return result.toString();
}
@Override
public Optional<BigDecimal> getWeightInKg()
{
return getAttribute(Weightables.ATTR_WeightNet)
.map(HUQRCodeAttribute::getValueAsBigDecimal)
.filter(weight -> weight.signum() > 0);
} | @Override
public Optional<LocalDate> getBestBeforeDate()
{
return getAttribute(AttributeConstants.ATTR_BestBeforeDate).map(HUQRCodeAttribute::getValueAsLocalDate);
}
@Override
public Optional<LocalDate> getProductionDate()
{
return getAttribute(AttributeConstants.ProductionDate).map(HUQRCodeAttribute::getValueAsLocalDate);
}
@Override
public Optional<String> getLotNumber()
{
return getAttribute(AttributeConstants.ATTR_LotNumber).map(HUQRCodeAttribute::getValue);
}
private Optional<HUQRCodeAttribute> getAttribute(@NonNull final AttributeCode attributeCode)
{
return attributes.stream().filter(attribute -> AttributeCode.equals(attribute.getCode(), attributeCode)).findFirst();
}
private static String extractPrintableBottomText(final HUQRCode qrCode)
{
return qrCode.getPackingInfo().getHuUnitType().getShortDisplayName() + " ..." + qrCode.toDisplayableQRCode();
}
public Optional<HUQRCodeProductInfo> getProduct() {return Optional.ofNullable(product);}
@JsonIgnore
public Optional<ProductId> getProductId() {return getProduct().map(HUQRCodeProductInfo::getId);}
@JsonIgnore
public ProductId getProductIdNotNull() {return getProductId().orElseThrow(() -> new AdempiereException("QR Code does not contain product information: " + this));}
public HuPackingInstructionsId getPackingInstructionsId() {return getPackingInfo().getPackingInstructionsId();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCode.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCarrier_Goods_Type_ID (final int Carrier_Goods_Type_ID)
{
if (Carrier_Goods_Type_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Goods_Type_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Goods_Type_ID, Carrier_Goods_Type_ID);
}
@Override
public int getCarrier_Goods_Type_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Goods_Type_ID);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
} | @Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Goods_Type.java | 1 |
请完成以下Java代码 | private static Executor createAsyncExecutor()
{
final CustomizableThreadFactory asyncThreadFactory = new CustomizableThreadFactory(SecurPharmActionProcessor.class.getSimpleName());
asyncThreadFactory.setDaemon(true);
return Executors.newSingleThreadExecutor(asyncThreadFactory);
}
@Override
public void setSecurPharmService(@NonNull final SecurPharmService securPharmService)
{
this.handlers.forEach(handler -> handler.setSecurPharmService(securPharmService));
}
@Override
public void post(@NonNull final SecurPharmaActionRequest request)
{
eventBus.enqueueObject(request);
}
@ToString(of = "delegate")
private static class AsyncSecurPharmActionsHandler
{
private final SecurPharmActionsHandler delegate;
private final Executor executor; | private AsyncSecurPharmActionsHandler(
@NonNull final SecurPharmActionsHandler delegate,
@NonNull final Executor executor)
{
this.delegate = delegate;
this.executor = executor;
}
public void handleActionRequest(@NonNull final SecurPharmaActionRequest request)
{
executor.execute(() -> delegate.handleActionRequest(request));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\actions\AsyncSecurPharmActionsDispatcher.java | 1 |
请完成以下Java代码 | public SetJobRetriesByJobsAsyncBuilder jobQuery(JobQuery query) {
this.jobQuery = query;
return this;
}
@Override
public SetJobRetriesByJobsAsyncBuilder jobIds(List<String> jobIds) {
this.jobIds = jobIds;
return this;
}
@Override
public SetJobRetriesAsyncBuilder dueDate(Date dueDate) {
this.dueDate = dueDate;
isDueDateSet = true;
return this;
} | @Override
public Batch executeAsync() {
validateParameters();
return commandExecutor.execute(new SetJobsRetriesBatchCmd(jobIds, jobQuery, retries, dueDate, isDueDateSet));
}
protected void validateParameters() {
ensureNotNull("commandExecutor", commandExecutor);
ensureNotNull("retries", retries);
if((jobIds == null || jobIds.isEmpty()) && jobQuery == null) {
throw LOG.exceptionSettingJobRetriesAsyncNoJobsSpecified();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\SetJobRetriesByJobsAsyncBuilderImpl.java | 1 |
请完成以下Java代码 | public class ProcessElementInstanceImpl implements ProcessElementInstance {
protected static final String[] NO_IDS = new String[0];
protected String id;
protected String parentActivityInstanceId;
protected String processInstanceId;
protected String processDefinitionId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParentActivityInstanceId() {
return parentActivityInstanceId;
}
public void setParentActivityInstanceId(String parentActivityInstanceId) {
this.parentActivityInstanceId = parentActivityInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
} | public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", parentActivityInstanceId=" + parentActivityInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessElementInstanceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersonController {
@Autowired
PersonService personService;
Logger logger = LoggerFactory.getLogger(PersonController.class);
@GetMapping("/persons/{id}")
public PersonEntity getPerson(@PathVariable("id") Long id) {
return personService.findPersonById(id);
}
@GetMapping("/persons")
public List<PersonEntity> listPerson() {
return personService.listPersons();
} | @PutMapping("/persons/{id}")
public ResponseEntity<PersonEntity> updatePerson(@PathVariable("id") Long id, @RequestBody PersonEntity person){
try {
PersonEntity entity = personService.updatePerson(id, person);
return new ResponseEntity<>(entity, HttpStatus.OK);
}
catch (RuntimeException ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);}
}
@PostMapping("/persons/batch")
public void batchCreatePerson(@RequestBody List<PersonEntity> persons) {
personService.createPersons(persons);
}
} | repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\hibernatejfr\rest\PersonController.java | 2 |
请完成以下Java代码 | public String getProcessInstanceId() {
return processInstanceId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
public String getActivityId() {
return activityId;
}
public String getType() {
return type;
}
public boolean getExcludeTaskRelated() { | return excludeTaskRelated;
}
public String getDetailId() {
return detailId;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public Date getOccurredBefore() {
return occurredBefore;
}
public Date getOccurredAfter() {
return occurredAfter;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isInitial() {
return initial;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDetailQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class X_QRCode_Attribute_Config extends org.compiere.model.PO implements I_QRCode_Attribute_Config, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1935730608L;
/** Standard Constructor */
public X_QRCode_Attribute_Config (final Properties ctx, final int QRCode_Attribute_Config_ID, @Nullable final String trxName)
{
super (ctx, QRCode_Attribute_Config_ID, trxName);
}
/** Load Constructor */
public X_QRCode_Attribute_Config (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Attribute_ID (final int AD_Attribute_ID)
{
if (AD_Attribute_ID < 1)
set_Value (COLUMNNAME_AD_Attribute_ID, null);
else
set_Value (COLUMNNAME_AD_Attribute_ID, AD_Attribute_ID);
}
@Override
public int getAD_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Attribute_ID);
}
@Override
public void setQRCode_Attribute_Config_ID (final int QRCode_Attribute_Config_ID)
{
if (QRCode_Attribute_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_QRCode_Attribute_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_QRCode_Attribute_Config_ID, QRCode_Attribute_Config_ID);
}
@Override
public int getQRCode_Attribute_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_QRCode_Attribute_Config_ID);
} | @Override
public I_QRCode_Configuration getQRCode_Configuration()
{
return get_ValueAsPO(COLUMNNAME_QRCode_Configuration_ID, I_QRCode_Configuration.class);
}
@Override
public void setQRCode_Configuration(final I_QRCode_Configuration QRCode_Configuration)
{
set_ValueFromPO(COLUMNNAME_QRCode_Configuration_ID, I_QRCode_Configuration.class, QRCode_Configuration);
}
@Override
public void setQRCode_Configuration_ID (final int QRCode_Configuration_ID)
{
if (QRCode_Configuration_ID < 1)
set_Value (COLUMNNAME_QRCode_Configuration_ID, null);
else
set_Value (COLUMNNAME_QRCode_Configuration_ID, QRCode_Configuration_ID);
}
@Override
public int getQRCode_Configuration_ID()
{
return get_ValueAsInt(COLUMNNAME_QRCode_Configuration_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_QRCode_Attribute_Config.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class VatCodeId implements RepoIdAware
{
@JsonCreator
public static VatCodeId ofRepoId(final int repoId)
{
return new VatCodeId(repoId);
}
public static VatCodeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new VatCodeId(repoId) : null;
}
public static int toRepoId(@Nullable final VatCodeId id)
{
return id != null ? id.getRepoId() : -1;
} | int repoId;
private VatCodeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Vat_Code_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\tax\api\VatCodeId.java | 2 |
请完成以下Java代码 | public class LwM2mResourceObserve {
@Schema(description = "LwM2M Resource Observe id.", example = "0")
int id;
@Schema(description = "LwM2M Resource Observe name.", example = "Data")
String name;
@Schema(description = "LwM2M Resource Observe observe.", example = "false")
boolean observe;
@Schema(description = "LwM2M Resource Observe attribute.", example = "false")
boolean attribute;
@Schema(description = "LwM2M Resource Observe telemetry.", example = "false")
boolean telemetry;
@Schema(description = "LwM2M Resource Observe key name.", example = "data")
String keyName;
public LwM2mResourceObserve(int id, String name, boolean observe, boolean attribute, boolean telemetry) {
this.id = id;
this.name = name;
this.observe = observe;
this.attribute = attribute;
this.telemetry = telemetry;
this.keyName = getCamelCase (this.name);
}
private String getCamelCase (String name) {
name = name.replaceAll("-", " "); | name = name.replaceAll("_", " ");
String [] nameCamel1 = name.split(" ");
String [] nameCamel2 = new String[nameCamel1.length];
int[] idx = { 0 };
Stream.of(nameCamel1).forEach((s -> {
nameCamel2[idx[0]] = toProperCase(idx[0]++, s);
}));
return String.join("", nameCamel2);
}
private String toProperCase(int idx, String s) {
if (!s.isEmpty() && s.length()> 0) {
String s1 = (idx == 0) ? s.substring(0, 1).toLowerCase() : s.substring(0, 1).toUpperCase();
String s2 = "";
if (s.length()> 1) s2 = s.substring(1).toLowerCase();
s = s1 + s2;
}
return s;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\lwm2m\LwM2mResourceObserve.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User other = (User) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (organization == null) {
if (other.organization != null) {
return false;
}
} else if (!organization.equals(other.organization)) {
return false;
}
if (password == null) {
if (other.password != null) {
return false;
} | } else if (!password.equals(other.password)) {
return false;
}
if (privileges == null) {
if (other.privileges != null) {
return false;
}
} else if (!privileges.equals(other.privileges)) {
return false;
}
if (username == null) {
if (other.username != null) {
return false;
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\User.java | 1 |
请完成以下Java代码 | public boolean isEnableFeelLegacyBehavior() {
return enableFeelLegacyBehavior;
}
/**
* Controls whether the FEEL legacy behavior is enabled or not
*
* @param enableFeelLegacyBehavior the FEEL legacy behavior
*/
public void setEnableFeelLegacyBehavior(boolean enableFeelLegacyBehavior) {
this.enableFeelLegacyBehavior = enableFeelLegacyBehavior;
}
/**
* Controls whether the FEEL legacy behavior is enabled or not
*
* @param enableFeelLegacyBehavior the FEEL legacy behavior
* @return this
*/
public DefaultDmnEngineConfiguration enableFeelLegacyBehavior(boolean enableFeelLegacyBehavior) {
setEnableFeelLegacyBehavior(enableFeelLegacyBehavior);
return this;
} | /**
* @return whether blank table outputs are swallowed or returned as {@code null}.
*/
public boolean isReturnBlankTableOutputAsNull() {
return returnBlankTableOutputAsNull;
}
/**
* Controls whether blank table outputs are swallowed or returned as {@code null}.
*
* @param returnBlankTableOutputAsNull toggles whether blank table outputs are swallowed or returned as {@code null}.
* @return this
*/
public DefaultDmnEngineConfiguration setReturnBlankTableOutputAsNull(boolean returnBlankTableOutputAsNull) {
this.returnBlankTableOutputAsNull = returnBlankTableOutputAsNull;
return this;
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnEngineConfiguration.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.