instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void onMessage(String message, @PathParam(value = "userId") String userId) {
if(!"ping".equals(message) && !WebsocketConst.CMD_CHECK.equals(message)){
log.debug("【系统 WebSocket】收到客户端消息:" + message);
}else{
log.debug("【系统 WebSocket】收到客户端消息:" + message);
// 代码逻辑说明: 【issues/1161】前端websocket因心跳导致监听不起作用---
this.sendMessage(userId, "ping");
}
// //------------------------------------------------------------------------------
// JSONObject obj = new JSONObject();
// //业务类型
// obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_CHECK);
// //消息内容
// obj.put(WebsocketConst.MSG_TXT, "心跳响应");
// this.pushMessage(userId, obj.toJSONString());
// //------------------------------------------------------------------------------
}
/**
* 配置错误信息处理
*
* @param session
* @param t
*/
@OnError
public void onError(Session session, Throwable t) {
log.warn("【系统 WebSocket】消息出现错误");
t.printStackTrace();
}
//==========【系统 WebSocket接受、推送消息等方法 —— 具体服务节点推送ws消息】========================================================================================
//==========【采用redis发布订阅模式——推送消息】========================================================================================
/**
* 后台发送消息到redis
*
* @param message
*/
public void sendMessage(String message) {
//log.debug("【系统 WebSocket】广播消息:" + message);
BaseMap baseMap = new BaseMap();
baseMap.put("userId", "");
baseMap.put("message", message); | jeecgRedisClient.sendMessage(WebSocket.REDIS_TOPIC_NAME, baseMap);
}
/**
* 此为单点消息 redis
*
* @param userId
* @param message
*/
public void sendMessage(String userId, String message) {
BaseMap baseMap = new BaseMap();
baseMap.put("userId", userId);
baseMap.put("message", message);
jeecgRedisClient.sendMessage(WebSocket.REDIS_TOPIC_NAME, baseMap);
}
/**
* 此为单点消息(多人) redis
*
* @param userIds
* @param message
*/
public void sendMessage(String[] userIds, String message) {
for (String userId : userIds) {
sendMessage(userId, message);
}
}
//=======【采用redis发布订阅模式——推送消息】==========================================================================================
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\websocket\WebSocket.java | 1 |
请完成以下Java代码 | public void onC_DocType_ID(final I_SAP_GLJournal glJournal)
{
final IDocumentNoInfo documentNoInfo = documentNoBuilderFactory
.createPreliminaryDocumentNoBuilder()
.setNewDocType(DocTypeId.optionalOfRepoId(glJournal.getC_DocType_ID())
.map(docTypeBL::getById)
.orElse(null))
.setOldDocumentNo(glJournal.getDocumentNo())
.setDocumentModel(glJournal)
.buildOrNull();
if (documentNoInfo != null && documentNoInfo.isDocNoControlled())
{
glJournal.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
@CalloutMethod(columnNames = I_SAP_GLJournal.COLUMNNAME_DateDoc)
public void onDateDoc(final I_SAP_GLJournal glJournal)
{
final Timestamp dateDoc = glJournal.getDateDoc();
if (dateDoc == null)
{
return;
}
glJournal.setDateAcct(dateDoc);
}
@CalloutMethod(columnNames = {
I_SAP_GLJournal.COLUMNNAME_DateAcct,
I_SAP_GLJournal.COLUMNNAME_Acct_Currency_ID,
I_SAP_GLJournal.COLUMNNAME_C_Currency_ID,
I_SAP_GLJournal.COLUMNNAME_C_ConversionType_ID })
public void updateCurrencyRate(final I_SAP_GLJournal glJournal)
{
final BigDecimal currencyRate = computeCurrencyRate(glJournal);
if (currencyRate == null)
{
return;
}
glJournal.setCurrencyRate(currencyRate);
} | @Nullable
private BigDecimal computeCurrencyRate(final I_SAP_GLJournal glJournal)
{
//
// Extract data from source Journal
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID());
if (currencyId == null)
{
// not set yet
return null;
}
final CurrencyId acctCurrencyId = CurrencyId.ofRepoIdOrNull(glJournal.getAcct_Currency_ID());
if (acctCurrencyId == null)
{
return null;
}
final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID());
Instant dateAcct = TimeUtil.asInstant(glJournal.getDateAcct());
if (dateAcct == null)
{
dateAcct = SystemTime.asInstant();
}
final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID());
return currencyBL.getCurrencyRateIfExists(
currencyId,
acctCurrencyId,
dateAcct,
conversionTypeId,
adClientId,
adOrgId)
.map(CurrencyRate::getConversionRate)
.orElse(BigDecimal.ZERO);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\callout\SAP_GLJournal.java | 1 |
请完成以下Java代码 | public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
}
@Override | public String getParentDeploymentId() {
return parentDeploymentId;
}
@Override
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\DeploymentEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static BPRelationId ofRepoId(final int repoId)
{
return new BPRelationId(repoId);
}
@Nullable
public static BPRelationId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new BPRelationId(repoId) : null;
}
@Nullable
public static BPRelationId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new BPRelationId(repoId) : null;
}
public static Optional<BPRelationId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final BPRelationId bpartnerId)
{
return toRepoIdOr(bpartnerId, -1);
} | public static int toRepoIdOr(@Nullable final BPRelationId bpartnerId, final int defaultValue)
{
return bpartnerId != null ? bpartnerId.getRepoId() : defaultValue;
}
private BPRelationId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BP_Relation_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(final BPRelationId o1, final BPRelationId o2)
{
return Objects.equals(o1, o2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPRelationId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<JobEntity> findExpiredJobs(List<String> enabledCategories, Page page) {
Map<String, Object> params = new HashMap<>();
params.put("jobExecutionScope", jobServiceConfiguration.getJobExecutionScope());
Date now = jobServiceConfiguration.getClock().getCurrentTime();
params.put("now", now);
if (enabledCategories != null && enabledCategories.size() > 0) {
params.put("enabledCategories", enabledCategories);
}
ListQueryParameterObject listQueryParameterObject = new ListQueryParameterObject(params, page.getFirstResult(), page.getMaxResults());
listQueryParameterObject.setIgnoreOrderBy();
return getDbSqlSession().selectList("selectExpiredJobs", listQueryParameterObject);
}
@Override
@SuppressWarnings("unchecked")
public List<Job> findJobsByQueryCriteria(JobQueryImpl jobQuery) {
final String query = "selectJobByQueryCriteria";
return getDbSqlSession().selectList(query, jobQuery);
}
@Override
public long findJobCountByQueryCriteria(JobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectJobCountByQueryCriteria", jobQuery);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().directUpdate("updateJobTenantIdForDeployment", params);
}
@Override
public void bulkUpdateJobLockWithoutRevisionCheck(List<JobEntity> jobEntities, String lockOwner, Date lockExpirationTime) {
Map<String, Object> params = new HashMap<>(3);
params.put("lockOwner", lockOwner); | params.put("lockExpirationTime", lockExpirationTime);
bulkUpdateEntities("updateJobLocks", params, "jobs", jobEntities);
}
@Override
public void resetExpiredJob(String jobId) {
Map<String, Object> params = new HashMap<>(2);
params.put("id", jobId);
params.put("now", jobServiceConfiguration.getClock().getCurrentTime());
getDbSqlSession().directUpdate("resetExpiredJob", params);
}
@Override
public void deleteJobsByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
deleteCachedEntities(dbSqlSession, jobsByExecutionIdMatcher, executionId);
} else {
bulkDelete("deleteJobsByExecutionId", jobsByExecutionIdMatcher, executionId);
}
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisJobDataManager.java | 2 |
请完成以下Spring Boot application配置 | #datasource
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
# //------------- MYSQL DB --------------------
spring.datasource.url = jdbc:mysql://localhost:3306/employeecrud?useSSL=false&serverTimezone=UTC&AllowPublicKeyRetrieval=True
spring.datasource.username=root
spring.datasource.password=posilka2020
#The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.di | alect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.sql = DEBUG
logging.level.org.hibernate.type = TRACE
server.port=8080 | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-1.SpringBoot-React-CRUD\fullstack\backend\src\main\resources\application.properties | 2 |
请完成以下Java代码 | class HeaderWriterResponse extends OnCommittedResponseWrapper {
private final HttpServletRequest request;
HeaderWriterResponse(HttpServletRequest request, HttpServletResponse response) {
super(response);
this.request = request;
}
@Override
protected void onResponseCommitted() {
writeHeaders();
this.disableOnResponseCommitted();
}
protected void writeHeaders() {
if (isDisableOnResponseCommitted()) {
return;
}
HeaderWriterFilter.this.writeHeaders(this.request, getHttpResponse());
}
private HttpServletResponse getHttpResponse() {
return (HttpServletResponse) getResponse();
}
}
static class HeaderWriterRequest extends HttpServletRequestWrapper {
private final HeaderWriterResponse response;
HeaderWriterRequest(HttpServletRequest request, HeaderWriterResponse response) {
super(request);
this.response = response;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return new HeaderWriterRequestDispatcher(super.getRequestDispatcher(path), this.response);
}
} | static class HeaderWriterRequestDispatcher implements RequestDispatcher {
private final RequestDispatcher delegate;
private final HeaderWriterResponse response;
HeaderWriterRequestDispatcher(RequestDispatcher delegate, HeaderWriterResponse response) {
this.delegate = delegate;
this.response = response;
}
@Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.delegate.forward(request, response);
}
@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.response.onResponseCommitted();
this.delegate.include(request, response);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\HeaderWriterFilter.java | 1 |
请完成以下Java代码 | public Set<Map.Entry<String, PairFrequency>> getBiGram()
{
return triePair.entrySet();
}
/**
* 获取三阶共现
* @return
*/
public Set<Map.Entry<String, TriaFrequency>> getTriGram()
{
return trieTria.entrySet();
}
// public static void main(String[] args)
// {
// Occurrence occurrence = new Occurrence();
// occurrence.addAll("算法工程师\n" +
// "算法(Algorithm)是一系列解决问题的清晰指令,也就是说,能够对一定规范的输入,在有限时间内获得所要求的输出。如果一个算法有缺陷,或不适合于某个问题,执行这个算法将不会解决这个问题。不同的算法可能用不同的时间、空间或效率来完成同样的任务。一个算法的优劣可以用空间复杂度与时间复杂度来衡量。算法工程师就是利用算法处理事物的人。\n" +
// "\n" +
// "1职位简介\n" +
// "算法工程师是一个非常高端的职位;\n" +
// "专业要求:计算机、电子、通信、数学等相关专业;\n" +
// "学历要求:本科及其以上的学历,大多数是硕士学历及其以上;\n" + | // "语言要求:英语要求是熟练,基本上能阅读国外专业书刊;\n" +
// "必须掌握计算机相关知识,熟练使用仿真工具MATLAB等,必须会一门编程语言。\n" +
// "\n" +
// "2研究方向\n" +
// "视频算法工程师、图像处理算法工程师、音频算法工程师 通信基带算法工程师\n" +
// "\n" +
// "3目前国内外状况\n" +
// "目前国内从事算法研究的工程师不少,但是高级算法工程师却很少,是一个非常紧缺的专业工程师。算法工程师根据研究领域来分主要有音频/视频算法处理、图像技术方面的二维信息算法处理和通信物理层、雷达信号处理、生物医学信号处理等领域的一维信息算法处理。\n" +
// "在计算机音视频和图形图形图像技术等二维信息算法处理方面目前比较先进的视频处理算法:机器视觉成为此类算法研究的核心;另外还有2D转3D算法(2D-to-3D conversion),去隔行算法(de-interlacing),运动估计运动补偿算法(Motion estimation/Motion Compensation),去噪算法(Noise Reduction),缩放算法(scaling),锐化处理算法(Sharpness),超分辨率算法(Super Resolution),手势识别(gesture recognition),人脸识别(face recognition)。\n" +
// "在通信物理层等一维信息领域目前常用的算法:无线领域的RRM、RTT,传送领域的调制解调、信道均衡、信号检测、网络优化、信号分解等。\n" +
// "另外数据挖掘、互联网搜索算法也成为当今的热门方向。\n" +
// "算法工程师逐渐往人工智能方向发展。");
// occurrence.compute();
// System.out.println(occurrence);
// System.out.println(occurrence.getPhraseByScore());
// }
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\occurrence\Occurrence.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String sum(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2);
return Single.fromPublisher(httpClient.retrieve(req))
.blockingGet();
}
public String subtract(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2);
return Single.fromPublisher(httpClient.retrieve(req))
.blockingGet();
}
public String multiply(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2);
return Single.fromPublisher(httpClient.retrieve(req)) | .blockingGet();
}
public String divide(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2);
return Single.fromPublisher(httpClient.retrieve(req))
.blockingGet();
}
public String memory() {
HttpRequest<String> req = HttpRequest.GET("/math/memory");
return Single.fromPublisher(httpClient.retrieve(req))
.blockingGet();
}
} | repos\tutorials-master\microservices-modules\micronaut\src\main\java\com\baeldung\micronaut\vs\springboot\client\ArithmeticClientImpl.java | 2 |
请完成以下Java代码 | public void completeSetup() {
userDetailsService = applicationContext.getBean(CustomUserDetailsService.class);
}
@Bean
public UserDetailsManager users(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(encoder());
authenticationManagerBuilder.authenticationProvider(authenticationProvider());
AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
jdbcUserDetailsManager.setAuthenticationManager(authenticationManager);
return jdbcUserDetailsManager;
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring().requestMatchers("/resources/**");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.requestMatchers("/login").permitAll())
.formLogin(httpSecurityFormLoginConfigurer ->
httpSecurityFormLoginConfigurer.permitAll().successHandler(successHandler))
.csrf(AbstractHttpConfigurer::disable); | return http.build();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder(11);
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\SpringSecurityConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmailServer {
@Value("${email.smtp.server}")
private String server;
@Value("${email.smtp.port}")
private Integer port;
@Value("${email.smtp.username}")
private String username;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
} | public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
} | repos\spring-boot-master\spring-boot-externalize-config-2\src\main\java\com\mkyong\global\EmailServer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class GoogleOpenIdConnectConfig {
@Value("${google.clientId}")
private String clientId;
@Value("${google.clientSecret}")
private String clientSecret;
@Value("${google.accessTokenUri}")
private String accessTokenUri;
@Value("${google.userAuthorizationUri}")
private String userAuthorizationUri;
@Value("${google.redirectUri}")
private String redirectUri;
@Bean
public OAuth2ProtectedResourceDetails googleOpenId() {
final AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails(); | details.setClientId(clientId);
details.setClientSecret(clientSecret);
details.setAccessTokenUri(accessTokenUri);
details.setUserAuthorizationUri(userAuthorizationUri);
details.setScope(Arrays.asList("openid", "email"));
details.setPreEstablishedRedirectUri(redirectUri);
details.setUseCurrentUri(false);
return details;
}
@Bean
public OAuth2RestTemplate googleOpenIdTemplate(final OAuth2ClientContext clientContext) {
final OAuth2RestTemplate template = new OAuth2RestTemplate(googleOpenId(), clientContext);
return template;
}
} | repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\GoogleOpenIdConnectConfig.java | 2 |
请完成以下Java代码 | public Graph toGraph()
{
Graph graph = new Graph(getVertexesLineFirst());
for (int row = 0; row < vertexes.length - 1; ++row)
{
List<Vertex> vertexListFrom = vertexes[row];
for (Vertex from : vertexListFrom)
{
assert from.realWord.length() > 0 : "空节点会导致死循环!";
int toIndex = row + from.realWord.length();
for (Vertex to : vertexes[toIndex])
{
graph.connect(from.index, to.index, MathUtility.calculateWeight(from, to));
}
}
}
return graph;
}
@Override
public String toString()
{
// return "Graph{" +
// "vertexes=" + Arrays.toString(vertexes) +
// '}';
StringBuilder sb = new StringBuilder();
int line = 0;
for (List<Vertex> vertexList : vertexes)
{
sb.append(String.valueOf(line++) + ':' + vertexList.toString()).append("\n");
}
return sb.toString();
}
/**
* 将连续的ns节点合并为一个
*/
public void mergeContinuousNsIntoOne()
{
for (int row = 0; row < vertexes.length - 1; ++row)
{
List<Vertex> vertexListFrom = vertexes[row];
ListIterator<Vertex> listIteratorFrom = vertexListFrom.listIterator();
while (listIteratorFrom.hasNext())
{
Vertex from = listIteratorFrom.next();
if (from.getNature() == Nature.ns)
{
int toIndex = row + from.realWord.length();
ListIterator<Vertex> listIteratorTo = vertexes[toIndex].listIterator();
while (listIteratorTo.hasNext())
{
Vertex to = listIteratorTo.next();
if (to.getNature() == Nature.ns)
{
// 我们不能直接改,因为很多条线路在公用指针
// from.realWord += to.realWord;
logger.info("合并【" + from.realWord + "】和【" + to.realWord + "】");
listIteratorFrom.set(Vertex.newAddressInstance(from.realWord + to.realWord));
// listIteratorTo.remove();
break;
}
}
}
}
}
}
/**
* 清空词图 | */
public void clear()
{
for (List<Vertex> vertexList : vertexes)
{
vertexList.clear();
}
size = 0;
}
/**
* 清理from属性
*/
public void clean()
{
for (List<Vertex> vertexList : vertexes)
{
for (Vertex vertex : vertexList)
{
vertex.from = null;
}
}
}
/**
* 获取内部顶点表格,谨慎操作!
*
* @return
*/
public LinkedList<Vertex>[] getVertexes()
{
return vertexes;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\WordNet.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isRouteFilterCacheEnabled() {
return routeFilterCacheEnabled;
}
public void setRouteFilterCacheEnabled(boolean routeFilterCacheEnabled) {
this.routeFilterCacheEnabled = routeFilterCacheEnabled;
}
public List<RouteDefinition> getRoutes() {
return routes;
}
public void setRoutes(List<RouteDefinition> routes) {
this.routes = routes;
if (routes != null && routes.size() > 0 && logger.isDebugEnabled()) {
logger.debug("Routes supplied from Gateway Properties: " + routes);
}
}
public List<FilterDefinition> getDefaultFilters() {
return defaultFilters;
}
public void setDefaultFilters(List<FilterDefinition> defaultFilters) {
this.defaultFilters = defaultFilters;
}
public List<MediaType> getStreamingMediaTypes() {
return streamingMediaTypes;
}
public void setStreamingMediaTypes(List<MediaType> streamingMediaTypes) {
this.streamingMediaTypes = streamingMediaTypes;
}
public boolean isFailOnRouteDefinitionError() { | return failOnRouteDefinitionError;
}
public void setFailOnRouteDefinitionError(boolean failOnRouteDefinitionError) {
this.failOnRouteDefinitionError = failOnRouteDefinitionError;
}
public String getTrustedProxies() {
return trustedProxies;
}
public void setTrustedProxies(String trustedProxies) {
this.trustedProxies = trustedProxies;
}
@Override
public String toString() {
return new ToStringCreator(this).append("routes", routes)
.append("defaultFilters", defaultFilters)
.append("streamingMediaTypes", streamingMediaTypes)
.append("failOnRouteDefinitionError", failOnRouteDefinitionError)
.append("routeFilterCacheEnabled", routeFilterCacheEnabled)
.append("trustedProxies", trustedProxies)
.toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayProperties.java | 2 |
请完成以下Java代码 | public class OmsOrderSetting implements Serializable {
private Long id;
@ApiModelProperty(value = "秒杀订单超时关闭时间(分)")
private Integer flashOrderOvertime;
@ApiModelProperty(value = "正常订单超时时间(分)")
private Integer normalOrderOvertime;
@ApiModelProperty(value = "发货后自动确认收货时间(天)")
private Integer confirmOvertime;
@ApiModelProperty(value = "自动完成交易时间,不能申请售后(天)")
private Integer finishOvertime;
@ApiModelProperty(value = "订单完成后自动好评时间(天)")
private Integer commentOvertime;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getFlashOrderOvertime() {
return flashOrderOvertime;
}
public void setFlashOrderOvertime(Integer flashOrderOvertime) {
this.flashOrderOvertime = flashOrderOvertime;
}
public Integer getNormalOrderOvertime() {
return normalOrderOvertime;
}
public void setNormalOrderOvertime(Integer normalOrderOvertime) {
this.normalOrderOvertime = normalOrderOvertime;
}
public Integer getConfirmOvertime() {
return confirmOvertime;
}
public void setConfirmOvertime(Integer confirmOvertime) {
this.confirmOvertime = confirmOvertime;
}
public Integer getFinishOvertime() {
return finishOvertime;
} | public void setFinishOvertime(Integer finishOvertime) {
this.finishOvertime = finishOvertime;
}
public Integer getCommentOvertime() {
return commentOvertime;
}
public void setCommentOvertime(Integer commentOvertime) {
this.commentOvertime = commentOvertime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", flashOrderOvertime=").append(flashOrderOvertime);
sb.append(", normalOrderOvertime=").append(normalOrderOvertime);
sb.append(", confirmOvertime=").append(confirmOvertime);
sb.append(", finishOvertime=").append(finishOvertime);
sb.append(", commentOvertime=").append(commentOvertime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderSetting.java | 1 |
请完成以下Java代码 | public void setSKU (java.lang.String SKU)
{
set_Value (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
@Override
public java.lang.String getSKU ()
{
return (java.lang.String)get_Value(COLUMNNAME_SKU);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public void setUPC (java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
@Override
public org.compiere.model.I_C_ElementValue getUser1() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
/** Set Nutzer 1.
@param User1_ID
User defined list element #1
*/
@Override
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get Nutzer 1.
@return User defined list element #1
*/
@Override
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); | if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ElementValue getUser2() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
/** Set Nutzer 2.
@param User2_ID
User defined list element #2
*/
@Override
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get Nutzer 2.
@return User defined list element #2
*/
@Override
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_GLJournal.java | 1 |
请完成以下Java代码 | public int bosTag()
{
return tagSet.size();
}
public TagSet tagSet;
/**
* 是否允许新增特征
*/
public boolean mutable;
public FeatureMap(TagSet tagSet)
{
this(tagSet, false);
}
public FeatureMap(TagSet tagSet, boolean mutable)
{
this.tagSet = tagSet;
this.mutable = mutable;
}
public abstract Set<Map.Entry<String, Integer>> entrySet();
public FeatureMap(boolean mutable)
{
this.mutable = mutable;
}
public FeatureMap()
{
this(false);
}
@Override
public void save(DataOutputStream out) throws IOException
{
tagSet.save(out);
out.writeInt(size());
for (Map.Entry<String, Integer> entry : entrySet()) | {
out.writeUTF(entry.getKey());
}
}
@Override
public boolean load(ByteArray byteArray)
{
loadTagSet(byteArray);
int size = byteArray.nextInt();
for (int i = 0; i < size; i++)
{
idOf(byteArray.nextUTF());
}
return true;
}
protected final void loadTagSet(ByteArray byteArray)
{
TaskType type = TaskType.values()[byteArray.nextInt()];
switch (type)
{
case CWS:
tagSet = new CWSTagSet();
break;
case POS:
tagSet = new POSTagSet();
break;
case NER:
tagSet = new NERTagSet();
break;
case CLASSIFICATION:
tagSet = new TagSet(TaskType.CLASSIFICATION);
break;
}
tagSet.load(byteArray);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\FeatureMap.java | 1 |
请完成以下Java代码 | private static String getSmsSignName(DySmsEnum dySmsEnum) {
JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class);
String signName = dySmsEnum.getSignName();
if (StringUtils.isNotEmpty(baseConfig.getSignature())) {
logger.debug("yml中读取签名名称: {}", baseConfig.getSignature());
signName = baseConfig.getSignature();
}
return signName;
}
/**
* 获取短信模板ID
*
* @param dySmsEnum 腾讯云对象
*/
private static String getSmsTemplateId(DySmsEnum dySmsEnum) {
JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class);
String templateCode = dySmsEnum.getTemplateCode();
if (StringUtils.isNotEmpty(baseConfig.getSignature())) {
Map<String, String> smsTemplate = baseConfig.getTemplateCode();
if (smsTemplate.containsKey(templateCode) &&
StringUtils.isNotEmpty(smsTemplate.get(templateCode))) {
templateCode = smsTemplate.get(templateCode);
logger.debug("yml中读取短信模板ID: {}", templateCode);
}
}
return templateCode; | }
/**
* 从JSONObject中提取模板参数(按原始顺序)
*
* @param templateParamJson 模板参数
*/
private static String[] extractTemplateParams(JSONObject templateParamJson) {
if (templateParamJson == null || templateParamJson.isEmpty()) {
return new String[0];
}
List<String> params = new ArrayList<>();
for (String key : templateParamJson.keySet()) {
Object value = templateParamJson.get(key);
if (value != null) {
params.add(value.toString());
} else {
// 处理null值
params.add("");
}
}
logger.debug("提取模板参数: {}", params);
return params.toArray(new String[0]);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\TencentSms.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:sqlite:dev.db
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.datasource.username=
spring.datasource.password=
spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true
image.default=https://static.productionready.io/images/smiley-cyrus.jpg
jwt.secret=nRvyYC4soFxBdZ-F-5Nnzz5USXstR1YylsTd-mA0aKtI9HUlriGrtkf-TiuDapkLiUCogO3JOK7kwZisrHp6wA
jwt.sessionTime=86400
mybatis.configuration.cache-enabled=true
mybatis.configuration.default-statement-timeout=3000
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.use-generated-key | s=true
mybatis.type-handlers-package=io.spring.infrastructure.mybatis
mybatis.mapper-locations=mapper/*.xml
logging.level.io.spring.infrastructure.mybatis.readservice.ArticleReadService=DEBUG
logging.level.io.spring.infrastructure.mybatis.mapper=DEBUG | repos\spring-boot-realworld-example-app-master\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public ImmutableSet<String> getFieldNames()
{
return map.keySet();
}
public Comparable<?> getAsComparable(
@NonNull final String fieldName,
@NonNull final JSONOptions jsonOpts)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return null;
}
else if (valueObj instanceof ITranslatableString)
{
return ((ITranslatableString)valueObj).translate(jsonOpts.getAdLanguage());
}
else if (valueObj instanceof Comparable)
{
return (Comparable<?>)valueObj;
}
else
{
return valueObj.toString();
}
}
public Object getAsJsonObject(
@NonNull final String fieldName,
@NonNull final JSONOptions jsonOpts)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return null;
}
else if (valueObj instanceof ITranslatableString)
{
return ((ITranslatableString)valueObj).translate(jsonOpts.getAdLanguage());
}
else
{
return Values.valueToJsonObject(valueObj, jsonOpts);
}
}
public int getAsInt(@NonNull final String fieldName, final int defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.toNullIfInstance(valueObj) == null)
{
return defaultValueIfNotFoundOrError;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else if (valueObj instanceof LookupValue)
{
return ((LookupValue)valueObj).getIdAsInt();
}
else if (valueObj instanceof JSONLookupValue)
{
return ((JSONLookupValue)valueObj).getKeyAsInt();
} | else
{
return NumberUtils.asInt(valueObj, defaultValueIfNotFoundOrError);
}
}
public BigDecimal getAsBigDecimal(@NonNull final String fieldName, final BigDecimal defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return defaultValueIfNotFoundOrError;
}
else
{
return NumberUtils.asBigDecimal(valueObj, defaultValueIfNotFoundOrError);
}
}
public boolean getAsBoolean(@NonNull final String fieldName, final boolean defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
return StringUtils.toBoolean(valueObj, defaultValueIfNotFoundOrError);
}
public boolean isEmpty(@NonNull final String fieldName)
{
final Object valueObj = map.get(fieldName);
return valueObj == null || JSONNullValue.isNull(valueObj) || valueObj.toString().isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowFieldNameAndJsonValues.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoController {
@Autowired
private UserServiceFeignClient userClient;
@GetMapping("/get")
public String get(@RequestParam("id") Integer id) {
// 请求
UserGetRequest request = new UserGetRequest();
request.setId(id);
// 执行 Web Services 请求
UserGetResponse response = userClient.getUser(request);
// 响应
return response.getName();
} | @GetMapping("/create") // 为了方便测试,实际使用 @PostMapping
public Integer create(@RequestParam("name") String name,
@RequestParam("gender") Integer gender) {
// 请求
UserCreateRequest request = new UserCreateRequest();
request.setName(name);
request.setGender(gender);
// 执行 Web Services 请求
UserCreateResponse response = userClient.createUser(request);
// 响应
return response.getId();
}
} | repos\SpringBoot-Labs-master\lab-65\lab-65-ws-feign-client\src\main\java\cn\iocoder\springboot\lab65\demo\controller\DemoController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ShipmentScheduleAndJobScheduleId implements Comparable<ShipmentScheduleAndJobScheduleId>
{
@NonNull ShipmentScheduleId shipmentScheduleId;
@Nullable PickingJobScheduleId jobScheduleId;
@Nullable
public static ShipmentScheduleAndJobScheduleId ofRepoIdsOrNull(final int shipmentScheduleRepoId, final int pickingJobScheduleRepoId)
{
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(shipmentScheduleRepoId);
if (shipmentScheduleId == null)
{
return null;
}
return of(shipmentScheduleId, PickingJobScheduleId.ofRepoIdOrNull(pickingJobScheduleRepoId));
}
@NonNull
public static ShipmentScheduleAndJobScheduleId ofRepoIds(final int shipmentScheduleRepoId, final int pickingJobScheduleRepoId)
{
final ShipmentScheduleAndJobScheduleId id = ofRepoIdsOrNull(shipmentScheduleRepoId, pickingJobScheduleRepoId);
if (id == null)
{
throw new AdempiereException("No " + ShipmentScheduleAndJobScheduleId.class + " found for shipmentScheduleRepoId=" + shipmentScheduleRepoId + " and pickingJobScheduleRepoId=" + pickingJobScheduleRepoId);
}
return id;
}
public static ShipmentScheduleAndJobScheduleId ofShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return of(shipmentScheduleId, null);
}
@Override
@Deprecated
public String toString() {return toJsonString();}
@JsonValue
public String toJsonString()
{
return jobScheduleId != null
? shipmentScheduleId.getRepoId() + "_" + jobScheduleId.getRepoId()
: "" + shipmentScheduleId.getRepoId();
}
@JsonCreator
public static ShipmentScheduleAndJobScheduleId ofJsonString(@NonNull final String json)
{ | try
{
final int idx = json.indexOf("_");
if (idx > 0)
{
return of(
ShipmentScheduleId.ofRepoId(Integer.parseInt(json.substring(0, idx))),
PickingJobScheduleId.ofRepoId(Integer.parseInt(json.substring(idx + 1)))
);
}
else
{
return of(
ShipmentScheduleId.ofRepoId(Integer.parseInt(json)),
null
);
}
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
public TableRecordReference toTableRecordReference()
{
return jobScheduleId != null ? jobScheduleId.toTableRecordReference() : shipmentScheduleId.toTableRecordReference();
}
public boolean isJobSchedule() {return jobScheduleId != null;}
@Override
public int compareTo(@NotNull final ShipmentScheduleAndJobScheduleId other)
{
return this.toJsonString().compareTo(other.toJsonString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\ShipmentScheduleAndJobScheduleId.java | 2 |
请完成以下Java代码 | public class Alphabet implements ICacheAble
{
ITrie<Integer> trie;
String[] idToLabelMap;
public Alphabet()
{
trie = new DoubleArrayTrie<Integer>();
}
/**
* id转label
* @param id
* @return
*/
public String labelOf(int id)
{
return idToLabelMap[id];
}
public int build(TreeMap<String, Integer> keyValueMap)
{
idToLabelMap = new String[keyValueMap.size()];
for (Map.Entry<String, Integer> entry : keyValueMap.entrySet())
{
idToLabelMap[entry.getValue()] = entry.getKey();
}
return trie.build(keyValueMap);
}
/**
* label转id
* @param label
* @return
*/
public Integer idOf(char[] label)
{
return trie.get(label);
}
/**
* label转id
* @param label
* @return
*/ | public Integer idOf(String label)
{
return trie.get(label);
}
/**
* 字母表大小
* @return
*/
public int size()
{
return trie.size();
}
public void save(DataOutputStream out) throws Exception
{
out.writeInt(idToLabelMap.length);
for (String value : idToLabelMap)
{
TextUtility.writeString(value, out);
}
}
public boolean load(ByteArray byteArray)
{
idToLabelMap = new String[byteArray.nextInt()];
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
for (int i = 0; i < idToLabelMap.length; i++)
{
idToLabelMap[i] = byteArray.nextString();
map.put(idToLabelMap[i], i);
}
return trie.build(map) == 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Alphabet.java | 1 |
请完成以下Java代码 | public Map<String, Map<String, Link>> links(ServerWebExchange exchange) {
String requestUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI())
.replaceQuery(null)
.toUriString();
Map<String, Link> links = WebFluxEndpointHandlerMapping.this.linksResolver.resolveLinks(requestUri);
return OperationResponseBody.of(Collections.singletonMap("_links", links));
}
@Override
public String toString() {
return "Actuator root web endpoint";
}
} | static class WebFluxEndpointHandlerMappingRuntimeHints implements RuntimeHintsRegistrar {
private final ReflectiveRuntimeHintsRegistrar reflectiveRegistrar = new ReflectiveRuntimeHintsRegistrar();
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.reflectiveRegistrar.registerRuntimeHints(hints, WebFluxLinksHandler.class);
this.bindingRegistrar.registerReflectionHints(hints.reflection(), Link.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\endpoint\web\WebFluxEndpointHandlerMapping.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ImmutableSet<DDOrderMoveScheduleId> getScheduleIds(final DistributionJob job)
{
return job.streamSteps()
.filter(this::isStepEligible)
.map(DistributionJobStep::getScheduleId)
.collect(ImmutableSet.toImmutableSet());
}
private boolean isStepEligible(final DistributionJobStep step)
{
if (onlyStepId != null && !DistributionJobStepId.equals(step.getId(), onlyStepId))
{
return false;
}
if (!step.isInTransit())
{
if (onlyStepId != null)
{
throw new AdempiereException("Step " + onlyStepId + " is not in transit"); // shall not happen
}
return false;
}
//noinspection RedundantIfStatement
if (inTransitLocatorId != null && !LocatorId.equals(step.getInTransitLocatorId(), inTransitLocatorId))
{
return false;
}
return true;
}
@Nullable
private LocatorId getDropToLocatorId()
{
if (dropToQRCode == null)
{
return null;
}
LocatorId dropToLocatorId = this._dropToLocatorId;
if (dropToLocatorId == null)
{
dropToLocatorId = this._dropToLocatorId = warehouseService.resolveLocator(dropToQRCode).getLocatorId();
}
return dropToLocatorId;
}
private ImmutableList<DistributionJob> updateJobsFromSchedules(final List<DistributionJob> jobs, final ImmutableList<DDOrderMoveSchedule> schedules)
{
final ImmutableMap<DistributionJobStepId, DDOrderMoveSchedule> schedulesByStepId = Maps.uniqueIndex(schedules, schedule -> DistributionJobStepId.ofScheduleId(schedule.getId()));
return jobs.stream()
.map(job -> updateJob(job, schedulesByStepId))
.collect(ImmutableList.toImmutableList());
} | private DistributionJob updateJob(final DistributionJob job, final ImmutableMap<DistributionJobStepId, DDOrderMoveSchedule> schedulesByStepId)
{
return job.withChangedSteps(step -> {
final DDOrderMoveSchedule schedule = schedulesByStepId.get(step.getId());
return schedule != null
? DistributionJobLoader.toDistributionJobStep(schedule, loadingSupportServices)
: step;
});
}
private List<DistributionJob> tryCompleteJobsIfFullyMoved(@NonNull final List<DistributionJob> jobs)
{
return jobs.stream()
.map(this::completeJobIfFullyMoved)
.collect(ImmutableList.toImmutableList());
}
private DistributionJob completeJobIfFullyMoved(@NonNull final DistributionJob job)
{
if (!job.isFullyMoved())
{
return job;
}
return distributionJobService.complete(job);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\commands\drop_to\DistributionJobDropToCommand.java | 2 |
请完成以下Java代码 | public void add(final CacheKey ignored, @NonNull final DataItem dataItem)
{
add(dataItem);
}
public void add(@NonNull final DataItem dataItem)
{
final DataItemId dataItemId = extractDataItemId(dataItem);
final Collection<CacheKey> cacheKeys = extractCacheKeys(dataItem);
final Collection<TableRecordReference> recordRefs = extractRecordRefs(dataItem);
add(dataItemId, cacheKeys, recordRefs);
}
private synchronized void add(
@NonNull final DataItemId dataItemId,
@NonNull final Collection<CacheKey> cacheKeys,
@NonNull final Collection<TableRecordReference> recordRefs)
{
logger.debug("Adding to index: {} -> {}", dataItemId, cacheKeys);
_dataItemId_to_cacheKey.putAll(dataItemId, cacheKeys);
logger.debug("Adding to index: {} -> {}", recordRefs, dataItemId);
recordRefs.forEach(recordRef -> _recordRef_to_dateItemId.put(recordRef, dataItemId));
}
public void remove(final CacheKey cacheKey, final DataItem dataItem)
{ | final DataItemId dataItemId = extractDataItemId(dataItem);
final Collection<TableRecordReference> recordRefs = extractRecordRefs(dataItem);
removeDataItemId(dataItemId, cacheKey, recordRefs);
}
private synchronized void removeDataItemId(
final DataItemId dataItemId,
final CacheKey cacheKey,
final Collection<TableRecordReference> recordRefs)
{
logger.debug("Removing pair from index: {}, {}", dataItemId, cacheKey);
_dataItemId_to_cacheKey.remove(dataItemId, cacheKey);
logger.debug("Removing pairs from index: {}, {}", recordRefs, dataItemId);
recordRefs.forEach(recordRef -> _recordRef_to_dateItemId.remove(recordRef, dataItemId));
}
@Override
public boolean isResetAll(final TableRecordReference recordRef)
{
return adapter.isResetAll(recordRef);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheIndex.java | 1 |
请完成以下Java代码 | public class AtomLink {
private String method;
private String href;
private String rel;
public AtomLink() {
}
public AtomLink(String rel, String href, String method) {
this.href = href;
this.rel = rel;
this.method = method;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getRel() { | return rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AtomLink.java | 1 |
请完成以下Java代码 | class UPCProductBarcodeFilterDataFactory implements ProductBarcodeFilterDataFactory
{
@Override
public Optional<ProductBarcodeFilterData> createData(
final @NonNull ProductBarcodeFilterServicesFacade services,
final @NonNull String barcodeParam,
final @NonNull ClientId clientId)
{
Check.assumeNotEmpty(barcodeParam, "barcode not empty");
final String barcodeNorm = barcodeParam.trim();
final ImmutableList<ResolvedScannedProductCode> ediProductLookupList = services.getEDIProductLookupByUPC(barcodeNorm);
final ProductId productId = services.getProductIdByBarcode(barcodeNorm, clientId).orElse(null);
final SqlAndParams sqlWhereClause = createSqlWhereClause(services, ediProductLookupList, productId).orElse(null);
if (sqlWhereClause == null)
{
return Optional.empty();
}
return Optional.of(ProductBarcodeFilterData.builder()
.barcode(barcodeNorm)
.sqlWhereClause(sqlWhereClause)
.build());
}
private static Optional<SqlAndParams> createSqlWhereClause(
@NonNull final ProductBarcodeFilterServicesFacade services,
@NonNull final ImmutableList<ResolvedScannedProductCode> ediProductLookupList,
@Nullable final ProductId productId)
{
if (productId == null && ediProductLookupList.isEmpty())
{
return Optional.empty();
}
final ICompositeQueryFilter<I_M_Packageable_V> resultFilter = services.createCompositeQueryFilter()
.setJoinOr(); | if (!ediProductLookupList.isEmpty())
{
for (final ResolvedScannedProductCode ediProductLookup : ediProductLookupList)
{
final ICompositeQueryFilter<I_M_Packageable_V> filter = resultFilter.addCompositeQueryFilter()
.setJoinAnd()
.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, ediProductLookup.getProductId());
if (ediProductLookup.getBpartnerId() != null)
{
filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, ediProductLookup.getBpartnerId());
}
}
}
if (productId != null)
{
resultFilter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productId);
}
return Optional.of(services.toSqlAndParams(resultFilter));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\UPCProductBarcodeFilterDataFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = 2978710889397403536L;
private ApiKeyAuthRequest apiKeyAuthRequest;
private SecurityUser securityUser;
public ApiKeyAuthenticationToken(ApiKeyAuthRequest apiKeyAuthRequest) {
super(null);
this.apiKeyAuthRequest = apiKeyAuthRequest;
setAuthenticated(false);
}
public ApiKeyAuthenticationToken(SecurityUser securityUser) {
super(securityUser.getAuthorities());
this.eraseCredentials();
this.securityUser = securityUser;
super.setAuthenticated(true); | }
@Override
public Object getCredentials() {
return apiKeyAuthRequest;
}
@Override
public Object getPrincipal() {
return this.securityUser;
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
this.apiKeyAuthRequest = null;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\pat\ApiKeyAuthenticationToken.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RpMicroSubmitRecordServiceImpl implements RpMicroSubmitRecordService {
@Autowired
private RpMicroSubmitRecordDao rpMicroSubmitRecordDao;
@Autowired
private RpTradePaymentRecordDao rpTradePaymentRecordDao;
private static final Logger LOG = LoggerFactory.getLogger(RpMicroSubmitRecordServiceImpl.class);
@Override
public PageBean listPage(PageParam pageParam, RpMicroSubmitRecord rpMicroSubmitRecord) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("storeName", rpMicroSubmitRecord.getStoreName());
paramMap.put("businessCode", rpMicroSubmitRecord.getBusinessCode());
paramMap.put("dCardName", rpMicroSubmitRecord.getIdCardName());
return rpMicroSubmitRecordDao.listPage(pageParam, paramMap);
}
@Override
public void saveData(RpMicroSubmitRecord rpMicroSubmitRecord) {
rpMicroSubmitRecord.setEditTime(new Date());
if (StringUtil.isEmpty(rpMicroSubmitRecord.getStatus())) {
rpMicroSubmitRecord.setStatus(PublicEnum.YES.name());
}
rpMicroSubmitRecordDao.insert(rpMicroSubmitRecord);
} | @Override
public Map<String, Object> microSubmit(RpMicroSubmitRecord rpMicroSubmitRecord) {
rpMicroSubmitRecord.setBusinessCode(StringUtil.get32UUID());
rpMicroSubmitRecord.setIdCardValidTime("[\"" + rpMicroSubmitRecord.getIdCardValidTimeBegin() + "\",\"" + rpMicroSubmitRecord.getIdCardValidTimeEnd() + "\"]");
Map<String, Object> returnMap = WeiXinMicroUtils.microSubmit(rpMicroSubmitRecord);
rpMicroSubmitRecord.setStoreStreet(WxCityNo.getCityNameByNo(rpMicroSubmitRecord.getStoreAddressCode()) + ":" + rpMicroSubmitRecord.getStoreStreet());
if ("SUCCESS".equals(returnMap.get("result_code"))) {
saveData(rpMicroSubmitRecord);
}
return returnMap;
}
@Override
public Map<String, Object> microQuery(String businessCode) {
Map<String, Object> returnMap = WeiXinMicroUtils.microQuery(businessCode);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("businessCode", businessCode);
RpMicroSubmitRecord rpMicroSubmitRecord = rpMicroSubmitRecordDao.getBy(paramMap);
if (StringUtil.isNotNull(returnMap.get("sub_mch_id")) && StringUtil.isEmpty(rpMicroSubmitRecord.getSubMchId())) {
rpMicroSubmitRecord.setSubMchId(String.valueOf(returnMap.get("sub_mch_id")));
rpMicroSubmitRecordDao.update(rpMicroSubmitRecord);
}
return returnMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\service\impl\RpMicroSubmitRecordServiceImpl.java | 2 |
请完成以下Java代码 | final ExecutorService getExecutor() {
return this.executor;
}
}
/**
* Client configuration for remote update and restarts.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(name = "spring.devtools.remote.restart.enabled", matchIfMissing = true)
static class RemoteRestartClientConfiguration {
private final DevToolsProperties properties;
RemoteRestartClientConfiguration(DevToolsProperties properties) {
this.properties = properties;
}
@Bean
ClassPathFileSystemWatcher classPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory,
ClassPathRestartStrategy classPathRestartStrategy) {
DefaultRestartInitializer restartInitializer = new DefaultRestartInitializer();
URL[] urls = restartInitializer.getInitialUrls(Thread.currentThread());
if (urls == null) {
urls = new URL[0];
}
return new ClassPathFileSystemWatcher(fileSystemWatcherFactory, classPathRestartStrategy, urls);
}
@Bean
FileSystemWatcherFactory getFileSystemWatcherFactory() {
return this::newFileSystemWatcher;
} | private FileSystemWatcher newFileSystemWatcher() {
Restart restartProperties = this.properties.getRestart();
FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(),
restartProperties.getQuietPeriod());
String triggerFile = restartProperties.getTriggerFile();
if (StringUtils.hasLength(triggerFile)) {
watcher.setTriggerFilter(new TriggerFileFilter(triggerFile));
}
return watcher;
}
@Bean
ClassPathRestartStrategy classPathRestartStrategy() {
return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude());
}
@Bean
ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory,
@Value("${remoteUrl}") String remoteUrl) {
String url = remoteUrl + this.properties.getRemote().getContextPath() + "/restart";
return new ClassPathChangeUploader(url, requestFactory);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\RemoteClientConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HCURR1 {
@XmlElement(name = "DOCUMENTID", required = true)
protected String documentid;
@XmlElement(name = "CURRENCYQUAL", required = true)
protected String currencyqual;
@XmlElement(name = "CURRENCYCODE", required = true)
protected String currencycode;
@XmlElement(name = "CURRENCYEXRATE")
protected String currencyexrate;
/**
* Gets the value of the documentid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the currencyqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCYQUAL() {
return currencyqual;
}
/**
* Sets the value of the currencyqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/ | public void setCURRENCYQUAL(String value) {
this.currencyqual = value;
}
/**
* Gets the value of the currencycode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCYCODE() {
return currencycode;
}
/**
* Sets the value of the currencycode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCYCODE(String value) {
this.currencycode = value;
}
/**
* Gets the value of the currencyexrate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCYEXRATE() {
return currencyexrate;
}
/**
* Sets the value of the currencyexrate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCYEXRATE(String value) {
this.currencyexrate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HCURR1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class RelatedDocumentsTargetWindow
{
public static RelatedDocumentsTargetWindow ofAdWindowId(@NonNull final AdWindowId adWindowId)
{
return new RelatedDocumentsTargetWindow(adWindowId, null);
}
public static RelatedDocumentsTargetWindow ofAdWindowIdAndCategory(
@NonNull final AdWindowId adWindowId,
@NonNull final ReferenceListAwareEnum category)
{
return new RelatedDocumentsTargetWindow(adWindowId, category.getCode());
}
public static RelatedDocumentsTargetWindow ofAdWindowIdAndCategory(
@NonNull final AdWindowId adWindowId, | @Nullable final String category)
{
return new RelatedDocumentsTargetWindow(adWindowId, category);
}
AdWindowId adWindowId;
String category;
private RelatedDocumentsTargetWindow(
@NonNull final AdWindowId adWindowId,
@Nullable final String category)
{
this.adWindowId = adWindowId;
this.category = StringUtils.trimBlankToNull(category);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\RelatedDocumentsTargetWindow.java | 2 |
请完成以下Java代码 | public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public boolean isIsFirstPage() {
return isFirstPage;
}
public void setIsFirstPage(boolean isFirstPage) {
this.isFirstPage = isFirstPage;
}
public boolean isIsLastPage() { | return isLastPage;
}
public void setIsLastPage(boolean isLastPage) {
this.isLastPage = isLastPage;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PageInfo{");
sb.append("pageNum=").append(pageNum);
sb.append(", pageSize=").append(pageSize);
sb.append(", total=").append(total);
sb.append(", pages=").append(pages);
sb.append(", list=").append(list);
sb.append(", isFirstPage=").append(isFirstPage);
sb.append(", isLastPage=").append(isLastPage);
sb.append(", navigatepageNums=");
sb.append('}');
return sb.toString();
}
} | repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\page\PageInfo.java | 1 |
请完成以下Java代码 | public class JsonAlbertaCareGiver
{
@ApiModelProperty(position = 10)
private String caregiverIdentifier;
@ApiModelProperty(position = 20)
@Nullable
private String type;
@ApiModelProperty(hidden = true)
private boolean typeSet;
@ApiModelProperty(position = 30)
@Nullable
private Boolean isLegalCarer;
@ApiModelProperty(hidden = true)
private boolean legalCarerSet; | public void setCaregiverIdentifier(@NonNull final String caregiverIdentifier)
{
this.caregiverIdentifier = caregiverIdentifier;
}
public void setType(@Nullable final String type)
{
this.type = type;
this.typeSet = true;
}
public void setIsLegalCarer(@Nullable final Boolean isLegalCarer)
{
this.isLegalCarer = isLegalCarer;
this.legalCarerSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\alberta\JsonAlbertaCareGiver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDocumentNo (final java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setIsClosed (final boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, IsClosed);
}
@Override
public boolean isClosed() | {
return get_ValueAsBoolean(COLUMNNAME_IsClosed);
}
@Override
public void setOpeningNote (final @Nullable java.lang.String OpeningNote)
{
set_Value (COLUMNNAME_OpeningNote, OpeningNote);
}
@Override
public java.lang.String getOpeningNote()
{
return get_ValueAsString(COLUMNNAME_OpeningNote);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Journal.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
public Set<Book> getBooks() {
return books;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | Author author = (Author) o;
return Objects.equals(id, author.id) && Objects.equals(name, author.name)
&& Objects.equals(books, author.books);
}
@Override
public int hashCode() {
return Objects.hash(id, name, books);
}
@Override
public String toString() {
return "Author{" + "name='" + name + '\'' + '}';
}
} | repos\spring-data-examples-main\jdbc\graalvm-native\src\main\java\example\springdata\jdbc\graalvmnative\model\Author.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class SecurityConfig {
private static final String[] AUTH_WHITELIST = {
"/swagger-resources/**",
"/swagger-ui/**",
"/swagger-ui.html",
"/v3/api-docs/**",
"/h2-console/**",
"/webjars/**",
"/favicon.ico",
"/static/**",
"/signup/**",
"/error/**",
"/public/**",
"/article/read/**",
"/download/file/**",
"/" //landing page is allowed for all
};
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.headers(h -> h.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.authorizeHttpRequests(ah -> ah
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers(AUTH_WHITELIST).permitAll()
.requestMatchers("/admin/**").hasAuthority(Constants.ROLE_ADMIN)
.requestMatchers("/user/**").hasAuthority(Constants.ROLE_USER)
.requestMatchers("/auth/login").permitAll()
.requestMatchers("/api/**").authenticated()//individual api will be secured differently
.anyRequest().authenticated()) //this one will catch the rest patterns
.csrf(AbstractHttpConfigurer::disable)
.oauth2Login(withDefaults())
.oauth2ResourceServer(o2 -> o2.jwt(withDefaults()))
.oauth2Client(withDefaults());
return http.build(); | }
@Bean
JwtDecoder jwtDecoder(@Value("${spring.security.oauth2.client.provider.oidc.issuer-uri}") String issuerUri) {
return JwtDecoders.fromOidcIssuerLocation(issuerUri);
}
@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
return authorities -> authorities.stream().filter(a -> a instanceof OidcUserAuthority)
.map(a -> (OidcUserAuthority) a)
.map(a -> SecurityUtils.extractAuthorityFromClaims(a.getUserInfo().getClaims()))
.flatMap(List::stream)
.collect(Collectors.toSet());
}
} | repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\config\security\SecurityConfig.java | 2 |
请完成以下Java代码 | public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext context = RequestContext.getCurrentContext();
try (final InputStream responseDataStream = context.getResponseDataStream()) {
if(responseDataStream == null) { | logger.info("BODY: {}", "");
return null;
}
String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8"));
logger.info("BODY: {}", responseData);
context.setResponseBody(responseData);
}
catch (Exception e) {
throw new ZuulException(e, INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
return null;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul\spring-zuul-post-filter\src\main\java\com\baeldung\filters\ResponseLogFilter.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyEnteredTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyProcessed (final BigDecimal QtyProcessed)
{
set_Value (COLUMNNAME_QtyProcessed, QtyProcessed);
}
@Override
public BigDecimal getQtyProcessed()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyProcessed);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToProcess (final BigDecimal QtyToProcess)
{
set_Value (COLUMNNAME_QtyToProcess, QtyToProcess);
}
@Override
public BigDecimal getQtyToProcess()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProcess);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSupplyDate (final java.sql.Timestamp SupplyDate)
{
set_Value (COLUMNNAME_SupplyDate, SupplyDate);
}
@Override
public java.sql.Timestamp getSupplyDate()
{
return get_ValueAsTimestamp(COLUMNNAME_SupplyDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_Order_Candidate.java | 1 |
请完成以下Java代码 | public void addLastClean(PropertySource<?> propertySource) {
envCopy.addLast(propertySource);
super.addLast(propertySource);
}
/** {@inheritDoc} */
@Override
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
envCopy.addBefore(relativePropertySourceName, propertySource);
super.addBefore(relativePropertySourceName, makeEncryptable(propertySource));
}
/** {@inheritDoc} */
@Override
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
envCopy.addAfter(relativePropertySourceName, propertySource);
super.addAfter(relativePropertySourceName, makeEncryptable(propertySource));
}
/** {@inheritDoc} */ | @Override
public void replace(String name, PropertySource<?> propertySource) {
envCopy.replace(name, propertySource);
super.replace(name, makeEncryptable(propertySource));
}
/** {@inheritDoc} */
@Override
public PropertySource<?> remove(String name) {
envCopy.remove(name);
PropertySource<?> ps = super.remove(name);
// Return the original source unwrapping the Encryptable wrappers. Spring boot does some weird things
// with property sources by type on its initialization. In particular, BootstrapApplicationListener
// reorders property sources by removing sources by name and applies type checks which break when
// the returned property source type is not what Spring Boot expects.
while (ps instanceof EncryptablePropertySource) {
ps = ((EncryptablePropertySource<?>) ps).getDelegate();
}
return ps;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\wrapper\EncryptableMutablePropertySourcesWrapper.java | 1 |
请完成以下Java代码 | public class X_M_Product_SupplierApproval_Norm extends org.compiere.model.PO implements I_M_Product_SupplierApproval_Norm, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1977517179L;
/** Standard Constructor */
public X_M_Product_SupplierApproval_Norm (final Properties ctx, final int M_Product_SupplierApproval_Norm_ID, @Nullable final String trxName)
{
super (ctx, M_Product_SupplierApproval_Norm_ID, trxName);
}
/** Load Constructor */
public X_M_Product_SupplierApproval_Norm (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Product_SupplierApproval_Norm_ID (final int M_Product_SupplierApproval_Norm_ID)
{
if (M_Product_SupplierApproval_Norm_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_SupplierApproval_Norm_ID, M_Product_SupplierApproval_Norm_ID);
} | @Override
public int getM_Product_SupplierApproval_Norm_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_SupplierApproval_Norm_ID);
}
/**
* SupplierApproval_Norm AD_Reference_ID=541363
* Reference name: SupplierApproval_Norm
*/
public static final int SUPPLIERAPPROVAL_NORM_AD_Reference_ID=541363;
/** ISO 9100 Luftfahrt = ISO9100 */
public static final String SUPPLIERAPPROVAL_NORM_ISO9100Luftfahrt = "ISO9100";
/** TS 16949 = TS16949 */
public static final String SUPPLIERAPPROVAL_NORM_TS16949 = "TS16949";
@Override
public void setSupplierApproval_Norm (final java.lang.String SupplierApproval_Norm)
{
set_Value (COLUMNNAME_SupplierApproval_Norm, SupplierApproval_Norm);
}
@Override
public java.lang.String getSupplierApproval_Norm()
{
return get_ValueAsString(COLUMNNAME_SupplierApproval_Norm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_SupplierApproval_Norm.java | 1 |
请完成以下Java代码 | public void setAD_PInstance_ID (int AD_PInstance_ID)
{
if (AD_PInstance_ID < 1)
set_Value (COLUMNNAME_AD_PInstance_ID, null);
else
set_Value (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID));
}
/** Get Process Instance.
@return Instance of the process
*/
public int getAD_PInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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();
}
/** Set Temporal MRP & CRP.
@param T_MRP_CRP_ID Temporal MRP & CRP */
public void setT_MRP_CRP_ID (int T_MRP_CRP_ID)
{
if (T_MRP_CRP_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_MRP_CRP_ID, Integer.valueOf(T_MRP_CRP_ID));
}
/** Get Temporal MRP & CRP.
@return Temporal MRP & CRP */
public int getT_MRP_CRP_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_T_MRP_CRP_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_T_MRP_CRP.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonExternalSystemLeichMehlPluFileConfig
{
@NonNull
@JsonProperty("targetFieldName")
String targetFieldName;
@NonNull
@JsonProperty("targetFieldType")
JsonTargetFieldType targetFieldType;
@NonNull
@JsonProperty("replacePattern")
String replacePattern;
@NonNull
@JsonProperty("replacement")
String replacement;
@NonNull
@JsonProperty("replacementSource") | JsonReplacementSource replacementSource;
@Builder
@JsonCreator
public JsonExternalSystemLeichMehlPluFileConfig(
@JsonProperty("targetFieldName") @NonNull final String targetFieldName,
@JsonProperty("targetFieldType") @NonNull final JsonTargetFieldType targetFieldType,
@JsonProperty("replacePattern") @NonNull final String replacePattern,
@JsonProperty("replacement") @NonNull final String replacement,
@JsonProperty("replacementSource") @NonNull final JsonReplacementSource replacementSource)
{
this.targetFieldName = targetFieldName;
this.targetFieldType = targetFieldType;
this.replacePattern = replacePattern;
this.replacement = replacement;
this.replacementSource = replacementSource;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-externalsystem\src\main\java\de\metas\common\externalsystem\leichundmehl\JsonExternalSystemLeichMehlPluFileConfig.java | 2 |
请完成以下Java代码 | public ImmutableList<PPOrderRoutingActivity> getNextActivities(@NonNull final PPOrderRoutingActivity activity)
{
return getNextActivityCodes(activity)
.stream()
.map(this::getActivityByCode)
.collect(ImmutableList.toImmutableList());
}
@Nullable
public PPOrderRoutingActivity getPreviousActivityOrNull(@NonNull final PPOrderRoutingActivity activity)
{
final ImmutableSet<PPOrderRoutingActivityCode> previousActivityCodes = getPreviousActivityCodes(activity);
if (previousActivityCodes.isEmpty())
{
return null;
}
final PPOrderRoutingActivityCode previousActivityCode = previousActivityCodes.iterator().next();
return getActivityByCode(previousActivityCode);
}
private ImmutableSet<PPOrderRoutingActivityCode> getNextActivityCodes(final PPOrderRoutingActivity activity)
{
return codeToNextCodeMap.get(activity.getCode());
}
private ImmutableSet<PPOrderRoutingActivityCode> getPreviousActivityCodes(final PPOrderRoutingActivity activity)
{
final ImmutableSetMultimap<PPOrderRoutingActivityCode, PPOrderRoutingActivityCode> codeToPreviousCodeMap = codeToNextCodeMap.inverse();
return codeToPreviousCodeMap.get(activity.getCode());
}
public PPOrderRoutingActivity getLastActivity()
{
return getActivities()
.stream()
.filter(this::isFinalActivity)
.findFirst()
.orElseThrow(() -> new AdempiereException("No final activity found in " + this));
}
private boolean isFinalActivity(final PPOrderRoutingActivity activity)
{
return getNextActivityCodes(activity).isEmpty();
}
public ImmutableSet<ProductId> getProductIdsByActivityId(@NonNull final PPOrderRoutingActivityId activityId)
{
return getProducts()
.stream()
.filter(activityProduct -> activityProduct.getId() != null && PPOrderRoutingActivityId.equals(activityProduct.getId().getActivityId(), activityId))
.map(PPOrderRoutingProduct::getProductId)
.collect(ImmutableSet.toImmutableSet());
}
public void voidIt()
{
getActivities().forEach(PPOrderRoutingActivity::voidIt);
}
public void reportProgress(final PPOrderActivityProcessReport report)
{ | getActivityById(report.getActivityId()).reportProgress(report);
}
public void completeActivity(final PPOrderRoutingActivityId activityId)
{
getActivityById(activityId).completeIt();
}
public void closeActivity(final PPOrderRoutingActivityId activityId)
{
getActivityById(activityId).closeIt();
}
public void uncloseActivity(final PPOrderRoutingActivityId activityId)
{
getActivityById(activityId).uncloseIt();
}
@NonNull
public RawMaterialsIssueStrategy getIssueStrategyForRawMaterialsActivity()
{
return activities.stream()
.filter(activity -> activity.getType() == PPRoutingActivityType.RawMaterialsIssue)
.findFirst()
.map(PPOrderRoutingActivity::getRawMaterialsIssueStrategy)
.orElse(RawMaterialsIssueStrategy.DEFAULT);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRouting.java | 1 |
请完成以下Java代码 | public static String parse(String expression, String inputVariable, String inputVariableType) {
expression = expression.replaceAll("fn_date", "date:toDate");
expression = expression.replaceAll("fn_subtractDate", "date:subtractDate");
expression = expression.replaceAll("fn_addDate", "date:addDate");
expression = expression.replaceAll("fn_now", "date:now");
if ((expression.contains("#{") || expression.contains("${")) && expression.contains("}")) {
return expression;
}
StringBuilder parsedExpressionBuilder = new StringBuilder();
parsedExpressionBuilder
.append("#{")
.append(inputVariable);
if ("date".equals(inputVariableType) || "number".equals(inputVariableType)) {
parsedExpressionBuilder.append(parseSegmentWithOperator(expression));
} else {
if (expression.startsWith(".")) {
parsedExpressionBuilder.append(expression);
} else {
parsedExpressionBuilder.append(parseSegmentWithOperator(expression)); | }
}
parsedExpressionBuilder.append("}");
return parsedExpressionBuilder.toString();
}
protected static String parseSegmentWithOperator(String expression) {
String parsedExpressionSegment;
if (expression.length() < 2 || !StringUtils.startsWithAny(expression, OPERATORS)) {
parsedExpressionSegment = " == " + expression;
} else {
parsedExpressionSegment = " " + expression;
}
return parsedExpressionSegment;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELInputEntryExpressionPreParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository() {
return new HttpSessionOAuth2AuthorizationRequestRepository();
}
@Bean
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
accessTokenResponseClient.setRequestEntityConverter(new CustomRequestEntityConverter());
OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter = new OAuth2AccessTokenResponseHttpMessageConverter();
tokenResponseHttpMessageConverter.setTokenResponseConverter(new CustomTokenResponseConverter());
RestTemplate restTemplate = new RestTemplate(Arrays.asList(new FormHttpMessageConverter(), tokenResponseHttpMessageConverter));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
accessTokenResponseClient.setRestOperations(restTemplate);
return accessTokenResponseClient;
}
// additional configuration for non-Spring Boot projects
private static List<String> clients = Arrays.asList("google", "facebook");
//@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
List<ClientRegistration> registrations = clients.stream()
.map(c -> getRegistration(c))
.filter(registration -> registration != null)
.collect(Collectors.toList());
return new InMemoryClientRegistrationRepository(registrations); | }
private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";
@Autowired
private Environment env;
private ClientRegistration getRegistration(String client) {
String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");
if (clientId == null) {
return null;
}
String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
if (client.equals("google")) {
return CommonOAuth2Provider.GOOGLE.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
if (client.equals("facebook")) {
return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
return null;
}
} | repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\java\com\baeldung\oauth2\CustomRequestSecurityConfig.java | 2 |
请完成以下Java代码 | public int getRecordId() {
return recordId;
}
/**
* Sets the value of the recordId property.
*
*/
public void setRecordId(int value) {
this.recordId = value;
}
/**
* Gets the value of the tariffType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTariffType() {
return tariffType;
}
/**
* Sets the value of the tariffType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTariffType(String value) {
this.tariffType = value;
}
/**
* Gets the value of the code property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the dateBegin property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
* | */
public XMLGregorianCalendar getDateBegin() {
return dateBegin;
}
/**
* Sets the value of the dateBegin property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateBegin(XMLGregorianCalendar value) {
this.dateBegin = value;
}
/**
* Gets the value of the dateEnd property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDateEnd() {
return dateEnd;
}
/**
* Sets the value of the dateEnd property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateEnd(XMLGregorianCalendar value) {
this.dateEnd = value;
}
/**
* Gets the value of the acid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAcid() {
return acid;
}
/**
* Sets the value of the acid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcid(String value) {
this.acid = 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\CaseDetailType.java | 1 |
请完成以下Java代码 | public class DBForeignKeyConstraintException extends DBException
{
/**
*
*/
private static final long serialVersionUID = -2810401877944246237L;
private static final String AD_Message = "DBForeignKeyConstraintException";
public DBForeignKeyConstraintException(final Throwable cause)
{
super(cause);
}
@Override
protected ITranslatableString buildMessage()
{
// TODO:
// * extract the foreign key name | // * find the local and foreign table and column names
// * display a nice error message: Datensatz {} kann nicht gelöscht werden, weil er von anderen Datensätzen referenziert wird
// NOTE:
// * here is how others extracted the foreign key name: org.hibernate.dialect.new TemplatedViolatedConstraintNameExtracter() {...}.extractConstraintName(SQLException)
// Examples or error messages:
// ERROR: update or delete on table "c_bpartner" violates foreign key constraint "cbpartner_ppmrp" on table "pp_mrp"
// Detail: Key (c_bpartner_id)=(2000037) is still referenced from table "pp_mrp".
//
return TranslatableStrings.builder()
.appendADMessage(AD_Message)
.append("\n")
.append("\n").appendADElement("Cause").append(": ").append(extractMessage(getCause()))
.append("\n").append(super.buildMessage())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\exceptions\DBForeignKeyConstraintException.java | 1 |
请完成以下Java代码 | protected ByteArrayEntity findByteArrayById(String byteArrayId, CommandContext commandContext) {
return commandContext.getDbEntityManager()
.selectById(ByteArrayEntity.class, byteArrayId);
}
protected HistoricProcessInstanceEntity findProcessInstanceById(String instanceId, CommandContext commandContext) {
return commandContext.getHistoricProcessInstanceManager()
.findHistoricProcessInstance(instanceId);
}
protected void registerTransactionHandler(SetRemovalTimeBatchConfiguration configuration,
Map<Class<? extends DbEntity>, DbOperation> operations,
Integer chunkSize,
MessageEntity currentJob,
CommandContext commandContext) {
CommandExecutor newCommandExecutor = commandContext.getProcessEngineConfiguration().getCommandExecutorTxRequiresNew();
TransactionListener transactionResulthandler = createTransactionHandler(configuration, operations, chunkSize,
currentJob, newCommandExecutor);
commandContext.getTransactionContext().addTransactionListener(TransactionState.COMMITTED, transactionResulthandler);
}
protected int getUpdateChunkSize(SetRemovalTimeBatchConfiguration configuration, CommandContext commandContext) {
return configuration.getChunkSize() == null
? commandContext.getProcessEngineConfiguration().getRemovalTimeUpdateChunkSize()
: configuration.getChunkSize();
}
protected TransactionListener createTransactionHandler(SetRemovalTimeBatchConfiguration configuration,
Map<Class<? extends DbEntity>, DbOperation> operations,
Integer chunkSize,
MessageEntity currentJob,
CommandExecutor newCommandExecutor) {
return new ProcessSetRemovalTimeResultHandler(configuration, chunkSize, newCommandExecutor, this,
currentJob.getId(), operations);
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override | protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration,
List<String> processInstanceIds) {
return new SetRemovalTimeBatchConfiguration(processInstanceIds)
.setRemovalTime(configuration.getRemovalTime())
.setHasRemovalTime(configuration.hasRemovalTime())
.setHierarchical(configuration.isHierarchical())
.setUpdateInChunks(configuration.isUpdateInChunks())
.setChunkSize(configuration.getChunkSize());
}
@Override
protected SetRemovalTimeJsonConverter getJsonConverterInstance() {
return SetRemovalTimeJsonConverter.INSTANCE;
}
@Override
public int calculateInvocationsPerBatchJob(String batchType, SetRemovalTimeBatchConfiguration configuration) {
if (configuration.isUpdateInChunks()) {
return 1;
}
return super.calculateInvocationsPerBatchJob(batchType, configuration);
}
@Override
public String getType() {
return Batch.TYPE_PROCESS_SET_REMOVAL_TIME;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\ProcessSetRemovalTimeJobHandler.java | 1 |
请完成以下Java代码 | private PartyIdentification32CHName convertPartyIdentification32CHName(
@NonNull final I_SEPA_Export_Line line,
@Nullable final BankAccount bankAccount,
@NonNull final String paymentType)
{
final PartyIdentification32CHName cdtr = objectFactory.createPartyIdentification32CHName();
if (bankAccount == null)
{
cdtr.setNm(SepaUtils.replaceForbiddenChars(getFirstNonEmpty(
line::getSEPA_MandateRefNo,
() -> getBPartnerNameById(line.getC_BPartner_ID()))));
}
else
{
cdtr.setNm(SepaUtils.replaceForbiddenChars(getFirstNonEmpty(
bankAccount::getAccountName,
line::getSEPA_MandateRefNo,
() -> getBPartnerNameById(line.getC_BPartner_ID()))));
}
final Properties ctx = InterfaceWrapperHelper.getCtx(line);
final I_C_BPartner_Location billToLocation = partnerDAO.retrieveBillToLocation(ctx, line.getC_BPartner_ID(), true, ITrx.TRXNAME_None);
if ((bankAccount == null || !bankAccount.isAddressComplete()) && billToLocation == null)
{
return cdtr;
}
final I_C_Location location = locationDAO.getById(LocationId.ofRepoId(billToLocation.getC_Location_ID()));
final PostalAddress6CH pstlAdr;
if (Objects.equals(paymentType, PAYMENT_TYPE_5) || Objects.equals(paymentType, PAYMENT_TYPE_6))
{
pstlAdr = createUnstructuredPstlAdr(bankAccount, location);
}
else
{
pstlAdr = createStructuredPstlAdr(bankAccount, location);
} | cdtr.setPstlAdr(pstlAdr);
return cdtr;
}
@VisibleForTesting
static boolean isInvalidQRReference(@NonNull final String reference)
{
if (reference.length() != 27)
{
return true;
}
final int[] checkSequence = { 0, 9, 4, 6, 8, 2, 7, 1, 3, 5 };
int carryOver = 0;
for (int i = 1; i <= reference.length() - 1; i++)
{
final int idx = ((carryOver + Integer.parseInt(reference.substring(i - 1, i))) % 10);
carryOver = checkSequence[idx];
}
return !(Integer.parseInt(reference.substring(26)) == (10 - carryOver) % 10);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\sepamarshaller\impl\SEPAVendorCreditTransferMarshaler_Pain_001_001_03_CH_02.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder nameFromDeployment(String deploymentId) {
String name = deployment.getName();
if (name != null && !name.isEmpty()) {
String message = String.format("Cannot set the given deployment id '%s' to get the name from it, because the deployment name has been already set to '%s'.", deploymentId, name);
throw new NotValidException(message);
}
nameFromDeployment = deploymentId;
return this;
}
public DeploymentBuilder enableDuplicateFiltering() {
return enableDuplicateFiltering(false);
}
public DeploymentBuilder enableDuplicateFiltering(boolean deployChangedOnly) {
this.isDuplicateFilterEnabled = true;
this.deployChangedOnly = deployChangedOnly;
return this;
}
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
public DeploymentBuilder source(String source) {
deployment.setSource(source);
return this;
}
public DeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
public Deployment deploy() {
return deployWithResult();
}
public DeploymentWithDefinitions deployWithResult() {
return repositoryService.deployWithResult(this);
}
public Collection<String> getResourceNames() {
if(deployment.getResources() == null) {
return Collections.<String>emptySet();
} else {
return deployment.getResources().keySet();
}
} | // getters and setters //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public boolean isDeployChangedOnly() {
return deployChangedOnly;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public String getNameFromDeployment() {
return nameFromDeployment;
}
public Set<String> getDeployments() {
return deployments;
}
public Map<String, Set<String>> getDeploymentResourcesById() {
return deploymentResourcesById;
}
public Map<String, Set<String>> getDeploymentResourcesByName() {
return deploymentResourcesByName;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause () | {
return (String)get_Value(COLUMNNAME_WhereClause);
}
@Override
public String getBeforeChangeWarning()
{
return (String)get_Value(COLUMNNAME_BeforeChangeWarning);
}
@Override
public void setBeforeChangeWarning(String BeforeChangeWarning)
{
set_Value (COLUMNNAME_BeforeChangeWarning, BeforeChangeWarning);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Table.java | 1 |
请完成以下Java代码 | public String docValidate(final PO po, final int timing)
{
// nothing to do
return null;
}
@Override
public String modelChange(final PO po, int type)
{
onNewAndChangeAndDelete(po, type);
return null;
}
private void onNewAndChangeAndDelete(final PO po, int type)
{
if (!(type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE || type == TYPE_AFTER_DELETE))
{
return;
}
final I_C_OrderLine ol = InterfaceWrapperHelper.create(po, I_C_OrderLine.class);
//
// updating the freight cost amount, if necessary
final MOrder orderPO = (MOrder)ol.getC_Order(); | final String dontUpdateOrder = Env.getContext(po.getCtx(), OrderFastInput.OL_DONT_UPDATE_ORDER + orderPO.get_ID());
if (Check.isEmpty(dontUpdateOrder) || !"Y".equals(dontUpdateOrder))
{
final boolean newOrDelete = type == TYPE_AFTER_NEW || type == TYPE_AFTER_DELETE;
final boolean lineNetAmtChanged = po.is_ValueChanged(I_C_OrderLine.COLUMNNAME_LineNetAmt);
final FreightCostRule freightCostRule = FreightCostRule.ofCode(orderPO.getFreightCostRule());
final boolean isCopy = InterfaceWrapperHelper.isCopy(po); // metas: cg: task US215
if (!isCopy && (lineNetAmtChanged || freightCostRule.isNotFixPrice() || newOrDelete))
{
final OrderFreightCostsService orderFreightCostsService = Adempiere.getBean(OrderFreightCostsService.class);
if (orderFreightCostsService.isFreightCostOrderLine(ol))
{
final I_C_Order order = InterfaceWrapperHelper.create(orderPO, I_C_Order.class);
orderFreightCostsService.updateFreightAmt(order);
orderPO.saveEx();
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\OrderLine.java | 1 |
请完成以下Java代码 | public int getRecord_ID()
{
return user.getAD_User_ID();
}
@Override
public EMail sendEMail(final I_AD_User from, final String toEmail, final String subject, final BoilerPlateContext attributes)
{
final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder()
.clientId(getClientId())
.orgId(getOrgId())
.adProcessId(getProcessInfo().getAdProcessId())
.fromUserId(getFromUserId())
.build());
return mailService.sendEMail(EMailRequest.builder()
.mailbox(mailbox)
.toList(toEMailAddresses(toEmail))
.subject(text.getSubject())
.message(text.getTextSnippetParsed(attributes))
.html(true)
.build());
}
});
}
private void createNote(MADBoilerPlate text, I_AD_User user, Exception e)
{
final AdMessageId adMessageId = Services.get(IMsgBL.class).getIdByAdMessage(AD_Message_UserNotifyError)
.orElseThrow(() -> new AdempiereException("@NotFound@ @AD_Message_ID@ " + AD_Message_UserNotifyError));
//
final IMsgBL msgBL = Services.get(IMsgBL.class);
final String reference = msgBL.parseTranslation(getCtx(), "@AD_BoilerPlate_ID@: " + text.get_Translation(MADBoilerPlate.COLUMNNAME_Name)) | + ", " + msgBL.parseTranslation(getCtx(), "@AD_User_ID@: " + user.getName())
// +", "+Msg.parseTranslation(getCtx(), "@AD_PInstance_ID@: "+getAD_PInstance_ID())
;
final MNote note = new MNote(getCtx(),
adMessageId.getRepoId(),
getFromUserId().getRepoId(),
InterfaceWrapperHelper.getModelTableId(user), user.getAD_User_ID(),
reference,
e.getLocalizedMessage(),
get_TrxName());
note.setAD_Org_ID(0);
note.saveEx();
m_count_notes++;
}
static List<EMailAddress> toEMailAddresses(final String string)
{
final StringTokenizer st = new StringTokenizer(string, " ,;", false);
final ArrayList<EMailAddress> result = new ArrayList<>();
while (st.hasMoreTokens())
{
result.add(EMailAddress.ofString(st.nextToken()));
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToUsers.java | 1 |
请完成以下Java代码 | public int getM_Product_ID()
{
return invoiceLine.getM_Product_ID();
}
@Override
public void setM_Product_ID(final int productId)
{
invoiceLine.setM_Product_ID(productId);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return invoiceLine.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
invoiceLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return invoiceLine.getC_UOM_ID();
}
@Override
public void setC_UOM_ID(final int uomId)
{
invoiceLine.setC_UOM_ID(uomId);
}
@Override
public void setQty(@NonNull final BigDecimal qtyInHUsUOM)
{
invoiceLine.setQtyEntered(qtyInHUsUOM);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyInvoiced = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qtyInHUsUOM);
invoiceLine.setQtyInvoiced(qtyInvoiced);
}
@Override
public BigDecimal getQty()
{
return invoiceLine.getQtyEntered();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
//
// Check the invoice line first
final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID();
if (invoiceLine_PIItemProductId > 0)
{
return invoiceLine_PIItemProductId;
}
//
// Check order line
final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class);
if (orderline == null)
{
//
// C_OrderLine not found (i.e Manual Invoice)
return -1;
}
return orderline.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{ | invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return invoiceLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
invoiceLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java | 1 |
请完成以下Java代码 | public Predicate<ServerWebExchange> apply(Config config) {
throw new UnsupportedOperationException("ReadBodyPredicateFactory is only async.");
}
public static class Config {
private @Nullable Class inClass;
private @Nullable Predicate predicate;
private @Nullable Map<String, Object> hints;
public @Nullable Class getInClass() {
return inClass;
}
public Config setInClass(Class inClass) {
this.inClass = inClass;
return this;
}
public @Nullable Predicate getPredicate() {
return predicate;
}
public Config setPredicate(Predicate predicate) {
this.predicate = predicate;
return this;
}
public <T> Config setPredicate(Class<T> inClass, Predicate<T> predicate) {
setInClass(inClass); | this.predicate = predicate;
return this;
}
public @Nullable Map<String, Object> getHints() {
return hints;
}
public Config setHints(Map<String, Object> hints) {
this.hints = hints;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\ReadBodyRoutePredicateFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Job numberGeneratorNotifierJob(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] billableData = { 11, -2, -3 };
Step dataProviderStep = numberGeneratorStep(jobRepository, transactionManager, billableData, "Second Dataset Processor");
return new JobBuilder("Number generator - second dataset", jobRepository)
.start(dataProviderStep)
.on(NOTIFY)
.to(notificationStep)
.end()
.build();
}
@Bean
@Qualifier("third_job")
@Primary
public Job numberGeneratorNotifierJobWithDecider(JobRepository jobRepository, PlatformTransactionManager transactionManager, @Qualifier("NotificationStep") Step notificationStep) {
int[] billableData = { 11, -2, -3 };
Step dataProviderStep = numberGeneratorStepDecider(jobRepository, transactionManager, billableData, "Third Dataset Processor");
return new JobBuilder("Number generator - third dataset", jobRepository)
.start(dataProviderStep)
.next(new NumberInfoDecider())
.on(NOTIFY)
.to(notificationStep)
.end()
.build();
}
@Bean(name = "jobRepository")
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource());
factory.setTransactionManager(getTransactionManager());
// JobRepositoryFactoryBean's methods Throws Generic Exception,
// it would have been better to have a specific one
factory.afterPropertiesSet(); | return factory.getObject();
}
@Bean(name = "dataSource")
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
}
@Bean(name = "transactionManager")
public PlatformTransactionManager getTransactionManager() {
return new ResourcelessTransactionManager();
}
@Bean(name = "jobLauncher")
public JobLauncher getJobLauncher() throws Exception {
TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher();
// SimpleJobLauncher's methods Throws Generic Exception,
// it would have been better to have a specific one
jobLauncher.setJobRepository(getJobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
} | repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\conditionalflow\config\NumberInfoConfig.java | 2 |
请完成以下Java代码 | public boolean canDebatch(MessageProperties properties) {
return MessageProperties.BATCH_FORMAT_LENGTH_HEADER4.equals(properties
.getHeaders()
.get(MessageProperties.SPRING_BATCH_FORMAT));
}
/**
* Debatch a message that has a header with {@link MessageProperties#SPRING_BATCH_FORMAT}
* set to {@link MessageProperties#BATCH_FORMAT_LENGTH_HEADER4}.
* @param message the batched message.
* @param fragmentConsumer a consumer for each fragment.
* @since 2.2
*/
@Override
public void deBatch(Message message, Consumer<Message> fragmentConsumer) {
ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBody());
MessageProperties messageProperties = message.getMessageProperties();
messageProperties.getHeaders().remove(MessageProperties.SPRING_BATCH_FORMAT);
while (byteBuffer.hasRemaining()) {
int length = byteBuffer.getInt();
if (length < 0 || length > byteBuffer.remaining()) {
throw new ListenerExecutionFailedException("Bad batched message received",
new MessageConversionException("Insufficient batch data at offset " + byteBuffer.position()),
message);
}
byte[] body = new byte[length];
byteBuffer.get(body);
messageProperties.setContentLength(length);
// Caveat - shared MessageProperties, except for last | Message fragment;
if (byteBuffer.hasRemaining()) {
fragment = new Message(body, messageProperties);
}
else {
MessageProperties lastProperties = new MessageProperties();
BeanUtils.copyProperties(messageProperties, lastProperties);
lastProperties.setLastInBatch(true);
fragment = new Message(body, lastProperties);
}
fragmentConsumer.accept(fragment);
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\batch\SimpleBatchingStrategy.java | 1 |
请完成以下Java代码 | private void checkOffsetsAndCommitIfNecessary(List<ConsumerRecord<K, R>> list, @Nullable Consumer<?, ?> consumer) {
list.forEach(record -> this.offsets.compute(
new TopicPartition(record.topic(), record.partition()),
(k, v) -> v == null ? record.offset() + 1 : Math.max(v, record.offset() + 1)));
if (this.pending.isEmpty() && !this.offsets.isEmpty() && consumer != null) {
consumer.commitSync(this.offsets.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
entry -> new OffsetAndMetadata(entry.getValue()))),
this.commitTimeout);
this.offsets.clear();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Set<RecordHolder<K, R>> addToCollection(ConsumerRecord record, Object correlationId) {
Set<RecordHolder<K, R>> set = this.pending.computeIfAbsent(correlationId, id -> new LinkedHashSet<>());
set.add(new RecordHolder<>(record));
return set;
}
private static final class RecordHolder<K, R> {
private final ConsumerRecord<K, R> record;
RecordHolder(ConsumerRecord<K, R> record) {
this.record = record;
}
ConsumerRecord<K, R> getRecord() {
return this.record;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ this.record.topic().hashCode()
+ this.record.partition()
+ (int) this.record.offset();
return result;
} | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
RecordHolder other = (RecordHolder) obj;
if (this.record == null) {
if (other.record != null) {
return false;
}
}
else {
return this.record.topic().equals(other.record.topic())
&& this.record.partition() == other.record.partition()
&& this.record.offset() == other.record.offset();
}
return false;
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\AggregatingReplyingKafkaTemplate.java | 1 |
请完成以下Java代码 | public class ImpDataLine
{
private final String lineStr;
private final int fileLineNo;
private final ImmutableList<ImpDataCell> cells;
private final ErrorMessage parseError;
@Builder
private ImpDataLine(
final int fileLineNo,
@Nullable final String lineStr,
@Nullable @Singular final ImmutableList<ImpDataCell> cells,
@Nullable final ErrorMessage parseError)
{
this.fileLineNo = fileLineNo;
this.lineStr = lineStr;
if (parseError == null)
{
this.cells = cells;
this.parseError = null;
}
else
{
this.cells = null;
this.parseError = parseError;
}
}
public int getFileLineNo()
{
return fileLineNo;
}
public String getLineString()
{
return lineStr;
}
public boolean hasErrors()
{
return parseError != null
|| (cells != null && cells.stream().anyMatch(ImpDataCell::isCellError));
}
public String getErrorMessageAsStringOrNull()
{
return getErrorMessageAsStringOrNull(-1);
}
public String getErrorMessageAsStringOrNull(final int maxLength)
{
final int maxLengthEffective = maxLength > 0 ? maxLength : Integer.MAX_VALUE;
final StringBuilder result = new StringBuilder();
if (parseError != null)
{
result.append(parseError.getMessage());
}
if (cells != null)
{ | for (final ImpDataCell cell : cells)
{
if (!cell.isCellError())
{
continue;
}
final String cellErrorMessage = cell.getCellErrorMessage().getMessage();
if (result.length() > 0)
{
result.append("; ");
}
result.append(cellErrorMessage);
if (result.length() >= maxLengthEffective)
{
break;
}
}
}
return result.length() > 0
? StringUtils.trunc(result.toString(), maxLengthEffective)
: null;
}
public List<Object> getJdbcValues(@NonNull final List<ImpFormatColumn> columns)
{
final int columnsCount = columns.size();
if (parseError != null)
{
final ArrayList<Object> nulls = new ArrayList<>(columnsCount);
for (int i = 0; i < columnsCount; i++)
{
nulls.add(null);
}
return nulls;
}
else
{
final ArrayList<Object> values = new ArrayList<>(columnsCount);
final int cellsCount = cells.size();
for (int i = 0; i < columnsCount; i++)
{
if (i < cellsCount)
{
values.add(cells.get(i).getJdbcValue());
}
else
{
values.add(null);
}
}
return values;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\ImpDataLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | default List<VariableInstanceEntity> findVariableInstanceByScopeIdAndScopeType(String scopeId, String scopeType) {
return createInternalVariableInstanceQuery().scopeId(scopeId).withoutSubScopeId().scopeType(scopeType).list();
}
default List<VariableInstanceEntity> findVariableInstanceBySubScopeIdAndScopeType(String subScopeId, String scopeType) {
return createInternalVariableInstanceQuery().subScopeId(subScopeId).scopeType(scopeType).list();
}
/**
* Create a variable instance with the given name and value for the given tenant.
*
* @param name the name of the variable to create
* @return the {@link VariableInstanceEntity} to be used
*/
VariableInstanceEntity createVariableInstance(String name); | void insertVariableInstance(VariableInstanceEntity variable);
/**
* Inserts a variable instance with the given value.
* @param variable the variable instance to insert
* @param value the value to set
* @param tenantId the tenant id of the variable instance
*/
void insertVariableInstanceWithValue(VariableInstanceEntity variable, Object value, String tenantId);
void deleteVariableInstance(VariableInstanceEntity variable);
void deleteVariablesByExecutionId(String executionId);
void deleteVariablesByTaskId(String taskId);
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\VariableService.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final QtyDemandQtySupply currentRow = demandSupplyRepository.getById(QtyDemandQtySupplyId.ofRepoId(getRecord_ID()));
final PPOrderCandidatesQuery ppOrderCandidatesQuery = PPOrderCandidatesQuery.builder()
.warehouseId(currentRow.getWarehouseId()) | .orgId(currentRow.getOrgId())
.productId(currentRow.getProductId())
.attributesKey(currentRow.getAttributesKey())
.onlyNonZeroQty(true)
.build();
final List<TableRecordReference> recordReferences = ppOrderCandidateDAO.listIdsByQuery(ppOrderCandidatesQuery)
.stream()
.map(id -> TableRecordReference.of(I_PP_Order_Candidate.Table_Name, id))
.collect(Collectors.toList());
getResult().setRecordsToOpen(recordReferences);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\process\QtyDemand_QtySupply_V_to_PP_Order_Candidate.java | 1 |
请完成以下Java代码 | public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_REFRESH)
|| e.getActionCommand().equals(ConfirmPanel.A_OK))
{
refresh();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_ZOOM))
{
zoom();
}
} // actionPerformed
/**************************************************************************
* Property Listener
* @param e event
*/
@Override
public void vetoableChange (PropertyChangeEvent e)
{
final String propertyName = e.getPropertyName();
if (I_M_Transaction.COLUMNNAME_M_Product_ID.equals(propertyName))
{
productField.setValue(e.getNewValue());
}
else if (I_M_Transaction.COLUMNNAME_C_BPartner_ID.equals(propertyName))
{
bpartnerField.setValue(e.getNewValue());
}
} // vetoableChange
public void setProductFieldValue(final Object value)
{
productField.setValue(value);
refresh();
}
public void setDate(final Timestamp date)
{
dateFField.setValue(date);
dateTField.setValue(date);
refresh();
}
/**************************************************************************
* Refresh - Create Query and refresh grid | */
private void refresh()
{
final Object organization = orgField.getValue();
final Object locator = locatorField.getValue();
final Object product = productField.getValue();
final Object movementType = mtypeField.getValue();
final Timestamp movementDateFrom = dateFField.getValue();
final Timestamp movementDateTo = dateTField.getValue();
final Object bpartnerId = bpartnerField.getValue();
Services.get(IClientUI.class).executeLongOperation(panel, () -> refresh(organization, locator, product, movementType, movementDateFrom, movementDateTo, bpartnerId, statusBar));
} // refresh
/**
* Zoom
*/
@Override
public void zoom()
{
super.zoom();
// Zoom
panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
AWindow frame = new AWindow();
if (!frame.initWindow(adWindowId, query))
{
panel.setCursor(Cursor.getDefaultCursor());
return;
}
AEnv.addToWindowManager(frame);
AEnv.showCenterScreen(frame);
frame = null;
panel.setCursor(Cursor.getDefaultCursor());
} // zoom
} // VTrxMaterial | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTrxMaterial.java | 1 |
请完成以下Java代码 | private void updateCampaignContactPersonAdUserId(@NonNull final I_MKTG_ContactPerson contactPersonRecord)
{
final UserId newAdUserId = UserId.ofRepoIdOrNullIfSystem(contactPersonRecord.getAD_User_ID());
final IQueryUpdater<I_MKTG_Campaign_ContactPerson> updater = queryBL
.createCompositeQueryUpdater(I_MKTG_Campaign_ContactPerson.class)
.addSetColumnValue(I_MKTG_Campaign_ContactPerson.COLUMNNAME_AD_User_ID, newAdUserId);
queryCampaignContactPersonAssignment(contactPersonRecord).update(updater);
}
private IQuery<I_MKTG_Campaign_ContactPerson> queryCampaignContactPersonAssignment(@NonNull final I_MKTG_ContactPerson contactPerson)
{
return queryBL.createQueryBuilder(I_MKTG_Campaign_ContactPerson.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MKTG_Campaign_ContactPerson.COLUMN_MKTG_ContactPerson_ID, contactPerson.getMKTG_ContactPerson_ID())
.create();
}
private void updateUserFromContactPerson(final I_MKTG_ContactPerson contactPersonRecord)
{
final I_MKTG_ContactPerson oldContactPersonRecord = InterfaceWrapperHelper.createOld(contactPersonRecord, I_MKTG_ContactPerson.class);
final String oldContactPersonMail = oldContactPersonRecord.getEMail();
final Language oldContactPersonLanguage = Language.asLanguage(oldContactPersonRecord.getAD_Language());
final ContactPerson contactPerson = ContactPersonRepository.toContactPerson(contactPersonRecord);
contactPersonService.updateUserFromContactPersonIfFeasible(
contactPerson,
oldContactPersonMail,
oldContactPersonLanguage);
}
//
//
//
private static class ChangesCollector
{
private final ContactPersonsEventBus contactPersonsEventBus;
private HashMap<ContactPersonId, ContactPerson> contacts = new HashMap<>();
private ChangesCollector(@NonNull final ContactPersonsEventBus contactPersonsEventBus)
{
this.contactPersonsEventBus = contactPersonsEventBus;
}
public void collectChangedContact(final ContactPerson contact) | {
if (contacts == null)
{
throw new AdempiereException("collector already committed");
}
contacts.put(contact.getContactPersonId(), contact);
}
public void commit()
{
if (contacts == null)
{
return;
}
final ImmutableList<ContactPerson> contacts = ImmutableList.copyOf(this.contacts.values());
this.contacts = null;
if (contacts.isEmpty())
{
return;
}
contactPersonsEventBus.notifyChanged(contacts);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\interceptor\MKTG_ContactPerson.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void configureSsl(ConfigurableEnvironment environment, String trustedKeyStore) {
Properties gemfireSslProperties = new Properties();
gemfireSslProperties.setProperty(SECURITY_SSL_KEYSTORE_PROPERTY, trustedKeyStore);
gemfireSslProperties.setProperty(SECURITY_SSL_TRUSTSTORE_PROPERTY, trustedKeyStore);
environment.getPropertySources()
.addFirst(newPropertySource(GEMFIRE_SSL_PROPERTY_SOURCE_NAME, gemfireSslProperties));
}
}
static class EnableSslCondition extends AllNestedConditions {
public EnableSslCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnProperty(name = SECURITY_SSL_ENVIRONMENT_POST_PROCESSOR_ENABLED_PROPERTY,
havingValue = "true", matchIfMissing = true)
static class SpringBootDataGemFireSecuritySslEnvironmentPostProcessorEnabled { }
@Conditional(SslTriggersCondition.class)
static class AnySslTriggerCondition { }
}
static class SslTriggersCondition extends AnyNestedCondition {
public SslTriggersCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@Conditional(TrustedKeyStoreIsPresentCondition.class)
static class TrustedKeyStoreCondition { }
@ConditionalOnProperty(prefix = SECURITY_SSL_PROPERTY_PREFIX, name = { "keystore", "truststore" })
static class SpringDataGemFireSecuritySslKeyStoreAndTruststorePropertiesSet { } | @ConditionalOnProperty(SECURITY_SSL_USE_DEFAULT_CONTEXT)
static class SpringDataGeodeSslUseDefaultContextPropertySet { }
@ConditionalOnProperty({ GEMFIRE_SSL_KEYSTORE_PROPERTY, GEMFIRE_SSL_TRUSTSTORE_PROPERTY })
static class ApacheGeodeSslKeyStoreAndTruststorePropertiesSet { }
}
static class TrustedKeyStoreIsPresentCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return locateKeyStoreInClassPath(environment).isPresent()
|| locateKeyStoreInFileSystem(environment).isPresent()
|| locateKeyStoreInUserHome(environment).isPresent();
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\SslAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class DemoServerInstanceConfiguration {
@Bean
ServiceInstanceListSupplier serviceInstanceListSupplier() {
return new DemoInstanceSupplier("example-service");
}
}
@Configuration
@LoadBalancerClient(name = "example-service", configuration = DemoServerInstanceConfiguration.class)
class WebClientConfig {
@LoadBalanced
@Bean
WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}
class DemoInstanceSupplier implements ServiceInstanceListSupplier {
private final String serviceId; | public DemoInstanceSupplier(String serviceId) {
this.serviceId = serviceId;
}
@Override
public String getServiceId() {
return serviceId;
}
@Override
public Flux<List<ServiceInstance>> get() {
return Flux.just(Arrays
.asList(new DefaultServiceInstance(serviceId + "1", serviceId, "localhost", 8080, false),
new DefaultServiceInstance(serviceId + "2", serviceId, "localhost", 8081, false)));
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-loadbalancer\spring-cloud-loadbalancer-client\src\main\java\com\baeldung\spring\cloud\loadbalancer\client\ClientApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@ManyToMany
@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.MERGE, CascadeType.PERSIST})
@JoinTable(joinColumns = { @JoinColumn(name = "author_id") })
private Set<Author> authors = new HashSet<>();
public void addAuthor(Author author) {
authors.add(author);
}
// standard getters and setters
public Book() {
}
public Book(String title) {
this.title = title;
}
public int getId() {
return id;
} | public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\transientobject\entity\Book.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private SecurityContext getContextByPath() {
Set<String> urls = AnonTagUtils.getAllAnonymousUrl(applicationContext);
urls = urls.stream().filter(url -> !url.equals("/")).collect(Collectors.toSet());
String regExp = "^(?!" + apiPath + String.join("|" + apiPath, urls) + ").*$";
return SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(o->o.requestMappingPattern()
// 排除不需要认证的接口
.matches(regExp))
.build();
}
private List<SecurityReference> defaultAuth() {
List<SecurityReference> securityReferences = new ArrayList<>();
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
securityReferences.add(new SecurityReference(tokenHeader, authorizationScopes));
return securityReferences;
}
/**
* 解决Springfox与SpringBoot集成后,WebMvcRequestHandlerProvider和WebFluxRequestHandlerProvider冲突问题
* @return /
*/
@Bean
@SuppressWarnings({"all"})
public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
return new BeanPostProcessor() {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
List<T> filteredMappings = mappings.stream()
.filter(mapping -> mapping.getPatternParser() == null)
.collect(Collectors.toList());
mappings.clear(); | mappings.addAll(filteredMappings);
}
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
if (field != null) {
field.setAccessible(true);
try {
return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Failed to access handlerMappings field", e);
}
}
return Collections.emptyList();
}
};
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\webConfig\SwaggerConfig.java | 2 |
请完成以下Java代码 | public TransportProtos.SessionInfoProto getSessionByEndpoint(String endpoint) {
return bsSessions.get(endpoint);
}
public TransportProtos.SessionInfoProto removeSessionByEndpoint(String endpoint) {
return bsSessions.remove(endpoint);
}
public BootstrapConfig getBootstrapConfigByEndpoint(String endpoint) {
return bootstrapConfigStore.getAll().get(endpoint);
}
public SecurityInfo addValueToStore(TbLwM2MSecurityInfo store, String endpoint) {
/* add value to store from BootstrapJson */
SecurityInfo securityInfo = null;
if (store != null && store.getBootstrapCredentialConfig() != null && store.getSecurityMode() != null) {
securityInfo = store.getSecurityInfo();
this.setBootstrapConfigSecurityInfo(store);
BootstrapConfig bsConfigNew = store.getBootstrapConfig();
if (bsConfigNew != null) {
try {
boolean bootstrapServerUpdateEnable = ((Lwm2mDeviceProfileTransportConfiguration) store.getDeviceProfile().getProfileData().getTransportConfiguration()).isBootstrapServerUpdateEnable();
if (!bootstrapServerUpdateEnable) {
Optional<Map.Entry<Integer, BootstrapConfig.ServerSecurity>> securities = bsConfigNew.security.entrySet().stream().filter(sec -> sec.getValue().bootstrapServer).findAny();
if (securities.isPresent()) {
bsConfigNew.security.entrySet().remove(securities.get());
int serverSortId = securities.get().getValue().serverId; | Optional<Map.Entry<Integer, BootstrapConfig.ServerConfig>> serverConfigs = bsConfigNew.servers.entrySet().stream().filter(serv -> (serv.getValue()).shortId == serverSortId).findAny();
if (serverConfigs.isPresent()) {
bsConfigNew.servers.entrySet().remove(serverConfigs.get());
}
}
}
for (String config : bootstrapConfigStore.getAll().keySet()) {
if (config.equals(endpoint)) {
bootstrapConfigStore.remove(config);
}
}
bootstrapConfigStore.add(endpoint, bsConfigNew);
} catch (InvalidConfigurationException e) {
if (e.getMessage().contains("Psk identity") && e.getMessage().contains("already used for this bootstrap server")) {
log.trace("Invalid Bootstrap Configuration", e);
} else {
log.error("Invalid Bootstrap Configuration", e);
}
}
}
}
return securityInfo;
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\store\LwM2MBootstrapSecurityStore.java | 1 |
请完成以下Java代码 | private void setupCaching()
{
CacheMgt.get().enableRemoteCacheInvalidationForTableName(I_M_ShipmentSchedule.Table_Name);
}
@VisibleForTesting
public static void registerSSAggregationKeyDependencies()
{
final IAggregationKeyRegistry keyRegistry = Services.get(IAggregationKeyRegistry.class);
final String registrationKey = ShipmentScheduleHeaderAggregationKeyBuilder.REGISTRATION_KEY;
//
// Register Handlers
keyRegistry.registerAggregationKeyValueHandler(registrationKey, new ShipmentScheduleKeyValueHandler());
//
// Register ShipmentScheduleHeaderAggregationKeyBuilder
keyRegistry.registerDependsOnColumnnames(registrationKey,
I_M_ShipmentSchedule.COLUMNNAME_C_DocType_ID,
I_M_ShipmentSchedule.COLUMNNAME_C_BPartner_ID,
I_M_ShipmentSchedule.COLUMNNAME_C_BPartner_Override_ID,
I_M_ShipmentSchedule.COLUMNNAME_C_BPartner_Location_ID,
I_M_ShipmentSchedule.COLUMNNAME_C_BP_Location_Override_ID,
I_M_ShipmentSchedule.COLUMNNAME_C_Order_ID, // by adding this, we also cover DateOrdered and POReference
I_M_ShipmentSchedule.COLUMNNAME_M_Warehouse_ID,
I_M_ShipmentSchedule.COLUMNNAME_M_Warehouse_Override_ID,
I_M_ShipmentSchedule.COLUMNNAME_AD_User_ID,
I_M_ShipmentSchedule.COLUMNNAME_AD_User_Override_ID,
I_M_ShipmentSchedule.COLUMNNAME_AD_Org_ID,
I_M_ShipmentSchedule.COLUMNNAME_DateOrdered,
I_M_ShipmentSchedule.COLUMNNAME_ExternalHeaderId,
I_M_ShipmentSchedule.COLUMNNAME_ExternalSystem_ID);
}
@Override
public void onModelChange(@NonNull final Object model, @NonNull final ModelChangeType changeType) throws Exception
{
if (InterfaceWrapperHelper.isInstanceOf(model, I_M_Product.class))
{
final I_M_Product product = InterfaceWrapperHelper.create(model, I_M_Product.class);
productChange(product, changeType);
} | }
private void productChange(@NonNull final I_M_Product productPO, @NonNull final ModelChangeType type)
{
if (type.isChange() /* not on new, because a new product can't have any shipment schedules yet */
&& type.isAfter())
{
final boolean isDiverseChanged = InterfaceWrapperHelper.isValueChanged(productPO, de.metas.adempiere.model.I_M_Product.COLUMNNAME_IsDiverse);
final boolean isProductTypeChanged = InterfaceWrapperHelper.isValueChanged(productPO, I_M_Product.COLUMNNAME_ProductType);
if (isDiverseChanged || isProductTypeChanged)
{
final ProductId productId = ProductId.ofRepoId(productPO.getM_Product_ID());
final boolean display = ProductType.ofCode(productPO.getProductType()).isItem();
final IShipmentSchedulePA shipmentSchedulePA = Services.get(IShipmentSchedulePA.class);
shipmentSchedulePA.setIsDiplayedForProduct(productId, display);
final IShipmentScheduleInvalidateBL shipmentScheduleInvalidator = Services.get(IShipmentScheduleInvalidateBL.class);
shipmentScheduleInvalidator.flagForRecompute(productId);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\InOutCandidateValidator.java | 1 |
请完成以下Java代码 | static String englishToMorse(String english) {
if (english == null) {
return null;
}
String upperCaseEnglish = english.toUpperCase();
String[] morse = new String[upperCaseEnglish.length()];
for (int index = 0; index < upperCaseEnglish.length(); index++) {
String morseCharacter = morseAlphabet.get(String.valueOf(upperCaseEnglish.charAt(index)));
if (morseCharacter == null) {
throw new IllegalArgumentException("Character " + upperCaseEnglish.charAt(index) + " can't be translated to morse");
}
morse[index] = morseCharacter;
}
return String.join(" ", morse);
}
static String morseToEnglish(String morse) {
if (morse == null) { | return null;
}
if (morse.isEmpty()) {
return "";
}
String[] morseUnitCharacters = morse.split(" ");
StringBuilder stringBuilder = new StringBuilder();
for (int index = 0; index < morseUnitCharacters.length; index ++) {
String englishCharacter = morseAlphabet.getKey(morseUnitCharacters[index]);
if (englishCharacter == null) {
throw new IllegalArgumentException("Character " + morseUnitCharacters[index] + " is not a valid morse character");
}
stringBuilder.append(englishCharacter);
}
return stringBuilder.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-9\src\main\java\com\baeldung\morse\MorseTranslator.java | 1 |
请完成以下Java代码 | public ChannelModel getChannelModelById(String channelDefinitionId) {
return commandExecutor.execute(new GetChannelModelCmd(null, channelDefinitionId));
}
@Override
public ChannelModel getChannelModelByKey(String channelDefinitionKey) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, null));
}
@Override
public ChannelModel getChannelModelByKey(String channelDefinitionKey, String tenantId) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, tenantId, null));
}
@Override
public ChannelModel getChannelModelByKeyAndParentDeploymentId(String channelDefinitionKey, String parentDeploymentId) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, null, parentDeploymentId));
}
@Override
public ChannelModel getChannelModelByKeyAndParentDeploymentId(String channelDefinitionKey, String parentDeploymentId, String tenantId) {
return commandExecutor.execute(new GetChannelModelCmd(channelDefinitionKey, tenantId, parentDeploymentId)); | }
@Override
public EventModelBuilder createEventModelBuilder() {
return new EventModelBuilderImpl(this, eventRegistryEngineConfiguration.getEventJsonConverter());
}
@Override
public InboundChannelModelBuilder createInboundChannelModelBuilder() {
return new InboundChannelDefinitionBuilderImpl(this, eventRegistryEngineConfiguration.getChannelJsonConverter());
}
@Override
public OutboundChannelModelBuilder createOutboundChannelModelBuilder() {
return new OutboundChannelDefinitionBuilderImpl(this, eventRegistryEngineConfiguration.getChannelJsonConverter());
}
public void registerEventModel(EventModel eventModel) {
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventRepositoryServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeleteSuspendedJobCmd implements Command<Object>, Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(DeleteSuspendedJobCmd.class);
private static final long serialVersionUID = 1L;
protected JobServiceConfiguration jobServiceConfiguration;
protected String suspendedJobId;
public DeleteSuspendedJobCmd(String suspendedJobId, JobServiceConfiguration jobServiceConfiguration) {
this.suspendedJobId = suspendedJobId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Object execute(CommandContext commandContext) {
SuspendedJobEntity jobToDelete = getJobToDelete(commandContext);
sendCancelEvent(jobToDelete);
jobServiceConfiguration.getSuspendedJobEntityManager().delete(jobToDelete);
return null;
}
protected void sendCancelEvent(SuspendedJobEntity jobToDelete) {
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) { | eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete),
jobServiceConfiguration.getEngineName());
}
}
protected SuspendedJobEntity getJobToDelete(CommandContext commandContext) {
if (suspendedJobId == null) {
throw new FlowableIllegalArgumentException("jobId is null");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Deleting job {}", suspendedJobId);
}
SuspendedJobEntity job = jobServiceConfiguration.getSuspendedJobEntityManager().findById(suspendedJobId);
if (job == null) {
throw new FlowableObjectNotFoundException("No suspended job found with id '" + suspendedJobId + "'", Job.class);
}
return job;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\DeleteSuspendedJobCmd.java | 2 |
请完成以下Java代码 | private void add(@NonNull final HUToReport hu, @NonNull final PrintInstructions printInstructions)
{
// Don't add it if we already considered it
if (!huIdsCollected.add(hu.getHUId()))
{
return;
}
final BatchToPrint lastBatch = !batches.isEmpty() ? batches.get(batches.size() - 1) : null;
final BatchToPrint batch;
if (lastBatch == null || !lastBatch.isMatching(printInstructions))
{
batch = new BatchToPrint(printInstructions);
batches.add(batch);
}
else
{
batch = lastBatch;
}
batch.addHU(hu);
}
public boolean isEmpty() {return huIdsCollected.isEmpty();}
public ImmutableSet<HuId> getHuIds() {return ImmutableSet.copyOf(huIdsCollected);}
public void forEach(@NonNull final Consumer<BatchToPrint> action)
{
batches.forEach(action);
}
}
@Getter
private static class BatchToPrint
{
@NonNull private final PrintInstructions printInstructions;
@NonNull private final ArrayList<HUToReport> hus = new ArrayList<>(); | private BatchToPrint(final @NonNull PrintInstructions printInstructions) {this.printInstructions = printInstructions;}
public boolean isMatching(@NonNull final PrintInstructions printInstructions)
{
return Objects.equals(this.printInstructions, printInstructions);
}
public void addHU(@NonNull final HUToReport hu) {this.hus.add(hu);}
}
@Value
@Builder
private static class PrintInstructions
{
@NonNull AdProcessId printFormatProcessId;
@Builder.Default PrintCopies copies = PrintCopies.ONE;
@Builder.Default boolean onlyOneHUPerPrint = true;
public static PrintInstructions of(HULabelConfig huLabelConfig)
{
return builder()
.printFormatProcessId(huLabelConfig.getPrintFormatProcessId())
.copies(huLabelConfig.getAutoPrintCopies())
// IMPORTANT: call the report with one HU only because label reports are working only if we provide M_HU_ID parameter.
// We changed HUReportExecutor to provide the M_HU_ID parameter and as AD_Table_ID/Record_ID in case only one HU is provided.
.onlyOneHUPerPrint(true)
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\labels\HULabelPrintCommand.java | 1 |
请完成以下Java代码 | public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Business Partner .
@return Identifies a Business Partner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class);
}
@Override
public void setC_BPartner_Location(org.compiere.model.I_C_BPartner_Location C_BPartner_Location)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class, C_BPartner_Location);
}
/** Set Partner Location.
@param C_BPartner_Location_ID
Identifies the (ship to) address for this Business Partner
*/
@Override
public void setC_BPartner_Location_ID (int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null); | else
set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID));
}
/** Get Partner Location.
@return Identifies the (ship to) address for this Business Partner
*/
@Override
public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recurrent Payment.
@param C_RecurrentPayment_ID Recurrent Payment */
@Override
public void setC_RecurrentPayment_ID (int C_RecurrentPayment_ID)
{
if (C_RecurrentPayment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, Integer.valueOf(C_RecurrentPayment_ID));
}
/** Get Recurrent Payment.
@return Recurrent Payment */
@Override
public int getC_RecurrentPayment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPayment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPayment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Employee {
@Id
private int id;
@Column
private String firstName;
@Column
private String lastName;
@Column
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
} | public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\data\noconverterfound\models\Employee.java | 2 |
请完成以下Java代码 | public List<String> getFieldNames() {
return getParent().getFieldNames();
}
@Override
public boolean isIdentityField(String fieldName) {
return getParent().isIdentityField(fieldName);
}
@Override
public Object getObject() {
return getParent().getObject();
}
@Override
public WritablePdxInstance createWriter() {
return this;
}
@Override
public boolean hasField(String fieldName) { | return getParent().hasField(fieldName);
}
};
}
/**
* Determines whether the given {@link String field name} is a {@link PropertyDescriptor property}
* on the underlying, target {@link Object}.
*
* @param fieldName {@link String} containing the name of the field to match against
* a {@link PropertyDescriptor property} from the underlying, target {@link Object}.
* @return a boolean value that determines whether the given {@link String field name}
* is a {@link PropertyDescriptor property} on the underlying, target {@link Object}.
* @see #getFieldNames()
*/
@Override
public boolean hasField(String fieldName) {
return getFieldNames().contains(fieldName);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\pdx\ObjectPdxInstanceAdapter.java | 1 |
请完成以下Java代码 | public class DLMReferenceException extends DBException
{
private static final long serialVersionUID = -4557251479983766242L;
private final boolean referencingTableHasDLMLevel;
private final TableRecordIdDescriptor tableReferenceDescriptor;
@VisibleForTesting
public DLMReferenceException(
@Nullable final Throwable cause,
final TableRecordIdDescriptor tableReferenceDescriptor,
final boolean referencingTableHasDLMLevel)
{
super("Another record references the given record", cause);
this.tableReferenceDescriptor = tableReferenceDescriptor;
this.referencingTableHasDLMLevel = referencingTableHasDLMLevel; | }
public boolean isReferencingTableHasDLMLevel()
{
return referencingTableHasDLMLevel;
}
public TableRecordIdDescriptor getTableReferenceDescriptor()
{
return tableReferenceDescriptor;
}
@Override
public String toString()
{
return "DLMException [tableReferenceDescriptor=" + tableReferenceDescriptor + ", referencingTableHasDLMLevel=" + referencingTableHasDLMLevel + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\exception\DLMReferenceException.java | 1 |
请完成以下Java代码 | public void evaluateModels() throws Exception {
log.info("Training model");
evaluate(model, "trainSet", trainSet);
log.info("Testing model");
evaluate(model, "testSet", testSet);
log.info("Dataset Provenance: --------------------");
log.info(ProvenanceUtil.formattedProvenanceString(model.getProvenance()
.getDatasetProvenance()));
log.info("Trainer Provenance: --------------------");
log.info(ProvenanceUtil.formattedProvenanceString(model.getProvenance()
.getTrainerProvenance()));
}
public void evaluate(Model<Regressor> model, String datasetName, Dataset<Regressor> dataset) {
log.info("Results for " + datasetName + "---------------------");
RegressionEvaluator evaluator = new RegressionEvaluator();
RegressionEvaluation evaluation = evaluator.evaluate(model, dataset); | Regressor dimension0 = new Regressor("DIM-0", Double.NaN);
log.info("MAE: " + evaluation.mae(dimension0));
log.info("RMSE: " + evaluation.rmse(dimension0));
log.info("R^2: " + evaluation.r2(dimension0));
}
public void saveModel() throws Exception {
File modelFile = new File(MODEL_PATH);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(modelFile))) {
objectOutputStream.writeObject(model);
}
}
} | repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\tribuo\WineQualityRegression.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PricingConditionsRowChangeRequest
{
PricingConditionsBreak pricingConditionsBreak;
PricingConditionsBreakId sourcePricingConditionsBreakId;
Percent discount;
/** {@code null} means that no change is requested. Empty means "change ID to null". */
@Nullable
Optional<PaymentTermId> paymentTermId;
/** {@code null} means that no change is requested. Empty means "change value to null". */
@Nullable
Optional<Percent> paymentDiscount;
PriceChange priceChange;
public static interface PriceChange
{
}
@lombok.Value
@lombok.Builder
public static final class PartialPriceChange implements PriceChange
{
/** Currently this field is just for debugging. But might also be used to distinguish between fields that were changed to null and fields that were not changed. */
@Singular
Set<String> changedFieldNames;
PriceSpecificationType priceType;
Optional<PricingSystemId> basePricingSystemId;
BigDecimal pricingSystemSurchargeAmt; | BigDecimal fixedPriceAmt;
CurrencyId currencyId;
CurrencyId defaultCurrencyId;
}
@lombok.Value(staticConstructor = "of")
public static final class CompletePriceChange implements PriceChange
{
@NonNull
PriceSpecification price;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowChangeRequest.java | 2 |
请完成以下Java代码 | public void setTp(CashAccountType2Choice value) {
this.tp = value;
}
/**
* Gets the value of the ccy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCcy() {
return ccy;
}
/**
* Sets the value of the ccy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCcy(String value) {
this.ccy = value;
}
/**
* Gets the value of the nm property.
*
* @return
* possible object is
* {@link String }
*
*/
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 ownr property.
*
* @return
* possible object is
* {@link PartyIdentification43 }
*
*/
public PartyIdentification43 getOwnr() {
return ownr;
}
/** | * Sets the value of the ownr property.
*
* @param value
* allowed object is
* {@link PartyIdentification43 }
*
*/
public void setOwnr(PartyIdentification43 value) {
this.ownr = value;
}
/**
* Gets the value of the svcr property.
*
* @return
* possible object is
* {@link BranchAndFinancialInstitutionIdentification5 }
*
*/
public BranchAndFinancialInstitutionIdentification5 getSvcr() {
return svcr;
}
/**
* Sets the value of the svcr property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification5 }
*
*/
public void setSvcr(BranchAndFinancialInstitutionIdentification5 value) {
this.svcr = 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_04\CashAccount25.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?cachePrepStmts=true&useServerPrepStmts=true&rewriteBatchedStatements=true&createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.jdbc.batch_size=30
spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true
spring.jpa.pr | operties.hibernate.cache.use_second_level_cache=false
# this is needed for ordering updates in case of relationships
# spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.generate_statistics=true | repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchUpdateOrderSingleEntity\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public class C_BPartner_Modify_SupplierApproval extends JavaProcess implements IProcessPrecondition
{
final BPartnerSupplierApprovalRepository repo = SpringContextHolder.instance.getBean(BPartnerSupplierApprovalRepository.class);
@Param(parameterName = "SupplierApproval_Parameter")
private String p_SupplierApproval;
@Param(parameterName = "SupplierApproval_Date")
private Instant p_SupplierApproval_Date;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
} | return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final BPSupplierApprovalId bpSupplierApprovalId = BPSupplierApprovalId.ofRepoId(getRecord_ID());
repo.updateBPSupplierApproval(bpSupplierApprovalId,
p_SupplierApproval,
p_SupplierApproval_Date);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\process\C_BPartner_Modify_SupplierApproval.java | 1 |
请完成以下Java代码 | public class RefreshContextEditorAction extends AbstractContextMenuAction
{
@Override
public String getName()
{
return "Refresh";
}
@Override
public String getIcon()
{
return "Refresh16";
}
@Override
public boolean isAvailable()
{
final IRefreshableEditor editor = getRefreshableEditor();
if (editor == null)
{
return false;
}
return true;
}
public IRefreshableEditor getRefreshableEditor()
{
final VEditor editor = getEditor();
if (editor instanceof IRefreshableEditor)
{
return (IRefreshableEditor)editor;
} | else
{
return null;
}
}
@Override
public boolean isRunnable()
{
return true;
}
@Override
public void run()
{
final IRefreshableEditor editor = (IRefreshableEditor)getEditor();
editor.refreshValue();
}
@Override
public boolean isLongOperation()
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\RefreshContextEditorAction.java | 1 |
请完成以下Java代码 | public void onSuccess(SendResult sendResult) {
// 消息发送成功。
log.info( "async send success" );
}
@Override
public void onException(Throwable throwable) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
log.info( "async send fail" );
}
} );
}
/**
* 顺序消息
*/
public void sendOrderlyMsg() {
//根据指定的hashKey按顺序发送
for (int i = 0; i < 1000; i++) {
String orderId = "biz_" + i % 10;
// 分区顺序消息中区分不同分区的关键字段,Sharding Key与普通消息的key是完全不同的概念。
// 全局顺序消息,该字段可以设置为任意非空字符串。
String shardingKey = String.valueOf( orderId );
try {
SendResult sendResult = rocketMQTemplate.syncSendOrderly( "Topic-Order", "send order msg".getBytes(), shardingKey );
// 发送消息,只要不抛异常就是成功。
if (sendResult != null) {
System.out.println( new Date() + " Send mq message success . msgId is:" + sendResult.getMsgId() );
}
} catch (Exception e) {
// 消息发送失败,需要进行重试处理,可重新发送这条消息或持久化这条数据进行补偿处理。
System.out.println( new Date() + " Send mq message failed" );
e.printStackTrace();
}
}
}
/**
* 延时消息
*/
public void sendDelayMsg() {
rocketMQTemplate.syncSend( "Topic-Delay",
MessageBuilder.withPayload( "Hello MQ".getBytes() ).build(),
3000,
//设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
//messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
3 );
}
/**
* 批量消息 | */
public void sendBatchMsg(List<Message> messages) {
rocketMQTemplate.syncSend( "springboot-rocketmq", messages );
}
/**
* 事务消息
*/
public void sendTransactionMsg(){
TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
"Topic-Tx:TagA",
MessageBuilder.withPayload( "Hello MQ transaction===".getBytes() ).build(),
null );
SendStatus sendStatus = transactionSendResult.getSendStatus();
LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
System.out.println( new Date() + " Send mq message status "+ sendStatus +" , localTransactionState "+ localTransactionState );
}
} | repos\SpringBootLearning-master (1)\springboot-rocketmq-message\src\main\java\com\itwolfed\msg\Producer.java | 1 |
请完成以下Java代码 | public Batch execute(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = collectHistoricDecisionInstanceIds(commandContext);
ensureNotEmpty(BadUserRequestException.class, "historicDecisionInstanceIds", elementConfiguration.getIds());
return new BatchBuilder(commandContext)
.type(Batch.TYPE_HISTORIC_DECISION_INSTANCE_DELETION)
.config(getConfiguration(elementConfiguration))
.permission(BatchPermissions.CREATE_BATCH_DELETE_DECISION_INSTANCES)
.operationLogHandler(this::writeUserOperationLog)
.build();
}
protected BatchElementConfiguration collectHistoricDecisionInstanceIds(CommandContext commandContext) {
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
if (!CollectionUtil.isEmpty(historicDecisionInstanceIds)) {
HistoricDecisionInstanceQueryImpl query = new HistoricDecisionInstanceQueryImpl();
query.decisionInstanceIdIn(historicDecisionInstanceIds.toArray(new String[0]));
elementConfiguration.addDeploymentMappings(
commandContext.runWithoutAuthorization(query::listDeploymentIdMappings), historicDecisionInstanceIds);
}
final HistoricDecisionInstanceQueryImpl decisionInstanceQuery =
(HistoricDecisionInstanceQueryImpl) historicDecisionInstanceQuery; | if (decisionInstanceQuery != null) {
elementConfiguration.addDeploymentMappings(decisionInstanceQuery.listDeploymentIdMappings());
}
return elementConfiguration;
}
protected void writeUserOperationLog(CommandContext commandContext, int numInstances) {
List<PropertyChange> propertyChanges = new ArrayList<>();
propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances));
propertyChanges.add(new PropertyChange("async", null, true));
propertyChanges.add(new PropertyChange("deleteReason", null, deleteReason));
commandContext.getOperationLogManager()
.logDecisionInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY,
null,
propertyChanges);
}
public BatchConfiguration getConfiguration(BatchElementConfiguration elementConfiguration) {
return new BatchConfiguration(elementConfiguration.getIds(), elementConfiguration.getMappings());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\cmd\DeleteHistoricDecisionInstancesBatchCmd.java | 1 |
请完成以下Java代码 | private PPOrderId getPPOrderId()
{
Check.assumeEquals(getTableName(), I_PP_Order.Table_Name, "TableName");
return PPOrderId.ofRepoId(getRecord_ID());
}
private void unclose(final I_PP_Order ppOrder)
{
ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_BEFORE_UNCLOSE);
//
// Unclose PP_Order's Qty
ppOrderBL.uncloseQtyOrdered(ppOrder);
ppOrdersRepo.save(ppOrder);
//
// Unclose PP_Order BOM Line's quantities
final List<I_PP_Order_BOMLine> lines = ppOrderBOMDAO.retrieveOrderBOMLines(ppOrder);
for (final I_PP_Order_BOMLine line : lines)
{
ppOrderBOMBL.unclose(line);
}
//
// Unclose activities
final PPOrderId ppOrderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
ppOrderBL.uncloseActivities(ppOrderId);
// firing this before having updated the docstatus. This is how the *real* DocActions like MInvoice do it too.
ModelValidationEngine.get().fireDocValidate(ppOrder, ModelValidator.TIMING_AFTER_UNCLOSE);
//
// Update DocStatus
ppOrder.setDocStatus(IDocument.STATUS_Completed);
ppOrder.setDocAction(IDocument.ACTION_Close);
ppOrdersRepo.save(ppOrder);
//
// Reverse ALL cost collectors
reverseCostCollectorsGeneratedOnClose(ppOrderId);
}
private void reverseCostCollectorsGeneratedOnClose(final PPOrderId ppOrderId)
{
final ArrayList<I_PP_Cost_Collector> costCollectors = new ArrayList<>(ppCostCollectorDAO.getByOrderId(ppOrderId)); | // Sort the cost collectors in reverse order of their creation,
// just to make sure we are reversing the effect from last one to first one.
costCollectors.sort(ModelByIdComparator.getInstance().reversed());
for (final I_PP_Cost_Collector cc : costCollectors)
{
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(cc.getDocStatus());
if (docStatus.isReversedOrVoided())
{
continue;
}
final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType());
if (costCollectorType == CostCollectorType.UsageVariance)
{
if (docStatus.isClosed())
{
cc.setDocStatus(DocStatus.Completed.getCode());
ppCostCollectorDAO.save(cc);
}
docActionBL.processEx(cc, IDocument.ACTION_Reverse_Correct, DocStatus.Reversed.getCode());
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\PP_Order_UnClose.java | 1 |
请完成以下Java代码 | public class DeviceAuthResult {
private final boolean success;
private final DeviceId deviceId;
private final String errorMsg;
public static DeviceAuthResult of(DeviceId deviceId) {
return new DeviceAuthResult(true, deviceId, null);
}
public static DeviceAuthResult of(String errorMsg) {
return new DeviceAuthResult(false, null, errorMsg);
}
private DeviceAuthResult(boolean success, DeviceId deviceId, String errorMsg) {
super();
this.success = success;
this.deviceId = deviceId;
this.errorMsg = errorMsg;
}
public boolean isSuccess() {
return success; | }
public DeviceId getDeviceId() {
return deviceId;
}
public String getErrorMsg() {
return errorMsg;
}
@Override
public String toString() {
return "DeviceAuthResult [success=" + success + ", deviceId=" + deviceId + ", errorMsg=" + errorMsg + "]";
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\auth\DeviceAuthResult.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintPackageInfo other = (PrintPackageInfo)obj;
if (calX != other.calX)
return false;
if (calY != other.calY)
return false;
if (pageFrom != other.pageFrom)
return false;
if (pageTo != other.pageTo)
return false;
if (printService == null)
{
if (other.printService != null) | return false;
}
else if (!printService.equals(other.printService))
return false;
if (tray == null)
{
if (other.tray != null)
return false;
}
else if (!tray.equals(other.tray))
return false;
if (trayNumber != other.trayNumber)
return false;
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackageInfo.java | 1 |
请完成以下Java代码 | private I_PP_Order getPP_Order()
{
return ppOrder;
}
@Override
protected ProductId getProductId()
{
return productId;
}
@Override
protected Object getAllocationRequestReferencedModel()
{
return getPP_Order();
}
@Override
protected IAllocationSource createAllocationSource()
{
final I_PP_Order ppOrder = getPP_Order();
return huPPOrderBL.createAllocationSourceForPPOrder(ppOrder);
}
@Override
protected IDocumentLUTUConfigurationManager createReceiptLUTUConfigurationManager()
{
final I_PP_Order ppOrder = getPP_Order();
return huPPOrderBL.createReceiptLUTUConfigurationManager(ppOrder);
}
@Override
protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer()
{
final I_PP_Order order = getPP_Order();
final PPOrderId orderId = PPOrderId.ofRepoId(order.getPP_Order_ID());
final OrgId orgId = OrgId.ofRepoId(order.getAD_Org_ID());
return ReceiptCandidateRequestProducer.builder()
.orderId(orderId)
.orgId(orgId)
.date(getMovementDate()) | .locatorId(getLocatorId())
.pickingCandidateId(getPickingCandidateId())
.build();
}
@Override
protected void addAssignedHUs(final Collection<I_M_HU> hus)
{
final I_PP_Order ppOrder = getPP_Order();
huPPOrderBL.addAssignedHandlingUnits(ppOrder, hus);
}
@Override
public IPPOrderReceiptHUProducer withPPOrderLocatorId()
{
return locatorId(LocatorId.ofRepoId(ppOrder.getM_Warehouse_ID(), ppOrder.getM_Locator_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateFinishedGoodsHUProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ApplicationProps {
private List<Object> profiles;
private List<Map<String, Object>> props;
private List<User> users;
public List<Object> getProfiles() {
return profiles;
}
public void setProfiles(List<Object> profiles) {
this.profiles = profiles;
}
public List<Map<String, Object>> getProps() {
return props;
}
public void setProps(List<Map<String, Object>> props) {
this.props = props;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public static class User {
private String username;
private String password;
private List<String> roles;
public String getUsername() {
return username;
} | public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties\src\main\java\com\baeldung\yamllist\pojo\ApplicationProps.java | 2 |
请完成以下Java代码 | protected void ensureVariableDeletionsInitialized() {
if (variableDeletions == null) {
variableDeletions = new ArrayList<String>();
}
}
protected void ensureVariableDeletionsLocalInitialized() {
if (variableLocalDeletions == null) {
variableLocalDeletions = new ArrayList<String>();
}
}
public void execute() {
CaseExecutionVariableCmd command = new CaseExecutionVariableCmd(this);
executeCommand(command);
}
public void manualStart() {
ManualStartCaseExecutionCmd command = new ManualStartCaseExecutionCmd(this);
executeCommand(command);
}
public void disable() {
DisableCaseExecutionCmd command = new DisableCaseExecutionCmd(this);
executeCommand(command);
}
public void reenable() {
ReenableCaseExecutionCmd command = new ReenableCaseExecutionCmd(this);
executeCommand(command);
}
public void complete() {
CompleteCaseExecutionCmd command = new CompleteCaseExecutionCmd(this);
executeCommand(command);
}
public void close() {
CloseCaseInstanceCmd command = new CloseCaseInstanceCmd(this);
executeCommand(command);
}
public void terminate() {
TerminateCaseExecutionCmd command = new TerminateCaseExecutionCmd(this);
executeCommand(command);
}
protected void executeCommand(Command<?> command) {
try {
if(commandExecutor != null) {
commandExecutor.execute(command);
} else {
command.execute(commandContext); | }
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (CaseExecutionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (CaseDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (CaseIllegalStateTransitionException e) {
throw new NotAllowedException(e.getMessage(), e);
}
}
// getters ////////////////////////////////////////////////////////////////////////////////
public String getCaseExecutionId() {
return caseExecutionId;
}
public VariableMap getVariables() {
return variables;
}
public VariableMap getVariablesLocal() {
return variablesLocal;
}
public Collection<String> getVariableDeletions() {
return variableDeletions;
}
public Collection<String> getVariableLocalDeletions() {
return variableLocalDeletions;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\CaseExecutionCommandBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class SkipStrategy implements TbRuleEngineProcessingStrategy {
private final String queueName;
private final boolean skipTimeoutMsgs;
public SkipStrategy(String name, boolean skipTimeoutMsgs) {
this.queueName = name;
this.skipTimeoutMsgs = skipTimeoutMsgs;
}
@Override
public boolean isSkipTimeoutMsgs() {
return skipTimeoutMsgs;
} | @Override
public TbRuleEngineProcessingDecision analyze(TbRuleEngineProcessingResult result) {
if (!result.isSuccess()) {
log.debug("[{}] Reprocessing skipped for {} failed and {} timeout messages", queueName, result.getFailedMap().size(), result.getPendingMap().size());
}
if (log.isTraceEnabled()) {
result.getFailedMap().forEach((id, msg) -> log.trace("Failed messages [{}]: {}", id, ProtoUtils.fromTbMsgProto(result.getQueueName(), msg.getValue(), TbMsgCallback.EMPTY)));
}
if (log.isTraceEnabled()) {
result.getPendingMap().forEach((id, msg) -> log.trace("Timeout messages [{}]: {}", id, ProtoUtils.fromTbMsgProto(result.getQueueName(), msg.getValue(), TbMsgCallback.EMPTY)));
}
return new TbRuleEngineProcessingDecision(true, null);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\TbRuleEngineProcessingStrategyFactory.java | 2 |
请完成以下Java代码 | public class BulletedSection<T> implements Section {
private final TemplateRenderer templateRenderer;
private final String templateName;
private final String itemName;
private final List<T> items = new ArrayList<>();
/**
* Create a new instance adding items in the model with the {@code items} key.
* @param templateRenderer the {@linkplain TemplateRenderer template renderer} to use
* @param templateName the name of the template
*/
public BulletedSection(TemplateRenderer templateRenderer, String templateName) {
this(templateRenderer, templateName, "items");
}
/**
* Create a new instance.
* @param templateRenderer the {@linkplain TemplateRenderer template renderer} to use
* @param templateName the name of the template
* @param itemName the key of the items in the model
*/
public BulletedSection(TemplateRenderer templateRenderer, String templateName, String itemName) {
this.templateRenderer = templateRenderer;
this.templateName = templateName;
this.itemName = itemName;
}
/**
* Add an item to the list.
* @param item the item to add
* @return this for method chaining
*/
public BulletedSection<T> addItem(T item) {
this.items.add(item);
return this; | }
/**
* Specify whether this section is empty.
* @return {@code true} if no item is registered
*/
public boolean isEmpty() {
return this.items.isEmpty();
}
/**
* Return an immutable list of the registered items.
* @return the registered items
*/
public List<T> getItems() {
return Collections.unmodifiableList(this.items);
}
@Override
public void write(PrintWriter writer) throws IOException {
if (!isEmpty()) {
Map<String, Object> model = new HashMap<>();
model.put(this.itemName, this.items);
writer.println(this.templateRenderer.render(this.templateName, model));
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\text\BulletedSection.java | 1 |
请完成以下Java代码 | public class ActivityAfterInstantiationCmd extends AbstractInstantiationCmd {
protected String activityId;
public ActivityAfterInstantiationCmd(String activityId) {
this(null, activityId);
}
public ActivityAfterInstantiationCmd(String processInstanceId, String activityId) {
this(processInstanceId, activityId, null);
}
public ActivityAfterInstantiationCmd(String processInstanceId, String activityId,
String ancestorActivityInstanceId) {
super(processInstanceId, ancestorActivityInstanceId);
this.activityId = activityId;
}
@Override
protected ScopeImpl getTargetFlowScope(ProcessDefinitionImpl processDefinition) {
TransitionImpl transition = findTransition(processDefinition);
return transition.getDestination().getFlowScope();
}
@Override
protected CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition) {
return findTransition(processDefinition);
}
protected TransitionImpl findTransition(ProcessDefinitionImpl processDefinition) {
PvmActivity activity = processDefinition.findActivity(activityId);
EnsureUtil.ensureNotNull(NotValidException.class,
describeFailure("Activity '" + activityId + "' does not exist"),
"activity", | activity);
if (activity.getOutgoingTransitions().isEmpty()) {
throw new ProcessEngineException("Cannot start after activity " + activityId + "; activity "
+ "has no outgoing sequence flow to take");
}
else if (activity.getOutgoingTransitions().size() > 1) {
throw new ProcessEngineException("Cannot start after activity " + activityId + "; "
+ "activity has more than one outgoing sequence flow");
}
return (TransitionImpl) activity.getOutgoingTransitions().get(0);
}
@Override
public String getTargetElementId() {
return activityId;
}
@Override
protected String describe() {
StringBuilder sb = new StringBuilder();
sb.append("Start after activity '");
sb.append(activityId);
sb.append("'");
if (ancestorActivityInstanceId != null) {
sb.append(" with ancestor activity instance '");
sb.append(ancestorActivityInstanceId);
sb.append("'");
}
return sb.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ActivityAfterInstantiationCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MailWithAttachmentService {
private final String username;
private final String password;
private final String host;
private final int port;
MailWithAttachmentService(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", this.host);
props.put("mail.smtp.port", this.port);
return Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
public void sendMail(Session session) throws MessagingException, IOException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail@gmail.com"));
message.setSubject("Testing Subject");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart); | MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(getFile("attachment.txt"));
multipart.addBodyPart(attachmentPart);
MimeBodyPart attachmentPart2 = new MimeBodyPart();
attachmentPart2.attachFile(getFile("attachment2.txt"));
multipart.addBodyPart(attachmentPart2);
message.setContent(multipart);
Transport.send(message);
}
private File getFile(String filename) {
try {
URI uri = this.getClass()
.getClassLoader()
.getResource(filename)
.toURI();
return new File(uri);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to find file from resources: " + filename);
}
}
} | repos\tutorials-master\core-java-modules\core-java-networking-2\src\main\java\com\baeldung\mail\mailwithattachment\MailWithAttachmentService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public OrderMapping salesId(String salesId) {
this.salesId = salesId;
return this;
}
/**
* Id des Auftrags aus WaWi
* @return salesId
**/
@Schema(example = "A123445", description = "Id des Auftrags aus WaWi")
public String getSalesId() {
return salesId;
}
public void setSalesId(String salesId) {
this.salesId = salesId;
}
public OrderMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OrderMapping orderMapping = (OrderMapping) o;
return Objects.equals(this.orderId, orderMapping.orderId) &&
Objects.equals(this.salesId, orderMapping.salesId) &&
Objects.equals(this.updated, orderMapping.updated);
} | @Override
public int hashCode() {
return Objects.hash(orderId, salesId, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OrderMapping {\n");
sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n");
sb.append(" salesId: ").append(toIndentedString(salesId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderMapping.java | 2 |
请在Spring Boot框架中完成以下Java代码 | void setMessageConverter(@Nullable MessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
/**
* Set the {@link ExceptionListener} to use or {@code null} if no exception listener
* should be associated by default.
* @param exceptionListener the {@link ExceptionListener}
*/
void setExceptionListener(@Nullable ExceptionListener exceptionListener) {
this.exceptionListener = exceptionListener;
}
/**
* Set the {@link JmsProperties} to use.
* @param jmsProperties the {@link JmsProperties}
*/
void setJmsProperties(@Nullable JmsProperties jmsProperties) {
this.jmsProperties = jmsProperties;
}
/**
* Set the {@link ObservationRegistry} to use.
* @param observationRegistry the {@link ObservationRegistry}
*/
void setObservationRegistry(@Nullable ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
/**
* Return the {@link JmsProperties}.
* @return the jms properties
*/
protected JmsProperties getJmsProperties() {
Assert.state(this.jmsProperties != null, "'jmsProperties' must not be null");
return this.jmsProperties;
} | /**
* Configure the specified jms listener container factory. The factory can be further
* tuned and default settings can be overridden.
* @param factory the {@link AbstractJmsListenerContainerFactory} instance to
* configure
* @param connectionFactory the {@link ConnectionFactory} to use
*/
public void configure(T factory, ConnectionFactory connectionFactory) {
Assert.notNull(factory, "'factory' must not be null");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
JmsProperties properties = getJmsProperties();
JmsProperties.Listener listenerProperties = properties.getListener();
Session sessionProperties = listenerProperties.getSession();
factory.setConnectionFactory(connectionFactory);
PropertyMapper map = PropertyMapper.get();
map.from(properties::isPubSubDomain).to(factory::setPubSubDomain);
map.from(properties::isSubscriptionDurable).to(factory::setSubscriptionDurable);
map.from(properties::getClientId).to(factory::setClientId);
map.from(this.destinationResolver).to(factory::setDestinationResolver);
map.from(this.messageConverter).to(factory::setMessageConverter);
map.from(this.exceptionListener).to(factory::setExceptionListener);
map.from(sessionProperties.getAcknowledgeMode()::getMode).to(factory::setSessionAcknowledgeMode);
map.from(this.observationRegistry).to(factory::setObservationRegistry);
map.from(sessionProperties::getTransacted).to(factory::setSessionTransacted);
map.from(listenerProperties::isAutoStartup).to(factory::setAutoStartup);
}
} | repos\spring-boot-main\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\AbstractJmsListenerContainerFactoryConfigurer.java | 2 |
请完成以下Java代码 | static class OrderLinePromotionCandidate {
BigDecimal qty;
MOrderLine orderLine;
I_M_PromotionReward promotionReward;
}
private static void addDiscountLine(MOrder order, List<OrderLinePromotionCandidate> candidates) throws Exception
{
for (OrderLinePromotionCandidate candidate : candidates)
{
final String rewardMode = candidate.promotionReward.getRewardMode();
if (MPromotionReward.REWARDMODE_Charge.equals(rewardMode))
{
BigDecimal discount = candidate.orderLine.getPriceActual().multiply(candidate.qty);
discount = discount.subtract(candidate.promotionReward.getAmount());
BigDecimal qty = Env.ONE;
int C_Charge_ID = candidate.promotionReward.getC_Charge_ID();
I_M_Promotion promotion = candidate.promotionReward.getM_Promotion();
addDiscountLine(order, null, discount, qty, C_Charge_ID, promotion);
}
else if (MPromotionReward.REWARDMODE_SplitQuantity.equals(rewardMode))
{
if (candidate.promotionReward.getAmount().signum() != 0)
{
throw new AdempiereException("@NotSupported@ @M_PromotionReward@ @Amount@ (@RewardMode@:"+rewardMode+"@)");
}
MOrderLine nol = new MOrderLine(order);
MOrderLine.copyValues(candidate.orderLine, nol);
// task 09358: get rid of this; instead, update qtyReserved at one central place
// nol.setQtyReserved(Env.ZERO);
nol.setQtyDelivered(Env.ZERO);
nol.setQtyInvoiced(Env.ZERO);
nol.setQtyLostSales(Env.ZERO);
nol.setQty(candidate.qty);
nol.setPrice(Env.ZERO);
nol.setDiscount(Env.ONEHUNDRED);
setPromotion(nol, candidate.promotionReward.getM_Promotion());
setNextLineNo(nol);
nol.saveEx();
}
else
{
throw new AdempiereException("@NotSupported@ @RewardMode@ "+rewardMode); | }
}
}
private static void setPromotion(MOrderLine nol, I_M_Promotion promotion)
{
nol.addDescription(promotion.getName());
nol.set_ValueOfColumn("M_Promotion_ID", promotion.getM_Promotion_ID());
if (promotion.getC_Campaign_ID() > 0)
{
nol.setC_Campaign_ID(promotion.getC_Campaign_ID());
}
}
private static void setNextLineNo(MOrderLine ol)
{
if (ol != null && Integer.toString(ol.getLine()).endsWith("0")) {
for(int i = 0; i < 9; i++) {
int line = ol.getLine() + i + 1;
int r = DB.getSQLValue(ol.get_TrxName(), "SELECT C_OrderLine_ID FROM C_OrderLine WHERE C_Order_ID = ? AND Line = ?", ol.getC_Order_ID(), line);
if (r <= 0) {
ol.setLine(line);
return;
}
}
}
ol.setLine(0);
}
// metas: end
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\model\PromotionRule.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.