instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private ExplainedOptional<ClonePlan> getPlan(final @Nullable IProcessPreconditionsContext preconditionsContext) { final Set<TableRecordReference> selectedRowRefs; if (preconditionsContext != null) { if (preconditionsContext.getAdTabId() == null) { return ExplainedOptional.emptyBecause("No row(s) from a tab selected."); } selectedRowRefs = preconditionsContext.getSelectedIncludedRecords(); } else { selectedRowRefs = getProcessInfo().getSelectedIncludedRecords(); } if (selectedRowRefs.size() != 1) { return ExplainedOptional.emptyBecause("More or less than one row selected."); } final TableRecordReference rowRef = CollectionUtils.singleElement(selectedRowRefs); if (!CopyRecordFactory.isEnabledForTableName(rowRef.getTableName())) { return ExplainedOptional.emptyBecause("CopyRecordFactory not enabled for the table the row belongs to."); } // we have e.g. in the C_BPartner-window two subtabs ("Customer" and "Vendor") that show a different view on the same C_BPartner record. // There, cloning the subtab-line makes no sense if (Objects.equals(getProcessInfo().getTableNameOrNull(), rowRef.getTableName())) { return ExplainedOptional.emptyBecause("The main-window has the same Record as the sub-tab, there can only be one line."); }
final TableRecordReference headerRef = TableRecordReference.of(getTable_ID(), getRecord_ID()); final PO headerPO = headerRef.getModel(PlainContextAware.newWithThreadInheritedTrx(), PO.class); final String headerPO_KeyColumName = headerPO.getPOInfo().getKeyColumnName(); if (headerPO_KeyColumName == null) { throw new AdempiereException("A document header which does not have a single primary key is not supported"); } final PO rowPO = rowRef.getModel(PlainContextAware.newWithThreadInheritedTrx(), PO.class); if (!rowPO.getPOInfo().hasColumnName(headerPO_KeyColumName)) { throw new AdempiereException("Row which does not link to it's header via header's primary key is not supported"); } return ExplainedOptional.of( ClonePlan.builder() .rowPO(rowPO) .rowPO_LinkColumnName(headerPO_KeyColumName) .headerPO(headerPO) .adWindowId(getProcessInfo().getAdWindowId()) .build()); } @Value @Builder private static class ClonePlan { @NonNull PO rowPO; @NonNull String rowPO_LinkColumnName; @NonNull PO headerPO; @Nullable AdWindowId adWindowId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\WEBUI_CloneLine.java
1
请完成以下Java代码
public void updateDocTaxes(final DocTaxesList taxes) { final HashMap<TaxId, TaxAmounts> allTaxAmountsToPropagate = new HashMap<>(this.taxAmountsByTaxId); taxes.mapEach(docTax -> { final TaxAmounts taxAmounts = allTaxAmountsToPropagate.remove(docTax.getTaxId()); if (taxAmounts == null) { return null; // remove it } else { taxAmounts.updateDocTax(docTax); return docTax; } }); for (final TaxAmounts taxAmounts : allTaxAmountsToPropagate.values()) { taxes.add(toDocTax(taxAmounts)); } } private DocTax toDocTax(@NonNull TaxAmounts taxAmounts) { return DocTax.builderFrom(taxAmounts.getTax()) .accountProvider(accountProvider) .taxBaseAmt(taxAmounts.getTaxBaseAmt().toBigDecimal()) .taxAmt(taxAmounts.getTaxAmt().toBigDecimal()) .reverseChargeTaxAmt(taxAmounts.getReverseChargeAmt().toBigDecimal()) .build(); } // // // // // private static class TaxAmounts { @NonNull @Getter private final Tax tax; @NonNull private final CurrencyPrecision precision; @NonNull @Getter private Money taxBaseAmt; private boolean isTaxCalculated = false; private Money _taxAmt; private Money _reverseChargeAmt; public TaxAmounts(@NonNull final Tax tax, @NonNull final CurrencyId currencyId, @NonNull final CurrencyPrecision precision) { this.tax = tax; this.precision = precision;
this.taxBaseAmt = this._taxAmt = this._reverseChargeAmt = Money.zero(currencyId); } public void addTaxBaseAmt(@NonNull final Money taxBaseAmtToAdd) { if (taxBaseAmtToAdd.isZero()) { return; } this.taxBaseAmt = this.taxBaseAmt.add(taxBaseAmtToAdd); this.isTaxCalculated = false; } public Money getTaxAmt() { updateTaxAmtsIfNeeded(); return _taxAmt; } public Money getReverseChargeAmt() { updateTaxAmtsIfNeeded(); return _reverseChargeAmt; } private void updateTaxAmtsIfNeeded() { if (!isTaxCalculated) { final CalculateTaxResult result = tax.calculateTax(taxBaseAmt.toBigDecimal(), false, precision.toInt()); this._taxAmt = Money.of(result.getTaxAmount(), taxBaseAmt.getCurrencyId()); this._reverseChargeAmt = Money.of(result.getReverseChargeAmt(), taxBaseAmt.getCurrencyId()); this.isTaxCalculated = true; } } public void updateDocTax(@NonNull final DocTax docTax) { if (!TaxId.equals(tax.getTaxId(), docTax.getTaxId())) { throw new AdempiereException("TaxId not matching: " + this + ", " + docTax); } docTax.setTaxBaseAmt(getTaxBaseAmt().toBigDecimal()); docTax.setTaxAmt(getTaxAmt().toBigDecimal()); docTax.setReverseChargeTaxAmt(getReverseChargeAmt().toBigDecimal()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxUpdater.java
1
请完成以下Java代码
public FlowElement getCurrentFlowElement() { return currentFlowElement; } @Override public boolean isActive() { return active; } @Override public boolean isEnded() { return ended; } @Override public boolean isConcurrent() { return concurrent; } @Override public boolean isProcessInstanceType() { return processInstanceType; } @Override public boolean isScope() { return scope; } @Override public boolean isMultiInstanceRoot() { return multiInstanceRoot; } @Override public Object getVariable(String variableName) { return variables.get(variableName); } @Override public boolean hasVariable(String variableName) { return variables.containsKey(variableName);
} @Override public Set<String> getVariableNames() { return variables.keySet(); } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("id='" + id + "'") .add("currentActivityId='" + currentActivityId + "'") .add("processInstanceId='" + processInstanceId + "'") .add("processDefinitionId='" + processDefinitionId + "'") .add("tenantId='" + tenantId + "'") .toString(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java
1
请完成以下Java代码
public void createTUPackingInstructions(final CreateTUPackingInstructionsRequest request) { CreateTUPackingInstructionsCommand.builder() .handlingUnitsDAO(this) .request(request) .build() .execute(); } @Override public Optional<I_M_HU_PI_Item> getTUPIItemForLUPIAndItemProduct(final BPartnerId bpartnerId, final @NonNull HuPackingInstructionsId luPIId, final @NonNull HUPIItemProductId piItemProductId) { final I_M_HU_PI_Version luPIVersion = retrievePICurrentVersionOrNull(luPIId); if (luPIVersion == null || !luPIVersion.isActive() || !luPIVersion.isCurrent() || !X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit.equals(luPIVersion.getHU_UnitType())) { return Optional.empty(); } return queryBL.createQueryBuilder(I_M_HU_PI_Item_Product.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID, piItemProductId) .andCollect(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_ID, I_M_HU_PI_Item.class)
.addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_ItemType, X_M_HU_PI_Item.ITEMTYPE_Material) .addInArrayFilter(I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID, bpartnerId, null) .addOnlyActiveRecordsFilter() .andCollect(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID, I_M_HU_PI_Version.class) .addEqualsFilter(I_M_HU_PI_Version.COLUMNNAME_HU_UnitType, X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit) .addEqualsFilter(I_M_HU_PI_Version.COLUMNNAME_IsCurrent, true) .addOnlyActiveRecordsFilter() .andCollect(I_M_HU_PI_Version.COLUMNNAME_M_HU_PI_ID, I_M_HU_PI.class) .andCollectChildren(I_M_HU_PI_Item.COLUMNNAME_Included_HU_PI_ID, I_M_HU_PI_Item.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_ItemType, X_M_HU_PI_Item.ITEMTYPE_HandlingUnit) .addEqualsFilter(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID, luPIVersion.getM_HU_PI_Version_ID()) .orderBy(I_M_HU_PI_Item.COLUMNNAME_M_HU_PI_Version_ID) .create() .firstOptional(I_M_HU_PI_Item.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HandlingUnitsDAO.java
1
请完成以下Java代码
public class CleanableHistoricProcessInstanceReportResultEntity implements CleanableHistoricProcessInstanceReportResult { protected String processDefinitionId; protected String processDefinitionKey; protected String processDefinitionName; protected int processDefinitionVersion; protected Integer historyTimeToLive; protected long finishedProcessInstanceCount; protected long cleanableProcessInstanceCount; protected String tenantId; public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getProcessDefinitionName() { return processDefinitionName; } public void setProcessDefinitionName(String processDefinitionName) { this.processDefinitionName = processDefinitionName; } public int getProcessDefinitionVersion() { return processDefinitionVersion; } public void setProcessDefinitionVersion(int processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public long getFinishedProcessInstanceCount() {
return finishedProcessInstanceCount; } public void setFinishedProcessInstanceCount(Long finishedProcessInstanceCount) { this.finishedProcessInstanceCount = finishedProcessInstanceCount; } public long getCleanableProcessInstanceCount() { return cleanableProcessInstanceCount; } public void setCleanableProcessInstanceCount(Long cleanableProcessInstanceCount) { this.cleanableProcessInstanceCount = cleanableProcessInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String toString() { return this.getClass().getSimpleName() + "[processDefinitionId = " + processDefinitionId + ", processDefinitionKey = " + processDefinitionKey + ", processDefinitionName = " + processDefinitionName + ", processDefinitionVersion = " + processDefinitionVersion + ", historyTimeToLive = " + historyTimeToLive + ", finishedProcessInstanceCount = " + finishedProcessInstanceCount + ", cleanableProcessInstanceCount = " + cleanableProcessInstanceCount + ", tenantId = " + tenantId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricProcessInstanceReportResultEntity.java
1
请完成以下Java代码
public Long getSignatureCount() { return signatureCount; } public void setSignatureCount(Long signatureCount) { this.signatureCount = signatureCount; } public Boolean getUvInitialized() { return uvInitialized; } public void setUvInitialized(Boolean uvInitialized) { this.uvInitialized = uvInitialized; } public String getTransports() { return transports; } public void setTransports(String transports) { this.transports = transports; } public Boolean getBackupEligible() { return backupEligible; } public void setBackupEligible(Boolean backupEligible) { this.backupEligible = backupEligible; } public Boolean getBackupState() { return backupState; } public void setBackupState(Boolean backupState) { this.backupState = backupState; } public String getAttestationObject() {
return attestationObject; } public void setAttestationObject(String attestationObject) { this.attestationObject = attestationObject; } public Instant getLastUsed() { return lastUsed; } public void setLastUsed(Instant lastUsed) { this.lastUsed = lastUsed; } public Instant getCreated() { return created; } public void setCreated(Instant created) { this.created = created; } }
repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\domain\PasskeyCredential.java
1
请完成以下Java代码
public class DpdDatabaseClientLogger { public static final transient DpdDatabaseClientLogger instance = new DpdDatabaseClientLogger(); private static final Logger logger = LogManager.getLogger(DpdDatabaseClientLogger.class); private DpdDatabaseClientLogger() { } public void log(@NonNull final DpdClientLogEvent event) { try { createLogRecord(event); } catch (final Exception ex) { logger.warn("Failed creating Dpd log record: {}", event, ex); } normalLogging(event); } private void normalLogging(final DpdClientLogEvent event) { if (!logger.isTraceEnabled()) { return; } if (event.getResponseException() != null) { logger.trace("Dpd Send/Receive error: {}", event, event.getResponseException()); } else { logger.trace("Dpd Send/Receive OK: {}", event); } } private void createLogRecord(@NonNull final DpdClientLogEvent event) { final I_DPD_StoreOrder_Log logRecord = InterfaceWrapperHelper.newInstance(I_DPD_StoreOrder_Log.class); logRecord.setConfigSummary(event.getConfigSummary());
logRecord.setDurationMillis((int)event.getDurationMillis()); logRecord.setDPD_StoreOrder_ID(event.getDeliveryOrderRepoId()); //noinspection ConstantConditions logRecord.setRequestMessage(event.getRequestAsString()); if (event.getResponseException() != null) { logRecord.setIsError(true); final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(event.getResponseException()); logRecord.setAD_Issue_ID(issueId.getRepoId()); } else { logRecord.setIsError(false); //noinspection ConstantConditions logRecord.setResponseMessage(event.getResponseAsString()); } InterfaceWrapperHelper.save(logRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\logger\DpdDatabaseClientLogger.java
1
请完成以下Java代码
public final boolean isTaxIncluded() { return _taxIncluded; } // isTaxIncluded /** * Set Tax Included * * @param taxIncluded Is Tax Included? */ protected final void setIsTaxIncluded(final boolean taxIncluded) { _taxIncluded = taxIncluded; } /** * @see Doc#isSOTrx() */ public boolean isSOTrx() { return m_doc.isSOTrx(); } /** * @return document currency precision * @see Doc#getStdPrecision() */ protected final CurrencyPrecision getStdPrecision() { return m_doc.getStdPrecision(); }
/** * @return document (header) */ protected final DT getDoc() { return m_doc; } public final PostingException newPostingException() { return m_doc.newPostingException() .setDocument(getDoc()) .setDocLine(this); } public final PostingException newPostingException(final Throwable ex) { return m_doc.newPostingException(ex) .setDocument(getDoc()) .setDocLine(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine.java
1
请完成以下Java代码
public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setIsAcknowledged (final boolean IsAcknowledged) { set_Value (COLUMNNAME_IsAcknowledged, IsAcknowledged); } @Override public boolean isAcknowledged() { return get_ValueAsBoolean(COLUMNNAME_IsAcknowledged); } @Override public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRoot_AD_Table_ID (final int Root_AD_Table_ID) { if (Root_AD_Table_ID < 1) set_Value (COLUMNNAME_Root_AD_Table_ID, null); else set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID); } @Override public int getRoot_AD_Table_ID() { return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID); }
@Override public void setRoot_Record_ID (final int Root_Record_ID) { if (Root_Record_ID < 1) set_Value (COLUMNNAME_Root_Record_ID, null); else set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID); } @Override public int getRoot_Record_ID() { return get_ValueAsInt(COLUMNNAME_Root_Record_ID); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity) { set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
1
请完成以下Java代码
protected boolean afterSave (boolean newRecord, boolean success) { if (newRecord) insert_Tree(MTree_Base.TREETYPE_Menu); return success; } // afterSave /** * After Delete * @param success * @return deleted */ protected boolean afterDelete (boolean success) { if (success) delete_Tree(MTree_Base.TREETYPE_Menu); return success; } // afterDelete /** * FR [ 1966326 ] * get Menu ID * @param String Menu Name * @return int retValue */ public static int getMenu_ID(String menuName) { int retValue = 0; String SQL = "SELECT AD_Menu_ID FROM AD_Menu WHERE Name = ?"; PreparedStatement pstmt = null; ResultSet rs = null;
try { pstmt = DB.prepareStatement(SQL, null); pstmt.setString(1, menuName); rs = pstmt.executeQuery(); if (rs.next()) retValue = rs.getInt(1); } catch (SQLException e) { s_log.error(SQL, e); retValue = -1; } finally { DB.close(rs, pstmt); } return retValue; } } // MMenu
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMenu.java
1
请完成以下Java代码
protected String doIt() { if (p_Action == null) { throw new FillMandatoryException("Action"); } final List<Object> params = new ArrayList<>(); final StringBuffer whereClause = new StringBuffer(); whereClause.append(I_PP_Product_BOMLine.COLUMNNAME_M_Product_ID+"=?"); params.add(p_M_Product_ID); if (p_ValidTo != null) { whereClause.append(" AND TRUNC("+I_PP_Product_BOMLine.COLUMNNAME_ValidTo+") <= ?"); params.add(p_ValidTo); } if (p_ValidFrom != null) { whereClause.append(" AND TRUNC("+I_PP_Product_BOMLine.COLUMNNAME_ValidFrom+") >= ?"); params.add(p_ValidFrom); } final List<I_PP_Product_BOMLine> components = new Query(getCtx(), I_PP_Product_BOMLine.Table_Name, whereClause.toString(), get_TrxName()) .setParameters(params) .list(I_PP_Product_BOMLine.class); for(final I_PP_Product_BOMLine bomline : components) { if (p_Action.equals(ACTION_Add)) { actionAdd(bomline, 0); } else if (p_Action.equals(ACTION_Deactivate)) { actionDeactivate(bomline); } else if (p_Action.equals(ACTION_Expire)) { actionExpire(bomline); } else if (p_Action.equals(ACTION_Replace)) { actionAdd(bomline, bomline.getLine() + 1); actionDeactivate(bomline); } else if (p_Action.equals(ACTION_ReplaceAndExpire)) { actionAdd(bomline, bomline.getLine() + 1); actionExpire(bomline); } else { throw new LiberoException("Action not supported - "+p_Action); } addLog(ADReferenceService.get().retrieveListNameTrl(getCtx(), ACTION_AD_Reference_ID, p_Action));
} return "@OK@"; } // doIt protected void actionAdd(final I_PP_Product_BOMLine bomline, final int line) { final I_PP_Product_BOMLine newbomline = InterfaceWrapperHelper.copy() .setFrom(bomline) .copyToNew(I_PP_Product_BOMLine.class); newbomline.setIsActive(true); newbomline.setLine(line); newbomline.setM_ChangeNotice_ID(p_M_ChangeNotice_ID); // newbomline.setM_Product_ID(p_New_M_Product_ID); if (p_Qty.signum() != 0) { newbomline.setQtyBOM(p_Qty); } newbomline.setValidFrom(newbomline.getUpdated()); saveRecord(newbomline); } protected void actionDeactivate(final I_PP_Product_BOMLine bomline) { bomline.setIsActive(false); bomline.setM_ChangeNotice_ID(p_M_ChangeNotice_ID); saveRecord(bomline); } protected void actionExpire(final I_PP_Product_BOMLine bomline) { bomline.setIsActive(true); bomline.setValidTo(bomline.getUpdated()); bomline.setM_ChangeNotice_ID(p_M_ChangeNotice_ID); saveRecord(bomline); } } // Component Change
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\ComponentChange.java
1
请完成以下Java代码
public void setPP_Plant_ID (final int PP_Plant_ID) { if (PP_Plant_ID < 1) set_Value (COLUMNNAME_PP_Plant_ID, null); else set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID); } @Override public int getPP_Plant_ID() { return get_ValueAsInt(COLUMNNAME_PP_Plant_ID); } @Override public void setProductGroup (final @Nullable java.lang.String ProductGroup) { throw new IllegalArgumentException ("ProductGroup is virtual column"); } @Override public java.lang.String getProductGroup() { return get_ValueAsString(COLUMNNAME_ProductGroup); } @Override public void setProductName (final @Nullable java.lang.String ProductName) { throw new IllegalArgumentException ("ProductName is virtual column"); } @Override public java.lang.String getProductName() { return get_ValueAsString(COLUMNNAME_ProductName); } @Override public void setQtyCount (final BigDecimal QtyCount) { set_Value (COLUMNNAME_QtyCount, QtyCount);
} @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java
1
请完成以下Java代码
public BigDecimal getPointsBase_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiced (final @Nullable BigDecimal PointsBase_Invoiced) { set_ValueNoCheck (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced); } @Override public BigDecimal getPointsBase_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_Settled (final @Nullable BigDecimal PointsSum_Settled) { set_ValueNoCheck (COLUMNNAME_PointsSum_Settled, PointsSum_Settled); } @Override public BigDecimal getPointsSum_Settled() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsSum_ToSettle (final @Nullable BigDecimal PointsSum_ToSettle) { set_ValueNoCheck (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle); } @Override public BigDecimal getPointsSum_ToSettle()
{ final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_ValueNoCheck (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQtyEntered (final @Nullable BigDecimal QtyEntered) { set_ValueNoCheck (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.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Overview_V.java
1
请完成以下Java代码
public final AmountSourceAndAcct build() { return new AmountSourceAndAcct(this); } public Builder setAmtSource(final BigDecimal amtSource) { this.amtSource = amtSource; return this; } public Builder setAmtAcct(final BigDecimal amtAcct) { this.amtAcct = amtAcct; return this; } public Builder addAmtSource(final BigDecimal amtSourceToAdd) { amtSource = amtSource.add(amtSourceToAdd); return this; } public Builder addAmtAcct(final BigDecimal amtAcctToAdd) { amtAcct = amtAcct.add(amtAcctToAdd); return this; }
public Builder add(final AmountSourceAndAcct amtSourceAndAcctToAdd) { // Optimization: do nothing if zero if (amtSourceAndAcctToAdd == ZERO) { return this; } addAmtSource(amtSourceAndAcctToAdd.getAmtSource()); addAmtAcct(amtSourceAndAcctToAdd.getAmtAcct()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\AmountSourceAndAcct.java
1
请完成以下Java代码
public void setCountImportRecordsDeleted(final int countImportRecordsDeleted) { Check.assumeGreaterOrEqualToZero(countImportRecordsDeleted, "countImportRecordsDeleted"); this.countImportRecordsDeleted.set(countImportRecordsDeleted); } public void setCountImportRecordsWithValidationErrors(final int count) { Check.assumeGreaterOrEqualToZero(count, "count"); this.countImportRecordsWithValidationErrors.set(count); } public void addCountImportRecordsConsidered(final int count) { countImportRecordsConsidered.add(count); } public int getCountImportRecordsConsidered() {return countImportRecordsConsidered.toIntOr(0);} public void addInsertsIntoTargetTable(final int count) { countInsertsIntoTargetTable.add(count); } public void addUpdatesIntoTargetTable(final int count) { countUpdatesIntoTargetTable.add(count); } public void actualImportError(@NonNull final ActualImportRecordsResult.Error error) { actualImportErrors.add(error); } } @EqualsAndHashCode private static final class Counter { private boolean unknownValue; private int value = 0;
@Override public String toString() { return unknownValue ? "N/A" : String.valueOf(value); } public void set(final int value) { if (value < 0) { throw new AdempiereException("value shall NOT be negative: " + value); } this.value = value; this.unknownValue = false; } public void add(final int valueToAdd) { Check.assumeGreaterOrEqualToZero(valueToAdd, "valueToAdd"); set(this.value + valueToAdd); } public OptionalInt toOptionalInt() {return unknownValue ? OptionalInt.empty() : OptionalInt.of(value);} public int toIntOr(final int defaultValue) {return unknownValue ? defaultValue : value;} } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportProcessResult.java
1
请完成以下Java代码
abstract class Password4jPasswordEncoder extends AbstractValidatingPasswordEncoder { private final HashingFunction hashingFunction; /** * Constructs a Password4j password encoder with the specified hashing function. This * constructor is package-private and intended for use by subclasses only. * @param hashingFunction the hashing function to use for encoding passwords, must not * be null * @throws IllegalArgumentException if hashingFunction is null */ Password4jPasswordEncoder(HashingFunction hashingFunction) { Assert.notNull(hashingFunction, "hashingFunction cannot be null"); this.hashingFunction = hashingFunction; } @Override
protected String encodeNonNullPassword(String rawPassword) { Hash hash = Password.hash(rawPassword).with(this.hashingFunction); return hash.getResult(); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { return Password.check(rawPassword, encodedPassword).with(this.hashingFunction); } @Override protected boolean upgradeEncodingNonNull(String encodedPassword) { // Password4j handles upgrade detection internally for most algorithms // For now, we'll return false to maintain existing behavior return false; } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password4j\Password4jPasswordEncoder.java
1
请完成以下Java代码
public class PPOrderWeightingRunCheck { @NonNull private final PPOrderWeightingRunCheckId id; private final SeqNo lineNo; @NonNull private Quantity weight; @Nullable private final String description; @Getter private boolean isToleranceExceeded; @Builder private PPOrderWeightingRunCheck( final @NonNull PPOrderWeightingRunCheckId id, final @NonNull SeqNo lineNo, final @NonNull Quantity weight, final @Nullable String description, final boolean isToleranceExceeded) { this.id = id; this.lineNo = lineNo; this.weight = weight; this.description = description; this.isToleranceExceeded = isToleranceExceeded; }
void updateIsToleranceExceeded(final Range<Quantity> validRange) { this.isToleranceExceeded = !validRange.contains(weight); } public void setUomId(final UomId uomId) { if (UomId.equals(this.weight.getUomId(), uomId)) { return; } this.weight = Quantitys.of(this.weight.toBigDecimal(), uomId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunCheck.java
1
请完成以下Java代码
public String objectToString(I_AD_Column column, Object value) { final int displayType = column.getAD_Reference_ID(); final boolean isMandatory = column.isMandatory(); return objectToString(value, displayType, isMandatory); } @Override public String objectToString(POInfoColumn columnInfo, Object value) { return objectToString(value, columnInfo.getDisplayType(), columnInfo.isMandatory()); } private String objectToString(final Object value, final int displayType, final boolean isMandatory) { if (value == null) { if (isMandatory) { logger.warn("Value is null even if is marked to be mandatory [Returning null]"); } return null; } // final String valueStr; if (DisplayType.isDate(displayType)) {
valueStr = dateTimeFormat.format(value); } else if (DisplayType.YesNo == displayType) { if (value instanceof Boolean) { valueStr = ((Boolean)value) ? "true" : "false"; } else { valueStr = "Y".equals(value) ? "true" : "false"; } return valueStr; } else { valueStr = value.toString(); } return valueStr; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\util\DefaultDataConverter.java
1
请完成以下Java代码
public class X_K_Category extends PO implements I_K_Category, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_K_Category (Properties ctx, int K_Category_ID, String trxName) { super (ctx, K_Category_ID, trxName); /** if (K_Category_ID == 0) { setK_Category_ID (0); setName (null); } */ } /** Load Constructor */ public X_K_Category (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_K_Category[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Knowledge Category. @param K_Category_ID Knowledge Category */ public void setK_Category_ID (int K_Category_ID) { if (K_Category_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Category_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Category_ID, Integer.valueOf(K_Category_ID)); } /** Get Knowledge Category. @return Knowledge Category */ public int getK_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Category.java
1
请在Spring Boot框架中完成以下Java代码
public Result modifyLocation(LocationUpdateReq locationUpdateReq, HttpServletRequest httpReq) { // 获取UserID String userId = getUserId(httpReq); // 修改收货地址 userService.modifyLocation(locationUpdateReq, userId); // 修改成功 return newSuccessResult(); } /** * 处理登录成功 * @param userEntity 用户信息 * @param httpRsp HTTP响应参数 */ private void doLoginSuccess(UserEntity userEntity, HttpServletResponse httpRsp) { // 生成SessionID String sessionID = RedisPrefixUtil.SessionID_Prefix + KeyGenerator.getKey(); // 将 SessionID-UserEntity 存入Redis // TODO 暂时存储本地 // redisService.set(sessionID, userEntity, sessionExpireTime); RedisServiceTemp.userMap.put(sessionID, userEntity); // 将SessionID存入HTTP响应头 Cookie cookie = new Cookie(sessionIdName, sessionID); httpRsp.addCookie(cookie); } /** * 获取SessionID * @param request 当前的请求对象 * @return SessionID的值 */ private String getSessionID(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); // 遍历所有cookie,找出SessionID String sessionID = null; if (cookies!=null && cookies.length>0) { for (Cookie cookie : cookies) { if (sessionIdName.equals(cookie.getName())) { sessionID = cookie.getValue(); break; } } } return sessionID; } /**
* 获取SessionID对应的用户信息 * @param sessionID * @return */ private UserEntity getUserEntity(String sessionID) { // SessionID为空 if (StringUtils.isEmpty(sessionID)) { return null; } // 获取UserEntity // TODO 暂时存储本地 // Object userEntity = redisService.get(sessionID); Object userEntity = RedisServiceTemp.userMap.get(sessionID); if (userEntity==null) { return null; } return (UserEntity) userEntity; } /** * 获取用户ID * @param httpReq HTTP请求 * @return 用户ID */ private String getUserId(HttpServletRequest httpReq) { UserEntity userEntity = userUtil.getUser(httpReq); if (userEntity == null) { throw new CommonBizException(ExpCodeEnum.UNLOGIN); } return userEntity.getId(); } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Controller\src\main\java\com\gaoxi\controller\user\UserControllerImpl.java
2
请完成以下Java代码
public PageData<CalculatedField> findByEntityIdAndTypes(TenantId tenantId, EntityId entityId, Set<CalculatedFieldType> types, PageLink pageLink) { log.debug("Try to find calculated fields by entityId [{}] and type [{}] and pageLink [{}]", entityId, types, pageLink); return DaoUtil.toPageData(calculatedFieldRepository.findByTenantIdAndEntityIdAndTypes(tenantId.getId(), entityId.getId(), types.stream().map(Enum::name).toList(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override @Transactional public List<CalculatedField> removeAllByEntityId(TenantId tenantId, EntityId entityId) { return DaoUtil.convertDataList(calculatedFieldRepository.removeAllByTenantIdAndEntityId(tenantId.getId(), entityId.getId())); } @Override public long countByEntityIdAndTypeNot(TenantId tenantId, EntityId entityId, CalculatedFieldType type) { return calculatedFieldRepository.countByTenantIdAndEntityIdAndTypeNot(tenantId.getId(), entityId.getId(), type.name()); } @Override public PageData<CalculatedField> findByTenantIdAndFilter(TenantId tenantId, CalculatedFieldFilter filter, PageLink pageLink) { return DaoUtil.toPageData(calculatedFieldRepository.findByTenantIdAndFilter(tenantId.getId(), filter.getTypes().stream().map(Enum::name).toList(), filter.getEntityTypes().stream().map(Enum::name).toList(), CollectionUtils.isNotEmpty(filter.getEntityIds()) ? filter.getEntityIds() : null, CollectionUtils.isNotEmpty(filter.getNames()) ? filter.getNames() : null, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink)));
} @Override public PageData<String> findNamesByTenantIdAndType(TenantId tenantId, CalculatedFieldType type, PageLink pageLink) { return DaoUtil.pageToPageData(calculatedFieldRepository.findNamesByTenantIdAndType(tenantId.getId(), type.name(), Strings.emptyToNull(pageLink.getTextSearch()), DaoUtil.toPageable(pageLink, false))); } @Override protected Class<CalculatedFieldEntity> getEntityClass() { return CalculatedFieldEntity.class; } @Override protected JpaRepository<CalculatedFieldEntity, UUID> getRepository() { return calculatedFieldRepository; } @Override public EntityType getEntityType() { return EntityType.CALCULATED_FIELD; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\cf\JpaCalculatedFieldDao.java
1
请完成以下Java代码
public @NonNull String getColumnSql(@NonNull String columnName) { final StringBuilder sb = new StringBuilder(); sb.append(SQL_FUNC_AddHours).append("("); sb.append(columnName); // Param 1: Date Column sb.append(", "); sb.append(hoursColumnSql); // Param 2: Hours Column sb.append(")"); return sb.toString(); } @Override public String getValueSql(Object value, List<Object> params) { return NullQueryFilterModifier.instance.getValueSql(value, params); } @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable Object value, final @Nullable Object model) { // // Constant: don't change the value // because this is the second operand with which we are comparing... if (columnName == null || columnName == COLUMNNAME_Constant) { return value; } // // ColumnName: add Hours to it else { final Date dateTime = toDate(value);
if (dateTime == null) { return null; } final int hoursToAdd = getHours(model); return TimeUtil.addHours(dateTime, hoursToAdd); } } private int getHours(final Object model) { final Optional<Number> hours = InterfaceWrapperHelper.getValue(model, hoursColumnSql); if (!hours.isPresent()) { return 0; } return hours.get().intValue(); } private Date toDate(final Object value) { final Date date = (Date)value; return date; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AddHoursQueryFilterModifier.java
1
请完成以下Java代码
private IPPOrderReceiptHUProducer newReceiptCandidatesProducer() { final PPOrderLineRow row = getSingleSelectedRow(); final PPOrderLineType type = row.getType(); if (type == PPOrderLineType.MainProduct) { final PPOrderId ppOrderId = row.getOrderId(); return huPPOrderBL.receivingMainProduct(ppOrderId); } else if (type == PPOrderLineType.BOMLine_ByCoProduct) { final PPOrderBOMLineId ppOrderBOMLineId = row.getOrderBOMLineId(); return huPPOrderBL.receivingByOrCoProduct(ppOrderBOMLineId); } else
{ throw new AdempiereException("Receiving is not allowed"); } } @NonNull private Quantity getIndividualCUsCount() { if (p_NumberOfCUs <= 0) { throw new FillMandatoryException(PARAM_NumberOfCUs); } return Quantity.of(p_NumberOfCUs, getSingleSelectedRow().getUomNotNull()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Receipt.java
1
请完成以下Java代码
private static Integer computeQtyTUs(@NonNull final JsonHUType unitType, final List<JsonHU> includedHUs) { if (unitType == JsonHUType.LU) { return includedHUs.stream() .mapToInt(tu -> tu.isAggregatedTU() ? tu.numberOfAggregatedHUs : 1) .sum(); } else { return null; } } public JsonHU withIsDisposalPending(@Nullable final Boolean isDisposalPending) { return Objects.equals(this.isDisposalPending, isDisposalPending) ? this : toBuilder().isDisposalPending(isDisposalPending).build(); } public JsonHU withDisplayedAttributesOnly(@Nullable final List<String> displayedAttributeCodesOnly) { if (displayedAttributeCodesOnly == null || displayedAttributeCodesOnly.isEmpty()) { return this; } final JsonHUAttributes attributes2New = attributes2.retainOnlyAttributesInOrder(displayedAttributeCodesOnly); if (Objects.equals(attributes2New, this.attributes2)) { return this; } return toBuilder() .attributes2(attributes2New) .attributes(attributes2New.toJsonHUAttributeCodeAndValues()) .build(); }
public JsonHU withLayoutSections(@Nullable List<String> layoutSections) { final ImmutableList<String> layoutSectionsNorm = layoutSections == null || layoutSections.isEmpty() ? null : ImmutableList.copyOf(layoutSections); if (Objects.equals(layoutSectionsNorm, this.layoutSections)) { return this; } else { return toBuilder() .layoutSections(layoutSectionsNorm) .build(); } } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\handlingunits\JsonHU.java
1
请完成以下Java代码
public boolean isWriteOffApplied () { Object oo = get_Value(COLUMNNAME_IsWriteOffApplied); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) {
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_DunningDoc_Line_Source.java
1
请完成以下Java代码
public Collection<InputCaseParameter> getInputs() { return inputCollection.get(this); } public Collection<OutputCaseParameter> getOutputs() { return outputCollection.get(this); } public CasePlanModel getCasePlanModel() { return casePlanModelChild.getChild(this); } public void setCasePlanModel(CasePlanModel casePlanModel) { casePlanModelChild.setChild(this, casePlanModel); } public CaseFileModel getCaseFileModel() { return caseFileModelChild.getChild(this); } public void setCaseFileModel(CaseFileModel caseFileModel) { caseFileModelChild.setChild(this, caseFileModel); } public Integer getCamundaHistoryTimeToLive() { String ttl = getCamundaHistoryTimeToLiveString(); if (ttl != null) { return Integer.parseInt(ttl); } return null; } public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) { setCamundaHistoryTimeToLiveString(String.valueOf(historyTimeToLive)); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Case.class, CMMN_ELEMENT_CASE) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Case>() { public Case newInstance(ModelTypeInstanceContext instanceContext) { return new CaseImpl(instanceContext); } });
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); camundaHistoryTimeToLive = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); caseFileModelChild = sequenceBuilder.element(CaseFileModel.class) .build(); casePlanModelChild = sequenceBuilder.element(CasePlanModel.class) .build(); caseRolesCollection = sequenceBuilder.elementCollection(CaseRole.class) .build(); caseRolesChild = sequenceBuilder.element(CaseRoles.class) .build(); inputCollection = sequenceBuilder.elementCollection(InputCaseParameter.class) .build(); outputCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class) .build(); typeBuilder.build(); } @Override public String getCamundaHistoryTimeToLiveString() { return camundaHistoryTimeToLive.getValue(this); } @Override public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) { camundaHistoryTimeToLive.setValue(this, historyTimeToLive); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseImpl.java
1
请完成以下Java代码
public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) { Assert.notNull(request, "request cannot be null"); Assert.notNull(response, "response cannot be null"); if (authorizationRequest == null) { removeAuthorizationRequest(request, response); return; } String state = authorizationRequest.getState(); Assert.hasText(state, "authorizationRequest.state cannot be empty"); request.getSession().setAttribute(this.sessionAttributeName, authorizationRequest); } @Override public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request, HttpServletResponse response) { Assert.notNull(response, "response cannot be null"); OAuth2AuthorizationRequest authorizationRequest = loadAuthorizationRequest(request); if (authorizationRequest != null) { request.getSession().removeAttribute(this.sessionAttributeName); } return authorizationRequest;
} /** * Gets the state parameter from the {@link HttpServletRequest} * @param request the request to use * @return the state parameter or null if not found */ private String getStateParameter(HttpServletRequest request) { return request.getParameter(OAuth2ParameterNames.STATE); } private OAuth2AuthorizationRequest getAuthorizationRequest(HttpServletRequest request) { HttpSession session = request.getSession(false); return (session != null) ? (OAuth2AuthorizationRequest) session.getAttribute(this.sessionAttributeName) : null; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\HttpSessionOAuth2AuthorizationRequestRepository.java
1
请完成以下Java代码
public long getHeartbeatVersion() { return heartbeatVersion; } public void setHeartbeatVersion(long heartbeatVersion) { this.heartbeatVersion = heartbeatVersion; } public String getVersion() { return version; } public MachineInfo setVersion(String version) { this.version = version; return this; } public boolean isHealthy() { long delta = System.currentTimeMillis() - lastHeartbeat; return delta < DashboardConfig.getUnhealthyMachineMillis(); } /** * whether dead should be removed * * @return */ public boolean isDead() { if (DashboardConfig.getAutoRemoveMachineMillis() > 0) { long delta = System.currentTimeMillis() - lastHeartbeat; return delta > DashboardConfig.getAutoRemoveMachineMillis(); } return false; } public long getLastHeartbeat() { return lastHeartbeat; } public void setLastHeartbeat(long lastHeartbeat) { this.lastHeartbeat = lastHeartbeat; } @Override public int compareTo(MachineInfo o) { if (this == o) { return 0; } if (!port.equals(o.getPort())) { return port.compareTo(o.getPort()); } if (!StringUtil.equals(app, o.getApp())) { return app.compareToIgnoreCase(o.getApp()); } return ip.compareToIgnoreCase(o.getIp()); } @Override public String toString() { return new StringBuilder("MachineInfo {") .append("app='").append(app).append('\'') .append(",appType='").append(appType).append('\'') .append(", hostname='").append(hostname).append('\'') .append(", ip='").append(ip).append('\'') .append(", port=").append(port) .append(", heartbeatVersion=").append(heartbeatVersion) .append(", lastHeartbeat=").append(lastHeartbeat)
.append(", version='").append(version).append('\'') .append(", healthy=").append(isHealthy()) .append('}').toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof MachineInfo)) { return false; } MachineInfo that = (MachineInfo)o; return Objects.equals(app, that.app) && Objects.equals(ip, that.ip) && Objects.equals(port, that.port); } @Override public int hashCode() { return Objects.hash(app, ip, port); } /** * Information for log * * @return */ public String toLogString() { return app + "|" + ip + "|" + port + "|" + version; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\MachineInfo.java
1
请完成以下Java代码
public void addFailure(String failure) { failures.add(failure); } public List<String> getFailures() { return failures; } public boolean hasFailures() { return !failures.isEmpty() || !activityInstanceReports.isEmpty() || !transitionInstanceReports.isEmpty(); } public void writeTo(StringBuilder sb) { sb.append("Cannot migrate process instance '") .append(processInstanceId) .append("':\n"); for (String failure : failures) { sb.append("\t").append(failure).append("\n"); } for (MigratingActivityInstanceValidationReport report : activityInstanceReports) { sb.append("\tCannot migrate activity instance '") .append(report.getActivityInstanceId()) .append("':\n");
for (String failure : report.getFailures()) { sb.append("\t\t").append(failure).append("\n"); } } for (MigratingTransitionInstanceValidationReport report : transitionInstanceReports) { sb.append("\tCannot migrate transition instance '") .append(report.getTransitionInstanceId()) .append("':\n"); for (String failure : report.getFailures()) { sb.append("\t\t").append(failure).append("\n"); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\MigratingProcessInstanceValidationReportImpl.java
1
请完成以下Java代码
public class DefaultClockImpl implements org.flowable.common.engine.impl.runtime.Clock { private TimeZone timeZone; protected static volatile Calendar CURRENT_TIME; public DefaultClockImpl() { } public DefaultClockImpl(TimeZone timeZone) { this.timeZone = timeZone; } @Override public void setCurrentTime(Date currentTime) { Calendar time = null; if (currentTime != null) { time = (timeZone == null) ? new GregorianCalendar() : new GregorianCalendar(timeZone); time.setTime(currentTime); } setCurrentCalendar(time); } @Override public void setCurrentCalendar(Calendar currentTime) { CURRENT_TIME = currentTime; } @Override public void reset() { CURRENT_TIME = null; } @Override public Date getCurrentTime() { return CURRENT_TIME == null ? new Date() : CURRENT_TIME.getTime();
} @Override public Calendar getCurrentCalendar() { if (CURRENT_TIME == null) { return (timeZone == null) ? new GregorianCalendar() : new GregorianCalendar(timeZone); } return (Calendar) CURRENT_TIME.clone(); } @Override public Calendar getCurrentCalendar(TimeZone timeZone) { return TimeZoneUtil.convertToTimeZone(getCurrentCalendar(), timeZone); } @Override public TimeZone getCurrentTimeZone() { return getCurrentCalendar().getTimeZone(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\util\DefaultClockImpl.java
1
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public String getImplementationType() { return implementationType; } public void setImplementationType(String implementationType) { this.implementationType = implementationType; } public String getOperationRef() { return operationRef; } public void setOperationRef(String operationRef) { this.operationRef = operationRef; }
public SendTask clone() { SendTask clone = new SendTask(); clone.setValues(this); return clone; } public void setValues(SendTask otherElement) { super.setValues(otherElement); setType(otherElement.getType()); setImplementationType(otherElement.getImplementationType()); setOperationRef(otherElement.getOperationRef()); fieldExtensions = new ArrayList<FieldExtension>(); if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherElement.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SendTask.java
1
请完成以下Java代码
public Set<String> getScopes() { return this.scopes; } /** * Access Token Types. * * @see <a target="_blank" href= * "https://tools.ietf.org/html/rfc6749#section-7.1">Section 7.1 Access Token * Types</a> */ public static final class TokenType implements Serializable { private static final long serialVersionUID = 620L; public static final TokenType BEARER = new TokenType("Bearer"); /** * @since 6.5 */ public static final TokenType DPOP = new TokenType("DPoP"); private final String value; /** * Constructs a {@code TokenType} using the provided value. * @param value the value of the token type * @since 6.5 */ public TokenType(String value) { Assert.hasText(value, "value cannot be empty"); this.value = value; } /** * Returns the value of the token type. * @return the value of the token type */ public String getValue() { return this.value; }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } TokenType that = (TokenType) obj; return this.getValue().equalsIgnoreCase(that.getValue()); } @Override public int hashCode() { return this.getValue().hashCode(); } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2AccessToken.java
1
请完成以下Java代码
protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) { UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null; if (processInstanceIds != null) { groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds); } if (processInstanceQuery != null) { if (groupBuilder == null) { groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); } else { groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); } } if (historicProcessInstanceQuery != null) { if (groupBuilder == null) {
groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); } else { groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); } } return groupBuilder; } protected int parameterCount(Object... o) { int count = 0; for (Object o1 : o) { count += (o1 != null ? 1 : 0); } return count; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ProcessInstanceSuspensionStateAsyncDto.java
1
请完成以下Java代码
public RouterFunctions.Builder resources(Function<ServerRequest, Optional<Resource>> lookupFunction, BiConsumer<Resource, HttpHeaders> headersConsumer) { builder.resources(lookupFunction, headersConsumer); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder nest(RequestPredicate predicate, Supplier<RouterFunction<T>> routerFunctionSupplier) { builder.nest(predicate, routerFunctionSupplier); return this; } @Override public RouterFunctions.Builder nest(RequestPredicate predicate, Consumer<RouterFunctions.Builder> builderConsumer) { builder.nest(predicate, builderConsumer); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder path(String pattern, Supplier<RouterFunction<T>> routerFunctionSupplier) { builder.path(pattern, routerFunctionSupplier); return this; } @Override public RouterFunctions.Builder path(String pattern, Consumer<RouterFunctions.Builder> builderConsumer) { builder.path(pattern, builderConsumer); return this; } @Override public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder filter( HandlerFilterFunction<T, R> filterFunction) { builder.filter(filterFunction); return this; } @Override public RouterFunctions.Builder before(Function<ServerRequest, ServerRequest> requestProcessor) {
builder.before(requestProcessor); return this; } @Override public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder after( BiFunction<ServerRequest, T, R> responseProcessor) { builder.after(responseProcessor); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder onError(Predicate<Throwable> predicate, BiFunction<Throwable, ServerRequest, T> responseProvider) { builder.onError(predicate, responseProvider); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder onError(Class<? extends Throwable> exceptionType, BiFunction<Throwable, ServerRequest, T> responseProvider) { builder.onError(exceptionType, responseProvider); return this; } @Override public RouterFunctions.Builder withAttribute(String name, Object value) { builder.withAttribute(name, value); return this; } @Override public RouterFunctions.Builder withAttributes(Consumer<Map<String, Object>> attributesConsumer) { builder.withAttributes(attributesConsumer); return this; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayRouterFunctionsBuilder.java
1
请完成以下Java代码
public String toString() { return ObjectUtils.toString(this); } public void addListener(final IAggregationListener listener) { if (listener == null) { return; } listeners.addIfAbsent(listener); } @Override public void onAggregationCreated(final I_C_Aggregation aggregation) { for (final IAggregationListener listener : listeners) { listener.onAggregationCreated(aggregation); } }
@Override public void onAggregationChanged(final I_C_Aggregation aggregation) { for (final IAggregationListener listener : listeners) { listener.onAggregationChanged(aggregation); } } @Override public void onAggregationDeleted(final I_C_Aggregation aggregation) { for (final IAggregationListener listener : listeners) { listener.onAggregationDeleted(aggregation); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\listeners\impl\CompositeAggregationListener.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONDashboardItem { public static JSONDashboardItem of( @NonNull final UserDashboardItem item, @Nullable final UserDashboardItemDataResponse itemData, @NonNull final KPIJsonOptions jsonOpts) { return new JSONDashboardItem(item, itemData, jsonOpts); } int id; String caption; int seqNo; @JsonInclude(JsonInclude.Include.NON_EMPTY) String url; @JsonInclude(JsonInclude.Include.NON_NULL) JsonKPILayout kpi; @JsonInclude(JsonInclude.Include.NON_NULL) JsonKPIDataResult data; private JSONDashboardItem( @NonNull final UserDashboardItem item, @Nullable final UserDashboardItemDataResponse itemData, @NonNull final KPIJsonOptions jsonOpts) { this.id = item.getId().getRepoId();
this.caption = extractCaption(item, item.getKPI(), jsonOpts); this.seqNo = item.getSeqNo(); this.url = item.getUrl(); this.kpi = JsonKPILayout.of(item.getKPI(), jsonOpts); this.data = itemData != null ? JsonKPIDataResult.of(itemData, jsonOpts) : null; } private static String extractCaption(final @NonNull UserDashboardItem item, @NonNull final KPI kpi, final @NonNull KPIJsonOptions jsonOpts) { String caption = item.getCaption(jsonOpts.getAdLanguage()); if (jsonOpts.isDebugShowColumnNamesForCaption()) { caption = caption + " (" + item.getId() + ", kpiId=" + kpi.getId() + ")"; } return caption; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JSONDashboardItem.java
2
请在Spring Boot框架中完成以下Java代码
public List<UUID> findAll() { return CollUtil.newArrayList(DB.values()); } /** * 根据UserId查询SessionId * * @param userId 用户id * @return SessionId */ public Optional<UUID> findByUserId(String userId) { return Optional.ofNullable(DB.get(userId)); } /** * 保存/更新 user_id <-> session_id 的关系 * * @param userId 用户id * @param sessionId SessionId
*/ public void save(String userId, UUID sessionId) { DB.put(userId, sessionId); } /** * 删除 user_id <-> session_id 的关系 * * @param userId 用户id */ public void deleteByUserId(String userId) { DB.remove(userId); } }
repos\spring-boot-demo-master\demo-websocket-socketio\src\main\java\com\xkcoding\websocket\socketio\config\DbTemplate.java
2
请完成以下Java代码
public void setRefundAmt (java.math.BigDecimal RefundAmt) { set_Value (COLUMNNAME_RefundAmt, RefundAmt); } /** Get Rückvergütungsbetrag. @return Rückvergütungsbetrag pro Produkt-Einheit */ @Override public java.math.BigDecimal getRefundAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RefundAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** * RefundBase AD_Reference_ID=540902 * Reference name: RefundBase */ public static final int REFUNDBASE_AD_Reference_ID=540902; /** percentage = P */ public static final String REFUNDBASE_Percentage = "P"; /** amount = F */ public static final String REFUNDBASE_Amount = "F"; /** Set Vergütung basiert auf. @param RefundBase Vergütung basiert auf */ @Override public void setRefundBase (java.lang.String RefundBase) { set_Value (COLUMNNAME_RefundBase, RefundBase); } /** Get Vergütung basiert auf. @return Vergütung basiert auf */ @Override public java.lang.String getRefundBase () { return (java.lang.String)get_Value(COLUMNNAME_RefundBase); } /** * RefundInvoiceType AD_Reference_ID=540863 * Reference name: RefundInvoiceType */ public static final int REFUNDINVOICETYPE_AD_Reference_ID=540863; /** Invoice = Invoice */ public static final String REFUNDINVOICETYPE_Invoice = "Invoice"; /** Creditmemo = Creditmemo */ public static final String REFUNDINVOICETYPE_Creditmemo = "Creditmemo"; /** Set Rückvergütung per. @param RefundInvoiceType Rückvergütung per */ @Override public void setRefundInvoiceType (java.lang.String RefundInvoiceType) { set_Value (COLUMNNAME_RefundInvoiceType, RefundInvoiceType); } /** Get Rückvergütung per. @return Rückvergütung per */ @Override public java.lang.String getRefundInvoiceType () { return (java.lang.String)get_Value(COLUMNNAME_RefundInvoiceType); } /** * RefundMode AD_Reference_ID=540903 * Reference name: RefundMode */
public static final int REFUNDMODE_AD_Reference_ID=540903; /** Tiered = T */ public static final String REFUNDMODE_Tiered = "T"; /** Accumulated = A */ public static final String REFUNDMODE_Accumulated = "A"; /** Set Staffel-Modus. @param RefundMode Staffel-Modus */ @Override public void setRefundMode (java.lang.String RefundMode) { set_Value (COLUMNNAME_RefundMode, RefundMode); } /** Get Staffel-Modus. @return Staffel-Modus */ @Override public java.lang.String getRefundMode () { return (java.lang.String)get_Value(COLUMNNAME_RefundMode); } /** Set Rückvergütung %. @param RefundPercent Rückvergütung % */ @Override public void setRefundPercent (java.math.BigDecimal RefundPercent) { set_Value (COLUMNNAME_RefundPercent, RefundPercent); } /** Get Rückvergütung %. @return Rückvergütung % */ @Override public java.math.BigDecimal getRefundPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RefundPercent); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_RefundConfig.java
1
请完成以下Java代码
protected <T> void exceptionWhileClosingResourceStream(T response, IOException e) { logError( "003", "Exception while closing resource stream of response '" + response + "': ", e); } protected <T> EngineClientException exceptionWhileParsingJsonObject(Class<T> responseDtoClass, Throwable t) { return new EngineClientException(exceptionMessage( "004", "Exception while parsing json object to response dto class '{}'", responseDtoClass), t); } protected <T> EngineClientException exceptionWhileMappingJsonObject(Class<T> responseDtoClass, Throwable t) { return new EngineClientException(exceptionMessage( "005", "Exception while mapping json object to response dto class '{}'", responseDtoClass), t); }
protected <T> EngineClientException exceptionWhileDeserializingJsonObject(Class<T> responseDtoClass, Throwable t) { return new EngineClientException(exceptionMessage( "006", "Exception while deserializing json object to response dto class '{}'", responseDtoClass), t); } protected <D extends RequestDto> EngineClientException exceptionWhileSerializingJsonObject(D dto, Throwable t) { return new EngineClientException(exceptionMessage( "007", "Exception while serializing json object to '{}'", dto), t); } public void requestInterceptorException(Throwable e) { logError( "008", "Exception while executing request interceptor: {}", e); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClientLogger.java
1
请在Spring Boot框架中完成以下Java代码
public class HelloWorldServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HelloWorldServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = null; try { out = response.getWriter(); out.println("HelloWorldServlet: GET METHOD"); out.flush(); } finally { if (!Objects.isNull(out)) out.close(); }
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = null; try { out = response.getWriter(); out.println("HelloWorldServlet: POST METHOD"); out.flush(); } finally { if (!Objects.isNull(out)) out.close(); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-4\src\main\java\com\baeldung\boot\controller\servlet\HelloWorldServlet.java
2
请完成以下Java代码
public static PPOrderBOMLineId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PPOrderBOMLineId(repoId) : null; } public static Optional<PPOrderBOMLineId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final PPOrderBOMLineId id) { return id != null ? id.getRepoId() : -1; } int repoId; private PPOrderBOMLineId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_BOMLine_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final PPOrderBOMLineId id1, @Nullable final PPOrderBOMLineId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\eevolution\api\PPOrderBOMLineId.java
1
请完成以下Java代码
public class AtomicOperationProcessStart extends AbstractEventAtomicOperation { @Override protected ScopeImpl getScope(InterpretableExecution execution) { return execution.getProcessDefinition(); } @Override protected String getEventName() { return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_START; } @Override protected void eventNotificationsCompleted(InterpretableExecution execution) { if (Context.getProcessEngineConfiguration() != null && Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Map<String, Object> variablesMap = null; try { variablesMap = execution.getVariables(); } catch (Throwable t) {
// In some rare cases getting the execution variables can fail (JPA entity load failure for example) // We ignore the exception here, because it's only meant to include variables in the initialized event. } Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityWithVariablesEvent(FlowableEngineEventType.ENTITY_INITIALIZED, execution, variablesMap, false), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); Context.getProcessEngineConfiguration().getEventDispatcher() .dispatchEvent(ActivitiEventBuilder.createProcessStartedEvent(execution, variablesMap, false), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); } ProcessDefinitionImpl processDefinition = execution.getProcessDefinition(); StartingExecution startingExecution = execution.getStartingExecution(); List<ActivityImpl> initialActivityStack = processDefinition.getInitialActivityStack(startingExecution.getInitial()); execution.setActivity(initialActivityStack.get(0)); execution.performOperation(PROCESS_START_INITIAL); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationProcessStart.java
1
请完成以下Java代码
protected String generateCSRFToken() { byte random[] = new byte[16]; // Render the result as a String of hexadecimal digits StringBuilder buffer = new StringBuilder(); randomSource.nextBytes(random); for (int j = 0; j < random.length; j++) { byte b1 = (byte) ((random[j] & 0xf0) >> 4); byte b2 = (byte) (random[j] & 0x0f); if (b1 < 10) { buffer.append((char) ('0' + b1)); } else { buffer.append((char) ('A' + (b1 - 10))); } if (b2 < 10) { buffer.append((char) ('0' + b2)); } else { buffer.append((char) ('A' + (b2 - 10))); } } return buffer.toString(); } private Object getCSRFTokenSession(HttpSession session) { return session.getAttribute(CsrfConstants.CSRF_TOKEN_SESSION_ATTR_NAME); } private String getCSRFTokenHeader(HttpServletRequest request) { return request.getHeader(CsrfConstants.CSRF_TOKEN_HEADER_NAME); } private Object getSessionMutex(HttpSession session) { if (session == null) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "HttpSession is missing"); } Object mutex = session.getAttribute(CsrfConstants.CSRF_SESSION_MUTEX);
if (mutex == null) { mutex = session; } return mutex; } private boolean isBlank(String s) { return s == null || s.trim().isEmpty(); } private String getRequestedPath(HttpServletRequest request) { String path = request.getServletPath(); if (request.getPathInfo() != null) { path = path + request.getPathInfo(); } return path; } private Set<String> parseURLs(String urlString) { Set<String> urlSet = new HashSet<>(); if (urlString != null && !urlString.isEmpty()) { String values[] = urlString.split(","); for (String value : values) { urlSet.add(value.trim()); } } return urlSet; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\CsrfPreventionFilter.java
1
请完成以下Java代码
public void setRemote_Addr (String Remote_Addr) { set_Value (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_Value (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Reply. @param Reply
Reply or Answer */ public void setReply (String Reply) { set_Value (COLUMNNAME_Reply, Reply); } /** Get Reply. @return Reply or Answer */ public String getReply () { return (String)get_Value(COLUMNNAME_Reply); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AccessLog.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(status, noteText, patientId, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientNote {\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).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-patient-api\src\main\java\io\swagger\client\model\PatientNote.java
2
请在Spring Boot框架中完成以下Java代码
public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String email; private String password; @Transient private String currentDevice; // Needed for Hibernate mapping public User() { } public User(String email, String password, String currentDevice) { this.email = email; this.password = password; this.currentDevice = currentDevice; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCurrentDevice() { return currentDevice; } public void setCurrentDevice(String currentDevice) { this.currentDevice = currentDevice; } @Override public String toString() { return new StringJoiner(", ", User.class.getSimpleName() + "[", "]").add("id=" + id) .add("email='" + email + "'") .add("password='" + password + "'") .add("currentDevice='" + currentDevice + "'") .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return email.equals(user.email); } }
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\ignorable\fields\User.java
2
请完成以下Java代码
public Process getParentProcess() { return parentProcess; } public void setParentProcess(Process parentProcess) { this.parentProcess = parentProcess; } public List<String> getFlowReferences() { return flowReferences; } public void setFlowReferences(List<String> flowReferences) { this.flowReferences = flowReferences; } public Lane clone() { Lane clone = new Lane();
clone.setValues(this); return clone; } public void setValues(Lane otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setParentProcess(otherElement.getParentProcess()); flowReferences = new ArrayList<String>(); if (otherElement.getFlowReferences() != null && !otherElement.getFlowReferences().isEmpty()) { flowReferences.addAll(otherElement.getFlowReferences()); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Lane.java
1
请完成以下Java代码
public class DmnDecisionTableImpl implements DmnDecisionLogic { protected DmnHitPolicyHandler hitPolicyHandler; protected List<DmnDecisionTableInputImpl> inputs = new ArrayList<DmnDecisionTableInputImpl>(); protected List<DmnDecisionTableOutputImpl> outputs = new ArrayList<DmnDecisionTableOutputImpl>(); protected List<DmnDecisionTableRuleImpl> rules = new ArrayList<DmnDecisionTableRuleImpl>(); public DmnHitPolicyHandler getHitPolicyHandler() { return hitPolicyHandler; } public void setHitPolicyHandler(DmnHitPolicyHandler hitPolicyHandler) { this.hitPolicyHandler = hitPolicyHandler; } public List<DmnDecisionTableInputImpl> getInputs() { return inputs; } public void setInputs(List<DmnDecisionTableInputImpl> inputs) { this.inputs = inputs; } public List<DmnDecisionTableOutputImpl> getOutputs() { return outputs; } public void setOutputs(List<DmnDecisionTableOutputImpl> outputs) { this.outputs = outputs; } public List<DmnDecisionTableRuleImpl> getRules() {
return rules; } public void setRules(List<DmnDecisionTableRuleImpl> rules) { this.rules = rules; } @Override public String toString() { return "DmnDecisionTableImpl{" + " hitPolicyHandler=" + hitPolicyHandler + ", inputs=" + inputs + ", outputs=" + outputs + ", rules=" + rules + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionTableImpl.java
1
请完成以下Java代码
public synchronized BigDecimal acquireValue() { logger.debug("This: {}, Device: {}; Request: {}", this, device, request); final ISingleValueResponse response = device.accessDevice(request); logger.debug("Device {}; Response: {}", device, response); return response.getSingleValue(); } public synchronized void beforeAcquireValue(@NonNull final Map<String, List<String>> parameters) { final Map<String, List<String>> runParameters = Stream.concat(parameters.entrySet().stream(), getDeviceConfigParams().entrySet().stream()) .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue)); for (final BeforeAcquireValueHook hook : beforeHooks) { hook.run(RunParameters.of(runParameters), device, request); }
} public Optional<String> getConfigValue(@NonNull final String parameterName) { return deviceConfig.getDeviceConfigParamValue(parameterName); } @NonNull private Map<String, List<String>> getDeviceConfigParams() { return deviceConfig.getDeviceConfigParams() .entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> ImmutableList.of(entry.getValue()) )); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceAccessor.java
1
请完成以下Java代码
public void setIsUnique (boolean IsUnique) { set_Value (COLUMNNAME_IsUnique, Boolean.valueOf(IsUnique)); } /** Get Unique. @return Unique */ public boolean isUnique () { Object oo = get_Value(COLUMNNAME_IsUnique); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
} /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } @Override public String getBeforeChangeWarning() { return (String)get_Value(COLUMNNAME_BeforeChangeWarning); } @Override public void setBeforeChangeWarning(String BeforeChangeWarning) { set_Value (COLUMNNAME_BeforeChangeWarning, BeforeChangeWarning); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Table.java
1
请在Spring Boot框架中完成以下Java代码
public String getEncoding() { return encoding; } /** * Sets the value of the encoding property. * * @param value * allowed object is * {@link String } * */ public void setEncoding(String value) { this.encoding = value; } /** * Gets the value of the content property. * * @return * possible object is * {@link String } * */ public String getContent() { return content; } /** * Sets the value of the content property. * * @param value * allowed object is * {@link String } * */ public void setContent(String value) { this.content = value; } } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="Link" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name", "link" }) public static class LinkAttachment { @XmlElement(name = "Name") protected String name; @XmlElement(name = "Link", required = true) protected String link; /** * Gets the value of the name property.
* * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the link property. * * @return * possible object is * {@link String } * */ public String getLink() { return link; } /** * Sets the value of the link property. * * @param value * allowed object is * {@link String } * */ public void setLink(String value) { this.link = value; } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AttachmentsType.java
2
请完成以下Java代码
static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) { var x = cars.poll(); var y = cars.poll(); var z = cars.poll(); return x; } static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) { var car = cars.poll(); var _ = cars.poll(); var _ = cars.poll(); return car; } static void handleCarExceptionWithNamedVariables(Car<?> car) { try { someOperationThatFails(car); } catch (IllegalStateException ex) { System.out.println("Got an illegal state exception for: " + car.name()); } catch (RuntimeException ex) { System.out.println("Got a runtime exception!"); } } static void handleCarExceptionWithUnnamedVariables(Car<?> car) { try { someOperationThatFails(car); } catch (IllegalStateException | NumberFormatException _) { System.out.println("Got an illegal state exception for: " + car.name()); } catch (RuntimeException _) { System.out.println("Got a runtime exception!"); } } static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) { try (var transaction = new Transaction()) { updateCar(car); } } static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
try (var _ = new Transaction()) { updateCar(car); } } static void updateCar(Car<?> car) { // Some update logic System.out.println("Car updated!"); } static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) { Map<String, List<Car<?>>> carMap = new HashMap<>(); cars.forEach(car -> carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car) ); return carMap; } static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) { Map<String, List<Car<?>>> carMap = new HashMap<>(); cars.forEach(car -> carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car) ); return carMap; } private static void someOperationThatFails(Car<?> car) { throw new IllegalStateException("Triggered exception for: " + car.name()); } }
repos\tutorials-master\core-java-modules\core-java-21\src\main\java\com\baeldung\unnamed\variables\UnnamedVariables.java
1
请完成以下Java代码
public static MaterialRequest mkRequest( @NonNull final SupplyRequiredDescriptor supplyRequiredDescriptor, @NonNull final MaterialPlanningContext context) { return MaterialRequest.builder() .qtyToSupply(getQuantity(supplyRequiredDescriptor)) .context(context) .mrpDemandBPartnerId(BPartnerId.toRepoIdOr(supplyRequiredDescriptor.getCustomerId(), -1)) .mrpDemandOrderLineSOId(supplyRequiredDescriptor.getOrderLineId()) .mrpDemandShipmentScheduleId(supplyRequiredDescriptor.getShipmentScheduleId()) .demandDate(supplyRequiredDescriptor.getDemandDate()) .isSimulated(supplyRequiredDescriptor.isSimulated()) .build(); } private static @NonNull Quantity getQuantity(final @NonNull SupplyRequiredDescriptor supplyRequiredDescriptor) { final IProductBL productBL = Services.get(IProductBL.class); final ProductId productId = ProductId.ofRepoId(supplyRequiredDescriptor.getProductId()); final BigDecimal qtyToSupplyBD = supplyRequiredDescriptor.getQtyToSupplyBD(); final I_C_UOM uom = productBL.getStockUOM(productId); return Quantity.of(qtyToSupplyBD, uom); } public void updateQtySupplyRequired( @NonNull final MaterialDescriptor materialDescriptor, @NonNull final EventDescriptor eventDescriptor, @NonNull final BigDecimal qtySupplyRequiredDelta) {
if (qtySupplyRequiredDelta.signum() == 0) { return; } final IOrgDAO orgDAO = Services.get(IOrgDAO.class); final ZoneId orgTimezone = orgDAO.getTimeZone(eventDescriptor.getOrgId()); final MainDataRecordIdentifier mainDataRecordIdentifier = MainDataRecordIdentifier.createForMaterial(materialDescriptor, orgTimezone); mainDataRequestHandler.handleDataUpdateRequest( UpdateMainDataRequest.builder() .identifier(mainDataRecordIdentifier) .qtySupplyRequired(qtySupplyRequiredDelta) .build() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredHandlerUtils.java
1
请完成以下Java代码
public JacksonJsonSerde<T> forKeys() { this.jsonSerializer.forKeys(); this.jsonDeserializer.forKeys(); return this; } /** * Configure the serializer to not add type information. * @return the serde. */ public JacksonJsonSerde<T> noTypeInfo() { this.jsonSerializer.noTypeInfo(); return this; } /** * Don't remove type information headers after deserialization. * @return the serde. */ public JacksonJsonSerde<T> dontRemoveTypeHeaders() { this.jsonDeserializer.dontRemoveTypeHeaders(); return this;
} /** * Ignore type information headers and use the configured target class. * @return the serde. */ public JacksonJsonSerde<T> ignoreTypeHeaders() { this.jsonDeserializer.ignoreTypeHeaders(); return this; } /** * Use the supplied {@link JacksonJavaTypeMapper}. * @param mapper the mapper. * @return the serde. */ public JacksonJsonSerde<T> typeMapper(JacksonJavaTypeMapper mapper) { this.jsonSerializer.setTypeMapper(mapper); this.jsonDeserializer.setTypeMapper(mapper); return this; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\JacksonJsonSerde.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthorizationInterceptor implements HandlerInterceptor { @Autowired private AuthService<HttpServletRequest> authService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler.getClass().isAssignableFrom(HandlerMethod.class)) { Method method = ((HandlerMethod) handler).getMethod(); AuthAction authAction = method.getAnnotation(AuthAction.class); if (authAction != null) { AuthService.AuthUser authUser = authService.getAuthUser(request); if (authUser == null) { responseNoPrivilegeMsg(response, authAction.message()); return false; } String target = request.getParameter(authAction.targetName()); if (!authUser.authTarget(target, authAction.value())) {
responseNoPrivilegeMsg(response, authAction.message()); return false; } } } return true; } private void responseNoPrivilegeMsg(HttpServletResponse response, String message) throws IOException { Result result = Result.ofFail(-1, message); response.addHeader("Content-Type", "application/json;charset=UTF-8"); response.getOutputStream().write(JSON.toJSONBytes(result)); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\auth\AuthorizationInterceptor.java
2
请完成以下Java代码
public DocumentUserNotificationsProducer<ModelType> notify(final ModelType document, final UserId recipientUserId) { if (document == null) { return this; } try { postNotification(createUserNotification(document, recipientUserId)); } catch (final Exception e) { logger.warn("Failed creating event for {}. Ignored.", document, e); } return this; } private final UserNotificationRequest createUserNotification(@NonNull final ModelType document, final UserId recipientUserId) { Check.assumeNotNull(document, "document not null"); // // Get the recipient final UserId recipientUserIdToUse; if (recipientUserId != null) { recipientUserIdToUse = recipientUserId; } else { recipientUserIdToUse = extractRecipientUser(document); if (recipientUserIdToUse == null) { throw new AdempiereException("No recipient found for " + document); } } // // Extract event message parameters final List<Object> adMessageParams = extractEventMessageParams(document); // // Create an return the user notification return newUserNotificationRequest() .recipientUserId(recipientUserIdToUse) .contentADMessage(eventAD_Message) .contentADMessageParams(adMessageParams) .targetAction(TargetRecordAction.of(TableRecordReference.of(document))) .build(); }
private final UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(topic); } private List<Object> extractEventMessageParams(final ModelType document) { List<Object> params = eventAD_MessageParamsExtractor.apply(document); return params != null ? params : ImmutableList.of(); } private UserId extractRecipientUser(final ModelType document) { final Integer createdBy = InterfaceWrapperHelper.getValueOrNull(document, "CreatedBy"); return createdBy == null ? null : UserId.ofRepoIdOrNull(createdBy); } private void postNotification(final UserNotificationRequest notification) { notificationBL.sendAfterCommit(notification); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\DocumentUserNotificationsProducer.java
1
请完成以下Java代码
public void setReference (java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Referenz. @return Reference for this record */ @Override public java.lang.String getReference () { return (java.lang.String)get_Value(COLUMNNAME_Reference); } /** Set Mitteilung. @param TextMsg Text Message */ @Override public void setTextMsg (java.lang.String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Mitteilung. @return Text Message */ @Override public java.lang.String getTextMsg () { return (java.lang.String)get_Value(COLUMNNAME_TextMsg); } /** Set View ID. @param ViewId View ID */ @Override public void setViewId (java.lang.String ViewId) { set_Value (COLUMNNAME_ViewId, ViewId); } /** Get View ID. @return View ID */ @Override public java.lang.String getViewId () { return (java.lang.String)get_Value(COLUMNNAME_ViewId); } /** Set Sql WHERE. @param WhereClause Fully qualified SQL WHERE clause */ @Override public void setWhereClause (java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause
*/ @Override public java.lang.String getWhereClause () { return (java.lang.String)get_Value(COLUMNNAME_WhereClause); } /** * NotificationSeverity AD_Reference_ID=541947 * Reference name: NotificationSeverity */ public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947; /** Notice = Notice */ public static final String NOTIFICATIONSEVERITY_Notice = "Notice"; /** Warning = Warning */ public static final String NOTIFICATIONSEVERITY_Warning = "Warning"; /** Error = Error */ public static final String NOTIFICATIONSEVERITY_Error = "Error"; @Override public void setNotificationSeverity (final java.lang.String NotificationSeverity) { set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity); } @Override public java.lang.String getNotificationSeverity() { return get_ValueAsString(COLUMNNAME_NotificationSeverity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java
1
请完成以下Java代码
public String getContentType() { return CONTENT_TYPE; } @Override public long getLastModified() { if (this.lastModified == -1) { try { this.lastModified = Files.getLastModifiedTime(this.resources.getLocation().path()).toMillis(); } catch (IOException ex) { this.lastModified = 0; } } return this.lastModified; } @Override public Permission getPermission() throws IOException { if (this.permission == null) { File file = this.resources.getLocation().path().toFile(); this.permission = new FilePermission(file.getCanonicalPath(), "read"); } return this.permission; } @Override public InputStream getInputStream() throws IOException { connect(); return new ConnectionInputStream(this.resources.getInputStream()); } @Override public void connect() throws IOException { if (this.connected) { return; } this.resources.connect(); this.connected = true; } /** * Connection {@link InputStream}.
*/ class ConnectionInputStream extends FilterInputStream { private volatile boolean closing; ConnectionInputStream(InputStream in) { super(in); } @Override public void close() throws IOException { if (this.closing) { return; } this.closing = true; try { super.close(); } finally { try { NestedUrlConnection.this.cleanup.clean(); } catch (UncheckedIOException ex) { throw ex.getCause(); } } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnection.java
1
请完成以下Java代码
public HistoricExternalTaskLogResource getHistoricExternalTaskLog(String historicExternalTaskLogId) { return new HistoricExternalTaskLogResourceImpl(historicExternalTaskLogId, processEngine); } @Override public List<HistoricExternalTaskLogDto> getHistoricExternalTaskLogs(UriInfo uriInfo, Integer firstResult, Integer maxResults) { HistoricExternalTaskLogQueryDto queryDto = new HistoricExternalTaskLogQueryDto(objectMapper, uriInfo.getQueryParameters()); return queryHistoricExternalTaskLogs(queryDto, firstResult, maxResults); } @Override public List<HistoricExternalTaskLogDto> queryHistoricExternalTaskLogs(HistoricExternalTaskLogQueryDto queryDto, Integer firstResult, Integer maxResults) { queryDto.setObjectMapper(objectMapper); HistoricExternalTaskLogQuery query = queryDto.toQuery(processEngine); List<HistoricExternalTaskLog> matchingHistoricExternalTaskLogs = QueryUtil.list(query, firstResult, maxResults); List<HistoricExternalTaskLogDto> results = new ArrayList<HistoricExternalTaskLogDto>(); for (HistoricExternalTaskLog historicExternalTaskLog : matchingHistoricExternalTaskLogs) { HistoricExternalTaskLogDto result = HistoricExternalTaskLogDto.fromHistoricExternalTaskLog(historicExternalTaskLog); results.add(result); }
return results; } @Override public CountResultDto getHistoricExternalTaskLogsCount(UriInfo uriInfo) { HistoricExternalTaskLogQueryDto queryDto = new HistoricExternalTaskLogQueryDto(objectMapper, uriInfo.getQueryParameters()); return queryHistoricExternalTaskLogsCount(queryDto); } @Override public CountResultDto queryHistoricExternalTaskLogsCount(HistoricExternalTaskLogQueryDto queryDto) { queryDto.setObjectMapper(objectMapper); HistoricExternalTaskLogQuery query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricExternalTaskLogRestServiceImpl.java
1
请完成以下Java代码
public T buildAccessor() { this.accessorFunction.accept(new Accessor(this)); return this.parent; } } static final class Accessor implements Annotatable { private final AnnotationContainer annotations; private final CodeBlock code; Accessor(AccessorBuilder<?> builder) { this.annotations = builder.annotations.deepCopy();
this.code = builder.code; } CodeBlock getCode() { return this.code; } @Override public AnnotationContainer annotations() { return this.annotations; } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
GitProperties gitProperties() throws Exception { return new GitProperties( loadFrom(this.properties.getGit().getLocation(), "git", this.properties.getGit().getEncoding())); } @ConditionalOnResource(resources = "${spring.info.build.location:classpath:META-INF/build-info.properties}") @ConditionalOnMissingBean @Bean BuildProperties buildProperties() throws Exception { return new BuildProperties( loadFrom(this.properties.getBuild().getLocation(), "build", this.properties.getBuild().getEncoding())); } protected Properties loadFrom(Resource location, String prefix, Charset encoding) throws IOException { prefix = prefix.endsWith(".") ? prefix : prefix + "."; Properties source = loadSource(location, encoding); Properties target = new Properties(); for (String key : source.stringPropertyNames()) { if (key.startsWith(prefix)) { target.put(key.substring(prefix.length()), source.get(key)); } } return target; } private Properties loadSource(Resource location, @Nullable Charset encoding) throws IOException { if (encoding != null) { return PropertiesLoaderUtils.loadProperties(new EncodedResource(location, encoding)); } return PropertiesLoaderUtils.loadProperties(location); }
static class GitResourceAvailableCondition extends SpringBootCondition { @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { ResourceLoader loader = context.getResourceLoader(); Environment environment = context.getEnvironment(); String location = environment.getProperty("spring.info.git.location"); if (location == null) { location = "classpath:git.properties"; } ConditionMessage.Builder message = ConditionMessage.forCondition("GitResource"); if (loader.getResource(location).exists()) { return ConditionOutcome.match(message.found("git info at").items(location)); } return ConditionOutcome.noMatch(message.didNotFind("git info at").items(location)); } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\info\ProjectInfoAutoConfiguration.java
2
请完成以下Java代码
public org.compiere.model.I_C_Currency getLastSalesPrice_Currency() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_LastSalesPrice_Currency_ID, org.compiere.model.I_C_Currency.class); } @Override public void setLastSalesPrice_Currency(org.compiere.model.I_C_Currency LastSalesPrice_Currency) { set_ValueFromPO(COLUMNNAME_LastSalesPrice_Currency_ID, org.compiere.model.I_C_Currency.class, LastSalesPrice_Currency); } /** Set Letzter VK Währung. @param LastSalesPrice_Currency_ID Letzter Verkaufspreis Währung */ @Override public void setLastSalesPrice_Currency_ID (int LastSalesPrice_Currency_ID) { if (LastSalesPrice_Currency_ID < 1) set_Value (COLUMNNAME_LastSalesPrice_Currency_ID, null); else set_Value (COLUMNNAME_LastSalesPrice_Currency_ID, Integer.valueOf(LastSalesPrice_Currency_ID)); } /** Get Letzter VK Währung. @return Letzter Verkaufspreis Währung */ @Override public int getLastSalesPrice_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_LastSalesPrice_Currency_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Letzte Lieferung. @param LastShipDate Letzte Lieferung */ @Override public void setLastShipDate (java.sql.Timestamp LastShipDate) { set_Value (COLUMNNAME_LastShipDate, LastShipDate); }
/** Get Letzte Lieferung. @return Letzte Lieferung */ @Override public java.sql.Timestamp getLastShipDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats.java
1
请完成以下Java代码
public PPOrderWeightingRun getById(final PPOrderWeightingRunId id) { final PPOrderWeightingRunLoaderAndSaver loader = new PPOrderWeightingRunLoaderAndSaver(); return loader.getById(id); } public SeqNo getNextLineNo(final PPOrderWeightingRunId weightingRunId) { final int lastLineNo = queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class) .addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, weightingRunId) .create() .maxInt(I_PP_Order_Weighting_RunCheck.COLUMNNAME_Line); return SeqNo.ofInt(lastLineNo).next(); } public void save(@NonNull final PPOrderWeightingRun weightingRun) { final PPOrderWeightingRunLoaderAndSaver saver = new PPOrderWeightingRunLoaderAndSaver(); saver.save(weightingRun); } public UomId getUomId(final PPOrderWeightingRunId id) { final PPOrderWeightingRunLoaderAndSaver loader = new PPOrderWeightingRunLoaderAndSaver(); return loader.getUomId(id); } public void updateWhileSaving( @NonNull final I_PP_Order_Weighting_Run record, @NonNull final Consumer<PPOrderWeightingRun> consumer) { final PPOrderWeightingRunId runId = PPOrderWeightingRunLoaderAndSaver.extractId(record); final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver(); loaderAndSaver.addToCacheAndAvoidSaving(record);
loaderAndSaver.updateById(runId, consumer); } public void updateById( @NonNull final PPOrderWeightingRunId runId, @NonNull final Consumer<PPOrderWeightingRun> consumer) { final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver(); loaderAndSaver.updateById(runId, consumer); } public void deleteChecks(final PPOrderWeightingRunId runId) { queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class) .addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, runId) .create() .delete(); } public PPOrderWeightingRunCheckId addRunCheck( @NonNull final PPOrderWeightingRunId weightingRunId, @NonNull final SeqNo lineNo, @NonNull final Quantity weight, @NonNull final OrgId orgId) { final I_PP_Order_Weighting_RunCheck record = InterfaceWrapperHelper.newInstance(I_PP_Order_Weighting_RunCheck.class); record.setAD_Org_ID(orgId.getRepoId()); record.setPP_Order_Weighting_Run_ID(weightingRunId.getRepoId()); record.setLine(lineNo.toInt()); record.setWeight(weight.toBigDecimal()); record.setC_UOM_ID(weight.getUomId().getRepoId()); InterfaceWrapperHelper.save(record); return PPOrderWeightingRunCheckId.ofRepoId(weightingRunId, record.getPP_Order_Weighting_RunCheck_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunRepository.java
1
请在Spring Boot框架中完成以下Java代码
public class SayHelloResponse { @XmlElement(name = "return") protected String _return; /** * 获取return属性的值。 * * @return * possible object is * {@link String } * */ public String getReturn() { return _return;
} /** * 设置return属性的值。 * * @param value * allowed object is * {@link String } * */ public void setReturn(String value) { this._return = value; } }
repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\client\SayHelloResponse.java
2
请完成以下Java代码
public final List<I_C_ReferenceNo_Doc> retrieveDocAssignments(@NonNull final I_C_ReferenceNo referenceNo) { final List<I_C_ReferenceNo_Doc> result = Services .get(IQueryBL.class) .createQueryBuilder(I_C_ReferenceNo_Doc.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_ReferenceNo_Doc.COLUMNNAME_C_ReferenceNo_ID, referenceNo.getC_ReferenceNo_ID()) .orderBy(I_C_ReferenceNo_Doc.COLUMNNAME_C_ReferenceNo_Doc_ID) .create() .setRequiredAccess(Access.READ) .list(); return result; } @Override public final I_C_ReferenceNo_Doc getCreateReferenceNoDoc( @NonNull final I_C_ReferenceNo referenceNo, @NonNull final ITableRecordReference referencedModel) { boolean isNewReference = false; if (referenceNo.getC_ReferenceNo_ID() <= 0) { save(referenceNo); isNewReference = true; } I_C_ReferenceNo_Doc assignment = null; // // Search for an already existing assignment, only if the reference was not new if (!isNewReference)
{ assignment = Services .get(IQueryBL.class) .createQueryBuilder(I_C_ReferenceNo_Doc.class, referenceNo) // .addOnlyActiveRecordsFilter() the old code didn't have an active-check; not sure why, but might be a feature .addEqualsFilter(I_C_ReferenceNo_Doc.COLUMNNAME_C_ReferenceNo_ID, referenceNo.getC_ReferenceNo_ID()) .addEqualsFilter(I_C_ReferenceNo_Doc.COLUMNNAME_AD_Table_ID, referencedModel.getAD_Table_ID()) .addEqualsFilter(I_C_ReferenceNo_Doc.COLUMNNAME_Record_ID, referencedModel.getRecord_ID()) .create() .firstOnly(I_C_ReferenceNo_Doc.class); } // // Creating new referenceNo assignment if (assignment == null) { assignment = newInstance(I_C_ReferenceNo_Doc.class, referenceNo); assignment.setC_ReferenceNo(referenceNo); assignment.setAD_Table_ID(referencedModel.getAD_Table_ID()); assignment.setRecord_ID(referencedModel.getRecord_ID()); } assignment.setIsActive(true); save(assignment); return assignment; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\AbstractReferenceNoDAO.java
1
请完成以下Java代码
public void setTermDurationUnit (final java.lang.String TermDurationUnit) { set_Value (COLUMNNAME_TermDurationUnit, TermDurationUnit); } @Override public java.lang.String getTermDurationUnit() { return get_ValueAsString(COLUMNNAME_TermDurationUnit); } @Override public void setTermOfNotice (final int TermOfNotice) { set_Value (COLUMNNAME_TermOfNotice, TermOfNotice); } @Override public int getTermOfNotice() { return get_ValueAsInt(COLUMNNAME_TermOfNotice); } /**
* TermOfNoticeUnit AD_Reference_ID=540281 * Reference name: TermDurationUnit */ public static final int TERMOFNOTICEUNIT_AD_Reference_ID=540281; /** Monat(e) = month */ public static final String TERMOFNOTICEUNIT_MonatE = "month"; /** Woche(n) = week */ public static final String TERMOFNOTICEUNIT_WocheN = "week"; /** Tag(e) = day */ public static final String TERMOFNOTICEUNIT_TagE = "day"; /** Jahr(e) = year */ public static final String TERMOFNOTICEUNIT_JahrE = "year"; @Override public void setTermOfNoticeUnit (final java.lang.String TermOfNoticeUnit) { set_Value (COLUMNNAME_TermOfNoticeUnit, TermOfNoticeUnit); } @Override public java.lang.String getTermOfNoticeUnit() { return get_ValueAsString(COLUMNNAME_TermOfNoticeUnit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Transition.java
1
请完成以下Java代码
public abstract class AbstractPvmAtomicOperationTransitionNotifyListenerTake extends AbstractPvmEventAtomicOperation { protected void eventNotificationsCompleted(PvmExecutionImpl execution) { PvmActivity destination = execution.getTransition().getDestination(); // check start behavior of next activity switch (destination.getActivityStartBehavior()) { case DEFAULT: execution.setActivity(destination); execution.dispatchDelayedEventsAndPerformOperation(TRANSITION_CREATE_SCOPE); break; case INTERRUPT_FLOW_SCOPE: execution.setActivity(null); execution.performOperation(TRANSITION_INTERRUPT_FLOW_SCOPE); break;
default: throw new ProcessEngineException("Unsupported start behavior for activity '"+destination +"' started from a sequence flow: "+destination.getActivityStartBehavior()); } } protected CoreModelElement getScope(PvmExecutionImpl execution) { return execution.getTransition(); } protected String getEventName() { return ExecutionListener.EVENTNAME_TAKE; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\AbstractPvmAtomicOperationTransitionNotifyListenerTake.java
1
请完成以下Java代码
public class Result<T> implements Serializable { private static final long serialVersionUID = 1696194043024336235L; /** * 错误码 */ private int errcode; /** * 错误信息 */ private String errmsg; /** * 响应数据 */ private T data; public Result() { } private Result(ResultCode resultCode) { this(resultCode.code, resultCode.msg); } private Result(ResultCode resultCode, T data) { this(resultCode.code, resultCode.msg, data); } private Result(int errcode, String errmsg) { this(errcode, errmsg, null); } private Result(int errcode, String errmsg, T data) { this.errcode = errcode; this.errmsg = errmsg; this.data = data; } /** * 返回成功
* * @param <T> 泛型标记 * @return 响应信息 {@code Result} */ public static <T> Result<T> success() { return new Result<>(ResultCode.SUCCESS); } /** * 返回成功-携带数据 * * @param data 响应数据 * @param <T> 泛型标记 * @return 响应信息 {@code Result} */ public static <T> Result<T> success(@Nullable T data) { return new Result<>(ResultCode.SUCCESS, data); } }
repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\common\Result.java
1
请完成以下Java代码
protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { final String name = para.getParameterName(); if (para.getParameter() == null) { } else if (name.equals(PARAM_C_Invoice_ID)) { p_C_Invoice_ID = para.getParameterAsInt(); } } if (p_C_Invoice_ID <= 0) { throw new FillMandatoryException(PARAM_C_Invoice_ID); } } @Override protected String doIt() throws Exception { final MInvoice invoice = new MInvoice(getCtx(), p_C_Invoice_ID, get_TrxName()); recalculateTax(invoice); // return "@ProcessOK@"; } public static void recalculateTax(final MInvoice invoice)
{ final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final I_C_BPartner partner = bpartnerDAO.getById(invoice.getC_BPartner_ID()); // // Delete accounting /UnPost MPeriod.testPeriodOpen(invoice.getCtx(), invoice.getDateAcct(), invoice.getC_DocType_ID(), invoice.getAD_Org_ID()); Services.get(IFactAcctDAO.class).deleteForDocument(invoice); // // Update Invoice invoice.calculateTaxTotal(); invoice.setPosted(false); invoice.saveEx(); // FRESH-152 Update bpartner stats Services.get(IBPartnerStatisticsUpdater.class) .updateBPartnerStatistics(BPartnerStatisticsUpdateRequest.builder() .bpartnerId(partner.getC_BPartner_ID()) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\eevolution\process\InvoiceCalculateTax.java
1
请完成以下Java代码
public class RSAKeyValueType { @XmlElement(name = "Modulus", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected byte[] modulus; @XmlElement(name = "Exponent", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected byte[] exponent; /** * Gets the value of the modulus property. * * @return * possible object is * byte[] */ public byte[] getModulus() { return modulus; } /** * Sets the value of the modulus property. * * @param value * allowed object is * byte[] */ public void setModulus(byte[] value) { this.modulus = value; } /** * Gets the value of the exponent property. * * @return * possible object is * byte[] */
public byte[] getExponent() { return exponent; } /** * Sets the value of the exponent property. * * @param value * allowed object is * byte[] */ public void setExponent(byte[] value) { this.exponent = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RSAKeyValueType.java
1
请在Spring Boot框架中完成以下Java代码
public List<P102> getP102Lines() { return p102Lines; } public void setP102Lines(final List<P102> p102Lines) { this.p102Lines = p102Lines; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (joinP060P100Lines == null ? 0 : joinP060P100Lines.hashCode()); result = prime * result + (levelNo == null ? 0 : levelNo.hashCode()); result = prime * result + (messageNo == null ? 0 : messageNo.hashCode()); result = prime * result + (p102Lines == null ? 0 : p102Lines.hashCode()); result = prime * result + (packageQty == null ? 0 : packageQty.hashCode()); result = prime * result + (packageType == null ? 0 : packageType.hashCode()); result = prime * result + (partner == null ? 0 : partner.hashCode()); result = prime * result + (record == null ? 0 : record.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final P050 other = (P050)obj; if (joinP060P100Lines == null) { if (other.joinP060P100Lines != null) { return false; } } else if (!joinP060P100Lines.equals(other.joinP060P100Lines)) { return false; } if (levelNo == null) { if (other.levelNo != null) { return false; } } else if (!levelNo.equals(other.levelNo)) { return false; } if (messageNo == null) { if (other.messageNo != null) { return false; } } else if (!messageNo.equals(other.messageNo)) { return false; } if (p102Lines == null) { if (other.p102Lines != null) { return false; } } else if (!p102Lines.equals(other.p102Lines)) { return false; } if (packageQty == null) { if (other.packageQty != null) { return false;
} } else if (!packageQty.equals(other.packageQty)) { return false; } if (packageType == null) { if (other.packageType != null) { return false; } } else if (!packageType.equals(other.packageType)) { return false; } if (partner == null) { if (other.partner != null) { return false; } } else if (!partner.equals(other.partner)) { return false; } if (record == null) { if (other.record != null) { return false; } } else if (!record.equals(other.record)) { return false; } return true; } @Override public String toString() { return "P050 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", levelNo=" + levelNo + ", packageQty=" + packageQty + ", packageType=" + packageType + ", p102Lines=" + p102Lines + ", joinP060P100Lines=" + joinP060P100Lines + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\compudata\P050.java
2
请完成以下Java代码
private Object getSourceNode() { return (sourceNode != null ? sourceNode : simplifiedSourceNode); } /** * 获取简化后的状态Array<br> * Returns the array of SimpleMDAGNodes collectively containing the * data of this MDAG, or null if it hasn't been simplified yet. * * @return the array of SimpleMDAGNodes collectively containing the data of this MDAG * if this MDAG has been simplified, or null if it has not */ public SimpleMDAGNode[] getSimpleMDAGArray() { return mdagDataArray; } /** * Procures the set of characters which collectively label the MDAG's transitions. * * @return a TreeSet of chars which collectively label all the transitions in the MDAG */ private TreeSet<Character> getTransitionLabelSet() { return charTreeSet; } /** * Determines if a child node object is accepting. * * @param nodeObj an Object * @return if {@code nodeObj} is either an MDAGNode or a SimplifiedMDAGNode, * true if the node is accepting, false otherwise * throws IllegalArgumentException if {@code nodeObj} is not an MDAGNode or SimplifiedMDAGNode */ private static boolean isAcceptNode(Object nodeObj) { if (nodeObj != null) { Class nodeObjClass = nodeObj.getClass(); if (nodeObjClass.equals(MDAGNode.class)) return ((MDAGNode) nodeObj).isAcceptNode(); else if (nodeObjClass.equals(SimpleMDAGNode.class)) return ((SimpleMDAGNode) nodeObj).isAcceptNode(); }
throw new IllegalArgumentException("Argument is not an MDAGNode or SimpleMDAGNode"); } // @Override // public String toString() // { // final StringBuilder sb = new StringBuilder("MDAG{"); // sb.append("sourceNode=").append(sourceNode); // sb.append(", simplifiedSourceNode=").append(simplifiedSourceNode); // sb.append(", equivalenceClassMDAGNodeHashMap=").append(equivalenceClassMDAGNodeHashMap); // sb.append(", mdagDataArray=").append(Arrays.toString(mdagDataArray)); // sb.append(", charTreeSet=").append(charTreeSet); // sb.append(", transitionCount=").append(transitionCount); // sb.append('}'); // return sb.toString(); // } /** * 调试用 * @return */ public HashMap<MDAGNode, MDAGNode> _getEquivalenceClassMDAGNodeHashMap() { return new HashMap<MDAGNode, MDAGNode>(equivalenceClassMDAGNodeHashMap); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAG.java
1
请完成以下Java代码
private static void pollEvents() { while (true) { List<MonitoringEvent> events = dataService.retrieveEvents(); events.forEach(mapper::add); producer.runCycle(task -> { events.forEach(task::add); }); producer.getWriteEngine().prepareForNextCycle(); sleep(POLL_INTERVAL_MILLISECONDS); } } private static void sleep(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
private static Path getSnapshotFilePath() { String moduleDir = System.getProperty("user.dir"); String snapshotDir = moduleDir + "/.hollow/snapshots"; logger.info("snapshot data directory: {}", snapshotDir); Path snapshotPath = Paths.get(snapshotDir); // Create directories if they don't exist try { Files.createDirectories(snapshotPath); } catch (java.io.IOException e) { throw new RuntimeException("Failed to create snapshot directory: " + snapshotDir, e); } return snapshotPath; } }
repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\producer\MonitoringEventProducer.java
1
请完成以下Java代码
public <T> T getSetting(String name) { Assert.hasText(name, "name cannot be empty"); return (T) getSettings().get(name); } /** * Returns a {@code Map} of the configuration settings. * @return a {@code Map} of the configuration settings */ public Map<String, Object> getSettings() { return this.settings; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } AbstractSettings that = (AbstractSettings) obj; return this.settings.equals(that.settings); } @Override public int hashCode() { return Objects.hash(this.settings); } @Override public String toString() { return "AbstractSettings {" + "settings=" + this.settings + '}'; } /** * A builder for subclasses of {@link AbstractSettings}. * * @param <T> the type of object * @param <B> the type of the builder */ protected abstract static class AbstractBuilder<T extends AbstractSettings, B extends AbstractBuilder<T, B>> { private final Map<String, Object> settings = new HashMap<>(); protected AbstractBuilder() {
} /** * Sets a configuration setting. * @param name the name of the setting * @param value the value of the setting * @return the {@link AbstractBuilder} for further configuration */ public B setting(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); getSettings().put(name, value); return getThis(); } /** * A {@code Consumer} of the configuration settings {@code Map} allowing the * ability to add, replace, or remove. * @param settingsConsumer a {@link Consumer} of the configuration settings * {@code Map} * @return the {@link AbstractBuilder} for further configuration */ public B settings(Consumer<Map<String, Object>> settingsConsumer) { settingsConsumer.accept(getSettings()); return getThis(); } public abstract T build(); protected final Map<String, Object> getSettings() { return this.settings; } @SuppressWarnings("unchecked") protected final B getThis() { return (B) this; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AbstractSettings.java
1
请完成以下Java代码
public class SseClientBroadcastApp { private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe"; public static void main(String... args) throws Exception { Client client = ClientBuilder.newClient(); WebTarget target = client.target(subscribeUrl); try (final SseEventSource eventSource = SseEventSource.target(target) .reconnectingEvery(5, TimeUnit.SECONDS) .build()) { eventSource.register(onEvent, onError, onComplete); eventSource.open(); System.out.println("Wainting for incoming event ..."); //Consuming events for one hour Thread.sleep(60 * 60 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } client.close(); System.out.println("End");
} // A new event is received private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> { String data = inboundSseEvent.readData(); System.out.println(data); }; //Error private static Consumer<Throwable> onError = (throwable) -> { throwable.printStackTrace(); }; //Connection close and there is nothing to receive private static Runnable onComplete = () -> { System.out.println("Done!"); }; }
repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-client\src\main\java\com\baeldung\sse\jaxrs\client\SseClientBroadcastApp.java
1
请完成以下Java代码
public boolean isReversalDocument(@NonNull final Object model) { // Try Reversal_ID column if available final Integer original_ID = InterfaceWrapperHelper.getValueOrNull(model, IDocument.Reversal_ID); if (original_ID != null && original_ID > 0) { final int reversal_id = InterfaceWrapperHelper.getId(model); return reversal_id > original_ID; } return false; } @Override public final Map<String, IDocActionItem> retrieveDocActionItemsIndexedByValue() { final ADReferenceService adReferenceService = ADReferenceService.get(); final Properties ctx = Env.getCtx(); final String adLanguage = Env.getAD_Language(ctx); return adReferenceService.retrieveListItems(X_C_Order.DOCACTION_AD_Reference_ID) // 135 .stream() .map(adRefListItem -> new DocActionItem(adRefListItem, adLanguage)) .sorted(Comparator.comparing(DocActionItem::toString)) .collect(GuavaCollectors.toImmutableMapByKey(IDocActionItem::getValue)); } private static final class DocActionItem implements IDocActionItem { private final String value; private final String caption; private final String description; private DocActionItem(final ADRefListItem adRefListItem, final String adLanguage) { this.value = adRefListItem.getValue(); this.caption = adRefListItem.getName().translate(adLanguage); this.description = adRefListItem.getDescription().translate(adLanguage); } @Override public String toString() { // IMPORTANT: this is how it will be displayed to user return caption; } @Override public int hashCode() { return Objects.hashCode(value);
} @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof DocActionItem) { final DocActionItem other = (DocActionItem)obj; return Objects.equal(value, other.value); } else { return false; } } @Override public String getValue() { return value; } @Override public String getDescription() { return description; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\AbstractDocumentBL.java
1
请完成以下Java代码
public String getName() { return name; } @Override public void setName(final String name) { this.name = name; } @Override public I_C_UOM getC_UOM() { return uom; } @Override public void setC_UOM(final I_C_UOM uom) { this.uom = uom; } @Override public BigDecimal getQty() { return qty; } @Override public void setQty(final BigDecimal qty) { this.qty = qty; } @Override public BigDecimal getQtyProjected() { return qtyProjected; } @Override public void setQtyProjected(final BigDecimal qtyProjected) { this.qtyProjected = qtyProjected; } @Override public BigDecimal getPercentage() { return percentage; } @Override public void setPercentage(final BigDecimal percentage) { this.percentage = percentage; } @Override public boolean isNegateQtyInReport() { return negateQtyInReport; } @Override public void setNegateQtyInReport(final boolean negateQtyInReport) { this.negateQtyInReport = negateQtyInReport; } @Override public String getComponentType() {
return componentType; } @Override public void setComponentType(final String componentType) { this.componentType = componentType; } @Override public String getVariantGroup() { return variantGroup; } @Override public void setVariantGroup(final String variantGroup) { this.variantGroup = variantGroup; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo; } @Override public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } @Override public void setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { handlingUnitsInfoProjected = handlingUnitsInfo; } @Override public IHandlingUnitsInfo getHandlingUnitsInfoProjected() { return handlingUnitsInfoProjected; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLine.java
1
请完成以下Java代码
public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { Matcher matcher = INTERVAL_PATTERN.matcher(feelExpression); if (matcher.matches()) { return transformInterval(transform, matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), inputName); } else { throw LOG.invalidIntervalExpression(feelExpression); } } public String transformInterval(FeelToJuelTransform transform, String startIntervalSymbol, String lowerEndpoint, String upperEndpoint, String stopIntervalSymbol, String inputName) { String juelLowerEndpoint = transform.transformEndpoint(lowerEndpoint, inputName); String juelUpperEndpoint = transform.transformEndpoint(upperEndpoint, inputName); String lowerEndpointComparator = transformLowerEndpointComparator(startIntervalSymbol); String upperEndpointComparator = transformUpperEndpointComparator(stopIntervalSymbol); return String.format("%s %s %s && %s %s %s", inputName, lowerEndpointComparator, juelLowerEndpoint, inputName, upperEndpointComparator, juelUpperEndpoint); } protected String transformLowerEndpointComparator(String startIntervalSymbol) { if (startIntervalSymbol.equals("[")) { return ">=";
} else { return ">"; } } protected String transformUpperEndpointComparator(String stopIntervalSymbol) { if (stopIntervalSymbol.equals("]")) { return "<="; } else { return "<"; } } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\transform\IntervalTransformer.java
1
请在Spring Boot框架中完成以下Java代码
public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public Graph tfModelGraph(@Value("${tf.frozenModelPath}") String tfFrozenModelPath) throws IOException { Resource graphResource = getResource(tfFrozenModelPath); Graph graph = new Graph(); graph.importGraphDef(GraphDef.parseFrom(graphResource.getInputStream())); log.info("Loaded Tensorflow model"); return graph; } private Resource getResource(@Value("${tf.frozenModelPath}") String tfFrozenModelPath) {
Resource graphResource = new FileSystemResource(tfFrozenModelPath); if (!graphResource.exists()) { graphResource = new ClassPathResource(tfFrozenModelPath); } if (!graphResource.exists()) { throw new IllegalArgumentException(String.format("File %s does not exist", tfFrozenModelPath)); } return graphResource; } @Bean public List<String> tfModelLabels(@Value("${tf.labelsPath}") String labelsPath) throws IOException { Resource labelsRes = getResource(labelsPath); log.info("Loaded model labels"); return IOUtils.readLines(labelsRes.getInputStream(), StandardCharsets.UTF_8).stream() .map(label -> label.substring(label.contains(":") ? label.indexOf(":") + 1 : 0)).collect(Collectors.toList()); } }
repos\springboot-demo-master\Tensorflow\src\main\java\com\et\tf\Application.java
2
请完成以下Java代码
public static LocatorQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCode(globalQRCode);} @JsonCreator public static LocatorQRCode ofScannedCode(final ScannedCode scannedCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(scannedCode.getAsString());} public static LocatorQRCode ofLocator(@NonNull final I_M_Locator locator) { return builder() .locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID())) .caption(locator.getValue()) .build(); } public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder() .qrCode(toGlobalQRCodeJsonString()) .bottomText(caption) .build();
} public GlobalQRCode toGlobalQRCode() { return LocatorQRCodeJsonConverter.toGlobalQRCode(this); } public ScannedCode toScannedCode() { return ScannedCode.ofString(toGlobalQRCodeJsonString()); } public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode) { return LocatorQRCodeJsonConverter.isTypeMatching(globalQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCode.java
1
请在Spring Boot框架中完成以下Java代码
public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) { return getHistoricEntityLinkEntityManager().findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(scopeId, scopeType, linkType); } @Override public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType, String linkType) { return getHistoricEntityLinkEntityManager().findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(scopeIds, scopeType, linkType); } @Override @SuppressWarnings("unchecked") public InternalEntityLinkQuery<HistoricEntityLink> createInternalHistoricEntityLinkQuery() { return (InternalEntityLinkQuery) getHistoricEntityLinkEntityManager().createInternalHistoricEntityLinkQuery(); } @Override public HistoricEntityLink createHistoricEntityLink() { return getHistoricEntityLinkEntityManager().create(); } @Override public void insertHistoricEntityLink(HistoricEntityLink entityLink, boolean fireCreateEvent) { getHistoricEntityLinkEntityManager().insert((HistoricEntityLinkEntity) entityLink, fireCreateEvent); } @Override public void deleteHistoricEntityLink(String id) { getHistoricEntityLinkEntityManager().delete(id); } @Override public void deleteHistoricEntityLink(HistoricEntityLink entityLink) { getHistoricEntityLinkEntityManager().delete((HistoricEntityLinkEntity) entityLink); } @Override public void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksByScopeIdAndScopeType(scopeId, scopeType); }
@Override public void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(scopeDefinitionId, scopeType); } @Override public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) { getHistoricEntityLinkEntityManager().bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(scopeType, scopeIds); } @Override public void deleteHistoricEntityLinksForNonExistingProcessInstances() { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksForNonExistingProcessInstances(); } @Override public void deleteHistoricEntityLinksForNonExistingCaseInstances() { getHistoricEntityLinkEntityManager().deleteHistoricEntityLinksForNonExistingCaseInstances(); } public HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() { return configuration.getHistoricEntityLinkEntityManager(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\HistoricEntityLinkServiceImpl.java
2
请完成以下Java代码
protected TaskEntity verifyTaskParameters(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId); if (task == null) { throw new FlowableObjectNotFoundException("Cannot find task with id " + taskId, Task.class); } if (task.isSuspended()) { throw new FlowableException("It is not allowed to add an attachment to a suspended " + task); } return task; }
protected ExecutionEntity verifyExecutionParameters(CommandContext commandContext) { ExecutionEntity execution = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstanceId); if (execution == null) { throw new FlowableObjectNotFoundException("Process instance " + processInstanceId + " doesn't exist", ProcessInstance.class); } if (execution.isSuspended()) { throw new FlowableException("It is not allowed to add an attachment to a suspended " + execution); } return execution; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\CreateAttachmentCmd.java
1
请完成以下Java代码
public TbResourceInfo findByTenantIdAndKey(TenantId tenantId, ResourceType resourceType, String resourceKey) { return DaoUtil.getData(resourceInfoRepository.findByTenantIdAndResourceTypeAndResourceKey(tenantId.getId(), resourceType.name(), resourceKey)); } @Override public boolean existsByTenantIdAndResourceTypeAndResourceKey(TenantId tenantId, ResourceType resourceType, String resourceKey) { return resourceInfoRepository.existsByTenantIdAndResourceTypeAndResourceKey(tenantId.getId(), resourceType.name(), resourceKey); } @Override public Set<String> findKeysByTenantIdAndResourceTypeAndResourceKeyPrefix(TenantId tenantId, ResourceType resourceType, String prefix) { return resourceInfoRepository.findKeysByTenantIdAndResourceTypeAndResourceKeyStartingWith(tenantId.getId(), resourceType.name(), prefix); } @Override public List<TbResourceInfo> findByTenantIdAndEtagAndKeyStartingWith(TenantId tenantId, String etag, String query) { return DaoUtil.convertDataList(resourceInfoRepository.findByTenantIdAndEtagAndResourceKeyStartingWith(tenantId.getId(), etag, query)); } @Override public TbResourceInfo findSystemOrTenantResourceByEtag(TenantId tenantId, ResourceType resourceType, String etag) { return DaoUtil.getData(resourceInfoRepository.findSystemOrTenantResourceByEtag(tenantId.getId(), resourceType.name(), etag)); }
@Override public boolean existsByPublicResourceKey(ResourceType resourceType, String publicResourceKey) { return resourceInfoRepository.existsByResourceTypeAndPublicResourceKey(resourceType.name(), publicResourceKey); } @Override public TbResourceInfo findPublicResourceByKey(ResourceType resourceType, String publicResourceKey) { return DaoUtil.getData(resourceInfoRepository.findByResourceTypeAndPublicResourceKeyAndIsPublicTrue(resourceType.name(), publicResourceKey)); } @Override public List<TbResourceInfo> findSystemOrTenantResourcesByIds(TenantId tenantId, List<TbResourceId> resourceIds) { return DaoUtil.convertDataList(resourceInfoRepository.findSystemOrTenantResourcesByIdIn(tenantId.getId(), TenantId.NULL_UUID, toUUIDs(resourceIds))); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\resource\JpaTbResourceInfoDao.java
1
请完成以下Java代码
public void deleteEntry(final DocumentId id) { final IPair<String, Integer> prefixAndId = toPrefixAndEntryId(id); final String idPrefix = prefixAndId.getLeft(); final int entryId = prefixAndId.getRight(); if (ID_PREFIX_Attachment.equals(idPrefix)) { final AttachmentEntry entry = attachmentEntryService.getById(AttachmentEntryId.ofRepoId(entryId)); attachmentEntryService.unattach(recordRef, entry); notifyRelatedDocumentTabsChanged(); } else if (ID_PREFIX_Archive.equals(idPrefix)) { final ArchiveId archiveId = ArchiveId.ofRepoId(entryId); final I_AD_Archive archive = archiveDAO.retrieveArchiveOrNull(recordRef, archiveId); if (archive == null) { throw new EntityNotFoundException(id.toJson()); } InterfaceWrapperHelper.delete(archive); } else { throw new EntityNotFoundException(id.toJson()); } } private static IPair<String, Integer> toPrefixAndEntryId(final DocumentId id) { final List<String> idParts = ID_Splitter.splitToList(id.toJson()); if (idParts.size() != 2)
{ throw new IllegalArgumentException("Invalid attachment ID"); } final String idPrefix = idParts.get(0); final int entryId = Integer.parseInt(idParts.get(1)); return ImmutablePair.of(idPrefix, entryId); } private static DocumentId buildId(final String idPrefix, final int id) { return DocumentId.ofString(ID_Joiner.join(idPrefix, id)); } /** * If the document contains some attachment related tabs, it will send an "stale" notification to frontend. * In this way, frontend will be aware of this and will have to refresh the tab. */ private void notifyRelatedDocumentTabsChanged() { final ImmutableSet<DetailId> attachmentRelatedTabIds = entityDescriptor .getIncludedEntities().stream() .filter(includedEntityDescriptor -> Objects.equals(includedEntityDescriptor.getTableNameOrNull(), I_AD_AttachmentEntry.Table_Name)) .map(DocumentEntityDescriptor::getDetailId) .collect(ImmutableSet.toImmutableSet()); if (attachmentRelatedTabIds.isEmpty()) { return; } websocketPublisher.staleTabs(documentPath.getWindowId(), documentPath.getDocumentId(), attachmentRelatedTabIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachments.java
1
请完成以下Java代码
public class JsonMessageConverter extends MessagingMessageConverter { private static final JavaType OBJECT = TypeFactory.defaultInstance().constructType(Object.class); private final ObjectMapper objectMapper; private Jackson2JavaTypeMapper typeMapper = new DefaultJackson2JavaTypeMapper(); public JsonMessageConverter() { this(JacksonUtils.enhancedObjectMapper()); } public JsonMessageConverter(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "'objectMapper' must not be null."); this.objectMapper = objectMapper; } public Jackson2JavaTypeMapper getTypeMapper() { return this.typeMapper; } /** * Set a customized type mapper. * @param typeMapper the type mapper. */ public void setTypeMapper(Jackson2JavaTypeMapper typeMapper) { Assert.notNull(typeMapper, "'typeMapper' cannot be null"); this.typeMapper = typeMapper; } /** * Return the object mapper. * @return the mapper. */ protected ObjectMapper getObjectMapper() { return this.objectMapper; } @Override protected Headers initialRecordHeaders(Message<?> message) { RecordHeaders headers = new RecordHeaders(); this.typeMapper.fromClass(message.getPayload().getClass(), headers); return headers; } @Override protected @Nullable Object convertPayload(Message<?> message) { throw new UnsupportedOperationException("Select a subclass that creates a ProducerRecord value " + "corresponding to the configured Kafka Serializer"); } @Override protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) { Object value = record.value(); if (record.value() == null) { return KafkaNull.INSTANCE;
} JavaType javaType = determineJavaType(record, type); if (value instanceof Bytes) { value = ((Bytes) value).get(); } if (value instanceof String) { try { return this.objectMapper.readValue((String) value, javaType); } catch (IOException e) { throw new ConversionException("Failed to convert from JSON", record, e); } } else if (value instanceof byte[]) { try { return this.objectMapper.readValue((byte[]) value, javaType); } catch (IOException e) { throw new ConversionException("Failed to convert from JSON", record, e); } } else { throw new IllegalStateException("Only String, Bytes, or byte[] supported"); } } private JavaType determineJavaType(ConsumerRecord<?, ?> record, @Nullable Type type) { JavaType javaType = this.typeMapper.getTypePrecedence() .equals(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper.TypePrecedence.INFERRED) && type != null ? TypeFactory.defaultInstance().constructType(type) : this.typeMapper.toJavaType(record.headers()); if (javaType == null) { // no headers if (type != null) { javaType = TypeFactory.defaultInstance().constructType(type); } else { javaType = OBJECT; } } return javaType; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\JsonMessageConverter.java
1
请完成以下Java代码
public final class NullTrxListenerManager implements ITrxListenerManager { public static final NullTrxListenerManager instance = new NullTrxListenerManager(); private NullTrxListenerManager() { } @Override public void registerListener(final RegisterListenerRequest listener) { // nothing } @Override public boolean canRegisterOnTiming(@NonNull final TrxEventTiming timing) { return false; } /** * Does nothing */ @Override 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代码
public UserNotificationsList getNotifications(final UserId adUserId, final QueryLimit limit) { return getNotificationsQueue(adUserId).getNotificationsAsList(limit); } private void forwardEventToNotificationsQueues(final IEventBus eventBus, final Event event) { logger.trace("Got event from {}: {}", eventBus, event); final UserNotification notification = UserNotificationUtils.toUserNotification(event); final UserId recipientUserId = UserId.ofRepoId(notification.getRecipientUserId()); final UserNotificationsQueue notificationsQueue = getNotificationsQueueOrNull(recipientUserId); if (notificationsQueue == null) { logger.trace("No notification queue was found for recipientUserId={}", recipientUserId); return; } notificationsQueue.addNotification(notification); } public void markNotificationAsRead(final UserId adUserId, final String notificationId) { getNotificationsQueue(adUserId).markAsRead(notificationId); } public void markAllNotificationsAsRead(final UserId adUserId) { getNotificationsQueue(adUserId).markAllAsRead();
} public int getNotificationsUnreadCount(final UserId adUserId) { return getNotificationsQueue(adUserId).getUnreadCount(); } public void deleteNotification(final UserId adUserId, final String notificationId) { getNotificationsQueue(adUserId).delete(notificationId); } public void deleteAllNotification(final UserId adUserId) { getNotificationsQueue(adUserId).deleteAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsService.java
1
请完成以下Java代码
public class ClusterUniversalStateVO { private ClusterStateSimpleEntity stateInfo; private ClusterClientStateVO client; private ClusterServerStateVO server; public ClusterClientStateVO getClient() { return client; } public ClusterUniversalStateVO setClient(ClusterClientStateVO client) { this.client = client; return this; } public ClusterServerStateVO getServer() { return server; } public ClusterUniversalStateVO setServer(ClusterServerStateVO server) { this.server = server; return this; } public ClusterStateSimpleEntity getStateInfo() { return stateInfo;
} public ClusterUniversalStateVO setStateInfo( ClusterStateSimpleEntity stateInfo) { this.stateInfo = stateInfo; return this; } @Override public String toString() { return "ClusterUniversalStateVO{" + "stateInfo=" + stateInfo + ", client=" + client + ", server=" + server + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\ClusterUniversalStateVO.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_ValueNoCheck (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public org.compiere.model.I_C_Location getOrg_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class); } @Override public void setOrg_Location(org.compiere.model.I_C_Location Org_Location) { set_ValueFromPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class, Org_Location); } /** Set Org Address. @param Org_Location_ID Organization Location/Address */ @Override public void setOrg_Location_ID (int Org_Location_ID) { if (Org_Location_ID < 1) set_ValueNoCheck (COLUMNNAME_Org_Location_ID, null); else set_ValueNoCheck (COLUMNNAME_Org_Location_ID, Integer.valueOf(Org_Location_ID)); } /** Get Org Address. @return Organization Location/Address */ @Override public int getOrg_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Org_Location_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Telefon. @param Phone Beschreibt eine Telefon Nummer */ @Override public void setPhone (java.lang.String Phone) { set_ValueNoCheck (COLUMNNAME_Phone, Phone); } /** Get Telefon. @return Beschreibt eine Telefon Nummer */
@Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Steuer-ID. @param TaxID Tax Identification */ @Override public void setTaxID (java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } /** Get Steuer-ID. @return Tax Identification */ @Override public java.lang.String getTaxID () { return (java.lang.String)get_Value(COLUMNNAME_TaxID); } /** Set Titel. @param Title Name this entity is referred to as */ @Override public void setTitle (java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } /** Get Titel. @return Name this entity is referred to as */ @Override public java.lang.String getTitle () { return (java.lang.String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java
1
请完成以下Java代码
public class WebsocketConst { /** * 消息json key:cmd */ public static final String MSG_CMD = "cmd"; /** * 消息json key:msgId */ public static final String MSG_ID = "msgId"; /** * 消息json key:msgTxt */ public static final String MSG_TXT = "msgTxt"; /** * 消息json key:userId */ public static final String MSG_USER_ID = "userId"; /** * 消息json key:chat */ public static final String MSG_CHAT = "chat"; /** * 消息类型 heartcheck */ public static final String CMD_CHECK = "heartcheck"; /** * 消息类型 user 用户消息 */ public static final String CMD_USER = "user";
/** * 消息类型 topic 系统通知 */ public static final String CMD_TOPIC = "topic"; /** * 消息类型 email */ public static final String CMD_EMAIL = "email"; /** * 消息类型 meetingsign 会议签到 */ public static final String CMD_SIGN = "sign"; /** * 消息类型 新闻发布/取消 */ public static final String NEWS_PUBLISH = "publish"; }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\WebsocketConst.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return DataConstants.SNMP_TRANSPORT_NAME; } @PreDestroy public void shutdown() { log.info("Stopping SNMP transport!"); if (scheduler != null) { scheduler.shutdownNow(); } if (executor != null) { executor.shutdownNow(); } if (snmp != null) { try { snmp.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } log.info("SNMP transport stopped!"); } @Data private static class RequestContext { private final Integer requestId; private final SnmpCommunicationSpec communicationSpec; private final SnmpMethod method; private final List<SnmpMapping> responseMappings; private final int requestSize; private List<PDU> responseParts; @Builder public RequestContext(Integer requestId, SnmpCommunicationSpec communicationSpec, SnmpMethod method, List<SnmpMapping> responseMappings, int requestSize) { this.requestId = requestId; this.communicationSpec = communicationSpec;
this.method = method; this.responseMappings = responseMappings; this.requestSize = requestSize; if (requestSize > 1) { this.responseParts = Collections.synchronizedList(new ArrayList<>()); } } } private interface ResponseDataMapper { JsonObject map(List<PDU> pdus, RequestContext requestContext); } private interface ResponseProcessor { void process(JsonObject responseData, RequestContext requestContext, DeviceSessionContext sessionContext); } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\SnmpTransportService.java
2
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public List<OtherTaxType> getOtherTax() { if (otherTax == null) { otherTax = new ArrayList<OtherTaxType>(); } return this.otherTax; } /** * Gets the value of the taxExtension property. * * @return * possible object is * {@link TaxExtensionType } * */ public TaxExtensionType getTaxExtension() {
return taxExtension; } /** * Sets the value of the taxExtension property. * * @param value * allowed object is * {@link TaxExtensionType } * */ public void setTaxExtension(TaxExtensionType value) { this.taxExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\TaxType.java
2
请完成以下Java代码
public class JpaOtaPackageDao extends JpaAbstractDao<OtaPackageEntity, OtaPackage> implements OtaPackageDao, TenantEntityDao<OtaPackage> { @Autowired private OtaPackageRepository otaPackageRepository; @Override public Long sumDataSizeByTenantId(TenantId tenantId) { return otaPackageRepository.sumDataSizeByTenantId(tenantId.getId()); } @Transactional @Override public OtaPackage findOtaPackageByTenantIdAndTitleAndVersion(TenantId tenantId, String title, String version) { return DaoUtil.getData(otaPackageRepository.findByTenantIdAndTitleAndVersion(tenantId.getId(), title, version)); } @Transactional @Override public PageData<OtaPackage> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(otaPackageRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } @Transactional @Override public PageData<OtaPackage> findByTenantId(UUID tenantId, PageLink pageLink) { return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink); } @Override public PageData<OtaPackageId> findIdsByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.pageToPageData(otaPackageRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink)).map(OtaPackageId::new)); } @Transactional @Override public OtaPackage findByTenantIdAndExternalId(UUID tenantId, UUID externalId) { return DaoUtil.getData(otaPackageRepository.findByTenantIdAndExternalId(tenantId, externalId)); } @Override public OtaPackageId getExternalIdByInternal(OtaPackageId internalId) { return DaoUtil.toEntityId(otaPackageRepository.getExternalIdById(internalId.getId()), OtaPackageId::new); } @Override protected Class<OtaPackageEntity> getEntityClass() { return OtaPackageEntity.class; } @Override protected JpaRepository<OtaPackageEntity, UUID> getRepository() { return otaPackageRepository; } @Override public EntityType getEntityType() { return EntityType.OTA_PACKAGE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\ota\JpaOtaPackageDao.java
1
请完成以下Java代码
protected String doIt() { final I_AD_Table targetTable = getTargetTable(); final CopyColumnsResult result = CopyColumnsProducer.newInstance() .setLogger(Loggables.nop()) .setTargetTable(targetTable) .setSourceColumns(getSourceColumns()) .setSyncDatabase(p_IsSyncDatabase) .setDryRun(p_IsTest) .create(); // return "" + result; } private I_AD_Table getTargetTable() { if (p_target_AD_Table_ID <= 0) { throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_target_AD_Table_ID); } final MTable targetTable = new MTable(getCtx(), p_target_AD_Table_ID, get_TrxName()); return targetTable; } private List<I_AD_Column> getSourceColumns() { if (p_source_AD_Table_ID <= 0)
{ throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_source_AD_Table_ID); } final MTable sourceTable = new MTable(getCtx(), p_source_AD_Table_ID, get_TrxName()); final MColumn[] sourceColumnsArr = sourceTable.getColumns(true); if (sourceColumnsArr == null || sourceColumnsArr.length == 0) { throw new AdempiereException("@NotFound@ @AD_Column_ID@ (@AD_Table_ID@:" + sourceTable.getTableName() + ")"); } final List<I_AD_Column> sourceColumns = new ArrayList<>(sourceColumnsArr.length); for (final I_AD_Column sourceColumn : sourceColumnsArr) { sourceColumns.add(sourceColumn); } return sourceColumns; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\CopyColumnsFromTable.java
1
请完成以下Java代码
private Set<List<Boolean>> recursivePowerSetBinaryRepresentation(int idx, int n) { if (idx == n) { Set<List<Boolean>> powerSetOfEmptySet = new HashSet<>(); powerSetOfEmptySet.add(Arrays.asList(new Boolean[n])); return powerSetOfEmptySet; } Set<List<Boolean>> powerSetSubset = recursivePowerSetBinaryRepresentation(idx + 1, n); Set<List<Boolean>> powerSet = new HashSet<>(); for (List<Boolean> s : powerSetSubset) { List<Boolean> subSetIdxExclusive = new ArrayList<>(s); subSetIdxExclusive.set(idx, false); powerSet.add(subSetIdxExclusive); List<Boolean> subSetIdxInclusive = new ArrayList<>(s); subSetIdxInclusive.set(idx, true); powerSet.add(subSetIdxInclusive); } return powerSet; } private void initializeMap(Collection<T> collection) { int mapId = 0; for (T c : collection) { map.put(c, mapId++); reverseMap.add(c); } } private Set<Set<T>> unMapIndex(Set<Set<Integer>> sets) { Set<Set<T>> ret = new HashSet<>(); for (Set<Integer> s : sets) { HashSet<T> subset = new HashSet<>(); for (Integer i : s) subset.add(reverseMap.get(i)); ret.add(subset); } return ret; } private Set<Set<T>> unMapBinary(Collection<List<Boolean>> sets) { Set<Set<T>> ret = new HashSet<>(); for (List<Boolean> s : sets) { HashSet<T> subset = new HashSet<>(); for (int i = 0; i < s.size(); i++) if (s.get(i)) subset.add(reverseMap.get(i)); ret.add(subset); }
return ret; } private List<List<T>> unMapListBinary(Collection<List<Boolean>> sets) { List<List<T>> ret = new ArrayList<>(); for (List<Boolean> s : sets) { List<T> subset = new ArrayList<>(); for (int i = 0; i < s.size(); i++) if (s.get(i)) subset.add(reverseMap.get(i)); ret.add(subset); } return ret; } private Set<Set<T>> addElementToAll(Set<Set<T>> powerSetSubSetWithoutElement, T element) { Set<Set<T>> powerSetSubSetWithElement = new HashSet<>(); for (Set<T> subsetWithoutElement : powerSetSubSetWithoutElement) { Set<T> subsetWithElement = new HashSet<>(subsetWithoutElement); subsetWithElement.add(element); powerSetSubSetWithElement.add(subsetWithElement); } return powerSetSubSetWithElement; } private Set<T> getSubSetWithoutElement(Set<T> set, T element) { Set<T> subsetWithoutElement = new HashSet<>(); for (T s : set) { if (!s.equals(element)) subsetWithoutElement.add(s); } return subsetWithoutElement; } }
repos\tutorials-master\core-java-modules\core-java-lang-math-5\src\main\java\com\baeldung\powerset\PowerSetUtility.java
1
请完成以下Java代码
public String getPrototypeValue() { return prototypeValue; } void setPrototypeValue(final String prototypeValue) { this.prototypeValue = prototypeValue; } public int getDisplayType(final int defaultDisplayType) { return displayType > 0 ? displayType : defaultDisplayType; } public int getDisplayType() { return displayType; }
void setDisplayType(int displayType) { this.displayType = displayType; } public boolean isSelectionColumn() { return selectionColumn; } public void setSelectionColumn(boolean selectionColumn) { this.selectionColumn = selectionColumn; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableColumnInfo.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaField.class, CAMUNDA_ELEMENT_FIELD) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaField>() { public CamundaField newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaFieldImpl(instanceContext); } }); camundaNameAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_NAME) .namespace(CAMUNDA_NS) .build(); camundaExpressionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_EXPRESSION) .namespace(CAMUNDA_NS) .build(); camundaStringValueAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_STRING_VALUE) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); camundaExpressionChild = sequenceBuilder.element(CamundaExpression.class) .build(); camundaStringChild = sequenceBuilder.element(CamundaString.class) .build(); typeBuilder.build(); } public CamundaFieldImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getCamundaName() { return camundaNameAttribute.getValue(this); }
public void setCamundaName(String camundaName) { camundaNameAttribute.setValue(this, camundaName); } public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaStringValue() { return camundaStringValueAttribute.getValue(this); } public void setCamundaStringValue(String camundaStringValue) { camundaStringValueAttribute.setValue(this, camundaStringValue); } public CamundaString getCamundaString() { return camundaStringChild.getChild(this); } public void setCamundaString(CamundaString camundaString) { camundaStringChild.setChild(this, camundaString); } public CamundaExpression getCamundaExpressionChild() { return camundaExpressionChild.getChild(this); } public void setCamundaExpressionChild(CamundaExpression camundaExpression) { camundaExpressionChild.setChild(this, camundaExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFieldImpl.java
1
请完成以下Java代码
public abstract class M_HU_SyncTo_ExternalSystem extends ViewBasedProcessTemplate implements IProcessPrecondition, IProcessDefaultParametersProvider { private final ExternalSystemConfigRepo externalSystemConfigRepo = SpringContextHolder.instance.getBean(ExternalSystemConfigRepo.class); @Nullable @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (getExternalSystemParam().equals(parameter.getColumnName())) { final ImmutableList<ExternalSystemParentConfig> activeConfigs = externalSystemConfigRepo.getActiveByType(getExternalSystemType()) .stream() .collect(ImmutableList.toImmutableList()); return activeConfigs.size() == 1 ? activeConfigs.get(0).getChildConfig().getId().getRepoId() : IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE; } @Override public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().size() <= 0) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { addLog("Calling with params: externalSystemChildConfigId: {}", getExternalSystemChildConfigId()); final Set<I_M_HU> hus = getHUsToExport();
final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId(); for (final I_M_HU hu : hus) { final TableRecordReference topLevelHURecordRef = TableRecordReference.of(hu); getExportToHUExternalSystem().exportToExternalSystem(externalSystemChildConfigId, topLevelHURecordRef, getPinstanceId()); } return JavaProcess.MSG_OK; } protected abstract Set<I_M_HU> getHUsToExport(); protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId(); protected abstract ExportHUToExternalSystemService getExportToHUExternalSystem(); protected abstract ExternalSystemType getExternalSystemType(); protected abstract String getExternalSystemParam(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\M_HU_SyncTo_ExternalSystem.java
1
请完成以下Java代码
private static ShapefileDataStore setDataStoreParams(ShapefileDataStoreFactory dataStoreFactory, Map<String, Serializable> params, File shapeFile, SimpleFeatureType CITY) throws Exception { params.put("url", shapeFile.toURI() .toURL()); params.put("create spatial index", Boolean.TRUE); ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); dataStore.createSchema(CITY); return dataStore; } private static void writeToFile(ShapefileDataStore dataStore, DefaultFeatureCollection collection) throws Exception { // If you decide to use the TYPE type and create a Data Store with it, // You will need to uncomment this line to set the Coordinate Reference System // newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName); if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction);
try { featureStore.addFeatures(collection); transaction.commit(); } catch (Exception problem) { problem.printStackTrace(); transaction.rollback(); } finally { transaction.close(); } System.exit(0); // success! } else { System.out.println(typeName + " does not support read/write access"); System.exit(1); } } }
repos\tutorials-master\geotools\src\main\java\com\baeldung\geotools\ShapeFile.java
1