Datasets:
instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setAD_Index_Table_ID (int AD_Index_Table_ID)
{
if (AD_Index_Table_ID < 1)
set_Value (COLUMNNAME_AD_Index_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Index_Table_ID, Integer.valueOf(AD_Index_Table_ID));
}
/** Get Table Index.
@return Table Index */
public int getAD_Index_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Index_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Column SQL.
@param ColumnSQL
Virtual Column (r/o)
*/
public void setColumnSQL (String ColumnSQL)
{
set_Value (COLUMNNAME_ColumnSQL, ColumnSQL);
}
/** Get Column SQL.
@return Virtual Column (r/o)
*/
public String getColumnSQL ()
{
return (String)get_Value(COLUMNNAME_ColumnSQL);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
|
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Column.java
| 1
|
请完成以下Java代码
|
private static int[] getArrayFromSet(Set<Integer> set) {
int[] mergedArrWithoutDuplicated = new int[set.size()];
int i = 0;
for (Integer el: set) {
mergedArrWithoutDuplicated[i] = el;
i++;
}
return mergedArrWithoutDuplicated;
}
public static int[] mergeAndRemoveDuplicates(int[] arr1, int[] arr2) {
return removeDuplicate(mergeArrays(arr1, arr2));
}
public static int[] mergeAndRemoveDuplicatesOnSortedArray(int[] arr1, int[] arr2) {
return removeDuplicateOnSortedArray(mergeArrays(arr1, arr2));
}
private static int[] mergeArrays(int[] arr1, int[] arr2) {
int[] mergedArrays = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, mergedArrays, 0, arr1.length);
System.arraycopy(arr2, 0, mergedArrays, arr1.length, arr2.length);
return mergedArrays;
}
private static int[] removeDuplicate(int[] arr) {
int[] withoutDuplicates = new int[arr.length];
int i = 0;
for(int element : arr) {
|
if(!isElementPresent(withoutDuplicates, element)) {
withoutDuplicates[i] = element;
i++;
}
}
int[] truncatedArray = new int[i];
System.arraycopy(withoutDuplicates, 0, truncatedArray, 0, i);
return truncatedArray;
}
private static boolean isElementPresent(int[] arr, int element) {
for(int el : arr) {
if(el == element) {
return true;
}
}
return false;
}
}
|
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\mergeandremoveduplicate\MergeArraysAndRemoveDuplicate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void setUserTenantAndDepart(SysUser sysUser, JSONObject obj, Result<JSONObject> result) {
//1.设置登录租户
sysUserService.setLoginTenant(sysUser, obj, sysUser.getUsername(), result);
//2.设置登录部门
String orgCode = sysUser.getOrgCode();
//部门不为空还是用原来的部门code
if(StringUtils.isEmpty(orgCode)){
List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
//部门不为空取第一个作为当前登录部门
if(CollectionUtil.isNotEmpty(departs)){
orgCode = departs.get(0).getOrgCode();
sysUser.setOrgCode(orgCode);
this.sysUserService.updateUserDepart(sysUser.getUsername(), orgCode,null);
}
}
}
/**
* 新版钉钉登录
*
* @param authCode
* @param state
* @param tenantId
* @param response
* @return
*/
@ResponseBody
@GetMapping("/oauth2/dingding/login")
public String OauthDingDingLogin(@RequestParam(value = "authCode", required = false) String authCode,
@RequestParam("state") String state,
@RequestParam(name = "tenantId",defaultValue = "0") String tenantId,
HttpServletResponse response) {
SysUser loginUser = thirdAppDingtalkService.oauthDingDingLogin(authCode,Integer.valueOf(tenantId));
try {
String redirect = "";
if (state.indexOf("?") > 0) {
String[] arr = state.split("\\?");
state = arr[0];
if(arr.length>1){
redirect = arr[1];
}
}
String token = saveToken(loginUser);
state += "/oauth2-app/login?oauth2LoginToken=" + URLEncoder.encode(token, "UTF-8") + "&tenantId=" + URLEncoder.encode(tenantId, "UTF-8");
state += "&thirdType=DINGTALK";
if (redirect != null && redirect.length() > 0) {
state += "&" + redirect;
}
log.info("OAuth2登录重定向地址: " + state);
try {
response.sendRedirect(state);
|
return "ok";
} catch (IOException e) {
log.error(e.getMessage(),e);
return "重定向失败";
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(),e);
return "解码失败";
}
}
/**
* 获取企业id和应用id
* @param tenantId
* @return
*/
@ResponseBody
@GetMapping("/get/corpId/clientId")
public Result<SysThirdAppConfig> getCorpIdClientId(@RequestParam(value = "tenantId", defaultValue = "0") String tenantId){
Result<SysThirdAppConfig> result = new Result<>();
SysThirdAppConfig sysThirdAppConfig = thirdAppDingtalkService.getCorpIdClientId(Integer.valueOf(tenantId));
result.setSuccess(true);
result.setResult(sysThirdAppConfig);
return result;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\ThirdLoginController.java
| 2
|
请完成以下Java代码
|
public Boolean toBooleanOrNull()
{
switch (this)
{
case TRUE:
return Boolean.TRUE;
case FALSE:
return Boolean.FALSE;
case UNKNOWN:
return null;
default:
throw new IllegalStateException("Type not handled: " + this);
}
}
@Nullable
public String toBooleanString()
{
return StringUtils.ofBoolean(toBooleanOrNull());
}
public void ifPresent(@NonNull final BooleanConsumer action)
{
if (this == TRUE)
{
action.accept(true);
|
}
else if (this == FALSE)
{
action.accept(false);
}
}
public void ifTrue(@NonNull final Runnable action)
{
if (this == TRUE)
{
action.run();
}
}
public <U> Optional<U> map(@NonNull final BooleanFunction<? extends U> mapper)
{
return isPresent() ? Optional.ofNullable(mapper.apply(isTrue())) : Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\OptionalBoolean.java
| 1
|
请完成以下Java代码
|
public Stream<HUWithExpiryDates> streamByWarnDateExceeded(@NonNull final LocalDate today)
{
final Timestamp todayTS = TimeUtil.asTimestamp(today);
return queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addCompareFilter(I_M_HU_BestBefore_V.COLUMN_HU_ExpiredWarnDate, Operator.LESS_OR_EQUAL, todayTS, DateTruncQueryFilterModifier.DAY)
.addNotEqualsFilter(I_M_HU_BestBefore_V.COLUMN_HU_Expired, HUAttributeConstants.ATTR_Expired_Value_Expired)
.orderBy(I_M_HU_BestBefore_V.COLUMN_M_HU_ID)
.create()
.iterateAndStream()
.map(record -> ofRecordOrNull(record));
}
private static HUWithExpiryDates ofRecordOrNull(@Nullable final I_M_HU_BestBefore_V record)
{
if (record == null)
{
return null;
}
return HUWithExpiryDates.builder()
.huId(HuId.ofRepoId(record.getM_HU_ID()))
.bestBeforeDate(TimeUtil.asLocalDate(record.getHU_BestBeforeDate()))
.expiryWarnDate(TimeUtil.asLocalDate(record.getHU_ExpiredWarnDate()))
.build();
}
public HUWithExpiryDates getByIdIfWarnDateExceededOrNull(
@NonNull final HuId huId,
@Nullable final LocalDate expiryWarnDate)
{
final Timestamp timestamp = TimeUtil.asTimestamp(expiryWarnDate);
|
final I_M_HU_BestBefore_V recordOrdNull = queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addCompareFilter(I_M_HU_BestBefore_V.COLUMN_HU_ExpiredWarnDate, Operator.LESS_OR_EQUAL, timestamp, DateTruncQueryFilterModifier.DAY)
.addNotEqualsFilter(I_M_HU_BestBefore_V.COLUMN_HU_Expired, HUAttributeConstants.ATTR_Expired_Value_Expired)
.addEqualsFilter(I_M_HU_BestBefore_V.COLUMN_M_HU_ID, huId)
.create()
.firstOnly(I_M_HU_BestBefore_V.class);
return ofRecordOrNull(recordOrdNull);
}
public HUWithExpiryDates getById(@NonNull final HuId huId)
{
final I_M_HU_BestBefore_V recordOrdNull = queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addEqualsFilter(I_M_HU_BestBefore_V.COLUMN_M_HU_ID, huId)
.create()
.firstOnly(I_M_HU_BestBefore_V.class);
return ofRecordOrNull(recordOrdNull);
}
public Iterator<HuId> getAllWithBestBeforeDate()
{
return handlingUnitsDAO.createHUQueryBuilder()
.addOnlyWithAttributeNotNull(AttributeConstants.ATTR_BestBeforeDate)
.addHUStatusesToInclude(huStatusBL.getQtyOnHandStatuses())
.createQuery()
.iterateIds(HuId::ofRepoId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\HUWithExpiryDatesRepository.java
| 1
|
请完成以下Java代码
|
public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() {
return toVersionControl;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() {
return toHousekeeper;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() {
return toEdge;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() {
return toEdgeNotifications;
|
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() {
return toEdgeEvents;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() {
return toCalculatedFields;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() {
return toCalculatedFieldNotifications;
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbCoreQueueProducerProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private @Nullable AsyncTaskExecutor determineBootstrapExecutor(Map<String, AsyncTaskExecutor> taskExecutors) {
if (taskExecutors.size() == 1) {
return taskExecutors.values().iterator().next();
}
return taskExecutors.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME);
}
private static final class BootstrapExecutorCondition extends AnyNestedCondition {
BootstrapExecutorCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "deferred")
static class DeferredBootstrapMode {
}
@ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "lazy")
static class LazyBootstrapMode {
}
|
}
static class JpaRepositoriesImportSelector implements ImportSelector {
private static final boolean ENVERS_AVAILABLE = ClassUtils.isPresent(
"org.springframework.data.envers.repository.config.EnableEnversRepositories",
JpaRepositoriesImportSelector.class.getClassLoader());
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[] { determineImport() };
}
private String determineImport() {
return ENVERS_AVAILABLE ? EnversRevisionRepositoriesRegistrar.class.getName()
: DataJpaRepositoriesRegistrar.class.getName();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-jpa\src\main\java\org\springframework\boot\data\jpa\autoconfigure\DataJpaRepositoriesAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public HttpSyncGraphQlClient build() {
this.restClientBuilder.configureMessageConverters((builder) -> {
builder.registerDefaults().configureMessageConverters((converter) -> {
if (HttpMessageConverterDelegate.isJsonConverter(converter)) {
setJsonConverter((HttpMessageConverter<Object>) converter);
}
});
});
RestClient restClient = this.restClientBuilder.build();
HttpSyncGraphQlTransport transport = new HttpSyncGraphQlTransport(restClient);
GraphQlClient graphQlClient = super.buildGraphQlClient(transport);
return new DefaultHttpSyncGraphQlClient(graphQlClient, restClient, getBuilderInitializer());
}
/**
* Default {@link HttpSyncGraphQlClient} implementation.
*/
private static class DefaultHttpSyncGraphQlClient
extends AbstractDelegatingGraphQlClient implements HttpSyncGraphQlClient {
private final RestClient restClient;
private final Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer;
DefaultHttpSyncGraphQlClient(
GraphQlClient delegate, RestClient restClient,
Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer) {
|
super(delegate);
Assert.notNull(restClient, "RestClient is required");
Assert.notNull(builderInitializer, "`builderInitializer` is required");
this.restClient = restClient;
this.builderInitializer = builderInitializer;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder mutate() {
DefaultSyncHttpGraphQlClientBuilder builder = new DefaultSyncHttpGraphQlClientBuilder(this.restClient);
this.builderInitializer.accept(builder);
return builder;
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultSyncHttpGraphQlClientBuilder.java
| 1
|
请完成以下Java代码
|
public static ColumnNameFQ ofTableAndColumnName(@NonNull final TableName tableName, @NonNull final String columnName)
{
return new ColumnNameFQ(tableName, ColumnName.ofString(columnName));
}
public static ColumnNameFQ ofTableAndColumnName(@NonNull final TableName tableName, @NonNull final ColumnName columnName)
{
return new ColumnNameFQ(tableName, columnName);
}
private ColumnNameFQ(@NonNull final TableName tableName, @NonNull final ColumnName columnName)
{
this.tableName = tableName;
this.columnName = columnName;
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
public String getAsString()
{
return tableName.getAsString() + "." + columnName.getAsString();
}
public static TableName extractSingleTableName(final ColumnNameFQ... columnNames)
{
if (columnNames == null || columnNames.length == 0)
{
throw new AdempiereException("Cannot extract table name from null/empty column names array");
|
}
TableName singleTableName = null;
for (final ColumnNameFQ columnNameFQ : columnNames)
{
if (columnNameFQ == null)
{
continue;
}
else if (singleTableName == null)
{
singleTableName = columnNameFQ.getTableName();
}
else if (!TableName.equals(singleTableName, columnNameFQ.getTableName()))
{
throw new AdempiereException("More than one table name found in " + Arrays.asList(columnNames));
}
}
if (singleTableName == null)
{
throw new AdempiereException("Cannot extract table name from null/empty column names array: " + Arrays.asList(columnNames));
}
return singleTableName;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\ColumnNameFQ.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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代码
|
public Response index() {
return Response.ok()
.entity(meals)
.build();
}
@GET
@Path("/{id}")
@Produces({ "application/json" })
public Response meal(@PathParam("id") int id) {
return Response.ok()
.entity(meals.get(id))
.build();
}
@POST
@Path("/")
@Consumes("application/json")
@Produces({ "application/json" })
public Response create(Meal meal) {
meals.add(meal);
return Response.ok()
.entity(meal)
.build();
}
@PUT
@Path("/{id}")
@Consumes("application/json")
@Produces({ "application/json" })
public Response update(@PathParam("id") int id, Meal meal) {
meals.set(id, meal);
return Response.ok()
|
.entity(meal)
.build();
}
@DELETE
@Path("/{id}")
@Produces({ "application/json" })
public Response delete(@PathParam("id") int id) {
Meal meal = meals.get(id);
meals.remove(id);
return Response.ok()
.entity(meal)
.build();
}
}
|
repos\tutorials-master\microservices-modules\msf4j\src\main\java\com\baeldung\msf4j\msf4japi\MenuService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SwaggerDataConfig {
@Bean
public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) {
return new AlternateTypeRuleConvention() {
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
@Override
public List<AlternateTypeRule> rules() {
return CollUtil.newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class)));
}
};
|
}
@ApiModel
@Data
private static class Page {
@ApiModelProperty("页码 (0..N)")
private Integer page;
@ApiModelProperty("每页显示的数目")
private Integer size;
@ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc")
private List<String> sort;
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\webConfig\SwaggerDataConfig.java
| 2
|
请完成以下Java代码
|
public void inverseMatrix() {
Matrix m1 = new DenseMatrix(new double[][]{
{1, 2},
{3, 4}
});
Inverse m2 = new Inverse(m1);
log.info("Inverting a matrix: {}", m2);
log.info("Verifying a matrix inverse: {}", m1.multiply(m2));
}
public Polynomial createPolynomial() {
return new Polynomial(new double[]{3, -5, 1});
}
|
public void evaluatePolynomial(Polynomial p) {
// Evaluate using a real number
log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5));
// Evaluate using a complex number
log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2)));
}
public void solvePolynomial() {
Polynomial p = new Polynomial(new double[]{2, 2, -4});
PolyRootSolver solver = new PolyRoot();
List<? extends Number> roots = solver.solve(p);
log.info("Finding polynomial roots: {}", roots);
}
}
|
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\suanshu\SuanShuMath.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<PmsOperator> listOperatorByRoleId(Long roleId) {
return pmsOperatorDao.listByRoleId(roleId);
}
/**
* 修改操作員信息及其关联的角色.
*
* @param pmsOperator
* .
* @param OperatorRoleStr
* .
*/
public void updateOperator(PmsOperator pmsOperator, String OperatorRoleStr) {
pmsOperatorDao.update(pmsOperator);
// 更新角色信息
saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
}
/**
* 保存用户和角色之间的关联关系
*/
private void saveOrUpdateOperatorRole(Long operatorId, String roleIdsStr) {
// 删除原来的角色与操作员关联
List<PmsOperatorRole> listPmsOperatorRoles = pmsOperatorRoleDao.listByOperatorId(operatorId);
Map<Long, PmsOperatorRole> delMap = new HashMap<Long, PmsOperatorRole>();
for (PmsOperatorRole pmsOperatorRole : listPmsOperatorRoles) {
delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
}
if (StringUtils.isNotBlank(roleIdsStr)) {
|
// 创建新的关联
String[] roleIds = roleIdsStr.split(",");
for (int i = 0; i < roleIds.length; i++) {
Long roleId = Long.valueOf(roleIds[i]);
if (delMap.get(roleId) == null) {
PmsOperatorRole pmsOperatorRole = new PmsOperatorRole();
pmsOperatorRole.setOperatorId(operatorId);
pmsOperatorRole.setRoleId(roleId);
pmsOperatorRoleDao.insert(pmsOperatorRole);
} else {
delMap.remove(roleId);
}
}
}
Iterator<Long> iterator = delMap.keySet().iterator();
while (iterator.hasNext()) {
Long roleId = iterator.next();
pmsOperatorRoleDao.deleteByRoleIdAndOperatorId(roleId, operatorId);
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorRoleServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SessionRepositoryMessageInterceptor<S> sessionRepositoryInterceptor() {
return new SessionRepositoryMessageInterceptor<>(this.sessionRepository);
}
/**
* A {@link StompEndpointRegistry} that applies {@link HandshakeInterceptor}.
*/
static class SessionStompEndpointRegistry implements StompEndpointRegistry {
private final WebMvcStompEndpointRegistry registry;
private final HandshakeInterceptor interceptor;
SessionStompEndpointRegistry(WebMvcStompEndpointRegistry registry, HandshakeInterceptor interceptor) {
this.registry = registry;
this.interceptor = interceptor;
}
@Override
public StompWebSocketEndpointRegistration addEndpoint(String... paths) {
StompWebSocketEndpointRegistration endpoints = this.registry.addEndpoint(paths);
endpoints.addInterceptors(this.interceptor);
return endpoints;
}
|
@Override
public void setOrder(int order) {
this.registry.setOrder(order);
}
@Override
public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
this.registry.setUrlPathHelper(urlPathHelper);
}
@Override
public WebMvcStompEndpointRegistry setErrorHandler(StompSubProtocolErrorHandler errorHandler) {
return this.registry.setErrorHandler(errorHandler);
}
@Override
public WebMvcStompEndpointRegistry setPreserveReceiveOrder(boolean preserveReceiveOrder) {
return this.registry.setPreserveReceiveOrder(preserveReceiveOrder);
}
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\config\annotation\AbstractSessionWebSocketMessageBrokerConfigurer.java
| 2
|
请完成以下Java代码
|
public Set<String> findAllPalindromesUsingBruteForceApproach(String input) {
Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j <= input.length(); j++)
if (isPalindrome(input.substring(i, j))) {
palindromes.add(input.substring(i, j));
}
}
return palindromes;
}
private boolean isPalindrome(String input) {
StringBuilder plain = new StringBuilder(input);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(input);
}
public Set<String> findAllPalindromesUsingManachersAlgorithm(String input) {
Set<String> palindromes = new HashSet<>();
String formattedInput = "@" + input + "#";
char inputCharArr[] = formattedInput.toCharArray();
int max;
int radius[][] = new int[2][input.length() + 1];
for (int j = 0; j <= 1; j++) {
radius[j][0] = max = 0;
int i = 1;
while (i <= input.length()) {
palindromes.add(Character.toString(inputCharArr[i]));
while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
max++;
radius[j][i] = max;
|
int k = 1;
while ((radius[j][i - k] != max - k) && (k < max)) {
radius[j][i + k] = Math.min(radius[j][i - k], max - k);
k++;
}
max = Math.max(max - k, 0);
i += k;
}
}
for (int i = 1; i <= input.length(); i++) {
for (int j = 0; j <= 1; j++) {
for (max = radius[j][i]; max > 0; max--) {
palindromes.add(input.substring(i - max - 1, max + j + i - 1));
}
}
}
return palindromes;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\string\SubstringPalindrome.java
| 1
|
请完成以下Java代码
|
public void setPrev_CurrentCostPrice (java.math.BigDecimal Prev_CurrentCostPrice)
{
set_Value (COLUMNNAME_Prev_CurrentCostPrice, Prev_CurrentCostPrice);
}
/** Get Previous Current Cost Price.
@return Previous Current Cost Price */
@Override
public java.math.BigDecimal getPrev_CurrentCostPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentCostPrice);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Previous Current Cost Price LL.
@param Prev_CurrentCostPriceLL Previous Current Cost Price LL */
@Override
public void setPrev_CurrentCostPriceLL (java.math.BigDecimal Prev_CurrentCostPriceLL)
{
set_Value (COLUMNNAME_Prev_CurrentCostPriceLL, Prev_CurrentCostPriceLL);
}
/** Get Previous Current Cost Price LL.
@return Previous Current Cost Price LL */
@Override
public java.math.BigDecimal getPrev_CurrentCostPriceLL ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentCostPriceLL);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Previous Current Qty.
@param Prev_CurrentQty Previous Current Qty */
@Override
public void setPrev_CurrentQty (java.math.BigDecimal Prev_CurrentQty)
{
set_Value (COLUMNNAME_Prev_CurrentQty, Prev_CurrentQty);
}
|
/** Get Previous Current Qty.
@return Previous Current Qty */
@Override
public java.math.BigDecimal getPrev_CurrentQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_CostDetailAdjust.java
| 1
|
请完成以下Java代码
|
public void configure(Map<String, ?> configs, boolean isKey) {
super.configure(configs, isKey);
}
@Override
protected Deserializer<?> configureDelegate(Map<String, ?> configs, boolean isKey, Deserializer<?> delegate) {
delegate.configure(configs, isKey);
return delegate;
}
@Override
protected boolean isInstance(Object delegate) {
return delegate instanceof Deserializer;
}
|
@Override
public Object deserialize(String topic, byte[] data) {
throw new UnsupportedOperationException();
}
@Override
public @Nullable Object deserialize(String topic, Headers headers, byte[] data) {
return findDelegate(topic).deserialize(topic, headers, data);
}
@Override
public @Nullable Object deserialize(String topic, Headers headers, ByteBuffer data) {
return findDelegate(topic).deserialize(topic, headers, data);
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTopicDeserializer.java
| 1
|
请完成以下Java代码
|
public int getAD_Client_ID()
{
return invoiceLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return invoiceLine.getAD_Org_ID();
}
@Override
public boolean isSOTrx()
{
final I_C_Invoice invoice = getInvoice();
return invoice.isSOTrx();
}
@Override
public I_C_Country getC_Country()
{
final I_C_Invoice invoice = getInvoice();
|
if (invoice.getC_BPartner_Location_ID() <= 0)
{
return null;
}
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner_Location bPartnerLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(BPartnerLocationId.ofRepoId(invoice.getC_BPartner_ID(), invoice.getC_BPartner_Location_ID()));
return bPartnerLocationRecord.getC_Location().getC_Country();
}
private I_C_Invoice getInvoice()
{
final I_C_Invoice invoice = invoiceLine.getC_Invoice();
if (invoice == null)
{
throw new AdempiereException("Invoice not set for" + invoiceLine);
}
return invoice;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\InvoiceLineCountryAware.java
| 1
|
请完成以下Java代码
|
public UserOperationLogContextEntry create() {
return entry;
}
public UserOperationLogContextEntryBuilder jobId(String jobId) {
entry.setJobId(jobId);
return this;
}
public UserOperationLogContextEntryBuilder jobDefinitionId(String jobDefinitionId) {
entry.setJobDefinitionId(jobDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder processDefinitionId(String processDefinitionId) {
entry.setProcessDefinitionId(processDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder processDefinitionKey(String processDefinitionKey) {
entry.setProcessDefinitionKey(processDefinitionKey);
return this;
}
public UserOperationLogContextEntryBuilder processInstanceId(String processInstanceId) {
entry.setProcessInstanceId(processInstanceId);
return this;
}
public UserOperationLogContextEntryBuilder caseDefinitionId(String caseDefinitionId) {
entry.setCaseDefinitionId(caseDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder deploymentId(String deploymentId) {
entry.setDeploymentId(deploymentId);
return this;
}
public UserOperationLogContextEntryBuilder batchId(String batchId) {
entry.setBatchId(batchId);
return this;
}
public UserOperationLogContextEntryBuilder taskId(String taskId) {
entry.setTaskId(taskId);
|
return this;
}
public UserOperationLogContextEntryBuilder caseInstanceId(String caseInstanceId) {
entry.setCaseInstanceId(caseInstanceId);
return this;
}
public UserOperationLogContextEntryBuilder category(String category) {
entry.setCategory(category);
return this;
}
public UserOperationLogContextEntryBuilder annotation(String annotation) {
entry.setAnnotation(annotation);
return this;
}
public UserOperationLogContextEntryBuilder tenantId(String tenantId) {
entry.setTenantId(tenantId);
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntryBuilder.java
| 1
|
请完成以下Java代码
|
private DispatcherHandlerMappingDescription describe(Entry<PathPattern, Object> mapping) {
return new DispatcherHandlerMappingDescription(mapping.getKey().getPatternString(),
mapping.getValue().toString(), null);
}
}
private static final class RouterFunctionMappingDescriptionProvider
implements HandlerMappingDescriptionProvider<RouterFunctionMapping> {
@Override
public Class<RouterFunctionMapping> getMappingClass() {
return RouterFunctionMapping.class;
}
@Override
public List<DispatcherHandlerMappingDescription> describe(RouterFunctionMapping handlerMapping) {
MappingDescriptionVisitor visitor = new MappingDescriptionVisitor();
RouterFunction<?> routerFunction = handlerMapping.getRouterFunction();
if (routerFunction != null) {
routerFunction.accept(visitor);
}
return visitor.descriptions;
}
}
private static final class MappingDescriptionVisitor implements Visitor {
private final List<DispatcherHandlerMappingDescription> descriptions = new ArrayList<>();
@Override
public void startNested(RequestPredicate predicate) {
}
@Override
public void endNested(RequestPredicate predicate) {
}
@Override
public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) {
DispatcherHandlerMappingDetails details = new DispatcherHandlerMappingDetails();
details.setHandlerFunction(new HandlerFunctionDescription(handlerFunction));
this.descriptions.add(
new DispatcherHandlerMappingDescription(predicate.toString(), handlerFunction.toString(), details));
}
|
@Override
public void resources(Function<ServerRequest, Mono<Resource>> lookupFunction) {
}
@Override
public void attributes(Map<String, Object> attributes) {
}
@Override
public void unknown(RouterFunction<?> routerFunction) {
}
}
static class DispatcherHandlersMappingDescriptionProviderRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(),
DispatcherHandlerMappingDescription.class);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\DispatcherHandlersMappingDescriptionProvider.java
| 1
|
请完成以下Java代码
|
public void buildByteOutputStream(final ByteArrayOutputStream out, final TargetDataLine line, int frameSizeInBytes, final int bufferLengthInBytes) throws IOException {
final byte[] data = new byte[bufferLengthInBytes];
int numBytesRead;
line.start();
while (thread != null) {
if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;
}
out.write(data, 0, numBytesRead);
}
}
private void setAudioInputStream(AudioInputStream aStream) {
this.audioInputStream = aStream;
}
public AudioInputStream convertToAudioIStream(final ByteArrayOutputStream out, int frameSizeInBytes) {
byte audioBytes[] = out.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);
AudioInputStream audioStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);
long milliseconds = (long) ((audioInputStream.getFrameLength() * 1000) / format.getFrameRate());
duration = milliseconds / 1000.0;
System.out.println("Recorded duration in seconds:" + duration);
return audioStream;
}
public TargetDataLine getTargetDataLineForRecord() {
TargetDataLine line;
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
|
return null;
}
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (final Exception ex) {
return null;
}
return line;
}
public AudioInputStream getAudioInputStream() {
return audioInputStream;
}
public AudioFormat getFormat() {
return format;
}
public void setFormat(AudioFormat format) {
this.format = format;
}
public Thread getThread() {
return thread;
}
public double getDuration() {
return duration;
}
}
|
repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\example\soundapi\SoundRecorder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GoogleController {
@Autowired
private GoogleService service;
@GetMapping(value ="/me/google")
public void me(HttpServletResponse response){
String auth = service.getService().getAuthorizationUrl();
response.setHeader("Location", auth);
response.setStatus(302);
}
@GetMapping(value = "/auth/google")
public String google(@RequestParam String code, HttpServletResponse servletResponse){
try {
|
OAuth2AccessToken token = service.getService().getAccessToken(code);
OAuthRequest request = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo?alt=json");
service.getService().signRequest(token, request);
Response response = service.getService().execute(request);
return response.getBody();
}catch (Exception e){
servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
return null;
}
}
|
repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\scribejava\controller\GoogleController.java
| 2
|
请完成以下Java代码
|
public void setDbType(String dbType) {
this.dbType = dbType;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
public String getVal() {
return val;
}
|
public void setVal(String val) {
this.val = val;
}
@Override
public String toString(){
StringBuffer sb =new StringBuffer();
if(field == null || "".equals(field)){
return "";
}
sb.append(this.field).append(" ").append(this.rule).append(" ").append(this.type).append(" ").append(this.dbType).append(" ").append(this.val);
return sb.toString();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\query\QueryCondition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Connector getConnector() {
return this.connector;
}
public void setConnector(@Nullable Connector connector) {
this.connector = connector;
}
/**
* Supported factory types.
*/
public enum Connector {
/**
* Reactor-Netty.
*/
REACTOR(ClientHttpConnectorBuilder::reactor),
/**
* Jetty's HttpClient.
*/
JETTY(ClientHttpConnectorBuilder::jetty),
/**
* Apache HttpComponents HttpClient.
*/
HTTP_COMPONENTS(ClientHttpConnectorBuilder::httpComponents),
|
/**
* Java's HttpClient.
*/
JDK(ClientHttpConnectorBuilder::jdk);
private final Supplier<ClientHttpConnectorBuilder<?>> builderSupplier;
Connector(Supplier<ClientHttpConnectorBuilder<?>> builderSupplier) {
this.builderSupplier = builderSupplier;
}
ClientHttpConnectorBuilder<?> builder() {
return this.builderSupplier.get();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\reactive\ReactiveHttpClientsProperties.java
| 2
|
请完成以下Java代码
|
public class DataSetBatch {
public static void main(String[] args) throws Exception {
// 创建执行环境
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
// 获取文件路径
String path = DataSetBatch.class.getClassLoader().getResource("word.txt").getPath();
// 从文件中读取数据
DataSource<String> lineDS = env.readTextFile(path);
// 切分、转换,例如: (word,1)
FlatMapOperator<String, Tuple2<String, Integer>> wordAndOne = lineDS.flatMap(new MyFlatMapper());
// 按word分组 按照第一个位置的word分组
UnsortedGrouping<Tuple2<String, Integer>> wordAndOneGroupby = wordAndOne.groupBy(0);
// 分组内聚合统计 将第二个位置上的数据求和
AggregateOperator<Tuple2<String, Integer>> sum = wordAndOneGroupby.sum(1);
// 输出
sum.print();
}
|
/**
* 自定义MyFlatMapper类,实现FlatMapFunction接口
* 输出: String 元组Tuple2<String, Integer>> Tuple2是flink提供的元组类型
*/
public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {
@Override
//value是输入,out就是输出的数据
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
// 按空格切分单词
String[] words = value.split(" ");
// 遍历所有word,包成二元组输出 将单词转换为 (word,1)
for (String word : words) {
Tuple2<String, Integer> wordTuple2 = Tuple2.of(word, 1);
// 使用Collector向下游发送数据
out.collect(wordTuple2);
}
}
}
}
|
repos\springboot-demo-master\flink\src\main\java\com\et\flink\job\DataSetBatch.java
| 1
|
请完成以下Java代码
|
public static String convertDecimalToFractionUsingGCD(double decimal) {
String decimalStr = String.valueOf(decimal);
int decimalPlaces = decimalStr.length() - decimalStr.indexOf('.') - 1;
long denominator = (long) Math.pow(10, decimalPlaces);
long numerator = (long) (decimal * denominator);
long gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
return numerator + "/" + denominator;
}
public static String convertDecimalToFractionUsingApacheCommonsMath(double decimal) {
Fraction fraction = new Fraction(decimal);
return fraction.toString();
}
private static String extractRepeatingDecimal(String fractionalPart) {
int length = fractionalPart.length();
for (int i = 1; i <= length / 2; i++) {
String sub = fractionalPart.substring(0, i);
boolean repeating = true;
for (int j = i; j + i <= length; j += i) {
if (!fractionalPart.substring(j, j + i)
.equals(sub)) {
repeating = false;
break;
}
}
|
if (repeating) {
return sub;
}
}
return "";
}
public static String convertDecimalToFractionUsingGCDRepeating(double decimal) {
String decimalStr = String.valueOf(decimal);
int indexOfDot = decimalStr.indexOf('.');
String afterDot = decimalStr.substring(indexOfDot + 1);
String repeatingNumber = extractRepeatingDecimal(afterDot);
if (repeatingNumber == "") {
return convertDecimalToFractionUsingGCD(decimal);
} else {
int n = repeatingNumber.length();
int repeatingValue = Integer.parseInt(repeatingNumber);
int integerPart = Integer.parseInt(decimalStr.substring(0, indexOfDot));
long denominator = (long) Math.pow(10, n) - 1;
long numerator = repeatingValue + (integerPart * denominator);
long gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
return numerator + "/" + denominator;
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-8\src\main\java\com\baeldung\decimaltofraction\DecimalToFraction.java
| 1
|
请完成以下Java代码
|
private int getTemplateTabIdEffective()
{
return _templateTabId > 0 ? _templateTabId : getAD_Tab_ID();
}
public GridFieldVOsLoader setTabIncludeFiltersStrategy(@NonNull final TabIncludeFiltersStrategy tabIncludeFiltersStrategy)
{
this.tabIncludeFiltersStrategy = tabIncludeFiltersStrategy;
return this;
}
public GridFieldVOsLoader setTabReadOnly(final boolean tabReadOnly)
{
_tabReadOnly = tabReadOnly;
return this;
}
private boolean isTabReadOnly()
{
return _tabReadOnly;
}
public GridFieldVOsLoader setLoadAllLanguages(final boolean loadAllLanguages)
{
_loadAllLanguages = loadAllLanguages;
|
return this;
}
private boolean isLoadAllLanguages()
{
return _loadAllLanguages;
}
public GridFieldVOsLoader setApplyRolePermissions(final boolean applyRolePermissions)
{
this._applyRolePermissions = applyRolePermissions;
return this;
}
private boolean isApplyRolePermissions()
{
return _applyRolePermissions;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVOsLoader.java
| 1
|
请完成以下Java代码
|
public void setAD_BusinessRule_Trigger_ID (final int AD_BusinessRule_Trigger_ID)
{
if (AD_BusinessRule_Trigger_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_Trigger_ID, AD_BusinessRule_Trigger_ID);
}
@Override
public int getAD_BusinessRule_Trigger_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_Trigger_ID);
}
@Override
public void setConditionSQL (final @Nullable java.lang.String ConditionSQL)
{
set_Value (COLUMNNAME_ConditionSQL, ConditionSQL);
}
@Override
public java.lang.String getConditionSQL()
{
return get_ValueAsString(COLUMNNAME_ConditionSQL);
}
@Override
public void setOnDelete (final boolean OnDelete)
{
set_Value (COLUMNNAME_OnDelete, OnDelete);
}
@Override
public boolean isOnDelete()
{
return get_ValueAsBoolean(COLUMNNAME_OnDelete);
}
@Override
public void setOnNew (final boolean OnNew)
{
set_Value (COLUMNNAME_OnNew, OnNew);
}
@Override
public boolean isOnNew()
{
return get_ValueAsBoolean(COLUMNNAME_OnNew);
}
@Override
public void setOnUpdate (final boolean OnUpdate)
{
set_Value (COLUMNNAME_OnUpdate, OnUpdate);
|
}
@Override
public boolean isOnUpdate()
{
return get_ValueAsBoolean(COLUMNNAME_OnUpdate);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTargetRecordMappingSQL (final java.lang.String TargetRecordMappingSQL)
{
set_Value (COLUMNNAME_TargetRecordMappingSQL, TargetRecordMappingSQL);
}
@Override
public java.lang.String getTargetRecordMappingSQL()
{
return get_ValueAsString(COLUMNNAME_TargetRecordMappingSQL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Trigger.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/activity?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.properties.hibernate.hbm2ddl.a
|
uto=update
spring.jpa.show-sql=true
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8
server.port=8088
|
repos\springboot-demo-master\activiti\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public static class JSONOpenSingleDocumentAction extends JSONResultAction
{
private final WindowId windowId;
private final String documentId;
private final boolean advanced = false;
private final ProcessExecutionResult.RecordsToOpen.TargetTab targetTab;
public JSONOpenSingleDocumentAction(final WindowId windowId, final String documentId, final ProcessExecutionResult.RecordsToOpen.TargetTab targetTab)
{
super("openDocument");
this.windowId = windowId;
this.documentId = documentId;
this.targetTab = targetTab;
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public static class JSONCloseView extends JSONResultAction
{
public static final JSONCloseView instance = new JSONCloseView();
private JSONCloseView()
{
super("closeView");
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Getter
public static class JSONSelectViewRowsAction extends JSONResultAction
{
private final WindowId windowId;
private final String viewId;
private final Set<String> rowIds;
public JSONSelectViewRowsAction(final ViewId viewId, final DocumentIdsSelection rowIds)
{
super("selectViewRows");
this.windowId = viewId.getWindowId();
this.viewId = viewId.getViewId();
this.rowIds = rowIds.toJsonSet();
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Getter
public static class JSONDisplayQRCodeAction extends JSONResultAction
{
private final String code;
protected JSONDisplayQRCodeAction(@NonNull final String code)
{
|
super("displayQRCode");
this.code = code;
}
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@lombok.Getter
public static class JSONNewRecordAction extends JSONResultAction
{
@NonNull private final WindowId windowId;
@NonNull private final Map<String, String> fieldValues;
@NonNull private final String targetTab;
public JSONNewRecordAction(
@NonNull final WindowId windowId,
@Nullable final Map<String, String> fieldValues,
@NonNull final ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab)
{
super("newRecord");
this.windowId = windowId;
this.fieldValues = fieldValues != null && !fieldValues.isEmpty()
? new HashMap<>(fieldValues)
: ImmutableMap.of();
this.targetTab = targetTab.name();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONProcessInstanceResult.java
| 1
|
请完成以下Java代码
|
public Batch execute(CommandContext commandContext) {
Collection<String> collectedInstanceIds = collectProcessInstanceIds();
MigrationPlan migrationPlan = executionBuilder.getMigrationPlan();
ensureNotNull(BadUserRequestException.class,
"Migration plan cannot be null", "migration plan", migrationPlan);
ensureNotEmpty(BadUserRequestException.class,
"Process instance ids cannot empty", "process instance ids", collectedInstanceIds);
ensureNotContainsNull(BadUserRequestException.class,
"Process instance ids cannot be null", "process instance ids", collectedInstanceIds);
ProcessDefinitionEntity sourceDefinition = resolveSourceProcessDefinition(commandContext);
ProcessDefinitionEntity targetDefinition = resolveTargetProcessDefinition(commandContext);
String tenantId = sourceDefinition.getTenantId();
Map<String, Object> variables = migrationPlan.getVariables();
Batch batch = new BatchBuilder(commandContext)
.type(Batch.TYPE_PROCESS_INSTANCE_MIGRATION)
.config(getConfiguration(collectedInstanceIds, sourceDefinition.getDeploymentId()))
.permission(BatchPermissions.CREATE_BATCH_MIGRATE_PROCESS_INSTANCES)
.permissionHandler(ctx -> checkAuthorizations(ctx, sourceDefinition, targetDefinition))
.tenantId(tenantId)
.operationLogHandler((ctx, instanceCount) ->
writeUserOperationLog(ctx, sourceDefinition, targetDefinition, instanceCount, variables, true))
.build();
|
if (variables != null) {
String batchId = batch.getId();
VariableUtil.setVariablesByBatchId(variables, batchId);
}
return batch;
}
public BatchConfiguration getConfiguration(Collection<String> instanceIds, String deploymentId) {
return new MigrationBatchConfiguration(
new ArrayList<>(instanceIds), DeploymentMappings.of(new DeploymentMapping(deploymentId, instanceIds.size())),
executionBuilder.getMigrationPlan(),
executionBuilder.isSkipCustomListeners(),
executionBuilder.isSkipIoMappings());
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\batch\MigrateProcessInstanceBatchCmd.java
| 1
|
请完成以下Java代码
|
public class JpaUserDao implements Dao<User> {
private final EntityManager entityManager;
public JpaUserDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Optional<User> get(long id) {
return Optional.ofNullable(entityManager.find(User.class, id));
}
@Override
public List<User> getAll() {
Query query = entityManager.createQuery("SELECT e FROM User e");
return query.getResultList();
}
@Override
public void save(User user) {
executeInsideTransaction(entityManager -> entityManager.persist(user));
}
@Override
public void update(User user, String[] params) {
user.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null"));
executeInsideTransaction(entityManager -> entityManager.merge(user));
}
@Override
public void delete(User user) {
executeInsideTransaction(entityManager -> entityManager.remove(user));
|
}
private void executeInsideTransaction(Consumer<EntityManager> action) {
final EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
action.accept(entityManager);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e;
}
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\daos\JpaUserDao.java
| 1
|
请完成以下Java代码
|
public static Optional<Integer> getMemoryUsage() {
try {
GlobalMemory memory = HARDWARE.getMemory();
long total = memory.getTotal();
long available = memory.getAvailable();
return Optional.of(toPercent(total - available, total));
} catch (Throwable e) {
log.debug("Failed to get memory usage!!!", e);
}
return Optional.empty();
}
public static Optional<Long> getTotalMemory() {
try {
return Optional.of(HARDWARE.getMemory().getTotal());
} catch (Throwable e) {
log.debug("Failed to get total memory!!!", e);
}
return Optional.empty();
}
public static Optional<Integer> getCpuUsage() {
try {
return Optional.of((int) (HARDWARE.getProcessor().getSystemCpuLoad(1000) * 100.0));
} catch (Throwable e) {
log.debug("Failed to get cpu usage!!!", e);
}
return Optional.empty();
}
public static Optional<Integer> getCpuCount() {
try {
return Optional.of(HARDWARE.getProcessor().getLogicalProcessorCount());
} catch (Throwable e) {
log.debug("Failed to get total cpu count!!!", e);
}
return Optional.empty();
}
public static Optional<Integer> getDiscSpaceUsage() {
|
try {
FileStore store = Files.getFileStore(Paths.get("/"));
long total = store.getTotalSpace();
long available = store.getUsableSpace();
return Optional.of(toPercent(total - available, total));
} catch (Throwable e) {
log.debug("Failed to get free disc space!!!", e);
}
return Optional.empty();
}
public static Optional<Long> getTotalDiscSpace() {
try {
FileStore store = Files.getFileStore(Paths.get("/"));
return Optional.of(store.getTotalSpace());
} catch (Throwable e) {
log.debug("Failed to get total disc space!!!", e);
}
return Optional.empty();
}
private static int toPercent(long used, long total) {
BigDecimal u = new BigDecimal(used);
BigDecimal t = new BigDecimal(total);
BigDecimal i = new BigDecimal(100);
return u.multiply(i).divide(t, RoundingMode.HALF_UP).intValue();
}
}
|
repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\SystemUtil.java
| 1
|
请完成以下Java代码
|
public T get()
{
return orElseThrow();
}
public boolean isPresent()
{
return value != null;
}
public <U> ExplainedOptional<U> map(@NonNull final Function<? super T, ? extends U> mapper)
{
if (!isPresent())
{
return emptyBecause(explanation);
}
else
{
final U newValue = mapper.apply(value);
if (newValue == null)
{
return emptyBecause(explanation);
}
else
{
return of(newValue);
}
}
}
public ExplainedOptional<T> ifPresent(@NonNull final Consumer<T> consumer)
{
if (isPresent())
{
consumer.accept(value);
}
return this;
|
}
@SuppressWarnings("UnusedReturnValue")
public ExplainedOptional<T> ifAbsent(@NonNull final Consumer<ITranslatableString> consumer)
{
if (!isPresent())
{
consumer.accept(explanation);
}
return this;
}
/**
* @see #resolve(Function, Function)
*/
public <R> Optional<R> mapIfAbsent(@NonNull final Function<ITranslatableString, R> mapper)
{
return isPresent()
? Optional.empty()
: Optional.ofNullable(mapper.apply(getExplanation()));
}
/**
* @see #mapIfAbsent(Function)
*/
public <R> R resolve(
@NonNull final Function<T, R> mapPresent,
@NonNull final Function<ITranslatableString, R> mapAbsent)
{
return isPresent()
? mapPresent.apply(value)
: mapAbsent.apply(explanation);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\ExplainedOptional.java
| 1
|
请完成以下Java代码
|
public I_M_Attribute retrieveADRAttribute(Properties ctx)
{
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx);
return retrieveADRAttribute(adClientId, adOrgId);
}
private I_M_Attribute retrieveADRAttribute(int adClientId, int adOrgId)
{
final AttributeId adrAttributeId = retrieveADRAttributeId(adClientId, adOrgId);
if (adrAttributeId == null)
{
return null;
}
return Services.get(IAttributeDAO.class).getAttributeRecordById(adrAttributeId);
}
@Override
public AttributeListValue retrieveADRAttributeValue(final Properties ctx, @NonNull final I_C_BPartner partner, boolean isSOTrx)
{
|
final String adrRegionValue = Services.get(IADRAttributeBL.class).getADRForBPartner(partner, isSOTrx);
if (Check.isEmpty(adrRegionValue, true))
{
return null;
}
final I_M_Attribute adrAttribute = retrieveADRAttribute(partner);
if (adrAttribute == null)
{
return null;
}
return Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(adrAttribute, adrRegionValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\ADRAttributeDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
/**
* 注入权限验证控制器 来支持 password grant type
*/
@Autowired
private AuthenticationManager authenticationManager;
/**
* 注入userDetailsService,开启refresh_token需要用到
*/
@Autowired
private MyUserDetailsService userDetailsService;
/**
* 数据源
*/
@Autowired
private DataSource dataSource;
/**
* 设置保存token的方式,一共有五种,这里采用数据库的方式
*/
@Autowired
private TokenStore tokenStore;
@Autowired
private WebResponseExceptionTranslator webResponseExceptionTranslator;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore( dataSource );
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
|
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//开启密码授权类型
endpoints.authenticationManager(authenticationManager);
//配置token存储方式
endpoints.tokenStore(tokenStore);
//自定义登录或者鉴权失败时的返回信息
endpoints.exceptionTranslator(webResponseExceptionTranslator);
//要使用refresh_token的话,需要额外配置userDetailsService
endpoints.userDetailsService( userDetailsService );
}
}
|
repos\SpringBootLearning-master (1)\springboot-security-oauth2\src\main\java\com\gf\config\AuthorizationServerConfiguration.java
| 2
|
请完成以下Java代码
|
private static PickingSlotRow createPickedHURow(@NonNull final PickedHUEditorRow from, final PickingSlotId pickingSlotId)
{
final HUEditorRow huEditorRow = from.getHuEditorRow();
final List<PickingSlotRow> includedHURows = huEditorRow.getIncludedRows()
.stream()
.map(includedHUEditorRow -> createPickedHURow(
new PickedHUEditorRow(includedHUEditorRow, // create PickingSlotRows for the included HU rows which shall inherit the parent's processed flag
from.isProcessed(),
from.getPickingOrderIdsFor(includedHUEditorRow.getAllHuIds())),
pickingSlotId))
.collect(ImmutableList.toImmutableList());
return PickingSlotRow.fromPickedHUBuilder()
.pickingSlotId(pickingSlotId)
.huId(huEditorRow.getHURowId().getHuId())
.huStorageProductId(ProductId.toRepoId(huEditorRow.getHURowId().getStorageProductId()))
.huEditorRowType(huEditorRow.getType())
// do *not* take the HUEditorRow's processed flag, because we don't care about that; we do care about PickingSlotHUEditorRow.isProcessed() because that's the value coming from the M_Picking_Candidate
.processed(from.isProcessed())
.huCode(huEditorRow.getValue())
.product(huEditorRow.getProduct())
.packingInfo(huEditorRow.getPackingInfo())
.qtyCU(huEditorRow.getQtyCU())
.topLevelHU(huEditorRow.isTopLevel())
.huId2OpenPickingOrderIds(from.getHuIds2OpenPickingOrderIds())
//
.includedHURows(includedHURows)
//
.build();
}
private PickingSlotRow createPickingSlotRowWithIncludedRows(
@NonNull final I_M_PickingSlot pickingSlot,
@NonNull final List<PickingSlotRow> pickedHuRows)
{
|
return PickingSlotRow.fromPickingSlotBuilder()
.pickingSlotId(PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID()))
//
.pickingSlotName(pickingSlot.getPickingSlot())
.pickingSlotWarehouse(warehouseLookup.get().findById(pickingSlot.getM_Warehouse_ID()))
.pickingSlotLocatorId(warehousesRepo.getLocatorIdByRepoIdOrNull(pickingSlot.getM_Locator_ID()))
.pickingSlotBPartner(bpartnerLookup.get().findById(pickingSlot.getC_BPartner_ID()))
.pickingSlotBPLocation(bpartnerLocationLookup.get().findById(pickingSlot.getC_BPartner_Location_ID()))
.includedHURows(pickedHuRows)
//
.build();
}
public List<PickingSlotRow> retrievePickingSlotsRowsForClearing(@NonNull final PickingSlotQuery query)
{
final List<I_M_PickingSlot> pickingSlots = Services.get(IPickingSlotDAO.class).retrievePickingSlots(query);
final ListMultimap<PickingSlotId, PickedHUEditorRow> huEditorRowsByPickingSlotId = pickingHUsRepo.retrieveAllPickedHUsIndexedByPickingSlotId(pickingSlots);
return pickingSlots.stream() // get stream of I_M_PickingSlot
.map(pickingSlot -> createPickingSlotRow(pickingSlot, huEditorRowsByPickingSlotId)) // create the actual PickingSlotRows
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewRepository.java
| 1
|
请完成以下Java代码
|
public Synonym randomSynonym(Type type, String preWord)
{
ArrayList<Synonym> synonymArrayList = new ArrayList<Synonym>(synonymList);
ListIterator<Synonym> listIterator = synonymArrayList.listIterator();
if (type != null) while (listIterator.hasNext())
{
Synonym synonym = listIterator.next();
if (synonym.type != type || (preWord != null && CoreBiGramTableDictionary.getBiFrequency(preWord, synonym.realWord) == 0)) listIterator.remove();
}
if (synonymArrayList.size() == 0) return null;
return synonymArrayList.get((int) (System.currentTimeMillis() % (long)synonymArrayList.size()));
}
public Synonym randomSynonym()
{
return randomSynonym(null, null);
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append(entry);
sb.append(' ');
sb.append(type);
sb.append(' ');
sb.append(synonymList);
return sb.toString();
}
/**
* 语义距离
*
|
* @param other
* @return
*/
public long distance(SynonymItem other)
{
return entry.distance(other.entry);
}
/**
* 创建一个@类型的词典之外的条目
*
* @param word
* @return
*/
public static SynonymItem createUndefined(String word)
{
SynonymItem item = new SynonymItem(new Synonym(word, word.hashCode() * 1000000 + Long.MAX_VALUE / 3), null, Type.UNDEFINED);
return item;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\CommonSynonymDictionary.java
| 1
|
请完成以下Java代码
|
public static Color getColor(final String colorKey)
{
return UIManager.getColor(colorKey);
}
public static Color getColor(final String colorKey, final Color defaultColor)
{
final Color color = getColor(colorKey);
return color == null ? defaultColor : color;
}
public static Color getColor(final String colorKey, final String colorKeyDefault, final Color defaultColor)
{
Color color = getColor(colorKey);
if (color != null)
{
return color;
}
color = getColor(colorKeyDefault);
if (color != null)
{
return color;
}
return defaultColor;
}
/**
* Creates an active value which actual value will always be resolved as the value of the given proxy key.
*
* If there is no value for proxy key, the given default value will be returned.
*
* @param proxyKey
* @param defaultValue
* @return active value which forward to the value of given given proxy key.
*/
public static UIDefaults.ActiveValue createActiveValueProxy(final String proxyKey, final Object defaultValue)
{
return new UIDefaults.ActiveValue()
{
@Override
public Object createValue(final UIDefaults table)
{
final Object value = table.get(proxyKey);
return value != null ? value : defaultValue;
}
|
};
}
/**
* Gets integer value of given key. If no value was found or the value is not {@link Integer} the default value will be returned.
*
* @return integer value or default value
*/
public static int getInt(final String key, final int defaultValue)
{
final Object value = UIManager.getDefaults().get(key);
if (value instanceof Integer)
{
return ((Integer)value).intValue();
}
return defaultValue;
}
public static boolean getBoolean(final String key, final boolean defaultValue)
{
final Object value = UIManager.getDefaults().get(key);
if (value instanceof Boolean)
{
return ((Boolean)value).booleanValue();
}
return defaultValue;
}
public static String getString(final String key, final String defaultValue)
{
final Object value = UIManager.getDefaults().get(key);
if(value == null)
{
return defaultValue;
}
return value.toString();
}
public static void setDefaultBackground(final JComponent comp)
{
comp.putClientProperty(AdempiereLookAndFeel.BACKGROUND, MFColor.ofFlatColor(AdempierePLAF.getFormBackground()));
}
} // AdempierePLAF
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempierePLAF.java
| 1
|
请完成以下Java代码
|
public int getXmlLineNumber() {
return xmlLineNumber;
}
public void setXmlLineNumber(int xmlLineNumber) {
this.xmlLineNumber = xmlLineNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
public boolean isWarning() {
return isWarning;
}
public void setWarning(boolean isWarning) {
this.isWarning = isWarning;
}
|
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '").append(validatorSetName).append("' | Problem: '").append(problem).append("'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (processDefinitionId != null) {
strb.append("processDefinitionId = ").append(processDefinitionId);
extraInfoAlreadyPresent = true;
}
if (processDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("processDefinitionName = ").append(processDefinitionName).append(" | ");
extraInfoAlreadyPresent = true;
}
if (activityId != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("id = ").append(activityId).append(" | ");
extraInfoAlreadyPresent = true;
}
if (activityName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("activityName = ").append(activityName).append(" | ");
extraInfoAlreadyPresent = true;
}
strb.append("]");
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: ").append(xmlLineNumber).append(", column: ").append(xmlColumnNumber).append(")");
}
return strb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\ValidationError.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Zeile Nr..
@param Line
Einzelne Zeile in dem Dokument
*/
@Override
public void setLine (int Line)
{
set_ValueNoCheck (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Einzelne Zeile in dem Dokument
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UUID.
@param UUID UUID */
@Override
public void setUUID (java.lang.String UUID)
{
set_ValueNoCheck (COLUMNNAME_UUID, UUID);
}
/** Get UUID.
@return UUID */
@Override
public java.lang.String getUUID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UUID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection.java
| 1
|
请完成以下Java代码
|
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Catalog [id=" + id + ", name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Publisher other = (Publisher) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Publisher.java
| 1
|
请完成以下Java代码
|
public ShipperGatewayClient newClientForShipperId(@NonNull final ShipperId shipperId)
{
final DhlClientConfig config = configRepo.getByShipperId(shipperId);
// Create the RestTemplate configured with OAuth2
final RestTemplate restTemplate = buildOAuth2RestTemplate(config);
// Return the DhlShipperGatewayClient instance
return DhlShipperGatewayClient.builder()
.config(config)
.databaseLogger(DhlDatabaseClientLogger.instance)
.restTemplate(restTemplate)
.build();
}
/**
* Creates a RestTemplate configured to authenticate with OAuth2 using the provided DhlClientConfig.
*/
|
private RestTemplate buildOAuth2RestTemplate(final DhlClientConfig clientConfig)
{
final RestTemplate restTemplate = new RestTemplate();
// Add the CustomOAuth2TokenRetriever to handle DHL's OAuth2 flow
final CustomOAuth2TokenRetriever tokenRetriever = new CustomOAuth2TokenRetriever(new RestTemplate());
// Add an interceptor that dynamically retrieves and injects the `Authorization` header
restTemplate.getInterceptors().add(
new OAuth2AuthorizationInterceptor(tokenRetriever, clientConfig)
);
return restTemplate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlShipperGatewayClientFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Page<AnnouncementSendModel> getMyAnnouncementSendPage(Page<AnnouncementSendModel> page,
AnnouncementSendModel announcementSendModel) {
return page.setRecords(sysAnnouncementSendMapper.getMyAnnouncementSendList(page, announcementSendModel));
}
@Override
public AnnouncementSendModel getOne(String sendId) {
return sysAnnouncementSendMapper.getOne(sendId);
}
/**
* 获取当前用户已阅读数量
*
* @param id
* @return
*/
@Override
public long getReadCountByUserId(String id) {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
return sysAnnouncementSendMapper.getReadCountByUserId(id, sysUser.getId());
}
/**
* 根据多个id批量删除已阅读的数量
*
* @param ids
*/
@Override
public void deleteBatchByIds(String ids) {
LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//根据用户id和阅读表的id获取所有阅读的数据
List<String> sendIds = sysAnnouncementSendMapper.getReadAnnSendByUserId(Arrays.asList(ids.split(SymbolConstant.COMMA)),sysUser.getId());
if(CollectionUtil.isNotEmpty(sendIds)){
this.removeByIds(sendIds);
|
}
}
/**
* 根据busId更新阅读状态
* @param busId
* @param busType
*/
@Override
public void updateReadFlagByBusId(String busId, String busType) {
SysAnnouncement announcement = sysAnnouncementMapper.selectOne(new QueryWrapper<SysAnnouncement>().eq("bus_type",busType).eq("bus_id",busId));
if(oConvertUtils.isNotEmpty(announcement)){
LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
String userId = sysUser.getId();
LambdaUpdateWrapper<SysAnnouncementSend> updateWrapper = new UpdateWrapper().lambda();
updateWrapper.set(SysAnnouncementSend::getReadFlag, CommonConstant.HAS_READ_FLAG);
updateWrapper.set(SysAnnouncementSend::getReadTime, new Date());
updateWrapper.eq(SysAnnouncementSend::getAnntId,announcement.getId());
updateWrapper.eq(SysAnnouncementSend::getUserId,userId);
SysAnnouncementSend announcementSend = new SysAnnouncementSend();
sysAnnouncementSendMapper.update(announcementSend, updateWrapper);
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysAnnouncementSendServiceImpl.java
| 2
|
请完成以下Java代码
|
public ScriptTraceEnhancer.ScriptTraceContext addTraceTag(String tag, String value) {
this.traceTags.put(tag, value);
return this;
}
@Override
public ScriptEngineRequest getRequest() {
return request;
}
@Override
public Throwable getException() {
return exception;
}
@Override
public Map<String, String> getTraceTags() {
return traceTags;
}
|
@Override
public Duration getDuration() {
return duration;
}
@Override
public String toString() {
return new StringJoiner(", ", DefaultScriptTrace.class.getSimpleName() + "[", "]")
.add("duration=" + duration)
.add("request=" + request)
.add("exception=" + exception)
.add("traceTags=" + traceTags)
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\DefaultScriptTrace.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ADWindowName
{
@NonNull AdWindowId adWindowId;
@Nullable String name;
@Nullable String entityType;
boolean missing;
public static ADWindowName missing(@NonNull final AdWindowId adWindowId)
{
return builder()
.adWindowId(adWindowId)
.missing(true)
.build();
}
|
@Override
public String toString() {return toShortString();}
public String toShortString()
{
if (missing)
{
return "<" + adWindowId.getRepoId() + ">";
}
else
{
return "" + name + "(" + adWindowId.getRepoId() + "," + entityType + ")";
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\ADWindowName.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DinoController {
ArrayList<Dino> dinos = new ArrayList<Dino>();
@RequestMapping("/")
public String dinoList(Model model) {
Dino dinos = new Dino(1, "alpha", "red", "50kg");
model.addAttribute("dinos", new Dino());
model.addAttribute("dinos", dinos);
System.out.println(dinos);
return "index";
}
@RequestMapping("/create")
public String dinoCreate(Model model) {
|
model.addAttribute("dinos", new Dino());
return "form";
}
@PostMapping("/dino")
public String dinoSubmit(@ModelAttribute Dino dino, Model model) {
model.addAttribute("dino", dino);
return "result";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-4\src\main\java\com\baeldung\thymeleaf\expression\DinoController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static class ReactiveConfiguration {
@Bean
@Lazy(false)
@ConditionalOnMissingBean
public ApplicationFactory applicationFactory(InstanceProperties instance, ManagementServerProperties management,
ServerProperties server, PathMappedEndpoints pathMappedEndpoints, WebEndpointProperties webEndpoint,
ObjectProvider<List<MetadataContributor>> metadataContributors, WebFluxProperties webFluxProperties) {
return new ReactiveApplicationFactory(instance, management, server, pathMappedEndpoints, webEndpoint,
new CompositeMetadataContributor(metadataContributors.getIfAvailable(Collections::emptyList)),
webFluxProperties);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(RestTemplateBuilder.class)
public static class BlockingRegistrationClientConfig {
@Bean
@ConditionalOnMissingBean
public RegistrationClient registrationClient(ClientProperties client) {
RestTemplateBuilder builder = new RestTemplateBuilder().connectTimeout(client.getConnectTimeout())
.readTimeout(client.getReadTimeout());
if (client.getUsername() != null && client.getPassword() != null) {
builder = builder.basicAuthentication(client.getUsername(), client.getPassword());
}
RestTemplate build = builder.build();
return new BlockingRegistrationClient(build);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean({ RestClient.Builder.class, ClientHttpRequestFactoryBuilder.class })
public static class RestClientRegistrationClientConfig {
@Bean
@ConditionalOnMissingBean
public RegistrationClient registrationClient(ClientProperties client, RestClient.Builder restClientBuilder,
ClientHttpRequestFactoryBuilder<?> clientHttpRequestFactoryBuilder) {
var factorySettings = ClientHttpRequestFactorySettings.defaults()
.withConnectTimeout(client.getConnectTimeout())
|
.withReadTimeout(client.getReadTimeout());
var clientHttpRequestFactory = clientHttpRequestFactoryBuilder.build(factorySettings);
restClientBuilder = restClientBuilder.requestFactory(clientHttpRequestFactory);
if (client.getUsername() != null && client.getPassword() != null) {
restClientBuilder = restClientBuilder
.requestInterceptor(new BasicAuthenticationInterceptor(client.getUsername(), client.getPassword()));
}
var restClient = restClientBuilder.build();
return new RestClientRegistrationClient(restClient);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(WebClient.Builder.class)
public static class ReactiveRegistrationClientConfig {
@Bean
@ConditionalOnMissingBean
public RegistrationClient registrationClient(ClientProperties client, WebClient.Builder webClient) {
if (client.getUsername() != null && client.getPassword() != null) {
webClient = webClient.filter(basicAuthentication(client.getUsername(), client.getPassword()));
}
return new ReactiveRegistrationClient(webClient.build(), client.getReadTimeout());
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\config\SpringBootAdminClientAutoConfiguration.java
| 2
|
请完成以下Java代码
|
protected String getWebServerFactoryBeanName() {
// Use bean names so that we don't consider the hierarchy
String[] beanNames = getBeanFactory().getBeanNamesForType(ReactiveWebServerFactory.class);
if (beanNames.length == 0) {
throw new MissingWebServerFactoryBeanException(getClass(), ReactiveWebServerFactory.class,
WebApplicationType.REACTIVE);
}
if (beanNames.length > 1) {
throw new ApplicationContextException("Unable to start ReactiveWebApplicationContext due to multiple "
+ "ReactiveWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
}
return beanNames[0];
}
protected ReactiveWebServerFactory getWebServerFactory(String factoryBeanName) {
return getBeanFactory().getBean(factoryBeanName, ReactiveWebServerFactory.class);
}
/**
* Return the {@link HttpHandler} that should be used to process the reactive web
* server. By default this method searches for a suitable bean in the context itself.
* @return a {@link HttpHandler} (never {@code null}
*/
protected HttpHandler getHttpHandler() {
// Use bean names so that we don't consider the hierarchy
String[] beanNames = getBeanFactory().getBeanNamesForType(HttpHandler.class);
if (beanNames.length == 0) {
throw new ApplicationContextException(
"Unable to start ReactiveWebApplicationContext due to missing HttpHandler bean.");
}
if (beanNames.length > 1) {
throw new ApplicationContextException(
"Unable to start ReactiveWebApplicationContext due to multiple HttpHandler beans : "
+ StringUtils.arrayToCommaDelimitedString(beanNames));
}
return getBeanFactory().getBean(beanNames[0], HttpHandler.class);
}
@Override
protected void doClose() {
|
if (isActive()) {
AvailabilityChangeEvent.publish(this, ReadinessState.REFUSING_TRAFFIC);
}
super.doClose();
WebServer webServer = getWebServer();
if (webServer != null) {
webServer.destroy();
}
}
/**
* Returns the {@link WebServer} that was created by the context or {@code null} if
* the server has not yet been created.
* @return the web server
*/
@Override
public @Nullable WebServer getWebServer() {
WebServerManager serverManager = this.serverManager;
return (serverManager != null) ? serverManager.getWebServer() : null;
}
@Override
public @Nullable String getServerNamespace() {
return this.serverNamespace;
}
@Override
public void setServerNamespace(@Nullable String serverNamespace) {
this.serverNamespace = serverNamespace;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\ReactiveWebServerApplicationContext.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected void prepare()
{
if (I_M_Tour.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_tour = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_Tour.class, ITrx.TRXNAME_None);
}
if (I_M_TourVersion.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
p_tourVersion = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_TourVersion.class, ITrx.TRXNAME_None);
p_tour = p_tourVersion.getM_Tour();
}
}
@Override
protected String doIt() throws Exception
{
Check.assumeNotNull(p_DateFrom, "p_DateFrom not null");
Check.assumeNotNull(p_DateTo, "p_DateTo not null");
Check.assumeNotNull(p_tour, "p_tour not null");
//
|
// Create generator instance and configure it
final IDeliveryDayGenerator generator = tourBL.createDeliveryDayGenerator(this);
generator.setDateFrom(TimeUtil.asLocalDate(p_DateFrom));
generator.setDateTo(TimeUtil.asLocalDate(p_DateTo));
generator.setM_Tour(p_tour);
//
// Generate delivery days
if (p_tourVersion == null)
{
generator.generate(getTrxName());
}
else
{
generator.generateForTourVersion(getTrxName(), p_tourVersion);
}
final int countGeneratedDeliveryDays = generator.getCountGeneratedDeliveryDays();
//
// Return result
return "@Created@ #" + countGeneratedDeliveryDays;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\process\GenerateDeliveryDays.java
| 1
|
请完成以下Java代码
|
public static Attribute of(@NonNull final org.adempiere.mm.attributes.api.Attribute attributeDescriptor)
{
return Attribute.builder()
.attributeCode(attributeDescriptor.getAttributeCode())
.displayName(attributeDescriptor.getDisplayName())
.valueType(attributeDescriptor.getValueType())
.value(null)
.build();
}
public String getValueAsString()
{
return value != null ? value.toString() : null;
}
public BigDecimal getValueAsBigDecimal()
{
return value != null ? NumberUtils.asBigDecimal(value) : null;
}
public LocalDate getValueAsLocalDate()
{
return value == null ? null : TimeUtil.asLocalDate(value);
}
public Object getValueAsJson()
{
if (AttributeValueType.STRING.equals(valueType))
{
return getValueAsString();
}
else if (AttributeValueType.NUMBER.equals(valueType))
{
return getValueAsBigDecimal();
}
else if (AttributeValueType.DATE.equals(valueType))
{
final LocalDate value = getValueAsLocalDate();
return value != null ? value.toString() : null;
}
else if (AttributeValueType.LIST.equals(valueType))
{
return getValueAsString();
}
else
{
throw new AdempiereException("Unknown attribute type: " + valueType);
}
}
public ITranslatableString getValueAsTranslatableString()
{
switch (valueType)
|
{
case STRING:
case LIST:
{
final String valueStr = getValueAsString();
return TranslatableStrings.anyLanguage(valueStr);
}
case NUMBER:
{
final BigDecimal valueBD = getValueAsBigDecimal();
return valueBD != null
? TranslatableStrings.number(valueBD, de.metas.common.util.NumberUtils.isInteger(valueBD) ? DisplayType.Integer : DisplayType.Number)
: TranslatableStrings.empty();
}
case DATE:
{
final LocalDate valueDate = getValueAsLocalDate();
return valueDate != null
? TranslatableStrings.date(valueDate, DisplayType.Date)
: TranslatableStrings.empty();
}
default:
{
return TranslatableStrings.empty();
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\Attribute.java
| 1
|
请完成以下Java代码
|
public void setM_Attribute_ID (final int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_Value (COLUMNNAME_M_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_Attribute_ID, M_Attribute_ID);
}
@Override
public int getM_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Attribute_ID);
}
@Override
public de.metas.inoutcandidate.model.I_M_IolCandHandler getM_IolCandHandler()
{
return get_ValueAsPO(COLUMNNAME_M_IolCandHandler_ID, de.metas.inoutcandidate.model.I_M_IolCandHandler.class);
}
@Override
public void setM_IolCandHandler(final de.metas.inoutcandidate.model.I_M_IolCandHandler M_IolCandHandler)
{
set_ValueFromPO(COLUMNNAME_M_IolCandHandler_ID, de.metas.inoutcandidate.model.I_M_IolCandHandler.class, M_IolCandHandler);
}
@Override
public void setM_IolCandHandler_ID (final int M_IolCandHandler_ID)
{
if (M_IolCandHandler_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_IolCandHandler_ID, M_IolCandHandler_ID);
}
@Override
public int getM_IolCandHandler_ID()
|
{
return get_ValueAsInt(COLUMNNAME_M_IolCandHandler_ID);
}
@Override
public void setM_ShipmentSchedule_AttributeConfig_ID (final int M_ShipmentSchedule_AttributeConfig_ID)
{
if (M_ShipmentSchedule_AttributeConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID, M_ShipmentSchedule_AttributeConfig_ID);
}
@Override
public int getM_ShipmentSchedule_AttributeConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_AttributeConfig_ID);
}
@Override
public void setOnlyIfInReferencedASI (final boolean OnlyIfInReferencedASI)
{
set_Value (COLUMNNAME_OnlyIfInReferencedASI, OnlyIfInReferencedASI);
}
@Override
public boolean isOnlyIfInReferencedASI()
{
return get_ValueAsBoolean(COLUMNNAME_OnlyIfInReferencedASI);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_AttributeConfig.java
| 1
|
请完成以下Java代码
|
public Document add(String category, String text)
{
if (editMode) return null;
Document document = convert(category, text);
documentList.add(document);
return document;
}
@Override
public int size()
{
return documentList.size();
}
@Override
public void clear()
{
documentList.clear();
}
@Override
public IDataSet shrink(int[] idMap)
{
Iterator<Document> iterator = iterator();
while (iterator.hasNext())
{
|
Document document = iterator.next();
FrequencyMap<Integer> tfMap = new FrequencyMap<Integer>();
for (Map.Entry<Integer, int[]> entry : document.tfMap.entrySet())
{
Integer feature = entry.getKey();
if (idMap[feature] == -1) continue;
tfMap.put(idMap[feature], entry.getValue());
}
// 检查是否是空白文档
if (tfMap.size() == 0) iterator.remove();
else document.tfMap = tfMap;
}
return this;
}
@Override
public Iterator<Document> iterator()
{
return documentList.iterator();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\MemoryDataSet.java
| 1
|
请完成以下Java代码
|
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
UsernameAndPasswordAuthenticationRequest authenticationRequest = new ObjectMapper()
.readValue(request.getInputStream(), UsernameAndPasswordAuthenticationRequest.class);
Authentication authentication = new UsernamePasswordAuthenticationToken(
authenticationRequest.getUsername(),
authenticationRequest.getPassword()
);
Authentication authentication1 = authenticationManager.authenticate(authentication);
return authentication1;
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
// Send Credentials (Client to Server)
|
String key = "securesecuresecuresecuresecuresecuresecuresecuresecuresecure";
String token = Jwts.builder()
.setSubject(authResult.getName())
.claim("authorities", authResult.getAuthorities())
.setIssuedAt(new Date())
.setExpiration(java.sql.Date.valueOf(LocalDate. now().plusWeeks(2)))
.signWith(Keys.hmacShaKeyFor(key.getBytes()))
.compact();
// Response Send Token to Client.
response.addHeader("Authorization", "Bearer " + token);
super.successfulAuthentication(request, response, chain, authResult);
}
}
|
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\jwt-secure\spring-jwt-secure\src\main\java\uz\bepro\springjwtsecure\jwt\JwtUsernameAndPasswordAuthenticationFilter.java
| 1
|
请完成以下Java代码
|
public class CreditType {
@XmlAttribute(name = "request_timestamp", required = true)
@XmlSchemaType(name = "unsignedLong")
protected BigInteger requestTimestamp;
@XmlAttribute(name = "request_date", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar requestDate;
@XmlAttribute(name = "request_id", required = true)
protected String requestId;
/**
* Gets the value of the requestTimestamp property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getRequestTimestamp() {
return requestTimestamp;
}
/**
* Sets the value of the requestTimestamp property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setRequestTimestamp(BigInteger value) {
this.requestTimestamp = value;
}
/**
* Gets the value of the requestDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getRequestDate() {
return requestDate;
}
/**
* Sets the value of the requestDate property.
*
|
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setRequestDate(XMLGregorianCalendar value) {
this.requestDate = value;
}
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestId(String value) {
this.requestId = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CreditType.java
| 1
|
请完成以下Java代码
|
public ImportedElement getImportedElement() {
return importedElementChild.getChild(this);
}
public void setImportedElement(ImportedElement importedElement) {
importedElementChild.setChild(this, importedElement);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ImportedValues.class, DMN_ELEMENT_IMPORTED_VALUES)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Import.class)
.instanceProvider(new ModelTypeInstanceProvider<ImportedValues>() {
public ImportedValues newInstance(ModelTypeInstanceContext instanceContext) {
return new ImportedValuesImpl(instanceContext);
}
|
});
expressionLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importedElementChild = sequenceBuilder.element(ImportedElement.class)
.required()
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ImportedValuesImpl.java
| 1
|
请完成以下Java代码
|
private boolean shouldInstrument(VariableTree parameter) {
return TARGET_TYPES.contains(parameter.getType().toString())
&& parameter.getModifiers().getAnnotations()
.stream()
.anyMatch(a -> Positive.class.getSimpleName().equals(a.getAnnotationType().toString()));
}
private void addCheck(MethodTree method, VariableTree parameter, Context context) {
JCTree.JCIf check = createCheck(parameter, context);
JCTree.JCBlock body = (JCTree.JCBlock) method.getBody();
body.stats = body.stats.prepend(check);
}
private static JCTree.JCIf createCheck(VariableTree parameter, Context context) {
TreeMaker factory = TreeMaker.instance(context);
Names symbolsTable = Names.instance(context);
return factory.at(((JCTree) parameter).pos)
.If(factory.Parens(createIfCondition(factory, symbolsTable, parameter)),
createIfBlock(factory, symbolsTable, parameter),
null);
}
private static JCTree.JCBinary createIfCondition(TreeMaker factory, Names symbolsTable, VariableTree parameter) {
Name parameterId = symbolsTable.fromString(parameter.getName().toString());
return factory.Binary(JCTree.Tag.LE,
factory.Ident(parameterId),
factory.Literal(TypeTag.INT, 0));
}
private static JCTree.JCBlock createIfBlock(TreeMaker factory, Names symbolsTable, VariableTree parameter) {
String parameterName = parameter.getName().toString();
Name parameterId = symbolsTable.fromString(parameterName);
|
String errorMessagePrefix = String.format("Argument '%s' of type %s is marked by @%s but got '",
parameterName, parameter.getType(), Positive.class.getSimpleName());
String errorMessageSuffix = "' for it";
return factory.Block(0, com.sun.tools.javac.util.List.of(
factory.Throw(
factory.NewClass(null, nil(),
factory.Ident(symbolsTable.fromString(IllegalArgumentException.class.getSimpleName())),
com.sun.tools.javac.util.List.of(factory.Binary(JCTree.Tag.PLUS,
factory.Binary(JCTree.Tag.PLUS, factory.Literal(TypeTag.CLASS, errorMessagePrefix),
factory.Ident(parameterId)),
factory.Literal(TypeTag.CLASS, errorMessageSuffix))), null))));
}
}
|
repos\tutorials-master\core-java-modules\core-java-sun\src\main\java\com\baeldung\javac\SampleJavacPlugin.java
| 1
|
请完成以下Java代码
|
public void setIsStartTLS (final boolean IsStartTLS)
{
set_Value (COLUMNNAME_IsStartTLS, IsStartTLS);
}
@Override
public boolean isStartTLS()
{
return get_ValueAsBoolean(COLUMNNAME_IsStartTLS);
}
@Override
public void setMSGRAPH_ClientId (final @Nullable java.lang.String MSGRAPH_ClientId)
{
set_Value (COLUMNNAME_MSGRAPH_ClientId, MSGRAPH_ClientId);
}
@Override
public java.lang.String getMSGRAPH_ClientId()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientId);
}
@Override
public void setMSGRAPH_ClientSecret (final @Nullable java.lang.String MSGRAPH_ClientSecret)
{
set_Value (COLUMNNAME_MSGRAPH_ClientSecret, MSGRAPH_ClientSecret);
}
@Override
public java.lang.String getMSGRAPH_ClientSecret()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientSecret);
}
@Override
public void setMSGRAPH_TenantId (final @Nullable java.lang.String MSGRAPH_TenantId)
{
set_Value (COLUMNNAME_MSGRAPH_TenantId, MSGRAPH_TenantId);
}
@Override
public java.lang.String getMSGRAPH_TenantId()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_TenantId);
}
@Override
public void setPassword (final @Nullable java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setSMTPHost (final @Nullable java.lang.String SMTPHost)
{
set_Value (COLUMNNAME_SMTPHost, SMTPHost);
}
@Override
public java.lang.String getSMTPHost()
{
return get_ValueAsString(COLUMNNAME_SMTPHost);
|
}
@Override
public void setSMTPPort (final int SMTPPort)
{
set_Value (COLUMNNAME_SMTPPort, SMTPPort);
}
@Override
public int getSMTPPort()
{
return get_ValueAsInt(COLUMNNAME_SMTPPort);
}
/**
* Type AD_Reference_ID=541904
* Reference name: AD_MailBox_Type
*/
public static final int TYPE_AD_Reference_ID=541904;
/** SMTP = smtp */
public static final String TYPE_SMTP = "smtp";
/** MSGraph = msgraph */
public static final String TYPE_MSGraph = "msgraph";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java
| 1
|
请完成以下Java代码
|
public class C_Letter_CreateFrom_MKTG_ContactPerson extends JavaProcess
{
// Services
private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class);
private final ContactPersonRepository contactPersonRepo = SpringContextHolder.instance.getBean(ContactPersonRepository.class);
private int campaignId;
@Override
protected void prepare()
{
campaignId = getRecord_ID();
}
@Override
protected String doIt() throws Exception
{
final Set<Integer> campaignContactPersonIds = contactPersonRepo.getIdsByCampaignId(campaignId);
if (campaignContactPersonIds.isEmpty())
{
return MSG_Error + ": 0 records enqueued";
}
final AsyncBatchId asyncbatchId = createAsyncBatch();
for (final Integer campaignContactPersonId : campaignContactPersonIds)
{
enqueue(asyncbatchId, campaignContactPersonId);
}
return MSG_OK;
}
private AsyncBatchId createAsyncBatch()
{
// Create Async Batch for tracking
return asyncBatchBL.newAsyncBatch()
|
.setContext(getCtx())
.setC_Async_Batch_Type(LetterConstants.C_Async_Batch_InternalName_CreateLettersAsync)
.setAD_PInstance_Creator_ID(getPinstanceId())
.setName("Create Letters for Campaign " + campaignId)
.buildAndEnqueue();
}
private void enqueue(
@NonNull final AsyncBatchId asyncbatchId,
@Nullable final Integer campaignContactPersonId)
{
if (campaignContactPersonId == null || campaignContactPersonId <= 0)
{
// should not happen
return;
}
final I_MKTG_Campaign_ContactPerson campaignContactPerson = load(campaignContactPersonId, I_MKTG_Campaign_ContactPerson.class);
final IWorkPackageQueueFactory workPackageQueueFactory = Services.get(IWorkPackageQueueFactory.class);
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(getCtx(), C_Letter_CreateFromMKTG_ContactPerson_Async.class);
queue.newWorkPackage()
.setAsyncBatchId(asyncbatchId) // set the async batch in workpackage in order to track it
.addElement(campaignContactPerson)
.setUserInChargeId(getUserId())
.buildAndEnqueue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\serialletter\src\main\java\de\metas\letter\process\C_Letter_CreateFrom_MKTG_ContactPerson.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public OAuthAccessToken getAccessToken(@NonNull OAuthAccessTokenRequest request)
{
final OAuthAccessToken cachedToken = accessTokensCache.getIfPresent(request.getIdentity());
if (cachedToken != null && !cachedToken.isExpired(now()))
{
return cachedToken;
}
// Fetch new token
final OAuthAccessToken newToken = fetchNewAccessToken(request);
accessTokensCache.put(request.getIdentity(), newToken);
return newToken;
}
/**
* If a token is known to be invalid, it can be removed from the cache with this method
*/
public void invalidateToken(@NonNull OAuthIdentity identity)
{
accessTokensCache.invalidate(identity);
accessTokensCache.cleanUp();
}
private OAuthAccessToken fetchNewAccessToken(@NonNull final OAuthAccessTokenRequest request)
{
try
{
final HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
final Map<String, String> formData = createFormData(request);
final ResponseEntity<String> response = restTemplate.postForEntity(
request.getIdentity().getTokenUrl(),
new HttpEntity<>(jsonObjectMapper.writeValueAsString(formData), httpHeaders),
String.class);
final JsonNode jsonNode = jsonObjectMapper.readTree(response.getBody());
final String accessToken = jsonNode.get("bearer").asText();
return OAuthAccessToken.of(accessToken, now().plus(EXPIRING_DURATION));
}
catch (final JsonProcessingException e)
{
throw new RuntimeCamelException("Failed to parse OAuth token response", e);
}
|
}
@NonNull
private static Map<String, String> createFormData(@NonNull final OAuthAccessTokenRequest request)
{
final Map<String, String> formData = new HashMap<>();
if (Check.isNotBlank(request.getIdentity().getClientId()))
{
formData.put("client_id", request.getIdentity().getClientId());
}
if (Check.isNotBlank(request.getClientSecret()))
{
formData.put("client_secret", request.getClientSecret());
}
if (Check.isNotBlank(request.getIdentity().getUsername()))
{
formData.put("email", request.getIdentity().getUsername());
}
if (Check.isNotBlank(request.getPassword()))
{
formData.put("password", request.getPassword());
}
return formData;
}
@Value
@Builder
private static class CacheKey
{
@NonNull String tokenUrl;
@Nullable String clientId;
@Nullable String username;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\oauth\OAuthTokenManager.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_S_Resource getPP_Plant() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setPP_Plant(org.compiere.model.I_S_Resource PP_Plant)
{
set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant);
}
/** Set Produktionsstätte.
@param PP_Plant_ID Produktionsstätte */
@Override
public void setPP_Plant_ID (int PP_Plant_ID)
{
if (PP_Plant_ID < 1)
set_Value (COLUMNNAME_PP_Plant_ID, null);
else
set_Value (COLUMNNAME_PP_Plant_ID, Integer.valueOf(PP_Plant_ID));
}
/** Get Produktionsstätte.
@return Produktionsstätte */
@Override
public int getPP_Plant_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Plant_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
|
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_Order_MFGWarehouse_Report.java
| 1
|
请完成以下Java代码
|
private ListenableFuture<TbMsg> publishMessageAsync(TbContext ctx, TbMsg msg) {
return ctx.getExternalCallExecutor().executeAsync(() -> publishMessage(msg));
}
private TbMsg publishMessage(TbMsg msg) {
String topicArn = TbNodeUtils.processPattern(this.config.getTopicArnPattern(), msg);
PublishRequest publishRequest = new PublishRequest()
.withTopicArn(topicArn)
.withMessage(msg.getData());
PublishResult result = this.snsClient.publish(publishRequest);
return processPublishResult(msg, result);
}
private TbMsg processPublishResult(TbMsg origMsg, PublishResult result) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(MESSAGE_ID, result.getMessageId());
metaData.putValue(REQUEST_ID, result.getSdkResponseMetadata().getRequestId());
return origMsg.transform()
.metaData(metaData)
.build();
}
private TbMsg processException(TbMsg origMsg, Throwable t) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue(ERROR, t.getClass() + ": " + t.getMessage());
return origMsg.transform()
|
.metaData(metaData)
.build();
}
@Override
public void destroy() {
if (this.snsClient != null) {
try {
this.snsClient.shutdown();
} catch (Exception e) {
log.error("Failed to shutdown SNS client during destroy()", e);
}
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\sns\TbSnsNode.java
| 1
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
public UserDO setId(Integer id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
|
public Date getCreateTime() {
return createTime;
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
public Integer getDeleted() {
return deleted;
}
public UserDO setDeleted(Integer deleted) {
this.deleted = deleted;
return this;
}
public Integer getTenantId() {
return tenantId;
}
public UserDO setTenantId(Integer tenantId) {
this.tenantId = tenantId;
return this;
}
}
|
repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\dataobject\UserDO.java
| 1
|
请完成以下Java代码
|
public List<I_M_InOut> getReceiptsToReverseFromHUIds(final Collection<Integer> huIds)
{
if (huIds == null || huIds.isEmpty())
{
return ImmutableList.of();
}
return getReceiptsToReverse(huIds.stream());
}
private final List<I_M_InOut> getReceiptsToReverse(final Stream<Integer> huIds)
{
return huIds
.map(huId -> getReceiptOrNull(huId))
// skip if no receipt found because
// * it could be that user selected not a top level HU.... skip it for now
// * or we were really asked to as much as we can
.filter(receipt -> receipt != null)
.collect(GuavaCollectors.toImmutableList());
}
/**
* Get all HUs which are assigned to given receipts.
*
* @param receipts
* @return HUs
*/
public Set<I_M_HU> getHUsForReceipts(final Collection<? extends I_M_InOut> receipts)
{
final Set<I_M_HU> hus = new TreeSet<>(HUByIdComparator.instance);
for (final I_M_InOut receipt : receipts)
{
final int inoutId = receipt.getM_InOut_ID();
final Collection<I_M_HU> husForReceipt = inoutId2hus.get(inoutId);
if (Check.isEmpty(husForReceipt))
{
continue;
}
hus.addAll(husForReceipt);
}
return hus;
}
|
public static final class Builder
{
private I_M_ReceiptSchedule receiptSchedule;
private boolean tolerateNoHUsFound = false;
private Builder()
{
super();
}
public ReceiptCorrectHUsProcessor build()
{
return new ReceiptCorrectHUsProcessor(this);
}
public Builder setM_ReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule)
{
this.receiptSchedule = receiptSchedule;
return this;
}
private I_M_ReceiptSchedule getM_ReceiptSchedule()
{
Check.assumeNotNull(receiptSchedule, "Parameter receiptSchedule is not null");
return receiptSchedule;
}
public Builder tolerateNoHUsFound()
{
tolerateNoHUsFound = true;
return this;
}
private boolean isFailOnNoHUsFound()
{
return !tolerateNoHUsFound;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\ReceiptCorrectHUsProcessor.java
| 1
|
请完成以下Java代码
|
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
@Override
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
@Override
public java.lang.String getVendorProductNo()
{
return get_ValueAsString(COLUMNNAME_VendorProductNo);
}
@Override
public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeightUOM (final @Nullable java.lang.String WeightUOM)
{
set_Value (COLUMNNAME_WeightUOM, WeightUOM);
}
|
@Override
public java.lang.String getWeightUOM()
{
return get_ValueAsString(COLUMNNAME_WeightUOM);
}
@Override
public void setWeight_UOM_ID (final int Weight_UOM_ID)
{
if (Weight_UOM_ID < 1)
set_Value (COLUMNNAME_Weight_UOM_ID, null);
else
set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID);
}
@Override
public int getWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID);
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
@Override
public void setX12DE355 (final @Nullable java.lang.String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
@Override
public java.lang.String getX12DE355()
{
return get_ValueAsString(COLUMNNAME_X12DE355);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ProductCategoryId getProductCategoryId(@NonNull final ProductId productId)
{
return getProductInfo(productId).getProductCategoryId();
}
@Override
public ITranslatableString getProductName(@NonNull final ProductId productId)
{
return getProductInfo(productId).getName();
}
private ProductInfo getProductInfo(@NonNull final ProductId productId)
{
return productInfoCache.computeIfAbsent(productId, productService::getById);
}
@Override
public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId)
{
return huService.getPackingInfo(huPIItemProductId);
}
@Override
public String getPICaption(@NonNull final HuPackingInstructionsId piId)
{
return huService.getPI(piId).getName();
}
@Override
public String getLocatorName(@NonNull final LocatorId locatorId)
{
return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById);
}
|
@Override
public HUQRCode getQRCodeByHUId(final HuId huId)
{
return huService.getQRCodeByHuId(huId);
}
@Override
public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds)
{
return pickingJobLockService.getLocks(scheduleIds);
}
@Override
public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId)
{
return orderService.getSalesOrderLineSeqNo(orderAndLineId);
}
//
//
//
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java
| 2
|
请完成以下Java代码
|
public int getMSV3_Tour_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Tour_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil getMSV3_VerfuegbarkeitAnteil() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil.class);
}
@Override
public void setMSV3_VerfuegbarkeitAnteil(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil MSV3_VerfuegbarkeitAnteil)
{
set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitAnteil.class, MSV3_VerfuegbarkeitAnteil);
}
/** Set MSV3_VerfuegbarkeitAnteil.
|
@param MSV3_VerfuegbarkeitAnteil_ID MSV3_VerfuegbarkeitAnteil */
@Override
public void setMSV3_VerfuegbarkeitAnteil_ID (int MSV3_VerfuegbarkeitAnteil_ID)
{
if (MSV3_VerfuegbarkeitAnteil_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID, Integer.valueOf(MSV3_VerfuegbarkeitAnteil_ID));
}
/** Get MSV3_VerfuegbarkeitAnteil.
@return MSV3_VerfuegbarkeitAnteil */
@Override
public int getMSV3_VerfuegbarkeitAnteil_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitAnteil_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_Tour.java
| 1
|
请完成以下Java代码
|
public OutputSet newInstance(ModelTypeInstanceContext instanceContext) {
return new OutputSetImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataOutputRefsCollection = sequenceBuilder.elementCollection(DataOutputRefs.class)
.idElementReferenceCollection(DataOutput.class)
.build();
optionalOutputRefsCollection = sequenceBuilder.elementCollection(OptionalOutputRefs.class)
.idElementReferenceCollection(DataOutput.class)
.build();
whileExecutingOutputRefsCollection = sequenceBuilder.elementCollection(WhileExecutingOutputRefs.class)
.idElementReferenceCollection(DataOutput.class)
.build();
inputSetInputSetRefsCollection = sequenceBuilder.elementCollection(InputSetRefs.class)
.idElementReferenceCollection(InputSet.class)
.build();
typeBuilder.build();
}
public OutputSetImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
|
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Collection<DataOutput> getDataOutputRefs() {
return dataOutputRefsCollection.getReferenceTargetElements(this);
}
public Collection<DataOutput> getOptionalOutputRefs() {
return optionalOutputRefsCollection.getReferenceTargetElements(this);
}
public Collection<DataOutput> getWhileExecutingOutputRefs() {
return whileExecutingOutputRefsCollection.getReferenceTargetElements(this);
}
public Collection<InputSet> getInputSetRefs() {
return inputSetInputSetRefsCollection.getReferenceTargetElements(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\OutputSetImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class User {
@Id
private Long id;
private String username;
private String email;
@JsonManagedReference
@OneToOne(cascade = CascadeType.ALL)
private Profile profile;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "author", fetch = FetchType.EAGER)
protected List<Post> posts;
@ManyToMany(mappedBy = "members", fetch = FetchType.EAGER)
private List<Group> groups;
public User() {
}
public Long getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public String getEmail() {
return this.email;
}
public Profile getProfile() {
return this.profile;
}
public List<Post> getPosts() {
return this.posts;
}
public List<Group> getGroups() {
return this.groups;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
|
public void setEmail(String email) {
this.email = email;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", profile="
+ this.getProfile() + ", posts=" + this.getPosts() + ", groups=" + this.getGroups() + ")";
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\User.java
| 2
|
请完成以下Java代码
|
public static List<ModelToIndexEnqueueRequest> extractRequests(
@NonNull final Object model,
@NonNull final ModelToIndexEventType eventType,
@NonNull final FTSConfigSourceTablesMap sourceTablesMap)
{
final TableName tableName = TableName.ofString(InterfaceWrapperHelper.getModelTableName(model));
final int recordId = InterfaceWrapperHelper.getId(model);
final TableRecordReference recordRef = TableRecordReference.of(tableName.getAsString(), recordId);
final boolean recordIsActive = InterfaceWrapperHelper.isActive(model);
final ImmutableList<FTSConfigSourceTable> sourceTables = sourceTablesMap.getByTableName(tableName);
final ArrayList<ModelToIndexEnqueueRequest> result = new ArrayList<>(sourceTables.size());
for (final FTSConfigSourceTable sourceTable : sourceTables)
{
final TableRecordReference recordRefEffective;
final ModelToIndexEventType eventTypeEffective;
final TableRecordReference parentRecordRef = extractParentRecordRef(model, sourceTable);
if (parentRecordRef != null)
{
recordRefEffective = parentRecordRef;
eventTypeEffective = ModelToIndexEventType.CREATED_OR_UPDATED;
}
else
{
recordRefEffective = recordRef;
if (recordIsActive)
{
eventTypeEffective = eventType;
}
else
{
eventTypeEffective = ModelToIndexEventType.REMOVED;
}
}
result.add(ModelToIndexEnqueueRequest.builder()
.ftsConfigId(sourceTable.getFtsConfigId())
.eventType(eventTypeEffective)
.sourceModelRef(recordRefEffective)
.build());
}
return result;
}
|
@Nullable
private static TableRecordReference extractParentRecordRef(@NonNull final Object model, @NonNull final FTSConfigSourceTable sourceTable)
{
final TableAndColumnName parentColumnName = sourceTable.getParentColumnName();
if (parentColumnName == null)
{
return null;
}
final int parentId = InterfaceWrapperHelper.getValue(model, parentColumnName.getColumnNameAsString())
.map(NumberUtils::asIntegerOrNull)
.orElse(-1);
if (parentId <= 0)
{
return null;
}
return TableRecordReference.of(parentColumnName.getTableNameAsString(), parentId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\model_interceptor\EnqueueSourceModelInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EmployeeController {
private final EmployeeService organisationService;
public EmployeeController(EmployeeService organisationService) {
this.organisationService = organisationService;
}
@GetMapping("/employee")
public ResponseEntity<Page<EmployeeDto>> getEmployeeData(Pageable pageable) {
Page<EmployeeDto> employeeData = organisationService.getEmployeeData(pageable);
return ResponseEntity.ok(employeeData);
}
@GetMapping("/data")
public ResponseEntity<Page<EmployeeDto>> getData(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
List<EmployeeDto> empList = listImplementation();
int totalSize = empList.size();
|
int startIndex = page * size;
int endIndex = Math.min(startIndex + size, totalSize);
List<EmployeeDto> pageContent = empList.subList(startIndex, endIndex);
Page<EmployeeDto> employeeDtos = new PageImpl<>(pageContent, PageRequest.of(page, size), totalSize);
return ResponseEntity.ok()
.body(employeeDtos);
}
private static List<EmployeeDto> listImplementation() {
List<EmployeeDto> empList = new ArrayList<>();
empList.add(new EmployeeDto("Jane", "Finance", 50000));
empList.add(new EmployeeDto("Sarah", "IT", 70000));
empList.add(new EmployeeDto("John", "IT", 90000));
return empList;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\pageentityresponse\EmployeeController.java
| 2
|
请完成以下Java代码
|
public void clear() {
throw new FlowableException("can't clear configuration beans");
}
@Override
public boolean containsValue(Object value) {
throw new FlowableException("can't search values in configuration beans");
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public boolean isEmpty() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Object put(Object key, Object value) {
throw new FlowableException("unsupported operation on configuration beans");
}
|
@Override
public void putAll(Map<? extends Object, ? extends Object> m) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Object remove(Object key) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public int size() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Collection<Object> values() {
throw new FlowableException("unsupported operation on configuration beans");
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\SpringBeanFactoryProxyMap.java
| 1
|
请完成以下Java代码
|
public String getTalentId() {
return TalentId;
}
public void setTalentId(String TalentId) {
this.TalentId = TalentId;
}
public String getCallbackData() {
return CallbackData;
}
public void setCallbackData(String CallbackData) {
this.CallbackData = CallbackData;
}
public String getCallbackQueue() {
|
return CallbackQueue;
}
public void setCallbackQueue(String CallbackQueue) {
this.CallbackQueue = CallbackQueue;
}
@Override
public String toString() {
return "TalentMQMessage{" +
"TalentId='" + TalentId + '\'' +
", CallbackData='" + CallbackData + '\'' +
", CallbackQueue='" + CallbackQueue + '\'' +
'}';
}
}
|
repos\spring-boot-quick-master\quick-activemq\src\main\java\com\mq\model\TalentMQMessage.java
| 1
|
请完成以下Java代码
|
public static class ParentNodeIterator implements Iterator<HierarchyNode>
{
private final ImmutableMap<HierarchyNode, HierarchyNode> child2Parent;
private HierarchyNode next;
private HierarchyNode previous;
private ParentNodeIterator(
@NonNull final ImmutableMap<HierarchyNode, HierarchyNode> childAndParent,
@NonNull final HierarchyNode first)
{
this.child2Parent = childAndParent;
this.next = first;
}
@Override
public boolean hasNext()
{
|
return next != null;
}
@Override
public HierarchyNode next()
{
final HierarchyNode result = next;
if (result == null)
{
throw new NoSuchElementException("Previous HierarchyNode=" + previous + " had no parent");
}
previous = next;
next = child2Parent.get(next);
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\hierarchy\Hierarchy.java
| 1
|
请完成以下Java代码
|
public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
this.nm = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
* possible object is
* {@link PostalAddress6 }
*
*/
public PostalAddress6 getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link PostalAddress6 }
*
*/
public void setPstlAdr(PostalAddress6 value) {
this.pstlAdr = value;
}
/**
|
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link GenericFinancialIdentification1 }
*
*/
public GenericFinancialIdentification1 getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link GenericFinancialIdentification1 }
*
*/
public void setOthr(GenericFinancialIdentification1 value) {
this.othr = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\FinancialInstitutionIdentification7.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TwilioConfigurationProperties {
@NotBlank(message = "Twilio account SID must be configured")
@Pattern(regexp = "^AC[0-9a-fA-F]{32}$", message = "Invalid Twilio account SID format")
private String accountSid;
@NotBlank(message = "Twilio auth token must be configured")
private String authToken;
@NotBlank(message = "Twilio messaging SID must be configured")
@Pattern(regexp = "^MG[0-9a-fA-F]{32}$", message = "Invalid Twilio messaging SID format")
private String messagingSid;
@Valid
private NewArticleNotification newArticleNotification = new NewArticleNotification();
public String getAccountSid() {
return accountSid;
}
public void setAccountSid(String accountSid) {
this.accountSid = accountSid;
}
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
|
public String getMessagingSid() {
return messagingSid;
}
public void setMessagingSid(String messagingSid) {
this.messagingSid = messagingSid;
}
public NewArticleNotification getNewArticleNotification() {
return newArticleNotification;
}
public void setNewArticleNotification(NewArticleNotification newArticleNotification) {
this.newArticleNotification = newArticleNotification;
}
public class NewArticleNotification {
@NotBlank(message = "Content SID must be configured")
@Pattern(regexp = "^HX[0-9a-fA-F]{32}$", message = "Invalid content SID format")
private String contentSid;
public String getContentSid() {
return contentSid;
}
public void setContentSid(String contentSid) {
this.contentSid = contentSid;
}
}
}
|
repos\tutorials-master\saas-modules\twilio-whatsapp\src\main\java\com\baeldung\twilio\whatsapp\TwilioConfigurationProperties.java
| 2
|
请完成以下Java代码
|
public String createShowWindowHTML(String text, String tableName, final int adWindowId, String whereClause)
{
final int AD_Table_ID = Services.get(IADTableDAO.class).retrieveTableId(tableName);
final Map<String, String> params = new LinkedHashMap<>(); // we use LinkedHashMap because we need a predictable order; tests are depending on this.
params.put("AD_Table_ID", Integer.toString(AD_Table_ID));
params.put("WhereClause", whereClause);
if(adWindowId > 0)
{
params.put("AD_Window_ID", Integer.toString(adWindowId));
}
final ADHyperlink link = new ADHyperlink(ADHyperlink.Action.ShowWindow, params);
final URI uri = toURI(link);
return "<a href=\"" + uri.toString() + "\">"
+ StringEscapeUtils.escapeHtml4(text)
+ "</a>";
}
public ADHyperlink getADHyperlink(String uri)
{
try
{
return getADHyperlink(new URI(uri));
}
catch (URISyntaxException e)
{
throw new AdempiereException(e);
}
}
public ADHyperlink getADHyperlink(final URI uri)
{
String protocol = uri.getScheme();
if (!PROTOCOL.equals(protocol))
return null;
String host = uri.getHost();
if (!HOST.equals(host))
return null;
String actionStr = uri.getPath();
if (actionStr.startsWith("/"))
actionStr = actionStr.substring(1);
ADHyperlink.Action action = ADHyperlink.Action.valueOf(actionStr);
Map<String, String> params = StringUtils.parseURLQueryString(uri.getQuery());
return new ADHyperlink(action, params);
}
private String encodeParams(Map<String, String> params)
{
StringBuilder urlParams = new StringBuilder();
if (params != null && !params.isEmpty())
{
for (Map.Entry<String, String> e : params.entrySet())
{
if (urlParams.length() > 0)
{
// We need to use %26 instead of "&" because of org.compiere.process.ProcessInfo.getSummary(),
// which strips ampersands
urlParams.append("%26");
}
urlParams.append(encode(e.getKey()));
urlParams.append("=");
urlParams.append(encode(e.getValue()));
|
}
}
return urlParams.toString();
}
private URI toURI(ADHyperlink link)
{
String urlParams = encodeParams(link.getParameters());
String urlStr = PROTOCOL + "://" + HOST + "/" + link.getAction().toString() + "?" + urlParams;
try
{
return new URI(urlStr);
}
catch (URISyntaxException e)
{
throw new AdempiereException(e);
}
}
private String encode(String s)
{
try
{
return URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new AdempiereException(e);
}
}
private String decode(String s)
{
try
{
return URLDecoder.decode(s, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
throw new AdempiereException(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\util\ADHyperlinkBuilder.java
| 1
|
请完成以下Java代码
|
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(Jwt.class, principal, "principal must be of type Jwt");
return token((Jwt) principal);
}
/**
* A synonym for {@link #token(Jwt)}
* @return the {@link Builder} for further configurations
*/
@Override
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 <S> S getServiceValue(ServiceType type, String localName) {
String globalName = composeLocalName(type, localName);
ObjectName serviceName = getObjectName(globalName);
return getServiceValue(serviceName);
}
/**
* @return all services for a specific {@link ServiceType}
*/
@SuppressWarnings("unchecked")
public <S> List<PlatformService<S>> getServicesByType(ServiceType type) {
// query the MBeanServer for all services of the given type
Set<String> serviceNames = getServiceNames(type);
List<PlatformService<S>> res = new ArrayList<PlatformService<S>>();
for (String serviceName : serviceNames) {
res.add((PlatformService<S>) servicesByName.get(getObjectName(serviceName)));
}
return res;
}
/**
* @return the service names ( {@link ObjectName} ) for all services for a given type
*/
public Set<String> getServiceNames(ServiceType type) {
String typeName = composeLocalName(type, "*");
ObjectName typeObjectName = getObjectName(typeName);
Set<ObjectName> resultNames = getmBeanServer().queryNames(typeObjectName, null);
Set<String> result= new HashSet<String>();
for (ObjectName objectName : resultNames) {
result.add(objectName.toString());
}
return result;
}
/**
* @return the values of all services for a specific {@link ServiceType}
*/
@SuppressWarnings("unchecked")
public <S> List<S> getServiceValuesByType(ServiceType type) {
|
// query the MBeanServer for all services of the given type
Set<String> serviceNames = getServiceNames(type);
List<S> res = new ArrayList<S>();
for (String serviceName : serviceNames) {
PlatformService<S> BpmPlatformService = (PlatformService<S>) servicesByName.get(getObjectName(serviceName));
if (BpmPlatformService != null) {
res.add(BpmPlatformService.getValue());
}
}
return res;
}
public MBeanServer getmBeanServer() {
if (mBeanServer == null) {
synchronized (this) {
if (mBeanServer == null) {
mBeanServer = createOrLookupMbeanServer();
}
}
}
return mBeanServer;
}
public void setmBeanServer(MBeanServer mBeanServer) {
this.mBeanServer = mBeanServer;
}
protected MBeanServer createOrLookupMbeanServer() {
return ManagementFactory.getPlatformMBeanServer();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\MBeanServiceContainer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getAdditionalPath() {
return this.additionalPath;
}
public void setAdditionalPath(@Nullable String additionalPath) {
this.additionalPath = additionalPath;
}
}
/**
* Health logging properties.
*/
public static class Logging {
|
/**
* Threshold after which a warning will be logged for slow health indicators.
*/
private Duration slowIndicatorThreshold = Duration.ofSeconds(10);
public Duration getSlowIndicatorThreshold() {
return this.slowIndicatorThreshold;
}
public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) {
this.slowIndicatorThreshold = slowIndicatorThreshold;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class FooController {
@PostConstruct
public void init(){
System.out.println("test");
}
@Autowired
private FooRepository repo;
// API - read
@GetMapping("/foos/{id}")
@ResponseBody
@Validated
public Foo findById(@PathVariable @Min(0) final long id) {
return repo.findById(id)
.orElse(null);
}
@GetMapping
@ResponseBody
public List<Foo> findAll() {
|
return repo.findAll();
}
@GetMapping(params = { "page", "size" })
@ResponseBody
@Validated
public List<Foo> findPaginated(@RequestParam("page") @Min(0) final int page, @Max(100) @RequestParam("size") final int size) {
return repo.findAll(PageRequest.of(page, size))
.getContent();
}
// API - write
@PutMapping("/foos/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Foo update(@PathVariable("id") final String id, @RequestBody final Foo foo) {
return foo;
}
}
|
repos\tutorials-master\spring-5\src\main\java\com\baeldung\web\FooController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Duration getTimeoutWithMargin() {
return this.timeout.minusSeconds(1).abs();
}
protected Mono<StatusInfo> convertStatusInfo(ClientResponse response) {
boolean hasCompatibleContentType = response.headers()
.contentType()
.filter((mt) -> mt.isCompatibleWith(MediaType.APPLICATION_JSON)
|| this.apiMediaTypeHandler.isApiMediaType(mt))
.isPresent();
StatusInfo statusInfoFromStatus = this.getStatusInfoFromStatus(response.statusCode(), emptyMap());
if (hasCompatibleContentType) {
return response.bodyToMono(RESPONSE_TYPE).map((body) -> {
if (body.get("status") instanceof String) {
return StatusInfo.from(body);
}
return getStatusInfoFromStatus(response.statusCode(), body);
}).defaultIfEmpty(statusInfoFromStatus);
}
return response.releaseBody().then(Mono.just(statusInfoFromStatus));
}
@SuppressWarnings("unchecked")
protected StatusInfo getStatusInfoFromStatus(HttpStatusCode httpStatus, Map<String, ?> body) {
if (httpStatus.is2xxSuccessful()) {
return StatusInfo.ofUp();
}
Map<String, Object> details = new LinkedHashMap<>();
details.put("status", httpStatus.value());
details.put("error", Objects.requireNonNull(HttpStatus.resolve(httpStatus.value())).getReasonPhrase());
if (body.get("details") instanceof Map) {
details.putAll((Map<? extends String, ?>) body.get("details"));
|
}
else {
details.putAll(body);
}
return StatusInfo.ofDown(details);
}
protected Mono<StatusInfo> handleError(Throwable ex) {
Map<String, Object> details = new HashMap<>();
details.put("message", ex.getMessage());
details.put("exception", ex.getClass().getName());
return Mono.just(StatusInfo.ofOffline(details));
}
protected void logError(Instance instance, Throwable ex) {
if (instance.getStatusInfo().isOffline()) {
log.debug("Couldn't retrieve status for {}", instance, ex);
}
else {
log.info("Couldn't retrieve status for {}", instance, ex);
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\StatusUpdater.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void changeTaskAssignee(TaskEntity taskEntity, String userId) {
getTaskEntityManager().changeTaskAssignee(taskEntity, userId);
}
@Override
public void changeTaskOwner(TaskEntity taskEntity, String ownerId) {
getTaskEntityManager().changeTaskOwner(taskEntity, ownerId);
}
@Override
public void updateTaskTenantIdForDeployment(String deploymentId, String tenantId) {
getTaskEntityManager().updateTaskTenantIdForDeployment(deploymentId, tenantId);
}
@Override
public void updateTask(TaskEntity taskEntity, boolean fireUpdateEvent) {
getTaskEntityManager().update(taskEntity, fireUpdateEvent);
}
@Override
public void updateAllTaskRelatedEntityCountFlags(boolean configProperty) {
getTaskEntityManager().updateAllTaskRelatedEntityCountFlags(configProperty);
}
@Override
public TaskEntity createTask() {
return getTaskEntityManager().create();
}
@Override
public void insertTask(TaskEntity taskEntity, boolean fireCreateEvent) {
getTaskEntityManager().insert(taskEntity, fireCreateEvent);
}
@Override
public void deleteTask(TaskEntity task, boolean fireEvents) {
|
getTaskEntityManager().delete(task, fireEvents);
}
@Override
public void deleteTasksByExecutionId(String executionId) {
getTaskEntityManager().deleteTasksByExecutionId(executionId);
}
public TaskEntityManager getTaskEntityManager() {
return configuration.getTaskEntityManager();
}
@Override
public TaskEntity createTask(TaskBuilder taskBuilder) {
return getTaskEntityManager().createTask(taskBuilder);
}
protected VariableServiceConfiguration getVariableServiceConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public R copy(@Parameter(description = "主键", required = true) @RequestParam Long id) {
Code code = codeService.getById(id);
code.setId(null);
code.setCodeName(code.getCodeName() + "-copy");
return R.status(codeService.save(code));
}
/**
* 代码生成
*/
@PostMapping("/gen-code")
@ApiOperationSupport(order = 6)
@Operation(summary = "代码生成", description = "传入ids")
public R genCode(@Parameter(description = "主键集合", required = true) @RequestParam String ids, @RequestParam(defaultValue = "saber3") String system) {
Collection<Code> codes = codeService.listByIds(Func.toLongList(ids));
codes.forEach(code -> {
BladeCodeGenerator generator = new BladeCodeGenerator();
// 设置数据源
Datasource datasource = datasourceService.getById(code.getDatasourceId());
generator.setDriverName(datasource.getDriverClass());
generator.setUrl(datasource.getUrl());
generator.setUsername(datasource.getUsername());
generator.setPassword(datasource.getPassword());
// 设置基础配置
generator.setSystemName(system);
generator.setServiceName(code.getServiceName());
|
generator.setPackageName(code.getPackageName());
generator.setPackageDir(code.getApiPath());
generator.setPackageWebDir(code.getWebPath());
generator.setTablePrefix(Func.toStrArray(code.getTablePrefix()));
generator.setIncludeTables(Func.toStrArray(code.getTableName()));
// 设置是否继承基础业务字段
generator.setHasSuperEntity(code.getBaseMode() == 2);
// 设置是否开启包装器模式
generator.setHasWrapper(code.getWrapMode() == 2);
generator.run();
});
return R.success("代码生成成功");
}
}
|
repos\SpringBlade-master\blade-ops\blade-develop\src\main\java\org\springblade\develop\controller\CodeController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DatabaseService {
@Value("${db.name:hello}")
private String name; // if db.name doesn't exist, we get the default hello
@Value("${db.thread-pool:3}")
private Integer threadPool; // if db.thread-pool doesn't exist, we get the default 3
@Override
public String toString() {
return "DatabaseService{" +
"name='" + name + '\'' +
", threadPool=" + threadPool +
'}';
}
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getThreadPool() {
return threadPool;
}
public void setThreadPool(Integer threadPool) {
this.threadPool = threadPool;
}
}
|
repos\spring-boot-master\spring-boot-externalize-config-4\src\main\java\com\mkyong\service\DatabaseService.java
| 2
|
请完成以下Java代码
|
private MStorage[] getSources(final int M_Product_ID, final int M_Locator_ID)
{
ArrayList<MStorage> list = new ArrayList<>();
String sql = "SELECT * "
+ "FROM M_Storage s "
+ "WHERE QtyOnHand > 0"
+ " AND M_Product_ID=?"
// Empty ASI
+ " AND (M_AttributeSetInstance_ID=0"
+ " OR EXISTS (SELECT * FROM M_AttributeSetInstance asi "
+ "WHERE s.M_AttributeSetInstance_ID=asi.M_AttributeSetInstance_ID"
+ " AND asi.Description IS NULL) )"
// Stock in same Warehouse
+ " AND EXISTS (SELECT * FROM M_Locator sl, M_Locator x "
+ "WHERE s.M_Locator_ID=sl.M_Locator_ID"
+ " AND x.M_Locator_ID=?"
+ " AND sl.M_Warehouse_ID=x.M_Warehouse_ID) "
+ "ORDER BY M_AttributeSetInstance_ID";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, M_Product_ID);
pstmt.setInt(2, M_Locator_ID);
|
rs = pstmt.executeQuery();
while (rs.next())
{
list.add(new MStorage(getCtx(), rs, get_TrxName()));
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
final MStorage[] retValue = new MStorage[list.size()];
list.toArray(retValue);
return retValue;
} // getSources
} // StorageCleanup
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\StorageCleanup.java
| 1
|
请完成以下Java代码
|
public static class CreateUpdateAsyncEventRepositoryFunction<T, ID>
extends AbstractAsyncEventOperationRepositoryFunction<T, ID> {
/**
* Constructs a new instance of {@link CreateUpdateAsyncEventRepositoryFunction} initialized with the given,
* required {@link RepositoryAsyncEventListener}.
*
* @param listener {@link RepositoryAsyncEventListener} forwarding {@link AsyncEvent AsyncEvents} for processing
* by this {@link Function}
* @see RepositoryAsyncEventListener
*/
public CreateUpdateAsyncEventRepositoryFunction(@NonNull RepositoryAsyncEventListener<T, ID> listener) {
super(listener);
}
/**
* @inheritDoc
*/
@Override
public boolean canProcess(@Nullable AsyncEvent<ID, T> event) {
Operation operation = event != null ? event.getOperation() : null;
return operation != null && (operation.isCreate() || operation.isUpdate());
}
/**
* @inheritDoc
*/
@Override
@SuppressWarnings("unchecked")
protected <R> R doRepositoryOp(T entity) {
return (R) getRepository().save(entity);
}
}
/**
* An {@link Function} implementation capable of handling {@link Operation#REMOVE} {@link AsyncEvent AsyncEvents}.
*
* Invokes the {@link CrudRepository#delete(Object)} data access operation.
*
* @param <T> {@link Class type} of the entity tied to the event.
* @param <ID> {@link Class type} of the identifier of the entity.
*/
public static class RemoveAsyncEventRepositoryFunction<T, ID>
extends AbstractAsyncEventOperationRepositoryFunction<T, ID> {
/**
* Constructs a new instance of {@link RemoveAsyncEventRepositoryFunction} initialized with the given, required
* {@link RepositoryAsyncEventListener}.
*
* @param listener {@link RepositoryAsyncEventListener} forwarding {@link AsyncEvent AsyncEvents} for processing
* by this {@link Function}
* @see RepositoryAsyncEventListener
|
*/
public RemoveAsyncEventRepositoryFunction(@NonNull RepositoryAsyncEventListener<T, ID> listener) {
super(listener);
}
/**
* @inheritDoc
*/
@Override
public boolean canProcess(@Nullable AsyncEvent<ID, T> event) {
Operation operation = event != null ? event.getOperation() : null;
return Operation.REMOVE.equals(operation);
}
/**
* @inheritDoc
*/
@Override
protected <R> R doRepositoryOp(T entity) {
getRepository().delete(entity);
return null;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\RepositoryAsyncEventListener.java
| 1
|
请完成以下Java代码
|
public boolean isAccountingTable(final String docTableName)
{
return docProviders.isAccountingTable(docTableName);
}
//
//
//
// ------------------------------------------------------------------------
//
//
//
@ToString
private static class AggregatedAcctDocProvider implements IAcctDocProvider
{
private final ImmutableMap<String, IAcctDocProvider> providersByDocTableName;
private AggregatedAcctDocProvider(final List<IAcctDocProvider> providers)
{
final ImmutableMap.Builder<String, IAcctDocProvider> mapBuilder = ImmutableMap.builder();
for (final IAcctDocProvider provider : providers)
{
for (final String docTableName : provider.getDocTableNames())
{
mapBuilder.put(docTableName, provider);
}
}
this.providersByDocTableName = mapBuilder.build();
}
public boolean isAccountingTable(final String docTableName)
{
return getDocTableNames().contains(docTableName);
}
@Override
public Set<String> getDocTableNames()
{
return providersByDocTableName.keySet();
}
@Override
public Doc<?> getOrNull(
@NonNull final AcctDocRequiredServicesFacade services,
@NonNull final List<AcctSchema> acctSchemas,
@NonNull final TableRecordReference documentRef)
{
try
|
{
final String docTableName = documentRef.getTableName();
final IAcctDocProvider provider = providersByDocTableName.get(docTableName);
if (provider == null)
{
return null;
}
return provider.getOrNull(services, acctSchemas, documentRef);
}
catch (final AdempiereException ex)
{
throw ex;
}
catch (final Exception ex)
{
throw PostingExecutionException.wrapIfNeeded(ex);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\AcctDocRegistry.java
| 1
|
请完成以下Java代码
|
public void setPage_Identifier (java.lang.String Page_Identifier)
{
set_ValueNoCheck (COLUMNNAME_Page_Identifier, Page_Identifier);
}
/** Get Page_Identifier.
@return Page_Identifier */
@Override
public java.lang.String getPage_Identifier ()
{
return (java.lang.String)get_Value(COLUMNNAME_Page_Identifier);
}
/** Set Page_Offset.
@param Page_Offset Page_Offset */
@Override
public void setPage_Offset (int Page_Offset)
{
set_ValueNoCheck (COLUMNNAME_Page_Offset, Integer.valueOf(Page_Offset));
}
/** Get Page_Offset.
@return Page_Offset */
@Override
public int getPage_Offset ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Page_Offset);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Page_Size.
@param Page_Size Page_Size */
@Override
public void setPage_Size (int Page_Size)
{
set_ValueNoCheck (COLUMNNAME_Page_Size, Integer.valueOf(Page_Size));
}
/** Get Page_Size.
@return Page_Size */
@Override
public int getPage_Size ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Page_Size);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Result_Time.
@param Result_Time Result_Time */
@Override
public void setResult_Time (java.sql.Timestamp Result_Time)
{
set_ValueNoCheck (COLUMNNAME_Result_Time, Result_Time);
}
/** Get Result_Time.
@return Result_Time */
@Override
public java.sql.Timestamp getResult_Time ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_Result_Time);
|
}
/** Set Total_Size.
@param Total_Size Total_Size */
@Override
public void setTotal_Size (int Total_Size)
{
set_ValueNoCheck (COLUMNNAME_Total_Size, Integer.valueOf(Total_Size));
}
/** Get Total_Size.
@return Total_Size */
@Override
public int getTotal_Size ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Total_Size);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UUID.
@param UUID UUID */
@Override
public void setUUID (java.lang.String UUID)
{
set_ValueNoCheck (COLUMNNAME_UUID, UUID);
}
/** Get UUID.
@return UUID */
@Override
public java.lang.String getUUID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UUID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection_Pagination.java
| 1
|
请完成以下Java代码
|
private boolean isInvoicePaySelectionLine(@NonNull final I_C_PaySelectionLine line)
{
return paySelectionBL.extractType(line) == PaySelectionLineType.Invoice;
}
private static @Nullable String toNullOrRemoveSpaces(@Nullable final String from)
{
final String fromNorm = StringUtils.trimBlankToNull(from);
return fromNorm != null ? fromNorm.replace(" ", "") : null;
}
@NonNull
private static String extractIBAN(@NonNull final BankAccount bpBankAccount)
{
final String iban = coalesceSuppliers(
() -> toNullOrRemoveSpaces(bpBankAccount.getIBAN()),
() -> toNullOrRemoveSpaces(bpBankAccount.getQR_IBAN())
);
if (Check.isBlank(iban))
{
throw new AdempiereException(ERR_C_BP_BankAccount_IBANNotSet, bpBankAccount);
}
return iban;
}
@NonNull
private CreateSEPAExportFromPaySelectionCommand.InvoicePaySelectionLinesAggregationKey extractPaySelectionLinesKey(@NonNull final I_C_PaySelectionLine paySelectionLine)
{
final BankAccountId bankAccountId = BankAccountId.ofRepoId(paySelectionLine.getC_BP_BankAccount_ID());
final BankAccount bpBankAccount = bankAccountDAO.getById(bankAccountId);
|
return InvoicePaySelectionLinesAggregationKey.builder()
.orgId(OrgId.ofRepoId(paySelectionLine.getAD_Org_ID()))
.partnerId(BPartnerId.ofRepoId(paySelectionLine.getC_BPartner_ID()))
.bankAccountId(bankAccountId)
.currencyId(bpBankAccount.getCurrencyId())
.iban(extractIBAN(bpBankAccount))
.swiftCode(extractSwiftCode(bpBankAccount))
.build();
}
private @Nullable String extractSwiftCode(@NonNull final BankAccount bpBankAccount)
{
return Optional.ofNullable(bpBankAccount.getBankId())
.map(bankRepo::getById)
.map(bank -> toNullOrRemoveSpaces(bank.getSwiftCode()))
.orElse(null);
}
@Value
@Builder
private static class InvoicePaySelectionLinesAggregationKey
{
@NonNull OrgId orgId;
@NonNull BPartnerId partnerId;
@NonNull BankAccountId bankAccountId;
@NonNull CurrencyId currencyId;
@NonNull String iban;
@Nullable String swiftCode;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\CreateSEPAExportFromPaySelectionCommand.java
| 1
|
请完成以下Java代码
|
public abstract class HistoricScopeInstanceEntityImpl
extends AbstractEntityNoRevision
implements HistoricScopeInstanceEntity, Serializable {
private static final long serialVersionUID = 1L;
protected String processInstanceId;
protected String processDefinitionId;
protected Date startTime;
protected Date endTime;
protected Long durationInMillis;
protected String deleteReason;
public void markEnded(String deleteReason) {
if (this.endTime == null) {
this.deleteReason = deleteReason;
this.endTime = Context.getProcessEngineConfiguration().getClock().getCurrentTime();
this.durationInMillis = endTime.getTime() - startTime.getTime();
}
}
// getters and setters ////////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDurationInMillis() {
return durationInMillis;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
|
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricScopeInstanceEntityImpl.java
| 1
|
请完成以下Spring Boot application配置
|
zuul:
routes:
static:
path: /hello.txt
url: http://127.0.0.1:8000/
stripPrefix: false
api:
path: /**
url: http:/
|
/127.0.0.1:8080
include-debug-header: true
server:
port: 8081
|
repos\SpringBoot-Labs-master\lab-07\lab-07-zuul\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
private int validateAgainstContextBPartner(@NonNull final I_C_BP_BankAccount bpBankAccount, final int contextBPartner_ID)
{
if (contextBPartner_ID <= 0)
{
// we have no BPartner-Context-Info, so we can't verify the bank account.
return 1;
}
if (contextBPartner_ID == bpBankAccount.getC_BPartner_ID())
{
// the BPartner from the account we looked up is the one from context
return 1;
}
final IQueryBL queryBL = Services.get(IQueryBL.class);
final boolean existsRelation = queryBL.createQueryBuilder(I_C_BP_Relation.class, bpBankAccount)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BP_Relation.COLUMNNAME_IsRemitTo, true)
.addEqualsFilter(I_C_BP_Relation.COLUMNNAME_C_BPartner_ID, contextBPartner_ID)
.addEqualsFilter(I_C_BP_Relation.COLUMNNAME_C_BPartnerRelation_ID, bpBankAccount.getC_BPartner_ID())
.create()
.anyMatch();
if (existsRelation)
{
return 2;
}
return 3;
}
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
final I_C_Invoice invoice = context.getSelectedModel(I_C_Invoice.class);
if (invoice == null)
{
return ProcessPreconditionsResolution.reject(Services.get(IMsgBL.class).getTranslatableMsgText(MSG_NO_INVOICE_SELECTED));
}
// only completed invoiced
if (!invoiceBL.isComplete(invoice))
{
return ProcessPreconditionsResolution.reject(Services.get(IMsgBL.class).getTranslatableMsgText(MSG_INVOICE_IS_NOT_COMPLETED));
}
return ProcessPreconditionsResolution.acceptIf(!invoice.isSOTrx());
}
public void createPaymentRequestFromTemplate(@NonNull final org.compiere.model.I_C_Invoice invoice, @Nullable final I_C_Payment_Request template)
|
{
if (template == null)
{
throw new AdempiereException(MSG_COULD_NOT_CREATE_PAYMENT_REQUEST).markAsUserValidationError();
}
//
// Get the selected invoice
if (paymentRequestDAO.hasPaymentRequests(invoice))
{
throw new AdempiereException(MSG_PAYMENT_REQUEST_FOR_INVOICE_ALREADY_EXISTS_EXCEPTION).markAsUserValidationError();
}
paymentRequestBL.createPaymentRequest(invoice, template);
}
public I_C_Payment_Request createPaymentRequestTemplate(final I_C_BP_BankAccount bankAccount, final BigDecimal amount, final PaymentString paymentString)
{
final IContextAware contextProvider = PlainContextAware.newOutOfTrx(Env.getCtx());
//
// Create it, but do not save it!
final I_C_Payment_Request paymentRequestTemplate = InterfaceWrapperHelper.newInstance(I_C_Payment_Request.class, contextProvider);
InterfaceWrapperHelper.setSaveDeleteDisabled(paymentRequestTemplate, true);
paymentRequestTemplate.setC_BP_BankAccount(bankAccount);
paymentRequestTemplate.setAmount(amount);
if (paymentString != null)
{
paymentRequestTemplate.setReference(paymentString.getReferenceNoComplete());
paymentRequestTemplate.setFullPaymentString(paymentString.getRawPaymentString());
}
return paymentRequestTemplate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\process\paymentdocumentform\PaymentStringProcessService.java
| 1
|
请完成以下Java代码
|
public String getMessage()
{
final StringBuilder retValue = new StringBuilder();
if (m_inserting)
{
retValue.append("+");
}
retValue.append(m_changed ? m_autoSave ? "*" : "?" : " ");
// current row
if (m_totalRows == 0)
{
retValue.append(m_currentRow);
}
else
{
retValue.append(m_currentRow + 1);
}
// of
retValue.append("/");
if (m_allLoaded)
{
retValue.append(m_totalRows);
}
else
{
retValue.append(m_loadedRows).append("->").append(m_totalRows);
}
//
return retValue.toString();
} // getMessage
/**
* Is Data Changed
*
* @return true if changed
*/
public boolean isChanged()
{
return m_changed;
} // isChanged
/**
* Is First Row - (zero based)
*
* @return true if first row
*/
public boolean isFirstRow()
{
if (m_totalRows == 0)
{
return true;
}
return m_currentRow == 0;
} // isFirstRow
/**
* Is Last Row - (zero based)
*
* @return true if last row
*/
public boolean isLastRow()
{
if (m_totalRows == 0)
{
return true;
}
return m_currentRow == m_totalRows - 1;
} // isLastRow
/**
* Set Changed Column
*
* @param col column
* @param columnName column name
*/
public void setChangedColumn(final int col, final String columnName)
{
m_changedColumn = col;
m_columnName = columnName;
} // setChangedColumn
/**
* Get Changed Column
*
* @return changed column
*/
public int getChangedColumn()
{
return m_changedColumn;
} // getChangedColumn
/**
* Get Column Name
*
* @return column name
*/
public String getColumnName()
{
return m_columnName;
} // getColumnName
/**
* Set Confirmed toggle
*
* @param confirmed confirmed
*/
public void setConfirmed(final boolean confirmed)
{
m_confirmed = confirmed;
} // setConfirmed
/**
* Is Confirmed (e.g. user has seen it)
|
*
* @return true if confirmed
*/
public boolean isConfirmed()
{
return m_confirmed;
} // isConfirmed
public void setCreated(final Integer createdBy, final Timestamp created)
{
this.createdBy = createdBy;
this.created = created;
}
public void setUpdated(final Integer updatedBy, final Timestamp updated)
{
this.updatedBy = updatedBy;
this.updated = updated;
}
public void setAdTableId(final int adTableId)
{
this.adTableId = adTableId;
this.recordId = null;
}
public void setSingleKeyRecord(final int adTableId, @NonNull final String keyColumnName, final int recordId)
{
setRecord(adTableId, ComposedRecordId.singleKey(keyColumnName, recordId));
}
public void setRecord(final int adTableId, @NonNull final ComposedRecordId recordId)
{
Check.assumeGreaterThanZero(adTableId, "adTableId");
this.adTableId = adTableId;
this.recordId = recordId;
}
public OptionalInt getSingleRecordId()
{
if (recordId == null)
{
return OptionalInt.empty();
}
return recordId.getSingleRecordId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\DataStatusEvent.java
| 1
|
请完成以下Java代码
|
private I_Carrier_ShipmentOrder_Item createItem(final DeliveryOrderItem item, final @NonNull DeliveryOrderParcelId deliveryOrderParcelId)
{
final I_Carrier_ShipmentOrder_Item po;
if (item.getId() != null)
{
po = InterfaceWrapperHelper.load(item.getId(), I_Carrier_ShipmentOrder_Item.class);
Check.assumeEquals(po.getCarrier_ShipmentOrder_Parcel_ID(), item.getId().getRepoId());
}
else
{
po = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Item.class);
po.setCarrier_ShipmentOrder_Parcel_ID(deliveryOrderParcelId.getRepoId());
}
po.setProductName(item.getProductName());
po.setArticleValue(item.getProductValue());
Check.assumeEquals(item.getTotalValue().getCurrencyId(), item.getUnitPrice().getCurrencyId());
po.setPrice(item.getUnitPrice().toBigDecimal());
po.setC_Currency_ID(item.getUnitPrice().getCurrencyId().getRepoId());
po.setTotalPrice(item.getTotalValue().toBigDecimal());
po.setTotalWeightInKg(item.getTotalWeightInKg());
po.setC_UOM_ID(item.getShippedQuantity().getUomId().getRepoId());
po.setQtyShipped(item.getShippedQuantity().toBigDecimal());
return po;
}
private I_Carrier_ShipmentOrder_Parcel createParcel(final @NonNull DeliveryOrderParcel parcelRequest, @NonNull final DeliveryOrderId deliveryOrderId)
{
final I_Carrier_ShipmentOrder_Parcel po;
if (parcelRequest.getId() != null)
{
po = InterfaceWrapperHelper.load(parcelRequest.getId(), I_Carrier_ShipmentOrder_Parcel.class);
|
Check.assumeEquals(po.getCarrier_ShipmentOrder_ID(), parcelRequest.getId().getRepoId());
}
else
{
po = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Parcel.class);
po.setCarrier_ShipmentOrder_ID(deliveryOrderId.getRepoId());
}
final PackageDimensions packageDimensions = parcelRequest.getPackageDimensions();
po.setHeightInCm(packageDimensions.getHeightInCM());
po.setLengthInCm(packageDimensions.getLengthInCM());
po.setWidthInCm(packageDimensions.getWidthInCM());
po.setWeightInKg(parcelRequest.getGrossWeightKg());
po.setM_Package_ID(PackageId.toRepoId(parcelRequest.getPackageId()));
return po;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\ShipmentOrderRepository.java
| 1
|
End of preview. Expand
in Data Studio
Spring Boot Code Completion Dataset
概述
这是一个专为 Spring Boot 框架代码补全任务设计的中文优先数据集。通过从 GitHub 上 90 个高质量开源 Spring Boot 项目中提取方法级、类级代码片段及配置文件,构建而成。数据集重点突出 Spring Boot 典型特征(注解驱动、依赖注入、配置绑定等),适用于参数高效微调(PEFT,如 LoRA/QLoRA)下的代码生成研究。
数据集统计
- 总样本数:81,085 条
- 训练集:64,868 条
- 验证集:8,108 条
- 测试集:8,109 条
- 优先级 2 样本数(含典型 Spring Boot 特征,如 @RestController、@Service、@Entity 等):19,740 条
- 优先级 2 占比:24.34%
数据格式(Alpaca 风格)
每条数据为 JSON 对象,包含以下字段:
{
"instruction": "请在Spring Boot框架中完成以下Java代码" 或 "请完成以下Java代码",
"input": "代码前缀(prefix)",
"output": "代码补全部分(completion)",
"source_file": "原始文件路径",
"priority": 1 或 2 // 2 表示含有 Spring Boot 典型特征
}
提取与清洗流程
从 GitHub 采集 90 个典型 Spring Boot 项目
使用 javalang 进行 AST 解析,提取方法/类级代码片段及 application 配置
多维度 Spring Boot 特征检测(注解、接口实现、包路径、类名后缀等)标记 priority
清洗:精确 MD5 去重 + SentenceTransformer + FAISS 相似度去重(阈值 0.95)+ priority 2 优先保护
长度过滤:input > 50 字符,output > 20 字符
划分:80% 训练 / 10% 验证 / 10% 测试
使用方式
Pythonfrom datasets import load_dataset
dataset = load_dataset("您的用户名/springboot-code-completion-dataset")
# 或指定子集
train = dataset["train"]
许可
本数据集仅限学术研究与非商业用途使用。原始代码来源于 GitHub 开源项目,请遵守各项目原许可协议。
引用
如果在论文中使用,请引用本仓库:
text@misc{唯一2026-springboot-dataset,
author = {唯一},
title = {Spring Boot Code Completion Dataset},
year = {2026},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/datasets/您的用户名/springboot-code-completion-dataset}}
}
欢迎反馈与合作!
- Downloads last month
- 12