instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected void sendProcessInstanceCancelledEvent(DelegateExecution execution, FlowElement terminateEndEvent) {
if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
if (execution.isProcessInstanceType() && execution instanceof ExecutionEntity) {
Context.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createProcessCancelledEvent(
((ExecutionEntity) execution).getProcessInstance(),
createDeleteReason(terminateEndEvent.getId())
)
);
}
}
dispatchExecutionCancelled(execution, terminateEndEvent);
}
protected void dispatchExecutionCancelled(DelegateExecution execution, FlowElement terminateEndEvent) {
ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager();
// subprocesses
for (DelegateExecution subExecution : executionEntityManager.findChildExecutionsByParentExecutionId(
execution.getId()
)) {
dispatchExecutionCancelled(subExecution, terminateEndEvent);
}
// call activities
ExecutionEntity subProcessInstance = Context.getCommandContext()
.getExecutionEntityManager()
.findSubProcessInstanceBySuperExecutionId(execution.getId()); | if (subProcessInstance != null) {
dispatchExecutionCancelled(subProcessInstance, terminateEndEvent);
}
}
public static String createDeleteReason(String activityId) {
return activityId != null
? DeleteReason.TERMINATE_END_EVENT + ": " + activityId
: DeleteReason.TERMINATE_END_EVENT;
}
public boolean isTerminateAll() {
return terminateAll;
}
public void setTerminateAll(boolean terminateAll) {
this.terminateAll = terminateAll;
}
public boolean isTerminateMultiInstance() {
return terminateMultiInstance;
}
public void setTerminateMultiInstance(boolean terminateMultiInstance) {
this.terminateMultiInstance = terminateMultiInstance;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\TerminateEndEventActivityBehavior.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws IOException, InvalidFormatException {
try (final Workbook workbook = new XSSFWorkbook();
FileOutputStream saveExcel = new FileOutputStream("target/baeldung-apachepoi.xlsx");) {
Sheet sheet = workbook.createSheet("Avengers");
XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
XSSFClientAnchor ironManAnchor = new XSSFClientAnchor();
XSSFClientAnchor spiderManAnchor = new XSSFClientAnchor();
// Fill row1 data
Row row1 = sheet.createRow(0);
row1.setHeight((short) 1000);
row1.createCell(0)
.setCellValue("IRON-MAN");
updateCellWithImage(workbook, 1, drawing, ironManAnchor, "ironman.png");
// Fill row2 data
Row row2 = sheet.createRow(1);
row2.setHeight((short) 1000);
row2.createCell(0)
.setCellValue("SPIDER-MAN");
updateCellWithImage(workbook, 2, drawing, spiderManAnchor, "spiderman.png");
// Resize all columns to fit the content size
for (int i = 0; i < 2; i++) {
sheet.autoSizeColumn(i);
}
workbook.write(saveExcel);
} | }
/**
* This method position the anchor for a given rowNum and add the image correctly.
* @param workbook
* @param rowNum
* @param drawing
* @param inputImageAnchor
* @throws IOException
*/
private static void updateCellWithImage(Workbook workbook, int rowNum, XSSFDrawing drawing, XSSFClientAnchor inputImageAnchor, String inputImageName) throws IOException {
InputStream inputImageStream = ExcelCellImageHelper.class.getClassLoader()
.getResourceAsStream(inputImageName);
byte[] inputImageBytes = IOUtils.toByteArray(inputImageStream);
int inputImagePictureID = workbook.addPicture(inputImageBytes, Workbook.PICTURE_TYPE_PNG);
inputImageStream.close();
inputImageAnchor.setCol1(1);
inputImageAnchor.setRow1(rowNum - 1);
inputImageAnchor.setCol2(2);
inputImageAnchor.setRow2(rowNum);
drawing.createPicture(inputImageAnchor, inputImagePictureID);
}
} | repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\excel\write\addimageincell\ExcelCellImageHelper.java | 1 |
请完成以下Java代码 | public void configure(StateMachineStateConfigurer<States, Events> states)
throws Exception {
states
.withStates()
.initial(States.UNPAID)
.states(EnumSet.allOf(States.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<States, Events> transitions)
throws Exception {
transitions
.withExternal()
.source(States.UNPAID).target(States.WAITING_FOR_RECEIVE)
.event(Events.PAY)
.and()
.withExternal()
.source(States.WAITING_FOR_RECEIVE).target(States.DONE)
.event(Events.RECEIVE);
}
// @Override
// public void configure(StateMachineConfigurationConfigurer<States, Events> config)
// throws Exception {
// config
// .withConfiguration()
// .listener(listener());
// }
//
// @Bean
// public StateMachineListener<States, Events> listener() {
// return new StateMachineListenerAdapter<States, Events>() { | //
// @Override
// public void transition(Transition<States, Events> transition) {
// if(transition.getTarget().getId() == States.UNPAID) {
// logger.info("订单创建,待支付");
// return;
// }
//
// if(transition.getSource().getId() == States.UNPAID
// && transition.getTarget().getId() == States.WAITING_FOR_RECEIVE) {
// logger.info("用户完成支付,待收货");
// return;
// }
//
// if(transition.getSource().getId() == States.WAITING_FOR_RECEIVE
// && transition.getTarget().getId() == States.DONE) {
// logger.info("用户已收货,订单完成");
// return;
// }
// }
//
// };
// }
} | repos\SpringBoot-Learning-master\1.x\Chapter6-1-1\src\main\java\com\didispace\StateMachineConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(User requester, Article article) {
if (article.isNotAuthor(requester)) {
throw new IllegalArgumentException("you can't delete articles written by others.");
}
articleRepository.delete(article);
}
/**
* Check if the requester has favorited the article.
*
* @param requester user who requested
* @param article article
* @return Returns true if already favorited
*/
public boolean isFavorite(User requester, Article article) {
return articleFavoriteRepository.existsBy(requester, article);
}
/**
* Favorite article.
*
* @param requester user who requested
* @param article article
*/
public void favorite(User requester, Article article) {
if (this.isFavorite(requester, article)) {
throw new IllegalArgumentException("you already favorited this article.");
}
articleFavoriteRepository.save(new ArticleFavorite(requester, article));
}
/**
* Unfavorite article.
*
* @param requester user who requested | * @param article article
*/
public void unfavorite(User requester, Article article) {
if (!this.isFavorite(requester, article)) {
throw new IllegalArgumentException("you already unfavorited this article.");
}
articleFavoriteRepository.deleteBy(requester, article);
}
/**
* Get article details for anonymous users
*
* @param article article
* @return Returns article details
*/
public ArticleDetails getArticleDetails(Article article) {
return articleRepository.findArticleDetails(article);
}
/**
* Get article details for user.
*
* @param requester user who requested
* @param article article
* @return Returns article details
*/
public ArticleDetails getArticleDetails(User requester, Article article) {
return articleRepository.findArticleDetails(requester, article);
}
} | repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\ArticleService.java | 2 |
请完成以下Java代码 | public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/**
* 获取字典数据
*
* @return
*/
public static List<DictModel> getDictList() {
List<DictModel> list = new ArrayList<>();
DictModel dictModel = null;
for (MessageTypeEnum e : MessageTypeEnum.values()) {
dictModel = new DictModel();
dictModel.setValue(e.getType());
dictModel.setText(e.getNote());
list.add(dictModel);
}
return list;
} | /**
* 根据type获取枚举
*
* @param type
* @return
*/
public static MessageTypeEnum valueOfType(String type) {
for (MessageTypeEnum e : MessageTypeEnum.values()) {
if (e.getType().equals(type)) {
return e;
}
}
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\MessageTypeEnum.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<UserVO> get(@RequestParam("id") Integer id) {
// 查询用户
UserVO user = new UserVO().setId(id).setUsername("username:" + id);
// 返回
return Mono.just(user);
}
/**
* 获得指定用户编号的用户
*
* @param id 用户编号
* @return 用户
*/
@GetMapping("/v2/get")
public Mono<UserVO> get2(@RequestParam("id") Integer id) {
// 查询用户
UserVO user = userService.get(id);
// 返回
return Mono.just(user);
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("add")
public Mono<Integer> add(@RequestBody Publisher<UserAddDTO> addDTO) {
// 插入用户记录,返回编号
Integer returnId = 1;
// 返回用户编号
return Mono.just(returnId);
}
/**
* 添加用户
*
* @param addDTO 添加用户信息 DTO
* @return 添加成功的用户编号
*/
@PostMapping("add2")
public Mono<Integer> add2(Mono<UserAddDTO> addDTO) {
// 插入用户记录,返回编号
Integer returnId = 1;
// 返回用户编号 | return Mono.just(returnId);
}
/**
* 更新指定用户编号的用户
*
* @param updateDTO 更新用户信息 DTO
* @return 是否修改成功
*/
@PostMapping("/update")
public Mono<Boolean> update(@RequestBody Publisher<UserUpdateDTO> updateDTO) {
// 更新用户记录
Boolean success = true;
// 返回更新是否成功
return Mono.just(success);
}
/**
* 删除指定用户编号的用户
*
* @param id 用户编号
* @return 是否删除成功
*/
@PostMapping("/delete") // URL 修改成 /delete ,RequestMethod 改成 DELETE
public Mono<Boolean> delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = true;
// 返回是否更新成功
return Mono.just(success);
}
} | repos\SpringBoot-Labs-master\lab-27\lab-27-webflux-01\src\main\java\cn\iocoder\springboot\lab27\springwebflux\controller\UserController.java | 2 |
请完成以下Java代码 | public Object generateSeedValue(IAttributeSet attributeSet, I_M_Attribute attribute, Object valueInitialDefault)
{
return null;
}
@Override
public boolean isReadonlyUI(IAttributeValueContext ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
return false;
}
@Override
public boolean isAlwaysEditableUI(IAttributeValueContext ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
return true;
} | @Override
public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Date;
}
/**
* @return {@code false} because none of the {@code generate*Value()} methods is implemented.
*/
@Override
public boolean canGenerateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HULotNumberAttributeHandler.java | 1 |
请完成以下Java代码 | public final class CachedMethodInvocation implements Serializable {
private Object key;
private String targetBean;
private String targetMethod;
private List<Object> arguments;
private List<String> parameterTypes = new ArrayList<>();
public CachedMethodInvocation() {
}
public CachedMethodInvocation(Object key, Object targetBean, Method targetMethod, Class[] parameterTypes, Object[] arguments) {
this.key = key;
this.targetBean = targetBean.getClass().getName();
this.targetMethod = targetMethod.getName();
if (arguments != null && arguments.length != 0) {
this.arguments = Arrays.asList(arguments);
}
if (parameterTypes != null && parameterTypes.length != 0) {
for (Class clazz : parameterTypes) {
this.parameterTypes.add(clazz.getName());
}
}
}
public Object getKey() {
return key;
}
public void setKey(Object key) {
this.key = key;
}
public String getTargetBean() {
return targetBean;
}
public void setTargetBean(String targetBean) {
this.targetBean = targetBean;
}
public String getTargetMethod() {
return targetMethod;
}
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
public List<Object> getArguments() {
return arguments;
} | public void setArguments(List<Object> arguments) {
this.arguments = arguments;
}
public List<String> getParameterTypes() {
return parameterTypes;
}
public void setParameterTypes(List<String> parameterTypes) {
this.parameterTypes = parameterTypes;
}
/**
* 必须重写equals和hashCode方法,否则放到set集合里没法去重
*
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CachedMethodInvocation that = (CachedMethodInvocation) o;
return key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CachedMethodInvocation.java | 1 |
请完成以下Java代码 | public List<String> getMoveToPlanItemDefinitionIds() {
return moveToPlanItemDefinitionIds;
}
public void setMoveToPlanItemDefinitionIds(List<String> moveToPlanItemDefinitionIds) {
this.moveToPlanItemDefinitionIds = moveToPlanItemDefinitionIds;
}
public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
public String getNewAssigneeId() {
return newAssigneeId;
}
public void setNewAssigneeId(String newAssigneeId) {
this.newAssigneeId = newAssigneeId;
}
public Map<String, PlanItemInstanceEntity> getContinueParentPlanItemInstanceMap() {
return continueParentPlanItemInstanceMap;
}
public void setContinueParentPlanItemInstanceMap(Map<String, PlanItemInstanceEntity> continueParentPlanItemInstanceMap) {
this.continueParentPlanItemInstanceMap = continueParentPlanItemInstanceMap;
}
public void addContinueParentPlanItemInstance(String planItemInstanceId, PlanItemInstanceEntity continueParentPlanItemInstance) {
continueParentPlanItemInstanceMap.put(planItemInstanceId, continueParentPlanItemInstance);
}
public PlanItemInstanceEntity getContinueParentPlanItemInstance(String planItemInstanceId) {
return continueParentPlanItemInstanceMap.get(planItemInstanceId);
}
public Map<String, PlanItemMoveEntry> getMoveToPlanItemMap() {
return moveToPlanItemMap;
}
public void setMoveToPlanItemMap(Map<String, PlanItemMoveEntry> moveToPlanItemMap) {
this.moveToPlanItemMap = moveToPlanItemMap;
} | public PlanItemMoveEntry getMoveToPlanItem(String planItemId) {
return moveToPlanItemMap.get(planItemId);
}
public List<PlanItemMoveEntry> getMoveToPlanItems() {
return new ArrayList<>(moveToPlanItemMap.values());
}
public static class PlanItemMoveEntry {
protected PlanItem originalPlanItem;
protected PlanItem newPlanItem;
public PlanItemMoveEntry(PlanItem originalPlanItem, PlanItem newPlanItem) {
this.originalPlanItem = originalPlanItem;
this.newPlanItem = newPlanItem;
}
public PlanItem getOriginalPlanItem() {
return originalPlanItem;
}
public PlanItem getNewPlanItem() {
return newPlanItem;
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemInstanceEntityContainer.java | 1 |
请完成以下Java代码 | private Mono<OidcIdToken> createOidcToken(ClientRegistration clientRegistration,
OAuth2AccessTokenResponse accessTokenResponse) {
ReactiveJwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
String rawIdToken = (String) accessTokenResponse.getAdditionalParameters().get(OidcParameterNames.ID_TOKEN);
// @formatter:off
return jwtDecoder.decode(rawIdToken)
.map((jwt) ->
new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims())
);
// @formatter:on
}
private static Mono<OidcIdToken> validateNonce(
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OidcIdToken idToken) {
String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest()
.getAttribute(OidcParameterNames.NONCE);
if (requestNonce != null) {
String nonceHash = getNonceHash(requestNonce);
String nonceHashClaim = idToken.getNonce();
if (nonceHashClaim == null || !nonceHashClaim.equals(nonceHash)) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
} | }
return Mono.just(idToken);
}
private static String getNonceHash(String requestNonce) {
try {
return createHash(requestNonce);
}
catch (NoSuchAlgorithmException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
static String createHash(String nonce) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeReactiveAuthenticationManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static Map<String, String> getAllRequestParam(final HttpServletRequest request) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String str = "";
StringBuilder wholeStr = new StringBuilder();
// 一行一行的读取body体里面的内容;
while ((str = reader.readLine()) != null) {
wholeStr.append(str);
}
// 转化成json对象
return JSONObject.parseObject(wholeStr.toString(), Map.class);
}
/**
* 获取 Body 参数
*
* @date 15:04 20210621
* @param body
*/
public static Map<String, String> getAllRequestParam(final byte[] body) throws IOException {
if(body==null){
return null;
}
String wholeStr = new String(body);
// 转化成json对象
return JSONObject.parseObject(wholeStr.toString(), Map.class);
}
/**
* 将URL请求参数转换成Map
*
* @param request
*/
public static Map<String, String> getUrlParams(HttpServletRequest request) {
Map<String, String> result = new HashMap<>(16);
if (oConvertUtils.isEmpty(request.getQueryString())) {
return result;
}
String param = "";
try {
param = URLDecoder.decode(request.getQueryString(), "utf-8");
} catch (UnsupportedEncodingException e) { | e.printStackTrace();
}
String[] params = param.split("&");
for (String s : params) {
int index = s.indexOf("=");
// 代码逻辑说明: [issues/5879]数据查询传ds=“”造成的异常------------
if (index != -1) {
result.put(s.substring(0, index), s.substring(index + 1));
}
}
return result;
}
/**
* 将URL请求参数转换成Map
*
* @param queryString
*/
public static Map<String, String> getUrlParams(String queryString) {
Map<String, String> result = new HashMap<>(16);
if (oConvertUtils.isEmpty(queryString)) {
return result;
}
String param = "";
try {
param = URLDecoder.decode(queryString, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] params = param.split("&");
for (String s : params) {
int index = s.indexOf("=");
// 代码逻辑说明: [issues/5879]数据查询传ds=“”造成的异常------------
if (index != -1) {
result.put(s.substring(0, index), s.substring(index + 1));
}
}
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\HttpUtils.java | 2 |
请完成以下Java代码 | public static CostingDocumentRef ofCostRevaluationLineId(@NonNull final CostRevaluationLineId costRevaluationLineId)
{
return new CostingDocumentRef(TABLE_NAME_M_CostRevaluationLine, costRevaluationLineId, I_M_CostDetail.COLUMNNAME_M_CostRevaluationLine_ID, null);
}
String tableName;
RepoIdAware id;
String costDetailColumnName;
Boolean outboundTrx;
private CostingDocumentRef(
@NonNull final String tableName,
@NonNull final RepoIdAware id,
@NonNull final String costDetailColumnName,
@Nullable final Boolean outboundTrx)
{
this.tableName = tableName;
this.id = id;
this.costDetailColumnName = costDetailColumnName;
this.outboundTrx = outboundTrx;
}
public boolean isTableName(final String expectedTableName) {return Objects.equals(tableName, expectedTableName);}
public boolean isInventoryLine() {return isTableName(TABLE_NAME_M_InventoryLine);}
public boolean isCostRevaluationLine() {return isTableName(TABLE_NAME_M_CostRevaluationLine);}
public boolean isMatchInv()
{
return isTableName(TABLE_NAME_M_MatchInv);
}
public PPCostCollectorId getCostCollectorId()
{
return getId(PPCostCollectorId.class); | }
public <T extends RepoIdAware> T getId(final Class<T> idClass)
{
if (idClass.isInstance(id))
{
return idClass.cast(id);
}
else
{
throw new AdempiereException("Expected id to be of type " + idClass + " but it was " + id);
}
}
public static boolean equals(CostingDocumentRef ref1, CostingDocumentRef ref2) {return Objects.equals(ref1, ref2);}
public TableRecordReference toTableRecordReference() {return TableRecordReference.of(tableName, id);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostingDocumentRef.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String echo() {
return "echo";
}
@GetMapping("/test")
public String test() {
return "test";
}
// 测试【熔断降级】
@GetMapping("/sleep")
public String sleep() throws InterruptedException {
Thread.sleep(100L);
return "sleep";
}
// 测试【热点参数限流】
@GetMapping("/product_info")
@SentinelResource("demo_product_info_hot")
public String productInfo(Integer id) {
return "商品编号:" + id;
}
// 测试「Sentinel 客户端 API」
@GetMapping("/entry_demo")
public String entryDemo() {
Entry entry = null;
try {
// <1> 访问资源
entry = SphU.entry("entry_demo");
// <2> ... 执行业务逻辑
return "执行成功";
} catch (BlockException ex) { // <3>
return "被拒绝";
} finally {
// <4> 释放资源
if (entry != null) { | entry.exit();
}
}
}
// 测试「Sentinel @SentinelResource 注解」
@GetMapping("/annotations_demo")
@SentinelResource(value = "annotations_demo_resource",
blockHandler = "blockHandler",
fallback = "fallback")
public String annotationsDemo(@RequestParam(required = false) Integer id) throws InterruptedException {
if (id == null) {
throw new IllegalArgumentException("id 参数不允许为空");
}
return "success...";
}
// BlockHandler 处理函数,参数最后多一个 BlockException,其余与原函数一致.
public String blockHandler(Integer id, BlockException ex) {
return "block:" + ex.getClass().getSimpleName();
}
// Fallback 处理函数,函数签名与原函数一致或加一个 Throwable 类型的参数.
public String fallback(Integer id, Throwable throwable) {
return "fallback:" + throwable.getMessage();
}
} | repos\SpringBoot-Labs-master\labx-04-spring-cloud-alibaba-sentinel\labx-04-sca-sentinel-actuator-provider\src\main\java\cn\iocoder\springcloudalibaba\labx04\sentineldemo\provider\controller\DemoController.java | 2 |
请完成以下Java代码 | public void setM_DistributionList_ID (int M_DistributionList_ID)
{
if (M_DistributionList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID));
}
/** Get Distribution List.
@return Distribution Lists allow to distribute products to a selected list of partners
*/
public int getM_DistributionList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_DistributionList_ID()));
}
/** Set Distribution List Line.
@param M_DistributionListLine_ID
Distribution List Line with Business Partner and Quantity/Percentage
*/
public void setM_DistributionListLine_ID (int M_DistributionListLine_ID)
{
if (M_DistributionListLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, Integer.valueOf(M_DistributionListLine_ID));
}
/** Get Distribution List Line.
@return Distribution List Line with Business Partner and Quantity/Percentage
*/
public int getM_DistributionListLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionListLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Minimum Quantity.
@param MinQty
Minimum quantity for the business partner
*/
public void setMinQty (BigDecimal MinQty)
{
set_Value (COLUMNNAME_MinQty, MinQty);
} | /** Get Minimum Quantity.
@return Minimum quantity for the business partner
*/
public BigDecimal getMinQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Ratio.
@param Ratio
Relative Ratio for Distributions
*/
public void setRatio (BigDecimal Ratio)
{
set_Value (COLUMNNAME_Ratio, Ratio);
}
/** Get Ratio.
@return Relative Ratio for Distributions
*/
public BigDecimal getRatio ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Ratio);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionListLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<String> getUris() {
return this.uris;
}
public void setUris(List<String> uris) {
this.uris = uris;
}
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getApiKey() {
return this.apiKey;
}
public void setApiKey(@Nullable String apiKey) {
this.apiKey = apiKey;
}
public Duration getConnectionTimeout() {
return this.connectionTimeout;
}
public void setConnectionTimeout(Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public Duration getSocketTimeout() {
return this.socketTimeout;
}
public void setSocketTimeout(Duration socketTimeout) {
this.socketTimeout = socketTimeout;
}
public boolean isSocketKeepAlive() {
return this.socketKeepAlive;
}
public void setSocketKeepAlive(boolean socketKeepAlive) {
this.socketKeepAlive = socketKeepAlive;
}
public @Nullable String getPathPrefix() {
return this.pathPrefix;
}
public void setPathPrefix(@Nullable String pathPrefix) {
this.pathPrefix = pathPrefix;
}
public Restclient getRestclient() {
return this.restclient;
}
public static class Restclient {
private final Sniffer sniffer = new Sniffer();
private final Ssl ssl = new Ssl();
public Sniffer getSniffer() {
return this.sniffer;
}
public Ssl getSsl() {
return this.ssl;
}
public static class Sniffer {
/**
* Whether the sniffer is enabled.
*/
private boolean enabled;
/**
* Interval between consecutive ordinary sniff executions.
*/
private Duration interval = Duration.ofMinutes(5);
/** | * Delay of a sniff execution scheduled after a failure.
*/
private Duration delayAfterFailure = Duration.ofMinutes(1);
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getInterval() {
return this.interval;
}
public void setInterval(Duration interval) {
this.interval = interval;
}
public Duration getDelayAfterFailure() {
return this.delayAfterFailure;
}
public void setDelayAfterFailure(Duration delayAfterFailure) {
this.delayAfterFailure = delayAfterFailure;
}
}
public static class Ssl {
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java | 2 |
请完成以下Java代码 | public ShortcutType shortcutType() {
return ShortcutType.GATHER_LIST;
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("sources");
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
if (log.isDebugEnabled()) {
log.debug("Applying XForwardedRemoteAddr route predicate with maxTrustedIndex of "
+ config.getMaxTrustedIndex() + " for " + config.getSources().size() + " source(s)");
}
// Reuse the standard RemoteAddrRoutePredicateFactory but instead of using the
// default RemoteAddressResolver to determine the client IP address, use an
// XForwardedRemoteAddressResolver.
RemoteAddrRoutePredicateFactory.Config wrappedConfig = new RemoteAddrRoutePredicateFactory.Config();
wrappedConfig.setSources(config.getSources());
wrappedConfig
.setRemoteAddressResolver(XForwardedRemoteAddressResolver.maxTrustedIndex(config.getMaxTrustedIndex()));
RemoteAddrRoutePredicateFactory remoteAddrRoutePredicateFactory = new RemoteAddrRoutePredicateFactory();
Predicate<ServerWebExchange> wrappedPredicate = remoteAddrRoutePredicateFactory.apply(wrappedConfig);
return exchange -> {
Boolean isAllowed = wrappedPredicate.test(exchange);
if (log.isDebugEnabled()) {
ServerHttpRequest request = exchange.getRequest();
String clientAddress = request.getRemoteAddress() != null
? request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
log.debug("Request for \"" + request.getURI() + "\" from client \"" + clientAddress + "\" with \""
+ XForwardedRemoteAddressResolver.X_FORWARDED_FOR + "\" header value of \""
+ request.getHeaders().get(XForwardedRemoteAddressResolver.X_FORWARDED_FOR) + "\" is "
+ (isAllowed ? "ALLOWED" : "NOT ALLOWED"));
}
return isAllowed;
};
}
public static class Config { | // Trust the last (right-most) value in the "X-Forwarded-For" header by default,
// which represents the last reverse proxy that was used when calling the gateway.
private int maxTrustedIndex = 1;
private List<String> sources = new ArrayList<>();
public int getMaxTrustedIndex() {
return this.maxTrustedIndex;
}
public Config setMaxTrustedIndex(int maxTrustedIndex) {
this.maxTrustedIndex = maxTrustedIndex;
return this;
}
public List<String> getSources() {
return this.sources;
}
public Config setSources(List<String> sources) {
this.sources = sources;
return this;
}
public Config setSources(String... sources) {
this.sources = Arrays.asList(sources);
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\XForwardedRemoteAddrRoutePredicateFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeServiceTopDown_Service
extends Service
{
private final static URL EMPLOYEESERVICETOPDOWN_WSDL_LOCATION;
private final static WebServiceException EMPLOYEESERVICETOPDOWN_EXCEPTION;
private final static QName EMPLOYEESERVICETOPDOWN_QNAME = new QName("http://topdown.server.jaxws.baeldung.com/", "EmployeeServiceTopDown");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URI("file:/Users/do-enr-lap-4/Developer/baeldung/source/tutorials/jee7/src/main/java/com/baeldung/jaxws/server/topdown/wsdl/employeeservicetopdown.wsdl").toURL();
} catch (MalformedURLException | URISyntaxException ex) {
e = new WebServiceException(ex);
}
EMPLOYEESERVICETOPDOWN_WSDL_LOCATION = url;
EMPLOYEESERVICETOPDOWN_EXCEPTION = e;
}
public EmployeeServiceTopDown_Service() {
super(__getWsdlLocation(), EMPLOYEESERVICETOPDOWN_QNAME);
}
public EmployeeServiceTopDown_Service(WebServiceFeature... features) {
super(__getWsdlLocation(), EMPLOYEESERVICETOPDOWN_QNAME, features);
}
public EmployeeServiceTopDown_Service(URL wsdlLocation) {
super(wsdlLocation, EMPLOYEESERVICETOPDOWN_QNAME);
}
public EmployeeServiceTopDown_Service(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, EMPLOYEESERVICETOPDOWN_QNAME, features);
}
public EmployeeServiceTopDown_Service(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public EmployeeServiceTopDown_Service(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns EmployeeServiceTopDown
*/
@WebEndpoint(name = "EmployeeServiceTopDownSOAP")
public EmployeeServiceTopDown getEmployeeServiceTopDownSOAP() { | return super.getPort(new QName("http://topdown.server.jaxws.baeldung.com/", "EmployeeServiceTopDownSOAP"), EmployeeServiceTopDown.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns EmployeeServiceTopDown
*/
@WebEndpoint(name = "EmployeeServiceTopDownSOAP")
public EmployeeServiceTopDown getEmployeeServiceTopDownSOAP(WebServiceFeature... features) {
return super.getPort(new QName("http://topdown.server.jaxws.baeldung.com/", "EmployeeServiceTopDownSOAP"), EmployeeServiceTopDown.class, features);
}
private static URL __getWsdlLocation() {
if (EMPLOYEESERVICETOPDOWN_EXCEPTION!= null) {
throw EMPLOYEESERVICETOPDOWN_EXCEPTION;
}
return EMPLOYEESERVICETOPDOWN_WSDL_LOCATION;
}
} | repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\server\topdown\EmployeeServiceTopDown_Service.java | 2 |
请完成以下Java代码 | public I_M_HU retrieveParent(final I_M_HU hu)
{
return db.retrieveParent(hu);
}
@Override
public HuId retrieveParentId(final @NonNull I_M_HU hu)
{
return db.retrieveParentId(hu);
}
@Override
public I_M_HU_Item retrieveParentItem(final I_M_HU hu)
{
return db.retrieveParentItem(hu);
}
@Override
public ArrayList<I_M_HU> retrieveIncludedHUs(@NonNull final I_M_HU_Item huItem)
{
final HuItemId huItemKey = mkHUItemKey(huItem);
ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(huItemKey);
if (includedHUs == null)
{
includedHUs = new ArrayList<>(db.retrieveIncludedHUs(huItem));
for (final I_M_HU includedHU : includedHUs)
{
includedHU.setM_HU_Item_Parent(huItem);
}
huItemKey2includedHUs.put(huItemKey, includedHUs);
}
return new ArrayList<>(includedHUs);
}
@Override
public void setParentItem(final I_M_HU hu, final I_M_HU_Item parentItem)
{
// TODO: Skip if no actual change; shall not happen because the caller it's already checking this
final HuId huId = HuId.ofRepoId(hu.getM_HU_ID());
final HuItemId parentHUItemIdOld = HuItemId.ofRepoIdOrNull(hu.getM_HU_Item_Parent_ID());
//
// Perform database change
db.setParentItem(hu, parentItem);
//
// Remove HU from included HUs list of old parent (if any)
if (parentHUItemIdOld != null)
{
final ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(parentHUItemIdOld);
if (includedHUs != null)
{
boolean removed = false;
for (final Iterator<I_M_HU> it = includedHUs.iterator(); it.hasNext(); )
{
final I_M_HU includedHU = it.next(); | final HuId includedHUId = HuId.ofRepoId(includedHU.getM_HU_ID());
if (HuId.equals(includedHUId, huId))
{
it.remove();
removed = true;
break;
}
}
if (!removed)
{
throw new HUException("Included HU not found in cached included HUs list of old parent"
+ "\n HU: " + Services.get(IHandlingUnitsBL.class).getDisplayName(hu)
+ "\n Included HUs (cached): " + includedHUs);
}
}
}
//
// Add HU to include HUs list of new parent (if any)
final HuItemId parentHUItemIdNew = HuItemId.ofRepoIdOrNull(hu.getM_HU_Item_Parent_ID());
if (parentHUItemIdNew != null)
{
final ArrayList<I_M_HU> includedHUs = huItemKey2includedHUs.get(parentHUItemIdNew);
if (includedHUs != null)
{
boolean added = false;
for (final ListIterator<I_M_HU> it = includedHUs.listIterator(); it.hasNext(); )
{
final I_M_HU includedHU = it.next();
final HuId includedHUId = HuId.ofRepoId(includedHU.getM_HU_ID());
if (HuId.equals(includedHUId, huId))
{
it.set(hu);
added = true;
break;
}
}
if (!added)
{
includedHUs.add(hu);
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CachedHUAndItemsDAO.java | 1 |
请完成以下Java代码 | class CreateS3Bucket {
private final Log log = LogFactory.getLog(CreateS3Bucket.class);
private AmazonS3 s3Client;
public CreateS3Bucket(AmazonS3 s3Client) {
this.s3Client = s3Client;
}
public CreateS3Bucket() {
AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
this.s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentialsProvider.getCredentials()))
.withRegion(Regions.EU_CENTRAL_1)
.build();
}
public void createBucket(String bucketName) throws SdkClientException, AmazonServiceException {
try {
if (!this.s3Client.doesBucketExistV2(bucketName)) {
this.s3Client.createBucket(bucketName);
}
String bucketRegion = this.s3Client.getBucketLocation(bucketName);
log.info(bucketRegion); | } catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it and returned an error response.
throw new AmazonServiceException(e.getErrorMessage());
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
throw new SdkClientException(e.getMessage());
}
}
public static void main(String[] args) {
new CreateS3Bucket().createBucket("bucket-name-" + UUID.randomUUID());
}
} | repos\tutorials-master\aws-modules\aws-s3-2\src\main\java\com\baeldung\s3\CreateS3Bucket.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Email implements Serializable {
@Id
private long id;
private String name;
private String domain;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() { | return name;
}
public void setName(String name) {
this.name = name;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\serializable\Email.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Boolean getAnalyticsEnabled() {
return this.analyticsEnabled;
}
public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) {
this.analyticsEnabled = analyticsEnabled;
}
public @Nullable String getLicenseKey() {
return this.licenseKey;
}
public void setLicenseKey(@Nullable String licenseKey) {
this.licenseKey = licenseKey;
}
/**
* Enumeration of types of summary to show. Values are the same as those on
* {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum
* is not used directly.
*/
public enum ShowSummary {
/**
* Do not show a summary.
*/
OFF,
/**
* Show a summary.
*/
SUMMARY,
/**
* Show a verbose summary.
*/
VERBOSE
}
/**
* Enumeration of destinations to which the summary should be output. Values are the
* same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards
* compatibility, the Liquibase enum is not used directly.
*/
public enum ShowSummaryOutput {
/**
* Log the summary.
*/
LOG,
/**
* Output the summary to the console.
*/
CONSOLE, | /**
* Log the summary and output it to the console.
*/
ALL
}
/**
* Enumeration of types of UIService. Values are the same as those on
* {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is
* not used directly.
*/
public enum UiService {
/**
* Console-based UIService.
*/
CONSOLE,
/**
* Logging-based UIService.
*/
LOGGER
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getINSTITUTIONNAMECODE() {
return institutionnamecode;
}
/**
* Sets the value of the institutionnamecode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONNAMECODE(String value) {
this.institutionnamecode = value;
}
/**
* Gets the value of the institutionbranchid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINSTITUTIONBRANCHID() {
return institutionbranchid;
}
/**
* Sets the value of the institutionbranchid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONBRANCHID(String value) {
this.institutionbranchid = value;
}
/**
* Gets the value of the institutionname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINSTITUTIONNAME() {
return institutionname;
}
/**
* Sets the value of the institutionname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONNAME(String value) {
this.institutionname = value;
}
/**
* Gets the value of the institutionlocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getINSTITUTIONLOCATION() {
return institutionlocation;
}
/**
* Sets the value of the institutionlocation property. | *
* @param value
* allowed object is
* {@link String }
*
*/
public void setINSTITUTIONLOCATION(String value) {
this.institutionlocation = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCOUNTRY() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCOUNTRY(String value) {
this.country = 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\HFINI1.java | 2 |
请完成以下Java代码 | public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
@Override
public boolean equals(Object o) { | if (this == o) {
return true;
}
if (!(o instanceof Comment)) {
return false;
}
Comment comment = (Comment) o;
return getId().equals(comment.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\aggregation\model\Comment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Security {
/**
* Whether the driver should use encrypted traffic.
*/
private boolean encrypted;
/**
* Trust strategy to use.
*/
private TrustStrategy trustStrategy = TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES;
/**
* Path to the file that holds the trusted certificates.
*/
private @Nullable File certFile;
/**
* Whether hostname verification is required.
*/
private boolean hostnameVerificationEnabled = true;
public boolean isEncrypted() {
return this.encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
public TrustStrategy getTrustStrategy() {
return this.trustStrategy;
}
public void setTrustStrategy(TrustStrategy trustStrategy) {
this.trustStrategy = trustStrategy;
}
public @Nullable File getCertFile() {
return this.certFile;
}
public void setCertFile(@Nullable File certFile) {
this.certFile = certFile; | }
public boolean isHostnameVerificationEnabled() {
return this.hostnameVerificationEnabled;
}
public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) {
this.hostnameVerificationEnabled = hostnameVerificationEnabled;
}
public enum TrustStrategy {
/**
* Trust all certificates.
*/
TRUST_ALL_CERTIFICATES,
/**
* Trust certificates that are signed by a trusted certificate.
*/
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES,
/**
* Trust certificates that can be verified through the local system store.
*/
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java | 2 |
请完成以下Java代码 | final class NumberTranslatableString implements ITranslatableString
{
static NumberTranslatableString of(final BigDecimal valueBD, final int displayType)
{
return new NumberTranslatableString(valueBD, displayType);
}
static NumberTranslatableString of(final int valueInt)
{
return new NumberTranslatableString(BigDecimal.valueOf(valueInt), DisplayType.Integer);
}
private final BigDecimal valueBD;
private final int displayType;
private NumberTranslatableString(@NonNull final BigDecimal valueBD, final int displayType)
{
this.valueBD = valueBD;
if (!DisplayType.isNumeric(displayType))
{
throw new IllegalArgumentException("displayType is not numeric: " + displayType);
}
this.displayType = displayType;
}
@Override
@Deprecated
public String toString()
{
return valueBD.toString();
} | @Override
public String translate(final String adLanguage)
{
final Language language = Language.getLanguage(adLanguage);
final DecimalFormat numberFormat = DisplayType.getNumberFormat(displayType, language);
final String valueStr = numberFormat.format(valueBD);
return valueStr;
}
@Override
public String getDefaultValue()
{
final DecimalFormat numberFormat = DisplayType.getNumberFormat(displayType);
final String valueStr = numberFormat.format(valueBD);
return valueStr;
}
@Override
public Set<String> getAD_Languages()
{
return ImmutableSet.of();
}
@Override
public boolean isTranslatedTo(final String adLanguage)
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\NumberTranslatableString.java | 1 |
请完成以下Java代码 | final class CollectionToDelimitedStringConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
CollectionToDelimitedStringConverter(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Collection.class, String.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
TypeDescriptor sourceElementType = sourceType.getElementTypeDescriptor();
if (targetType == null || sourceElementType == null) {
return true;
}
return this.conversionService.canConvert(sourceElementType, targetType)
|| sourceElementType.getType().isAssignableFrom(targetType.getType());
}
@Override
@Contract("!null, _, _ -> !null")
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
Collection<?> sourceCollection = (Collection<?>) source;
return convert(sourceCollection, sourceType, targetType);
}
private Object convert(Collection<?> source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source.isEmpty()) {
return "";
} | return source.stream()
.map((element) -> convertElement(element, sourceType, targetType))
.collect(Collectors.joining(getDelimiter(sourceType)));
}
private CharSequence getDelimiter(TypeDescriptor sourceType) {
Delimiter annotation = sourceType.getAnnotation(Delimiter.class);
return (annotation != null) ? annotation.value() : ",";
}
private String convertElement(Object element, TypeDescriptor sourceType, TypeDescriptor targetType) {
return String
.valueOf(this.conversionService.convert(element, sourceType.elementTypeDescriptor(element), targetType));
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\CollectionToDelimitedStringConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static List<File> getReportsDirectories(@NonNull final File dir)
{
final ArrayList<File> result = new ArrayList<>();
if (isIgnore(dir))
{
return result;
}
if (isProjectDir(dir))
{
final File reportsDir = getReportsDirOfProjectDirIfExists(dir);
if (reportsDir != null)
{
result.add(reportsDir);
}
}
for (final File subProjectDir : dir.listFiles(DevelopmentWorkspaceJasperDirectoriesFinder::isProjectDir))
{
result.addAll(getReportsDirectories(subProjectDir));
}
return result;
}
@Nullable
private static File getReportsDirOfProjectDirIfExists(final File projectDir)
{
final File reportsDir = new File(projectDir, "src//main//jasperreports");
if (reportsDir.exists() && reportsDir.isDirectory())
{
return reportsDir;
} | else
{
return null;
}
}
private static boolean isProjectDir(final File dir)
{
return dir.isDirectory()
&& new File(dir, "pom.xml").exists()
&& !isIgnore(dir);
}
private static boolean isIgnore(final File dir)
{
return new File(dir, ".ignore-reports").exists();
}
private static boolean isMetasfreshRepository(@NonNull final File projectDir)
{
return "metasfresh".equals(projectDir.getName())
&& projectDir.isDirectory();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\util\DevelopmentWorkspaceJasperDirectoriesFinder.java | 2 |
请完成以下Java代码 | public Set<String> getAuthorizedGrantTypes() {
return stringToSet(grantTypes);
}
@Override
public Set<String> getResourceIds() {
return stringToSet(resourceIds);
}
/**
* 获取回调地址
*
* @return redirectUrl
*/
@Override
public Set<String> getRegisteredRedirectUri() {
return stringToSet(redirectUrl);
}
/**
* 这里需要提一下
* 个人觉得这里应该是客户端所有的权限
* 但是已经有 scope 的存在可以很好的对客户端的权限进行认证了
* 那么在 oauth2 的四个角色中,这里就有可能是资源服务器的权限
* 但是一般资源服务器都有自己的权限管理机制,比如拿到用户信息后做 RBAC
* 所以在 spring security 的默认实现中直接给的是空的一个集合
* 这里我们也给他一个空的把
*
* @return GrantedAuthority
*/
@Override
public Collection<GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
/**
* 判断是否自动授权
*
* @param scope scope
* @return 结果
*/
@Override
public boolean isAutoApprove(String scope) {
if (autoApproveScopes == null || autoApproveScopes.isEmpty()) {
return false;
}
Set<String> authorizationSet = stringToSet(authorizations); | for (String auto : authorizationSet) {
if ("true".equalsIgnoreCase(auto) || scope.matches(auto)) {
return true;
}
}
return false;
}
/**
* additional information 是 spring security 的保留字段
* 暂时用不到,直接给个空的即可
*
* @return map
*/
@Override
public Map<String, Object> getAdditionalInformation() {
return Collections.emptyMap();
}
private Set<String> stringToSet(String s) {
return Arrays.stream(s.split(",")).collect(Collectors.toSet());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\entity\SysClientDetails.java | 1 |
请完成以下Java代码 | public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public de.metas.handlingunits.model.I_M_HU getVHU()
{
return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU)
{
set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU);
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_ValueNoCheck (COLUMNNAME_VHU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getVHU_Source()
{
return get_ValueAsPO(COLUMNNAME_VHU_Source_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setVHU_Source(final de.metas.handlingunits.model.I_M_HU VHU_Source)
{
set_ValueFromPO(COLUMNNAME_VHU_Source_ID, de.metas.handlingunits.model.I_M_HU.class, VHU_Source); | }
@Override
public void setVHU_Source_ID (final int VHU_Source_ID)
{
if (VHU_Source_ID < 1)
set_Value (COLUMNNAME_VHU_Source_ID, null);
else
set_Value (COLUMNNAME_VHU_Source_ID, VHU_Source_ID);
}
@Override
public int getVHU_Source_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_Source_ID);
}
/**
* VHUStatus AD_Reference_ID=540478
* Reference name: HUStatus
*/
public static final int VHUSTATUS_AD_Reference_ID=540478;
/** Planning = P */
public static final String VHUSTATUS_Planning = "P";
/** Active = A */
public static final String VHUSTATUS_Active = "A";
/** Destroyed = D */
public static final String VHUSTATUS_Destroyed = "D";
/** Picked = S */
public static final String VHUSTATUS_Picked = "S";
/** Shipped = E */
public static final String VHUSTATUS_Shipped = "E";
/** Issued = I */
public static final String VHUSTATUS_Issued = "I";
@Override
public void setVHUStatus (final java.lang.String VHUStatus)
{
set_ValueNoCheck (COLUMNNAME_VHUStatus, VHUStatus);
}
@Override
public java.lang.String getVHUStatus()
{
return get_ValueAsString(COLUMNNAME_VHUStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trace.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerDepartmentRepo
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<BPartnerId, List<BPartnerDepartment>> bPartnerDepartmentCache = CCache.newLRUCache(I_C_BPartner_Department.Table_Name + "#by#C_BPartner_ID", 200, 60);
@Nullable
public BPartnerDepartment getById(@NonNull final BPartnerDepartmentId id)
{
return getByBPartnerId(id.getBpartnerId())
.stream()
.filter(dpt -> id.equals(dpt.getId()))
.findFirst().orElse(null);
}
@NonNull
public BPartnerDepartment getByIdNotNull(@NonNull final BPartnerDepartmentId id)
{
return getByBPartnerId(id.getBpartnerId())
.stream()
.filter(dpt -> id.equals(dpt.getId()))
.findFirst().orElseThrow(() -> new AdempiereException("Missing BPartnerDepartment for id=" + id));
}
@NonNull
public List<BPartnerDepartment> getByBPartnerId(@NonNull final BPartnerId bPartnerId)
{
return bPartnerDepartmentCache.getOrLoad(bPartnerId, this::getByBPartnerId0);
}
private List<BPartnerDepartment> getByBPartnerId0(@NonNull final BPartnerId bPartnerId)
{ | return queryBL.createQueryBuilder(I_C_BPartner_Department.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner_Department.COLUMNNAME_C_BPartner_ID, bPartnerId)
.orderBy(I_C_BPartner_Department.COLUMNNAME_Value)
.create()
.stream()
.map(this::fromPO)
.collect(ImmutableList.toImmutableList());
}
private BPartnerDepartment fromPO(@NonNull final I_C_BPartner_Department po)
{
final BPartnerDepartmentId id = BPartnerDepartmentId.ofRepoId(po.getC_BPartner_ID(), po.getC_BPartner_Department_ID());
return new BPartnerDepartment(id, po.getValue(), po.getName(), po.getDescription());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\department\BPartnerDepartmentRepo.java | 2 |
请完成以下Java代码 | public List<VariableInstanceEntity> findVariableInstancesByProcessInstanceId(String processInstanceId) {
return getDbEntityManager().selectList("selectVariablesByProcessInstanceId", processInstanceId);
}
public List<VariableInstanceEntity> findVariableInstancesByCaseExecutionId(String caseExecutionId) {
return findVariableInstancesByCaseExecutionIdAndVariableNames(caseExecutionId, null);
}
@SuppressWarnings("unchecked")
public List<VariableInstanceEntity> findVariableInstancesByCaseExecutionIdAndVariableNames(String caseExecutionId, Collection<String> variableNames) {
Map<String, Object> parameter = new HashMap<String, Object>();
parameter.put("caseExecutionId", caseExecutionId);
parameter.put("variableNames", variableNames);
return getDbEntityManager().selectList("selectVariablesByCaseExecutionId", parameter);
}
public void deleteVariableInstanceByTask(TaskEntity task) {
List<VariableInstanceEntity> variableInstances = task.variableStore.getVariables();
for (VariableInstanceEntity variableInstance: variableInstances) {
variableInstance.delete();
}
}
public long findVariableInstanceCountByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery) { | configureQuery(variableInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectVariableInstanceCountByQueryCriteria", variableInstanceQuery);
}
@SuppressWarnings("unchecked")
public List<VariableInstance> findVariableInstanceByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery, Page page) {
configureQuery(variableInstanceQuery);
return getDbEntityManager().selectList("selectVariableInstanceByQueryCriteria", variableInstanceQuery, page);
}
protected void configureQuery(VariableInstanceQueryImpl query) {
getAuthorizationManager().configureVariableInstanceQuery(query);
getTenantManager().configureQuery(query);
}
@SuppressWarnings("unchecked")
public List<VariableInstanceEntity> findVariableInstancesByBatchId(String batchId) {
Map<String, String> parameters = Collections.singletonMap("batchId", batchId);
return getDbEntityManager().selectList("selectVariableInstancesByBatchId", parameters);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceManager.java | 1 |
请完成以下Java代码 | public String getUser(@PathVariable("id") String id) {
return "user";
}
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')")
@GetMapping("/users")
public String getUsers() {
return "users";
}
@GetMapping("v2/user/{id}")
public String getUserUsingSecurityContext() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
return "user";
}
throw new UnauthorizedException();
}
@GetMapping("v2/users")
public String getUsersUsingDetailsService() { | UserDetails details = userDetailsService.loadUserByUsername("mike");
if (details != null && details.getAuthorities().stream()
.anyMatch(a -> a.getAuthority().equals("ADMIN"))) {
return "users";
}
throw new UnauthorizedException();
}
@GetMapping("v3/users")
public String getUsers(HttpServletRequest request) {
if (request.isUserInRole("ROLE_ADMIN")) {
return "users";
}
throw new UnauthorizedException();
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\checkrolejava\UserController.java | 1 |
请完成以下Java代码 | public class ClassDelegateTaskListener extends ClassDelegate implements TaskListener {
public ClassDelegateTaskListener(String className, List<FieldDeclaration> fieldDeclarations) {
super(className, fieldDeclarations);
}
public ClassDelegateTaskListener(Class<?> clazz, List<FieldDeclaration> fieldDeclarations) {
super(clazz, fieldDeclarations);
}
public void notify(DelegateTask delegateTask) {
TaskListener taskListenerInstance = getTaskListenerInstance();
try {
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(new TaskListenerInvocation(taskListenerInstance, delegateTask));
}catch (Exception e) {
throw new ProcessEngineException("Exception while invoking TaskListener: "+e.getMessage(), e); | }
}
protected TaskListener getTaskListenerInstance() {
Object delegateInstance = instantiateDelegate(className, fieldDeclarations);
if (delegateInstance instanceof TaskListener) {
return (TaskListener) delegateInstance;
} else {
throw new ProcessEngineException(delegateInstance.getClass().getName()+" doesn't implement "+TaskListener.class);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\listener\ClassDelegateTaskListener.java | 1 |
请完成以下Java代码 | public static class Cors {
/**
* Enable/disable CORS filter.
*/
private boolean enabled = false;
/**
* Allow/disallow CORS credentials.
*/
private boolean allowCredentials = false;
/**
* Allowed CORS origins, use * for all, but not in production. Default empty.
*/
private Set<String> allowedOrigins;
/**
* Allowed CORS headers, use * for all, but not in production. Default empty.
*/
private Set<String> allowedHeaders;
/**
* Exposed CORS headers, use * for all, but not in production. Default empty.
*/
private Set<String> exposedHeaders;
/**
* Allowed CORS methods, use * for all, but not in production. Default empty.
*/
private Set<String> allowedMethods;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAllowCredentials() {
return allowCredentials;
}
public void setAllowCredentials(boolean allowCredentials) {
this.allowCredentials = allowCredentials;
} | public Set<String> getAllowedOrigins() {
return allowedOrigins == null ? Collections.emptySet() : allowedOrigins;
}
public void setAllowedOrigins(Set<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public Set<String> getAllowedHeaders() {
return allowedHeaders == null ? Collections.emptySet() : allowedHeaders;
}
public void setAllowedHeaders(Set<String> allowedHeaders) {
this.allowedHeaders = allowedHeaders;
}
public Set<String> getExposedHeaders() {
return exposedHeaders == null ? Collections.emptySet() : exposedHeaders;
}
public void setExposedHeaders(Set<String> exposedHeaders) {
this.exposedHeaders = exposedHeaders;
}
public Set<String> getAllowedMethods() {
return allowedMethods == null ? Collections.emptySet() : allowedMethods;
}
public void setAllowedMethods(Set<String> allowedMethods) {
this.allowedMethods = allowedMethods;
}
}
} | repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\RestAppProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WidgetsBundleDataValidator extends DataValidator<WidgetsBundle> {
private final WidgetsBundleDao widgetsBundleDao;
private final TenantService tenantService;
@Override
protected void validateDataImpl(TenantId tenantId, WidgetsBundle widgetsBundle) {
validateString("Widgets bundle title", widgetsBundle.getTitle());
if (widgetsBundle.getTenantId() == null) {
widgetsBundle.setTenantId(TenantId.fromUUID(ModelConstants.NULL_UUID));
}
if (!widgetsBundle.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
if (!tenantService.tenantExists(widgetsBundle.getTenantId())) {
throw new DataValidationException("Widgets bundle is referencing to non-existent tenant!");
}
}
}
@Override
protected void validateCreate(TenantId tenantId, WidgetsBundle widgetsBundle) {
String alias = widgetsBundle.getAlias();
if (alias == null || alias.trim().isEmpty()) {
alias = widgetsBundle.getTitle().toLowerCase().replaceAll("\\W+", "_");
}
String originalAlias = alias;
int c = 1;
WidgetsBundle withSameAlias;
do {
withSameAlias = widgetsBundleDao.findWidgetsBundleByTenantIdAndAlias(widgetsBundle.getTenantId().getId(), alias);
if (withSameAlias != null) { | alias = originalAlias + (++c);
}
} while (withSameAlias != null);
widgetsBundle.setAlias(alias);
}
@Override
protected WidgetsBundle validateUpdate(TenantId tenantId, WidgetsBundle widgetsBundle) {
WidgetsBundle storedWidgetsBundle = widgetsBundleDao.findById(tenantId, widgetsBundle.getId().getId());
if (!storedWidgetsBundle.getTenantId().getId().equals(widgetsBundle.getTenantId().getId())) {
throw new DataValidationException("Can't move existing widgets bundle to different tenant!");
}
if (!storedWidgetsBundle.getAlias().equals(widgetsBundle.getAlias())) {
throw new DataValidationException("Update of widgets bundle alias is prohibited!");
}
return storedWidgetsBundle;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\WidgetsBundleDataValidator.java | 2 |
请完成以下Java代码 | public class UserAuthQRCodeJsonConverter
{
public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("AUTH");
public static String toGlobalQRCodeJsonString(final UserAuthQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final UserAuthQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
@NonNull
public static UserAuthQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static UserAuthQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!isTypeMatching(globalQRCode))
{
throw new AdempiereException("Invalid QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long | }
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode)
{
return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\qr\UserAuthQRCodeJsonConverter.java | 1 |
请完成以下Java代码 | public boolean isDefaultOrderBy()
{
final DocumentFieldDataBindingDescriptor dataBinding = getDataBinding().orElse(null);
return dataBinding != null && dataBinding.isDefaultOrderBy();
}
public int getDefaultOrderByPriority()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().getDefaultOrderByPriority();
}
public boolean isDefaultOrderByAscending()
{
// we assume isDefaultOrderBy() was checked before calling this method
//noinspection OptionalGetWithoutIsPresent
return getDataBinding().get().isDefaultOrderByAscending();
}
public Builder deviceDescriptorsProvider(@NonNull final DeviceDescriptorsProvider deviceDescriptorsProvider) | {
this.deviceDescriptorsProvider = deviceDescriptorsProvider;
return this;
}
private DeviceDescriptorsProvider getDeviceDescriptorsProvider()
{
return deviceDescriptorsProvider;
}
public Builder mainAdFieldId(@Nullable final AdFieldId mainAdFieldId)
{
this.mainAdFieldId = mainAdFieldId;
return this;
}
@Nullable
public AdFieldId getMainAdFieldId() {return mainAdFieldId;}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected BeanDefinitionBuilder parseBinding(String exchangeName, Element binding, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(BindingFactoryBean.class);
Element argumentsElement = DomUtils.getChildElementByTagName(binding, BINDING_ARGUMENTS);
String key = binding.getAttribute("key");
String value = binding.getAttribute("value");
boolean hasKey = StringUtils.hasText(key);
boolean hasValue = StringUtils.hasText(value);
if (argumentsElement != null && (hasKey || hasValue)) {
parserContext.getReaderContext()
.error("'binding-arguments' sub-element and 'key/value' attributes are mutually exclusive.", binding);
}
parseDestination(binding, parserContext, builder);
if (hasKey ^ hasValue) {
parserContext.getReaderContext().error("Both 'key/value' attributes have to be declared.", binding);
} | if (argumentsElement == null) {
if (!hasKey & !hasValue) {
parserContext.getReaderContext()
.error("At least one of 'binding-arguments' sub-element or 'key/value' attributes pair have to be declared.", binding);
}
ManagedMap<TypedStringValue, TypedStringValue> map = new ManagedMap<>();
map.put(new TypedStringValue(key), new TypedStringValue(value));
builder.addPropertyValue("arguments", map);
}
builder.addPropertyValue("exchange", new TypedStringValue(exchangeName));
return builder;
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\HeadersExchangeParser.java | 2 |
请完成以下Java代码 | public void afterSave(final I_AD_Role role, final ModelChangeType changeType)
{
// services:
final IRoleDAO roleDAO = Services.get(IRoleDAO.class);
final RoleId roleId = RoleId.ofRepoId(role.getAD_Role_ID());
//
// Automatically assign new role to SuperUser and to the user who created it.
if (changeType.isNew() && !InterfaceWrapperHelper.isCopying(role))
{
// Add Role to SuperUser
roleDAO.createUserRoleAssignmentIfMissing(UserId.METASFRESH, roleId);
// Add Role to User which created this record
final UserId createdByUserId = UserId.ofRepoId(role.getCreatedBy());
if (!createdByUserId.equals(UserId.METASFRESH))
{
roleDAO.createUserRoleAssignmentIfMissing(createdByUserId, roleId);
}
}
//
// Update role access records
final boolean userLevelChange = InterfaceWrapperHelper.isValueChanged(role, I_AD_Role.COLUMNNAME_UserLevel);
final boolean notManual = !role.isManual();
if ((changeType.isNew() || userLevelChange) && notManual) | {
final UserId userId = UserId.ofRepoId(role.getUpdatedBy());
Services.get(IUserRolePermissionsDAO.class).updateAccessRecords(roleId, userId);
}
//
// Reset the cached role permissions after the transaction is commited.
// NOTE: not needed because it's performed automatically
// Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
} // afterSave
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteAccessRecords(final I_AD_Role role)
{
final RoleId roleId = RoleId.ofRepoId(role.getAD_Role_ID());
Services.get(IUserRolePermissionsDAO.class).deleteAccessRecords(roleId);
} // afterDelete
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Role.java | 1 |
请完成以下Java代码 | public ITrxConstraints setMaxTrx(final int max)
{
this.maxTrx = max;
return this;
}
@Override
public ITrxConstraints incMaxTrx(final int num)
{
this.maxTrx += num;
return this;
}
@Override
public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow)
{
this.allowTrxAfterThreadEnd = allow;
return this;
}
@Override
public int getMaxTrx()
{
return maxTrx;
}
@Override
public ITrxConstraints setMaxSavepoints(int maxSavepoints)
{
this.maxSavepoints = maxSavepoints;
return this;
}
@Override
public int getMaxSavepoints()
{
return maxSavepoints;
}
@Override
public ITrxConstraints setActive(boolean active)
{
this.active = active;
return this;
}
@Override
public boolean isActive()
{
return active;
}
@Override
public boolean isOnlyAllowedTrxNamePrefixes()
{
return onlyAllowedTrxNamePrefixes;
}
@Override
public ITrxConstraints setOnlyAllowedTrxNamePrefixes(boolean onlyAllowedTrxNamePrefixes)
{
this.onlyAllowedTrxNamePrefixes = onlyAllowedTrxNamePrefixes;
return this;
}
@Override
public ITrxConstraints addAllowedTrxNamePrefix(final String trxNamePrefix)
{
allowedTrxNamePrefixes.add(trxNamePrefix);
return this; | }
@Override
public ITrxConstraints removeAllowedTrxNamePrefix(final String trxNamePrefix)
{
allowedTrxNamePrefixes.remove(trxNamePrefix);
return this;
}
@Override
public Set<String> getAllowedTrxNamePrefixes()
{
return allowedTrxNamePrefixesRO;
}
@Override
public boolean isAllowTrxAfterThreadEnd()
{
return allowTrxAfterThreadEnd;
}
@Override
public void reset()
{
setActive(DEFAULT_ACTIVE);
setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END);
setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS);
setMaxTrx(DEFAULT_MAX_TRX);
setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY);
setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES);
allowedTrxNamePrefixes.clear();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("TrxConstraints[");
sb.append("active=" + this.active);
sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes());
sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd());
sb.append(", maxSavepoints=" + getMaxSavepoints());
sb.append(", maxTrx=" + getMaxTrx());
sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes());
sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly());
sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs());
sb.append("]");
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java | 1 |
请完成以下Java代码 | public synchronized void appendSqlStatement(@NonNull final Sql sqlStatement)
{
collectorFactory.collect(sqlStatement);
}
public synchronized void appendSqlStatements(@NonNull final SqlBatch sqlBatch)
{
sqlBatch.streamSqls().forEach(collectorFactory::collect);
}
private synchronized void appendNow(final String sqlStatements)
{
if (sqlStatements == null || sqlStatements.isEmpty())
{
return;
}
try
{
final Path path = getCreateFilePath();
FileUtil.writeString(path, sqlStatements, CHARSET, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} | catch (final IOException ex)
{
logger.error("Failed writing to {}:\n {}", this, sqlStatements, ex);
close(); // better to close the file ... so, next time a new one will be created
}
}
/**
* Close underling file.
* <p>
* Next time, {@link #appendSqlStatement(Sql)} will be called, a new file will be created, so it's safe to call this method as many times as needed.
*/
public synchronized void close()
{
watcher.addLog("Closed migration script: " + _path);
_path = null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
/**
* Ensures that Redis is configured to send keyspace notifications. This is important
* to ensure that expiration and deletion of sessions trigger SessionDestroyedEvents.
* Without the SessionDestroyedEvent resources may not get cleaned up properly. For
* example, the mapping of the Session to WebSocket connections may not get cleaned
* up.
*/
static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean {
private final RedisConnectionFactory connectionFactory;
private final ConfigureRedisAction configure;
EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory,
ConfigureRedisAction configure) {
this.connectionFactory = connectionFactory;
this.configure = configure;
}
@Override
public void afterPropertiesSet() {
if (this.configure == ConfigureRedisAction.NO_OP) {
return;
} | RedisConnection connection = this.connectionFactory.getConnection();
try {
this.configure.configure(connection);
}
finally {
try {
connection.close();
}
catch (Exception ex) {
LogFactory.getLog(getClass()).error("Error closing RedisConnection", ex);
}
}
}
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\RedisIndexedHttpSessionConfiguration.java | 2 |
请完成以下Java代码 | public void setUsernameParameter(String usernameParameter) {
Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
this.usernameParameter = usernameParameter;
}
/**
* Sets the parameter name which will be used to obtain the password from the login
* request.
* @param passwordParameter the parameter name. Defaults to "password".
*/
public void setPasswordParameter(String passwordParameter) {
Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
this.passwordParameter = passwordParameter;
}
/**
* Defines whether only HTTP POST requests will be allowed by this filter. If set to
* true, and an authentication request is received which is not a POST request, an
* exception will be raised immediately and authentication will not be attempted. The
* <tt>unsuccessfulAuthentication()</tt> method will be called as if handling a failed
* authentication. | * <p>
* Defaults to <tt>true</tt> but may be overridden by subclasses.
*/
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getUsernameParameter() {
return this.usernameParameter;
}
public final String getPasswordParameter() {
return this.passwordParameter;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\UsernamePasswordAuthenticationFilter.java | 1 |
请完成以下Java代码 | public FindAdvancedSearchTableModel getModel()
{
return (FindAdvancedSearchTableModel)super.getModel();
}
@Override
public void setModel(final TableModel dataModel)
{
Check.assumeInstanceOfOrNull(dataModel, FindAdvancedSearchTableModel.class, "dataModel");
super.setModel(dataModel);
}
public void stopEditor(final boolean saveValue)
{
CTable.stopEditor(this, saveValue);
}
private static class ProxyRenderer implements TableCellRenderer
{
public ProxyRenderer(TableCellRenderer renderer)
{
super();
this.delegate = renderer;
}
/** The renderer. */
private final TableCellRenderer delegate;
@Override
public Component getTableCellRendererComponent(final JTable table, Object value, boolean isSelected, boolean hasFocus, final int row, final int col)
{
final Component comp = delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
if (hasFocus && table.isCellEditable(row, col))
table.editCellAt(row, col);
return comp;
}
} // ProxyRenderer
/**
* Create a new row
*/
public void newRow()
{
stopEditor(true);
final FindAdvancedSearchTableModel model = getModel();
model.newRow();
final int rowIndex = model.getRowCount() - 1; | getSelectionModel().setSelectionInterval(rowIndex, rowIndex);
requestFocusInWindow();
}
public void deleteCurrentRow()
{
stopEditor(false);
final int rowIndex = getSelectedRow();
if (rowIndex >= 0)
{
final FindAdvancedSearchTableModel model = getModel();
model.removeRow(rowIndex);
// Select next row if possible
final int rowToSelect = Math.min(rowIndex, model.getRowCount() - 1);
if (rowToSelect >= 0)
{
getSelectionModel().setSelectionInterval(rowToSelect, rowToSelect);
}
}
requestFocusInWindow();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindAdvancedSearchTable.java | 1 |
请完成以下Java代码 | public boolean isProperty() {
return this.property != null;
}
/**
* Return the {@link VersionProperty} or {@code null} if this reference is not a
* property.
* @return the version property or {@code null}
*/
public VersionProperty getProperty() {
return this.property;
}
/**
* Return the version or {@code null} if this reference is backed by a property.
* @return the version or {@code null}
*/
public String getValue() {
return this.value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} | if (o == null || getClass() != o.getClass()) {
return false;
}
VersionReference that = (VersionReference) o;
return Objects.equals(this.property, that.property) && Objects.equals(this.value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.value);
}
@Override
public String toString() {
return (this.property != null) ? "${" + this.property.toStandardFormat() + "}" : this.value;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionReference.java | 1 |
请完成以下Java代码 | public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
startDate.datesUntil(endDate)
.forEach(this::processDate);
}
public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
processDate(date);
}
}
public void iterateBetweenDatesJava7(Date start, Date end) {
Date current = start;
while (current.before(end)) {
processDate(current); | Calendar calendar = Calendar.getInstance();
calendar.setTime(current);
calendar.add(Calendar.DATE, 1);
current = calendar.getTime();
}
}
private void processDate(LocalDate date) {
log.debug(date.toString());
}
private void processDate(Date date) {
log.debug(date.toString());
}
} | repos\tutorials-master\core-java-modules\core-java-9\src\main\java\com\baeldung\java9\rangedates\RangeDatesIteration.java | 1 |
请完成以下Java代码 | public List<Employee> getAllEmployees() {
return employeeRepository.getAllEmployees();
}
@GET
@Path("/{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Employee getEmployee(@PathParam("id") int id) {
return employeeRepository.getEmployee(id);
}
@PUT
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response updateEmployee(Employee employee, @PathParam("id") int id) {
employeeRepository.updateEmployee(employee, id);
return Response.status(Response.Status.OK.getStatusCode()).build();
} | @DELETE
@Path("/{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteEmployee(@PathParam("id") int id) {
employeeRepository.deleteEmployee(id);
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response addEmployee(Employee employee, @Context UriInfo uriInfo) {
employeeRepository.addEmployee(new Employee(employee.getId(), employee.getFirstName()));
return Response.status(Response.Status.CREATED.getStatusCode()).header("Location", String.format("%s/%s", uriInfo.getAbsolutePath().toString(), employee.getId())).build();
}
} | repos\tutorials-master\spring-web-modules\spring-jersey\src\main\java\com\baeldung\server\rest\EmployeeResource.java | 1 |
请完成以下Java代码 | public int getM_MovementConfirm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementConfirm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Movement getM_Movement() throws RuntimeException
{
return (I_M_Movement)MTable.get(getCtx(), I_M_Movement.Table_Name)
.getPO(getM_Movement_ID(), get_TrxName()); }
/** Set Inventory Move.
@param M_Movement_ID
Movement of Inventory
*/
public void setM_Movement_ID (int M_Movement_ID)
{
if (M_Movement_ID < 1)
set_Value (COLUMNNAME_M_Movement_ID, null);
else
set_Value (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID));
}
/** Get Inventory Move.
@return Movement of Inventory
*/
public int getM_Movement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null) | {
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementConfirm.java | 1 |
请完成以下Java代码 | public String getSql()
{
if (sqlOrderByCompiled)
{
return sqlOrderBy;
}
if (items != null && !items.isEmpty())
{
final StringBuilder sqlBuf = new StringBuilder();
for (final QueryOrderByItem item : items)
{
appendSql(sqlBuf, item);
}
sqlOrderBy = sqlBuf.toString();
}
else
{
sqlOrderBy = null;
}
sqlOrderByCompiled = true;
return sqlOrderBy;
}
// NOTE: not static just because we want to build nice exceptions
private void appendSql(final StringBuilder sql, final QueryOrderByItem item)
{
if (sql.length() > 0)
{
sql.append(", ");
}
//
// ColumnName
sql.append(item.getColumnName());
//
// Direction ASC/DESC
final Direction direction = item.getDirection();
if (direction == Direction.Ascending)
{
sql.append(" ASC");
}
else if (direction == Direction.Descending)
{
sql.append(" DESC");
}
else
{
throw new IllegalStateException("Unknown direction '" + direction + "' for " + this);
}
//
// Nulls First/Last | final Nulls nulls = item.getNulls();
if (nulls == Nulls.First)
{
sql.append(" NULLS FIRST");
}
else if (nulls == Nulls.Last)
{
sql.append(" NULLS LAST");
}
else
{
throw new IllegalStateException("Unknown NULLS option '" + nulls + "' for " + this);
}
}
@Override
public Comparator<Object> getComparator()
{
if (comparator != null)
{
return comparator;
}
if (items != null && !items.isEmpty())
{
final ComparatorChain<Object> cmpChain = new ComparatorChain<>();
for (final QueryOrderByItem item : items)
{
@SuppressWarnings("rawtypes")
final ModelAccessor<Comparable> accessor = new ModelAccessor<>(item.getColumnName());
final boolean reverse = item.getDirection() == Direction.Descending;
final Comparator<Object> cmpDirection = new AccessorComparator<>(
ComparableComparatorNullsEqual.getInstance(),
accessor);
cmpChain.addComparator(cmpDirection, reverse);
final boolean nullsFirst = item.getNulls() == Nulls.First;
final Comparator<Object> cmpNulls = new AccessorComparator<>(
ComparableComparator.getInstance(nullsFirst),
accessor);
cmpChain.addComparator(cmpNulls);
}
comparator = cmpChain;
}
else
{
comparator = NullComparator.getInstance();
}
return comparator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderBy.java | 1 |
请完成以下Java代码 | public class JpaOtaPackageInfoDao extends JpaAbstractDao<OtaPackageInfoEntity, OtaPackageInfo> implements OtaPackageInfoDao {
@Autowired
private OtaPackageInfoRepository otaPackageInfoRepository;
@Override
protected Class<OtaPackageInfoEntity> getEntityClass() {
return OtaPackageInfoEntity.class;
}
@Override
protected JpaRepository<OtaPackageInfoEntity, UUID> getRepository() {
return otaPackageInfoRepository;
}
@Override
public OtaPackageInfo findById(TenantId tenantId, UUID id) {
return DaoUtil.getData(otaPackageInfoRepository.findOtaPackageInfoById(id));
}
@Transactional
@Override
public OtaPackageInfo save(TenantId tenantId, OtaPackageInfo otaPackageInfo) {
OtaPackageInfo savedOtaPackage = super.save(tenantId, otaPackageInfo);
if (otaPackageInfo.getId() == null) {
return savedOtaPackage;
} else {
return findById(tenantId, savedOtaPackage.getId().getId());
}
}
@Override
public PageData<OtaPackageInfo> findOtaPackageInfoByTenantId(TenantId tenantId, PageLink pageLink) { | return DaoUtil.toPageData(otaPackageInfoRepository
.findAllByTenantId(
tenantId.getId(),
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<OtaPackageInfo> findOtaPackageInfoByTenantIdAndDeviceProfileIdAndTypeAndHasData(TenantId tenantId, DeviceProfileId deviceProfileId, OtaPackageType otaPackageType, PageLink pageLink) {
return DaoUtil.toPageData(otaPackageInfoRepository
.findAllByTenantIdAndTypeAndDeviceProfileIdAndHasData(
tenantId.getId(),
deviceProfileId.getId(),
otaPackageType,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public boolean isOtaPackageUsed(OtaPackageId otaPackageId, OtaPackageType otaPackageType, DeviceProfileId deviceProfileId) {
return otaPackageInfoRepository.isOtaPackageUsed(otaPackageId.getId(), deviceProfileId.getId(), otaPackageType.name());
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\ota\JpaOtaPackageInfoDao.java | 1 |
请完成以下Java代码 | public String getType() {
return TYPE;
}
public void execute(BatchSeedJobConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) {
String batchId = configuration.getBatchId();
BatchEntity batch = commandContext.getBatchManager().findBatchById(batchId);
ensureNotNull("Batch with id '" + batchId + "' cannot be found", "batch", batch);
BatchJobHandler<?> batchJobHandler = commandContext
.getProcessEngineConfiguration()
.getBatchHandlers()
.get(batch.getType());
boolean done = batchJobHandler.createJobs(batch);
if (!done) {
batch.createSeedJob();
}
else {
// create monitor job initially without due date to
// enable rapid completion of simple batches
batch.createMonitorJob(false);
}
}
@Override
public BatchSeedJobConfiguration newConfiguration(String canonicalString) {
return new BatchSeedJobConfiguration(canonicalString);
}
public static class BatchSeedJobConfiguration implements JobHandlerConfiguration {
protected String batchId; | public BatchSeedJobConfiguration(String batchId) {
this.batchId = batchId;
}
public String getBatchId() {
return batchId;
}
@Override
public String toCanonicalString() {
return batchId;
}
}
public void onDelete(BatchSeedJobConfiguration configuration, JobEntity jobEntity) {
// do nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchSeedJobHandler.java | 1 |
请完成以下Java代码 | public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId; | }
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[taskId" + taskId
+ ", assignee=" + assignee
+ ", owner=" + owner
+ ", name=" + name
+ ", description=" + description
+ ", dueDate=" + dueDate
+ ", followUpDate=" + followUpDate
+ ", priority=" + priority
+ ", parentTaskId=" + parentTaskId
+ ", deleteReason=" + deleteReason
+ ", taskDefinitionKey=" + taskDefinitionKey
+ ", durationInMillis=" + durationInMillis
+ ", startTime=" + startTime
+ ", endTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", activityInstanceId=" + activityInstanceId
+ ", tenantId=" + tenantId
+ ", taskState=" + taskState
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricTaskInstanceEventEntity.java | 1 |
请完成以下Java代码 | public String getHtmlText()
{
return m_text;
} // getHTMLText
/**
* Set Html Text
* @param htmlText
*/
public void setHtmlText (String htmlText)
{
m_text = htmlText;
editorPane.setText(htmlText);
} // setHTMLText
/**************************************************************************
* Test
* @param args ignored
*/
public static void main (String[] args)
{
Adempiere.startupEnvironment(true);
JFrame frame = new JFrame("test");
frame.setVisible(true);
String text = "<html><p>this is a line<br>with <b>bold</> info</html>";
int i = 0;
while (true)
{
HTMLEditor ed = new HTMLEditor (frame, "heading " + ++i, text, true);
text = ed.getHtmlText();
}
} // main
// metas: begin
public HTMLEditor (Frame owner, String title, String htmlText, boolean editable, GridField gridField)
{
super (owner, title == null ? Msg.getMsg(Env.getCtx(), "Editor") : title, true);
BoilerPlateMenu.createFieldMenu(editorPane, null, gridField);
init(owner, htmlText, editable);
}
// metas: end
} // HTMLEditor
/******************************************************************************
* HTML Editor Menu Action
*/
class HTMLEditor_MenuAction
{
public HTMLEditor_MenuAction(String name, HTMLEditor_MenuAction[] subMenus)
{
m_name = name;
m_subMenus = subMenus; | }
public HTMLEditor_MenuAction(String name, String actionName)
{
m_name = name;
m_actionName = actionName;
}
public HTMLEditor_MenuAction(String name, Action action)
{
m_name = name;
m_action = action;
}
private String m_name;
private String m_actionName;
private Action m_action;
private HTMLEditor_MenuAction[] m_subMenus;
public boolean isSubMenu()
{
return m_subMenus != null;
}
public boolean isAction()
{
return m_action != null;
}
public String getName()
{
return m_name;
}
public HTMLEditor_MenuAction[] getSubMenus()
{
return m_subMenus;
}
public String getActionName()
{
return m_actionName;
}
public Action getAction()
{
return m_action;
}
} // MenuAction | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\HTMLEditor.java | 1 |
请完成以下Java代码 | public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public ProcessInstanceQueryDto getProcessInstanceQuery() {
return processInstanceQuery;
}
public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) {
this.processInstanceQuery = processInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public Batch updateSuspensionStateAsync(ProcessEngine engine) {
int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery);
if (params == 0) {
String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine);
if (getSuspended()) {
return updateSuspensionStateBuilder.suspendAsync();
} else {
return updateSuspensionStateBuilder.activateAsync();
}
}
protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) {
UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState();
UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null; | if (processInstanceIds != null) {
groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds);
}
if (processInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
} else {
groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine));
}
}
if (historicProcessInstanceQuery != null) {
if (groupBuilder == null) {
groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
} else {
groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine));
}
}
return groupBuilder;
}
protected int parameterCount(Object... o) {
int count = 0;
for (Object o1 : o) {
count += (o1 != null ? 1 : 0);
}
return count;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateAsyncDto.java | 1 |
请完成以下Java代码 | private AttachmentEntry attachCsvToRecord(
@NonNull final List<String> csvLines,
@NonNull final String attachmentFileName,
@NonNull final Object targetRecordModel)
{
// thx to https://stackoverflow.com/a/5619144/1012103
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream out = new DataOutputStream(baos);
for (final String csvLine : csvLines)
{
writeLineToStream(csvLine, out);
}
final byte[] byteArray = baos.toByteArray();
return attachmentEntryService.createNewAttachment(
TableRecordReference.of(targetRecordModel),
attachmentFileName,
byteArray);
}
private void writeLineToStream(
@NonNull final String csvLine,
@NonNull final DataOutputStream dataOutputStream)
{
try
{
final byte[] bytes = (csvLine + "\n").getBytes(DerKurierConstants.CSV_DATA_CHARSET);
dataOutputStream.write(bytes);
}
catch (final IOException e)
{
throw new AdempiereException("IOException writing cvsLine to dataOutputStream", e).appendParametersToMessage()
.setParameter("csvLine", csvLine) | .setParameter("dataOutputStream", dataOutputStream);
}
}
public static LinkedHashSet<String> readLinesFromArray(@NonNull final byte[] bytes)
{
final InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(bytes), DerKurierConstants.CSV_DATA_CHARSET);
try (final BufferedReader bufferedReader = new BufferedReader(inputStreamReader))
{
final LinkedHashSet<String> result = new LinkedHashSet<>();
for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine())
{
result.add(line);
}
return result;
}
catch (IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierDeliveryOrderService.java | 1 |
请完成以下Java代码 | public void postConstruct()
{
Services.get(IAttributeStorageFactoryService.class).addAttributeStorageListener(this);
}
@Override
public void onAttributeValueChanged(
@NonNull final IAttributeValueContext attributeValueContext,
@NonNull final IAttributeStorage storage,
final IAttributeValue attributeValue,
final Object valueOld_NOTUSED)
{
final AbstractHUAttributeStorage huAttributeStorage = AbstractHUAttributeStorage.castOrNull(storage);
final boolean storageIsAboutHUs = huAttributeStorage != null;
if (!storageIsAboutHUs)
{
return;
}
final boolean relevantAttributesArePresent = storage.hasAttribute(AttributeConstants.ATTR_MonthsUntilExpiry)
&& storage.hasAttribute(AttributeConstants.ATTR_BestBeforeDate);
if (!relevantAttributesArePresent)
{
return;
}
final AttributeCode attributeCode = attributeValue.getAttributeCode();
final boolean relevantAttributeHasChanged = AttributeConstants.ATTR_BestBeforeDate.equals(attributeCode);
if (!relevantAttributeHasChanged)
{ | return;
}
final LocalDate today = SystemTime.asLocalDate();
final OptionalInt monthsUntilExpiry = UpdateMonthsUntilExpiryCommand.computeMonthsUntilExpiry(storage, today);
if (monthsUntilExpiry.isPresent())
{
storage.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, monthsUntilExpiry.getAsInt());
}
else
{
storage.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\MonthsUntilExpiryAttributeStorageListener.java | 1 |
请完成以下Java代码 | public String getCountry() {
return super.getCountry();
}
@Schema(description = "State", example = "NY")
@Override
public String getState() {
return super.getState();
}
@Schema(description = "City", example = "New York")
@Override
public String getCity() {
return super.getCity();
}
@Schema(description = "Address Line 1", example = "42 Broadway Suite 12-400")
@Override
public String getAddress() {
return super.getAddress();
}
@Schema(description = "Address Line 2", example = "")
@Override
public String getAddress2() {
return super.getAddress2();
}
@Schema(description = "Zip code", example = "10004")
@Override
public String getZip() {
return super.getZip();
}
@Schema(description = "Phone number", example = "+1(415)777-7777")
@Override
public String getPhone() {
return super.getPhone();
}
@Schema(description = "Email", example = "example@company.com")
@Override
public String getEmail() {
return super.getEmail();
}
@Schema(description = "Additional parameters of the device", implementation = com.fasterxml.jackson.databind.JsonNode.class) | @Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Tenant [title=");
builder.append(title);
builder.append(", region=");
builder.append(region);
builder.append(", tenantProfileId=");
builder.append(tenantProfileId);
builder.append(", additionalInfo=");
builder.append(getAdditionalInfo());
builder.append(", country=");
builder.append(country);
builder.append(", state=");
builder.append(state);
builder.append(", city=");
builder.append(city);
builder.append(", address=");
builder.append(address);
builder.append(", address2=");
builder.append(address2);
builder.append(", zip=");
builder.append(zip);
builder.append(", phone=");
builder.append(phone);
builder.append(", email=");
builder.append(email);
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Tenant.java | 1 |
请完成以下Java代码 | public class AdempiereSystemError extends Exception
{
/**
*
*/
private static final long serialVersionUID = 9111445784263763938L;
/**
* Adempiere System Error
* @param message message
*/
public AdempiereSystemError (String message)
{
super (message);
} // AdempiereSystemError
/**
* Adempiere System Error
* @param message message
* @param detail detail
*/
public AdempiereSystemError (String message, Object detail)
{
super (message);
setDetail (detail);
} // AdempiereSystemError
/**
* Adempiere System Error
* @param message
* @param cause
*/
public AdempiereSystemError (String message, Throwable cause)
{
super (message, cause);
} // AdempiereSystemError | /** Details */
private Object m_detail = null;
/**
* @return Returns the detail.
*/
public Object getDetail ()
{
return m_detail;
}
/**
* @param detail The detail to set.
*/
public void setDetail (Object detail)
{
m_detail = detail;
}
/**
* String Representation
* @return info
*/
public String toString ()
{
super.toString();
StringBuffer sb = new StringBuffer ("SystemError: ");
sb.append(getLocalizedMessage());
if (m_detail != null)
sb.append(" (").append(m_detail).append (")");
return sb.toString ();
} // toString
} // AdempiereSystemError | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AdempiereSystemError.java | 1 |
请完成以下Java代码 | public Color getTitleBackgroundColor()
{
return titleBackgroundColor;
}
/**
* Set background color of title
*
* @param titleBackgroundColor
*/
public void setTitleBackgroundColor(final Color titleBackgroundColor)
{
this.titleBackgroundColor = titleBackgroundColor;
}
/**
* Set title of the section
*
* @param title
*/
public void setTitle(final String title)
{
if (link != null)
{
link.setText(title);
}
}
/**
*
* @return collapsible pane
*/
public JXCollapsiblePane getCollapsiblePane()
{
return collapsible;
}
public JComponent getContentPane()
{
return (JComponent)getCollapsiblePane().getContentPane();
}
public void setContentPane(JComponent contentPanel)
{
getCollapsiblePane().setContentPane(contentPanel);
}
/**
* The border between the stack components. It separates each component with a fine line border.
*/
class SeparatorBorder implements Border
{
boolean isFirst(final Component c)
{
return c.getParent() == null || c.getParent().getComponent(0) == c;
}
@Override
public Insets getBorderInsets(final Component c)
{
// if the collapsible is collapsed, we do not want its border to be
// painted.
if (c instanceof JXCollapsiblePane)
{
if (((JXCollapsiblePane)c).isCollapsed())
{
return new Insets(0, 0, 0, 0);
}
}
return new Insets(4, 0, 1, 0);
}
@Override
public boolean isBorderOpaque()
{
return true;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height)
{
// if the collapsible is collapsed, we do not want its border to be painted.
if (c instanceof JXCollapsiblePane) | {
if (((JXCollapsiblePane)c).isCollapsed())
{
return;
}
}
g.setColor(getSeparatorColor());
if (isFirst(c))
{
g.drawLine(x, y + 2, x + width, y + 2);
}
g.drawLine(x, y + height - 1, x + width, y + height - 1);
}
}
@Override
public final Component add(final Component comp)
{
return collapsible.add(comp);
}
public final void setCollapsed(final boolean collapsed)
{
collapsible.setCollapsed(collapsed);
}
public final void setCollapsible(final boolean collapsible)
{
this.toggleAction.setEnabled(collapsible);
if (!collapsible)
{
this.collapsible.setCollapsed(false);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CollapsiblePanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BatchPartBuilder status(String status) {
if (status == null) {
throw new FlowableIllegalArgumentException("status is null");
}
this.status = status;
return this;
}
@Override
public BatchPartBuilder scopeId(String scopeId) {
if (scopeId == null) {
throw new FlowableIllegalArgumentException("scopeId is null");
}
this.scopeId = scopeId;
return this;
}
@Override
public BatchPartBuilder subScopeId(String subScopeId) {
if (subScopeId == null) {
throw new FlowableIllegalArgumentException("subScopeId is null");
}
this.subScopeId = subScopeId;
return this;
}
@Override
public BatchPartBuilder scopeType(String scopeType) {
if (scopeType == null) {
throw new FlowableIllegalArgumentException("scopeType is null");
}
this.scopeType = scopeType;
return this;
}
@Override
public BatchPart create() {
if (batch == null) {
throw new FlowableIllegalArgumentException("batch has to be provided");
} | if (type == null) {
throw new FlowableIllegalArgumentException("type has to be provided");
}
if (commandExecutor != null) {
return commandExecutor.execute(commandContext -> createSafe());
} else {
return createSafe();
}
}
protected BatchPart createSafe() {
BatchPartEntityManager partEntityManager = batchServiceConfiguration.getBatchPartEntityManager();
BatchPartEntity batchPart = partEntityManager.create();
batchPart.setBatchId(batch.getId());
batchPart.setBatchType(batch.getBatchType());
batchPart.setBatchSearchKey(batch.getBatchSearchKey());
batchPart.setBatchSearchKey2(batch.getBatchSearchKey2());
if (batch.getTenantId() != null) {
batchPart.setTenantId(batch.getTenantId());
}
batchPart.setType(type);
batchPart.setSearchKey(searchKey);
batchPart.setSearchKey2(searchKey2);
batchPart.setStatus(status);
batchPart.setScopeId(scopeId);
batchPart.setSubScopeId(subScopeId);
batchPart.setScopeType(scopeType);
batchPart.setCreateTime(batchServiceConfiguration.getClock().getCurrentTime());
partEntityManager.insert(batchPart);
return batchPart;
}
} | repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\BatchPartBuilderImpl.java | 2 |
请完成以下Java代码 | public C_Aggregation_Builder setIsDefault(final boolean isDefault)
{
this.isDefault = isDefault;
return this;
}
public C_Aggregation_Builder setIsDefaultSO(final boolean isDefaultSO)
{
this.isDefaultSO = isDefaultSO;
return this;
}
public C_Aggregation_Builder setIsDefaultPO(final boolean isDefaultPO)
{
this.isDefaultPO = isDefaultPO;
return this;
}
public C_Aggregation_Builder setAggregationUsageLevel(final String aggregationUsageLevel) | {
this.aggregationUsageLevel = aggregationUsageLevel;
return this;
}
public C_AggregationItem_Builder newItem()
{
if (adTableId <= 0)
{
throw new AdempiereException("Before creating a new item, a adTableId needs to be set to the builder")
.appendParametersToMessage()
.setParameter("C_Aggregation_Builder", this);
}
final C_AggregationItem_Builder itemBuilder = new C_AggregationItem_Builder(this, AdTableId.ofRepoId(adTableId));
itemBuilders.add(itemBuilder);
return itemBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_Aggregation_Builder.java | 1 |
请完成以下Java代码 | public class OrderPricingHUDocumentHandler implements IHUDocumentHandler
{
/**
* Suggests the {@link I_M_HU_PI_Item_Product} for Order Quick Input
*/
@Override
public I_M_HU_PI_Item_Product getM_HU_PI_ItemProductFor(final Object orderObj, final ProductId productId)
{
Check.assumeInstanceOf(orderObj, I_C_Order.class, "orderObj not null");
final I_C_Order order = InterfaceWrapperHelper.create(orderObj, I_C_Order.class);
final I_M_PriceList_Version plv = Services.get(IOrderBL.class).getPriceListVersion(order);
final I_M_ProductPrice productPrice = ProductPrices.newQuery(plv)
.setProductId(productId)
.onlyAttributePricing()
.onlyValidPrices(true)
.retrieveDefault(I_M_ProductPrice.class);
if (productPrice != null)
{ | final HUPIItemProductId packingMaterialId = HUPIItemProductId.ofRepoIdOrNull(productPrice.getM_HU_PI_Item_Product_ID());
if (packingMaterialId != null)
{
return Services.get(IHUPIItemProductDAO.class).getRecordById(packingMaterialId);
}
}
return null;
}
@Override
public void applyChangesFor(final Object document)
{
// Nothing to do for order.
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pricing\spi\impl\OrderPricingHUDocumentHandler.java | 1 |
请完成以下Java代码 | private static class ProcessDefinitionGroup {
String key;
String tenant;
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProcessDefinitionGroup other = (ProcessDefinitionGroup) obj; | if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (tenant == null) {
if (other.tenant != null)
return false;
} else if (!tenant.equals(other.tenant))
return false;
return true;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteProcessDefinitionsByIdsCmd.java | 1 |
请完成以下Java代码 | /* package */class IC_ApproveForInvoicing_Action extends ExecutableSideAction
{
// services
private final transient IMsgBL msgBL = Services.get(IMsgBL.class);
private final transient IClientUI clientUI = Services.get(IClientUI.class);
// messages
private static final String MSG_Root = "C_Invoice_Candidate.SideActions.ApproveForInvoicing.";
private static final String MSG_DisplayName = MSG_Root + "title";
private static final String MSG_DoYouWantToUpdate_1P = MSG_Root + "DoYouWantToUpdate";
// parameters
private final GridTab gridTab;
private final int windowNo;
private final String displayName;
private boolean running = false;
public IC_ApproveForInvoicing_Action(final GridTab gridTab)
{
super();
Check.assumeNotNull(gridTab, "gridTab not null");
this.gridTab = gridTab;
windowNo = gridTab.getWindowNo();
displayName = msgBL.translate(Env.getCtx(), MSG_DisplayName);
}
@Override
public String getDisplayName()
{
return displayName;
}
/**
* @return true if this action is currently running
*/
public final boolean isRunning()
{
return running;
}
@Override
public void execute()
{
running = true;
try
{
execute0();
}
finally
{
running = false;
}
}
private void execute0()
{
final IQuery<I_C_Invoice_Candidate> query = retrieveInvoiceCandidatesToApproveQuery()
.create();
//
// Fail if there is nothing to update
final int countToUpdate = query.count();
if (countToUpdate <= 0)
{
throw new AdempiereException("@NoSelection@"); | }
//
// Ask user if we shall updated
final boolean doUpdate = clientUI.ask()
.setParentWindowNo(windowNo)
.setAdditionalMessage(msgBL.getMsg(Env.getCtx(), MSG_DoYouWantToUpdate_1P, new Object[] { countToUpdate }))
.setDefaultAnswer(false)
.getAnswer();
if (!doUpdate)
{
return;
}
//
// Update selected invoice candidates and mark them as approved for invoicing
final int countUpdated = query.update(new IQueryUpdater<I_C_Invoice_Candidate>()
{
@Override
public boolean update(final I_C_Invoice_Candidate ic)
{
ic.setApprovalForInvoicing(true);
return MODEL_UPDATED;
}
});
//
// Refresh rows, because they were updated
if (countUpdated > 0)
{
gridTab.dataRefreshAll();
}
//
// Inform the user
clientUI.info(windowNo,
"Updated", // AD_Message/title
"#" + countUpdated // message
);
}
private final IQueryBuilder<I_C_Invoice_Candidate> retrieveInvoiceCandidatesToApproveQuery()
{
return gridTab.createQueryBuilder(I_C_Invoice_Candidate.class)
.addOnlyActiveRecordsFilter()
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, true) // not processed
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_ApprovalForInvoicing, true) // not already approved
;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\IC_ApproveForInvoicing_Action.java | 1 |
请完成以下Java代码 | protected void createErrorStartEventDefinition(ErrorEventDefinition errorEventDefinition, ActivityImpl startEventActivity, ScopeImpl scope) {
org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition definition = new org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition(startEventActivity.getId());
if (StringUtils.isNotEmpty(errorEventDefinition.getErrorCode())) {
definition.setErrorCode(errorEventDefinition.getErrorCode());
}
definition.setPrecedence(10);
addErrorEventDefinition(definition, scope);
}
public void createBoundaryErrorEventDefinition(ErrorEventDefinition errorEventDefinition, boolean interrupting,
ActivityImpl activity, ActivityImpl nestedErrorEventActivity) {
nestedErrorEventActivity.setProperty("type", "boundaryError");
ScopeImpl catchingScope = nestedErrorEventActivity.getParent();
((ActivityImpl) catchingScope).setScope(true);
org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition definition = new org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition(nestedErrorEventActivity.getId());
definition.setErrorCode(errorEventDefinition.getErrorCode());
addErrorEventDefinition(definition, catchingScope); | }
@SuppressWarnings("unchecked")
protected void addErrorEventDefinition(org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition errorEventDefinition, ScopeImpl catchingScope) {
List<org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition> errorEventDefinitions = (List<org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition>) catchingScope.getProperty(PROPERTYNAME_ERROR_EVENT_DEFINITIONS);
if (errorEventDefinitions == null) {
errorEventDefinitions = new ArrayList<>();
catchingScope.setProperty(PROPERTYNAME_ERROR_EVENT_DEFINITIONS, errorEventDefinitions);
}
errorEventDefinitions.add(errorEventDefinition);
Collections.sort(errorEventDefinitions, org.activiti.engine.impl.bpmn.parser.ErrorEventDefinition.comparator);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\ErrorEventDefinitionParseHandler.java | 1 |
请完成以下Java代码 | public class BoundaryMessageEventActivityBehavior extends BoundaryEventActivityBehavior {
private static final long serialVersionUID = 1L;
private final MessageEventDefinition messageEventDefinition;
private final MessageExecutionContext messageExecutionContext;
public BoundaryMessageEventActivityBehavior(
MessageEventDefinition messageEventDefinition,
boolean interrupting,
MessageExecutionContext messageExecutionContext
) {
super(interrupting);
this.messageEventDefinition = messageEventDefinition;
this.messageExecutionContext = messageExecutionContext;
}
@Override
public void execute(DelegateExecution execution) {
CommandContext commandContext = Context.getCommandContext();
ExecutionEntity executionEntity = (ExecutionEntity) execution;
MessageEventSubscriptionEntity messageEvent = messageExecutionContext.createMessageEventSubscription(
commandContext,
executionEntity
);
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext
.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createMessageWaitingEvent(
executionEntity,
messageEvent.getEventName(),
messageEvent.getConfiguration()
)
);
}
}
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement();
// Should we use triggerName and triggerData, because message name expression can change?
String messageName = messageExecutionContext.getMessageName(execution);
if (boundaryEvent.isCancelActivity()) {
EventSubscriptionEntityManager eventSubscriptionEntityManager = | Context.getCommandContext().getEventSubscriptionEntityManager();
List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();
for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
if (
eventSubscription instanceof MessageEventSubscriptionEntity &&
eventSubscription.getEventName().equals(messageName)
) {
eventSubscriptionEntityManager.delete(eventSubscription);
}
}
}
super.trigger(executionEntity, triggerName, triggerData);
}
public MessageEventDefinition getMessageEventDefinition() {
return messageEventDefinition;
}
public MessageExecutionContext getMessageExecutionContext() {
return messageExecutionContext;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\BoundaryMessageEventActivityBehavior.java | 1 |
请完成以下Java代码 | public void springHandleNotFound(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.NOT_FOUND.value());
}
/*@ExceptionHandler(BookNotFoundException.class)
public ResponseEntity<CustomErrorResponse> customHandleNotFound(Exception ex, WebRequest request) {
CustomErrorResponse errors = new CustomErrorResponse();
errors.setTimestamp(LocalDateTime.now());
errors.setError(ex.getMessage());
errors.setStatus(HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(errors, HttpStatus.NOT_FOUND);
}*/
@ExceptionHandler(BookUnSupportedFieldPatchException.class)
public void springUnSupportedFieldPatch(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
}
// @Validate For Validating Path Variables and Request Parameters
@ExceptionHandler(ConstraintViolationException.class)
public void constraintViolationException(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
// error handle for @Valid | @Override
protected ResponseEntity<Object>
handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
//Map<String, String> fieldErrors = ex.getBindingResult().getFieldErrors().stream().collect(
// Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
}
} | repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\error\CustomGlobalExceptionHandler.java | 1 |
请完成以下Java代码 | public RepetitionRule getRepetitionRule() {
return repetitionRuleChild.getChild(this);
}
public void setRepetitionRule(RepetitionRule repetitionRule) {
repetitionRuleChild.setChild(this, repetitionRule);
}
public RequiredRule getRequiredRule() {
return requiredRuleChild.getChild(this);
}
public void setRequiredRule(RequiredRule requiredRule) {
requiredRuleChild.setChild(this, requiredRule);
}
public ManualActivationRule getManualActivationRule() {
return manualActivationRuleChild.getChild(this);
}
public void setManualActivationRule(ManualActivationRule manualActivationRule) {
manualActivationRuleChild.setChild(this, manualActivationRule);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemControl.class, CMMN_ELEMENT_PLAN_ITEM_CONTROL)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class) | .instanceProvider(new ModelTypeInstanceProvider<PlanItemControl>() {
public PlanItemControl newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanItemControlImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
repetitionRuleChild = sequenceBuilder.element(RepetitionRule.class)
.build();
requiredRuleChild = sequenceBuilder.element(RequiredRule.class)
.build();
manualActivationRuleChild = sequenceBuilder.element(ManualActivationRule.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemControlImpl.java | 1 |
请完成以下Java代码 | public class MyDtoIgnoreField {
private String stringValue;
@JsonIgnore
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreField() {
super();
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue; | }
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
} | repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\ignore\MyDtoIgnoreField.java | 1 |
请完成以下Java代码 | protected static String getExpressionLanguage(DmnElementTransformContext context, String expressionLanguage) {
if (expressionLanguage != null) {
return expressionLanguage;
}
else {
return getGlobalExpressionLanguage(context);
}
}
protected static String getGlobalExpressionLanguage(DmnElementTransformContext context) {
String expressionLanguage = context.getModelInstance().getDefinitions().getExpressionLanguage();
if (!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14.equals(expressionLanguage) &&
!DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15.equals(expressionLanguage)) {
return expressionLanguage;
}
else {
return null;
}
}
public static String getExpression(LiteralExpression expression) {
return getExpression(expression.getText());
} | public static String getExpression(UnaryTests expression) {
return getExpression(expression.getText());
}
protected static String getExpression(Text text) {
if (text != null) {
String textContent = text.getTextContent();
if (textContent != null && !textContent.isEmpty()) {
return textContent;
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnExpressionTransformHelper.java | 1 |
请完成以下Java代码 | public PreInvocationAttribute createPreInvocationAttribute(String preFilterAttribute, String filterObject,
String preAuthorizeAttribute) {
try {
// TODO: Optimization of permitAll
ExpressionParser parser = getParser();
Expression preAuthorizeExpression = (preAuthorizeAttribute != null)
? parser.parseExpression(preAuthorizeAttribute) : parser.parseExpression("permitAll");
Expression preFilterExpression = (preFilterAttribute != null) ? parser.parseExpression(preFilterAttribute)
: null;
return new PreInvocationExpressionAttribute(preFilterExpression, filterObject, preAuthorizeExpression);
}
catch (ParseException ex) {
throw new IllegalArgumentException("Failed to parse expression '" + ex.getExpressionString() + "'", ex);
}
}
@Override
public @Nullable PostInvocationAttribute createPostInvocationAttribute(String postFilterAttribute,
String postAuthorizeAttribute) {
try {
ExpressionParser parser = getParser();
Expression postAuthorizeExpression = (postAuthorizeAttribute != null)
? parser.parseExpression(postAuthorizeAttribute) : null;
Expression postFilterExpression = (postFilterAttribute != null)
? parser.parseExpression(postFilterAttribute) : null;
if (postFilterExpression != null || postAuthorizeExpression != null) {
return new PostInvocationExpressionAttribute(postFilterExpression, postAuthorizeExpression);
}
}
catch (ParseException ex) {
throw new IllegalArgumentException("Failed to parse expression '" + ex.getExpressionString() + "'", ex);
}
return null;
} | /**
* Delay the lookup of the {@link ExpressionParser} to prevent SEC-2136
* @return
*/
private ExpressionParser getParser() {
if (this.parser != null) {
return this.parser;
}
synchronized (this.parserLock) {
this.parser = this.handler.getExpressionParser();
this.handler = null;
}
return this.parser;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\expression\method\ExpressionBasedAnnotationAttributeFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EngineConfigurationConfigurer<SpringIdmEngineConfiguration> ldapIdmEngineConfigurer(LDAPConfiguration ldapConfiguration) {
return idmEngineConfiguration -> idmEngineConfiguration
.setIdmIdentityService(new LDAPIdentityServiceImpl(ldapConfiguration,
createCache(idmEngineConfiguration, ldapConfiguration), idmEngineConfiguration));
}
// We need a custom AuthenticationProvider for the LDAP Support
// since the default (DaoAuthenticationProvider) from Spring Security
// uses a Password encoder to perform the matching and we need to use
// the IdmIdentityService for LDAP
@Bean
@ConditionalOnMissingBean(AuthenticationProvider.class)
public FlowableAuthenticationProvider flowableAuthenticationProvider(IdmIdentityService idmIdentitySerivce,
UserDetailsService userDetailsService) {
return new FlowableAuthenticationProvider(idmIdentitySerivce, userDetailsService);
} | protected LDAPGroupCache createCache(SpringIdmEngineConfiguration engineConfiguration, LDAPConfiguration ldapConfiguration) {
LDAPGroupCache ldapGroupCache = null;
if (ldapConfiguration.getGroupCacheSize() > 0) {
// We need to use a supplier for the clock as the clock would be created later
ldapGroupCache = new LDAPGroupCache(ldapConfiguration.getGroupCacheSize(),
ldapConfiguration.getGroupCacheExpirationTime(), engineConfiguration::getClock);
if (ldapConfiguration.getGroupCacheListener() != null) {
ldapGroupCache.setLdapCacheListener(ldapConfiguration.getGroupCacheListener());
}
}
return ldapGroupCache;
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ldap\FlowableLdapAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PrimaryConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
public Map<String, Object> getVendorProperties() {
return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());
}
@Bean(name = "entityManagerFactoryPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties())
.packages("com.neo.model") //设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.build(); | }
@Bean(name = "entityManagerPrimary")
@Primary
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Bean(name = "transactionManagerPrimary")
@Primary
PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-7 课: Spring Boot 集成 Druid 监控数据源\spring-boot-multi-Jpa-druid\src\main\java\com\neo\config\PrimaryConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DeviceActivityTriggerProcessor implements NotificationRuleTriggerProcessor<DeviceActivityTrigger, DeviceActivityNotificationRuleTriggerConfig> {
private final TbDeviceProfileCache deviceProfileCache;
@Override
public boolean matchesFilter(DeviceActivityTrigger trigger, DeviceActivityNotificationRuleTriggerConfig triggerConfig) {
DeviceEvent event = trigger.isActive() ? DeviceEvent.ACTIVE : DeviceEvent.INACTIVE;
if (!triggerConfig.getNotifyOn().contains(event)) {
return false;
}
DeviceId deviceId = trigger.getDeviceId();
if (CollectionUtils.isNotEmpty(triggerConfig.getDevices())) {
return triggerConfig.getDevices().contains(deviceId.getId());
} else if (CollectionUtils.isNotEmpty(triggerConfig.getDeviceProfiles())) {
DeviceProfile deviceProfile = deviceProfileCache.get(TenantId.SYS_TENANT_ID, deviceId);
return deviceProfile != null && triggerConfig.getDeviceProfiles().contains(deviceProfile.getUuidId());
} else {
return true;
} | }
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(DeviceActivityTrigger trigger) {
return DeviceActivityNotificationInfo.builder()
.eventType(trigger.isActive() ? "active" : "inactive")
.deviceId(trigger.getDeviceId().getId())
.deviceName(trigger.getDeviceName())
.deviceType(trigger.getDeviceType())
.deviceLabel(trigger.getDeviceLabel())
.deviceCustomerId(trigger.getCustomerId())
.build();
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.DEVICE_ACTIVITY;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\DeviceActivityTriggerProcessor.java | 2 |
请完成以下Spring Boot application配置 | management:
endpoints:
web:
exposure:
include: '*'
resilience4j.circuitbreaker:
configs:
default:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
waitDurationInOpenState: 5s
failureRateThreshold: 50
eventConsumerBufferSize: 50
instances:
externalService:
baseConfig: default
resilience4j.retry:
configs:
default:
maxAttempts: 3
waitDuration: 100
instances:
externalService:
baseConfig: default
resilience4j.timelimiter:
configs:
default:
cancelRunningFuture: true
timeoutDuration: 2s
instances:
externalService:
baseConfig: default
resilience4j.bulkhead:
configs:
default:
max-concurrent-calls: 3
max-wa | it-duration: 1
instances:
externalService:
baseConfig: default
resilience4j.ratelimiter:
configs:
default:
limit-for-period: 5
limit-refresh-period: 60s
timeout-duration: 0s
allow-health-indicator-to-fail: true
subscribe-for-events: true
event-consumer-buffer-size: 50
instances:
externalService:
baseConfig: default | repos\tutorials-master\spring-boot-modules\spring-boot-resilience4j\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public class AppModule {
@Provides
public SignatureKey signatureKey() {
return new SignatureKey("restx-demo -447494532235718370 restx-demo 801c9eaf-4116-48f2-906b-e979fba72757".getBytes(Charsets.UTF_8));
}
@Provides
@Named("restx.admin.password")
public String restxAdminPassword() {
return "4780";
}
@Provides
public ConfigSupplier appConfigSupplier(ConfigLoader configLoader) {
// Load settings.properties in restx.demo package as a set of config entries
return configLoader.fromResource("web-modules/restx/demo/settings");
}
@Provides
public CredentialsStrategy credentialsStrategy() {
return new BCryptCredentialsStrategy();
}
@Provides
public BasicPrincipalAuthenticator basicPrincipalAuthenticator(
SecuritySettings securitySettings, CredentialsStrategy credentialsStrategy,
@Named("restx.admin.passwordHash") String defaultAdminPasswordHash, ObjectMapper mapper) {
return new StdBasicPrincipalAuthenticator(new StdUserService<>(
// use file based users repository. | // Developer's note: prefer another storage mechanism for your users if you need real user management
// and better perf
new FileBasedUserRepository<>(
StdUser.class, // this is the class for the User objects, that you can get in your app code
// with RestxSession.current().getPrincipal().get()
// it can be a custom user class, it just need to be json deserializable
mapper,
// this is the default restx admin, useful to access the restx admin console.
// if one user with restx-admin role is defined in the repository, this default user won't be
// available anymore
new StdUser("admin", ImmutableSet.<String>of("*")),
// the path where users are stored
Paths.get("data/users.json"),
// the path where credentials are stored. isolating both is a good practice in terms of security
// it is strongly recommended to follow this approach even if you use your own repository
Paths.get("data/credentials.json"),
// tells that we want to reload the files dynamically if they are touched.
// this has a performance impact, if you know your users / credentials never change without a
// restart you can disable this to get better perfs
true),
credentialsStrategy, defaultAdminPasswordHash),
securitySettings);
}
} | repos\tutorials-master\web-modules\restx\src\main\java\restx\demo\AppModule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeferredResultController {
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
@GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
LOG.info("Received request");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
deferredResult.onCompletion(() -> LOG.info("Processing complete"));
CompletableFuture.supplyAsync(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "OK";
})
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
LOG.info("Servlet thread freed");
return deferredResult;
}
@GetMapping("/process-blocking")
public ResponseEntity<?> handleReqSync(Model model) {
// ...
return ResponseEntity.ok("ok");
}
@GetMapping("/async-deferredresult-timeout")
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
LOG.info("Received async request with a configured timeout");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
deferredResult.onTimeout(() -> deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT)
.body("Request timeout occurred.")));
CompletableFuture.supplyAsync(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "error"; | })
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
LOG.info("servlet thread freed");
return deferredResult;
}
@GetMapping("/async-deferredresult-error")
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
LOG.info("Received async request with a configured error handler");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
deferredResult.onError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t) {
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred."));
}
});
LOG.info("servlet thread freed");
return deferredResult;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\DeferredResultController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public RuleOriginatedNotificationInfo constructNotificationInfo(AlarmTrigger trigger) {
AlarmApiCallResult alarmUpdate = trigger.getAlarmUpdate();
AlarmInfo alarmInfo = alarmUpdate.getAlarm();
return AlarmNotificationInfo.builder()
.alarmId(alarmInfo.getUuidId())
.alarmType(alarmInfo.getType())
.action(alarmUpdate.isCreated() ? "created" :
alarmUpdate.isSeverityChanged() ? "severity changed" :
alarmUpdate.isAcknowledged() ? "acknowledged" :
alarmUpdate.isCleared() ? "cleared" :
alarmUpdate.isDeleted() ? "deleted" : null)
.alarmOriginator(alarmInfo.getOriginator())
.alarmOriginatorName(alarmInfo.getOriginatorName())
.alarmOriginatorLabel(alarmInfo.getOriginatorLabel())
.alarmSeverity(alarmInfo.getSeverity())
.alarmStatus(alarmInfo.getStatus())
.acknowledged(alarmInfo.isAcknowledged())
.cleared(alarmInfo.isCleared())
.alarmCustomerId(alarmInfo.getCustomerId())
.dashboardId(alarmInfo.getDashboardId()) | .details(toDetailsTemplateMap(alarmInfo.getDetails()))
.build();
}
private Map<String, String> toDetailsTemplateMap(JsonNode details) {
Map<String, String> infoMap = JacksonUtil.toFlatMap(details);
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> entry : infoMap.entrySet()) {
String key = "details." + entry.getKey();
result.put(key, entry.getValue());
}
return result;
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.ALARM;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\AlarmTriggerProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public final class OpenTelemetrySdkAutoConfiguration {
OpenTelemetrySdkAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(OpenTelemetry.class)
OpenTelemetrySdk openTelemetrySdk(ObjectProvider<SdkTracerProvider> openTelemetrySdkTracerProvider,
ObjectProvider<ContextPropagators> openTelemetryContextPropagators,
ObjectProvider<SdkLoggerProvider> openTelemetrySdkLoggerProvider,
ObjectProvider<SdkMeterProvider> openTelemetrySdkMeterProvider) {
OpenTelemetrySdkBuilder builder = OpenTelemetrySdk.builder();
openTelemetrySdkTracerProvider.ifAvailable(builder::setTracerProvider);
openTelemetryContextPropagators.ifAvailable(builder::setPropagators);
openTelemetrySdkLoggerProvider.ifAvailable(builder::setLoggerProvider);
openTelemetrySdkMeterProvider.ifAvailable(builder::setMeterProvider);
return builder.build(); | }
@Bean
@ConditionalOnMissingBean
Resource openTelemetryResource(Environment environment, OpenTelemetryProperties properties) {
return Resource.getDefault().merge(toResource(environment, properties));
}
private Resource toResource(Environment environment, OpenTelemetryProperties properties) {
ResourceBuilder builder = Resource.builder();
new OpenTelemetryResourceAttributes(environment, properties.getResourceAttributes()).applyTo(builder::put);
return builder.build();
}
} | repos\spring-boot-4.0.1\module\spring-boot-opentelemetry\src\main\java\org\springframework\boot\opentelemetry\autoconfigure\OpenTelemetrySdkAutoConfiguration.java | 2 |
请完成以下Java代码 | public Component getTreeCellRendererComponent(
final JTree tree,
final Object value,
final boolean Selected,
final boolean expanded,
final boolean leaf,
final int row,
final boolean HasFocus)
{
final VTreeCellRenderer c = (VTreeCellRenderer)super.getTreeCellRendererComponent
(tree, value, Selected, expanded, leaf, row, HasFocus);
c.setFont(c.getFont().deriveFont(Font.PLAIN)); // metas
setBackground(null); // metas: reset background
if (!leaf)
{
// task 09079: also setting custom icons for summary nodes
// note: we didn't move the logic to select the icon into MTreeNode because currently MTreeNode is aiming a leafs that have a partcular *action* like window, form process. MTreeNode is not
// about mere summary nodes.
final String iconName = expanded ? "mOpen": "mClosed";
c.setIcon(Images.getImageIcon2(iconName));
return c;
}
// We have a leaf
final MTreeNode nd = (MTreeNode)value;
// metas: add special handling for the product category tree
if (I_M_Product_Category.Table_Name.equals(nd.getImageIndiactor()))
{
// if (Selected) {
// c.setLeafIcon(c.getOpenIcon());
// } else {
c.setLeafIcon(c.getClosedIcon());
// }
}
else | {
final String iconName = nd.getIconName();
final Icon icon = Images.getImageIcon2(iconName);
if (icon != null)
{
c.setIcon(icon);
}
}
c.setText(nd.getName());
c.setToolTipText(nd.getDescription());
if (!Selected)
{
c.setForeground(nd.getColor());
}
// metas: begin:
if (nd.isPlaceholder())
{
c.setFont(c.getFont().deriveFont(Font.ITALIC));
}
if (nd.getBackgroundColor() != null)
{
c.setBackground(nd.getBackgroundColor());
}
else
{
c.setBackground(null);
}
// metas: end
return c;
} // getTreeCellRendererComponent
} // VTreeCellRenderer | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreeCellRenderer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ManagementProperties {
private Health health = new Health();
/**
* @return the health
*/
public Health getHealth() {
return health;
}
/**
* @param health the health to set
*/
public void setHealth(Health health) {
this.health = health;
}
@Override
public String toString() {
return "ManagementProperties [health=" + health + "]";
}
public static class Health {
private Camunda camunda = new Camunda();
/**
* @return the camunda
*/
public Camunda getCamunda() {
return camunda;
}
/**
* @param camunda the camunda to set
*/
public void setCamunda(Camunda camunda) {
this.camunda = camunda;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("camunda=" + camunda)
.toString();
}
public class Camunda {
private boolean enabled = true;
/**
* @return the enabled | */
public boolean isEnabled() {
return enabled;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
.toString();
}
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\ManagementProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EDIImpCBPartnerLocationLookupGLNType {
@XmlElement(name = "C_BPartner_ID")
protected EDICBPartnerLookupBPLGLNVType cbPartnerID;
@XmlElement(name = "GLN", required = true)
protected String gln;
/**
* Gets the value of the cbPartnerID property.
*
* @return
* possible object is
* {@link EDICBPartnerLookupBPLGLNVType }
*
*/
public EDICBPartnerLookupBPLGLNVType getCBPartnerID() {
return cbPartnerID;
}
/**
* Sets the value of the cbPartnerID property.
*
* @param value
* allowed object is
* {@link EDICBPartnerLookupBPLGLNVType }
*
*/
public void setCBPartnerID(EDICBPartnerLookupBPLGLNVType value) {
this.cbPartnerID = value;
}
/**
* Gets the value of the gln property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getGLN() {
return gln;
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGLN(String value) {
this.gln = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIImpCBPartnerLocationLookupGLNType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isForce() {
return Boolean.TRUE.equals(this.force);
}
public void setForce(boolean force) {
this.force = force;
}
public boolean isForceRequest() {
return Boolean.TRUE.equals(this.forceRequest);
}
public void setForceRequest(boolean forceRequest) {
this.forceRequest = forceRequest;
}
public boolean isForceResponse() {
return Boolean.TRUE.equals(this.forceResponse);
}
public void setForceResponse(boolean forceResponse) {
this.forceResponse = forceResponse;
}
public boolean shouldForce(HttpMessageType type) {
Boolean force = (type != HttpMessageType.REQUEST) ? this.forceResponse : this.forceRequest;
if (force == null) {
force = this.force;
}
if (force == null) { | force = (type == HttpMessageType.REQUEST);
}
return force;
}
/**
* Type of HTTP message to consider for encoding configuration.
*/
public enum HttpMessageType {
/**
* HTTP request message.
*/
REQUEST,
/**
* HTTP response message.
*/
RESPONSE
}
} | repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\ServletEncodingProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerProductRouteBuilder extends RouteBuilder
{
@Override
public void configure() throws Exception
{
errorHandler(noErrorHandler());
from(direct(MF_GET_BPARTNER_PRODUCTS_ROUTE_ID))
.routeId(MF_GET_BPARTNER_PRODUCTS_ROUTE_ID)
.streamCache("true")
.log("Route invoked")
.process(exchange -> {
final var lookupRequest = exchange.getIn().getBody();
if (!(lookupRequest instanceof BPProductCamelRequest)) | {
throw new RuntimeCamelException("The route " + MF_GET_BPARTNER_PRODUCTS_ROUTE_ID + " requires the body to be instanceof BPProductCamelRequest."
+ " However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName()));
}
exchange.getIn().setHeader(HEADER_ORG_CODE, ((BPProductCamelRequest)lookupRequest).getOrgCode());
exchange.getIn().setHeader(HEADER_BPARTNER_IDENTIFIER, ((BPProductCamelRequest)lookupRequest).getBPartnerIdentifier());
})
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.GET))
.toD("{{metasfresh.upsert-bpartner-v2.api.uri}}/${header." + HEADER_ORG_CODE + "}/${header." + HEADER_BPARTNER_IDENTIFIER + "}/products")
.to(direct(UNPACK_V2_API_RESPONSE));
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\BPartnerProductRouteBuilder.java | 2 |
请完成以下Java代码 | public EverLivingJobEntity reconfigure(HistoryCleanupContext context, EverLivingJobEntity job) {
HistoryCleanupJobHandlerConfiguration configuration = resolveJobHandlerConfiguration(context);
job.setJobHandlerConfiguration(configuration);
return job;
}
@Override
protected HistoryCleanupJobHandlerConfiguration resolveJobHandlerConfiguration(HistoryCleanupContext context) {
HistoryCleanupJobHandlerConfiguration config = new HistoryCleanupJobHandlerConfiguration();
config.setImmediatelyDue(context.isImmediatelyDue());
config.setMinuteFrom(context.getMinuteFrom());
config.setMinuteTo(context.getMinuteTo());
return config;
}
@Override
protected int resolveRetries(HistoryCleanupContext context) {
return context.getMaxRetries();
}
@Override
public Date resolveDueDate(HistoryCleanupContext context) {
return resolveDueDate(context.isImmediatelyDue());
}
private Date resolveDueDate(boolean isImmediatelyDue) { | CommandContext commandContext = Context.getCommandContext();
if (isImmediatelyDue) {
return ClockUtil.getCurrentTime();
} else {
final BatchWindow currentOrNextBatchWindow = commandContext.getProcessEngineConfiguration().getBatchWindowManager()
.getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), commandContext.getProcessEngineConfiguration());
if (currentOrNextBatchWindow != null) {
return currentOrNextBatchWindow.getStart();
} else {
return null;
}
}
}
public ParameterValueProvider getJobPriorityProvider() {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
long historyCleanupJobPriority = configuration.getHistoryCleanupJobPriority();
return new ConstantValueProvider(historyCleanupJobPriority);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobDeclaration.java | 1 |
请完成以下Java代码 | public void setAddress(String address) {
this.address = address;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
} | public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ContactBased.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ThemeMVCConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/themes/**").addResourceLocations("classpath:/themes/");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(themeChangeInterceptor());
}
@Bean
public ThemeChangeInterceptor themeChangeInterceptor() {
ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor();
interceptor.setParamName("theme");
return interceptor;
}
@Bean
public ResourceBundleThemeSource resourceBundleThemeSource() {
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
themeSource.setFallbackToSystemLocale(true);
return themeSource; | }
@Bean
public ThemeResolver themeResolver() {
UserPreferenceThemeResolver themeResolver = new UserPreferenceThemeResolver();
themeResolver.setDefaultThemeName("light");
return themeResolver;
}
@Override
public void configureViewResolvers(ViewResolverRegistry resolverRegistry) {
resolverRegistry.jsp();
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-views\src\main\java\com\baeldung\themes\config\ThemeMVCConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void prepareQueryServiceStatusRequests(@NonNull final Exchange exchange)
{
final List<RetreiveServiceStatusCamelRequest> retreiveServiceStatusRequests = externalSystemServices.stream()
.map(IExternalSystemService::getExternalSystemTypeCode)
.collect(ImmutableSet.toImmutableSet())
.stream()
.map(type -> RetreiveServiceStatusCamelRequest.builder().type(type).build())
.collect(ImmutableList.toImmutableList());
exchange.getIn().setBody(retreiveServiceStatusRequests);
}
private void filterActiveServices(@NonNull final Exchange exchange)
{
final JsonExternalStatusResponse externalStatusInfoResponse = exchange.getIn().getBody(JsonExternalStatusResponse.class);
exchange.getIn().setBody(externalStatusInfoResponse.getExternalStatusResponses()
.stream()
.filter(response -> response.getExpectedStatus().equals(JsonExternalStatus.Active))
.collect(ImmutableList.toImmutableList()));
}
private void createEnableServiceRequest(@NonNull final Exchange exchange)
{
final JsonExternalStatusResponseItem externalStatusResponse = exchange.getIn().getBody(JsonExternalStatusResponseItem.class);
final Optional<IExternalSystemService> matchedExternalService = externalSystemServices.stream()
.filter(externalService -> externalService.getServiceValue().equals(externalStatusResponse.getServiceValue()))
.findFirst(); | if (matchedExternalService.isEmpty())
{
log.warn("*** No Service found for value = " + externalStatusResponse.getServiceValue() + " !");
return;
}
final InvokeExternalSystemActionCamelRequest camelRequest = InvokeExternalSystemActionCamelRequest.builder()
.externalSystemChildValue(externalStatusResponse.getExternalSystemChildValue())
.externalSystemConfigType(externalStatusResponse.getExternalSystemConfigType())
.command(matchedExternalService.get().getEnableCommand())
.build();
exchange.getIn().setBody(camelRequest, InvokeExternalSystemActionCamelRequest.class);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\ExternalSystemRestAPIHandler.java | 2 |
请完成以下Java代码 | public String getHistoryConfiguration() {
return historyConfiguration;
}
public void setHistoryConfiguration(String historyConfiguration) {
this.historyConfiguration = historyConfiguration;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", incidentTimestamp=" + incidentTimestamp
+ ", incidentType=" + incidentType
+ ", executionId=" + executionId
+ ", activityId=" + activityId
+ ", processInstanceId=" + processInstanceId
+ ", processDefinitionId=" + processDefinitionId
+ ", causeIncidentId=" + causeIncidentId
+ ", rootCauseIncidentId=" + rootCauseIncidentId | + ", configuration=" + configuration
+ ", tenantId=" + tenantId
+ ", incidentMessage=" + incidentMessage
+ ", jobDefinitionId=" + jobDefinitionId
+ ", failedActivityId=" + failedActivityId
+ ", annotation=" + annotation
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IncidentEntity other = (IncidentEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IncidentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected WidgetsBundle saveOrUpdate(EntitiesImportCtx ctx, WidgetsBundle widgetsBundle, WidgetsBundleExportData exportData, IdProvider idProvider, CompareResult compareResult) {
if (CollectionsUtil.isNotEmpty(exportData.getWidgets())) {
exportData.getWidgets().forEach(widgetTypeNode -> {
String bundleAlias = widgetTypeNode.remove("bundleAlias").asText();
String alias = widgetTypeNode.remove("alias").asText();
String fqn = String.format("%s.%s", bundleAlias, alias);
exportData.addFqn(fqn);
WidgetTypeDetails widgetType = JacksonUtil.treeToValue(widgetTypeNode, WidgetTypeDetails.class);
widgetType.setTenantId(ctx.getTenantId());
widgetType.setFqn(fqn);
var existingWidgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(ctx.getTenantId(), fqn);
if (existingWidgetType == null) {
widgetType.setId(null);
} else {
widgetType.setId(existingWidgetType.getId());
widgetType.setCreatedTime(existingWidgetType.getCreatedTime());
}
widgetTypeService.saveWidgetType(widgetType);
});
}
WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);
widgetTypeService.updateWidgetsBundleWidgetFqns(ctx.getTenantId(), savedWidgetsBundle.getId(), exportData.getFqns());
return savedWidgetsBundle;
}
@Override | protected CompareResult compare(EntitiesImportCtx ctx, WidgetsBundleExportData exportData, WidgetsBundle prepared, WidgetsBundle existing) {
return new CompareResult(true);
}
@Override
protected WidgetsBundle deepCopy(WidgetsBundle widgetsBundle) {
return new WidgetsBundle(widgetsBundle);
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGETS_BUNDLE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\WidgetsBundleImportService.java | 2 |
请完成以下Java代码 | public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TEXT_ANNOTATION, TextAnnotationJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
convertersToJsonMap.put(TextAnnotation.class, TextAnnotationJsonConverter.class);
}
protected String getStencilId(BaseElement baseElement) {
return STENCIL_TEXT_ANNOTATION;
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
TextAnnotation annotation = (TextAnnotation) baseElement;
if (StringUtils.isNotEmpty(annotation.getText())) {
setPropertyValue("text", annotation.getText(), propertiesNode);
} | }
protected BaseElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
TextAnnotation annotation = new TextAnnotation();
String text = getPropertyValueAsString("text", elementNode);
if (StringUtils.isNotEmpty(text)) {
annotation.setText(text);
}
return annotation;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\TextAnnotationJsonConverter.java | 1 |
请完成以下Java代码 | public String getTopicName() {
return topicName;
}
public boolean isDeserializeVariables() {
return deserializeVariables;
}
public void setDeserializeVariables(boolean deserializeVariables) {
this.deserializeVariables = deserializeVariables;
}
public void ensureVariablesInitialized() {
if (!filterVariables.isEmpty()) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue queryVariableValue : filterVariables) {
queryVariableValue.initialize(variableSerializers, dbType);
}
}
}
public boolean isLocalVariables() {
return localVariables; | }
public void setLocalVariables(boolean localVariables) {
this.localVariables = localVariables;
}
public boolean isIncludeExtensionProperties() {
return includeExtensionProperties;
}
public void setIncludeExtensionProperties(boolean includeExtensionProperties) {
this.includeExtensionProperties = includeExtensionProperties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\TopicFetchInstruction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class XmlPayload
{
/** Expecting default = invoice */
@NonNull
String type;
/** Expecting default = false */
@NonNull
Boolean storno;
/** Expecting default = false */
@NonNull
Boolean copy;
/** Expecting default = false */
@Nullable
Boolean creditAdvice;
/** Expecting default = false */
@Nullable
Boolean ifStornoFollowupInvoiceProbable;
@Nullable
XmlCredit credit;
@NonNull
XmlInvoice invoice;
@Nullable
XmlReminder reminder;
@NonNull
XmlBody body;
public XmlPayload withMod(@Nullable final PayloadMod payloadMod)
{
if (payloadMod == null)
{
return this;
}
final XmlPayloadBuilder builder = toBuilder();
if (payloadMod.getStorno() != null)
{
builder.storno(payloadMod.getStorno());
}
if (payloadMod.getCopy() != null)
{
builder.copy(payloadMod.getCopy());
}
if (payloadMod.getCreditAdvice() != null)
{
builder.creditAdvice(payloadMod.getCreditAdvice());
}
return builder
.invoice(invoice.withMod(payloadMod.getInvoiceMod())) | .reminder(payloadMod.getReminder())
.body(body.withMod(payloadMod.getBodyMod()))
.build();
}
@Value
@Builder
public static class PayloadMod
{
@Nullable
String type;
@Nullable
Boolean storno;
@Nullable
Boolean copy;
@Nullable
Boolean creditAdvice;
@Nullable
InvoiceMod invoiceMod;
@Nullable
XmlReminder reminder;
@Nullable
BodyMod bodyMod;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\request\model\XmlPayload.java | 2 |
请完成以下Java代码 | public Long getNumber() {
return number;
}
public void setNumber(Long number) {
this.number = number;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Supplier getSupplier() { | return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
} | repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\libraries\smooks\model\Order.java | 1 |
请完成以下Java代码 | private static Encoder<?> findJsonEncoder(Stream<Encoder<?>> stream) {
return stream
.filter((encoder) -> encoder.canEncode(MESSAGE_TYPE, MediaType.APPLICATION_JSON))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Encoder"));
}
private static Decoder<?> findJsonDecoder(Stream<Decoder<?>> decoderStream) {
return decoderStream
.filter((decoder) -> decoder.canDecode(MESSAGE_TYPE, MediaType.APPLICATION_JSON))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No JSON Decoder"));
}
CodecConfigurer getCodecConfigurer() {
return this.codecConfigurer;
} | @SuppressWarnings("unchecked")
<T> WebSocketMessage encode(WebSocketSession session, GraphQlWebSocketMessage message) {
DataBuffer buffer = ((Encoder<T>) this.encoder).encodeValue(
(T) message, session.bufferFactory(), MESSAGE_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
return new WebSocketMessage(WebSocketMessage.Type.TEXT, buffer);
}
@SuppressWarnings("ConstantConditions")
@Nullable GraphQlWebSocketMessage decode(WebSocketMessage webSocketMessage) {
DataBuffer buffer = DataBufferUtils.retain(webSocketMessage.getPayload());
return (GraphQlWebSocketMessage) this.decoder.decode(buffer, MESSAGE_TYPE, null, null);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\CodecDelegate.java | 1 |
请完成以下Java代码 | protected void doFilterInternal(@Nonnull HttpServletRequest request,
@Nonnull HttpServletResponse response,
@Nonnull FilterChain filterChain) throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication instanceof OAuth2AuthenticationToken) {
var token = (OAuth2AuthenticationToken) authentication;
authorizeToken(token, request, response);
}
filterChain.doFilter(request, response);
}
protected boolean hasTokenExpired(OAuth2Token token) {
return token.getExpiresAt() == null || ClockUtil.now().after(Date.from(token.getExpiresAt()));
}
protected void clearContext(HttpServletRequest request) {
SecurityContextHolder.clearContext();
try {
request.getSession().invalidate();
} catch (Exception ignored) {
}
}
protected void authorizeToken(OAuth2AuthenticationToken token,
HttpServletRequest request,
HttpServletResponse response) { | // @formatter:off
var authRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(token.getAuthorizedClientRegistrationId())
.principal(token)
.attributes(attrs -> {
attrs.put(HttpServletRequest.class.getName(), request);
attrs.put(HttpServletResponse.class.getName(), response);
}).build();
// @formatter:on
var name = token.getName();
try {
var res = clientManager.authorize(authRequest);
if (res == null || hasTokenExpired(res.getAccessToken())) {
logger.warn("Authorize failed for '{}': could not re-authorize expired access token", name);
clearContext(request);
} else {
logger.debug("Authorize successful for '{}', access token expiry: {}", name, res.getAccessToken().getExpiresAt());
}
} catch (OAuth2AuthorizationException e) {
logger.warn("Authorize failed for '{}': {}", name, e.getMessage());
clearContext(request);
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\impl\AuthorizeTokenFilter.java | 1 |
请完成以下Java代码 | public final void addRetryableExceptions(Class<? extends Exception>... exceptionTypes) {
add(true, exceptionTypes);
}
@SafeVarargs
@SuppressWarnings("varargs")
private void add(boolean classified, Class<? extends Exception>... exceptionTypes) {
Assert.notNull(exceptionTypes, "'exceptionTypes' cannot be null");
Assert.noNullElements(exceptionTypes, "'exceptionTypes' cannot contain nulls");
for (Class<? extends Exception> exceptionType : exceptionTypes) {
Assert.isTrue(Exception.class.isAssignableFrom(exceptionType),
() -> "exceptionType " + exceptionType + " must be an Exception");
this.exceptionMatcher.getEntries().put(exceptionType, classified);
}
}
/**
* Remove an exception type from the configured list. By default, the following
* exceptions will not be retried:
* <ul>
* <li>{@link DeserializationException}</li>
* <li>{@link MessageConversionException}</li>
* <li>{@link ConversionException}</li>
* <li>{@link MethodArgumentResolutionException}</li>
* <li>{@link NoSuchMethodException}</li>
* <li>{@link ClassCastException}</li>
* </ul>
* All others will be retried, unless {@link #defaultFalse()} has been called.
* @param exceptionType the exception type.
* @return the classification of the exception if removal was successful;
* null otherwise.
* @since 2.8.4
* @see #addNotRetryableExceptions(Class...)
* @see #setClassifications(Map, boolean)
*/
@Nullable
public Boolean removeClassification(Class<? extends Exception> exceptionType) {
return this.exceptionMatcher.getEntries().remove(exceptionType); | }
/**
* Extended to provide visibility to the current classified exceptions.
*
* @author Gary Russell
*
*/
@SuppressWarnings("serial")
private static final class ExtendedExceptionMatcher extends ExceptionMatcher {
ExtendedExceptionMatcher(Map<Class<? extends Throwable>, Boolean> typeMap, boolean defaultValue) {
super(typeMap, defaultValue, true);
}
@Override
protected Map<Class<? extends Throwable>, Boolean> getEntries() { // NOSONAR worthless override
return super.getEntries();
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ExceptionClassifier.java | 1 |
请完成以下Spring Boot application配置 | #local
server.contextPath=/
server.port=8080
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/epp_manager?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=admi | n
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
logging.config=classpath:log4j.properties | repos\springBoot-master\springboot-shiro\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public class TablePageQueryImpl implements TablePageQuery, Command<TablePage>, Serializable {
private static final long serialVersionUID = 1L;
transient CommandExecutor commandExecutor;
protected String tableName;
protected String order;
protected int firstResult;
protected int maxResults;
public TablePageQueryImpl() {}
public TablePageQueryImpl(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor;
}
public TablePageQueryImpl tableName(String tableName) {
this.tableName = tableName;
return this;
}
public TablePageQueryImpl orderAsc(String column) {
addOrder(column, AbstractQuery.SORTORDER_ASC);
return this;
}
public TablePageQueryImpl orderDesc(String column) {
addOrder(column, AbstractQuery.SORTORDER_DESC);
return this;
}
public String getTableName() {
return tableName;
}
protected void addOrder(String column, String sortOrder) {
if (order == null) {
order = "";
} else { | order = order + ", ";
}
order = order + column + " " + sortOrder;
}
public TablePage listPage(int firstResult, int maxResults) {
this.firstResult = firstResult;
this.maxResults = maxResults;
return commandExecutor.execute(this);
}
public TablePage execute(CommandContext commandContext) {
return commandContext.getTableDataManager().getTablePage(this, firstResult, maxResults);
}
public String getOrder() {
return order;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TablePageQueryImpl.java | 1 |
请完成以下Java代码 | public void setCategory(String category) {
this.category = category;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override | public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDefinitionEntityImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.