instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) { Element messageEventDefinitionElement = endEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION); if (messageEventDefinitionElement != null) { parseConnectorElement(messageEventDefinitionElement, scope, activity); } } @Override public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { Element messageEventDefinitionElement = intermediateEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION); if (messageEventDefinitionElement != null) { parseConnectorElement(messageEventDefinitionElement, scope, activity); } } @Override public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) { parseConnectorElement(businessRuleTaskElement, scope, activity); } @Override public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) { parseConnectorElement(sendTaskElement, scope, activity); }
protected void parseConnectorElement(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) { Element connectorDefinition = findCamundaExtensionElement(serviceTaskElement, "connector"); if (connectorDefinition != null) { Element connectorIdElement = connectorDefinition.element("connectorId"); String connectorId = null; if (connectorIdElement != null) { connectorId = connectorIdElement.getText().trim(); } if (connectorIdElement == null || connectorId.isEmpty()) { throw new BpmnParseException("No 'id' defined for connector.", connectorDefinition); } IoMapping ioMapping = parseInputOutput(connectorDefinition); activity.setActivityBehavior(new ServiceTaskConnectorActivityBehavior(connectorId, ioMapping)); } } }
repos\camunda-bpm-platform-master\engine-plugins\connect-plugin\src\main\java\org\camunda\connect\plugin\impl\ConnectorParseListener.java
1
请完成以下Java代码
public boolean isDown() { return STATUS_DOWN.equals(status); } public boolean isUnknown() { return STATUS_UNKNOWN.equals(status); } public static Comparator<String> severity() { return Comparator.comparingInt(STATUS_ORDER::indexOf); } @SuppressWarnings("unchecked") public static StatusInfo from(Map<String, ?> body) { Map<String, ?> details = Collections.emptyMap();
/* * Key "details" is present when accessing Spring Boot Actuator Health using * Accept-Header {@link org.springframework.boot.actuate.endpoint.ApiVersion#V2}. */ if (body.containsKey("details")) { details = (Map<String, ?>) body.get("details"); } else if (body.containsKey("components")) { details = (Map<String, ?>) body.get("components"); } return StatusInfo.valueOf((String) body.get("status"), details); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\StatusInfo.java
1
请完成以下Java代码
public CaseInstanceStartEventSubscriptionBuilder tenantId(String tenantId) { this.tenantId = tenantId; return this; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public Map<String, Object> getCorrelationParameterValues() { return correlationParameterValues; } public boolean isDoNotUpdateToLatestVersionAutomatically() { return doNotUpdateToLatestVersionAutomatically; } public String getTenantId() { return tenantId; } @Override
public EventSubscription subscribe() { checkValidInformation(); return cmmnRuntimeService.registerCaseInstanceStartEventSubscription(this); } protected void checkValidInformation() { if (StringUtils.isEmpty(caseDefinitionKey)) { throw new FlowableIllegalArgumentException("The case definition must be provided using the key for the subscription to be registered."); } if (correlationParameterValues.isEmpty()) { throw new FlowableIllegalArgumentException( "At least one correlation parameter value must be provided for a dynamic case start event subscription, " + "otherwise the case would get started on all events, regardless their correlation parameter values."); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionBuilderImpl.java
1
请完成以下Java代码
private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final DateFilterVO dateFilterVO) { if (dateFilterVO == null) { return false; } final LocalDate date = dateFilterVO.getDate(); if (date == null) { return false; } queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.GREATER_OR_EQUAL, date); queryBuilder.addCompareFilter(I_MD_Cockpit.COLUMN_DateGeneral, CompareQueryFilter.Operator.LESS, date.plusDays(1)); return true; } private boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Cockpit> queryBuilder, final ProductFilterVO productFilterVO) { final IQuery<I_M_Product> productQuery = ProductFilterUtil.createProductQueryOrNull(productFilterVO); if (productQuery == null) { return false; } queryBuilder.addInSubQueryFilter(I_MD_Cockpit.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, productQuery); return true; }
private IQueryBuilder<I_MD_Cockpit> augmentQueryBuilderWithOrderBy(@NonNull final IQueryBuilder<I_MD_Cockpit> queryBuilder) { return queryBuilder .orderByDescending(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate) .orderBy(I_MD_Cockpit.COLUMNNAME_DateGeneral) .orderBy(I_MD_Cockpit.COLUMNNAME_M_Product_ID) .orderBy(I_MD_Cockpit.COLUMNNAME_AttributesKey); } public LocalDate getFilterByDate(@NonNull final DocumentFilterList filters) { final DateFilterVO dateFilterVO = DateFilterUtil.extractDateFilterVO(filters); return dateFilterVO.getDate(); } public Predicate<I_M_Product> toProductFilterPredicate(@NonNull final DocumentFilterList filters) { return ProductFilterUtil.toPredicate(filters); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\MaterialCockpitFilters.java
1
请完成以下Java代码
public String getVertifyMan() { return vertifyMan; } public void setVertifyMan(String vertifyMan) { this.vertifyMan = vertifyMan; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail;
} @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productId=").append(productId); sb.append(", createTime=").append(createTime); sb.append(", vertifyMan=").append(vertifyMan); sb.append(", status=").append(status); sb.append(", detail=").append(detail); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductVertifyRecord.java
1
请完成以下Java代码
public static Pair<DataType, Number> castToNumber(String value) { if (isNumber(value)) { String formattedValue = value.replace(',', '.'); BigDecimal bd = new BigDecimal(formattedValue); if (bd.stripTrailingZeros().scale() > 0 || isSimpleDouble(formattedValue)) { if (bd.scale() <= 16) { return Pair.of(DataType.DOUBLE, bd.doubleValue()); } else { return Pair.of(DataType.DOUBLE, bd); } } else { return Pair.of(DataType.LONG, bd.longValueExact()); } } else { throw new IllegalArgumentException("'" + value + "' can't be parsed as number"); } }
private static boolean isNumber(String value) { return NumberUtils.isNumber(value.replace(',', '.')); } private static boolean isSimpleDouble(String valueAsString) { return valueAsString.contains(".") && !valueAsString.contains("E") && !valueAsString.contains("e"); } private static boolean looksLikeJson(String value) { String trimmed = value.trim(); return (trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]")); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\util\TypeCastUtil.java
1
请完成以下Java代码
public void fireBeforeCommit(final ITrx trx) { // nothing } /** * Does nothing */ @Override public void fireAfterCommit(final ITrx trx) { // nothing } /** * Does nothing */ @Override
public void fireAfterRollback(final ITrx trx) { // nothing } /** * Does nothing */ @Override public void fireAfterClose(ITrx trx) { // nothing } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\NullTrxListenerManager.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_C_Order getC_Order() { return get_ValueAsPO(COLUMNNAME_C_Order_ID, org.compiere.model.I_C_Order.class); } @Override public void setC_Order(final org.compiere.model.I_C_Order C_Order) { set_ValueFromPO(COLUMNNAME_C_Order_ID, org.compiere.model.I_C_Order.class, C_Order); } @Override public void setC_Order_ID (final int C_Order_ID) { if (C_Order_ID < 1) set_Value (COLUMNNAME_C_Order_ID, null); else set_Value (COLUMNNAME_C_Order_ID, C_Order_ID); } @Override public int getC_Order_ID() { return get_ValueAsInt(COLUMNNAME_C_Order_ID); } @Override public void setDateOrdered (final @Nullable java.sql.Timestamp DateOrdered) { set_Value (COLUMNNAME_DateOrdered, DateOrdered); } @Override public java.sql.Timestamp getDateOrdered() { return get_ValueAsTimestamp(COLUMNNAME_DateOrdered); } @Override public void setEDI_cctop_111_v_ID (final int EDI_cctop_111_v_ID) { if (EDI_cctop_111_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, EDI_cctop_111_v_ID); } @Override public int getEDI_cctop_111_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_111_v_ID); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); } @Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { if (M_InOut_ID < 1) set_Value (COLUMNNAME_M_InOut_ID, null);
else set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID); } @Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_111_v.java
1
请完成以下Java代码
public void setPriceStd (final BigDecimal PriceStd) { set_Value (COLUMNNAME_PriceStd, PriceStd); } @Override public BigDecimal getPriceStd() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * UseScalePrice AD_Reference_ID=541376 * Reference name: UseScalePrice */ public static final int USESCALEPRICE_AD_Reference_ID=541376; /** Use scale price, fallback to product price = Y */ public static final String USESCALEPRICE_UseScalePriceFallbackToProductPrice = "Y"; /** Don't use scale price = N */ public static final String USESCALEPRICE_DonTUseScalePrice = "N"; /** Use scale price (strict) = S */ public static final String USESCALEPRICE_UseScalePriceStrict = "S";
@Override public void setUseScalePrice (final java.lang.String UseScalePrice) { set_Value (COLUMNNAME_UseScalePrice, UseScalePrice); } @Override public java.lang.String getUseScalePrice() { return get_ValueAsString(COLUMNNAME_UseScalePrice); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { throw new IllegalArgumentException ("ValidFrom is virtual column"); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPrice.java
1
请完成以下Java代码
public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getWidth() { return width; }
public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ParticipantProcess.java
1
请完成以下Java代码
public void setIsMandatory (boolean IsMandatory) { set_Value (COLUMNNAME_IsMandatory, Boolean.valueOf(IsMandatory)); } /** Get Mandatory. @return Data entry is required in this column */ public boolean isMandatory () { Object oo = get_Value(COLUMNNAME_IsMandatory); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Null Value. @param IsNullFieldValue Null Value */ public void setIsNullFieldValue (boolean IsNullFieldValue) { set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue)); } /** Get Null Value. @return Null Value */ public boolean isNullFieldValue () { Object oo = get_Value(COLUMNNAME_IsNullFieldValue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Operation AD_Reference_ID=205 */ public static final int OPERATION_AD_Reference_ID=205; /** = = == */ public static final String OPERATION_Eq = "=="; /** >= = >= */ public static final String OPERATION_GtEq = ">="; /** > = >> */ public static final String OPERATION_Gt = ">>"; /** < = << */ public static final String OPERATION_Le = "<<"; /** ~ = ~~ */ public static final String OPERATION_Like = "~~"; /** <= = <= */ public static final String OPERATION_LeEq = "<="; /** |<x>| = AB */ public static final String OPERATION_X = "AB"; /** sql = SQ */ public static final String OPERATION_Sql = "SQ"; /** != = != */ public static final String OPERATION_NotEq = "!="; /** Set Arbeitsvorgang . @param Operation Compare Operation */ public void setOperation (String Operation) {
set_Value (COLUMNNAME_Operation, Operation); } /** Get Arbeitsvorgang . @return Compare Operation */ public String getOperation () { return (String)get_Value(COLUMNNAME_Operation); } /** Type AD_Reference_ID=540202 */ public static final int TYPE_AD_Reference_ID=540202; /** Field Value = FV */ public static final String TYPE_FieldValue = "FV"; /** Context Value = CV */ public static final String TYPE_ContextValue = "CV"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Criteria.java
1
请在Spring Boot框架中完成以下Java代码
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 int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public int getMax() { return max; } public void setMax(int max) { this.max = max; }
public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } }
repos\SpringBootLearning-master\springboot-config\src\main\java\com\forezp\bean\ConfigBean.java
2
请完成以下Java代码
public void remove (final int offset, final int length) throws BadLocationException { if (log.isTraceEnabled()) log.trace("Offset=" + offset + ",Length=" + length); // Case: clear the field (i.e removing the whole content) if (offset == 0 && length == getLength()) { super.remove(offset, length); return; } // begin of string if (offset == 0 || length == 0) { // empty the field // if the length is 0 or greater or equal with the mask length - teo_sarca, [ 1660595 ] Date field: incorrect functionality on paste if (length >= m_mask.length() || length == 0) super.remove(offset, length); return; } // one position behind delimiter if (offset-1 >= 0 && offset-1 < m_mask.length() && m_mask.charAt(offset-1) == DELIMITER) { if (offset-2 >= 0) m_tc.setCaretPosition(offset-2); else return; } else m_tc.setCaretPosition(offset-1); } // deleteString @Override public void replace(final int offset, final int length, final String text, final AttributeSet attrs) throws BadLocationException { super.replace(offset, length, text, attrs); } /** * Caret Listener * @param e event */ @Override public void caretUpdate(CaretEvent e) { if(log.isTraceEnabled()) log.trace("Dot=" + e.getDot() + ",Last=" + m_lastDot + ", Mark=" + e.getMark()); // Selection if (e.getDot() != e.getMark()) { m_lastDot = e.getDot(); return; } // // Is the current position a fixed character? if (e.getDot()+1 > m_mask.length() || m_mask.charAt(e.getDot()) != DELIMITER) { m_lastDot = e.getDot(); return; } // Direction? int newDot = -1; if (m_lastDot > e.getDot()) // <- newDot = e.getDot() - 1; else // -> (or same) newDot = e.getDot() + 1;
if (e.getDot() == 0) // first newDot = 1; else if (e.getDot() == m_mask.length()-1) // last newDot = e.getDot() - 1; // if (log.isDebugEnabled()) log.debug("OnFixedChar=" + m_mask.charAt(e.getDot()) + ", newDot=" + newDot + ", last=" + m_lastDot); // m_lastDot = e.getDot(); if (newDot >= 0 && newDot < getText().length()) m_tc.setCaretPosition(newDot); } // caretUpdate /** * Get Full Text * @return text */ private String getText() { String str = ""; try { str = getContent().getString(0, getContent().length() - 1); // cr at end } catch (Exception e) { str = ""; } return str; } private final void provideErrorFeedback() { UIManager.getLookAndFeel().provideErrorFeedback(m_tc); } } // MDocDate
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocDate.java
1
请完成以下Java代码
HuId resolveHUId( @NonNull final ProductId productId, @NonNull final JsonRequestHULookup request) { final IHUQueryBuilder queryBuilder = handlingUnitsBL.createHUQueryBuilder() .setHUStatus(X_M_HU.HUSTATUS_Active) .addOnlyWithProductId(productId); if (!Check.isBlank(request.getHuValue())) { queryBuilder.addOnlyHUValue(request.getHuValue()); } if (!Check.isBlank(request.getLotNumber())) { queryBuilder.addOnlyWithAttribute(AttributeConstants.ATTR_LotNumber, request.getLotNumber()); } if (request.getBestBeforeDate() != null) { queryBuilder.addOnlyWithAttribute(AttributeConstants.ATTR_BestBeforeDate, request.getBestBeforeDate()); } if (!Check.isBlank(request.getSerialNo())) { queryBuilder.addOnlyWithAttribute(AttributeConstants.ATTR_SerialNo, request.getSerialNo()); } final HuId huId = queryBuilder.createQueryBuilder() .orderBy(I_M_HU.COLUMNNAME_M_HU_ID) .create() .firstId(HuId::ofRepoIdOrNull); if (huId == null) { throw new AdempiereException("No HU found for M_Product_ID=" + productId.getRepoId() + " and request=" + request); } return huId; } private JsonErrorItem createJsonErrorItem(@NonNull final Exception ex) { final AdIssueId adIssueId = errorManager.createIssue(ex); return JsonErrorItem.builder() .message(ex.getLocalizedMessage()) .stackTrace(Trace.toOneLineStackTraceString(ex.getStackTrace())) .adIssueId(JsonMetasfreshId.of(adIssueId.getRepoId())) .errorCode(AdempiereException.extractErrorCodeOrNull(ex)) .throwable(ex) .build();
} private String toJsonString(@NonNull final Object obj) { try { return jsonObjectMapper.writeValueAsString(obj); } catch (final JsonProcessingException ex) { logger.warn("Failed converting {} to JSON. Returning toString()", obj, ex); return obj.toString(); } } @Nullable private static PPCostCollectorId extractCostCollectorId(@NonNull final JsonResponseIssueToManufacturingOrderDetail issueDetail) { return toPPCostCollectorId(issueDetail.getCostCollectorId()); } @Nullable private static PPCostCollectorId toPPCostCollectorId(@Nullable final JsonMetasfreshId id) { return id != null ? PPCostCollectorId.ofRepoIdOrNull(id.getValue()) : null; } @Nullable private static JsonMetasfreshId toJsonMetasfreshId(@Nullable final PPCostCollectorId costCollectorId) { return costCollectorId != null ? JsonMetasfreshId.of(costCollectorId.getRepoId()) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrderReportProcessCommand.java
1
请在Spring Boot框架中完成以下Java代码
protected void applyFilters(DecisionRequirementsDefinitionQuery query) { if (decisionRequirementsDefinitionId != null) { query.decisionRequirementsDefinitionId(decisionRequirementsDefinitionId); } if (decisionRequirementsDefinitionIdIn != null && !decisionRequirementsDefinitionIdIn.isEmpty()) { query.decisionRequirementsDefinitionIdIn(decisionRequirementsDefinitionIdIn.toArray(new String[decisionRequirementsDefinitionIdIn.size()])); } if (category != null) { query.decisionRequirementsDefinitionCategory(category); } if (categoryLike != null) { query.decisionRequirementsDefinitionCategoryLike(categoryLike); } if (name != null) { query.decisionRequirementsDefinitionName(name); } if (nameLike != null) { query.decisionRequirementsDefinitionNameLike(nameLike); } if (deploymentId != null) { query.deploymentId(deploymentId); } if (key != null) { query.decisionRequirementsDefinitionKey(key); } if (keyLike != null) { query.decisionRequirementsDefinitionKeyLike(keyLike); } if (resourceName != null) { query.decisionRequirementsDefinitionResourceName(resourceName); } if (resourceNameLike != null) { query.decisionRequirementsDefinitionResourceNameLike(resourceNameLike); } if (version != null) { query.decisionRequirementsDefinitionVersion(version);
} if (TRUE.equals(latestVersion)) { query.latestVersion(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (TRUE.equals(includeDefinitionsWithoutTenantId)) { query.includeDecisionRequirementsDefinitionsWithoutTenantId(); } } @Override protected void applySortBy(DecisionRequirementsDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { query.orderByDecisionRequirementsDefinitionCategory(); } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { query.orderByDecisionRequirementsDefinitionKey(); } else if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByDecisionRequirementsDefinitionId(); } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { query.orderByDecisionRequirementsDefinitionVersion(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByDecisionRequirementsDefinitionName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { query.orderByDeploymentId(); } else if (sortBy.equals(SORT_BY_TENANT_ID)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DecisionRequirementsDefinitionQueryDto.java
2
请完成以下Java代码
public void run(String innerTrxName) { try { load0(innerTrxName); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AdempiereException(e); } } }); } private void load0(String trxName) throws ParserConfigurationException, SAXException, IOException { this.objects = new ArrayList<Object>(); final IXMLHandlerFactory factory = Services.get(IXMLHandlerFactory.class); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setIgnoringElementContentWhitespace(true); final DocumentBuilder builder = dbf.newDocumentBuilder(); final InputSource source = getInputSource(); final Document doc = builder.parse(source); final NodeList nodes = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (!(nodes.item(i) instanceof Element)) { continue; } final Element element = (Element)nodes.item(i); final String name = element.getLocalName(); final Class<Object> beanClass = factory.getBeanClassByNodeName(name); if (beanClass == null) { addLog("Error: node is not handled: " + name); continue; } final IXMLHandler<Object> converter = factory.getHandler(beanClass); final Object bean = InterfaceWrapperHelper.create(ctx, beanClass, trxName); if (converter.fromXmlNode(bean, element)) { InterfaceWrapperHelper.save(bean); // make sure is saved objects.add(bean);
} } } private InputSource getInputSource() { if (fileName != null) { return new InputSource(fileName); } else if (inputStream != null) { return new InputSource(inputStream); } else { throw new AdempiereException("Cannot identify source"); } } private void addLog(String msg) { logger.info(msg); } public List<Object> getObjects() { if (objects == null) { return new ArrayList<Object>(); } return new ArrayList<Object>(this.objects); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\XMLLoader.java
1
请完成以下Java代码
UserRolePermissionsBuilder setConstraints(final Constraints constraints) { Check.assumeNull(this.constraints, "constraints not already configured"); this.constraints = constraints; return this; } public Constraints getConstraints() { Check.assumeNotNull(constraints, "constraints configured"); return constraints; } @SuppressWarnings("UnusedReturnValue") public UserRolePermissionsBuilder includeUserRolePermissions(final UserRolePermissions userRolePermissions, final int seqNo) { userRolePermissionsToInclude.add(UserRolePermissionsInclude.of(userRolePermissions, seqNo)); return this; } UserRolePermissionsBuilder setAlreadyIncludedRolePermissions(final UserRolePermissionsIncludesList userRolePermissionsAlreadyIncluded) { Check.assumeNotNull(userRolePermissionsAlreadyIncluded, "included not null"); Check.assumeNull(this.userRolePermissionsAlreadyIncluded, "already included permissions were not configured before"); this.userRolePermissionsAlreadyIncluded = userRolePermissionsAlreadyIncluded; return this; } UserRolePermissionsIncludesList getUserRolePermissionsIncluded() { Check.assumeNotNull(userRolePermissionsIncluded, "userRolePermissionsIncluded not null"); return userRolePermissionsIncluded; } public UserRolePermissionsBuilder setMenuInfo(final UserMenuInfo menuInfo) { this._menuInfo = menuInfo; return this; } public UserMenuInfo getMenuInfo() {
if (_menuInfo == null) { _menuInfo = findMenuInfo(); } return _menuInfo; } private UserMenuInfo findMenuInfo() { final Role adRole = getRole(); final AdTreeId roleMenuTreeId = adRole.getMenuTreeId(); if (roleMenuTreeId != null) { return UserMenuInfo.of(roleMenuTreeId, adRole.getRootMenuId()); } final I_AD_ClientInfo adClientInfo = getAD_ClientInfo(); final AdTreeId adClientMenuTreeId = AdTreeId.ofRepoIdOrNull(adClientInfo.getAD_Tree_Menu_ID()); if (adClientMenuTreeId != null) { return UserMenuInfo.of(adClientMenuTreeId, adRole.getRootMenuId()); } // Fallback: when role has NO menu and there is no menu defined on AD_ClientInfo level - shall not happen return UserMenuInfo.DEFAULT_MENU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public Wsdl11Definition orderStatusWebServiceV1() { return createWsdl(OrderStatusWebServiceV1.WSDL_BEAN_NAME); } @Bean("Msv3Service_schema1") public XsdSchema msv3serviceSchemaXsdV1() { return createXsdSchema("Msv3Service_schema1.xsd"); } @Bean("Msv3FachlicheFunktionen") public XsdSchema msv3FachlicheFunktionenV1() { return createXsdSchema("Msv3FachlicheFunktionen.xsd"); }
private static Wsdl11Definition createWsdl(@NonNull final String beanName) { return new SimpleWsdl11Definition(createSchemaResource(beanName + ".wsdl")); } private static XsdSchema createXsdSchema(@NonNull final String resourceName) { return new SimpleXsdSchema(createSchemaResource(resourceName)); } private static ClassPathResource createSchemaResource(@NonNull final String resourceName) { return new ClassPathResource(SCHEMA_RESOURCE_PREFIX + "/" + resourceName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\WebServiceConfigV1.java
2
请完成以下Java代码
protected PlanItemInstanceEntity reactivatePlanItem(PlanItemInstanceEntity planItemInstance) { PlanItemInstanceEntityManager planItemInstanceEntityManager = CommandContextUtil.getPlanItemInstanceEntityManager(commandContext); PlanItemInstance stagePlanItem = planItemInstance.getStagePlanItemInstanceEntity(); if (stagePlanItem == null && planItemInstance.getStageInstanceId() != null) { stagePlanItem = planItemInstanceEntityManager.findById(planItemInstance.getStageInstanceId()); } PlanItemInstanceEntity reactivatedPlanItemInstance = planItemInstanceEntityManager .createPlanItemInstanceEntityBuilder() .planItem(planItemInstance.getPlanItem()) .caseDefinitionId(planItemInstance.getCaseDefinitionId()) .caseInstanceId(planItemInstance.getCaseInstanceId()) .stagePlanItemInstance(stagePlanItem) .tenantId(planItemInstance.getTenantId()) .addToParent(true) .silentNameExpressionEvaluation(false) .create(); CommandContextUtil.getAgenda(commandContext).planReactivatePlanItemInstanceOperation(reactivatedPlanItemInstance);
return reactivatedPlanItemInstance; } protected PlanItemInstanceEntity searchPlanItemInstance(String planItemDefinitionId, List<PlanItemInstanceEntity> planItemInstances) { for (PlanItemInstanceEntity planItemInstance : planItemInstances) { if (planItemInstance.getPlanItemDefinitionId().equals(planItemDefinitionId)) { return planItemInstance; } } throw new FlowableIllegalArgumentException("Could not find plan item instance for plan item with definition id " + planItemDefinitionId); } @Override public String toString() { return "[Init Plan Model] initializing plan model for case instance " + caseInstanceEntity.getId(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ReactivateCaseInstanceOperation.java
1
请完成以下Java代码
private boolean isMultiValue(Class<?> returnType, @Nullable ReactiveAdapter adapter) { if (Flux.class.isAssignableFrom(returnType)) { return true; } return adapter == null || adapter.isMultiValue(); } private Mono<?> filterSingleValue(Publisher<?> publisher, EvaluationContext ctx, ExpressionAttribute attribute) { return Mono.from(publisher) .doOnNext((result) -> setFilterObject(ctx, result)) .flatMap((result) -> postFilter(ctx, result, attribute)); } private Flux<?> filterMultiValue(Publisher<?> publisher, EvaluationContext ctx, ExpressionAttribute attribute) { return Flux.from(publisher) .doOnNext((result) -> setFilterObject(ctx, result)) .flatMap((result) -> postFilter(ctx, result, attribute)); } private void setFilterObject(EvaluationContext ctx, Object result) { TypedValue rootObject = ctx.getRootObject(); Assert.notNull(rootObject, "rootObject cannot be null"); MethodSecurityExpressionOperations methodOperations = (MethodSecurityExpressionOperations) rootObject .getValue(); Assert.notNull(methodOperations, "methodOperations cannot be null"); methodOperations.setFilterObject(result); } private Mono<?> postFilter(EvaluationContext ctx, Object result, ExpressionAttribute attribute) { return ReactiveExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx) .flatMap((granted) -> granted ? Mono.just(result) : Mono.empty()); } @Override public Pointcut getPointcut() {
return this.pointcut; } @Override public Advice getAdvice() { return this; } @Override public boolean isPerInstance() { return true; } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationReactiveMethodInterceptor.java
1
请完成以下Java代码
public void setLabelMinWidth(final int labelMinWidth) { this.labelMinWidth = labelMinWidth; } public void setLabelMaxWidth(final int labelMaxWidth) { this.labelMaxWidth = labelMaxWidth; } public void setFieldMinWidth(final int fieldMinWidth) { this.fieldMinWidth = fieldMinWidth; } public void setFieldMaxWidth(final int fieldMaxWidth) { this.fieldMaxWidth = fieldMaxWidth; } public void updateMinWidthFrom(final CLabel label) { final int labelWidth = label.getPreferredSize().width; labelMinWidth = labelWidth > labelMinWidth ? labelWidth : labelMinWidth;
logger.trace("LabelMinWidth={} ({})", new Object[] { labelMinWidth, label }); } public void updateMinWidthFrom(final VEditor editor) { final JComponent editorComp = swingEditorFactory.getEditorComponent(editor); final int editorCompWidth = editorComp.getPreferredSize().width; if (editorCompWidth > fieldMinWidth) { fieldMinWidth = editorCompWidth; } logger.trace("FieldMinWidth={} ({})", new Object[] { fieldMinWidth, editorComp }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelLayoutCallback.java
1
请在Spring Boot框架中完成以下Java代码
public void processorRegisterRoute(@NotNull final Exchange exchange) { final JsonAuthenticateRequest request = exchange.getIn().getBody(JsonAuthenticateRequest.class); final SimpleGrantedAuthority authority = new SimpleGrantedAuthority(request.getGrantedAuthority()); tokenService.store(request.getAuthKey(), ImmutableList.of(authority), getTokenCredentials(request)); } public void processorExpireRoute(@NotNull final Exchange exchange) { final JsonAuthenticateRequest request = exchange.getIn().getBody(JsonAuthenticateRequest.class); tokenService.expiryToken(request.getAuthKey()); final int numberOfAuthenticatedTokens = tokenService.getNumberOfAuthenticatedTokens(request.getGrantedAuthority());
exchange.getIn().setBody(JsonExpireTokenResponse.builder() .numberOfAuthenticatedTokens(numberOfAuthenticatedTokens) .build()); } @NotNull private TokenCredentials getTokenCredentials(@NotNull final JsonAuthenticateRequest request) { return TokenCredentials.builder() .pInstance(request.getPInstance()) .auditTrailEndpoint(request.getAuditTrailEndpoint()) .externalSystemValue(request.getExternalSystemValue()) .orgCode(request.getOrgCode()) .build(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\RestAPIAuthenticateRoute.java
2
请完成以下Java代码
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return -o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<String, Integer> entry : entries) { sb.append(entry.getKey()); sb.append(' '); sb.append(entry.getValue()); sb.append(' '); } return sb.toString(); } public static SimpleItem create(String param) { if (param == null) return null; String[] array = param.split(" "); return create(array); } public static SimpleItem create(String param[]) { if (param.length % 2 == 1) return null; SimpleItem item = new SimpleItem(); int natureCount = (param.length) / 2; for (int i = 0; i < natureCount; ++i) { item.labelMap.put(param[2 * i], Integer.parseInt(param[1 + 2 * i])); } return item; } /** * 合并两个条目,两者的标签map会合并 * @param other */ public void combine(SimpleItem other) { for (Map.Entry<String, Integer> entry : other.labelMap.entrySet()) { addLabel(entry.getKey(), entry.getValue());
} } /** * 获取全部频次 * @return */ public int getTotalFrequency() { int frequency = 0; for (Integer f : labelMap.values()) { frequency += f; } return frequency; } public String getMostLikelyLabel() { return labelMap.entrySet().iterator().next().getKey(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\SimpleItem.java
1
请在Spring Boot框架中完成以下Java代码
public class WarehouseRouteBuilderV2 extends RouteBuilder { @VisibleForTesting static final String ROUTE_ID = "To-MF_Upsert-Warehouse_V2"; @Override public void configure() { errorHandler(noErrorHandler()); from("{{" + ExternalSystemCamelConstants.MF_UPSERT_WAREHOUSE_V2_CAMEL_URI + "}}") .routeId(ROUTE_ID) .streamCache("true") .process(exchange -> { final var upsertRequest = exchange.getIn().getBody(); if (!(upsertRequest instanceof WarehouseUpsertCamelRequest)) {
throw new RuntimeCamelException("The route " + ROUTE_ID + " requires the body to be instanceof WarehouseUpsertCamelRequest V2." + " However, it is " + (upsertRequest == null ? "null" : upsertRequest.getClass().getName())); } exchange.getIn().setHeader(HEADER_ORG_CODE, ((WarehouseUpsertCamelRequest)upsertRequest).getOrgCode()); final var jsonRequestWarehouseUpsert = ((WarehouseUpsertCamelRequest)upsertRequest).getJsonRequestWarehouseUpsert(); log.info("Warehouse upsert route invoked with " + jsonRequestWarehouseUpsert.getRequestItems().size() + " requestItems"); exchange.getIn().setBody(jsonRequestWarehouseUpsert); }) .marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonRequestWarehouseUpsert.class)) .removeHeaders("CamelHttp*") .setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.PUT)) .toD("{{metasfresh.upsert-warehouse-v2.api.uri}}/${header." + HEADER_ORG_CODE + "}") .to(direct(UNPACK_V2_API_RESPONSE)); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\WarehouseRouteBuilderV2.java
2
请完成以下Java代码
public int getAD_Table_ID() { return AD_Table_ID; } public void setAD_Table_ID(int aD_Table_ID) { AD_Table_ID = aD_Table_ID; } @Override public int getRecord_ID() { return Record_ID; } public void setRecord_ID(int record_ID) { Record_ID = record_ID; } @Override public List<I_C_DunningLevel> getC_DunningLevels() { return C_DunningLevels; } public void setC_DunningLevels(List<I_C_DunningLevel> c_DunningLevels) { C_DunningLevels = c_DunningLevels; } @Override public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public boolean isApplyClientSecurity() { return applyClientSecurity; } public void setApplyClientSecurity(boolean applyClientSecurity) {
this.applyClientSecurity = applyClientSecurity; } @Override public Boolean getProcessed() { return processed; } public void setProcessed(Boolean processed) { this.processed = processed; } @Override public Boolean getWriteOff() { return writeOff; } public void setWriteOff(Boolean writeOff) { this.writeOff = writeOff; } @Override public String getAdditionalWhere() { return additionalWhere; } public void setAdditionalWhere(String additionalWhere) { this.additionalWhere = additionalWhere; } @Override public ApplyAccessFilter getApplyAccessFilter() { return applyAccessFilter; } public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter) { this.applyAccessFilter = applyAccessFilter; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java
1
请完成以下Java代码
public Long getExceptionQps() { return exceptionQps; } public void setExceptionQps(Long exceptionQps) { this.exceptionQps = exceptionQps; } public Long getOneMinutePass() { return oneMinutePass; } public void setOneMinutePass(Long oneMinutePass) { this.oneMinutePass = oneMinutePass; } public Long getOneMinuteBlock() { return oneMinuteBlock; } public void setOneMinuteBlock(Long oneMinuteBlock) { this.oneMinuteBlock = oneMinuteBlock; } public Long getOneMinuteException() { return oneMinuteException; } public void setOneMinuteException(Long oneMinuteException) { this.oneMinuteException = oneMinuteException; } public Long getOneMinuteTotal() { return oneMinuteTotal; }
public void setOneMinuteTotal(Long oneMinuteTotal) { this.oneMinuteTotal = oneMinuteTotal; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public List<ResourceTreeNode> getChildren() { return children; } public void setChildren(List<ResourceTreeNode> children) { this.children = children; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\ResourceTreeNode.java
1
请在Spring Boot框架中完成以下Java代码
public List<PmsMenu> listByParentId(Long parentId) { return pmsMenuDao.listByParentId(parentId); } /*** * 根据名称和是否叶子节点查询数据 * * @param isLeaf * 是否是叶子节点 * @param name * 节点名称 * @return */ public List<PmsMenu> getMenuByNameAndIsLeaf(Map<String, Object> map) { return pmsMenuDao.getMenuByNameAndIsLeaf(map); } /** * 根据菜单ID获取菜单. * * @param pid * @return */ public PmsMenu getById(Long pid) { return pmsMenuDao.getById(pid); } /** * 更新菜单. *
* @param menu */ public void update(PmsMenu menu) { pmsMenuDao.update(menu); } /** * 根据角色查找角色对应的菜单ID集 * * @param roleId * @return */ public String getMenuIdsByRoleId(Long roleId) { List<PmsMenuRole> menuList = pmsMenuRoleDao.listByRoleId(roleId); StringBuffer menuIds = new StringBuffer(""); if (menuList != null && !menuList.isEmpty()) { for (PmsMenuRole rm : menuList) { menuIds.append(rm.getMenuId()).append(","); } } return menuIds.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsMenuServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
private IHUPackingAware createHUPackingAware( @NonNull final I_C_Order order, @NonNull final ProductsProposalRow fromRow) { final PlainHUPackingAware huPackingAware = createAndInitHUPackingAware(order, fromRow); final BigDecimal qty = fromRow.getQty(); if (qty == null || qty.signum() <= 0) { throw new AdempiereException("Qty shall be greather than zero"); // TODO trl } huPackingAwareBL.computeAndSetQtysForNewHuPackingAware(huPackingAware, qty); validateNewHUPackingAware(huPackingAware); return huPackingAware; } private PlainHUPackingAware createAndInitHUPackingAware( @NonNull final I_C_Order order, @NonNull final ProductsProposalRow fromRow) { final PlainHUPackingAware huPackingAware = new PlainHUPackingAware(); huPackingAware.setBpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID())); huPackingAware.setInDispute(false); final UomId uomId = productBL.getStockUOMId(fromRow.getProductId());
huPackingAware.setProductId(fromRow.getProductId()); huPackingAware.setUomId(uomId); huPackingAware.setM_AttributeSetInstance_ID(AttributeSetInstanceId.toRepoId(fromRow.getAsiId())); huPackingAware.setPiItemProductId(fromRow.getPackingMaterialId()); return huPackingAware; } private void validateNewHUPackingAware(@NonNull final PlainHUPackingAware huPackingAware) { if (huPackingAware.getQty() == null || huPackingAware.getQty().signum() <= 0) { logger.warn("Invalid Qty={} for {}", huPackingAware.getQty(), huPackingAware); throw new AdempiereException("Qty shall be greather than zero"); // TODO trl } if (huPackingAware.getQtyTU() == null || huPackingAware.getQtyTU().signum() <= 0) { logger.warn("Invalid QtyTU={} for {}", huPackingAware.getQtyTU(), huPackingAware); throw new AdempiereException("QtyTU shall be greather than zero"); // TODO trl } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\service\OrderLinesFromProductProposalsProducer.java
2
请完成以下Java代码
public void propertyChange(final PropertyChangeEvent evt) { if (isDisposed()) { return; } final JComponent textComponent = (JComponent)evt.getSource(); if (textComponent == null) { return; // shall not happen } final VEditorActionButton actionButton = getActionButton(); if (actionButton == null) { dispose();
return; } final String propertyName = evt.getPropertyName(); if (PROPERTY_PreferredSize.equals(propertyName)) { updateActionButtonUI_PreferredSize(actionButton, textComponent); } else if (PROPERTY_Background.equals(propertyName)) { updateActionButtonUI_Background(actionButton, textComponent); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorActionButton.java
1
请完成以下Java代码
public class SubProcessActivityBehavior extends AbstractBpmnActivityBehavior implements CompositeActivityBehavior { @Override public void execute(ActivityExecution execution) throws Exception { PvmActivity activity = execution.getActivity(); PvmActivity initialActivity = activity.getProperties().get(BpmnProperties.INITIAL_ACTIVITY); ensureNotNull("No initial activity found for subprocess " + execution.getActivity().getId(), "initialActivity", initialActivity); execution.executeActivity(initialActivity); } @Override public void concurrentChildExecutionEnded(ActivityExecution scopeExecution, ActivityExecution endedExecution) { // join endedExecution.remove(); scopeExecution.tryPruneLastConcurrentChild(); scopeExecution.forceUpdate();
} @Override public void complete(ActivityExecution scopeExecution) { leave(scopeExecution); } @Override public void doLeave(ActivityExecution execution) { CompensationUtil.createEventScopeExecution((ExecutionEntity) execution); super.doLeave(execution); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\SubProcessActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public void setCertificate(@Nullable String certificate) { this.certificate = certificate; } public @Nullable String getPrivateKey() { return this.privateKey; } public void setPrivateKey(@Nullable String privateKey) { this.privateKey = privateKey; } public @Nullable String getPrivateKeyPassword() { return this.privateKeyPassword; }
public void setPrivateKeyPassword(@Nullable String privateKeyPassword) { this.privateKeyPassword = privateKeyPassword; } public boolean isVerifyKeys() { return this.verifyKeys; } public void setVerifyKeys(boolean verifyKeys) { this.verifyKeys = verifyKeys; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\PemSslBundleProperties.java
2
请完成以下Java代码
public void setAD_Process_Stats_ID (int AD_Process_Stats_ID) { if (AD_Process_Stats_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Process_Stats_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Process_Stats_ID, Integer.valueOf(AD_Process_Stats_ID)); } /** Get Process Statistics. @return Process Statistics */ @Override public int getAD_Process_Stats_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Stats_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Statistic Count. @param Statistic_Count Internal statistics how often the entity was used */ @Override public void setStatistic_Count (int Statistic_Count) { set_Value (COLUMNNAME_Statistic_Count, Integer.valueOf(Statistic_Count)); } /** Get Statistic Count. @return Internal statistics how often the entity was used */ @Override public int getStatistic_Count () {
Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Count); if (ii == null) return 0; return ii.intValue(); } /** Set Statistic Milliseconds. @param Statistic_Millis Internal statistics how many milliseconds a process took */ @Override public void setStatistic_Millis (int Statistic_Millis) { set_Value (COLUMNNAME_Statistic_Millis, Integer.valueOf(Statistic_Millis)); } /** Get Statistic Milliseconds. @return Internal statistics how many milliseconds a process took */ @Override public int getStatistic_Millis () { Integer ii = (Integer)get_Value(COLUMNNAME_Statistic_Millis); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Stats.java
1
请完成以下Java代码
public void generateDirectMovements() { trxManager.runInThreadInheritedTrx(this::generateDirectMovementsInTrx); } private void generateDirectMovementsInTrx() { trxManager.assertThreadInheritedTrxExists(); markExecuted(); schedules.forEach(this::generateDirectMovement); } private void markExecuted() { if (executed) { throw new AdempiereException("Already executed"); } this.executed = true; } private void generateDirectMovement(final DDOrderMoveSchedule schedule) { // // Make sure DD Order is completed final DDOrderId ddOrderId = schedule.getDdOrderId(); if (!skipCompletingDDOrder) { final I_DD_Order ddOrder = getDDOrderById(ddOrderId); ddOrderService.completeDDOrderIfNeeded(ddOrder); } schedule.assertNotPickedFrom(); schedule.assertNotDroppedTo(); final Quantity qtyToMove = schedule.getQtyToPick(); final HuId huIdToMove = schedule.getPickFromHUId(); final MovementId directMovementId = createDirectMovement(schedule, huIdToMove); schedule.markAsPickedFrom( null, DDOrderMoveSchedulePickedHUs.of( DDOrderMoveSchedulePickedHU.builder() .actualHUIdPicked(huIdToMove) .qtyPicked(qtyToMove) .pickFromMovementId(directMovementId) .inTransitLocatorId(null) .dropToLocatorId(schedule.getDropToLocatorId()) .build()) ); schedule.markAsDroppedTo(schedule.getDropToLocatorId(), directMovementId); ddOrderMoveScheduleService.save(schedule); } private MovementId createDirectMovement( final @NonNull DDOrderMoveSchedule schedule,
final @NonNull HuId huIdToMove) { final HUMovementGeneratorResult result = new HUMovementGenerator(toMovementGenerateRequest(schedule, huIdToMove)) .sharedHUIdsWithPackingMaterialsTransferred(huIdsWithPackingMaterialsTransferred) .createMovement(); return result.getSingleMovementLineId().getMovementId(); } private HUMovementGenerateRequest toMovementGenerateRequest( final @NonNull DDOrderMoveSchedule schedule, final @NonNull HuId huIdToMove) { final I_DD_Order ddOrder = ddOrdersCache.getById(schedule.getDdOrderId()); return DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate) .fromLocatorId(schedule.getPickFromLocatorId()) .toLocatorId(locatorToIdOverride != null ? locatorToIdOverride : schedule.getDropToLocatorId()) .huIdToMove(huIdToMove) .build(); } private I_DD_Order getDDOrderById(final DDOrderId ddOrderId) { return ddOrdersCache.getById(ddOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\generate\DirectMovementsFromSchedulesGenerator.java
1
请完成以下Java代码
public void planContinueProcessWithMigrationContextOperation(ExecutionEntity execution, MigrationContext migrationContext) { planOperation(new ContinueProcessOperation(commandContext, execution, false, false, migrationContext), execution); } @Override public void planContinueProcessInCompensation(ExecutionEntity execution) { planOperation(new ContinueProcessOperation(commandContext, execution, false, true, null), execution); } @Override public void planContinueMultiInstanceOperation(ExecutionEntity execution, ExecutionEntity multiInstanceRootExecution, int loopCounter) { planOperation(new ContinueMultiInstanceOperation(commandContext, execution, multiInstanceRootExecution, loopCounter), execution); } @Override public void planTakeOutgoingSequenceFlowsOperation(ExecutionEntity execution, boolean evaluateConditions) { planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions, false), execution); } @Override public void planTakeOutgoingSequenceFlowsSynchronousOperation(ExecutionEntity execution, boolean evaluateConditions) { planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions, true), execution); } @Override public void planEndExecutionOperation(ExecutionEntity execution) { planOperation(new EndExecutionOperation(commandContext, execution), execution); } @Override public void planEndExecutionOperationSynchronous(ExecutionEntity execution) { planOperation(new EndExecutionOperation(commandContext, execution, true), execution); } @Override public void planTriggerExecutionOperation(ExecutionEntity execution) { planOperation(new TriggerExecutionOperation(commandContext, execution), execution); } @Override public void planAsyncTriggerExecutionOperation(ExecutionEntity execution) {
planOperation(new TriggerExecutionOperation(commandContext, execution, true), execution); } @Override public void planEvaluateConditionalEventsOperation(ExecutionEntity execution) { planOperation(new EvaluateConditionalEventsOperation(commandContext, execution), execution); } @Override public void planEvaluateVariableListenerEventsOperation(String processDefinitionId, String processInstanceId) { planOperation(new EvaluateVariableListenerEventDefinitionsOperation(commandContext, processDefinitionId, processInstanceId)); } @Override public void planDestroyScopeOperation(ExecutionEntity execution) { planOperation(new DestroyScopeOperation(commandContext, execution), execution); } @Override public void planExecuteInactiveBehaviorsOperation(Collection<ExecutionEntity> executions) { planOperation(new ExecuteInactiveBehaviorsOperation(commandContext, executions)); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\agenda\DefaultFlowableEngineAgenda.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return this.id; } /** * {@inheritDoc} */ public String getName() { return this.name; } /** * {@inheritDoc} */ public MessageInstance sendFor( MessageInstance message, Operation operation, ConcurrentMap<QName, URL> overridenEndpointAddresses ) throws Exception { Object[] arguments = this.getArguments(message); Object[] results = this.safeSend(arguments, overridenEndpointAddresses); return this.createResponseMessage(results, operation); } private Object[] getArguments(MessageInstance message) { return message.getStructureInstance().toArray(); } private Object[] safeSend(Object[] arguments, ConcurrentMap<QName, URL> overridenEndpointAddresses) throws Exception { Object[] results = null; results = this.service.getClient().send(this.name, arguments, overridenEndpointAddresses); if (results == null) {
results = new Object[] {}; } return results; } private MessageInstance createResponseMessage(Object[] results, Operation operation) { MessageInstance message = null; MessageDefinition outMessage = operation.getOutMessage(); if (outMessage != null) { message = outMessage.createInstance(); message.getStructureInstance().loadFrom(results); } return message; } public WSService getService() { return this.service; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\webservice\WSOperation.java
2
请在Spring Boot框架中完成以下Java代码
public String getHandlerType() { return this.handlerType; } public Collection<String> getHandlerTypes() { return handlerTypes; } public Date getNow() { return jobServiceConfiguration.getClock().getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public String getScopeType() { return scopeType; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; }
public static long getSerialversionuid() { return serialVersionUID; } public String getId() { return id; } public String getLockOwner() { return lockOwner; } public boolean isOnlyLocked() { return onlyLocked; } public boolean isOnlyUnlocked() { return onlyUnlocked; } public boolean isWithoutScopeType() { return withoutScopeType; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java
2
请完成以下Java代码
public int getListenerIndex() { return listenerIndex; } public void setListenerIndex(int listenerIndex) { this.listenerIndex = listenerIndex; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void invokeListener(DelegateListener listener) throws Exception { listener.notify(this); } public boolean hasFailedOnEndListeners() { return false; } // getters / setters ///////////////////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBusinessKeyWithoutCascade() { return businessKeyWithoutCascade; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; this.businessKeyWithoutCascade = businessKey; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } public boolean isSkipCustomListeners() { return skipCustomListeners; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public boolean isSkipIoMappings() { return skipIoMapping; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMapping = skipIoMappings; } public boolean isSkipSubprocesses() { return skipSubprocesses; } public void setSkipSubprocesseses(boolean skipSubprocesses) { this.skipSubprocesses = skipSubprocesses; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\instance\CoreExecution.java
1
请完成以下Java代码
public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!LogicExpressionResult.class.isAssignableFrom(obj.getClass())) { return false; } final LogicExpressionResult other = (LogicExpressionResult)obj; return Objects.equals(name, other.name) && Objects.equals(value, other.value) && Objects.equals(expression, other.expression) && Objects.equals(usedParameters, other.usedParameters); } /** * @param obj * @return true if the value of this result equals with the value of given result * @see #booleanValue() */ public boolean equalsByValue(final LogicExpressionResult obj) { if (this == obj) { return true; } if (obj == null) { return false; } return value == obj.value; } public boolean equalsByNameAndValue(final LogicExpressionResult obj) { if (this == obj) { return true; } if (obj == null) { return false; } return Objects.equals(name, obj.name) && value == obj.value; } public boolean booleanValue() { return value; } public boolean isTrue() { return value; } public boolean isFalse() { return !value; } public String getName() {
return name; } public ILogicExpression getExpression() { return expression; } /** * @return which parameters were used while evaluating and which was their value */ public Map<CtxName, String> getUsedParameters() { return usedParameters == null ? ImmutableMap.of() : usedParameters; } private static final class Constant extends LogicExpressionResult { private Constant(final boolean value) { super(null, value, value ? ConstantLogicExpression.TRUE : ConstantLogicExpression.FALSE, null); } @Override public String toString() { return value ? "TRUE" : "FALSE"; } } private static final class NamedConstant extends LogicExpressionResult { private transient String _toString = null; // lazy private NamedConstant(final String name, final boolean value) { super(name, value, value ? ConstantLogicExpression.TRUE : ConstantLogicExpression.FALSE, null); } @Override public String toString() { if (_toString == null) { _toString = MoreObjects.toStringHelper(value ? "TRUE" : "FALSE") .omitNullValues() .addValue(name) .toString(); } return _toString; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\LogicExpressionResult.java
1
请完成以下Spring Boot application配置
spring.mvc.view.prefix: /WEB-INF/jsp/ spring.mvc.view.suffix: .jsp logging.level.org.springframework=INFO ################### DataSource Configuration ########################## spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/users_database spring.datasource.username=root spring.datasour
ce.password=root ################### Hibernate Configuration ########################## spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
repos\Spring-Boot-Advanced-Projects-main\springboot2-webapp-jsp\src\main\resources\application.properties
2
请完成以下Java代码
final class ConsoleLoggable implements ILoggable { private static final ConsoleLoggable defaultInstance = new ConsoleLoggable(null); @Nullable private final String prefix; @NonNull private final PrintStream out; private ConsoleLoggable(@Nullable final String prefix) { this.prefix = prefix; this.out = System.out; } public static ConsoleLoggable withPrefix(@Nullable final String prefix) { if (Objects.equals(defaultInstance.prefix, prefix)) { return defaultInstance; } return new ConsoleLoggable(prefix); } @Override
public ILoggable addLog(final String msg, final Object... msgParameter) { if (prefix != null) { out.print(prefix); } out.println(StringUtils.formatMessage(msg, msgParameter)); return this; } @Override public void flush() { out.flush(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\ConsoleLoggable.java
1
请完成以下Java代码
public void assertTUValid(final I_M_ShipmentSchedule_QtyPicked alloc) { final I_M_HU tuHU = alloc.getM_TU_HU(); if (tuHU == null || tuHU.getM_HU_ID() <= 0) { // not set => ok return; } final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); if (!handlingUnitsBL.isTransportUnitOrVirtual(tuHU)) { final HUException ex = new HUException("Transport unit expected." + "\n@M_TU_HU_ID@: " + handlingUnitsBL.getDisplayName(tuHU) + "\n@M_ShipmentSchedule_QtyPicked_ID@: " + alloc + "\n@M_ShipmentSchedule_ID@: " + alloc.getM_ShipmentSchedule()); // logger.warn(ex.getLocalizedMessage(), ex); throw ex; } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_QtyPicked, I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_QtyDeliveredCatch, I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_Catch_UOM_ID }) public void syncInvoiceCandidateQtyPicked(@NonNull final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked) { final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(shipmentScheduleQtyPicked.getM_ShipmentSchedule_ID()); if (shipmentScheduleId == null)
{ return; } final I_M_ShipmentSchedule shipmentSchedule = shipmentSchedulePA.getById(shipmentScheduleId); final OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID()); if (orderLineId == null) { return; } final I_C_OrderLine orderLine = orderDAO.getOrderLineById(orderLineId); invoiceCandidateHandlerBL.invalidateCandidatesFor(orderLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\interceptor\M_ShipmentSchedule_QtyPicked.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> toggleStatus(String id, String action) { if (oConvertUtils.isEmpty(id)) { return Result.error("id不能为空"); } if (oConvertUtils.isEmpty(action)) { return Result.error("action不能为空"); } String normalized = action.toLowerCase(); if (!"enable".equals(normalized) && !"disable".equals(normalized)) { return Result.error("action只能为enable或disable"); } AiragMcp mcp = this.getById(id); if (mcp == null) { return Result.error("未找到对应的MCP服务"); } if (normalized.equalsIgnoreCase(mcp.getStatus())) { return Result.OK("操作成功"); } mcp.setStatus(normalized); this.updateById(mcp); return Result.OK("操作成功"); } /** * 保存插件工具(仅更新tools字段) * for [QQYUN-12453]【AI】支持插件 * @param id 插件ID * @param tools 工具列表JSON字符串 * @return 操作结果 * @author chenrui * @date 2025/10/30 */ @Override public Result<String> saveTools(String id, String tools) { if (oConvertUtils.isEmpty(id)) { return Result.error("插件ID不能为空"); } AiragMcp mcp = this.getById(id); if (mcp == null) { return Result.error("未找到对应的插件"); } // 验证是否为插件类型 String category = mcp.getCategory(); if (oConvertUtils.isEmpty(category)) { category = "mcp"; // 兼容旧数据 } if (!"plugin".equalsIgnoreCase(category)) { return Result.error("只有插件类型才能保存工具"); } // 更新tools字段 mcp.setTools(tools);
// 更新metadata中的tool_count try { com.alibaba.fastjson.JSONArray toolsArray = com.alibaba.fastjson.JSONArray.parseArray(tools); int toolCount = toolsArray != null ? toolsArray.size() : 0; // 解析现有metadata JSONObject metadata = new JSONObject(); if (oConvertUtils.isNotEmpty(mcp.getMetadata())) { try { JSONObject metadataJson = JSONObject.parseObject(mcp.getMetadata()); if (metadataJson != null) { metadata.putAll(metadataJson); } } catch (Exception e) { log.warn("解析metadata失败,将重新创建: {}", mcp.getMetadata()); } } // 更新tool_count metadata.put("tool_count", toolCount); // 保存metadata mcp.setMetadata(metadata.toJSONString()); } catch (Exception e) { log.warn("更新工具数量失败: {}", e.getMessage()); // 即使更新tool_count失败,也不影响保存tools } this.updateById(mcp); return Result.OK("保存成功"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\service\impl\AiragMcpServiceImpl.java
2
请完成以下Java代码
public int getM_HU_Item_Storage_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_Snapshot_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java
1
请在Spring Boot框架中完成以下Java代码
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(themeChangeInterceptor()); } @Bean public ThemeChangeInterceptor themeChangeInterceptor() { ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor(); interceptor.setParamName("theme"); return interceptor; } @Bean public ResourceBundleThemeSource resourceBundleThemeSource() { ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); themeSource.setFallbackToSystemLocale(true);
return themeSource; } @Bean public ThemeResolver themeResolver() { UserPreferenceThemeResolver themeResolver = new UserPreferenceThemeResolver(); themeResolver.setDefaultThemeName("light"); return themeResolver; } @Override public void configureViewResolvers(ViewResolverRegistry resolverRegistry) { resolverRegistry.jsp(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-views\src\main\java\com\baeldung\themes\config\ThemeMVCConfig.java
2
请在Spring Boot框架中完成以下Java代码
public static class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().permitAll().and().csrf().disable(); } } @Profile("secure") @Configuration public static class SecuritySecureConfig extends WebSecurityConfigurerAdapter{ private String adminContextPath; public SecuritySecureConfig( AdminServerProperties adminServerProperties ) {
this.adminContextPath = adminServerProperties.getContextPath(); } @Override protected void configure(HttpSecurity http) throws Exception { SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler(); successHandler.setTargetUrlParameter("redirectTo"); http.authorizeRequests().antMatchers(adminContextPath+"/assets/**").permitAll() .antMatchers(adminContextPath+"/login").permitAll().anyRequest().authenticated().and().formLogin() .loginPage(adminContextPath+"/login").successHandler(successHandler).and().logout() .logoutUrl(adminContextPath+"/logout").and().httpBasic().and().csrf().disable(); } } }
repos\Spring-Boot-In-Action-master\spring_boot_admin2.0_demo\sba_server_2_0\src\main\java\cn\codesheep\sba_server_2_0\SbaServer20Application.java
2
请完成以下Java代码
public void insert() { Context.getCommandContext() .getDbSqlSession() .insert(this); // add link to execution if (executionId != null) { ExecutionEntity execution = Context.getCommandContext() .getExecutionEntityManager() .findExecutionById(executionId); // Inherit tenant if (if applicable) if (execution.getTenantId() != null) { setTenantId(execution.getTenantId()); } } if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_CREATED, this), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_INITIALIZED, this),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } public void delete() { Context.getCommandContext() .getDbSqlSession() .delete(this); // Also delete the job's exception and the custom values byte array exceptionByteArrayRef.delete(); customValuesByteArrayRef.delete(); if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, this), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeadLetterJobEntity.java
1
请完成以下Java代码
public boolean supports(Class<?> clazz) { return User.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { User user = (User) target; if (StringUtils.isEmpty(user.getName())) { errors.rejectValue("name", "name.required"); } if (StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("email", "email.required"); } // Add more validation rules as needed } public void validate(Object target, Errors errors, Object... validationHints) { User user = (User) target; if (validationHints.length > 0) { if (validationHints[0] == "create") { if (StringUtils.isEmpty(user.getName())) { errors.rejectValue("name", "name.required","Name cannot be empty"); }
if (StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("email", "email.required" , "Invalid email format"); } if (user.getAge() < 18 || user.getAge() > 65) { errors.rejectValue("age", "user.age.outOfRange", new Object[]{18, 65}, "Age must be between 18 and 65"); } } else if (validationHints[0] == "update") { // Perform update-specific validation if (StringUtils.isEmpty(user.getName()) && StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("name", "name.or.email.required", "Name or email cannot be empty"); } } } else { // Perform default validation if (StringUtils.isEmpty(user.getName())) { errors.rejectValue("name", "name.required"); } if (StringUtils.isEmpty(user.getEmail())) { errors.rejectValue("email", "email.required"); } } } }
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\springvalidator\UserValidator.java
1
请完成以下Java代码
public void deleteCandidateGroups(CandidateGroupsPayload candidateGroupsPayload) { if ( candidateGroupsPayload.getCandidateGroups() != null && !candidateGroupsPayload.getCandidateGroups().isEmpty() ) { for (String g : candidateGroupsPayload.getCandidateGroups()) { taskService.deleteCandidateGroup(candidateGroupsPayload.getTaskId(), g); } } } @Override public List<String> userCandidates(String taskId) { List<IdentityLink> identityLinks = getIdentityLinks(taskId); List<String> userCandidates = new ArrayList<>(); if (identityLinks != null) { for (IdentityLink i : identityLinks) { if (i.getUserId() != null) { if (i.getType().equals(IdentityLinkType.CANDIDATE)) { userCandidates.add(i.getUserId()); } } } } return userCandidates; }
@Override public List<String> groupCandidates(String taskId) { List<IdentityLink> identityLinks = getIdentityLinks(taskId); List<String> groupCandidates = new ArrayList<>(); if (identityLinks != null) { for (IdentityLink i : identityLinks) { if (i.getGroupId() != null) { if (i.getType().equals(IdentityLinkType.CANDIDATE)) { groupCandidates.add(i.getGroupId()); } } } } return groupCandidates; } private List<IdentityLink> getIdentityLinks(String taskId) { return taskService.getIdentityLinksForTask(taskId); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskAdminRuntimeImpl.java
1
请完成以下Spring Boot application配置
################### App Version ########################## app.version=de4db33lzbl spring.profiles.active=dev ################### Resource Handler Configuration #############
############# resource.handler.conf=4.1.0 ###resource.handler.conf=4.0.7###
repos\tutorials-master\spring-web-modules\spring-static-resources\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public PlatformTransactionManager securityTransactionManager() { EntityManagerFactory factory = securityEntityManagerFactory().getObject(); return new JpaTransactionManager(factory); } @Bean public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(securityDataSource()); factory.setPackagesToScan(new String[]{"net.alanbinu.springboot.springbootmultipledatasources.security.entities"}); factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); Properties jpaProperties = new Properties(); jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto")); jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql")); factory.setJpaProperties(jpaProperties);
return factory; } @Bean public DataSourceInitializer securityDataSourceInitializer() { DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(securityDataSource()); ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); databasePopulator.addScript(new ClassPathResource("security-data.sql")); dataSourceInitializer.setDatabasePopulator(databasePopulator); dataSourceInitializer.setEnabled(env.getProperty("datasource.security.initialize", Boolean.class, false)); return dataSourceInitializer; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\java\net\alanbinu\springboot\springbootmultipledatasources\config\SecurityDataSourceConfig.java
2
请完成以下Java代码
public class FindOperation { private static MongoClient mongoClient; private static MongoDatabase database; private static MongoCollection<Document> collection; private static String collectionName; private static String databaseName; public static void setUp() { if (mongoClient == null) { mongoClient = new MongoClient("localhost", 27017); databaseName = "baeldung"; collectionName = "employee"; database = mongoClient.getDatabase(databaseName); collection = database.getCollection(collectionName); } } public static void retrieveAllDocumentsUsingFind() { FindIterable<Document> documents = collection.find(); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void retrieveAllDocumentsUsingFindWithQueryFilter() { Bson filter = eq("department", "Engineering"); FindIterable<Document> documents = collection.find(filter); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next());
} } public static void retrieveAllDocumentsUsingFindWithQueryFilterAndProjection() { Bson filter = eq("department", "Engineering"); Bson projection = fields(include("name", "age")); FindIterable<Document> documents = collection.find(filter) .projection(projection); MongoCursor<Document> cursor = documents.iterator(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } public static void retrieveFirstDocument() { FindIterable<Document> documents = collection.find(); Document document = documents.first(); System.out.println(document); } public static void main(String args[]) { setUp(); retrieveAllDocumentsUsingFind(); retrieveAllDocumentsUsingFindWithQueryFilter(); retrieveAllDocumentsUsingFindWithQueryFilterAndProjection(); retrieveFirstDocument(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\find\FindOperation.java
1
请完成以下Java代码
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }; } /** * init consumer bean * * @param interfaceClazz interfaceClazz * @param reference reference * @return ReferenceBean<T> * @throws BeansException BeansException */ private <T> ReferenceBean<T> getConsumerBean(String beanName, Field field, Reference reference) throws BeansException { ReferenceBean<T> referenceBean = new ReferenceBean<T>(reference); if ((reference.interfaceClass() == null || reference.interfaceClass() == void.class) && (reference.interfaceName() == null || "".equals(reference.interfaceName()))) { referenceBean.setInterface(field.getType()); } Environment environment = this.applicationContext.getEnvironment(); String application = reference.application(); referenceBean.setApplication(this.parseApplication(application, this.properties, environment, beanName, field.getName(), "application", application)); String module = reference.module(); referenceBean.setModule(this.parseModule(module, this.properties, environment, beanName, field.getName(), "module", module)); String[] registries = reference.registry(); referenceBean.setRegistries(this.parseRegistries(registries, this.properties, environment, beanName, field.getName(), "registry")); String monitor = reference.monitor(); referenceBean.setMonitor(this.parseMonitor(monitor, this.properties, environment, beanName, field.getName(), "monitor", monitor));
String consumer = reference.consumer(); referenceBean.setConsumer(this.parseConsumer(consumer, this.properties, environment, beanName, field.getName(), "consumer", consumer)); referenceBean.setApplicationContext(DubboConsumerAutoConfiguration.this.applicationContext); return referenceBean; } @Override protected String buildErrorMsg(String... errors) { if (errors == null || errors.length != 4) { return super.buildErrorMsg(errors); } return new StringBuilder().append("beanName=").append(errors[0]).append(", field=") .append(errors[1]).append(", ").append(errors[2]).append("=").append(errors[3]) .append(" not found in multi configs").toString(); } }
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\DubboConsumerAutoConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemWooCommerceHouseKeepingTask implements IStartupHouseKeepingTask { private static final Logger logger = LogManager.getLogger(ExternalSystemWooCommerceHouseKeepingTask.class); private final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); private final ExternalSystemConfigRepo externalSystemConfigDAO; public ExternalSystemWooCommerceHouseKeepingTask(@NonNull final ExternalSystemConfigRepo externalSystemConfigDAO) { this.externalSystemConfigDAO = externalSystemConfigDAO; } @Override public void executeTask() { final AdProcessId processId = adProcessDAO.retrieveProcessIdByClassIfUnique(ExternalSystemProcesses.getExternalSystemProcessClassName(ExternalSystemType.WOO)); if (processId == null) { Loggables.withLogger(logger, Level.DEBUG).addLog("Nothing to do!"); return; }
final ImmutableList<ExternalSystemParentConfig> parentConfigList = externalSystemConfigDAO.getActiveByType(ExternalSystemType.WOO); parentConfigList .stream() .peek(config -> Loggables.withLogger(logger, Level.DEBUG).addLog("Firing process " + processId + " for WooCommerce config " + config.getChildConfig().getId())) .forEach((config -> ProcessInfo.builder() .setAD_Process_ID(processId) .setAD_User_ID(UserId.METASFRESH.getRepoId()) .addParameter(PARAM_EXTERNAL_REQUEST, WooCommerceCommand.EnableRestAPI.getValue()) .addParameter(PARAM_CHILD_CONFIG_ID, config.getChildConfig().getId().getRepoId()) .buildAndPrepareExecution() .executeSync())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\woocommerce\housekeeping\ExternalSystemWooCommerceHouseKeepingTask.java
2
请完成以下Java代码
public void rotateLogFile() { if (metasfreshRollingPolicy != null) { final TimeBasedFileNamingAndTriggeringPolicy<?> triggeringPolicy = metasfreshRollingPolicy.getTimeBasedFileNamingAndTriggeringPolicy(); if (triggeringPolicy instanceof MetasfreshTimeBasedFileNamingAndTriggeringPolicy) { final MetasfreshTimeBasedFileNamingAndTriggeringPolicy<?> metasfreshTriggeringPolicy = (MetasfreshTimeBasedFileNamingAndTriggeringPolicy<?>)triggeringPolicy; metasfreshTriggeringPolicy.setForceRollover(); } } if (rollingFileAppender != null) { rollingFileAppender.rollover(); } } public void setDisabled(final boolean disabled)
{ if (rollingFileAppender instanceof MetasfreshFileAppender) { ((MetasfreshFileAppender<?>)rollingFileAppender).setDisabled(disabled); } } public boolean isDisabled() { if (rollingFileAppender instanceof MetasfreshFileAppender) { return ((MetasfreshFileAppender<?>)rollingFileAppender).isDisabled(); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\logging\MetasfreshFileLoggerHelper.java
1
请完成以下Java代码
public static void main(String[] args) throws Exception { SslContext sslCtx = Http2Util.createSSLContext(true); EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(group) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { if (sslCtx != null) { ch.pipeline() .addLast(sslCtx.newHandler(ch.alloc()), Http2Util.getServerAPNHandler()); } } });
Channel ch = b.bind(PORT) .sync() .channel(); logger.info("HTTP/2 Server is listening on https://127.0.0.1:" + PORT + '/'); ch.closeFuture() .sync(); } finally { group.shutdownGracefully(); } } }
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\netty\http2\server\Http2Server.java
1
请完成以下Java代码
public Quantity deserialize(final JsonParser p, final DeserializationContext ctx) throws IOException { final JsonNode node = p.getCodec().readTree(p); final String qtyStr = node.get("qty").asText(); final int uomRepoId = (Integer)node.get("uomId").numberValue(); final String sourceQtyStr; final int sourceUomRepoId; if (node.has("sourceQty")) { sourceQtyStr = node.get("sourceQty").asText(); sourceUomRepoId = (Integer)node.get("sourceUomId").numberValue(); } else { sourceQtyStr = qtyStr; sourceUomRepoId = uomRepoId; } return Quantitys.of( new BigDecimal(qtyStr), UomId.ofRepoId(uomRepoId), new BigDecimal(sourceQtyStr), UomId.ofRepoId(sourceUomRepoId)); } } public static class QuantitySerializer extends StdSerializer<Quantity> { private static final long serialVersionUID = -8292209848527230256L; public QuantitySerializer() { super(Quantity.class); } @Override public void serialize(final Quantity value, final JsonGenerator gen, final SerializerProvider provider) throws IOException {
gen.writeStartObject(); final String qtyStr = value.toBigDecimal().toString(); final int uomId = value.getUomId().getRepoId(); gen.writeFieldName("qty"); gen.writeString(qtyStr); gen.writeFieldName("uomId"); gen.writeNumber(uomId); final String sourceQtyStr = value.getSourceQty().toString(); final int sourceUomId = value.getSourceUomId().getRepoId(); if (!qtyStr.equals(sourceQtyStr) || uomId != sourceUomId) { gen.writeFieldName("sourceQty"); gen.writeString(sourceQtyStr); gen.writeFieldName("sourceUomId"); gen.writeNumber(sourceUomId); } gen.writeEndObject(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantitys.java
1
请完成以下Java代码
protected int getNumberOfActiveChildExecutionsForExecution( ExecutionEntityManager executionEntityManager, String executionId ) { List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(executionId); int activeExecutions = 0; // Filter out the boundary events for (ExecutionEntity activeExecution : executions) { if (!(activeExecution.getCurrentFlowElement() instanceof BoundaryEvent)) { activeExecutions++; } } return activeExecutions; } protected List<ExecutionEntity> getActiveChildExecutionsForExecution( ExecutionEntityManager executionEntityManager, String executionId ) { List<ExecutionEntity> activeChildExecutions = new ArrayList<ExecutionEntity>(); List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(executionId); for (ExecutionEntity activeExecution : executions) { if (!(activeExecution.getCurrentFlowElement() instanceof BoundaryEvent)) { activeChildExecutions.add(activeExecution); } } return activeChildExecutions; } protected boolean isAllEventScopeExecutions( ExecutionEntityManager executionEntityManager, ExecutionEntity parentExecution ) { boolean allEventScopeExecutions = true; List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId( parentExecution.getId() ); for (ExecutionEntity childExecution : executions) { if (childExecution.isEventScope() && childExecution.getExecutions().size() == 0) { executionEntityManager.deleteExecutionAndRelatedData(childExecution, null); } else { allEventScopeExecutions = false; break; }
} return allEventScopeExecutions; } protected boolean allChildExecutionsEnded( ExecutionEntity parentExecutionEntity, ExecutionEntity executionEntityToIgnore ) { for (ExecutionEntity childExecutionEntity : parentExecutionEntity.getExecutions()) { if ( executionEntityToIgnore == null || !executionEntityToIgnore.getId().equals(childExecutionEntity.getId()) ) { if (!childExecutionEntity.isEnded()) { return false; } if (childExecutionEntity.getExecutions() != null && childExecutionEntity.getExecutions().size() > 0) { if (!allChildExecutionsEnded(childExecutionEntity, executionEntityToIgnore)) { return false; } } } } return true; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\EndExecutionOperation.java
1
请完成以下Java代码
public void linkOnSameReferenceNo(final Object fromModel, final Object toModel) { if (fromModel == null) { logger.debug("fromModel is null. Skip."); return; } if (toModel == null) { logger.debug("toModel is null. Skip."); return; } // We use ctx and trxName from "toModel", because that one was produced now final Properties ctx = InterfaceWrapperHelper.getCtx(toModel); final String trxName = InterfaceWrapperHelper.getTrxName(toModel); final String fromTableName = InterfaceWrapperHelper.getModelTableName(fromModel); final int fromRecordId = InterfaceWrapperHelper.getId(fromModel); if (fromRecordId <= 0) { logger.warn("fromModel {} was not saved yet or does not support simple primary key. Skip.", fromModel); return; } final int toRecordId = InterfaceWrapperHelper.getId(toModel); if (toRecordId <= 0) { logger.warn("toModel {} was not saved yet or does not support simple primary key. Skip.", toModel); return; }
final IReferenceNoDAO dao = Services.get(IReferenceNoDAO.class); final List<I_C_ReferenceNo_Doc> fromAssignments = dao.retrieveAllDocAssignments(ctx, -1, // referenceNoTypeId - return all assignments MTable.getTable_ID(fromTableName), // tableId fromRecordId, trxName); for (final I_C_ReferenceNo_Doc fromAssignment : fromAssignments) { final I_C_ReferenceNo referenceNo = fromAssignment.getC_ReferenceNo(); dao.getCreateReferenceNoDoc(referenceNo, TableRecordReference.of(toModel)); logger.info("Linked {} to {}", new Object[] { toModel, referenceNo }); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\ReferenceNoBL.java
1
请完成以下Java代码
public Forwarded put(String key, String value) { this.values.put(key, quoteIfNeeded(value)); return this; } private String quoteIfNeeded(String s) { if (s != null && s.contains(":")) { // TODO: broaded quote return "\"" + s + "\""; } return s; } public @Nullable String get(String key) { return this.values.get(key); } /* for testing */ Map<String, String> getValues() { return this.values; } @Override
public String toString() { return "Forwarded{" + "values=" + this.values + '}'; } public String toHeaderValue() { StringBuilder builder = new StringBuilder(); for (Map.Entry<String, String> entry : this.values.entrySet()) { if (!builder.isEmpty()) { builder.append(SEMICOLON); } builder.append(entry.getKey()).append(EQUALS).append(entry.getValue()); } return builder.toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\ForwardedHeadersFilter.java
1
请完成以下Java代码
public void enable() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new EnablePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables)); } @Override public void disable() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new DisablePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables)); } @Override public void start() { commandExecutor.execute(new StartPlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables, childTaskVariables, childTaskFormVariables, childTaskFormOutcome, childTaskFormInfo)); } @Override public void terminate() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new TerminatePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables)); } @Override public void completeStage() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new CompleteStagePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables, false)); }
@Override public void forceCompleteStage() { validateChildTaskVariablesNotSet(); commandExecutor.execute(new CompleteStagePlanItemInstanceCmd(planItemInstanceId, variables, formVariables, formOutcome, formInfo, localVariables, transientVariables, true)); } protected void validateChildTaskVariablesNotSet() { if (childTaskVariables != null) { throw new FlowableIllegalArgumentException("Child task variables can only be set when starting a plan item instance"); } if (childTaskFormInfo != null) { throw new FlowableIllegalArgumentException("Child form variables can only be set when starting a plan item instance"); } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\PlanItemInstanceTransitionBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class SpringSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin") .password(passwordEncoder().encode("admin123")) .roles("ADMIN").authorities("ACCESS_TEST1", "ACCESS_TEST2") .and() .withUser("hamdamboy") .password(passwordEncoder().encode("hamdamboy123")) .roles("USER") .and() .withUser("manager") .password(passwordEncoder().encode("manager")) .roles("MANAGER") .authorities("ACCESS_TEST1"); } /** * * **/ @Override protected void configure(HttpSecurity http) throws Exception {
http .authorizeRequests() // .anyRequest().permitAll() if you fix all permission values, then remove all conditions. .antMatchers("/index.html").permitAll() .antMatchers("/profile/**").authenticated() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER") .antMatchers("/api/public/test1").hasAuthority("ACCESS_TEST1") .antMatchers("/api/public/test2").hasAuthority("ACCESS_TEST2") .and() .httpBasic(); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\4. SpringSecureAuthorization\src\main\java\spring\security\security\SpringSecurity.java
2
请完成以下Java代码
public void run() { logger.info("destination:{} running", destination); process(); } }); thread.setUncaughtExceptionHandler(handler); thread.start(); running = true; } public void stop() { if (!running) { return; } running = false; } private void process() { int batchSize = 4 * 1024; while (running) { try { MDC.put("destination", destination); connector.connect(); connector.subscribe(); while (running) { Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据 long batchId = message.getId(); int size = message.getEntries().size(); if (batchId != -1 && size > 0) { logger.info(canal_get, batchId, size); // for (CanalEntry.Entry entry : message.getEntries()) { // logger.info("parse event has an data:" + entry.toString()); // } MessageHandler messageHandler = SpringUtil.getBean("messageHandler", MessageHandler.class);
messageHandler.execute(message.getEntries()); logger.info(canal_ack, batchId); } connector.ack(batchId); // 提交确认 } } catch (Exception e) { logger.error("process error!", e); } finally { connector.disconnect(); MDC.remove("destination"); } } } }
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\canal\CanalClient.java
1
请在Spring Boot框架中完成以下Java代码
public class UserDao { // ------------------------ // PUBLIC METHODS // ------------------------ /** * Save the user in the database. */ public void create(User user) { entityManager.persist(user); return; } /** * Delete the user from the database. */ public void delete(User user) { if (entityManager.contains(user)) entityManager.remove(user); else entityManager.remove(entityManager.merge(user)); return; } /** * Return all the users stored in the database. */ @SuppressWarnings("unchecked") public List<User> getAll() { return entityManager.createQuery("from User").getResultList(); } /** * Return the user having the passed email. */ public User getByEmail(String email) { return (User) entityManager.createQuery( "from User where email = :email")
.setParameter("email", email) .getSingleResult(); } /** * Return the user having the passed id. */ public User getById(long id) { return entityManager.find(User.class, id); } /** * Update the passed user in the database. */ public void update(User user) { entityManager.merge(user); return; } // ------------------------ // PRIVATE FIELDS // ------------------------ // An EntityManager will be automatically injected from entityManagerFactory // setup on DatabaseConfig class. @PersistenceContext private EntityManager entityManager; } // class UserDao
repos\spring-boot-samples-master\spring-boot-mysql-jpa-hibernate\src\main\java\netgloo\models\UserDao.java
2
请完成以下Java代码
public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); } /** Set Registered EMail. @param UserName Email of the responsible for the System */
@Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java-gen\de\metas\marketing\cleverreach\model\X_MKTG_CleverReach_Config.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); result = prime * result + ((tenant == null) ? 0 : tenant.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProcessDefinitionGroup other = (ProcessDefinitionGroup) obj; if (key == null) {
if (other.key != null) return false; } else if (!key.equals(other.key)) return false; if (tenant == null) { if (other.tenant != null) return false; } else if (!tenant.equals(other.tenant)) return false; return true; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteProcessDefinitionsByIdsCmd.java
1
请完成以下Java代码
public void setAddressName(String addressName) { this.addressName = addressName; } public Integer getSendStatus() { return sendStatus; } public void setSendStatus(Integer sendStatus) { this.sendStatus = sendStatus; } public Integer getReceiveStatus() { return receiveStatus; } public void setReceiveStatus(Integer receiveStatus) { this.receiveStatus = receiveStatus; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; }
public void setCity(String city) { this.city = city; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getDetailAddress() { return detailAddress; } public void setDetailAddress(String detailAddress) { this.detailAddress = detailAddress; } @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(", addressName=").append(addressName); sb.append(", sendStatus=").append(sendStatus); sb.append(", receiveStatus=").append(receiveStatus); sb.append(", name=").append(name); sb.append(", phone=").append(phone); sb.append(", province=").append(province); sb.append(", city=").append(city); sb.append(", region=").append(region); sb.append(", detailAddress=").append(detailAddress); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCompanyAddress.java
1
请完成以下Java代码
public ILogicExpression getLeft() { return left; } /** * @return right expression; never null */ public ILogicExpression getRight() { return right; } /** * @return logic operator; never null */ public String getOperator() { return operator; } @Override public String toString() { return getExpressionString(); } @Override public ILogicExpression evaluatePartial(final Evaluatee ctx) { if (isConstant()) {
return this; } final ILogicExpression leftExpression = getLeft(); final ILogicExpression newLeftExpression = leftExpression.evaluatePartial(ctx); final ILogicExpression rightExpression = getRight(); final ILogicExpression newRightExpression = rightExpression.evaluatePartial(ctx); final String logicOperator = getOperator(); if (newLeftExpression.isConstant() && newRightExpression.isConstant()) { final BooleanEvaluator logicExprEvaluator = LogicExpressionEvaluator.getBooleanEvaluatorByOperator(logicOperator); final boolean result = logicExprEvaluator.evaluateOrNull(newLeftExpression::constantValue, newRightExpression::constantValue); return ConstantLogicExpression.of(result); } else if (Objects.equals(leftExpression, newLeftExpression) && Objects.equals(rightExpression, newRightExpression)) { return this; } else { return LogicExpression.of(newLeftExpression, logicOperator, newRightExpression); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpression.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Ssl getSsl() { return this.ssl; } public void setSsl(@Nullable Ssl ssl) { this.ssl = ssl; } public Spec getSpec() { return this.spec; } public static class Spec { /** * Sub-protocols to use in websocket handshake signature. */ private @Nullable String protocols; /** * Maximum allowable frame payload length. */ private DataSize maxFramePayloadLength = DataSize.ofBytes(65536); /** * Whether to proxy websocket ping frames or respond to them. */ private boolean handlePing; /** * Whether the websocket compression extension is enabled. */ private boolean compress; public @Nullable String getProtocols() { return this.protocols; } public void setProtocols(@Nullable String protocols) { this.protocols = protocols; }
public DataSize getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(DataSize maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isHandlePing() { return this.handlePing; } public void setHandlePing(boolean handlePing) { this.handlePing = handlePing; } public boolean isCompress() { return this.compress; } public void setCompress(boolean compress) { this.compress = compress; } } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void contextCreated(ELContextEvent evt) { evt.getELContext() .getImportHandler() .importClass("com.baeldung.springintegration.controllers.ELSampleBean"); } }); } public void save() { } public static String constantField() { return constantField; } public void saveFirstName(String firstName) { this.firstName = firstName; } public Long multiplyValue(LambdaExpression expr) { Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance() .getELContext(), pageCounter); return theResult; } public void saveByELEvaluation() { firstName = (String) evaluateEL("#{firstName.value}", String.class); FacesContext ctx = FacesContext.getCurrentInstance(); FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName); theMessage.setSeverity(FacesMessage.SEVERITY_INFO); ctx.addMessage(null, theMessage); } private Object evaluateEL(String elExpression, Class<?> clazz) { Object toReturn = null; FacesContext ctx = FacesContext.getCurrentInstance(); Application app = ctx.getApplication(); toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz); return toReturn; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) {
this.lastName = lastName; } /** * @return the pageDescription */ public String getPageDescription() { return pageDescription; } /** * @param pageDescription the pageDescription to set */ public void setPageDescription(String pageDescription) { this.pageDescription = pageDescription; } /** * @return the pageCounter */ public int getPageCounter() { return pageCounter; } /** * @param pageCounter the pageCounter to set */ public void setPageCounter(int pageCounter) { this.pageCounter = pageCounter; } }
repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\ELSampleBean.java
2
请完成以下Java代码
public ClientGraphQlResponse executeSync() { return initRequestSpec().executeSync(); } /** * Create {@link GraphQLQueryRequest}, serialize it to a String document * to send, and delegate to the wrapped {@code GraphQlClient}. * <p>See Javadoc of delegate method * {@link GraphQlClient.RequestSpec#execute()} for details. */ public Mono<ClientGraphQlResponse> execute() { return initRequestSpec().execute(); } /** * Create {@link GraphQLQueryRequest}, serialize it to a String document * to send, and delegate to the wrapped {@code GraphQlClient}. * <p>See Javadoc of delegate method * {@link GraphQlClient.RequestSpec#executeSubscription()} for details. */ public Flux<ClientGraphQlResponse> executeSubscription() { return initRequestSpec().executeSubscription(); } private GraphQLQueryRequest createRequest() { Assert.state(this.projectionNode != null || this.coercingMap == null, "Coercing map provided without projection"); GraphQLQueryRequest request; if (this.coercingMap != null && this.projectionNode != null) { request = new GraphQLQueryRequest(this.query, this.projectionNode, this.coercingMap); } else if (this.projectionNode != null) { request = new GraphQLQueryRequest(this.query, this.projectionNode); } else { request = new GraphQLQueryRequest(this.query); } return request; } @SuppressWarnings("NullAway") private GraphQlClient.RequestSpec initRequestSpec() { String document; String operationName; if (!this.additionalRequests.isEmpty()) { this.additionalRequests.add(createRequest());
document = new GraphQLMultiQueryRequest(this.additionalRequests).serialize(); operationName = null; } else { document = createRequest().serialize(); operationName = (this.query.getName() != null) ? this.query.getName() : null; } return DgsGraphQlClient.this.graphQlClient.document(document) .operationName(operationName) .attributes((map) -> { if (this.attributes != null) { map.putAll(this.attributes); } }); } private String getDefaultPath() { return this.query.getOperationName(); } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DgsGraphQlClient.java
1
请完成以下Java代码
public HashableString hash() { final String salt = UIDStringUtil.createRandomUUID(); return hashWithSalt(salt); } public HashableString hashWithSalt(@Nullable final String salt) { if (hashed) { return this; } HashableString hashedObject = _hashedObject; if (hashedObject == null) { final String valueHashed = hashValue(value, salt); hashedObject = _hashedObject = new HashableString(valueHashed, true, salt); } return hashedObject; } private static String hashValue(final String valuePlain, @Nullable final String salt) { // IMPORTANT: please keep it in sync with "hash_column_value" database function final String valuePlainNorm = valuePlain != null ? valuePlain : ""; final String valueWithSalt; if (salt != null && !salt.isEmpty()) { valueWithSalt = valuePlainNorm + salt; } else { valueWithSalt = valuePlainNorm; } final HashCode valueHashed = Hashing.sha512().hashString(valueWithSalt, StandardCharsets.UTF_8); final String valueHashedAndEncoded = valueHashed.toString(); // hex encoding return PREFIX_SHA512 + valueHashedAndEncoded + SEPARATOR + salt; }
public boolean isMatching(@Nullable final HashableString other) { if (this == other) { return true; } if (other == null) { return false; } if (isPlain()) { if (other.isPlain()) { return valueEquals(other.value); } else { return hashWithSalt(other.salt).valueEquals(other.value); } } else { if (other.isPlain()) { return other.hashWithSalt(salt).valueEquals(value); } else { return valueEquals(other.value); } } } private boolean valueEquals(final String otherValue) { return Objects.equals(this.value, otherValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\hash\HashableString.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 String[] getRoles() { return roles; }
public void setRoles(String[] roles) { this.roles = roles; } public Integer[] getLocations() { return locations; } public void setLocations(Integer[] locations) { this.locations = locations; } public String[] getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(String[] phoneNumbers) { this.phoneNumbers = phoneNumbers; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\User.java
1
请完成以下Java代码
public void firePdfUpdate( @NonNull final I_AD_Archive archive, @Nullable final UserId userId) { for (final IArchiveEventListener listener : listeners) { listener.onPdfUpdate(archive, userId); } } @Override public void firePdfUpdate( @NonNull final I_AD_Archive archive, @Nullable final UserId userId, String action) { for (final IArchiveEventListener listener : listeners) { listener.onPdfUpdate(archive, userId, action); } } @Override public void fireEmailSent( final I_AD_Archive archive, final UserEMailConfig user, final EMailAddress emailFrom, final EMailAddress emailTo, final EMailAddress emailCc, final EMailAddress emailBcc, final ArchiveEmailSentStatus status) { for (final IArchiveEventListener listener : listeners) { listener.onEmailSent(archive, user, emailFrom, emailTo, emailCc, emailBcc, status); } } @Override public void firePrintOut( final I_AD_Archive archive, @Nullable final UserId userId, final String printerName,
final int copies, @NonNull final ArchivePrintOutStatus status) { for (final IArchiveEventListener listener : listeners) { listener.onPrintOut(archive, userId, printerName, copies, status); } } @Override public void firePrintOut( final I_AD_Archive archive, @Nullable final UserId userId, @NonNull final Set<String> printerNames, final int copies, @NonNull final ArchivePrintOutStatus status) { for (final String printerName : printerNames) { for (final IArchiveEventListener listener : listeners) { listener.onPrintOut(archive, userId, printerName, copies, status); } } } @Override public void fireVoidDocument(final I_AD_Archive archive) { for (final IArchiveEventListener listener : listeners) { listener.onVoidDocument(archive); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\archive\api\impl\ArchiveEventManager.java
1
请完成以下Spring Boot application配置
spring: application: name: dubbo-externalized-configuration-consumer-sample management: endpoints: web: exposure: include: '*' endpoint: dubbo: enabled: true dubboshutdown: enabled: true dubboconfigs: enabled: true dubboservices: enabled: true dubboreferences: enabled: true dubboproperties: enabled: true security: ## Deprecated 2.x enabled: false ## For Spring Boot 1.x demo endpoints: dubbo: enabled: true sensitive: false dubboshutd
own: enabled: true dubboconfigs: enabled: true dubboservices: enabled: true dubboreferences: enabled: true dubboproperties: enabled: true demo: service: version: 1.0.0 url: dubbo://localhost:12345
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-samples\externalized-configuration-samples\consumer-sample\src\main\resources\application.yml
2
请完成以下Java代码
public org.compiere.model.I_AD_Ref_List getAD_Ref_List() { return get_ValueAsPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class); } @Override public void setAD_Ref_List(final org.compiere.model.I_AD_Ref_List AD_Ref_List) { set_ValueFromPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class, AD_Ref_List); } @Override public void setAD_Ref_List_ID (final int AD_Ref_List_ID) { if (AD_Ref_List_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID); } @Override public int getAD_Ref_List_ID() { return get_ValueAsInt(COLUMNNAME_AD_Ref_List_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsTranslated (final boolean IsTranslated) { set_Value (COLUMNNAME_IsTranslated, IsTranslated);
} @Override public boolean isTranslated() { return get_ValueAsBoolean(COLUMNNAME_IsTranslated); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List_Trl.java
1
请在Spring Boot框架中完成以下Java代码
public Queue fanoutQueueB() { return QueueBuilder.durable("FANOUT_QUEUE_B").build(); } /** * 绑定队列A 到Fanout 交换机. * * @param queue the queue * @param fanoutExchange the fanout exchange * @return the binding */ @Bean public Binding bindingA(@Qualifier("fanoutQueueA") Queue queue, @Qualifier("fanoutExchange") FanoutExchange fanoutExchange) { return BindingBuilder.bind(queue).to(fanoutExchange);
} /** * 绑定队列B 到Fanout 交换机. * * @param queue the queue * @param fanoutExchange the fanout exchange * @return the binding */ @Bean public Binding bindingB(@Qualifier("fanoutQueueB") Queue queue, @Qualifier("fanoutExchange") FanoutExchange fanoutExchange) { return BindingBuilder.bind(queue).to(fanoutExchange); } }
repos\SpringBootBucket-master\springboot-rabbitmq\src\main\java\com\xncoding\pos\config\RabbitConfig.java
2
请完成以下Java代码
protected boolean afterDelete (boolean success) { if (!success) return success; // StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_IDOld ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString (), get_TrxName ()); // If 0 than there is nothing to delete which is okay. if (no > 0) log.debug("#" + no + " - TreeType=CMC"); else log.warn("#" + no + " - TreeType=CMC"); return true; } // afterDelete /** * reIndex * @param newRecord */ public void reIndex(boolean newRecord)
{ String [] toBeIndexed = new String[8]; toBeIndexed[0] = this.getName(); toBeIndexed[1] = this.getDescription(); toBeIndexed[2] = this.getRelativeURL(); toBeIndexed[3] = this.getMeta_Author(); toBeIndexed[4] = this.getMeta_Copyright(); toBeIndexed[5] = this.getMeta_Description(); toBeIndexed[6] = this.getMeta_Keywords(); toBeIndexed[7] = this.getMeta_Publisher(); MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), getCM_WebProject_ID(), this.getUpdated()); MContainerElement[] theseElements = getAllElements(); if (theseElements!=null) for (int i=0;i<theseElements.length;i++) theseElements[i].reIndex (false); } // reIndex } // MContainer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContainer.java
1
请完成以下Java代码
public org.compiere.model.I_M_PriceList getUVP_Price_List() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_UVP_Price_List_ID, org.compiere.model.I_M_PriceList.class); } @Override public void setUVP_Price_List(org.compiere.model.I_M_PriceList UVP_Price_List) { set_ValueFromPO(COLUMNNAME_UVP_Price_List_ID, org.compiere.model.I_M_PriceList.class, UVP_Price_List); } /** Set Price List UVP. @param UVP_Price_List_ID Price List UVP */ @Override public void setUVP_Price_List_ID (int UVP_Price_List_ID) { if (UVP_Price_List_ID < 1) set_Value (COLUMNNAME_UVP_Price_List_ID, null); else set_Value (COLUMNNAME_UVP_Price_List_ID, Integer.valueOf(UVP_Price_List_ID)); } /** Get Price List UVP. @return Price List UVP */ @Override public int getUVP_Price_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_UVP_Price_List_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_PriceList getZBV_Price_List() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class);
} @Override public void setZBV_Price_List(org.compiere.model.I_M_PriceList ZBV_Price_List) { set_ValueFromPO(COLUMNNAME_ZBV_Price_List_ID, org.compiere.model.I_M_PriceList.class, ZBV_Price_List); } /** Set Price List ZBV. @param ZBV_Price_List_ID Price List ZBV */ @Override public void setZBV_Price_List_ID (int ZBV_Price_List_ID) { if (ZBV_Price_List_ID < 1) set_Value (COLUMNNAME_ZBV_Price_List_ID, null); else set_Value (COLUMNNAME_ZBV_Price_List_ID, Integer.valueOf(ZBV_Price_List_ID)); } /** Get Price List ZBV. @return Price List ZBV */ @Override public int getZBV_Price_List_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ZBV_Price_List_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_I_Pharma_Product.java
1
请完成以下Java代码
public boolean isAutoCommit() { return true; } // metas @Override public void addMouseListener(final MouseListener l) { m_text.addMouseListener(l); } @Override public void addKeyListener(final KeyListener l) { m_text.addKeyListener(l); } public int getCaretPosition() { return m_text.getCaretPosition(); } public void setCaretPosition(final int position) { m_text.setCaretPosition(position); } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } @Override protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed) {
// Forward all key events on this component to the text field. // We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component. // Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here. if (m_text != null && condition == WHEN_FOCUSED) { if (m_text.processKeyBinding(ks, e, condition, pressed)) { return true; } } // // Fallback to super return super.processKeyBinding(ks, e, condition, pressed); } } // VDate
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java
1
请完成以下Java代码
private ProcessParamBasicInfo buildProcessParamBasicInfo(@NonNull final I_AD_Process_Para processPara) { final IModelTranslationMap processParamTrlMap; if (processPara.getAD_Element_ID() <= 0) { processParamTrlMap = InterfaceWrapperHelper.getModelTranslationMap(processPara); } else { final I_AD_Element element = elementDAO.getById(processPara.getAD_Element_ID()); processParamTrlMap = InterfaceWrapperHelper.getModelTranslationMap(element); } return ProcessParamBasicInfo.builder() .columnName(processPara.getColumnName()) .type(DisplayType.getDescription(processPara.getAD_Reference_ID())) .name(processParamTrlMap.getColumnTrl(I_AD_Process_Para.COLUMNNAME_Name, processPara.getName())) .description(processParamTrlMap.getColumnTrl(I_AD_Process_Para.COLUMNNAME_Description, processPara.getDescription())) .build(); }
private ProcessBasicInfo buildProcessBasicInfo(@NonNull final I_AD_Process adProcess, @Nullable final List<ProcessParamBasicInfo> paramBasicInfos) { final IModelTranslationMap processTrlMap = InterfaceWrapperHelper.getModelTranslationMap(adProcess); return ProcessBasicInfo.builder() .processId(AdProcessId.ofRepoId(adProcess.getAD_Process_ID())) .value(adProcess.getValue()) .name(processTrlMap.getColumnTrl(I_AD_Process.COLUMNNAME_Name, adProcess.getName())) .description(processTrlMap.getColumnTrl(I_AD_Process.COLUMNNAME_Description, adProcess.getName())) .type(ProcessType.ofCode(adProcess.getType())) .parameters(paramBasicInfos) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\process\impl\ProcessService.java
1
请完成以下Java代码
protected Permission getDefaultUserPermissionForTask() { return Context .getProcessEngineConfiguration() .getDefaultUserPermissionForTask(); } protected boolean isEnforceSpecificVariablePermission() { return Context.getProcessEngineConfiguration() .isEnforceSpecificVariablePermission(); } /** * Searches through the cache, if there is already an authorization with same rights. If that's the case * update the given authorization with the permissions and remove the old one from the cache. */ protected void updateAuthorizationBasedOnCacheEntries(AuthorizationEntity authorization, String userId, String groupId, Resource resource, String resourceId) { DbEntityManager dbManager = Context.getCommandContext().getDbEntityManager(); List<AuthorizationEntity> list = dbManager.getCachedEntitiesByType(AuthorizationEntity.class); for (AuthorizationEntity authEntity : list) { boolean hasSameAuthRights = hasEntitySameAuthorizationRights(authEntity, userId, groupId, resource, resourceId); if (hasSameAuthRights) { int previousPermissions = authEntity.getPermissions(); authorization.setPermissions(previousPermissions); dbManager.getDbEntityCache().remove(authEntity); return; } } } protected boolean hasEntitySameAuthorizationRights(AuthorizationEntity authEntity, String userId, String groupId,
Resource resource, String resourceId) { boolean sameUserId = areIdsEqual(authEntity.getUserId(), userId); boolean sameGroupId = areIdsEqual(authEntity.getGroupId(), groupId); boolean sameResourceId = areIdsEqual(authEntity.getResourceId(), (resourceId)); boolean sameResourceType = authEntity.getResourceType() == resource.resourceType(); boolean sameAuthorizationType = authEntity.getAuthorizationType() == AUTH_TYPE_GRANT; return sameUserId && sameGroupId && sameResourceType && sameResourceId && sameAuthorizationType; } protected boolean areIdsEqual(String firstId, String secondId) { if (firstId == null || secondId == null) { return firstId == secondId; }else { return firstId.equals(secondId); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\auth\DefaultAuthorizationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class ModelsToIndexQueueService { private final ITrxManager trxManager = Services.get(ITrxManager.class); private final ModelToIndexRepository repository; public ModelsToIndexQueueService( @NonNull final ModelToIndexRepository repository) { this.repository = repository; } public void enqueue(@NonNull final Collection<ModelToIndexEnqueueRequest> requests) { if (!requests.isEmpty()) { getRequestsCollector().addRequests(requests); } } private RequestsCollector getRequestsCollector() { return trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.Fail) // at this point we always run in trx .getPropertyAndProcessAfterCommit( RequestsCollector.class.getName(), RequestsCollector::new, this::enqueueNow); } private void enqueueNow(@NonNull final RequestsCollector requestsCollector) { final List<ModelToIndexEnqueueRequest> requests = requestsCollector.getRequestsAndMarkedProcessed(); enqueueNow(requests); } public void enqueueNow(@NonNull final List<ModelToIndexEnqueueRequest> requests) {
repository.addToQueue(requests); } @ToString private static class RequestsCollector { private boolean processed = false; private final ArrayList<ModelToIndexEnqueueRequest> requests = new ArrayList<>(); public synchronized void addRequests(@NonNull final Collection<ModelToIndexEnqueueRequest> requests) { assertNotProcessed(); this.requests.addAll(requests); } private void assertNotProcessed() { if (processed) { throw new AdempiereException("already processed: " + this); } } public synchronized List<ModelToIndexEnqueueRequest> getRequestsAndMarkedProcessed() { assertNotProcessed(); this.processed = true; return requests; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelsToIndexQueueService.java
2
请完成以下Java代码
public class LoginBean { @Inject private SecurityContext securityContext; @Inject private FacesContext facesContext; @NotNull private String username; @NotNull private String password; public void login() { Credential credential = new UsernamePasswordCredential(username, new Password(password)); AuthenticationStatus status = securityContext.authenticate( getHttpRequestFromFacesContext(), getHttpResponseFromFacesContext(), withParams().credential(credential)); if (status.equals(SEND_CONTINUE)) { facesContext.responseComplete(); } else if (status.equals(SEND_FAILURE)) { facesContext.addMessage(null, new FacesMessage(SEVERITY_ERROR, "Authentication failed", null)); } } private HttpServletRequest getHttpRequestFromFacesContext() { return (HttpServletRequest) facesContext .getExternalContext() .getRequest(); } private HttpServletResponse getHttpResponseFromFacesContext() { return (HttpServletResponse) facesContext
.getExternalContext() .getResponse(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
repos\tutorials-master\security-modules\java-ee-8-security-api\app-auth-custom-form-store-custom\src\main\java\com\baeldung\javaee\security\LoginBean.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Boolean getReturnBodyOnCreate() { return this.returnBodyOnCreate; } public void setReturnBodyOnCreate(@Nullable Boolean returnBodyOnCreate) { this.returnBodyOnCreate = returnBodyOnCreate; } public @Nullable Boolean getReturnBodyOnUpdate() { return this.returnBodyOnUpdate; } public void setReturnBodyOnUpdate(@Nullable Boolean returnBodyOnUpdate) { this.returnBodyOnUpdate = returnBodyOnUpdate; } public @Nullable Boolean getEnableEnumTranslation() { return this.enableEnumTranslation; }
public void setEnableEnumTranslation(@Nullable Boolean enableEnumTranslation) { this.enableEnumTranslation = enableEnumTranslation; } public void applyTo(RepositoryRestConfiguration rest) { PropertyMapper map = PropertyMapper.get(); map.from(this::getBasePath).to(rest::setBasePath); map.from(this::getDefaultPageSize).to(rest::setDefaultPageSize); map.from(this::getMaxPageSize).to(rest::setMaxPageSize); map.from(this::getPageParamName).to(rest::setPageParamName); map.from(this::getLimitParamName).to(rest::setLimitParamName); map.from(this::getSortParamName).to(rest::setSortParamName); map.from(this::getDetectionStrategy).to(rest::setRepositoryDetectionStrategy); map.from(this::getDefaultMediaType).to(rest::setDefaultMediaType); map.from(this::getReturnBodyOnCreate).to(rest::setReturnBodyOnCreate); map.from(this::getReturnBodyOnUpdate).to(rest::setReturnBodyOnUpdate); map.from(this::getEnableEnumTranslation).to(rest::setEnableEnumTranslation); } }
repos\spring-boot-4.0.1\module\spring-boot-data-rest\src\main\java\org\springframework\boot\data\rest\autoconfigure\DataRestProperties.java
2
请在Spring Boot框架中完成以下Java代码
public ApplicationRunner init() { return args -> { System.out.println("\nFetch the first 5 authors: \n" + bookstoreService.fetchFirst5() + "\n\n"); System.out.println("\nFetch the first 5 authors by age equal to 56: \n" + bookstoreService.fetchFirst5ByAge(56) + "\n\n"); System.out.println("\nFetch the first 5 authors by age greater than or equal to 30: \n" + bookstoreService.fetchFirst5ByAgeGreaterThanEqual(30) + "\n\n"); System.out.println("\nFetch the first 5 authors by age less than 35: \n" + bookstoreService.fetchFirst5ByAgeLessThan(35) + "\n\n"); System.out.println("\nFetch the first 5 authors by age equal to 56 ordered descending by name: \n" + bookstoreService.fetchFirst5ByAgeOrderByNameDesc(56) + "\n\n"); System.out.println("\nFetch the first 5 authors by genre equal to History ordered ascending by age: \n" + bookstoreService.fetchFirst5ByGenreOrderByAgeAsc("History")
+ "\n\n"); System.out.println("\nFetch the first 5 authors by age greater than or equal to 40 ordered ascending by name: \n" + bookstoreService.fetchFirst5ByAgeGreaterThanEqualOrderByNameAsc(40) + "\n\n"); System.out.println("\nFetch the first 5 authors by genre Horror and age less than 50 ordered descending by name: \n" + bookstoreService.fetchFirst5ByGenreAndAgeLessThanOrderByNameDesc("Horror", 50) + "\n\n"); System.out.println("\nFetch the first 5 authors ordered ascending by age as DTO: \n"); List<AuthorDto> authors = bookstoreService.fetchFirst5ByOrderByAgeAsc(); authors.forEach(a -> System.out.println("Author:" + a.getName() + ", " + a.getAge())); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootLimitResultSizeViaQueryCreator\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public boolean isGranted(Acl acl, List<Permission> permission, List<Sid> sids, boolean administrativeMode) throws NotFoundException { List<AccessControlEntry> aces = acl.getEntries(); AccessControlEntry firstRejection = null; for (Permission p : permission) { for (Sid sid : sids) { // Attempt to find exact match for this permission mask and SID boolean scanNextSid = true; for (AccessControlEntry ace : aces) { if (isGranted(ace, p) && ace.getSid().equals(sid)) { // Found a matching ACE, so its authorization decision will // prevail if (ace.isGranting()) { // Success if (!administrativeMode) { this.auditLogger.logIfNeeded(true, ace); } return true; } // Failure for this permission, so stop search // We will see if they have a different permission // (this permission is 100% rejected for this SID) if (firstRejection == null) { // Store first rejection for auditing reasons firstRejection = ace; } scanNextSid = false; // helps break the loop break; // exit aces loop } } if (!scanNextSid) { break; // exit SID for loop (now try next permission) } } } if (firstRejection != null) { // We found an ACE to reject the request at this point, as no // other ACEs were found that granted a different permission if (!administrativeMode) { this.auditLogger.logIfNeeded(false, firstRejection); } return false; } // No matches have been found so far if (acl.isEntriesInheriting() && (acl.getParentAcl() != null)) { // We have a parent, so let them try to find a matching ACE return acl.getParentAcl().isGranted(permission, sids, false); }
// We either have no parent, or we're the uppermost parent throw new NotFoundException("Unable to locate a matching ACE for passed permissions and SIDs"); } /** * Compares an ACE Permission to the given Permission. By default, we compare the * Permission masks for exact match. Subclasses of this strategy can override this * behavior and implement more sophisticated comparisons, e.g. a bitwise comparison * for ACEs that grant access. <pre>{@code * if (ace.isGranting() && p.getMask() != 0) { * return (ace.getPermission().getMask() & p.getMask()) != 0; * } else { * return ace.getPermission().getMask() == p.getMask(); * } * }</pre> * @param ace the ACE from the Acl holding the mask. * @param p the Permission we are checking against. * @return true, if the respective masks are considered to be equal. */ protected boolean isGranted(AccessControlEntry ace, Permission p) { return ace.getPermission().getMask() == p.getMask(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\DefaultPermissionGrantingStrategy.java
1
请完成以下Java代码
private void seleep(long millis, int nanos) { try { Thread.sleep(millis, random.nextInt(nanos)); } catch (InterruptedException e) { logger.info("获取分布式锁休眠被中断:", e); } } public String getLockKeyLog() { return lockKeyLog; } public void setLockKeyLog(String lockKeyLog) { this.lockKeyLog = lockKeyLog; }
public int getExpireTime() { return expireTime; } public void setExpireTime(int expireTime) { this.expireTime = expireTime; } public long getTimeOut() { return timeOut; } public void setTimeOut(long timeOut) { this.timeOut = timeOut; } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\lock\RedisLock.java
1
请完成以下Java代码
public CaseDefinitionEntity getCaseDefinition(String caseDefinitionKey, List<CaseDefinitionEntity> caseDefinitions) { for (CaseDefinitionEntity caseDefinition : caseDefinitions) { if (caseDefinition.getKey().equals(caseDefinitionKey)) { return caseDefinition; } } return null; } public CmmnParseHandlers getCmmnParseHandlers() { return cmmnParseHandlers; } public void setCmmnParseHandlers(CmmnParseHandlers cmmnParseHandlers) { this.cmmnParseHandlers = cmmnParseHandlers; }
public CmmnActivityBehaviorFactory getActivityBehaviorFactory() { return activityBehaviorFactory; } public void setActivityBehaviorFactory(CmmnActivityBehaviorFactory activityBehaviorFactory) { this.activityBehaviorFactory = activityBehaviorFactory; } public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\parser\CmmnParserImpl.java
1
请在Spring Boot框架中完成以下Java代码
public final class UserDetailsServiceAutoConfiguration { private static final String NOOP_PASSWORD_PREFIX = "{noop}"; private static final Pattern PASSWORD_ALGORITHM_PATTERN = Pattern.compile("^\\{.+}.*$"); private static final Log logger = LogFactory.getLog(UserDetailsServiceAutoConfiguration.class); @Bean InMemoryUserDetailsManager inMemoryUserDetailsManager(SecurityProperties properties, ObjectProvider<PasswordEncoder> passwordEncoder) { SecurityProperties.User user = properties.getUser(); List<String> roles = user.getRoles(); return new InMemoryUserDetailsManager(User.withUsername(user.getName()) .password(getOrDeducePassword(user, passwordEncoder.getIfAvailable())) .roles(StringUtils.toStringArray(roles)) .build()); }
private String getOrDeducePassword(SecurityProperties.User user, @Nullable PasswordEncoder encoder) { String password = user.getPassword(); if (user.isPasswordGenerated()) { logger.warn(String.format( "%n%nUsing generated security password: %s%n%nThis generated password is for development use only. " + "Your security configuration must be updated before running your application in " + "production.%n", user.getPassword())); } if (encoder != null || PASSWORD_ALGORITHM_PATTERN.matcher(password).matches()) { return password; } return NOOP_PASSWORD_PREFIX + password; } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\UserDetailsServiceAutoConfiguration.java
2
请完成以下Java代码
public class SQLDatabaseDriverFactory { public static final SQLDatabaseDriverFactory instance = new SQLDatabaseDriverFactory(); public static SQLDatabaseDriverFactory get() { return instance; } private final Map<String, ISQLDatabaseDriver> dbType2driver = new HashMap<String, ISQLDatabaseDriver>(); private SQLDatabaseDriverFactory() { super(); // Register defaults dbType2driver.put(PgSQLDatabaseDriver.DBTYPE, new PgSQLDatabaseDriver()); } public ISQLDatabaseDriver getSQLDatabaseDriver(final String dbType)
{ if (dbType == null || dbType.trim().isEmpty()) { throw new IllegalArgumentException("dbType shall not be empty"); } final ISQLDatabaseDriver driver = dbType2driver.get(dbType); if (driver == null) { throw new IllegalStateException("No database driver was found for database type: " + dbType); } return driver; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\SQLDatabaseDriverFactory.java
1
请完成以下Java代码
public HistoricDecisionInstanceQuery disableCustomObjectDeserialization() { isCustomObjectDeserializationEnabled = false; return this; } public boolean isByteArrayFetchingEnabled() { return isByteArrayFetchingEnabled; } public boolean isCustomObjectDeserializationEnabled() { return isCustomObjectDeserializationEnabled; } public String getRootDecisionInstanceId() { return rootDecisionInstanceId; } public HistoricDecisionInstanceQuery rootDecisionInstanceId(String rootDecisionInstanceId) { ensureNotNull(NotValidException.class, "rootDecisionInstanceId", rootDecisionInstanceId); this.rootDecisionInstanceId = rootDecisionInstanceId; return this; } public boolean isRootDecisionInstancesOnly() { return rootDecisionInstancesOnly; } public HistoricDecisionInstanceQuery rootDecisionInstancesOnly() { this.rootDecisionInstancesOnly = true; return this; }
@Override public HistoricDecisionInstanceQuery decisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionId", decisionRequirementsDefinitionId); this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; return this; } @Override public HistoricDecisionInstanceQuery decisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionKey", decisionRequirementsDefinitionKey); this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; return this; } public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public boolean isTenantIdSet() { return isTenantIdSet; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDecisionInstanceQueryImpl.java
1
请完成以下Java代码
public Object renderTaskForm(TaskFormData taskForm) { if (taskForm.getFormKey()==null) { return null; } String formTemplateString = getFormTemplateString(taskForm, taskForm.getFormKey()); TaskEntity task = (TaskEntity) taskForm.getTask(); return executeScript(formTemplateString, task.getExecution()); } protected Object executeScript(String scriptSrc, VariableScope scope) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); ScriptFactory scriptFactory = processEngineConfiguration.getScriptFactory(); ExecutableScript script = scriptFactory.createScriptFromSource(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE, scriptSrc); ScriptInvocation invocation = new ScriptInvocation(script, scope); try { processEngineConfiguration .getDelegateInterceptor() .handleInvocation(invocation); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ProcessEngineException(e); }
return invocation.getInvocationResult(); } protected String getFormTemplateString(FormData formInstance, String formKey) { String deploymentId = formInstance.getDeploymentId(); ResourceEntity resourceStream = Context .getCommandContext() .getResourceManager() .findResourceByDeploymentIdAndResourceName(deploymentId, formKey); ensureNotNull("Form with formKey '" + formKey + "' does not exist", "resourceStream", resourceStream); byte[] resourceBytes = resourceStream.getBytes(); String encoding = "UTF-8"; String formTemplateString = ""; try { formTemplateString = new String(resourceBytes, encoding); } catch (UnsupportedEncodingException e) { throw new ProcessEngineException("Unsupported encoding of :" + encoding, e); } return formTemplateString; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\JuelFormEngine.java
1
请完成以下Java代码
private String getFutureUrl(String host, Integer port, String accessToken, String clientKeys, String sharedKeys) { return "coaps://" + host + ":" + port + "/api/v1/" + accessToken + "/attributes?clientKeys=" + clientKeys + "&sharedKeys=" + sharedKeys; } public static void main(String[] args) throws URISyntaxException { System.out.println("Usage: java -cp ... org.thingsboard.server.transport.coap.client.SecureClientNoAuth " + "host port accessToken keyStoreUriPath keyStoreAlias trustedAliasPattern clientKeys sharedKeys"); String host = args[0]; int port = Integer.parseInt(args[1]); String accessToken = args[2]; String clientKeys = args[7]; String sharedKeys = args[8]; String keyStoreUriPath = args[3]; String keyStoreAlias = args[4]; String trustedAliasPattern = args[5]; String keyStorePassword = args[6]; DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new Configuration()); setupCredentials(builder, keyStoreUriPath, keyStoreAlias, trustedAliasPattern, keyStorePassword); DTLSConnector dtlsConnector = new DTLSConnector(builder.build()); SecureClientNoAuth client = new SecureClientNoAuth(dtlsConnector, host, port, accessToken, clientKeys, sharedKeys); client.test(); } private static void setupCredentials(DtlsConnectorConfig.Builder config, String keyStoreUriPath, String keyStoreAlias, String trustedAliasPattern, String keyStorePassword) { StaticNewAdvancedCertificateVerifier.Builder trustBuilder = StaticNewAdvancedCertificateVerifier.builder();
try { SslContextUtil.Credentials serverCredentials = SslContextUtil.loadCredentials( keyStoreUriPath, keyStoreAlias, keyStorePassword.toCharArray(), keyStorePassword.toCharArray()); Certificate[] trustedCertificates = SslContextUtil.loadTrustedCertificates( keyStoreUriPath, trustedAliasPattern, keyStorePassword.toCharArray()); trustBuilder.setTrustedCertificates(trustedCertificates); config.setAdvancedCertificateVerifier(trustBuilder.build()); config.setCertificateIdentityProvider(new SingleCertificateProvider(serverCredentials.getPrivateKey(), serverCredentials.getCertificateChain(), Collections.singletonList(CertificateType.X_509))); } catch (GeneralSecurityException e) { System.err.println("certificates are invalid!"); throw new IllegalArgumentException(e.getMessage()); } catch (IOException e) { System.err.println("certificates are missing!"); throw new IllegalArgumentException(e.getMessage()); } } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\client\SecureClientNoAuth.java
1
请完成以下Java代码
public class MultipartPayloadProvider implements MessageBodyReader<MultipartFormData> { public static final String TYPE_NAME = "multipart"; public static final String SUB_TYPE_NAME = "form-data"; public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return TYPE_NAME.equals(mediaType.getType().toLowerCase()) && SUB_TYPE_NAME.equals(mediaType.getSubtype().toLowerCase()); } public MultipartFormData readFrom(Class<MultipartFormData> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { final MultipartFormData multipartFormData = createMultipartFormDataInstance(); final FileUpload fileUpload = createFileUploadInstance(); String contentType = httpHeaders.getFirst("content-type"); RestMultipartRequestContext requestContext = createRequestContext(entityStream, contentType); // parse the request (populates the multipartFormData) parseRequest(multipartFormData, fileUpload, requestContext); return multipartFormData; } protected FileUpload createFileUploadInstance() { return new FileUpload(); } protected MultipartFormData createMultipartFormDataInstance() { return new MultipartFormData(); } protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) { try { FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext); while (itemIterator.hasNext()) { FileItemStream stream = itemIterator.next(); multipartFormData.addPart(new FormPart(stream)); } } catch (Exception e) { throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed"); } } protected RestMultipartRequestContext createRequestContext(InputStream entityStream, String contentType) { return new RestMultipartRequestContext(entityStream, contentType); } /** * Exposes the REST request to commons fileupload
* */ static class RestMultipartRequestContext implements RequestContext { protected InputStream inputStream; protected String contentType; public RestMultipartRequestContext(InputStream inputStream, String contentType) { this.inputStream = inputStream; this.contentType = contentType; } public String getCharacterEncoding() { return null; } public String getContentType() { return contentType; } public int getContentLength() { return -1; } public InputStream getInputStream() throws IOException { return inputStream; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\mapper\MultipartPayloadProvider.java
1
请完成以下Java代码
public void setScrap (final @Nullable BigDecimal Scrap) { set_Value (COLUMNNAME_Scrap, Scrap); } @Override public BigDecimal getScrap() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTM_Product_ID (final int TM_Product_ID) { if (TM_Product_ID < 1) set_Value (COLUMNNAME_TM_Product_ID, null); else set_Value (COLUMNNAME_TM_Product_ID, TM_Product_ID); } @Override public int getTM_Product_ID()
{ return get_ValueAsInt(COLUMNNAME_TM_Product_ID); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Product_BOMLine.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AttachmentMetadata attachmentMetadata = (AttachmentMetadata) o; return Objects.equals(this.type, attachmentMetadata.type) && Objects.equals(this.therapyId, attachmentMetadata.therapyId) && Objects.equals(this.therapyTypeId, attachmentMetadata.therapyTypeId) && Objects.equals(this.woundLocation, attachmentMetadata.woundLocation) && Objects.equals(this.patientId, attachmentMetadata.patientId) && Objects.equals(this.createdBy, attachmentMetadata.createdBy) && Objects.equals(this.createdAt, attachmentMetadata.createdAt) && Objects.equals(this.archived, attachmentMetadata.archived); } @Override public int hashCode() { return Objects.hash(type, therapyId, therapyTypeId, woundLocation, patientId, createdBy, createdAt, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AttachmentMetadata {\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" therapyId: ").append(toIndentedString(therapyId)).append("\n"); sb.append(" therapyTypeId: ").append(toIndentedString(therapyTypeId)).append("\n"); sb.append(" woundLocation: ").append(toIndentedString(woundLocation)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" archived: ").append(toIndentedString(archived)).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\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\AttachmentMetadata.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteUser(Long id) { userDao.deleteById(id); } /** * 更新用户 * * @param user 用户 * @return 更新后的用户 */ @Override public User updateUser(User user) { if (ObjectUtil.isNull(user)) { throw new RuntimeException("用户id不能为null"); } userDao.updateTemplateById(user); return userDao.single(user.getId()); } /** * 查询单个用户 * * @param id 主键id * @return 用户信息 */ @Override public User getUser(Long id) { return userDao.single(id);
} /** * 查询用户列表 * * @return 用户列表 */ @Override public List<User> getUserList() { return userDao.all(); } /** * 分页查询 * * @param currentPage 当前页 * @param pageSize 每页条数 * @return 分页用户列表 */ @Override public PageQuery<User> getUserByPage(Integer currentPage, Integer pageSize) { return userDao.createLambdaQuery().page(currentPage, pageSize); } }
repos\spring-boot-demo-master\demo-orm-beetlsql\src\main\java\com\xkcoding\orm\beetlsql\service\impl\UserServiceImpl.java
2
请完成以下Java代码
public int getPP_Order_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Candidate_ID); } @Override public void setPP_OrderLine_Candidate_ID (final int PP_OrderLine_Candidate_ID) { if (PP_OrderLine_Candidate_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_OrderLine_Candidate_ID, PP_OrderLine_Candidate_ID); } @Override public int getPP_OrderLine_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_PP_OrderLine_Candidate_ID); } @Override public org.eevolution.model.I_PP_Product_BOMLine getPP_Product_BOMLine() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class); } @Override public void setPP_Product_BOMLine(final org.eevolution.model.I_PP_Product_BOMLine PP_Product_BOMLine) { set_ValueFromPO(COLUMNNAME_PP_Product_BOMLine_ID, org.eevolution.model.I_PP_Product_BOMLine.class, PP_Product_BOMLine); } @Override public void setPP_Product_BOMLine_ID (final int PP_Product_BOMLine_ID) {
if (PP_Product_BOMLine_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMLine_ID, PP_Product_BOMLine_ID); } @Override public int getPP_Product_BOMLine_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMLine_ID); } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_Value (COLUMNNAME_QtyEntered, QtyEntered); } @Override public BigDecimal getQtyEntered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_OrderLine_Candidate.java
1
请完成以下Java代码
public Optional<User> findFirstUserByRoleClusterOperator(Service service) { Optional<User> optionalUser = Optional.empty(); String serviceName = service.getName(); String userPropertyName = String.format(VCAP_SERVICES_SERVICE_NAME_USERS_INDEX_PROPERTY, serviceName, 0); for (int index = 1; containsProperty(asUserRolesProperty(userPropertyName)); index++) { String roles = String.valueOf(getProperty(asUserRolesProperty(userPropertyName))); if (roles.contains(User.Role.CLUSTER_OPERATOR.name().toLowerCase())) { break; } userPropertyName = String.format(VCAP_SERVICES_SERVICE_NAME_USERS_INDEX_PROPERTY, serviceName, index); } if (containsProperty(asUserUsernameProperty(userPropertyName))) { String username = String.valueOf(getProperty(asUserUsernameProperty(userPropertyName))); String password = String.valueOf(getProperty(asUserPasswordProperty(userPropertyName))); User user = User.with(username) .withPassword(password) .withRole(User.Role.CLUSTER_OPERATOR); optionalUser = Optional.of(user); } return optionalUser; } private String asUserPasswordProperty(String userProperty) { return String.format("%s.password", userProperty); } private String asUserRolesProperty(String userProperty) { return String.format("%s.roles", userProperty); } private String asUserUsernameProperty(String userProperty) {
return String.format("%s.username", userProperty); } @Nullable @Override public Object getProperty(String name) { return getSource().getProperty(name); } @NonNull protected Predicate<String> getVcapServicePredicate() { return this.vcapServicePredicate != null ? this.vcapServicePredicate : propertyName -> true; } @Override public Iterator<String> iterator() { return Collections.unmodifiableList(Arrays.asList(getSource().getPropertyNames())).iterator(); } @NonNull public VcapPropertySource withVcapServiceName(@NonNull String serviceName) { Assert.hasText(serviceName, "Service name is required"); String resolvedServiceName = StringUtils.trimAllWhitespace(serviceName); Predicate<String> vcapServiceNamePredicate = propertyName -> propertyName.startsWith(String.format("%1$s%2$s.", VCAP_SERVICES_PROPERTY, resolvedServiceName)); return withVcapServicePredicate(vcapServiceNamePredicate); } @NonNull public VcapPropertySource withVcapServicePredicate(@Nullable Predicate<String> vcapServicePredicate) { this.vcapServicePredicate = vcapServicePredicate; return this; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\env\VcapPropertySource.java
1
请完成以下Java代码
public class CountDownLatchTest { static final CountDownLatch countDownLatch = new CountDownLatch(6); public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + "主线程开始......"); new Thread(new InitJob()).start(); new Thread(new BusinessWoerk()).start(); new Thread(new InitJob()).start(); new Thread(new InitWoerk()).start(); new Thread(new InitJob()).start(); new Thread(new InitJob()).start(); try { System.out.println(Thread.currentThread().getName() + "主线程等待初始化线程初始化完成......"); countDownLatch.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } sleep(5); System.out.println(Thread.currentThread().getName() + "主线程结束......"); } /** * 一个线程一个扣减点 */ static class InitJob implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + "初始化任务开始。。。。。。"); try { sleep(5); } finally { countDownLatch.countDown(); } sleep(5); System.out.println(Thread.currentThread().getName() + "初始化任务完毕后,处理业务逻辑。。。。。。"); } } /** * 一个线程两个扣减点 */ static class InitWoerk implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + "初始化工作开始第一步》》》》》"); try {
sleep(5); } finally { countDownLatch.countDown(); } System.out.println(Thread.currentThread().getName() + "初始化工作开始第二步》》》》》"); try { sleep(5); } finally { countDownLatch.countDown(); } System.out.println(Thread.currentThread().getName() + "初始化工作处理业务逻辑》》》》》"); } } /** * 业务线程 */ static class BusinessWoerk implements Runnable { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "初始化线程还未完成,业务线程阻塞----------"); countDownLatch.await(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------"); System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------"); System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------"); System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------"); } } private static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\CountDownLatchTest.java
1