instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class Wrapper<T> implements Serializable { private static final long serialVersionUID = -7755079424069021028L; /** 编号. */ private int code; /** 信息. */ private String message; /** 结果数据 */ private T data; /** * Instantiates a new wrapper. * * @param code * the code * @param message * the message */ public Wrapper(int code, String message) { this(code, message, null); } /** * Instantiates a new wrapper. * * @param code * the code * @param message * the message * @param result * the result */ public Wrapper(int code, String message, T result) { super(); this.code(code).message(message).result(result); } /** * Gets the 编号. * * @return the 编号 */ public int getCode() { return code; } /** * Sets the 编号. * * @param code * the new 编号 */ public void setCode(int code) { this.code = code; } /** * Gets the 信息. * * @return the 信息 */ public String getMessage() { return message; } /** * Sets the 信息. * * @param message * the new 信息 */ public void setMessage(String message) { this.message = message; } /** * Sets the 编号 ,返回自身的引用. * * @param code * the new 编号
* * @return the wrapper */ public Wrapper<T> code(int code) { this.setCode(code); return this; } /** * Sets the 信息 ,返回自身的引用. * * @param message * the new 信息 * * @return the wrapper */ public Wrapper<T> message(String message) { this.setMessage(message); return this; } /** * Sets the 结果数据 ,返回自身的引用. * * @param result * the new 结果数据 * * @return the wrapper */ public Wrapper<T> result(T result) { this.setData(result); return this; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\wrapper\Wrapper.java
1
请完成以下Java代码
public ScriptTaskActivityBehavior createScriptTaskActivityBehavior(PlanItem planItem, ScriptServiceTask task) { return new ScriptTaskActivityBehavior(task); } @Override public CasePageTaskActivityBehaviour createCasePageTaskActivityBehaviour(PlanItem planItem, CasePageTask task) { return new CasePageTaskActivityBehaviour(task); } public void setClassDelegateFactory(CmmnClassDelegateFactory classDelegateFactory) { this.classDelegateFactory = classDelegateFactory; } public ExpressionManager getExpressionManager() { return expressionManager;
} public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } protected Expression createExpression(String refExpressionString) { Expression expression = null; if (StringUtils.isNotEmpty(refExpressionString)) { expression = expressionManager.createExpression(refExpressionString); } return expression; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\DefaultCmmnActivityBehaviorFactory.java
1
请完成以下Java代码
public EventModelBuilder deploymentTenantId(String deploymentTenantId) { this.deploymentTenantId = deploymentTenantId; return this; } @Override public EventModelBuilder header(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.header(name, type)); return this; } @Override public EventModelBuilder headerWithCorrelation(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.headerWithCorrelation(name, type)); return this; } @Override public EventModelBuilder correlationParameter(String name, String type) { eventPayloadDefinitions.put(name, EventPayload.correlation(name, type)); return this; } @Override public EventModelBuilder payload(String name, String type) { eventPayloadDefinitions.put(name, new EventPayload(name, type)); return this; } @Override public EventModelBuilder metaParameter(String name, String type) { EventPayload payload = new EventPayload(name, type); payload.setMetaParameter(true); eventPayloadDefinitions.put(name, payload); return this; } @Override public EventModelBuilder fullPayload(String name) { eventPayloadDefinitions.put(name, EventPayload.fullPayload(name)); return this; } @Override public EventModel createEventModel() { return buildEventModel(); } @Override public EventDeployment deploy() { if (resourceName == null) { throw new FlowableIllegalArgumentException("A resource name is mandatory"); }
EventModel eventModel = buildEventModel(); return eventRepository.createDeployment() .name(deploymentName) .addEventDefinition(resourceName, eventJsonConverter.convertToJson(eventModel)) .category(category) .parentDeploymentId(parentDeploymentId) .tenantId(deploymentTenantId) .deploy(); } protected EventModel buildEventModel() { EventModel eventModel = new EventModel(); if (StringUtils.isNotEmpty(key)) { eventModel.setKey(key); } else { throw new FlowableIllegalArgumentException("An event definition key is mandatory"); } eventModel.setPayload(eventPayloadDefinitions.values()); return eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\EventModelBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductOrderEntity implements Serializable { /** 订单ID */ private String orderId; /** 产品详情 */ private ProductEntity productEntity; /** 产品数量 */ private int count; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public ProductEntity getProductEntity() { return productEntity; }
public void setProductEntity(ProductEntity productEntity) { this.productEntity = productEntity; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public String toString() { return "ProductOrderEntity{" + "orderId='" + orderId + '\'' + ", productEntity=" + productEntity + ", count=" + count + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\ProductOrderEntity.java
2
请完成以下Java代码
public void setEventName (final java.lang.String EventName) { set_Value (COLUMNNAME_EventName, EventName); } @Override public java.lang.String getEventName() { return get_ValueAsString(COLUMNNAME_EventName); } @Override public void setExternalId (final java.lang.String ExternalId) { set_Value (COLUMNNAME_ExternalId, ExternalId); } @Override public java.lang.String getExternalId() { return get_ValueAsString(COLUMNNAME_ExternalId); } @Override public void setTimestamp (final java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } @Override public void setUI_ApplicationId (final @Nullable java.lang.String UI_ApplicationId) { set_Value (COLUMNNAME_UI_ApplicationId, UI_ApplicationId); } @Override public java.lang.String getUI_ApplicationId() { return get_ValueAsString(COLUMNNAME_UI_ApplicationId); } @Override public void setUI_DeviceId (final @Nullable java.lang.String UI_DeviceId) { set_Value (COLUMNNAME_UI_DeviceId, UI_DeviceId); } @Override public java.lang.String getUI_DeviceId() { return get_ValueAsString(COLUMNNAME_UI_DeviceId); } @Override public void setUI_TabId (final @Nullable java.lang.String UI_TabId) { set_Value (COLUMNNAME_UI_TabId, UI_TabId); } @Override public java.lang.String getUI_TabId() { return get_ValueAsString(COLUMNNAME_UI_TabId); } @Override public void setUI_Trace_ID (final int UI_Trace_ID) { if (UI_Trace_ID < 1) set_ValueNoCheck (COLUMNNAME_UI_Trace_ID, null); else set_ValueNoCheck (COLUMNNAME_UI_Trace_ID, UI_Trace_ID);
} @Override public int getUI_Trace_ID() { return get_ValueAsInt(COLUMNNAME_UI_Trace_ID); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setUserAgent (final @Nullable java.lang.String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } @Override public java.lang.String getUserAgent() { return get_ValueAsString(COLUMNNAME_UserAgent); } @Override public void setUserName (final @Nullable java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_UI_Trace.java
1
请完成以下Java代码
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 Integer getChargeType() { return chargeType; } public void setChargeType(Integer chargeType) { this.chargeType = chargeType; } public BigDecimal getFirstWeight() { return firstWeight; } public void setFirstWeight(BigDecimal firstWeight) { this.firstWeight = firstWeight; } public BigDecimal getFirstFee() { return firstFee; } public void setFirstFee(BigDecimal firstFee) { this.firstFee = firstFee; } public BigDecimal getContinueWeight() { return continueWeight; } public void setContinueWeight(BigDecimal continueWeight) { this.continueWeight = continueWeight; } public BigDecimal getContinmeFee() { return continmeFee;
} public void setContinmeFee(BigDecimal continmeFee) { this.continmeFee = continmeFee; } public String getDest() { return dest; } public void setDest(String dest) { this.dest = dest; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", chargeType=").append(chargeType); sb.append(", firstWeight=").append(firstWeight); sb.append(", firstFee=").append(firstFee); sb.append(", continueWeight=").append(continueWeight); sb.append(", continmeFee=").append(continmeFee); sb.append(", dest=").append(dest); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsFeightTemplate.java
1
请完成以下Java代码
public void run() { while (!collided) { vader.move(2, 0); luke.move(-2, 0); switch (collisionType) { case BOUNDING_BOX: if (vader.getRectangleBounds().intersects(luke.getRectangleBounds())) { collided = true; } break; case AREA_CIRCLE: Area ellipseAreaVader = vader.getEllipseAreaBounds(); Area ellipseAreaLuke = luke.getEllipseAreaBounds(); ellipseAreaVader.intersect(ellipseAreaLuke); if (!ellipseAreaVader.isEmpty()) { collided = true; } break; case CIRCLE_DISTANCE: Ellipse2D circleVader = vader.getCircleBounds(); Ellipse2D circleLuke = luke.getCircleBounds(); double dx = circleVader.getCenterX() - circleLuke.getCenterX(); double dy = circleVader.getCenterY() - circleLuke.getCenterY(); double distance = Math.sqrt(dx * dx + dy * dy); double radiusVader = circleVader.getWidth() / 2.0; double radiusLuke = circleLuke.getWidth() / 2.0; if (distance < radiusVader + radiusLuke) { collided = true; } break; case POLYGON: Area polygonAreaVader = vader.getPolygonBounds(); Area polygonAreaLuke = luke.getPolygonBounds(); polygonAreaVader.intersect(polygonAreaLuke); if (!polygonAreaVader.isEmpty()) { collided = true; } break; case PIXEL_PERFECT: if (vader.collidesWith(luke)) { collided = true; } break; }
repaint(); try { Thread.sleep(16); } catch (InterruptedException e) { throw new RuntimeException(e); } } } protected void paintComponent(Graphics g) { super.paintComponent(g); vader.draw(g); luke.draw(g); if (collided) { g.setColor(Color.RED); g.setFont(new Font("SansSerif", Font.BOLD, 50)); g.drawString("COLLISION!", getWidth() / 2 - 100, getHeight() / 2); } } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Epic Duel"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1920, 1080); frame.add(new Game()); frame.setVisible(true); }); } }
repos\tutorials-master\image-processing\src\main\java\com\baeldung\imagecollision\Game.java
1
请在Spring Boot框架中完成以下Java代码
public class PmsMenuBiz { private static final Log log = LogFactory.getLog(PmsMenuBiz.class); @Autowired private PmsMenuService pmsMenuService; /** * 获取用于编制菜单时的树. */ @SuppressWarnings("rawtypes") public String getTreeMenu(String actionUrl) { List treeData = pmsMenuService.getListByParent(null); StringBuffer strJson = new StringBuffer(); recursionTreeMenu("0", strJson, treeData, actionUrl); return strJson.toString(); } /** * 递归输出树形菜单 * * @param pId * @param buffer */ @SuppressWarnings("rawtypes") private void recursionTreeMenu(String pId, StringBuffer buffer, List list, String url) { if (pId.equals("0")) { buffer.append("<ul class=\"tree treeFolder collapse \" >"); } else { buffer.append("<ul>"); } List<Map> listMap = getSonMenuListByPid(pId, list); for (Map map : listMap) { String id = map.get("id").toString();// id String name = map.get("name").toString();// 名称 String isLeaf = map.get("isLeaf").toString();// 是否叶子科目 buffer.append("<li><a onclick=\"onClickMenuNode(" + id + ")\" href=\"" + url + "?id=" + id + "\" target=\"ajax\" rel=\"jbsxBox\" value=" + id + ">" + name + "</a>"); if (!isLeaf.equals("1")) { recursionTreeMenu(id, buffer, list, url); } buffer.append("</li>"); } buffer.append("</ul>"); } /** * 根据(pId)获取(menuList)中的所有子菜单集合.
* * @param pId * 父菜单ID. * @param menuList * 菜单集合. * @return sonMenuList. */ @SuppressWarnings({ "rawtypes", "unchecked" }) private List<Map> getSonMenuListByPid(String pId, List menuList) { List sonMenuList = new ArrayList<Object>(); for (Object menu : menuList) { Map map = (Map) menu; if (map != null) { String parentId = map.get("pId").toString();// 父id if (parentId.equals(pId)) { sonMenuList.add(map); } } } return sonMenuList; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\biz\PmsMenuBiz.java
2
请完成以下Java代码
private Optional<TsKvEntry> processAvgOrSumResult(Aggregation aggregation, AggregationResult aggResult) { if (aggResult.count == 0 || (aggResult.dataType == DataType.DOUBLE && aggResult.dValue == null) || (aggResult.dataType == DataType.LONG && aggResult.lValue == null)) { return Optional.empty(); } else if (aggResult.dataType == DataType.DOUBLE || aggResult.dataType == DataType.LONG) { if (aggregation == Aggregation.AVG || aggResult.hasDouble) { double sum = Optional.ofNullable(aggResult.dValue).orElse(0.0d) + Optional.ofNullable(aggResult.lValue).orElse(0L); DoubleDataEntry doubleDataEntry = new DoubleDataEntry(key, aggregation == Aggregation.SUM ? sum : (sum / aggResult.count)); TsKvEntry result = aggregation == Aggregation.AVG ? new AggTsKvEntry(ts, doubleDataEntry, aggResult.count) : new BasicTsKvEntry(ts, doubleDataEntry); return Optional.of(result); } else { LongDataEntry longDataEntry = new LongDataEntry(key, aggregation == Aggregation.SUM ? aggResult.lValue : (aggResult.lValue / aggResult.count)); return Optional.of(new BasicTsKvEntry(ts, longDataEntry)); } } return Optional.empty(); } private Optional<TsKvEntry> processMinOrMaxResult(AggregationResult aggResult) { if (aggResult.dataType == DataType.DOUBLE || aggResult.dataType == DataType.LONG) { if (aggResult.hasDouble) { double currentD = aggregation == Aggregation.MIN ? Optional.ofNullable(aggResult.dValue).orElse(Double.MAX_VALUE) : Optional.ofNullable(aggResult.dValue).orElse(Double.MIN_VALUE); double currentL = aggregation == Aggregation.MIN ? Optional.ofNullable(aggResult.lValue).orElse(Long.MAX_VALUE) : Optional.ofNullable(aggResult.lValue).orElse(Long.MIN_VALUE); return Optional.of(new BasicTsKvEntry(ts, new DoubleDataEntry(key, aggregation == Aggregation.MIN ? Math.min(currentD, currentL) : Math.max(currentD, currentL))));
} else { return Optional.of(new BasicTsKvEntry(ts, new LongDataEntry(key, aggResult.lValue))); } } else if (aggResult.dataType == DataType.STRING) { return Optional.of(new BasicTsKvEntry(ts, new StringDataEntry(key, aggResult.sValue))); } else if (aggResult.dataType == DataType.JSON) { return Optional.of(new BasicTsKvEntry(ts, new JsonDataEntry(key, aggResult.jValue))); } else { return Optional.of(new BasicTsKvEntry(ts, new BooleanDataEntry(key, aggResult.bValue))); } } private class AggregationResult { DataType dataType = null; Boolean bValue = null; String sValue = null; String jValue = null; Double dValue = null; Long lValue = null; long count = 0; boolean hasDouble = false; long aggValuesLastTs = 0; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\AggregatePartitionsFunction.java
1
请在Spring Boot框架中完成以下Java代码
public class SimpleHttpResult { public SimpleHttpResult(int code){ this.statusCode = code; } public SimpleHttpResult(int code, String _content){ this.statusCode = code; this.content = _content; } public SimpleHttpResult(Exception e){ if(e==null){ throw new IllegalArgumentException("exception must be specified"); } this.statusCode = -1; this.exception = e; this.exceptionMsg = e.getMessage(); } /** * HTTP状态码 */ private int statusCode; /** * HTTP结果 */ private String content; private String exceptionMsg; private Exception exception; private Map<String,List<String>> headers; private String contentType; public String getHeaderField(String key){ if(headers==null){ return null; } List<String> headerValues = headers.get(key); if(headerValues==null || headerValues.isEmpty()){ return null; } return headerValues.get(headerValues.size()-1); } public String getContentType(){ return contentType; }
public int getStatusCode() { return statusCode; } public Map<String, List<String>> getHeaders() { return headers; } public void setHeaders(Map<String, List<String>> headers) { this.headers = headers; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getExceptionMsg() { return exceptionMsg; } public Exception getException() { return exception; } public boolean isSuccess(){ return statusCode==200; } public boolean isError(){ return exception!=null; } public void setContentType(String contentType) { this.contentType = contentType; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpResult.java
2
请完成以下Java代码
public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public byte[] getBytes() { return bytes; } @Override public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String getDeploymentId() { return deploymentId; } @Override
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @Override public Object getPersistentState() { return EventResourceEntityImpl.class; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "ResourceEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventResourceEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Integer createOrder(Long userId, Long productId, Integer price) throws IOException { Integer amount = 1; // 购买数量,暂时设置为 1。 log.info("[createOrder] 当前 XID: {}", RootContext.getXID()); // <2> 扣减库存 this.reduceStock(productId, amount); // <3> 扣减余额 this.reduceBalance(userId, price); // <4> 保存订单 log.info("[createOrder] 保存订单"); return this.saveOrder(userId,productId,price,amount); } private Integer saveOrder(Long userId, Long productId, Integer price,Integer amount){ // <4> 保存订单 OrderDO order = new OrderDO(); order.setUserId(userId); order.setProductId(productId); order.setPayAmount(amount * price); orderDao.saveOrder(order); log.info("[createOrder] 保存订单: {}", order.getId()); return order.getId(); } private void reduceStock(Long productId, Integer amount) throws IOException { // 参数拼接 JSONObject params = new JSONObject().fluentPut("productId", String.valueOf(productId)) .fluentPut("amount", String.valueOf(amount)); // 执行调用 HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:8082", "/stock", params, HttpResponse.class); // 解析结果
Boolean success = Boolean.valueOf(EntityUtils.toString(response.getEntity())); if (!success) { throw new RuntimeException("扣除库存失败"); } } private void reduceBalance(Long userId, Integer price) throws IOException { // 参数拼接 JSONObject params = new JSONObject().fluentPut("userId", String.valueOf(userId)) .fluentPut("price", String.valueOf(price)); // 执行调用 HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:8083", "/balance", params, HttpResponse.class); // 解析结果 Boolean success = Boolean.valueOf(EntityUtils.toString(response.getEntity())); if (!success) { throw new RuntimeException("扣除余额失败"); } } }
repos\springboot-demo-master\seata\seata-order\src\main\java\com\et\seata\order\service\OrderServiceImpl.java
2
请完成以下Java代码
public Object getCellEditorValue() { // log.debug( "IDColumnEditor.getCellEditorValue - " + m_check.isSelected()); if (m_value != null) m_value.setSelected (m_check.isSelected()); return m_value; } // getCellEditorValue /** * Get visual Component * @param table * @param value * @param isSelected * @param row * @param column * @return Component */ @Override public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column) { // log.debug( "IDColumnEditor.getTableCellEditorComponent", value); m_table = table; // set value if (value != null && value instanceof IDColumn) m_value = (IDColumn)value; else { m_value = null; return null; //throw new IllegalArgumentException("ICColumnEditor.getTableCellEditorComponent - value=" + value); } // set editor value m_check.setSelected(m_value.isSelected()); return m_check; } // getTableCellEditorComponent /** * Can we edit it * @param anEvent * @return true (constant) */ @Override public boolean isCellEditable (EventObject anEvent) { return true; } // isCellEditable /** * Can the cell be selected * @param anEvent
* @return true (constant) */ @Override public boolean shouldSelectCell (EventObject anEvent) { return true; } // shouldSelectCell /** * Action Listener * @param e */ @Override public void actionPerformed (ActionEvent e) { if (m_table != null) { m_table.editingStopped(new ChangeEvent(this)); } } // actionPerformed } // IDColumnEditor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\IDColumnEditor.java
1
请完成以下Java代码
public SeqNo getNextLineNo(final PPOrderWeightingRunId weightingRunId) { return ppOrderWeightingRunRepository.getNextLineNo(weightingRunId); } public void updateFromChecks(final Collection<PPOrderWeightingRunId> ids) { // NOTE: we usually expect only one element here, so it's OK to iterate for (final PPOrderWeightingRunId id : ids) { ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::updateToleranceExceededFlag); } } public UomId getUomId(final PPOrderWeightingRunId id) { return ppOrderWeightingRunRepository.getUomId(id); }
public PPOrderWeightingRunCheckId addRunCheck( @NonNull PPOrderWeightingRunId weightingRunId, @NonNull final BigDecimal weightBD) { PPOrderWeightingRun weightingRun = getById(weightingRunId); final Quantity weight = Quantity.of(weightBD, weightingRun.getUOM()); final SeqNo lineNo = weightingRun.getNextLineNo(); final OrgId orgId = weightingRun.getOrgId(); final PPOrderWeightingRunCheckId weightingRunCheckId = ppOrderWeightingRunRepository.addRunCheck(weightingRunId, lineNo, weight, orgId); weightingRun = getById(weightingRunId); weightingRun.updateToleranceExceededFlag(); ppOrderWeightingRunRepository.save(weightingRun); return weightingRunCheckId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunService.java
1
请完成以下Java代码
public class ADJavaClassValidator extends AbstractADValidator<I_AD_JavaClass> { @Override public void validate(@NonNull final I_AD_JavaClass item) { final I_AD_JavaClass_Type type = item.getAD_JavaClass_Type(); if (Check.isEmpty(type.getClassname(), true)) { Util.validateJavaClassname(item.getClassname(), null); } else { final Class<?> typeClass = Util.validateJavaClassname(type.getClassname(), null); Util.validateJavaClassname(item.getClassname(), typeClass); } } @Override public String getLogMessage(@NonNull final IADValidatorViolation violation) { final StringBuilder message = new StringBuilder(); try { final I_AD_JavaClass javaClass = InterfaceWrapperHelper.create(violation.getItem(), I_AD_JavaClass.class); message.append("Error on ").append(javaClass).append(" (IsActive=").append(javaClass.isActive()).append("): "); } catch (final Exception e) {
message.append("Error (InterfaceWrapperHelper exception: ").append(e.getLocalizedMessage()).append(") on ").append(violation.getItem()).append(": "); } message.append(violation.getError().getLocalizedMessage()); return message.toString(); } @Override public Class<I_AD_JavaClass> getType() { return I_AD_JavaClass.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\spi\impl\ADJavaClassValidator.java
1
请完成以下Java代码
public void setImportedPartientBP_Group(final org.compiere.model.I_C_BP_Group ImportedPartientBP_Group) { set_ValueFromPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedPartientBP_Group); } @Override public void setImportedPartientBP_Group_ID (final int ImportedPartientBP_Group_ID) { if (ImportedPartientBP_Group_ID < 1) set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, null); else set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, ImportedPartientBP_Group_ID); } @Override public int getImportedPartientBP_Group_ID() { return get_ValueAsInt(COLUMNNAME_ImportedPartientBP_Group_ID); } @Override public void setStoreDirectory (final @Nullable java.lang.String StoreDirectory) {
set_Value (COLUMNNAME_StoreDirectory, StoreDirectory); } @Override public java.lang.String getStoreDirectory() { return get_ValueAsString(COLUMNNAME_StoreDirectory); } @Override public void setVia_EAN (final java.lang.String Via_EAN) { set_Value (COLUMNNAME_Via_EAN, Via_EAN); } @Override public java.lang.String getVia_EAN() { return get_ValueAsString(COLUMNNAME_Via_EAN); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java-gen\de\metas\vertical\healthcare\forum_datenaustausch_ch\commons\model\X_HC_Forum_Datenaustausch_Config.java
1
请在Spring Boot框架中完成以下Java代码
public JdbcUserDetailsManagerConfigurer<B> rolePrefix(String rolePrefix) { getUserDetailsService().setRolePrefix(rolePrefix); return this; } /** * Defines the {@link UserCache} to use * @param userCache the {@link UserCache} to use * @return the {@link JdbcUserDetailsManagerConfigurer} for further customizations */ public JdbcUserDetailsManagerConfigurer<B> userCache(UserCache userCache) { getUserDetailsService().setUserCache(userCache); return this; } @Override protected void initUserDetailsService() { if (!this.initScripts.isEmpty()) { getDataSourceInit().afterPropertiesSet(); } super.initUserDetailsService(); } @Override public JdbcUserDetailsManager getUserDetailsService() { return (JdbcUserDetailsManager) super.getUserDetailsService(); }
/** * Populates the default schema that allows users and authorities to be stored. * @return The {@link JdbcUserDetailsManagerConfigurer} used for additional * customizations */ public JdbcUserDetailsManagerConfigurer<B> withDefaultSchema() { this.initScripts.add(new ClassPathResource("org/springframework/security/core/userdetails/jdbc/users.ddl")); return this; } protected DatabasePopulator getDatabasePopulator() { ResourceDatabasePopulator dbp = new ResourceDatabasePopulator(); dbp.setScripts(this.initScripts.toArray(new Resource[0])); return dbp; } private DataSourceInitializer getDataSourceInit() { DataSourceInitializer dsi = new DataSourceInitializer(); dsi.setDatabasePopulator(getDatabasePopulator()); dsi.setDataSource(this.dataSource); return dsi; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\provisioning\JdbcUserDetailsManagerConfigurer.java
2
请在Spring Boot框架中完成以下Java代码
private List<SecurityContext> securityContexts() { //设置需要登录认证的路径 List<SecurityContext> result = new ArrayList<>(); result.add(getContextByPath("/*/.*")); return result; } private SecurityContext getContextByPath(String pathRegex) { return SecurityContext.builder() .securityReferences(defaultAuth()) .operationSelector(oc -> oc.requestMappingPattern().matches(pathRegex)) .build(); } private List<SecurityReference> defaultAuth() { List<SecurityReference> result = new ArrayList<>(); AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; result.add(new SecurityReference("Authorization", authorizationScopes)); return result; } public BeanPostProcessor generateBeanPostProcessor(){ return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) { customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
} return bean; } private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) { List<T> copy = mappings.stream() .filter(mapping -> mapping.getPatternParser() == null) .collect(Collectors.toList()); mappings.clear(); mappings.addAll(copy); } @SuppressWarnings("unchecked") private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) { try { Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings"); field.setAccessible(true); return (List<RequestMappingInfoHandlerMapping>) field.get(bean); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IllegalStateException(e); } } }; } /** * 自定义Swagger配置 */ public abstract SwaggerProperties swaggerProperties(); }
repos\mall-master\mall-common\src\main\java\com\macro\mall\common\config\BaseSwaggerConfig.java
2
请完成以下Java代码
private InputStream getFormattingConfiguration() { final InputStream importedConfiguration = this.domXmlDataFormat.getFormattingConfiguration(); if (importedConfiguration != null) { return importedConfiguration; } // default strip-spaces.xsl return DomXmlDataFormatWriter.class.getClassLoader().getResourceAsStream(STRIP_SPACE_XSL); } /** * Returns a configured transformer to write XML and apply indentation (pretty-print) to the xml. * * @return the XML configured transformer * @throws SpinXmlElementException if no new transformer can be created */ protected Transformer getFormattingTransformer() { try { Transformer transformer = formattingTemplates.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } } /**
* Returns a configured transformer to write XML as is. * * @return the XML configured transformer * @throws SpinXmlElementException if no new transformer can be created */ protected Transformer getTransformer() { TransformerFactory transformerFactory = domXmlDataFormat.getTransformerFactory(); try { Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); return transformer; } catch (TransformerConfigurationException e) { throw LOG.unableToCreateTransformer(e); } } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatWriter.java
1
请完成以下Java代码
public Map<String, List<VariableListener<?>>> getVariableListeners(String eventName, boolean includeCustomListeners) { Map<String, Map<String, List<VariableListener<?>>>> listenerCache; if (includeCustomListeners) { if (resolvedVariableListeners == null) { resolvedVariableListeners = new HashMap<String, Map<String,List<VariableListener<?>>>>(); } listenerCache = resolvedVariableListeners; } else { if (resolvedBuiltInVariableListeners == null) { resolvedBuiltInVariableListeners = new HashMap<String, Map<String,List<VariableListener<?>>>>(); } listenerCache = resolvedBuiltInVariableListeners; } Map<String, List<VariableListener<?>>> resolvedListenersForEvent = listenerCache.get(eventName); if (resolvedListenersForEvent == null) { resolvedListenersForEvent = new HashMap<String, List<VariableListener<?>>>(); listenerCache.put(eventName, resolvedListenersForEvent); CmmnActivity currentActivity = this; while (currentActivity != null) { List<VariableListener<?>> localListeners = null;
if (includeCustomListeners) { localListeners = currentActivity.getVariableListenersLocal(eventName); } else { localListeners = currentActivity.getBuiltInVariableListenersLocal(eventName); } if (localListeners != null && !localListeners.isEmpty()) { resolvedListenersForEvent.put(currentActivity.getId(), localListeners); } currentActivity = currentActivity.getParent(); } } return resolvedListenersForEvent; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnActivity.java
1
请完成以下Java代码
public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) { Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null"); this.localeCharsetMappings = localeCharsetMappings; } public void setInitParameters(Map<String, String> initParameters) { this.initParameters = initParameters; } public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers); } public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers));
} public void addWebListenerClassNames(String... webListenerClassNames) { this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames)); } public Set<String> getWebListenerClassNames() { return this.webListenerClassNames; } public List<URL> getStaticResourceUrls() { return this.staticResourceJars.getUrls(); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java
1
请在Spring Boot框架中完成以下Java代码
public class RecipientServiceImpl implements RecipientService { private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired private RecipientRepository repository; @Override public Recipient findByAccountName(String accountName) { Assert.hasLength(accountName); return repository.findByAccountName(accountName); } /** * {@inheritDoc} */ @Override public Recipient save(String accountName, Recipient recipient) { recipient.setAccountName(accountName); recipient.getScheduledNotifications().values() .forEach(settings -> { if (settings.getLastNotified() == null) { settings.setLastNotified(new Date()); } }); repository.save(recipient); log.info("recipient {} settings has been updated", recipient); return recipient; }
/** * {@inheritDoc} */ @Override public List<Recipient> findReadyToNotify(NotificationType type) { switch (type) { case BACKUP: return repository.findReadyForBackup(); case REMIND: return repository.findReadyForRemind(); default: throw new IllegalArgumentException(); } } /** * {@inheritDoc} */ @Override public void markNotified(NotificationType type, Recipient recipient) { recipient.getScheduledNotifications().get(type).setLastNotified(new Date()); repository.save(recipient); } }
repos\piggymetrics-master\notification-service\src\main\java\com\piggymetrics\notification\service\RecipientServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getReplacement() { return this.replacement; } public void setReplacement(String replacement) { this.replacement = replacement; } @Override public String toString() { return "Deprecation{level='" + this.level + '\'' + ", reason='" + this.reason + '\'' + ", replacement='" + this.replacement + '\'' + '}'; } /** * Define the deprecation level. */
public enum Level { /** * The property is still bound. */ WARNING, /** * The property has been removed and is no longer bound. */ ERROR } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\Deprecation.java
2
请完成以下Java代码
public <T> T getCustomMapper(Class<T> type) { return sqlSession.getMapper(type); } public boolean isMysql() { return dbSqlSessionFactory.getDatabaseType().equals("mysql"); } public boolean isMariaDb() { return dbSqlSessionFactory.getDatabaseType().equals("mariadb"); } public boolean isOracle() { return dbSqlSessionFactory.getDatabaseType().equals("oracle"); } // query factory methods // //////////////////////////////////////////////////// public DeploymentQueryImpl createDeploymentQuery() { return new DeploymentQueryImpl(); } public ModelQueryImpl createModelQueryImpl() { return new ModelQueryImpl(); } public ProcessDefinitionQueryImpl createProcessDefinitionQuery() { return new ProcessDefinitionQueryImpl(); } public ProcessInstanceQueryImpl createProcessInstanceQuery() { return new ProcessInstanceQueryImpl(); } public ExecutionQueryImpl createExecutionQuery() { return new ExecutionQueryImpl(); } public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); }
public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); } public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } // getters and setters // ////////////////////////////////////////////////////// public SqlSession getSqlSession() { return sqlSession; } public DbSqlSessionFactory getDbSqlSessionFactory() { return dbSqlSessionFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
1
请完成以下Java代码
protected Class findClass(final String name) throws ClassNotFoundException { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws ClassNotFoundException { return bundle.loadClass(name); } }); } catch (PrivilegedActionException e) { Exception cause = e.getException(); if (cause instanceof ClassNotFoundException) throw (ClassNotFoundException) cause; else throw (RuntimeException) cause; } } @Override protected URL findResource(final String name) { URL resource = AccessController.doPrivileged(new PrivilegedAction<URL>() { @Override public URL run() { return bundle.getResource(name); } }); if (classLoader != null && resource == null) { resource = classLoader.getResource(name); } return resource; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected Enumeration findResources(final String name) throws IOException { Enumeration<URL> urls; try { urls = AccessController.doPrivileged(new PrivilegedExceptionAction<Enumeration<URL>>() { @Override public Enumeration<URL> run() throws IOException { return bundle.getResources(name); } }); } catch (PrivilegedActionException e) { Exception cause = e.getException(); if (cause instanceof IOException) throw (IOException) cause; else throw (RuntimeException) cause; } if (urls == null) { urls = Collections.enumeration(new ArrayList<>()); }
return urls; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { Class clazz; try { clazz = findClass(name); } catch (ClassNotFoundException cnfe) { if (classLoader != null) { try { clazz = classLoader.loadClass(name); } catch (ClassNotFoundException e) { throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId() + " (" + bundle.getSymbolicName() + ")", cnfe); } } else { throw new ClassNotFoundException(name + " from bundle " + bundle.getBundleId() + " (" + bundle.getSymbolicName() + ")", cnfe); } } if (resolve) { resolveClass(clazz); } return clazz; } public Bundle getBundle() { return bundle; } }
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\BundleDelegatingClassLoader.java
1
请完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public String getImageUrl() {
return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
repos\springbootwebapp-master\src\main\java\guru\springframework\domain\Product.java
1
请完成以下Java代码
public void add(@NonNull final PrintingData printingData) { printerQueuesMap.add(printingData); } public FrontendPrinterData getDataAndClear() { final FrontendPrinterData data = printerQueuesMap.toFrontendPrinterData(); printerQueuesMap.clear(); return data; } // // // // // @RequiredArgsConstructor private static class PrinterQueuesMap { private final LinkedHashMap<HardwarePrinterId, PrinterQueue> queuesMap = new LinkedHashMap<>(); public void add(@NonNull PrintingData printingData) { printingData.getSegments().forEach(segment -> add(printingData, segment)); } private void add( @NonNull PrintingData printingData, @NonNull PrintingSegment segment) { final HardwarePrinter printer = segment.getPrinter(); getOrCreateQueue(printer).add(printingData, segment); } private PrinterQueue getOrCreateQueue(final HardwarePrinter printer) { return queuesMap.computeIfAbsent(printer.getId(), k -> new PrinterQueue(printer)); } public void clear() { queuesMap.clear(); } public FrontendPrinterData toFrontendPrinterData() { return queuesMap.values() .stream() .map(PrinterQueue::toFrontendPrinterData) .collect(GuavaCollectors.collectUsingListAccumulator(FrontendPrinterData::of)); } } @RequiredArgsConstructor private static class PrinterQueue { @NonNull private final HardwarePrinter printer; @NonNull private final ArrayList<PrintingDataAndSegment> segments = new ArrayList<>(); public void add( @NonNull PrintingData printingData, @NonNull PrintingSegment segment) { Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer); segments.add(PrintingDataAndSegment.of(printingData, segment)); } public FrontendPrinterDataItem toFrontendPrinterData() { return FrontendPrinterDataItem.builder()
.printer(printer) .filename(suggestFilename()) .data(toByteArray()) .build(); } private byte[] toByteArray() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos)) { for (PrintingDataAndSegment printingDataAndSegment : segments) { pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment()); } } return baos.toByteArray(); } private String suggestFilename() { final ImmutableSet<String> filenames = segments.stream() .map(PrintingDataAndSegment::getDocumentFileName) .collect(ImmutableSet.toImmutableSet()); return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf"; } } @Value(staticConstructor = "of") private static class PrintingDataAndSegment { @NonNull PrintingData printingData; @NonNull PrintingSegment segment; public String getDocumentFileName() { return printingData.getDocumentFileName(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
1
请在Spring Boot框架中完成以下Java代码
public void cronJob(JobForm form) throws Exception { try { TriggerKey triggerKey = TriggerKey.triggerKey(form.getJobClassName(), form.getJobGroupName()); // 表达式调度构建器 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(form.getCronExpression()); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 根据Cron表达式构建一个Trigger trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); // 按新的trigger重新设置job执行 scheduler.rescheduleJob(triggerKey, trigger); } catch (SchedulerException e) { log.error("【定时任务】更新失败!", e); throw new Exception("【定时任务】创建失败!"); } }
/** * 查询定时任务列表 * * @param currentPage 当前页 * @param pageSize 每页条数 * @return 定时任务列表 */ @Override public PageInfo<JobAndTrigger> list(Integer currentPage, Integer pageSize) { PageHelper.startPage(currentPage, pageSize); List<JobAndTrigger> list = jobMapper.list(); return new PageInfo<>(list); } }
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\service\impl\JobServiceImpl.java
2
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** * PersonalDataCategory AD_Reference_ID=540857 * Reference name: PersonalDataCategory */ public static final int PERSONALDATACATEGORY_AD_Reference_ID=540857; /** NotPersonal = NP */ public static final String PERSONALDATACATEGORY_NotPersonal = "NP"; /** Personal = P */ public static final String PERSONALDATACATEGORY_Personal = "P"; /** SensitivePersonal = SP */ public static final String PERSONALDATACATEGORY_SensitivePersonal = "SP"; /** Set Datenschutz-Kategorie. @param PersonalDataCategory Datenschutz-Kategorie */ @Override public void setPersonalDataCategory (java.lang.String PersonalDataCategory) { set_Value (COLUMNNAME_PersonalDataCategory, PersonalDataCategory); } /** Get Datenschutz-Kategorie. @return Datenschutz-Kategorie */ @Override public java.lang.String getPersonalDataCategory () { return (java.lang.String)get_Value(COLUMNNAME_PersonalDataCategory); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Field.java
1
请在Spring Boot框架中完成以下Java代码
public class ParallelJobService { @Autowired private JobLauncher jobLauncher; @Autowired private Job jobOne; @Autowired private Job jobTwo; public void runJobsInParallel() { SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); taskExecutor.execute(() -> { try { jobLauncher.run(jobOne, new JobParametersBuilder().addString("ID", "Parallel 1")
.toJobParameters()); } catch (Exception e) { e.printStackTrace(); } }); taskExecutor.execute(() -> { try { jobLauncher.run(jobTwo, new JobParametersBuilder().addString("ID", "Parallel 2") .toJobParameters()); } catch (Exception e) { e.printStackTrace(); } }); taskExecutor.close(); } }
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\springbatch\jobs\ParallelJobService.java
2
请完成以下Java代码
public class CreateAccountAsyncEvent implements AccountAsyncEvent { private final String id; private final String accountId; private final String name; private final Integer credit; @JsonCreator public CreateAccountAsyncEvent(@JsonProperty("id") String id, @JsonProperty("accountId") String accountId, @JsonProperty("name") String name, @JsonProperty("credit") Integer credit) { this.id = id; this.accountId = accountId; this.name = name; this.credit = credit; } @Override public String getId() { return id; } @Override public String keyMessageKey() {
return accountId; } public String getAccountId() { return accountId; } public String getName() { return name; } public Integer getCredit() { return credit; } }
repos\spring-examples-java-17\spring-kafka\kafka-common\src\main\java\itx\examples\spring\kafka\events\CreateAccountAsyncEvent.java
1
请完成以下Java代码
public class AuthorDto implements Serializable { private static final long serialVersionUID = 1L; private Long authorId; private String name; private int age; private List<BookDto> books = new ArrayList<>(); public AuthorDto() { } public AuthorDto(Long authorId, String name, int age) { this.authorId = authorId; this.name = name; this.age = age; } public Long getId() { return authorId; } public void setId(Long authorId) { this.authorId = authorId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() {
return age; } public void setAge(int age) { this.age = age; } public List<BookDto> getBooks() { return books; } public void setBooks(List<BookDto> books) { this.books = books; } public void addBook(BookDto book) { books.add(book); } @Override public String toString() { return "AuthorDto{" + "authorId=" + authorId + ", name=" + name + ", age=" + age + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoCustomResultTransformer\src\main\java\com\bookstore\dto\AuthorDto.java
1
请完成以下Java代码
private static void addRoute(CamelContext context) throws Exception { context.addRoutes(newExchangeRoute()); } static RoutesBuilder traditionalWireTapRoute() { return new RouteBuilder() { public void configure() { from("direct:source").log("Main route: Send '${body}' to tap router").wireTap("direct:tap").delay(1000) .log("Main route: Add 'two' to '${body}'").bean(MyBean.class, "addTwo").to("direct:destination") .log("Main route: Output '${body}'"); from("direct:tap").log("Tap Wire route: received '${body}'") .log("Tap Wire route: Add 'three' to '${body}'").bean(MyBean.class, "addThree") .log("Tap Wire route: Output '${body}'");
from("direct:destination").log("Output at destination: '${body}'"); } }; } static RoutesBuilder newExchangeRoute() throws Exception { return new RouteBuilder() { public void configure() throws Exception { from("direct:source").wireTap("direct:tap").onPrepare(new MyPayloadClonePrepare()).end().delay(1000); from("direct:tap").bean(MyBean.class, "addThree"); } }; } }
repos\tutorials-master\patterns-modules\enterprise-patterns\src\main\java\com\baeldung\AmqApplication.java
1
请完成以下Java代码
protected void persistDefinition(DecisionRequirementsDefinitionEntity definition) { if (isDecisionRequirementsDefinitionPersistable(definition)) { getDecisionRequirementsDefinitionManager().insertDecisionRequirementsDefinition(definition); } } @Override protected void addDefinitionToDeploymentCache(DeploymentCache deploymentCache, DecisionRequirementsDefinitionEntity definition) { if (isDecisionRequirementsDefinitionPersistable(definition)) { deploymentCache.addDecisionRequirementsDefinition(definition); } } @Override protected void ensureNoDuplicateDefinitionKeys(List<DecisionRequirementsDefinitionEntity> definitions) { // ignore decision requirements definitions which will not be persistent ArrayList<DecisionRequirementsDefinitionEntity> persistableDefinitions = new ArrayList<DecisionRequirementsDefinitionEntity>(); for (DecisionRequirementsDefinitionEntity definition : definitions) { if (isDecisionRequirementsDefinitionPersistable(definition)) { persistableDefinitions.add(definition); } } super.ensureNoDuplicateDefinitionKeys(persistableDefinitions); } public static boolean isDecisionRequirementsDefinitionPersistable(DecisionRequirementsDefinitionEntity definition) { // persist no decision requirements definition for a single decision return definition.getDecisions().size() > 1; } @Override protected void updateDefinitionByPersistedDefinition(DeploymentEntity deployment, DecisionRequirementsDefinitionEntity definition, DecisionRequirementsDefinitionEntity persistedDefinition) { // cannot update the definition if it is not persistent if (persistedDefinition != null) { super.updateDefinitionByPersistedDefinition(deployment, definition, persistedDefinition); }
} //context /////////////////////////////////////////////////////////////////////////////////////////// protected DecisionRequirementsDefinitionManager getDecisionRequirementsDefinitionManager() { return getCommandContext().getDecisionRequirementsDefinitionManager(); } // getters/setters /////////////////////////////////////////////////////////////////////////////////// public DmnTransformer getTransformer() { return transformer; } public void setTransformer(DmnTransformer transformer) { this.transformer = transformer; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\deployer\DecisionRequirementsDefinitionDeployer.java
1
请完成以下Java代码
private ILUTUConfigurationEditor setEditingLUTUConfiguration(final I_M_HU_LUTU_Configuration lutuConfiguration) { if (lutuConfiguration != null && lutuConfiguration.getM_HU_LUTU_Configuration_ID() > 0) { throw new IllegalArgumentException("Editing configuration shall be a configuration which is not saved yet"); } _lutuConfigurationEditing = lutuConfiguration; return this; } @Override public ILUTUConfigurationEditor edit(final Function<I_M_HU_LUTU_Configuration, I_M_HU_LUTU_Configuration> lutuConfigurationEditor) { assertEditing(); Check.assumeNotNull(lutuConfigurationEditor, "lutuConfigurationEditor not null"); final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration(); final I_M_HU_LUTU_Configuration lutuConfigurationEditingNew = lutuConfigurationEditor.apply(lutuConfigurationEditing); setEditingLUTUConfiguration(lutuConfigurationEditingNew); return this; } @Override public ILUTUConfigurationEditor updateFromModel() { assertEditing(); final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration(); lutuConfigurationManager.updateLUTUConfigurationFromModel(lutuConfigurationEditing); return this; } @Override public boolean isEditing() { return _lutuConfigurationEditing != null; } private final void assertEditing() { Check.assume(isEditing(), HUException.class, "Editor shall be in editing mode"); } @Override public ILUTUConfigurationEditor save() { assertEditing(); final I_M_HU_LUTU_Configuration lutuConfigurationInitial = getLUTUConfiguration(); final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration(); // // Check if we need to use the new configuration or we are ok with the old one final I_M_HU_LUTU_Configuration lutuConfigurationToUse; if (InterfaceWrapperHelper.isNew(lutuConfigurationInitial))
{ lutuFactory.save(lutuConfigurationEditing); lutuConfigurationToUse = lutuConfigurationEditing; } else if (lutuFactory.isSameForHUProducer(lutuConfigurationInitial, lutuConfigurationEditing)) { // Copy all values from our new configuration to initial configuration InterfaceWrapperHelper.copyValues(lutuConfigurationEditing, lutuConfigurationInitial, false); // honorIsCalculated=false lutuFactory.save(lutuConfigurationInitial); lutuConfigurationToUse = lutuConfigurationInitial; } else { lutuFactory.save(lutuConfigurationEditing); lutuConfigurationToUse = lutuConfigurationEditing; } _lutuConfigurationInitial = lutuConfigurationToUse; _lutuConfigurationEditing = null; // stop editing mode return this; } @Override public ILUTUConfigurationEditor pushBackToModel() { if (isEditing()) { save(); } final I_M_HU_LUTU_Configuration lutuConfiguration = getLUTUConfiguration(); lutuConfigurationManager.setCurrentLUTUConfigurationAndSave(lutuConfiguration); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\LUTUConfigurationEditor.java
1
请完成以下Java代码
public Permission getPermission() throws IOException { if (this.permission == null) { File file = this.resources.getLocation().path().toFile(); this.permission = new FilePermission(file.getCanonicalPath(), "read"); } return this.permission; } @Override public InputStream getInputStream() throws IOException { connect(); return new ConnectionInputStream(this.resources.getInputStream()); } @Override public void connect() throws IOException { if (this.connected) { return; } this.resources.connect(); this.connected = true; } /** * Connection {@link InputStream}. */ class ConnectionInputStream extends FilterInputStream { private volatile boolean closing; ConnectionInputStream(InputStream in) { super(in); } @Override public void close() throws IOException {
if (this.closing) { return; } this.closing = true; try { super.close(); } finally { try { NestedUrlConnection.this.cleanup.clean(); } catch (UncheckedIOException ex) { throw ex.getCause(); } } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnection.java
1
请完成以下Java代码
public void setAD_PInstance_Log_ID (final int AD_PInstance_Log_ID) { if (AD_PInstance_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PInstance_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PInstance_Log_ID, AD_PInstance_Log_ID); } @Override public int getAD_PInstance_Log_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_Log_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null); else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setLog_ID (final int Log_ID) { if (Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Log_ID, Log_ID); } @Override public int getLog_ID() { return get_ValueAsInt(COLUMNNAME_Log_ID); } @Override public void setP_Date (final @Nullable java.sql.Timestamp P_Date) { set_ValueNoCheck (COLUMNNAME_P_Date, P_Date); } @Override public java.sql.Timestamp getP_Date() { return get_ValueAsTimestamp(COLUMNNAME_P_Date); } @Override public void setP_Msg (final @Nullable java.lang.String P_Msg) { set_ValueNoCheck (COLUMNNAME_P_Msg, P_Msg); } @Override
public java.lang.String getP_Msg() { return get_ValueAsString(COLUMNNAME_P_Msg); } @Override public void setP_Number (final @Nullable BigDecimal P_Number) { set_ValueNoCheck (COLUMNNAME_P_Number, P_Number); } @Override public BigDecimal getP_Number() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_P_Number); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setWarnings (final @Nullable java.lang.String Warnings) { set_Value (COLUMNNAME_Warnings, Warnings); } @Override public java.lang.String getWarnings() { return get_ValueAsString(COLUMNNAME_Warnings); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PInstance_Log.java
1
请完成以下Java代码
public class TaiwanToHongKongChineseDictionary extends BaseChineseDictionary { static AhoCorasickDoubleArrayTrie<String> trie = new AhoCorasickDoubleArrayTrie<String>(); static { long start = System.currentTimeMillis(); String datPath = HanLP.Config.tcDictionaryRoot + "tw2hk"; if (!loadDat(datPath, trie)) { TreeMap<String, String> t2hk = new TreeMap<String, String>(); TreeMap<String, String> tw2t = new TreeMap<String, String>(); if (!load(t2hk, false, HanLP.Config.tcDictionaryRoot + "t2hk.txt") || !load(tw2t, true, HanLP.Config.tcDictionaryRoot + "t2tw.txt")) { throw new IllegalArgumentException("台湾繁体转香港繁体词典加载失败"); } combineReverseChain(t2hk, tw2t, false);
trie.build(t2hk); saveDat(datPath, trie, t2hk.entrySet()); } logger.info("台湾繁体转香港繁体词典加载成功,耗时" + (System.currentTimeMillis() - start) + "ms"); } public static String convertToTraditionalHongKongChinese(String traditionalTaiwanChinese) { return segLongest(traditionalTaiwanChinese.toCharArray(), trie); } public static String convertToTraditionalHongKongChinese(char[] traditionalTaiwanChinese) { return segLongest(traditionalTaiwanChinese, trie); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ts\TaiwanToHongKongChineseDictionary.java
1
请在Spring Boot框架中完成以下Java代码
public class FileItemWriterDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private ListItemReader<TestData> simpleReader; @Bean public Job fileItemWriterJob() throws Exception { return jobBuilderFactory.get("fileItemWriterJob") .start(step()) .build(); } private Step step() throws Exception { return stepBuilderFactory.get("step") .<TestData, TestData>chunk(2) .reader(simpleReader) .writer(fileItemWriter()) .build(); } private FlatFileItemWriter<TestData> fileItemWriter() throws Exception {
FlatFileItemWriter<TestData> writer = new FlatFileItemWriter<>(); FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file"); Path path = Paths.get(file.getPath()); if (!Files.exists(path)) { Files.createFile(path); } writer.setResource(file); // 设置目标文件路径 // 把读到的每个TestData对象转换为JSON字符串 LineAggregator<TestData> aggregator = item -> { try { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(item); } catch (JsonProcessingException e) { e.printStackTrace(); } return ""; }; writer.setLineAggregator(aggregator); writer.afterPropertiesSet(); return writer; } }
repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\FileItemWriterDemo.java
2
请完成以下Java代码
public List<SingleQueryVariableValueCondition> getDisjunctiveConditions() { return Collections.singletonList(this); } public String getName() { return wrappedQueryValue.getName(); } public String getTextValue() { return textValue; } public void setTextValue(String textValue) { this.textValue = textValue; } public String getTextValue2() { return textValue2; } public void setTextValue2(String textValue2) { this.textValue2 = textValue2; } public Long getLongValue() { return longValue; } public void setLongValue(Long longValue) { this.longValue = longValue; } public Double getDoubleValue() { return doubleValue; } public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; }
public byte[] getByteArrayValue() { return null; } public void setByteArrayValue(byte[] bytes) { } public String getType() { return type; } public boolean getFindNulledEmptyStrings() { return findNulledEmptyStrings; } public void setFindNulledEmptyStrings(boolean findNulledEmptyStrings) { this.findNulledEmptyStrings = findNulledEmptyStrings; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\SingleQueryVariableValueCondition.java
1
请完成以下Java代码
public Long getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getBrand() { return brand;
} public void setBrand(String brand) { this.brand = brand; } @Override public String toString() { return "MerchandiseEntity{" + "id=" + id + ", title='" + title + '\'' + ", price=" + price + ", brand='" + brand + '\'' + '}'; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\boot\domain\MerchandiseEntity.java
1
请完成以下Java代码
public class DmnExtensionAttribute { protected String name; protected String value; protected String namespacePrefix; protected String namespace; public DmnExtensionAttribute() { } public DmnExtensionAttribute(String name) { this.name = name; } public DmnExtensionAttribute(String namespace, String name) { this.namespace = namespace; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getNamespacePrefix() { return namespacePrefix; } public void setNamespacePrefix(String namespacePrefix) { this.namespacePrefix = namespacePrefix; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); if (namespacePrefix != null) { sb.append(namespacePrefix); if (name != null) { sb.append(":").append(name); } } else { sb.append(name); } if (value != null) { sb.append("=").append(value); } return sb.toString(); } @Override public DmnExtensionAttribute clone() { DmnExtensionAttribute clone = new DmnExtensionAttribute(); clone.setValues(this); return clone; } public void setValues(DmnExtensionAttribute otherAttribute) { setName(otherAttribute.getName()); setValue(otherAttribute.getValue()); setNamespacePrefix(otherAttribute.getNamespacePrefix()); setNamespace(otherAttribute.getNamespace()); } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionAttribute.java
1
请完成以下Java代码
public class BankTransactionCodeStructure6 { @XmlElement(name = "Cd", required = true) protected String cd; @XmlElement(name = "SubFmlyCd", required = true) protected String subFmlyCd; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) { this.cd = value; }
/** * Gets the value of the subFmlyCd property. * * @return * possible object is * {@link String } * */ public String getSubFmlyCd() { return subFmlyCd; } /** * Sets the value of the subFmlyCd property. * * @param value * allowed object is * {@link String } * */ public void setSubFmlyCd(String value) { this.subFmlyCd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BankTransactionCodeStructure6.java
1
请完成以下Java代码
public Object getSession (HttpServletRequest request){ Map<String, Object> map = new HashMap<>(); map.put("sessionId", request.getSession().getId()); map.put("message", request.getSession().getAttribute("message")); return map; } @RequestMapping(value = "/index") public String index (HttpServletRequest request){ String msg="index content"; Object user= request.getSession().getAttribute("user"); if (user==null){ msg="please login first!"; }
return msg; } @RequestMapping(value = "/login") public String login (HttpServletRequest request,String userName,String password){ String msg="logon failure!"; User user= userRepository.findByUserName(userName); if (user!=null && user.getPassword().equals(password)){ request.getSession().setAttribute("user",user); msg="login successful!"; } return msg; } }
repos\spring-boot-leaning-master\1.x\第10课:Redis实现数据缓存和Session共享\spring-boot-redis-session\src\main\java\com\neo\web\UserController.java
1
请完成以下Java代码
public boolean canRunProcess(@NonNull final AdProcessId processId) { final PermissionRequest permissionRequest = PermissionRequest.builder() .orgId(OrgId.ANY) .processId(processId.getRepoId()) .build(); if (permissionsGranted.contains(permissionRequest)) { return true; } final IUserRolePermissions userPermissions = userRolePermissionsRepo.getUserRolePermissions(userRolePermissionsKey); final boolean canAccessProcess = userPermissions.checkProcessAccessRW(processId.getRepoId()); if (canAccessProcess) { permissionsGranted.add(permissionRequest); } return canAccessProcess; } private void assertPermission(@NonNull final PermissionRequest request) { if (permissionsGranted.contains(request)) { return; } final IUserRolePermissions userPermissions = userRolePermissionsRepo.getUserRolePermissions(userRolePermissionsKey); final BooleanWithReason allowed; if (request.getRecordId() >= 0) { allowed = userPermissions.checkCanUpdate( userPermissions.getClientId(), request.getOrgId(), request.getAdTableId(), request.getRecordId()); } else { allowed = userPermissions.checkCanCreateNewRecord( userPermissions.getClientId(), request.getOrgId(), AdTableId.ofRepoId(request.getAdTableId())); } if (allowed.isFalse()) {
throw new PermissionNotGrantedException(allowed.getReason()); } else { permissionsGranted.add(request); } } @lombok.Value @lombok.Builder private static class PermissionRequest { @lombok.NonNull OrgId orgId; @lombok.Builder.Default int adTableId = -1; @lombok.Builder.Default int recordId = -1; @lombok.Builder.Default int processId = -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions2\PermissionService.java
1
请完成以下Java代码
public class OrderItem { private Long id; private Double price; private OrderItemCategory category; public OrderItem(long id, OrderItemCategory category, double price) { this.id = id; this.category = category; this.price = price; } public OrderItemCategory getCategory() { return category; } public void setCategory(OrderItemCategory category) { this.category = category; }
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\minmaxbygroup\OrderItem.java
1
请完成以下Java代码
public void determineEntityReferences() { if (dbEntity instanceof HasDbReferences) { flushRelevantEntityReferences = ((HasDbReferences) dbEntity).getReferencedEntityIds(); } else { flushRelevantEntityReferences = Collections.emptySet(); } } public boolean areFlushRelevantReferencesDetermined() { return flushRelevantEntityReferences != null; } public Set<String> getFlushRelevantEntityReferences() { return flushRelevantEntityReferences; } // getters / setters //////////////////////////// public DbEntity getEntity() { return dbEntity; } public void setEntity(DbEntity dbEntity) { this.dbEntity = dbEntity;
} public DbEntityState getEntityState() { return entityState; } public void setEntityState(DbEntityState entityState) { this.entityState = entityState; } public Class<? extends DbEntity> getEntityType() { return dbEntity.getClass(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\cache\CachedDbEntity.java
1
请完成以下Java代码
public String getTableName() { return tableName; } /** * Gets the context value for the given {@code variableName} by calling {@link Env#getContext(Properties, int, int, String, Scope)} with {@link Scope#Window}. */ @Override public String get_ValueAsString(final String variableName) { Check.assumeNotNull(variableName, "variableName not null"); if(PARAMETER_ContextTableName.equals(variableName)) { return contextTableName; } // only checking the window scope; global scope might contain default values (e.g. #C_DocTypeTarget_ID) that might confuse a validation rule final String value = Env.getContext(ctx, windowNo, tabNo, variableName, Scope.Window); if (Env.isNumericPropertyName(variableName) && Env.isPropertyValueNull(variableName, value)) { // Because empty fields are not exported in context, even if they are present in Tab
// is better to return "-1" as default value, to make this explicit // and also to not make Env.parseContext log a WARNING message return "-1"; } return value; } @Override public String toString() { return "GridTabValidationContext [windowNo=" + windowNo + ", tabNo=" + tabNo + ", contextTableName=" + contextTableName + ", tableName=" + tableName + ", ctx=" + ctx + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\GridTabValidationContext.java
1
请完成以下Java代码
private static JsonTaxCategoryMapping toJsonTaxCategoryMapping(@NonNull final TaxCategoryPCMMapping taxCategory) { return JsonTaxCategoryMapping.builder() .taxCategory(taxCategory.getTaxCategory().getInternalName()) .taxRates(taxCategory.getTaxRates().asList()) .build(); } @NonNull private static Map<String, String> extractLocalFileSourceParameters(@NonNull final PCMContentSourceLocalFile contentSourceLocalFile) { final Map<String, String> parameters = new HashMap<>(); parameters.put(PARAM_LOCAL_FILE_PROCESSED_DIRECTORY, contentSourceLocalFile.getProcessedDirectory()); parameters.put(PARAM_LOCAL_FILE_ERRORED_DIRECTORY, contentSourceLocalFile.getErroredDirectory()); parameters.put(PARAM_LOCAL_FILE_POLLING_FREQUENCY_MS, String.valueOf(contentSourceLocalFile.getPollingFrequency().toMillis())); parameters.put(PARAM_LOCAL_FILE_ROOT_LOCATION, contentSourceLocalFile.getRootLocation());
parameters.put(PARAM_LOCAL_FILE_PRODUCT_FILE_NAME_PATTERN, contentSourceLocalFile.getFileNamePatternProduct()); parameters.put(PARAM_LOCAL_FILE_BPARTNER_FILE_NAME_PATTERN, contentSourceLocalFile.getFileNamePatternBPartner()); parameters.put(PARAM_LOCAL_FILE_WAREHOUSE_FILE_NAME_PATTERN, contentSourceLocalFile.getFileNamePatternWarehouse()); parameters.put(PARAM_LOCAL_FILE_PURCHASE_ORDER_FILE_NAME_PATTERN, contentSourceLocalFile.getFileNamePatternPurchaseOrder()); return parameters; } private static void throwErrorIfFalse(@NonNull final BooleanWithReason booleanWithReason) { if (booleanWithReason.isFalse()) { throw new AdempiereException(booleanWithReason.getReason()).markAsUserValidationError(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\pcm\InvokePCMService.java
1
请完成以下Java代码
private Optional<ProductsToProcess> getProductsToProcess(@NonNull final InventoryId inventoryId) { final Action actionToRun = getActionToRun(inventoryId); if (actionToRun == null) { // throw new AdempiereException("@Invalid@ @DocStatus@"); return Optional.empty(); } final ProductsToProcess.ProductsToProcessBuilder resultBuilder = ProductsToProcess.builder() .action(actionToRun) .inventoryId(inventoryId); for (final SecurPharmProduct product : securPharmService.findProductsToDecommissionForInventoryId(inventoryId)) { if (actionToRun == Action.DECOMMISSION) { if (securPharmService.isEligibleForDecommission(product)) { resultBuilder.product(product); } } else if (actionToRun == Action.UNDO_DECOMMISSION) { if (securPharmService.isEligibleForUndoDecommission(product)) { resultBuilder.product(product); } } } final ProductsToProcess result = resultBuilder.build(); if (result.isEmpty()) { return Optional.empty(); } return Optional.of(result); } private void process(@NonNull final ProductsToProcess productsToProcess) { final Action action = productsToProcess.getAction(); final InventoryId inventoryId = productsToProcess.getInventoryId(); for (final SecurPharmProduct product : productsToProcess.getProducts()) { process(product, action, inventoryId); } } private void process( @NonNull final SecurPharmProduct product, @NonNull final Action action, @NonNull final InventoryId inventoryId) { if (action == Action.DECOMMISSION)
{ securPharmService.decommissionProductIfEligible(product, inventoryId); } else if (action == Action.UNDO_DECOMMISSION) { securPharmService.undoDecommissionProductIfEligible(product, inventoryId); } else { throw new AdempiereException("Invalid action: " + action); } } private Action getActionToRun(@NonNull final InventoryId inventoryId) { final DocStatus inventoryDocStatus = Services.get(IInventoryBL.class).getDocStatus(inventoryId); if (DocStatus.Completed.equals(inventoryDocStatus)) { return Action.DECOMMISSION; } else if (DocStatus.Reversed.equals(inventoryDocStatus)) { return Action.UNDO_DECOMMISSION; } else { return null; } } private enum Action { DECOMMISSION, UNDO_DECOMMISSION } @Value @Builder private static class ProductsToProcess { @NonNull Action action; @NonNull InventoryId inventoryId; @NonNull @Singular ImmutableList<SecurPharmProduct> products; public boolean isEmpty() { return getProducts().isEmpty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\process\M_Inventory_SecurpharmActionRetry.java
1
请完成以下Java代码
public Pet status(StatusEnum status) { this.status = status; return this; } /** * pet status in the store * @return status **/ @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pet pet = (Pet) o; return Objects.equals(this.id, pet.id) && Objects.equals(this.category, pet.category) && Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && Objects.equals(this.status, pet.status); } @Override public int hashCode() { return Objects.hash(id, category, name, photoUrls, tags, status); } @Override public String toString() {
StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" category: ").append(toIndentedString(category)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Pet.java
1
请在Spring Boot框架中完成以下Java代码
class AspectJMethodMatcher implements MethodMatcher, ClassFilter, Pointcut { private static final PointcutParser parser; static { Set<PointcutPrimitive> supportedPrimitives = new HashSet<>(3); supportedPrimitives.add(PointcutPrimitive.EXECUTION); supportedPrimitives.add(PointcutPrimitive.ARGS); supportedPrimitives.add(PointcutPrimitive.REFERENCE); parser = PointcutParser .getPointcutParserSupportingSpecifiedPrimitivesAndUsingContextClassloaderForResolution(supportedPrimitives); } private final PointcutExpression expression; AspectJMethodMatcher(String expression) { this.expression = parser.parsePointcutExpression(expression); } @Override public boolean matches(Class<?> clazz) { return this.expression.couldMatchJoinPointsInType(clazz); } @Override public boolean matches(Method method, Class<?> targetClass) { return this.expression.matchesMethodExecution(method).alwaysMatches(); } @Override public boolean isRuntime() {
return false; } @Override public boolean matches(Method method, Class<?> targetClass, Object... args) { return matches(method, targetClass); } @Override public ClassFilter getClassFilter() { return this; } @Override public MethodMatcher getMethodMatcher() { return this; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\AspectJMethodMatcher.java
2
请完成以下Java代码
private void setIsFavorite(List<ArticleData> articles, User currentUser) { Set<String> favoritedArticles = articleFavoritesReadService.userFavorites(articles.stream().map(articleData -> articleData.getId()).collect(toList()), currentUser); articles.forEach(articleData -> { if (favoritedArticles.contains(articleData.getId())) { articleData.setFavorited(true); } }); } private void fillExtraInfo(String id, User user, ArticleData articleData) { articleData.setFavorited(articleFavoritesReadService.isUserFavorite(user.getId(), id)); articleData.setFavoritesCount(articleFavoritesReadService.articleFavoriteCount(id)); articleData.getProfileData().setFollowing( userRelationshipQueryService.isUserFollowing( user.getId(),
articleData.getProfileData().getId())); } public ArticleDataList findUserFeed(User user, Page page) { List<String> followdUsers = userRelationshipQueryService.followedUsers(user.getId()); if (followdUsers.size() == 0) { return new ArticleDataList(new ArrayList<>(), 0); } else { List<ArticleData> articles = articleReadService.findArticlesOfAuthors(followdUsers, page); fillExtraInfo(articles, user); int count = articleReadService.countFeedSize(followdUsers); return new ArticleDataList(articles, count); } } }
repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\application\ArticleQueryService.java
1
请完成以下Java代码
private static final boolean startsWithIgnoreCase(final String str1, final String str2) { final String s1 = StringUtils.stripDiacritics(str1.toUpperCase()).replaceAll("^\\s+", ""); final String s2 = StringUtils.stripDiacritics(str2.toUpperCase()).replaceAll("^\\s+", ""); return s1.startsWith(s2); } /** * Converts the combo value to string. * * This method tries to fetch the text as is rendered by the renderer if possible. We do this because the value's toString() might be different from what is rendered, and user sees and writes what * is rendered. * * If it's not possible it will fallback to "toString". * * @param value */ private final String valueToString(final E value) { if (value == null) { return ""; } final ListCellRenderer<? super E> renderer = comboBox.getRenderer(); if (renderer == null) { return value.toString(); } final JList<E> list = getJList(); if (list == null) { return value.toString(); } final int index = 0; // NOTE: most of the renderers are not using it. Also it is known that is not correct. final Component valueComp = renderer.getListCellRendererComponent(list, value, index, false, false); if (valueComp instanceof JLabel) { return ((JLabel)valueComp).getText(); } return value.toString(); } /** @return combobox's inner JList (if available) */ private JList<E> getJList() { final ComboPopup comboPopup = AdempiereComboBoxUI.getComboPopup(comboBox); if (comboPopup == null) { return null; } @SuppressWarnings("unchecked") final JList<E> list = (JList<E>)comboPopup.getList(); return list; } private final class EditingCommand { private boolean doSelectItem = false; private E itemToSelect = null; private boolean doSetText = false; private String textToSet = null; private boolean doHighlightText = false; private int highlightTextStartPosition = 0; public void setItemToSelect(final E itemToSelect)
{ this.itemToSelect = itemToSelect; this.doSelectItem = true; } public boolean isDoSelectItem() { return doSelectItem; } public E getItemToSelect() { return itemToSelect; } public void setTextToSet(String textToSet) { this.textToSet = textToSet; this.doSetText = true; } public boolean isDoSetText() { return doSetText; } public String getTextToSet() { return textToSet; } public void setHighlightTextStartPosition(int highlightTextStartPosition) { this.highlightTextStartPosition = highlightTextStartPosition; this.doHighlightText = true; } public boolean isDoHighlightText() { return doHighlightText; } public int getHighlightTextStartPosition() { return highlightTextStartPosition; } }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\ComboBoxAutoCompletion.java
1
请完成以下Java代码
protected boolean beforeSave(final boolean newRecord) { if (is_ValueChanged(COLUMNNAME_DatePattern)) { assertValidDatePattern(this); } return true; } private static final void assertValidDatePattern(I_AD_Language language) { final String datePattern = language.getDatePattern(); if (Check.isEmpty(datePattern)) { return; // OK } if (datePattern.indexOf("MM") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Month (MM)"); } if (datePattern.indexOf("dd") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Day (dd)");
} if (datePattern.indexOf("yy") == -1) { throw new AdempiereException("@Error@ @DatePattern@ - No Year (yy)"); } final Locale locale = new Locale(language.getLanguageISO(), language.getCountryCode()); final SimpleDateFormat dateFormat = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale); try { dateFormat.applyPattern(datePattern); } catch (final Exception e) { throw new AdempiereException("@Error@ @DatePattern@ - " + e.getMessage(), e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLanguage.java
1
请在Spring Boot框架中完成以下Java代码
public long contentLength() { return responseBody.contentLength(); } @Override public BufferedSource source() { if (bufferedSource == null) { bufferedSource = Okio.buffer(source(responseBody.source())); } return bufferedSource; } private Source source(Source source) {
return new ForwardingSource(source) { long totalBytesRead = 0L; @Override public long read(Buffer sink, long byteCount) throws IOException { long bytesRead = super.read(sink, byteCount); // read() returns the number of bytes read, or -1 if this source is exhausted. totalBytesRead += bytesRead != -1 ? bytesRead : 0; callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); return bytesRead; } }; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\invoker\ProgressResponseBody.java
2
请在Spring Boot框架中完成以下Java代码
public Object update() { // 创建条件对象 Criteria criteria = Criteria.where("age").is(30); // 创建查询对象,然后将条件对象添加到其中 Query query = new Query(criteria); // 创建更新对象,并设置更新的内容 Update update = new Update().set("age", 33).set("name", "zhangsansan"); // 执行更新,如果没有找到匹配查询的文档,则创建并插入一个新文档 UpdateResult result = mongoTemplate.upsert(query, update, User.class, COLLECTION_NAME); // 输出结果信息 String resultInfo = "匹配到" + result.getMatchedCount() + "条数据,对第一条数据进行了更改"; log.info("更新结果:{}", resultInfo); return resultInfo; } /** * 更新集合中【匹配】查询到的【文档数据集合】中的【第一条数据】 * * @return 执行更新的结果 */ public Object updateFirst() { // 创建条件对象 Criteria criteria = Criteria.where("name").is("zhangsan"); // 创建查询对象,然后将条件对象添加到其中,并设置排序 Query query = new Query(criteria).with(Sort.by("age").ascending()); // 创建更新对象,并设置更新的内容 Update update = new Update().set("age", 30).set("name", "zhangsansan"); // 执行更新 UpdateResult result = mongoTemplate.updateFirst(query, update, User.class, COLLECTION_NAME); // 输出结果信息 String resultInfo = "共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据"; log.info("更新结果:{}", resultInfo); return resultInfo; }
/** * 更新【匹配查询】到的【文档数据集合】中的【所有数据】 * * @return 执行更新的结果 */ public Object updateMany() { // 创建条件对象 Criteria criteria = Criteria.where("age").gt(28); // 创建查询对象,然后将条件对象添加到其中 Query query = new Query(criteria); // 设置更新字段和更新的内容 Update update = new Update().set("age", 29).set("salary", "1999"); // 执行更新 UpdateResult result = mongoTemplate.updateMulti(query, update, User.class, COLLECTION_NAME); // 输出结果信息 String resultInfo = "总共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据"; log.info("更新结果:{}", resultInfo); return resultInfo; } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\UpdateService.java
2
请完成以下Java代码
protected void compute() { if (Objects.isNull(file)) { return; } File[] files = file.listFiles(); List<ForkJoinSearchFileTask> fileTasks = new ArrayList<>(); if (Objects.nonNull(files)) { for (File f : files) { // 拆分任务 if (f.isDirectory()) { fileTasks.add(new ForkJoinSearchFileTask(f, suffix)); } else { if (f.getAbsolutePath().endsWith(suffix)) { System.out.println(Thread.currentThread().getName() + " 文件: " + f.getAbsolutePath()); } } } // 提交并执行任务 invokeAll(fileTasks); for (ForkJoinSearchFileTask fileTask : fileTasks) { // 等待任务执行完成 fileTask.join(); } } }
public static void main(String[] args) throws Exception { File file = new File("d:/"); ForkJoinPool pool = new ForkJoinPool(); // 生成一个计算任务,负责查找指定木目录 ForkJoinSearchFileTask searchFileTask = new ForkJoinSearchFileTask(file, ".txt"); // 异步执行一个任务 pool.execute(searchFileTask); Thread.sleep(10); // 做另外的事情 int count = 0; for (int i = 0; i < 1000; i++) { count += i; } System.out.println("计算任务:" + count); // join方法是一个阻塞方法,会等待任务执行完成 searchFileTask.join(); } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ForkJoinSearchFileTask.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_PP_WF_Node_Asset[") .append(get_ID()).append("]"); return sb.toString(); } public I_A_Asset getA_Asset() throws RuntimeException { return (I_A_Asset)MTable.get(getCtx(), I_A_Asset.Table_Name) .getPO(getA_Asset_ID(), get_TrxName()); } /** Set Asset. @param A_Asset_ID Asset used internally or by customers */ public void setA_Asset_ID (int A_Asset_ID) { if (A_Asset_ID < 1) set_Value (COLUMNNAME_A_Asset_ID, null); else set_Value (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID)); } /** Get Asset. @return Asset used internally or by customers */ public int getA_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_WF_Node getAD_WF_Node() throws RuntimeException { return (I_AD_WF_Node)MTable.get(getCtx(), I_AD_WF_Node.Table_Name) .getPO(getAD_WF_Node_ID(), get_TrxName()); } /** Set Node. @param AD_WF_Node_ID Workflow Node (activity), step or process */ public void setAD_WF_Node_ID (int AD_WF_Node_ID) { if (AD_WF_Node_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, Integer.valueOf(AD_WF_Node_ID)); } /** Get Node. @return Workflow Node (activity), step or process */ public int getAD_WF_Node_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Node_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Workflow Node Asset. @param PP_WF_Node_Asset_ID Workflow Node Asset */ public void setPP_WF_Node_Asset_ID (int PP_WF_Node_Asset_ID) { if (PP_WF_Node_Asset_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, Integer.valueOf(PP_WF_Node_Asset_ID)); } /** Get Workflow Node Asset. @return Workflow Node Asset */ public int getPP_WF_Node_Asset_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_WF_Node_Asset_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_WF_Node_Asset.java
1
请完成以下Java代码
public AbstractPackingMaterialDocumentLinesBuilder create() { // // Process all packing material lines for (final IPackingMaterialDocumentLine pmLine : packingMaterialKey2packingMaterialLine.values()) { createUpdateDeleteDocumentLineAndUpdateSources(pmLine); } // // Iterate those sources without packing materials // and make sure they are not linked to some packing material lines (i.e. unlink them) for (final IPackingMaterialDocumentLineSource source : sourcesWithoutPackingMaterials) { final IPackingMaterialDocumentLine pmLine = null; // no packing material line linkSourceToDocumentLine(source, pmLine); } return this; } /** * Create/update <b>or delete</b> the given packing material line. * <p> * Also, the linked source lines will be updated. * * @param pmLine */ private void createUpdateDeleteDocumentLineAndUpdateSources(final IPackingMaterialDocumentLine pmLine) { final IPackingMaterialDocumentLine pmLineToLink; // If there is no qty on current packing material order line, just delete it if (pmLine.getQty().signum() <= 0) { removeDocumentLine(pmLine); pmLineToLink = null; // we need to unlink our sources } // We have packing material qty => create the actual line else { createDocumentLine(pmLine); pmLineToLink = pmLine; } // // Update the link between "source" to "packing material line" for (final IPackingMaterialDocumentLineSource source : pmLine.getSources())
{ linkSourceToDocumentLine(source, pmLineToLink); } } /** * Makes sure the given is <code>source</code> accepted by this builder * * @param source */ protected abstract void assertValid(final IPackingMaterialDocumentLineSource source); /** * Called when we need to delete the given packing material line. * <p> * NOTE: Here is the place to delete your underlying database models. * * @param pmLine packing material line to delete */ protected abstract void removeDocumentLine(final IPackingMaterialDocumentLine pmLine); /** * Called when we need to create/update the given packing material line. * <p> * NOTE: Here is the place to save your underlying database models. * * @param pmLine packing material line to create/update */ protected abstract void createDocumentLine(final IPackingMaterialDocumentLine pmLine); /** * Called when we need to create a link from source line to packing material line. * <p> * NOTE: please make sure you are saving your database changes. * * @param source * @param pmLine packing material line; could be <code>null</code> in case we want to unlink any packing material lines from given <code>source</code>. */ protected abstract void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source, final IPackingMaterialDocumentLine pmLine); }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\AbstractPackingMaterialDocumentLinesBuilder.java
1
请完成以下Java代码
public class TbSlackNode extends TbAbstractExternalNode { private TbSlackNodeConfiguration config; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { super.init(ctx); config = TbNodeUtils.convert(configuration, TbSlackNodeConfiguration.class); } @Override public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { String token; if (config.isUseSystemSettings()) { token = ctx.getSlackService().getToken(ctx.getTenantId()); } else {
token = config.getBotToken(); } if (token == null) { throw new IllegalArgumentException("Slack token is missing"); } String message = TbNodeUtils.processPattern(config.getMessageTemplate(), msg); var tbMsg = ackIfNeeded(ctx, msg); DonAsynchron.withCallback(ctx.getExternalCallExecutor().executeAsync(() -> { ctx.getSlackService().sendMessage(ctx.getTenantId(), token, config.getConversation().getId(), message); }), r -> tellSuccess(ctx, tbMsg), e -> tellFailure(ctx, tbMsg, e)); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\notification\TbSlackNode.java
1
请在Spring Boot框架中完成以下Java代码
public DateTimeFormatters timeFormat(@Nullable String pattern) { this.timeFormatter = isIso(pattern) ? DateTimeFormatter.ISO_LOCAL_TIME : (isIsoOffset(pattern) ? DateTimeFormatter.ISO_OFFSET_TIME : formatter(pattern)); return this; } /** * Configures the date-time format using the given {@code pattern}. * @param pattern the pattern for formatting date-times * @return {@code this} for chained method invocation */ public DateTimeFormatters dateTimeFormat(@Nullable String pattern) { this.dateTimeFormatter = isIso(pattern) ? DateTimeFormatter.ISO_LOCAL_DATE_TIME : (isIsoOffset(pattern) ? DateTimeFormatter.ISO_OFFSET_DATE_TIME : formatter(pattern)); return this; } @Nullable DateTimeFormatter getDateFormatter() { return this.dateFormatter; } @Nullable String getDatePattern() { return this.datePattern; } @Nullable DateTimeFormatter getTimeFormatter() { return this.timeFormatter; } @Nullable DateTimeFormatter getDateTimeFormatter() { return this.dateTimeFormatter; }
boolean isCustomized() { return this.dateFormatter != null || this.timeFormatter != null || this.dateTimeFormatter != null; } private static @Nullable DateTimeFormatter formatter(@Nullable String pattern) { return StringUtils.hasText(pattern) ? DateTimeFormatter.ofPattern(pattern).withResolverStyle(ResolverStyle.SMART) : null; } private static boolean isIso(@Nullable String pattern) { return "iso".equalsIgnoreCase(pattern); } private static boolean isIsoOffset(@Nullable String pattern) { return "isooffset".equalsIgnoreCase(pattern) || "iso-offset".equalsIgnoreCase(pattern); } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\format\DateTimeFormatters.java
2
请完成以下Java代码
public java.math.BigDecimal getQtyPromised () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Menge angefragt. @param QtyRequiered Menge angefragt */ @Override public void setQtyRequiered (java.math.BigDecimal QtyRequiered) { set_ValueNoCheck (COLUMNNAME_QtyRequiered, QtyRequiered); } /** Get Menge angefragt. @return Menge angefragt */ @Override public java.math.BigDecimal getQtyRequiered () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyRequiered); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Use line quantity. @param UseLineQty Use line quantity */ @Override public void setUseLineQty (boolean UseLineQty) { set_Value (COLUMNNAME_UseLineQty, Boolean.valueOf(UseLineQty)); }
/** Get Use line quantity. @return Use line quantity */ @Override public boolean isUseLineQty () { Object oo = get_Value(COLUMNNAME_UseLineQty); 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.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLine.java
1
请完成以下Java代码
private static LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> processMap( LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap, ExpressionParser parser) { Assert.notNull(parser, "SecurityExpressionHandler returned a null parser object"); LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> processed = new LinkedHashMap<>(requestMap); requestMap.forEach((request, value) -> process(parser, request, value, processed::put)); return processed; } private static void process(ExpressionParser parser, RequestMatcher request, Collection<ConfigAttribute> value, BiConsumer<RequestMatcher, Collection<ConfigAttribute>> consumer) { String expression = getExpression(request, value); if (logger.isDebugEnabled()) { logger.debug(LogMessage.format("Adding web access control expression [%s] for %s", expression, request)); } AbstractVariableEvaluationContextPostProcessor postProcessor = createPostProcessor(request); ArrayList<ConfigAttribute> processed = new ArrayList<>(1); try { processed.add(new WebExpressionConfigAttribute(parser.parseExpression(expression), postProcessor)); } catch (ParseException ex) { throw new IllegalArgumentException("Failed to parse expression '" + expression + "'"); } consumer.accept(request, processed); }
private static String getExpression(RequestMatcher request, Collection<ConfigAttribute> value) { Assert.isTrue(value.size() == 1, () -> "Expected a single expression attribute for " + request); return value.toArray(new ConfigAttribute[1])[0].getAttribute(); } private static AbstractVariableEvaluationContextPostProcessor createPostProcessor(RequestMatcher request) { return new RequestVariablesExtractorEvaluationContextPostProcessor(request); } static class RequestVariablesExtractorEvaluationContextPostProcessor extends AbstractVariableEvaluationContextPostProcessor { private final RequestMatcher matcher; RequestVariablesExtractorEvaluationContextPostProcessor(RequestMatcher matcher) { this.matcher = matcher; } @Override Map<String, String> extractVariables(HttpServletRequest request) { return this.matcher.matcher(request).getVariables(); } } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\expression\ExpressionBasedFilterInvocationSecurityMetadataSource.java
1
请完成以下Java代码
private ProductsToPickRow withFinishedGoodsQtyOverride( @NonNull final Quantity finishedGoodsQty, @Nullable final Quantity finishedGoodsQtyOverride) { if (finishedGoodsQtyOverride != null) { Quantity.getCommonUomIdOfAll(finishedGoodsQty, finishedGoodsQtyOverride); // just to make sure // qty ............... finishedGoodsQty // qtyOverride ....... finishedGoodsQtyOverride // => qtyOverride = qty * (finishedGoodsQtyOverride / finishedGoodsQty) final BigDecimal multiplier = finishedGoodsQtyOverride.toBigDecimal() .divide(finishedGoodsQty.toBigDecimal(), 12, RoundingMode.HALF_UP); final Quantity qtyOverride = qty.multiply(multiplier).roundToUOMPrecision(); return withQtyOverride(qtyOverride); } else { return withQtyOverride((Quantity)null); } } public boolean isQtyOverrideEditableByUser() { return isFieldEditable(FIELD_QtyOverride); } @SuppressWarnings("SameParameterValue") private boolean isFieldEditable(final String fieldName) { final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName); return renderMode != null && renderMode.isEditable(); } public boolean isApproved() { return approvalStatus != null && approvalStatus.isApproved(); } private boolean isEligibleForChangingPickStatus() { return !isProcessed() && getType().isPickable(); } public boolean isEligibleForPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForPicking();
} public boolean isEligibleForRejectPicking() { return isEligibleForChangingPickStatus() && !isApproved() && pickStatus != null && pickStatus.isEligibleForRejectPicking(); } public boolean isEligibleForPacking() { return isEligibleForChangingPickStatus() && isApproved() && pickStatus != null && pickStatus.isEligibleForPacking(); } public boolean isEligibleForReview() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForReview(); } public boolean isEligibleForProcessing() { return isEligibleForChangingPickStatus() && pickStatus != null && pickStatus.isEligibleForProcessing(); } public String getLocatorName() { return locator != null ? locator.getDisplayName() : ""; } @Override public List<ProductsToPickRow> getIncludedRows() { return includedRows; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRow.java
1
请完成以下Java代码
public boolean isAccountNonExpired() { return true; } @JsonIgnore @Override public boolean isAccountNonLocked() { return true; } @JsonIgnore @Override public boolean isCredentialsNonExpired() { return true; } @JsonIgnore @Override
public boolean isEnabled() { return true; } @JsonIgnore @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) { this.authorities = authorities; } }
repos\springBoot-master\springboot-springSecurity2\src\main\java\com\us\example\domain\SysUser.java
1
请完成以下Java代码
public String getHospitalizationMode() { return hospitalizationMode; } /** * Sets the value of the hospitalizationMode property. * * @param value * allowed object is * {@link String } * */ public void setHospitalizationMode(String value) { this.hospitalizationMode = value; } /** * Gets the value of the clazz property. * * @return * possible object is * {@link String } * */ public String getClazz() { return clazz; } /** * Sets the value of the clazz property. * * @param value * allowed object is * {@link String } * */ public void setClazz(String value) { this.clazz = value; } /** * Gets the value of the sectionMajor property.
* * @return * possible object is * {@link String } * */ public String getSectionMajor() { return sectionMajor; } /** * Sets the value of the sectionMajor property. * * @param value * allowed object is * {@link String } * */ public void setSectionMajor(String value) { this.sectionMajor = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraAmbulatoryType.java
1
请在Spring Boot框架中完成以下Java代码
public ModelAndView sessionRequestCounts(HttpSession session) { this.sessionIds.add(session.getId()); Map<String, Object> model = new HashMap<>(); model.put("sessionType", session.getClass().getName()); model.put("sessionCount", this.sessionIds.size()); model.put("requestCount", getRequestCount(session)); return new ModelAndView(INDEX_TEMPLATE_VIEW_NAME, model); } private Object getRequestCount(HttpSession session) {
Integer requestCount = (Integer) session.getAttribute("requestCount"); requestCount = requestCount != null ? requestCount : 0; requestCount++; session.setAttribute("requestCount", requestCount); return requestCount; } private String format(String value) { return String.format("<h1>%s</h1>", value); } } //end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\http-session\src\main\java\example\app\caching\session\http\controller\CounterController.java
2
请在Spring Boot框架中完成以下Java代码
public String getNamespace() { return this.namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public FlushMode getFlushMode() { return this.flushMode; } public void setFlushMode(FlushMode flushMode) { this.flushMode = flushMode; } public SaveMode getSaveMode() { return this.saveMode; } public void setSaveMode(SaveMode saveMode) { this.saveMode = saveMode; } public @Nullable String getCleanupCron() { return this.cleanupCron; } public void setCleanupCron(@Nullable String cleanupCron) { this.cleanupCron = cleanupCron; } public ConfigureAction getConfigureAction() { return this.configureAction; } public void setConfigureAction(ConfigureAction configureAction) { this.configureAction = configureAction; } public RepositoryType getRepositoryType() { return this.repositoryType; }
public void setRepositoryType(RepositoryType repositoryType) { this.repositoryType = repositoryType; } /** * Strategies for configuring and validating Redis. */ public enum ConfigureAction { /** * Ensure that Redis Keyspace events for Generic commands and Expired events are * enabled. */ NOTIFY_KEYSPACE_EVENTS, /** * No not attempt to apply any custom Redis configuration. */ NONE } /** * Type of Redis session repository to auto-configure. */ public enum RepositoryType { /** * Auto-configure a RedisSessionRepository or ReactiveRedisSessionRepository. */ DEFAULT, /** * Auto-configure a RedisIndexedSessionRepository or * ReactiveRedisIndexedSessionRepository. */ INDEXED } }
repos\spring-boot-4.0.1\module\spring-boot-session-data-redis\src\main\java\org\springframework\boot\session\data\redis\autoconfigure\SessionDataRedisProperties.java
2
请完成以下Java代码
public Quantity getQtyRemainingToScheduleForPicking(@NonNull final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentScheduleRecord) { return shipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord); } @Override public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) {return;} final IShipmentScheduleInvalidateBL invalidSchedulesService = Services.get(IShipmentScheduleInvalidateBL.class); invalidSchedulesService.flagForRecompute(shipmentScheduleIds); } @Override public ShipmentScheduleLoadingCache<I_M_ShipmentSchedule> newLoadingCache() { return shipmentScheduleBL.newLoadingCache(I_M_ShipmentSchedule.class); }
@Nullable @Override public ProjectId extractSingleProjectIdOrNull(@NonNull final List<ShipmentScheduleWithHU> candidates) { final Set<ProjectId> projectIdsFromShipmentSchedules = candidates.stream() .map(ShipmentScheduleWithHU::getProjectId) .filter(Objects::nonNull) .collect(Collectors.toSet()); if (projectIdsFromShipmentSchedules.size() == 1) { return projectIdsFromShipmentSchedules.iterator().next(); } return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\HUShipmentScheduleBL.java
1
请完成以下Java代码
public I_AD_InfoColumn getAD_InfoColumn() { return infoColumn; } @Override public int getParameterCount() { return 1; } @Override public String getLabel(int index) { if (index == 0) return Msg.translate(Env.getCtx(), "search"); return null; } @Override public Object getParameterToComponent(int index) { return null; } @Override public String[] getWhereClauses(List<Object> params) { final List<String> whereClauses = new ArrayList<String>(); String search = getText(); if (!(search.equals("") || search.equals("%"))) { // search = search.trim(); // metas: Permutationen ueber alle Search-Kombinationen // z.B. 3 Tokens ergeben 3! Moeglichkeiten als Ergebnis. if (search.contains(" ")) { StringTokenizer st = new StringTokenizer(search, " "); int tokens = st.countTokens(); String input[] = new String[tokens]; Permutation perm = new Permutation(); perm.setMaxIndex(tokens - 1); for (int token = 0; token < tokens; token++) { input[token] = st.nextToken(); } perm.permute(input, tokens - 1); Iterator<String> itr = perm.getResult().iterator(); while (itr.hasNext()) { search = ("%" + itr.next() + "%").replace(" ", "%"); whereClauses.add("UPPER(bpcs.Search) LIKE UPPER(?)"); params.add(search); log.debug("Search: " + search);
} } else { if (!search.startsWith("%")) search = "%" + search; // metas-2009_0021_AP1_CR064: end if (!search.endsWith("%")) search += "%"; whereClauses.add("UPPER(bpcs.Search) LIKE UPPER(?)"); params.add(search); log.debug("Search(2): " + search); } // list.add ("UPPER(bpcs.Search) LIKE ?"); // metas ende } return whereClauses.toArray(new String[whereClauses.size()]); } public IInfoSimple getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPSearchAbstract.java
1
请完成以下Java代码
public String getName() { return this.name; } /** * Return the actual level value if possible. * @return the level value * @throws IllegalStateException if this is a {@link #isCustom() custom} level */ public LogLevel getLevel() { Assert.state(this.logLevel != null, () -> "Unable to provide LogLevel for '" + this.name + "'"); return this.logLevel; } /** * Return if this is a custom level and cannot be represented by {@link LogLevel}. * @return if this is a custom level */ public boolean isCustom() { return this.logLevel == null; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } LevelConfiguration other = (LevelConfiguration) obj; return this.logLevel == other.logLevel && ObjectUtils.nullSafeEquals(this.name, other.name); } @Override public int hashCode() { return Objects.hash(this.logLevel, this.name); } @Override public String toString() {
return "LevelConfiguration [name=" + this.name + ", logLevel=" + this.logLevel + "]"; } /** * Create a new {@link LevelConfiguration} instance of the given {@link LogLevel}. * @param logLevel the log level * @return a new {@link LevelConfiguration} instance */ public static LevelConfiguration of(LogLevel logLevel) { Assert.notNull(logLevel, "'logLevel' must not be null"); return new LevelConfiguration(logLevel.name(), logLevel); } /** * Create a new {@link LevelConfiguration} instance for a custom level name. * @param name the log level name * @return a new {@link LevelConfiguration} instance */ public static LevelConfiguration ofCustom(String name) { Assert.hasText(name, "'name' must not be empty"); return new LevelConfiguration(name, null); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\LoggerConfiguration.java
1
请完成以下Java代码
public int getFresh_QtyOnHand_Line_ID() { return get_ValueAsInt(COLUMNNAME_Fresh_QtyOnHand_Line_ID); } @Override public void setIsReverted (final boolean IsReverted) { set_Value (COLUMNNAME_IsReverted, IsReverted); } @Override public boolean isReverted() { return get_ValueAsBoolean(COLUMNNAME_IsReverted); } @Override public org.compiere.model.I_M_Inventory getM_Inventory() { return get_ValueAsPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class); } @Override public void setM_Inventory(final org.compiere.model.I_M_Inventory M_Inventory) { set_ValueFromPO(COLUMNNAME_M_Inventory_ID, org.compiere.model.I_M_Inventory.class, M_Inventory); } @Override public void setM_Inventory_ID (final int M_Inventory_ID) { if (M_Inventory_ID < 1) set_Value (COLUMNNAME_M_Inventory_ID, null); else set_Value (COLUMNNAME_M_Inventory_ID, M_Inventory_ID); } @Override public int getM_Inventory_ID() { return get_ValueAsInt(COLUMNNAME_M_Inventory_ID); } @Override public org.compiere.model.I_M_InventoryLine getM_InventoryLine() { return get_ValueAsPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class); } @Override public void setM_InventoryLine(final org.compiere.model.I_M_InventoryLine M_InventoryLine) { set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine); } @Override public void setM_InventoryLine_ID (final int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_Value (COLUMNNAME_M_InventoryLine_ID, null); else set_Value (COLUMNNAME_M_InventoryLine_ID, M_InventoryLine_ID); } @Override public int getM_InventoryLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID); }
@Override public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate() { return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class); } @Override public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID); } @Override public void setMD_Candidate_StockChange_Detail_ID (final int MD_Candidate_StockChange_Detail_ID) { if (MD_Candidate_StockChange_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, MD_Candidate_StockChange_Detail_ID); } @Override public int getMD_Candidate_StockChange_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_StockChange_Detail_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_StockChange_Detail.java
1
请完成以下Java代码
public I_C_ValidCombination getHR_Concept_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getHR_Concept_Acct(), get_TrxName()); } /** Set Payroll Concept Account. @param HR_Concept_Acct Payroll Concept Account */ public void setHR_Concept_Acct (int HR_Concept_Acct) { set_Value (COLUMNNAME_HR_Concept_Acct, Integer.valueOf(HR_Concept_Acct)); } /** Get Payroll Concept Account. @return Payroll Concept Account */ public int getHR_Concept_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Acct); if (ii == null) return 0; return ii.intValue(); } /** Set Payroll Concept Category. @param HR_Concept_Category_ID Payroll Concept Category */ public void setHR_Concept_Category_ID (int HR_Concept_Category_ID) { if (HR_Concept_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_HR_Concept_Category_ID, Integer.valueOf(HR_Concept_Category_ID)); } /** Get Payroll Concept Category. @return Payroll Concept Category */ public int getHR_Concept_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_HR_Concept_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default. @param IsDefault Default value */ public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); }
return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Concept_Category.java
1
请完成以下Java代码
public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceEndTime() { orderBy(HistoricActivityInstanceQueryProperty.END); return this; } public HistoricActivityInstanceQueryImpl orderByExecutionId() { orderBy(HistoricActivityInstanceQueryProperty.EXECUTION_ID); return this; } public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceId() { orderBy(HistoricActivityInstanceQueryProperty.HISTORIC_ACTIVITY_INSTANCE_ID); return this; } public HistoricActivityInstanceQueryImpl orderByProcessDefinitionId() { orderBy(HistoricActivityInstanceQueryProperty.PROCESS_DEFINITION_ID); return this; } public HistoricActivityInstanceQueryImpl orderByProcessInstanceId() { orderBy(HistoricActivityInstanceQueryProperty.PROCESS_INSTANCE_ID); return this; } public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceStartTime() { orderBy(HistoricActivityInstanceQueryProperty.START); return this; } public HistoricActivityInstanceQuery orderByActivityId() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_ID); return this; } public HistoricActivityInstanceQueryImpl orderByActivityName() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_NAME); return this; } public HistoricActivityInstanceQueryImpl orderByActivityType() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_TYPE); return this; } public HistoricActivityInstanceQueryImpl orderByTenantId() { orderBy(HistoricActivityInstanceQueryProperty.TENANT_ID); return this; } public HistoricActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } // getters and setters // ////////////////////////////////////////////////////// public String getProcessInstanceId() {
return processInstanceId; } public String getExecutionId() { return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public String getAssignee() { return assignee; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public static class FakeHostnameVerifier implements HostnameVerifier { /** * Always return true, indicating that the host name is * an acceptable match with the server's authentication scheme. * * @param hostname the host name. * @param session the SSL session used on the connection to * host. * @return the true boolean value * indicating the host name is trusted. */ public boolean verify(String hostname, SSLSession session) { return(true); } // verify } // FakeHostnameVerifier /** * This class allow any X509 certificates to be used to authenticate the * remote side of a secure socket, including self-signed certificates. * * @author Francis Labrie */ public static class FakeX509TrustManager implements X509TrustManager { /** * Empty array of certificate authority certificates. */ private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; /** * Always trust for client SSL chain peer certificate * chain with any authType authentication types. * * @param chain the peer certificate chain. * @param authType the authentication type based on the client * certificate. */ public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted /** * Always trust for server SSL chain peer certificate * chain with any authType exchange algorithm types. * * @param chain the peer certificate chain. * @param authType the key exchange algorithm used. */ public void checkServerTrusted(X509Certificate[] chain, String authType) { } // checkServerTrusted /** * Return an empty array of certificate authority certificates which * are trusted for authenticating peers. * * @return a empty array of issuer certificates. */ public X509Certificate[] getAcceptedIssuers() { return(_AcceptedIssuers); } // getAcceptedIssuers } // FakeX509TrustManager } // SSLUtilities
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\taxiMaster\SSLUtilities.java
2
请完成以下Java代码
public void setMargin (final int Margin) { set_Value (COLUMNNAME_Margin, Margin); } @Override public int getMargin() { return get_ValueAsInt(COLUMNNAME_Margin); } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null);
else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Customer_Trade_Margin_Line.java
1
请在Spring Boot框架中完成以下Java代码
private void fireSimulatedSupplyRequiredEvent(@NonNull final Candidate simulatedCandidate, @NonNull final Candidate stockCandidate) { Check.assume(simulatedCandidate.isSimulated(), "fireSimulatedSupplyRequiredEvent should only be called for simulated candidates!"); if (stockCandidate.getQuantity().signum() < 0) { postSupplyRequiredEvent(simulatedCandidate, stockCandidate.getQuantity().negate()); } } private void postSupplyRequiredEvent(@NonNull final Candidate demandCandidateWithId, @NonNull final BigDecimal requiredQty) { // create supply record now! otherwise final Candidate supplyCandidate = Candidate.builderForClientAndOrgId(demandCandidateWithId.getClientAndOrgId()) .type(CandidateType.SUPPLY) .businessCase(null) .businessCaseDetail(null)
.materialDescriptor(demandCandidateWithId.getMaterialDescriptor().withQuantity(requiredQty)) //.groupId() // don't assign the new supply candidate to the demand candidate's groupId! it needs to "found" its own group .minMaxDescriptor(demandCandidateWithId.getMinMaxDescriptor()) .quantity(requiredQty) .simulated(demandCandidateWithId.isSimulated()) .build(); final CandidateId supplyCandidateId = supplyCandidateHandler.onCandidateNewOrChange(supplyCandidate, OnNewOrChangeAdvise.DONT_UPDATE).getId(); final SupplyRequiredEvent supplyRequiredEvent = SupplyRequiredEventCreator .createSupplyRequiredEvent(demandCandidateWithId, requiredQty, supplyCandidateId); materialEventService.enqueueEventAfterNextCommit(supplyRequiredEvent); Loggables.addLog("Fire supplyRequiredEvent after next commit; event={}", supplyRequiredEvent); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\DemandCandiateHandler.java
2
请完成以下Java代码
public boolean accept(final T model) { final Instant value = InterfaceWrapperHelper.getValue(model, columnName) .map(TimeUtil::asInstant) .orElse(null); return value != null && range.contains(value); } @Override public final String getSql() { buildSql(); return sqlWhereClause; } @Override public final List<Object> getSqlParams(final Properties ctx) { return getSqlParams(); } public final List<Object> getSqlParams() { buildSql(); return sqlParams; } private void buildSql() { if (sqlBuilt) { return; } final ArrayList<Object> sqlParams = new ArrayList<>(); final StringBuilder sql = new StringBuilder(); sql.append(columnName).append(" IS NOT NULL"); if (range.hasLowerBound()) { final String operator; final BoundType boundType = range.lowerBoundType(); switch (boundType) { case OPEN: operator = ">"; break; case CLOSED: operator = ">="; break; default: throw new AdempiereException("Unknown bound: " + boundType); } sql.append(" AND ").append(columnName).append(operator).append("?"); sqlParams.add(range.lowerEndpoint()); }
if (range.hasUpperBound()) { final String operator; final BoundType boundType = range.upperBoundType(); switch (boundType) { case OPEN: operator = "<"; break; case CLOSED: operator = "<="; break; default: throw new AdempiereException("Unknown bound: " + boundType); } sql.append(" AND ").append(columnName).append(operator).append("?"); sqlParams.add(range.upperEndpoint()); } // this.sqlWhereClause = sql.toString(); this.sqlParams = !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of(); this.sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InstantRangeQueryFilter.java
1
请完成以下Java代码
public class AbstractStartProcessInstanceAfterContext { protected ExecutionEntity processInstance; protected ExecutionEntity childExecution; protected Map<String, Object> variables; protected Map<String, Object> transientVariables; protected FlowElement initialFlowElement; protected Process process; protected ProcessDefinition processDefinition; public AbstractStartProcessInstanceAfterContext() { } public AbstractStartProcessInstanceAfterContext(ExecutionEntity processInstance, ExecutionEntity childExecution, Map<String, Object> variables, Map<String, Object> transientVariables, FlowElement initialFlowElement, Process process, ProcessDefinition processDefinition) { this.processInstance = processInstance; this.childExecution = childExecution; this.variables = variables; this.transientVariables = transientVariables; this.initialFlowElement = initialFlowElement; this.process = process; this.processDefinition = processDefinition; } public ExecutionEntity getProcessInstance() { return processInstance; } public void setProcessInstance(ExecutionEntity processInstance) { this.processInstance = processInstance; } public ExecutionEntity getChildExecution() { return childExecution; } public void setChildExecution(ExecutionEntity childExecution) { this.childExecution = childExecution; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public Map<String, Object> getTransientVariables() { return transientVariables;
} public void setTransientVariables(Map<String, Object> transientVariables) { this.transientVariables = transientVariables; } public FlowElement getInitialFlowElement() { return initialFlowElement; } public void setInitialFlowElement(FlowElement initialFlowElement) { this.initialFlowElement = initialFlowElement; } public Process getProcess() { return process; } public void setProcess(Process process) { this.process = process; } public ProcessDefinition getProcessDefinition() { return processDefinition; } public void setProcessDefinition(ProcessDefinition processDefinition) { this.processDefinition = processDefinition; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\AbstractStartProcessInstanceAfterContext.java
1
请在Spring Boot框架中完成以下Java代码
public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String address; public Employee() { } public Employee(String name, Branch mainBranch, Branch subBranch, Branch additionalBranch) { this.name = name; this.mainBranch = mainBranch; this.subBranch = subBranch; this.additionalBranch = additionalBranch; } @ManyToOne private Branch mainBranch; @ManyToOne private Branch subBranch; @ManyToOne private Branch additionalBranch; 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 getAddress() { return address; } public void setAddress(String address) { this.address = address;
} public Branch getMainBranch() { return mainBranch; } public void setMainBranch(Branch mainBranch) { this.mainBranch = mainBranch; } public Branch getSubBranch() { return subBranch; } public void setSubBranch(Branch subBranch) { this.subBranch = subBranch; } public Branch getAdditionalBranch() { return additionalBranch; } public void setAdditionalBranch(Branch additionalBranch) { this.additionalBranch = additionalBranch; } }
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\lazycollection\model\Employee.java
2
请完成以下Java代码
public static final class Builder { private final List<ServerWebExchangeMatcherEntry<ReactiveAuthenticationManager>> entries = new ArrayList<>(); private Builder() { } /** * Maps a {@link ServerWebExchangeMatcher} to an * {@link ReactiveAuthenticationManager}. * @param matcher the {@link ServerWebExchangeMatcher} to use * @param manager the {@link ReactiveAuthenticationManager} to use * @return the * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder} * for further customizations */ public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.Builder add( ServerWebExchangeMatcher matcher, ReactiveAuthenticationManager manager) { Assert.notNull(matcher, "matcher cannot be null");
Assert.notNull(manager, "manager cannot be null"); this.entries.add(new ServerWebExchangeMatcherEntry<>(matcher, manager)); return this; } /** * Creates a * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} * instance. * @return the * {@link ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver} * instance */ public ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver build() { return new ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver(this.entries); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.java
1
请完成以下Java代码
public void shutdown() { executor.shutdown(); } /* public static void main(String[] args) throws InterruptedException { final Debouncer<Integer> debouncer = Debouncer.<Integer>builder() .name("test-debouncer") .delayInMillis(500) .bufferMaxSize(500) .consumer(items -> System.out.println("Got " + items.size() + " items: " + items.get(0) + "..." + items.get(items.size() - 1))) .build();
System.out.println("Start sending events..."); for (int i = 1; i <= 100; i++) { debouncer.add(i); //Thread.yield(); Thread.sleep(0, 1); } System.out.println("Enqueuing done. Waiting a bit to finish..."); Thread.sleep(5000); } */ }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\async\Debouncer.java
1
请在Spring Boot框架中完成以下Java代码
public static class DirectExchangeDemoConfiguration { // 创建 Queue @Bean public Queue demo15Queue() { return new Queue(Demo15Message.QUEUE, // Queue 名字 true, // durable: 是否持久化 false, // exclusive: 是否排它 false); // autoDelete: 是否自动删除 } // 创建 Direct Exchange @Bean public DirectExchange demo15Exchange() { return new DirectExchange(Demo15Message.EXCHANGE, true, // durable: 是否持久化 false); // exclusive: 是否排它 } // 创建 Binding // Exchange:Demo15Message.EXCHANGE
// Routing key:Demo15Message.ROUTING_KEY // Queue:Demo15Message.QUEUE @Bean public Binding demo15Binding() { return BindingBuilder.bind(demo15Queue()).to(demo15Exchange()).with(Demo15Message.ROUTING_KEY); } } @Bean public MessageConverter messageConverter() { return new Jackson2JsonMessageConverter(); } }
repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-json\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java
2
请完成以下Java代码
public final void await(String key, long milliseconds) throws InterruptedException { // 测试当前线程是否已经被中断 if (Thread.interrupted()) { throw new InterruptedException(); } Set<Thread> threadSet = threadMap.get(key); // 判断线程容器是否是null,如果是就新创建一个 if (threadSet == null) { threadSet = new HashSet<>(); threadMap.put(key, threadSet); } // 将线程放到容器 threadSet.add(Thread.currentThread()); // 阻塞一定的时间 LockSupport.parkNanos(this, TimeUnit.MILLISECONDS.toNanos(milliseconds)); } /** * 线程唤醒
* @param key */ public final void signalAll(String key) { Set<Thread> threadSet = threadMap.get(key); // 判断key所对应的等待线程容器是否是null if (!CollectionUtils.isEmpty(threadSet)) { for (Thread thread : threadSet) { LockSupport.unpark(thread); } // 清空等待线程容器 threadSet.clear(); } } }
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\redis\cache\ThreadAwaitContainer.java
1
请完成以下Java代码
public static QuantityTU ofInt(final int value) { if (value >= 0 && value < cache.length) { return cache[value]; } return new QuantityTU(value); } public static QuantityTU ofBigDecimal(@NonNull final BigDecimal value) { final int valueInt; try { valueInt = value.intValueExact(); } catch (Exception ex) { throw new AdempiereException("Quantity TUs shall be integer: " + value, ex); } return ofInt(valueInt); } public static final QuantityTU ZERO = new QuantityTU(0); public static final QuantityTU ONE = new QuantityTU(1); private static final QuantityTU[] cache = new QuantityTU[] { ZERO, ONE, new QuantityTU(2), new QuantityTU(3), new QuantityTU(4), new QuantityTU(5), new QuantityTU(6), new QuantityTU(7), new QuantityTU(8), new QuantityTU(9), new QuantityTU(10), }; private final int value; private QuantityTU(final int value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } @JsonValue public int toInt() { return value;
} public BigDecimal toBigDecimal() { return BigDecimal.valueOf(value); } @Override public int compareTo(@NonNull final QuantityTU other) { return this.value - other.value; } public QuantityTU add(@NonNull final QuantityTU toAdd) { if (this.value == 0) { return toAdd; } else if (toAdd.value == 0) { return this; } else { return ofInt(this.value + toAdd.value); } } public QuantityTU subtract(@NonNull final QuantityTU toSubtract) { if (toSubtract.value == 0) { return this; } else { return ofInt(this.value - toSubtract.value); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\QuantityTU.java
1
请完成以下Java代码
public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { onStartElement(); super.writeStartElement(namespaceURI, localName); } public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { onStartElement(); super.writeStartElement(prefix, localName, namespaceURI); } public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { onEmptyElement(); super.writeEmptyElement(namespaceURI, localName); } public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { onEmptyElement(); super.writeEmptyElement(prefix, localName, namespaceURI); } public void writeEmptyElement(String localName) throws XMLStreamException { onEmptyElement();
super.writeEmptyElement(localName); } public void writeEndElement() throws XMLStreamException { onEndElement(); super.writeEndElement(); } public void writeCharacters(String text) throws XMLStreamException { state = SEEN_DATA; super.writeCharacters(text); } public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { state = SEEN_DATA; super.writeCharacters(text, start, len); } public void writeCData(String data) throws XMLStreamException { state = SEEN_DATA; super.writeCData(data); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\IndentingXMLStreamWriter.java
1
请在Spring Boot框架中完成以下Java代码
public class DataImportConfigId implements RepoIdAware { @JsonCreator public static DataImportConfigId ofRepoId(final int repoId) { return new DataImportConfigId(repoId); } public static DataImportConfigId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new DataImportConfigId(repoId) : null; } int repoId; private DataImportConfigId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_DataImport_ID"); } @JsonValue
@Override public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final DataImportConfigId id) { return id != null ? id.getRepoId() : -1; } public TableRecordReference toRecordRef() { return TableRecordReference.of(I_C_DataImport.Table_Name, repoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\config\DataImportConfigId.java
2
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public String getAssignee() { return assignee; } public boolean isFinished() { return finished;
} public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请完成以下Java代码
public byte[] getBinaryData(final I_AD_Archive archive) { byte[] deflatedData = archive.getBinaryData(); // m_deflated = null; // m_inflated = null; if (deflatedData == null) return null; // logger.debug("ZipSize=" + deflatedData.length); // m_deflated = new Integer(deflatedData.length); if (deflatedData.length == 0) return null; byte[] inflatedData = null; try { ByteArrayInputStream in = new ByteArrayInputStream(deflatedData); ZipInputStream zip = new ZipInputStream(in); ZipEntry entry = zip.getNextEntry(); if (entry != null) // just one entry { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = zip.read(buffer); while (length != -1) { out.write(buffer, 0, length); length = zip.read(buffer); } // inflatedData = out.toByteArray(); logger.debug("Size=" + inflatedData.length + " - zip=" + entry.getCompressedSize() + "(" + entry.getSize() + ") " + (entry.getCompressedSize() * 100 / entry.getSize()) + "%"); // m_inflated = new Integer(inflatedData.length); } } catch (Exception e) { // logger.error("", e); inflatedData = null; throw new AdempiereException(e); } return inflatedData; } // getBinaryData @Override public void setBinaryData(@NonNull final I_AD_Archive archive, @NonNull final byte[] uncompressedData) { if (uncompressedData.length == 0) { throw new AdempiereException("uncompressedData may not be empty") .appendParametersToMessage() .setParameter("AD_Archive", archive); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ZipOutputStream zip = new ZipOutputStream(out); zip.setMethod(ZipOutputStream.DEFLATED); zip.setLevel(Deflater.BEST_COMPRESSION); zip.setComment("adempiere"); //
byte[] compressedData = null; try { final ZipEntry entry = new ZipEntry("AdempiereArchive"); entry.setTime(System.currentTimeMillis()); entry.setMethod(ZipEntry.DEFLATED); zip.putNextEntry(entry); zip.write(uncompressedData, 0, uncompressedData.length); zip.closeEntry(); logger.debug(entry.getCompressedSize() + " (" + entry.getSize() + ") " + (entry.getCompressedSize() * 100 / entry.getSize()) + "%"); // // zip.finish(); zip.close(); compressedData = out.toByteArray(); logger.debug("Length=" + uncompressedData.length); // m_deflated = new Integer(compressedData.length); } catch (Exception e) { // log.error("saveLOBData", e); // compressedData = null; // m_deflated = null; throw AdempiereException.wrapIfNeeded(e); } archive.setBinaryData(compressedData); archive.setIsFileSystem(false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\spi\impl\DBArchiveStorage.java
1
请在Spring Boot框架中完成以下Java代码
public Admin getUserDetailById(Long loginUserId) { return adminMapper.selectByPrimaryKey(loginUserId); } @Override public Boolean updatePassword(Long loginUserId, String originalPassword, String newPassword) { Admin adminUser = adminMapper.selectByPrimaryKey(loginUserId); //当前用户非空才可以进行更改 if (adminUser != null) { String originalPasswordMd5 = MD5Util.MD5Encode(originalPassword, "UTF-8"); String newPasswordMd5 = MD5Util.MD5Encode(newPassword, "UTF-8"); //比较原密码是否正确 if (originalPasswordMd5.equals(adminUser.getLoginPassword())) { //设置新密码并修改 adminUser.setLoginPassword(newPasswordMd5); if (adminMapper.updateByPrimaryKeySelective(adminUser) > 0) { //修改成功则返回true return true; } } } return false; }
@Override public Boolean updateName(Long loginUserId, String loginUserName, String nickName) { Admin adminUser = adminMapper.selectByPrimaryKey(loginUserId); //当前用户非空才可以进行更改 if (adminUser != null) { //设置新密码并修改 adminUser.setLoginName(loginUserName); adminUser.setAdminNickName(nickName); if (adminMapper.updateByPrimaryKeySelective(adminUser) > 0) { //修改成功则返回true return true; } } return false; } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\service\impl\AdminServiceImpl.java
2
请完成以下Java代码
protected void removeIdentityLinkType(CommandContext commandContext, String caseInstanceId, String identityType) { CaseInstanceEntity caseInstanceEntity = getCaseInstanceEntity(commandContext, caseInstanceId); // this will remove ALL identity links with the given identity type (for users AND groups) IdentityLinkUtil.deleteCaseInstanceIdentityLinks(caseInstanceEntity, null, null, identityType, CommandContextUtil.getCmmnEngineConfiguration(commandContext)); } /** * Creates a new identity link entry for the given case instance, which can either be a user or group based one, but not both the same time. * If both the user and group ids are null, no new identity link is created. * * @param commandContext the command context within which to perform the identity link creation * @param caseInstanceId the id of the case instance to create an identity link for * @param userId the user id if this is a user based identity link, otherwise null * @param groupId the group id if this is a group based identity link, otherwise null * @param identityType the type of identity link (e.g. owner or assignee, etc)
*/ protected void createIdentityLinkType(CommandContext commandContext, String caseInstanceId, String userId, String groupId, String identityType) { // if both user and group ids are null, don't create an identity link if (userId == null && groupId == null) { return; } // if both are set the same time, throw an exception as this is not allowed if (userId != null && groupId != null) { throw new FlowableIllegalArgumentException("Either set the user id or the group id for an identity link, but not both the same time."); } CaseInstanceEntity caseInstanceEntity = getCaseInstanceEntity(commandContext, caseInstanceId); IdentityLinkUtil.createCaseInstanceIdentityLink(caseInstanceEntity, userId, groupId, identityType, CommandContextUtil.getCmmnEngineConfiguration(commandContext)); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AbstractCaseInstanceIdentityLinkCmd.java
1
请完成以下Java代码
public I_GL_Fund getGL_Fund() throws RuntimeException { return (I_GL_Fund)MTable.get(getCtx(), I_GL_Fund.Table_Name) .getPO(getGL_Fund_ID(), get_TrxName()); } /** Set GL Fund. @param GL_Fund_ID General Ledger Funds Control */ public void setGL_Fund_ID (int GL_Fund_ID) { if (GL_Fund_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID)); } /** Get GL Fund. @return General Ledger Funds Control */ public int getGL_Fund_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Fund Restriction. @param GL_FundRestriction_ID Restriction of Funds */ public void setGL_FundRestriction_ID (int GL_FundRestriction_ID) { if (GL_FundRestriction_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, Integer.valueOf(GL_FundRestriction_ID)); } /** Get Fund Restriction. @return Restriction of Funds */ public int getGL_FundRestriction_ID () {
Integer ii = (Integer)get_Value(COLUMNNAME_GL_FundRestriction_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_FundRestriction.java
1
请完成以下Java代码
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final MethodDescriptor<ReqT, RespT> method, final CallOptions callOptions, final Channel next) { log.info("Received call to {}", method.getFullMethodName()); return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override public void sendMessage(ReqT message) { log.debug("Request message: {}", message); super.sendMessage(message); } @Override public void start(Listener<RespT> responseListener, Metadata headers) { super.start( new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) { @Override public void onMessage(RespT message) { log.debug("Response message: {}", message); super.onMessage(message); } @Override public void onHeaders(Metadata headers) {
log.debug("gRPC headers: {}", headers); super.onHeaders(headers); } @Override public void onClose(Status status, Metadata trailers) { log.info("Interaction ends with status: {}", status); log.info("Trailers: {}", trailers); super.onClose(status, trailers); } }, headers); } }; } }
repos\grpc-spring-master\examples\cloud-grpc-client\src\main\java\net\devh\boot\grpc\examples\cloud\client\LogGrpcInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
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 getAddress() { return address; } public void setAddress(String address) { this.address = address; } public List<Department> getDepartments() { return departments; } public void setDepartments(List<Department> departments) { this.departments = departments;
} public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } @Override public String toString() { return "Organization [id=" + id + ", name=" + name + ", address=" + address + "]"; } }
repos\sample-spring-microservices-new-master\organization-service\src\main\java\pl\piomin\services\organization\model\Organization.java
2
请完成以下Java代码
static ITranslatableString formatStringValue(@Nullable final String valueStr) { if (Check.isEmpty(valueStr, true)) { return TranslatableStrings.empty(); } else { return TranslatableStrings.anyLanguage(valueStr.trim()); } } static ITranslatableString formatNumber(@Nullable final BigDecimal valueBD, final int displayType) { if (valueBD == null) { return TranslatableStrings.anyLanguage("0"); } else { return TranslatableStrings.number(valueBD, displayType); } } static ITranslatableString formatDateValue(@Nullable final java.util.Date valueDate) { return valueDate != null ? TranslatableStrings.date(valueDate) : TranslatableStrings.anyLanguage("-"); } static ITranslatableString formatDateValue(@Nullable final LocalDate valueDate)
{ return valueDate != null ? TranslatableStrings.date(valueDate) : TranslatableStrings.anyLanguage("-"); } private void appendSeparator(final TranslatableStringBuilder description) { if (description.isEmpty()) { return; } description.append(SEPARATOR); } private void appendProductAttributes(final TranslatableStringBuilder description) { final boolean isInstanceAttribute = false; for (final Attribute attribute : attributesRepo.retrieveAttributes(attributeSetId, isInstanceAttribute)) { appendSeparator(description); description.append(attribute.getDisplayName()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\ASIDescriptionBuilderCommand.java
1
请完成以下Java代码
default Instant getExpiresAt() { return this.getClaimAsInstant(JwtClaimNames.EXP); } /** * Returns the Not Before {@code (nbf)} claim which identifies the time before which * the JWT MUST NOT be accepted for processing. * @return the Not Before time before which the JWT MUST NOT be accepted for * processing */ default Instant getNotBefore() { return this.getClaimAsInstant(JwtClaimNames.NBF); } /** * Returns the Issued at {@code (iat)} claim which identifies the time at which the * JWT was issued. * @return the Issued at claim which identifies the time at which the JWT was issued
*/ default Instant getIssuedAt() { return this.getClaimAsInstant(JwtClaimNames.IAT); } /** * Returns the JWT ID {@code (jti)} claim which provides a unique identifier for the * JWT. * @return the JWT ID claim which provides a unique identifier for the JWT */ default String getId() { return this.getClaimAsString(JwtClaimNames.JTI); } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimAccessor.java
1
请完成以下Java代码
public void updateDataEntriesOnNewAndchange(final I_C_Invoice_Candidate invoiceCand) { final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class); final boolean qtyChanged = InterfaceWrapperHelper.isValueChanged(invoiceCand, I_C_Invoice_Candidate.COLUMNNAME_QtyToInvoice) || InterfaceWrapperHelper.isValueChanged(invoiceCand, I_C_Invoice_Candidate.COLUMNNAME_QtyInvoiced); final boolean isToClearChanged = InterfaceWrapperHelper.isValueChanged(invoiceCand, I_C_Invoice_Candidate.COLUMNNAME_IsToClear); if ((qtyChanged || isToClearChanged) && invoiceCand.isToClear()) { // update data entries for (final I_C_Invoice_Clearing_Alloc ica : flatrateDAO.retrieveClearingAllocs(invoiceCand)) { if (ica.getC_Flatrate_DataEntry_ID() == 0) { continue; } final I_C_Flatrate_DataEntry dataEntry = ica.getC_Flatrate_DataEntry(); if (dataEntry.getC_Flatrate_Term().isClosingWithActualSum()) // TODO: don't use a virtual column! { if (X_C_Flatrate_DataEntry.DOCSTATUS_Completed.equals(dataEntry.getDocStatus())) { throw new InconsistentUpdateException( MSG_DATA_ENTRY_ERROR_ALREADY_COMPLETED_0P, MSG_DATA_ENTRY_ERROR_ALREADY_COMPLETED_TEXT_2P, new Object[] { invoiceCand.getC_Invoice_Candidate_ID(), dataEntry.getC_Period().getName() }, userDAO.getById(UserId.ofRepoId(dataEntry.getC_Flatrate_Term().getAD_User_InCharge_ID()))); } updateActualQty(dataEntry, invoiceCand, I_C_Invoice_Candidate.COLUMNNAME_QtyToInvoice, isToClearChanged); updateActualQty(dataEntry, invoiceCand, I_C_Invoice_Candidate.COLUMNNAME_QtyInvoiced, isToClearChanged); // note: this will also trigger updates of the other values of 'dataEntry' as well as of // possible aux entries InterfaceWrapperHelper.save(dataEntry); } } } } /** * @param isToClearChanged if <code>true</code>, then we assume that IsToClean has been change to 'Y'. In that case, we don't add the difference between old and new value, but just the new value */ private void updateActualQty( final I_C_Flatrate_DataEntry dataEntry,
final I_C_Invoice_Candidate invoiceCand, final String colName, final boolean isToClearChanged) { final PO po = InterfaceWrapperHelper.getPO(invoiceCand); BigDecimal oldValue = (BigDecimal)po.get_ValueOld(colName); if (isToClearChanged || oldValue == null) { oldValue = BigDecimal.ZERO; } BigDecimal currentValue = (BigDecimal)po.get_Value(colName); if (currentValue == null) { currentValue = BigDecimal.ZERO; } final BigDecimal diff = currentValue.subtract(oldValue); dataEntry.setActualQty(dataEntry.getActualQty().add(diff)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Invoice_Candidate.java
1
请在Spring Boot框架中完成以下Java代码
public String login() { if (ShiroKit.isAuthenticated()) { return "redirect:/"; } return "login"; } // 登录提交地址和applicationontext-shiro.xml配置的loginurl一致。 (配置文件方式的说法) @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(HttpServletRequest request, Map<String, Object> map) { _logger.info("登录方法start........."); // 登录失败从request中获取shiro处理的异常信息。shiroLoginFailure:就是shiro异常类的全类名. Object exception = request.getAttribute("shiroLoginFailure"); String msg; if (exception != null) { if (UnknownAccountException.class.isInstance(exception)) { msg = "用户名不正确,请重新输入"; } else if (IncorrectCredentialsException.class.isInstance(exception)) { msg = "密码错误,请重新输入"; } else if (IncorrectCaptchaException.class.isInstance(exception)) { msg = "验证码错误"; } else if (ForbiddenUserException.class.isInstance(exception)) { msg = "该用户已被禁用,如有疑问请联系系统管理员。"; } else { msg = "发生未知错误,请联系管理员。"; } map.put("username", request.getParameter("username")); map.put("password", request.getParameter("password")); map.put("msg", msg); return "login"; } //如果已经登录,直接跳转主页面 return "index"; } /** * 主页 * @param session
* @param model * @return */ @RequestMapping({"/", "/index"}) public String index(HttpSession session, Model model) { // _logger.info("访问首页start..."); // 做一些其他事情,比如把项目的数量放到session中 if (ShiroKit.hasRole("admin") && session.getAttribute("projectNum") == null) { session.setAttribute("projectNum", 2); } if (session.getAttribute("picsUrlPrefix") == null) { // 图片访问URL前缀 session.setAttribute("picsUrlPrefix", myProperties.getPicsUrlPrefix()); } return "index"; } /** * 欢迎页面 * @param request * @param model * @return */ @RequestMapping("/welcome") public String welcome(HttpServletRequest request, Model model) { return "modules/common/welcome"; } }
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\controller\LoginController.java
2
请完成以下Java代码
public ResponseEntity<Resource> fileUpload(@RequestParam("file") MultipartFile file) { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + UPLOAD_PREFIX).length())); LOG.info("upload: {}", filePath); fileService.saveFile(filePath, file.getInputStream()); return ResponseEntity.ok().build(); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @DeleteMapping(DELETE_PREFIX + "**") public ResponseEntity<Resource> delete() { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + DELETE_PREFIX).length())); LOG.info("delete: {}", filePath); fileService.delete(filePath); return ResponseEntity.ok().build(); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }
} @PostMapping(CREATEDIR_PREFIX + "**") public ResponseEntity<Resource> createDirectory() { try { String contextPath = httpServletRequest.getRequestURI(); Path filePath = Paths.get(contextPath.substring((URI_PREFIX + CREATEDIR_PREFIX).length())); LOG.info("createDirectory: {}", filePath); fileService.createDirectory(filePath); return ResponseEntity.ok().build(); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
repos\spring-examples-java-17\spring-fileserver\src\main\java\itx\examples\springboot\fileserver\rest\FileServerController.java
1