instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private OrgId getOrgId() { if (_adOrgId == null) { _adOrgId = extractOrgId(); } return _adOrgId; } private OrgId extractOrgId() { final Object documentModel = getDocumentModel(); if (documentModel != null) { final Integer adOrgId = InterfaceWrapperHelper.getValueOrNull(documentModel, "AD_Org_ID"); if (adOrgId != null) { return OrgId.ofRepoId(adOrgId); } else { // return Org=* to cover the user case when user clears (temporary) the Org field. return OrgId.ANY; } } // shall not happen throw new DocumentNoBuilderException("Could not get AD_Org_ID"); } @Override public IPreliminaryDocumentNoBuilder setNewDocType(@Nullable final I_C_DocType newDocType) { assertNotBuilt(); _newDocType = newDocType; return this; } private I_C_DocType getNewDocType() { return _newDocType; } @Override public IPreliminaryDocumentNoBuilder setOldDocType_ID(final int oldDocType_ID) { assertNotBuilt(); _oldDocType_ID = oldDocType_ID > 0 ? oldDocType_ID : -1; return this; } private I_C_DocType getOldDocType() { if (_oldDocType == null) { final int oldDocTypeId = _oldDocType_ID; if (oldDocTypeId > 0) { _oldDocType = InterfaceWrapperHelper.create(getCtx(), oldDocTypeId, I_C_DocType.class, ITrx.TRXNAME_None); } } return _oldDocType; } @Override public IPreliminaryDocumentNoBuilder setOldDocumentNo(final String oldDocumentNo) { assertNotBuilt(); _oldDocumentNo = oldDocumentNo; return this; } private String getOldDocumentNo()
{ return _oldDocumentNo; } private boolean isNewDocumentNo() { final String oldDocumentNo = getOldDocumentNo(); if (oldDocumentNo == null) { return true; } if (IPreliminaryDocumentNoBuilder.hasPreliminaryMarkers(oldDocumentNo)) { return true; } return false; } @Override public IPreliminaryDocumentNoBuilder setDocumentModel(final Object documentModel) { _documentModel = documentModel; return this; } private Object getDocumentModel() { Check.assumeNotNull(_documentModel, "_documentModel not null"); return _documentModel; } private java.util.Date getDocumentDate(final String dateColumnName) { final Object documentModel = getDocumentModel(); final Optional<java.util.Date> date = InterfaceWrapperHelper.getValue(documentModel, dateColumnName); return date.orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\PreliminaryDocumentNoBuilder.java
1
请完成以下Java代码
public EqualsBuilder append(final int value1, final int value2) { if (!isEqual) { return this; } if (value1 != value2) { isEqual = false; } return this; } public <T> EqualsBuilder append(final T value1, final T value2) { if (!isEqual) { return this; } if (!Check.equals(value1, value2)) { isEqual = false; } return this; } /** * Append values by reference, so values will be considered equal only if <code>value1 == value2</code>. * * @param value1 * @param value2 * @return this */ public <T> EqualsBuilder appendByRef(final T value1, final T value2) { if (!isEqual) { return this; } if (value1 != value2) { isEqual = false; } return this; } public EqualsBuilder append(final Map<String, Object> map1, final Map<String, Object> map2, final boolean handleEmptyAsNull) { if (!isEqual) { return this; } if (handleEmptyAsNull) { final Object value1 = map1 == null || map1.isEmpty() ? null : map1; final Object value2 = map2 == null || map2.isEmpty() ? null : map2; return append(value1, value2); } return append(map1, map2); } public boolean isEqual() { return isEqual; } /** * Checks and casts <code>other</code> to same class as <code>obj</code>. * * This method shall be used as first statement in an {@link Object#equals(Object)} implementation. <br/> * <br/> * Example: * * <pre> * public boolean equals(Object obj) * { * if (this == obj) * { * return true; * }
* final MyClass other = EqualsBuilder.getOther(this, obj); * if (other == null) * { * return false; * } * * return new EqualsBuilder() * .append(prop1, other.prop1) * .append(prop2, other.prop2) * .append(prop3, other.prop3) * // .... * .isEqual(); * } * </pre> * * @param thisObj this object * @param obj other object * @return <code>other</code> casted to same class as <code>obj</code> or null if <code>other</code> is null or does not have the same class */ public static <T> T getOther(final T thisObj, final Object obj) { if (thisObj == null) { throw new IllegalArgumentException("obj is null"); } if (thisObj == obj) { @SuppressWarnings("unchecked") final T otherCasted = (T)obj; return otherCasted; } if (obj == null) { return null; } if (thisObj.getClass() != obj.getClass()) { return null; } @SuppressWarnings("unchecked") final T otherCasted = (T)obj; return otherCasted; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\EqualsBuilder.java
1
请完成以下Java代码
public ProcessDefinitionBuilder endTransition() { processElement = scopeStack.peek(); transition = null; return this; } public ProcessDefinitionBuilder transition(String destinationActivityId) { return transition(destinationActivityId, null); } public ProcessDefinitionBuilder transition(String destinationActivityId, String transitionId) { startTransition(destinationActivityId, transitionId); endTransition(); return this; } public ProcessDefinitionBuilder behavior(ActivityBehavior activityBehaviour) { getActivity().setActivityBehavior(activityBehaviour); return this; } public ProcessDefinitionBuilder property(String name, Object value) { processElement.setProperty(name, value); return this; } public PvmProcessDefinition buildProcessDefinition() { for (Object[] unresolvedTransition: unresolvedTransitions) { TransitionImpl transition = (TransitionImpl) unresolvedTransition[0]; String destinationActivityName = (String) unresolvedTransition[1]; ActivityImpl destination = processDefinition.findActivity(destinationActivityName); if (destination == null) { throw new RuntimeException("destination '"+destinationActivityName+"' not found. (referenced from transition in '"+transition.getSource().getId()+"')"); } transition.setDestination(destination); } return processDefinition; } protected ActivityImpl getActivity() { return (ActivityImpl) scopeStack.peek(); }
public ProcessDefinitionBuilder scope() { getActivity().setScope(true); return this; } public ProcessDefinitionBuilder executionListener(ExecutionListener executionListener) { if (transition!=null) { transition.addExecutionListener(executionListener); } else { throw new PvmException("not in a transition scope"); } return this; } public ProcessDefinitionBuilder executionListener(String eventName, ExecutionListener executionListener) { if (transition==null) { scopeStack.peek().addExecutionListener(eventName, executionListener); } else { transition.addExecutionListener(executionListener); } return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\ProcessDefinitionBuilder.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_C_DirectDebitLine[") .append(get_ID()).append("]"); return sb.toString(); } @Override public I_C_DirectDebit getC_DirectDebit() throws Exception { return get_ValueAsPO(COLUMNNAME_C_DirectDebit_ID, org.compiere.model.I_C_DirectDebit.class); } /** Set C_DirectDebit_ID. @param C_DirectDebit_ID C_DirectDebit_ID */ @Override public void setC_DirectDebit_ID (int C_DirectDebit_ID) { if (C_DirectDebit_ID < 1) throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory."); set_Value (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID)); } /** Get C_DirectDebit_ID. @return C_DirectDebit_ID */ @Override public int getC_DirectDebit_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID); if (ii == null) return 0; return ii.intValue(); } /** Set C_DirectDebitLine_ID. @param C_DirectDebitLine_ID C_DirectDebitLine_ID */ @Override public void setC_DirectDebitLine_ID (int C_DirectDebitLine_ID) {
if (C_DirectDebitLine_ID < 1) throw new IllegalArgumentException ("C_DirectDebitLine_ID is mandatory."); set_ValueNoCheck (COLUMNNAME_C_DirectDebitLine_ID, Integer.valueOf(C_DirectDebitLine_ID)); } /** Get C_DirectDebitLine_ID. @return C_DirectDebitLine_ID */ @Override public int getC_DirectDebitLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebitLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public I_C_Invoice getC_Invoice() throws Exception { return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class); } /** Set Invoice. @param C_Invoice_ID Invoice Identifier */ @Override public void setC_Invoice_ID (int C_Invoice_ID) { if (C_Invoice_ID < 1) throw new IllegalArgumentException ("C_Invoice_ID is mandatory."); set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID)); } /** Get Invoice. @return Invoice Identifier */ @Override public int getC_Invoice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebitLine.java
1
请完成以下Java代码
public base addElement (String hashcode, Element element) { addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param hashcode * name of element for hash table * @param element * Adds an Element to the element. */ public base addElement (String hashcode, String element) { addElementToRegistry (hashcode, element); return (this); } /** * Adds an Element to the element. * * @param element * Adds an Element to the element. */ public base addElement (Element element) { addElementToRegistry (element); return (this);
} /** * Adds an Element to the element. * * @param element * Adds an Element to the element. */ public base addElement (String element) { addElementToRegistry (element); return (this); } /** * Removes an Element from the element. * * @param hashcode * the name of the element to be removed. */ public base removeElement (String hashcode) { removeElementFromRegistry (hashcode); return (this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\base.java
1
请完成以下Java代码
public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } public int getRevisionNext() { return revision+1; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public Set<Expression> getCandidateStarterUserIdExpressions() { return candidateStarterUserIdExpressions; } public void addCandidateStarterUserIdExpression(Expression userId) { candidateStarterUserIdExpressions.add(userId); } public Set<Expression> getCandidateStarterGroupIdExpressions() { return candidateStarterGroupIdExpressions; } public void addCandidateStarterGroupIdExpression(Expression groupId) { candidateStarterGroupIdExpressions.add(groupId); } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
public String getVersionTag() { return versionTag; } public void setVersionTag(String versionTag) { this.versionTag = versionTag; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public void setHistoryTimeToLive(Integer historyTimeToLive) { this.historyTimeToLive = historyTimeToLive; } public boolean isStartableInTasklist() { return isStartableInTasklist; } public void setStartableInTasklist(boolean isStartableInTasklist) { this.isStartableInTasklist = isStartableInTasklist; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessDefinitionEntity.java
1
请完成以下Java代码
public final class EncodingCursorStrategy<T> implements CursorStrategy<T> { private final CursorStrategy<T> delegate; private final CursorEncoder encoder; EncodingCursorStrategy(CursorStrategy<T> strategy, CursorEncoder encoder) { Assert.notNull(strategy, "CursorStrategy is required"); Assert.notNull(encoder, "CursorEncoder is required"); Assert.isTrue(!(strategy instanceof EncodingCursorStrategy<?>), "CursorStrategy already has encoding"); this.delegate = strategy; this.encoder = encoder; } /** * Return the decorated {@link CursorStrategy}. */ public CursorStrategy<T> getDelegate() { return this.delegate; } /**
* Return the configured {@link CursorEncoder}. */ public CursorEncoder getEncoder() { return this.encoder; } @Override public boolean supports(Class<?> targetType) { return this.delegate.supports(targetType); } @Override public String toCursor(T position) { String cursor = this.delegate.toCursor(position); return this.encoder.encode(cursor); } @Override public T fromCursor(String cursor) { String decodedCursor = this.encoder.decode(cursor); return this.delegate.fromCursor(decodedCursor); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\pagination\EncodingCursorStrategy.java
1
请完成以下Java代码
public BigDecimal mkPriceStdMinusDiscount() { calculatePrice(false); return result.getDiscount().subtractFromBase(result.getPriceStd(), result.getPrecision().toInt()); } @Override public String toString() { return "MProductPricing [" + pricingCtx + ", " + result + "]"; } public void setConvertPriceToContextUOM(boolean convertPriceToContextUOM) { pricingCtx.setConvertPriceToContextUOM(convertPriceToContextUOM); } public void setReferencedObject(Object referencedObject) { pricingCtx.setReferencedObject(referencedObject); } // metas: end public int getC_TaxCategory_ID()
{ return TaxCategoryId.toRepoId(result.getTaxCategoryId()); } public boolean isManualPrice() { return pricingCtx.getManualPriceEnabled().isTrue(); } public void setManualPrice(boolean manualPrice) { pricingCtx.setManualPriceEnabled(manualPrice); } public void throwProductNotOnPriceListException() { throw new ProductNotOnPriceListException(pricingCtx); } } // MProductPrice
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProductPricing.java
1
请完成以下Java代码
public int getMKTG_Platform_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Kennwort. @param Password Kennwort */ @Override public void setPassword (java.lang.String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Kennwort. @return Kennwort */ @Override public java.lang.String getPassword () { return (java.lang.String)get_Value(COLUMNNAME_Password); }
/** Set Registered EMail. @param UserName Email of the responsible for the System */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java-gen\de\metas\marketing\cleverreach\model\X_MKTG_CleverReach_Config.java
1
请完成以下Java代码
public abstract class HistoricDetailEntityImpl extends AbstractEntityNoRevision implements HistoricDetailEntity, Serializable { private static final long serialVersionUID = 1L; protected String processInstanceId; protected String activityInstanceId; protected String taskId; protected String executionId; protected Date time; protected String detailType; public Object getPersistentState() { // details are not updatable so we always provide the same object as the state return HistoricDetailEntityImpl.class; } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId;
} public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityImpl.java
1
请完成以下Java代码
protected ListenableFuture<JsonNode> buildAlarmDetails(TbMsg msg, JsonNode previousDetails) { try { TbMsg dummyMsg = msg; if (previousDetails != null) { TbMsgMetaData metaData = msg.getMetaData().copy(); metaData.putValue(PREV_ALARM_DETAILS, JacksonUtil.toString(previousDetails)); dummyMsg = msg.transform() .metaData(metaData) .build(); } return scriptEngine.executeJsonAsync(dummyMsg); } catch (Exception e) { return Futures.immediateFailedFuture(e); } } public static TbMsg toAlarmMsg(TbContext ctx, TbAlarmResult alarmResult, TbMsg originalMsg) { JsonNode jsonNodes = JacksonUtil.valueToTree(alarmResult.alarm); String data = jsonNodes.toString(); TbMsgMetaData metaData = originalMsg.getMetaData().copy(); if (alarmResult.isCreated) { metaData.putValue(DataConstants.IS_NEW_ALARM, Boolean.TRUE.toString()); } else if (alarmResult.isUpdated || alarmResult.isSeverityUpdated) { metaData.putValue(DataConstants.IS_EXISTING_ALARM, Boolean.TRUE.toString()); } else if (alarmResult.isCleared) { metaData.putValue(DataConstants.IS_CLEARED_ALARM, Boolean.TRUE.toString()); }
return ctx.transformMsg(originalMsg, TbMsgType.ALARM, originalMsg.getOriginator(), metaData, data); } @Override public void destroy() { if (scriptEngine != null) { scriptEngine.destroy(); } } private void tellNext(TbContext ctx, TbMsg msg, TbAlarmResult alarmResult, TbMsgType actionMsgType, String alarmAction) { ctx.enqueue(ctx.alarmActionMsg(alarmResult.alarm, ctx.getSelfId(), actionMsgType), () -> ctx.tellNext(toAlarmMsg(ctx, alarmResult, msg), alarmAction), throwable -> ctx.tellFailure(toAlarmMsg(ctx, alarmResult, msg), throwable)); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbAbstractAlarmNode.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog; } public boolean isDeletionLog() { return deletionLog; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); result.id = historicExternalTaskLog.getId();
result.timestamp = historicExternalTaskLog.getTimestamp(); result.removalTime = historicExternalTaskLog.getRemovalTime(); result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); result.topicName = historicExternalTaskLog.getTopicName(); result.workerId = historicExternalTaskLog.getWorkerId(); result.priority = historicExternalTaskLog.getPriority(); result.retries = historicExternalTaskLog.getRetries(); result.errorMessage = historicExternalTaskLog.getErrorMessage(); result.activityId = historicExternalTaskLog.getActivityId(); result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); result.executionId = historicExternalTaskLog.getExecutionId(); result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); result.tenantId = historicExternalTaskLog.getTenantId(); result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); result.creationLog = historicExternalTaskLog.isCreationLog(); result.failureLog = historicExternalTaskLog.isFailureLog(); result.successLog = historicExternalTaskLog.isSuccessLog(); result.deletionLog = historicExternalTaskLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricExternalTaskLogDto.java
1
请完成以下Java代码
public void setValueMin (java.lang.String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Wert. @return Minimum Value for a field */ @Override public java.lang.String getValueMin () { return (java.lang.String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/ @Override public void setVFormat (java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public java.lang.String getVFormat () { return (java.lang.String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Para.java
1
请完成以下Java代码
public class ProprietaryBankTransactionCodeStructure1 { @XmlElement(name = "Cd", required = true) protected String cd; @XmlElement(name = "Issr") protected String issr; /** * Gets the value of the cd property. * * @return * possible object is * {@link String } * */ public String getCd() { return cd; } /** * Sets the value of the cd property. * * @param value * allowed object is * {@link String } * */ public void setCd(String value) {
this.cd = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String } * */ public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ProprietaryBankTransactionCodeStructure1.java
1
请完成以下Java代码
public class ZKCreate { // create static instance for zookeeper class. private static ZooKeeper zk; // create static instance for ZooKeeperConnection class. private static ZooKeeperConnection conn; // Method to create znode in zookeeper ensemble public static void create(String path, byte[] data) throws KeeperException, InterruptedException { zk.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } public static void main(String[] args) {
// znode path String path = ZKConstants.ZK_FIRST_PATH; // Assign path to znode // data in byte array byte[] data = "My first zookeeper app".getBytes(); // Declare data try { conn = new ZooKeeperConnection(); zk = conn.connect(ZKConstants.ZK_HOST); create(path, data); // Create the data to the specified path conn.close(); } catch (Exception e) { System.out.println(e.getMessage()); //Catch error message } } }
repos\spring-boot-quick-master\quick-zookeeper\src\main\java\com\quick\zookeeper\client\ZKCreate.java
1
请完成以下Java代码
protected HistoricCaseInstanceEventEntity loadCaseInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { final String caseInstanceId = caseExecutionEntity.getCaseInstanceId(); HistoricCaseInstanceEventEntity cachedEntity = findInCache(HistoricCaseInstanceEventEntity.class, caseInstanceId); if (cachedEntity != null) { return cachedEntity; } else { return newCaseInstanceEventEntity(caseExecutionEntity); } } @Override protected HistoricCaseActivityInstanceEventEntity loadCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) { final String caseActivityInstanceId = caseExecutionEntity.getId();
HistoricCaseActivityInstanceEventEntity cachedEntity = findInCache(HistoricCaseActivityInstanceEventEntity.class, caseActivityInstanceId); if (cachedEntity != null) { return cachedEntity; } else { return newCaseActivityInstanceEventEntity(caseExecutionEntity); } } /** find a cached entity by primary key */ protected <T extends HistoryEvent> T findInCache(Class<T> type, String id) { return Context.getCommandContext() .getDbEntityManager() .getCachedEntity(type, id); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\CacheAwareCmmnHistoryEventProducer.java
1
请完成以下Java代码
public IAttributeSplitterStrategy retrieveSplitterStrategy() { return splitterStrategy; } @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return transferStrategy; } @Override public boolean isUseInASI() { return false; } @Override public boolean isDefinedByTemplate() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public boolean isReadonlyUI() { return false; } @Override public boolean isDisplayedUI() { return true; } @Override public boolean isMandatory() { return false; }
@Override public boolean isNew() { return isGeneratedAttribute; } @Override protected void setInternalValueDate(Date value) { this.valueDate = value; } @Override protected Date getInternalValueDate() { return valueDate; } @Override protected void setInternalValueDateInitial(Date value) { this.valueInitialDate = value; } @Override protected Date getInternalValueDateInitial() { return valueInitialDate; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\PlainAttributeValue.java
1
请在Spring Boot框架中完成以下Java代码
public void setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; } public Transport getTransport() { return this.transport; } public void setTransport(Transport transport) { this.transport = transport; } public Compression getCompression() { return this.compression; } public void setCompression(Compression compression) { this.compression = compression; } public Map<String, String> getHeaders() { return this.headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; }
public enum Compression { /** * Gzip compression. */ GZIP, /** * No compression. */ NONE } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\otlp\OtlpTracingProperties.java
2
请完成以下Java代码
public static class ConfigRequestForNewInstance { @NonNull OrgId orgId; @NonNull BPartnerId salesRepBPartnerId; /** * Needed because config settings can be specific to the customer's group. */ @NonNull BPartnerId customerBPartnerId; /** * Needed because config settings can be specific to the product's category. */ @NonNull ProductId salesProductId; @NonNull LocalDate commissionDate; @NonNull Hierarchy commissionHierarchy; @NonNull CommissionTriggerType commissionTriggerType;
public boolean isCustomerTheSalesRep() { return customerBPartnerId.equals(salesRepBPartnerId); } } @Builder @Value public static class ConfigRequestForExistingInstance { @NonNull ImmutableList<FlatrateTermId> contractIds; @NonNull BPartnerId customerBPartnerId; @NonNull ProductId salesProductId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionConfigProvider.java
1
请完成以下Java代码
public de.metas.handlingunits.model.I_M_HU_PI_Item getM_HU_PI_Item() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class); } @Override public void setM_HU_PI_Item(final de.metas.handlingunits.model.I_M_HU_PI_Item M_HU_PI_Item) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class, M_HU_PI_Item); } @Override public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID) { if (M_HU_PI_Item_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID); } @Override public int getM_HU_PI_Item_ID()
{ return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item.java
1
请完成以下Java代码
protected String doIt() throws Exception { final int accountLockExpire = Services.get(ISysConfigBL.class).getIntValue("USERACCOUNT_LOCK_EXPIRE", 30); final String sql = "SELECT * FROM AD_User" + " WHERE IsAccountLocked = 'Y'"; PreparedStatement pstmt = null; ResultSet rs = null; int no = 0; try { pstmt = DB.prepareStatement(sql, get_TrxName()); rs = pstmt.executeQuery(); while (rs.next()) { final int AD_User_IDToUnlock = rs.getInt(org.compiere.model.I_AD_User.COLUMNNAME_AD_User_ID); no = no + unlockUser(accountLockExpire, AD_User_IDToUnlock); } } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return "Unlock accounts: " + no; } // doIt private int unlockUser(final int accountLockExpire, final int AD_User_IDToUnlock) { final int result[] = { 0 }; Services.get(ITrxManager.class).runInNewTrx(new TrxRunnable() { @Override public void run(final String localTrxName) throws Exception { final org.compiere.model.I_AD_User user = InterfaceWrapperHelper.create(getCtx(), AD_User_IDToUnlock, I_AD_User.class, localTrxName);
final Timestamp curentLogin = (new Timestamp(System.currentTimeMillis())); final long loginFailureTime = user.getLoginFailureDate().getTime(); final long newloginFailureTime = loginFailureTime + (1000 * 60 * accountLockExpire); final Timestamp acountUnlock = new Timestamp(newloginFailureTime); if (curentLogin.compareTo(acountUnlock) > 0) { user.setLoginFailureCount(0); user.setIsAccountLocked(false); InterfaceWrapperHelper.save(user); result[0] = 1; } } }); return result[0]; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_ExpireLocks.java
1
请完成以下Java代码
public ICNetAmtToInvoiceChecker setNetAmtToInvoiceExpected(final BigDecimal netAmtToInvoiceExpected) { this._netAmtToInvoiceExpected = netAmtToInvoiceExpected; return this; } @Override public void add(@NonNull final I_C_Invoice_Candidate ic) { final BigDecimal icLineNetAmt = ic.getNetAmtToInvoice(); _netAmtToInvoice = _netAmtToInvoice.add(icLineNetAmt); _countInvoiceCandidates++; } @Override public BigDecimal getValue() { return _netAmtToInvoice; } /** * Asserts aggregated net amount to invoice equals with given expected value (if set). * * The expected amount is set using {@link #setNetAmtToInvoiceExpected(BigDecimal)}. * * @see #assertExpectedNetAmtToInvoice(BigDecimal) */ public void assertExpectedNetAmtToInvoiceIfSet() { if (_netAmtToInvoiceExpected == null) { return; } assertExpectedNetAmtToInvoice(_netAmtToInvoiceExpected); } /** * Asserts aggregated net amount to invoice equals with given expected value. * * If it's not equal, an error message will be logged to {@link ILoggable}. * * @throws AdempiereException if the checksums are not equal and {@link #isFailIfNetAmtToInvoiceChecksumNotMatch()}.
*/ public void assertExpectedNetAmtToInvoice(@NonNull final BigDecimal netAmtToInvoiceExpected) { Check.assume(netAmtToInvoiceExpected.signum() != 0, "netAmtToInvoiceExpected != 0"); final BigDecimal netAmtToInvoiceActual = getValue(); if (netAmtToInvoiceExpected.compareTo(netAmtToInvoiceActual) != 0) { final String errmsg = "NetAmtToInvoice checksum not match" + "\n Expected: " + netAmtToInvoiceExpected + "\n Actual: " + netAmtToInvoiceActual + "\n Invoice candidates count: " + _countInvoiceCandidates; Loggables.addLog(errmsg); if (isFailIfNetAmtToInvoiceChecksumNotMatch()) { throw new AdempiereException(errmsg); } } } /** * @return true if we shall fail if the net amount to invoice checksum does not match. */ public final boolean isFailIfNetAmtToInvoiceChecksumNotMatch() { final boolean failIfNetAmtToInvoiceChecksumNotMatchDefault = true; return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_FailIfNetAmtToInvoiceChecksumNotMatch, failIfNetAmtToInvoiceChecksumNotMatchDefault); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ICNetAmtToInvoiceChecker.java
1
请完成以下Java代码
public void windowOpened(WindowEvent e) { findPanel.requestFocus(); } @Override public void windowClosing(WindowEvent e) { findPanel.doCancel(); } }); AEnv.showCenterWindow(builder.getParentFrame(), this); } // Find @Override public void dispose() { findPanel.dispose(); removeAll(); super.dispose(); } // dispose
/************************************************************************** * Get Query - Retrieve result * * @return String representation of query */ public MQuery getQuery() { return findPanel.getQuery(); } // getQuery /** * @return true if cancel button pressed */ public boolean isCancel() { return findPanel.isCancel(); } } // Find
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\Find.java
1
请完成以下Java代码
public int getC_DocType_Sequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_Sequence_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Sequence getDocNoSequence() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setDocNoSequence(org.compiere.model.I_AD_Sequence DocNoSequence) { set_ValueFromPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class, DocNoSequence); } /** Set Nummernfolgen für Belege. @param DocNoSequence_ID Document sequence determines the numbering of documents */ @Override public void setDocNoSequence_ID (int DocNoSequence_ID) { if (DocNoSequence_ID < 1)
set_Value (COLUMNNAME_DocNoSequence_ID, null); else set_Value (COLUMNNAME_DocNoSequence_ID, Integer.valueOf(DocNoSequence_ID)); } /** Get Nummernfolgen für Belege. @return Document sequence determines the numbering of documents */ @Override public int getDocNoSequence_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DocNoSequence_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_DocType_Sequence.java
1
请完成以下Java代码
public String getDateFormatPattern() { return dateFormatPattern; } public void setDateFormatPattern(String dateFormatPattern) { this.dateFormatPattern = dateFormatPattern; } public Date parse(String value) throws DateTimeException { DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder() .appendPattern(getDateFormatPattern()) .toFormatter() .withZone(getZoneId()); try { ZonedDateTime zonedDateTime = dateTimeFormatter.parse(value, ZonedDateTime::from); return Date.from(zonedDateTime.toInstant()); } catch (DateTimeException e) { LocalDate localDate = dateTimeFormatter.parse(String.valueOf(value), LocalDate::from); return Date.from(localDate.atStartOfDay().atZone(getZoneId()).toInstant()); } } public Date toDate(Object value) { if (value instanceof String) { return parse((String) value); } if (value instanceof Date) { return (Date) value; } if (value instanceof Long) { return new Date((long) value);
} if (value instanceof LocalDate) { return Date.from(((LocalDate) value).atStartOfDay(getZoneId()).toInstant()); } if (value instanceof LocalDateTime) { return Date.from(((LocalDateTime) value).atZone(getZoneId()).toInstant()); } if (value instanceof ZonedDateTime) { return Date.from(((ZonedDateTime) value).toInstant()); } throw new DateTimeException( MessageFormat.format("Error while parsing date. Type: {0}, value: {1}", value.getClass().getName(), value) ); } }
repos\Activiti-develop\activiti-core-common\activiti-common-util\src\main\java\org\activiti\common\util\DateFormatterProvider.java
1
请完成以下Java代码
public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRestartedProcessInstanceId() { return restartedProcessInstanceId; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId) { this.restartedProcessInstanceId = restartedProcessInstanceId; } @Override public String toString() { return this.getClass().getSimpleName() + "[businessKey=" + businessKey + ", startUserId=" + startUserId
+ ", superProcessInstanceId=" + superProcessInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", superCaseInstanceId=" + superCaseInstanceId + ", deleteReason=" + deleteReason + ", durationInMillis=" + durationInMillis + ", startTime=" + startTime + ", endTime=" + endTime + ", removalTime=" + removalTime + ", endActivityId=" + endActivityId + ", startActivityId=" + startActivityId + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", tenantId=" + tenantId + ", restartedProcessInstanceId=" + restartedProcessInstanceId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricProcessInstanceEventEntity.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeWithAnnotation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToOne private Address address; @ManyToOne private Department department; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } }
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\undeterminejdbctype\EmployeeWithAnnotation.java
2
请在Spring Boot框架中完成以下Java代码
public SysTableWhiteList autoAdd(String tableName, String fieldName) { if (oConvertUtils.isEmpty(tableName)) { throw new JeecgBootException("操作失败,表名不能为空!"); } if (oConvertUtils.isEmpty(fieldName)) { throw new JeecgBootException("操作失败,字段名不能为空!"); } // 统一转换成小写 tableName = tableName.toLowerCase(); fieldName = fieldName.toLowerCase(); // 查询是否已经存在 LambdaQueryWrapper<SysTableWhiteList> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(SysTableWhiteList::getTableName, tableName); SysTableWhiteList getEntity = super.getOne(queryWrapper); if (getEntity != null) { // 如果已经存在,并且已禁用,则抛出异常 if (CommonConstant.STATUS_0.equals(getEntity.getStatus())) { throw new JeecgBootException("[白名单] 表名已存在,但是已被禁用,请先启用!tableName=" + tableName); } // 合并字段 Set<String> oldFieldSet = new HashSet<>(Arrays.asList(getEntity.getFieldName().split(","))); Set<String> newFieldSet = new HashSet<>(Arrays.asList(fieldName.split(","))); oldFieldSet.addAll(newFieldSet); getEntity.setFieldName(String.join(",", oldFieldSet)); this.checkEntity(getEntity); super.updateById(getEntity); log.info("修改表单白名单项,表名:{},oldFieldSet: {},newFieldSet:{}", tableName, oldFieldSet.toArray(), newFieldSet.toArray()); return getEntity; } else { // 新增白名单项 SysTableWhiteList saveEntity = new SysTableWhiteList();
saveEntity.setTableName(tableName); saveEntity.setFieldName(fieldName); saveEntity.setStatus(CommonConstant.STATUS_1); this.checkEntity(saveEntity); super.save(saveEntity); log.info("新增表单白名单项: 表名:{},配置 > {}", tableName, saveEntity.toString()); return saveEntity; } } @Override public Map<String, String> getAllConfigMap() { Map<String, String> map = new HashMap<>(); List<SysTableWhiteList> allData = super.list(); for (SysTableWhiteList item : allData) { // 只有启用的才放入map if (CommonConstant.STATUS_1.equals(item.getStatus())) { // 表名和字段名都转成小写,防止大小写不一致 map.put(item.getTableName().toLowerCase(), item.getFieldName().toLowerCase()); } } return map; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysTableWhiteListServiceImpl.java
2
请完成以下Java代码
public String toString() { return toDocumentId().toJson(); } public DocumentId toDocumentId() { DocumentId id = _documentId; if (id == null) { final String idStr = DOCUMENT_ID_JOINER.join( pickingSlotId != null ? pickingSlotId.getRepoId() : 0, huId != null ? huId.getRepoId() : null, huStorageProductId > 0 ? huStorageProductId : null); id = _documentId = DocumentId.ofString(idStr); } return id; } /** @return {@code true} if this row ID represents an actual picking slot and not any sort of HU that is also shown in this view. */ public boolean isPickingSlotRow() {
return getPickingSlotId() != null && getHuId() == null; } /** @return {@code true} is this row ID represents an HU that is assigned to a picking slot */ public boolean isPickedHURow() { return getPickingSlotId() != null && getHuId() != null; } /** @return {@code true} if this row ID represents an HU that is a source-HU for fine-picking. */ public boolean isPickingSourceHURow() { return getPickingSlotId() == null && getHuId() != null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRowId.java
1
请完成以下Java代码
public class GrpcServerStartedEvent extends GrpcServerLifecycleEvent { private static final long serialVersionUID = 1L; private final String address; private final int port; /** * Creates a new GrpcServerStartedEvent. * * @param lifecyle The lifecycle that caused this event. * @param clock The clock used to determine the timestamp. * @param server The server related to this event. * @param address The address the server is bound to. * @param port The port the server is bound to or {@code -1} if it isn't bound to a particular port. */ public GrpcServerStartedEvent( final GrpcServerLifecycle lifecyle, final Clock clock, final Server server, final String address, final int port) { super(lifecyle, clock, server); this.address = requireNonNull(address, "address"); this.port = port; } /** * Creates a new GrpcServerStartedEvent. * * @param lifecyle The lifecycle that caused this event. * @param server The server related to this event. * @param address The address the server is bound to. * @param port The port the server is bound to or {@code -1} if it isn't bound to a particular port. */ public GrpcServerStartedEvent(
final GrpcServerLifecycle lifecyle, final Server server, final String address, final int port) { super(lifecyle, server); this.address = requireNonNull(address, "address"); this.port = port; } /** * Gets the address the server server was started with. * * @return The address to use. */ public String getAddress() { return this.address; } /** * Gets the main port the server uses. * * @return The main port of the server. {@code -1} indicates that the server isn't bound to a particular port. */ public int getPort() { return this.port; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\event\GrpcServerStartedEvent.java
1
请完成以下Java代码
public String getElementId() { return innerPlanItemInstance.getElementId(); } @Override public String getPlanItemDefinitionId() { return innerPlanItemInstance.getPlanItemDefinitionId(); } @Override public String getStageInstanceId() { return innerPlanItemInstance.getStageInstanceId(); } @Override public String getState() {
return innerPlanItemInstance.getState(); } @Override public String toString() { return "SignalEventListenerInstanceImpl{" + "id='" + getId() + '\'' + ", name='" + getName() + '\'' + ", caseInstanceId='" + getCaseInstanceId() + '\'' + ", caseDefinitionId='" + getCaseDefinitionId() + '\'' + ", elementId='" + getElementId() + '\'' + ", planItemDefinitionId='" + getPlanItemDefinitionId() + '\'' + ", stageInstanceId='" + getStageInstanceId() + '\'' + '}'; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\SignalEventListenerInstanceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Queue AMessage() { return new Queue("fanout.A"); } @Bean public Queue BMessage() { return new Queue("fanout.B"); } @Bean public Queue CMessage() { return new Queue("fanout.C"); } //===============以上是验证Fanout Exchange的队列========== @Bean TopicExchange exchange() { return new TopicExchange("exchange"); } @Bean FanoutExchange fanoutExchange() { return new FanoutExchange("fanoutExchange"); } /** * 将队列topic.message与exchange绑定,binding_key为topic.message,就是完全匹配 * @param queueMessage * @param exchange * @return */ @Bean Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message"); } /** * 将队列topic.messages与exchange绑定,binding_key为topic.#,模糊匹配 * @param queueMessages * @param exchange * @return */ @Bean Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#"); } @Bean Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(AMessage).to(fanoutExchange); } @Bean Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(BMessage).to(fanoutExchange); } @Bean Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(CMessage).to(fanoutExchange); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //必须是prototype类型 public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); return template; } }
repos\spring-boot-quick-master\quick-rabbitmq\src\main\java\com\quick\mq\config\RabbitConfig.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return String.format("Employee[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); } }
repos\tutorials-master\vaadin\src\main\java\com\baeldung\data\Employee.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Book> getBooks() {
return books; } public void setBooks(Set<Book> books) { this.books = books; } @PreRemove private void removeBookAssociations() { for (Book book : this.books) { book.getAuthors().remove(this); } } }
repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\java\com\baeldung\manytomanyremoval\Author.java
1
请完成以下Java代码
public ApiRequestIterator getByQuery(@NonNull final ApiRequestQuery query) { final IQueryBuilder<I_API_Request_Audit> apiRequestQueryBuilder = queryBL.createQueryBuilder(I_API_Request_Audit.class) .addInArrayFilter(I_API_Request_Audit.COLUMNNAME_Status, query.getApiRequestStatusCodeSet()); if (query.getIsErrorAcknowledged() != null) { apiRequestQueryBuilder.addEqualsFilter(I_API_Request_Audit.COLUMNNAME_IsErrorAcknowledged, query.getIsErrorAcknowledged()); } final IQuery<I_API_Request_Audit> apiRequestAuditQuery = apiRequestQueryBuilder.create(); final IQueryOrderByBuilder<I_API_Request_Audit> orderBy = queryBL.createQueryOrderByBuilder(I_API_Request_Audit.class); if (query.isOrderByTimeAscending()) { orderBy.addColumnAscending(I_API_Request_Audit.COLUMNNAME_Time); } else { orderBy.addColumnAscending(I_API_Request_Audit.COLUMNNAME_API_Request_Audit_ID); } apiRequestAuditQuery.setOrderBy(orderBy.createQueryOrderBy()); final int bufferSize = sysConfigBL.getIntValue(SYS_CONFIG_ITERATOR_BUFFER_SIZE, -1); if (bufferSize > 0) { apiRequestAuditQuery.setOption(IQuery.OPTION_IteratorBufferSize, bufferSize); } final Iterator<I_API_Request_Audit> apiRequestRecordsIterator = apiRequestAuditQuery.iterate(I_API_Request_Audit.class); return ApiRequestIterator.of(apiRequestRecordsIterator, ApiRequestAuditRepository::recordToRequestAudit); } public void deleteRequestAudit(@NonNull final ApiRequestAuditId apiRequestAuditId) { final I_API_Request_Audit record = InterfaceWrapperHelper.load(apiRequestAuditId, I_API_Request_Audit.class); InterfaceWrapperHelper.deleteRecord(record);
} @NonNull public static ApiRequestAudit recordToRequestAudit(@NonNull final I_API_Request_Audit record) { return ApiRequestAudit.builder() .apiRequestAuditId(ApiRequestAuditId.ofRepoId(record.getAPI_Request_Audit_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .roleId(RoleId.ofRepoId(record.getAD_Role_ID())) .userId(UserId.ofRepoId(record.getAD_User_ID())) .apiAuditConfigId(ApiAuditConfigId.ofRepoId(record.getAPI_Audit_Config_ID())) .status(Status.ofCode(record.getStatus())) .isErrorAcknowledged(record.isErrorAcknowledged()) .body(record.getBody()) .method(HttpMethod.ofNullableCode(record.getMethod())) .path(record.getPath()) .remoteAddress(record.getRemoteAddr()) .remoteHost(record.getRemoteHost()) .time(TimeUtil.asInstantNonNull(record.getTime())) .httpHeaders(record.getHttpHeaders()) .requestURI(record.getRequestURI()) .uiTraceExternalId(UITraceExternalId.ofNullableString(record.getUI_Trace_ExternalId())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\request\ApiRequestAuditRepository.java
1
请完成以下Java代码
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Configure AuthenticationPrincipal template resolution * <p> * By default, this value is <code>null</code>, which indicates that templates should * not be resolved. * @param templateDefaults - whether to resolve AuthenticationPrincipal templates * parameters * @since 6.4 */ public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) { this.useAnnotationTemplate = templateDefaults != null; this.scanner = SecurityAnnotationScanners.requireUnique(AuthenticationPrincipal.class, templateDefaults); } /** * Obtains the specified {@link Annotation} on the specified {@link MethodParameter}. * {@link MethodParameter} * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */ private @Nullable AuthenticationPrincipal findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) { return this.scanner.scan(parameter.getParameter()); } AuthenticationPrincipal annotation = parameter.getParameterAnnotation(this.annotationType); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType); if (annotation != null) { return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize(); } } return null; } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\AuthenticationPrincipalArgumentResolver.java
1
请完成以下Java代码
public List<String> getSourceColumnNames() { return Collections.emptyList(); } /** * Updates the ASI of the <code>C_Order_Line_Alloc</code>'s <code>C_OrderLine</code> with the BPartner's ADR attribute, <b>if</b> that order line is a purchase order line. */ @Override public void modelChanged(Object model) { final I_C_Order_Line_Alloc alloc = InterfaceWrapperHelper.create(model, I_C_Order_Line_Alloc.class); final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(alloc.getC_OrderLine(), I_C_OrderLine.class); // final boolean forceApply = isEDIInput(alloc); // task 08692: We needed to copy the attribute even if it's a SO transaction, if this OL_Cand is about EDI, however... final boolean forceApply = false; // task 08803 ...as of now, EDI-order lines shall have the same attribute values that manually created order lines have. new BPartnerAwareAttributeUpdater() .setBPartnerAwareFactory(OrderLineBPartnerAware.factory)
.setBPartnerAwareAttributeService(Services.get(IADRAttributeBL.class)) .setSourceModel(orderLine) .setForceApplyForSOTrx(forceApply) .updateASI(); } @SuppressWarnings("unused") private boolean isEDIInput(final I_C_Order_Line_Alloc alloc) { // Services final IEDIOLCandBL ediOLCandBL = Services.get(IEDIOLCandBL.class); final I_C_OLCand olCand = alloc.getC_OLCand(); return ediOLCandBL.isEDIInput(olCand); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\listeners\adr\OrderLineAllocADRModelAttributeSetInstanceListener.java
1
请完成以下Java代码
public String getValue() { return this.value; } @Override public String toString() { return "AuthenticatorAttachment [" + this.value + "]"; } /** * Gets an instance of {@link AuthenticatorAttachment} based upon the value passed in. * @param value the value to obtain the {@link AuthenticatorAttachment} * @return the {@link AuthenticatorAttachment} */ public static AuthenticatorAttachment valueOf(String value) { switch (value) { case "cross-platform": return CROSS_PLATFORM; case "platform":
return PLATFORM; default: return new AuthenticatorAttachment(value); } } public static AuthenticatorAttachment[] values() { return new AuthenticatorAttachment[] { CROSS_PLATFORM, PLATFORM }; } @Serial private Object readResolve() throws ObjectStreamException { return valueOf(this.value); } }
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorAttachment.java
1
请完成以下Java代码
public class ScannedCode { private final String code; private ScannedCode(@NonNull final Object obj) { this.code = normalizeCode(obj); if (this.code == null) { throw new AdempiereException("code is blank"); } } @Nullable private static String normalizeCode(@Nullable final Object obj) { return obj != null ? StringUtils.trimBlankToNull(obj.toString()) : null; } public static ScannedCode ofString(@NonNull final String code) {return new ScannedCode(code);} @Nullable public static ScannedCode ofNullableString(@Nullable final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); return codeNorm != null ? new ScannedCode(codeNorm) : null; }
@Nullable @JsonCreator(mode = JsonCreator.Mode.DELEGATING) // IMPORTANT: keep it here because we want to handle the case when the JSON value is empty string, number etc. public static ScannedCode ofNullableObject(@Nullable final Object obj) { final String code = normalizeCode(obj); return code != null ? new ScannedCode(code) : null; } @Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() {return code;} public GlobalQRCode toGlobalQRCode() {return toGlobalQRCodeIfMatching().orThrow();} public GlobalQRCodeParseResult toGlobalQRCodeIfMatching() {return GlobalQRCode.parse(code);} public PrintableScannedCode toPrintableScannedCode() {return PrintableScannedCode.of(this);} public String substring(final int beginIndex, final int endIndex) {return code.substring(beginIndex, endIndex);} public int length() {return code.length();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scannable_code\ScannedCode.java
1
请完成以下Java代码
public static List<UserProfileDto> fromUserList(List<User> sourceList) { List<UserProfileDto> resultList = new ArrayList<UserProfileDto>(); for (User user : sourceList) { resultList.add(fromUser(user)); } return resultList; } public void update(User dbUser) { dbUser.setId(getId()); dbUser.setFirstName(getFirstName()); dbUser.setLastName(getLastName()); dbUser.setEmail(getEmail()); } // getter / setters //////////////////////////////////// public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName;
} public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserProfileDto.java
1
请在Spring Boot框架中完成以下Java代码
static class CachingConnectionFactoryConfiguration { @Bean(name = "jmsConnectionFactory") CachingConnectionFactory cachingJmsConnectionFactory(JmsProperties jmsProperties, ArtemisProperties properties, ArtemisConnectionDetails connectionDetails, ListableBeanFactory beanFactory) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); CachingConnectionFactory connectionFactory = new CachingConnectionFactory( createJmsConnectionFactory(properties, connectionDetails, beanFactory)); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); return connectionFactory; } } } @Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class }) @ConditionalOnBooleanProperty("spring.artemis.pool.enabled") static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") JmsPoolConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties, ArtemisConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails) .createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new); return new JmsPoolConnectionFactoryFactory(properties.getPool()) .createPooledConnectionFactory(connectionFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisConnectionFactoryConfiguration.java
2
请完成以下Spring Boot application配置
spring.application.name=account-service server.port=8081 spring.datasource.url=jdbc:mysql://172.16.2.101:3306/db_seata?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 seata.tx-service-group=my_test_tx_group mybatis.mapper-locations=classpath*:mapper/*Mapper.xml seat
a.service.grouplist=172.16.2.101:8091 logging.level.io.seata=info logging.level.io.seata.samples.account.persistence.AccountMapper=debug
repos\SpringBootLearning-master (1)\springboot-seata\sbm-account-service\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public void createSmsCode(HttpServletRequest request, HttpServletResponse response, String mobile) { SmsCode smsCode = createSMSCode(); sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_SMS_CODE + mobile, smsCode); // 输出验证码到控制台代替短信发送服务 System.out.println("您的登录验证码为:" + smsCode.getCode() + ",有效时间为60秒"); } private SmsCode createSMSCode() { String code = RandomStringUtils.randomNumeric(6); return new SmsCode(code, 60); } private ImageCode createImageCode() { int width = 100; // 验证码图片宽度 int height = 36; // 验证码图片长度 int length = 4; // 验证码位数 int expireIn = 60; // 验证码有效时间 60s BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.ITALIC, 20)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl);
} StringBuilder sRand = new StringBuilder(); for (int i = 0; i < length; i++) { String rand = String.valueOf(random.nextInt(10)); sRand.append(rand); g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 13 * i + 6, 16); } g.dispose(); return new ImageCode(image, sRand.toString(), expireIn); } private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }
repos\SpringAll-master\38.Spring-Security-SmsCode\src\main\java\cc\mrbird\web\controller\ValidateController.java
2
请完成以下Java代码
public String getId() { return idAttribute.getValue(this); } public void setId(String id) { idAttribute.setValue(this, id); } public String getLabel() { return labelAttribute.getValue(this); } public void setLabel(String label) { labelAttribute.setValue(this, label); } public Description getDescription() { return descriptionChild.getChild(this); } public void setDescription(Description description) { descriptionChild.setChild(this, description); } public ExtensionElements getExtensionElements() { return extensionElementsChild.getChild(this); } public void setExtensionElements(ExtensionElements extensionElements) { extensionElementsChild.setChild(this, extensionElements); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DmnElement.class, DMN_ELEMENT) .namespaceUri(LATEST_DMN_NS) .abstractType();
idAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_ID) .idAttribute() .build(); labelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LABEL) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); descriptionChild = sequenceBuilder.element(Description.class) .build(); extensionElementsChild = sequenceBuilder.element(ExtensionElements.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DmnElementImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static ImmutableList<OrderLineId> getOrderLineIds(@NonNull final QuotationLinesGroupAggregator linesGroup) { return linesGroup.streamQuotationLineIdsIndexedByCostCollectorId() .map(entry -> entry.getValue().getOrderLineId()) .distinct() .collect(ImmutableList.toImmutableList()); } private QuotationLinesGroupAggregator createGroupAggregator(@NonNull final QuotationLinesGroupKey key) { if (key.getType() == QuotationLinesGroupKey.Type.REPAIRED_PRODUCT) { final ServiceRepairProjectTask task = tasksById.get(key.getTaskId()); if (task == null) { // shall not happen throw new AdempiereException("No task found for " + key); } final int groupIndex = nextRepairingGroupIndex.getAndIncrement(); return RepairedProductAggregator.builder() .priceCalculator(priceCalculator) .key(key) .groupCaption(String.valueOf(groupIndex)) .repairOrderSummary(task.getRepairOrderSummary()) .repairServicePerformedId(task.getRepairServicePerformedId()) .build(); } else if (key.getType() == QuotationLinesGroupKey.Type.OTHERS) { return OtherLinesAggregator.builder() .priceCalculator(priceCalculator) .build(); } else { throw new AdempiereException("Unknown key type: " + key);
} } private OrderFactory newOrderFactory() { return OrderFactory.newSalesOrder() .docType(quotationDocTypeId) .orgId(pricingInfo.getOrgId()) .dateOrdered(extractDateOrdered(project, pricingInfo.getOrgTimeZone())) .datePromised(pricingInfo.getDatePromised()) .shipBPartner(project.getBpartnerId(), project.getBpartnerLocationId(), project.getBpartnerContactId()) .salesRepId(project.getSalesRepId()) .pricingSystemId(pricingInfo.getPricingSystemId()) .warehouseId(project.getWarehouseId()) .paymentTermId(project.getPaymentTermId()) .campaignId(project.getCampaignId()) .projectId(project.getProjectId()); } public final QuotationLineIdsByCostCollectorIdIndex getQuotationLineIdsIndexedByCostCollectorId() { Objects.requireNonNull(generatedQuotationLineIdsIndexedByCostCollectorId, "generatedQuotationLineIdsIndexedByCostCollectorId"); return generatedQuotationLineIdsIndexedByCostCollectorId; } public QuotationAggregator addAll(@NonNull final List<ServiceRepairProjectCostCollector> costCollectors) { this.costCollectorsToAggregate.addAll(costCollectors); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\QuotationAggregator.java
2
请完成以下Java代码
public void setCompleteOrderDiscount (final @Nullable BigDecimal CompleteOrderDiscount) { set_Value (COLUMNNAME_CompleteOrderDiscount, CompleteOrderDiscount); } @Override public BigDecimal getCompleteOrderDiscount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CompleteOrderDiscount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); }
/** * Type AD_Reference_ID=540836 * Reference name: C_CompensationGroup_SchemaLine_Type */ public static final int TYPE_AD_Reference_ID=540836; /** Revenue = R */ public static final String TYPE_Revenue = "R"; /** Flatrate = F */ public static final String TYPE_Flatrate = "F"; @Override public void setType (final @Nullable java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_SchemaLine.java
1
请完成以下Java代码
protected void applyConfigurators(Map<String, DataFormat<?>> dataFormats, ClassLoader classloader, List<DataFormatConfigurator> dataFormatConfigurators) { ServiceLoader<DataFormatConfigurator> configuratorLoader = ServiceLoader.load(DataFormatConfigurator.class, classloader); // apply SPI configurators for (DataFormatConfigurator configurator : configuratorLoader) { LOG.logDataFormatConfigurator(configurator); applyConfigurator(dataFormats, configurator); } // apply additional, non-SPI, configurators for (DataFormatConfigurator configurator : dataFormatConfigurators) { LOG.logDataFormatConfigurator(configurator); applyConfigurator(dataFormats, configurator); } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void applyConfigurator(Map<String, DataFormat<?>> dataFormats, DataFormatConfigurator configurator) { for (DataFormat<?> dataFormat : dataFormats.values()) { if (configurator.getDataFormatClass().isAssignableFrom(dataFormat.getClass())) { configurator.configure(dataFormat);
} } } public static void loadDataFormats() { loadDataFormats(null); } public static void loadDataFormats(ClassLoader classloader) { INSTANCE.registerDataFormats(classloader); } public static void loadDataFormats(ClassLoader classloader, List<DataFormatConfigurator> configurators) { INSTANCE.registerDataFormats(classloader, configurators); } public static void loadDataFormats(ClassLoader classloader, Map configurationProperties) { INSTANCE.registerDataFormats(classloader, Collections.EMPTY_LIST, configurationProperties); } }
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\DataFormats.java
1
请在Spring Boot框架中完成以下Java代码
private static ActiveMQConnectionFactory createJmsConnectionFactory(ArtemisProperties properties, ArtemisConnectionDetails connectionDetails, ListableBeanFactory beanFactory) { return new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails) .createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(CachingConnectionFactory.class) @ConditionalOnBooleanProperty(name = "spring.jms.cache.enabled", matchIfMissing = true) static class CachingConnectionFactoryConfiguration { @Bean(name = "jmsConnectionFactory") CachingConnectionFactory cachingJmsConnectionFactory(JmsProperties jmsProperties, ArtemisProperties properties, ArtemisConnectionDetails connectionDetails, ListableBeanFactory beanFactory) { JmsProperties.Cache cacheProperties = jmsProperties.getCache(); CachingConnectionFactory connectionFactory = new CachingConnectionFactory( createJmsConnectionFactory(properties, connectionDetails, beanFactory)); connectionFactory.setCacheConsumers(cacheProperties.isConsumers()); connectionFactory.setCacheProducers(cacheProperties.isProducers()); connectionFactory.setSessionCacheSize(cacheProperties.getSessionCacheSize()); return connectionFactory; } } }
@Configuration(proxyBeanMethods = false) @ConditionalOnClass({ JmsPoolConnectionFactory.class, PooledObject.class }) @ConditionalOnBooleanProperty("spring.artemis.pool.enabled") static class PooledConnectionFactoryConfiguration { @Bean(destroyMethod = "stop") JmsPoolConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties, ArtemisConnectionDetails connectionDetails) { ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails) .createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new); return new JmsPoolConnectionFactoryFactory(properties.getPool()) .createPooledConnectionFactory(connectionFactory); } } }
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisConnectionFactoryConfiguration.java
2
请完成以下Java代码
public void setM_Shipment_Constraint_ID (final int M_Shipment_Constraint_ID) { if (M_Shipment_Constraint_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, M_Shipment_Constraint_ID); } @Override public int getM_Shipment_Constraint_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipment_Constraint_ID); } @Override public void setSourceDoc_Record_ID (final int SourceDoc_Record_ID) { if (SourceDoc_Record_ID < 1) set_Value (COLUMNNAME_SourceDoc_Record_ID, null); else set_Value (COLUMNNAME_SourceDoc_Record_ID, SourceDoc_Record_ID); } @Override
public int getSourceDoc_Record_ID() { return get_ValueAsInt(COLUMNNAME_SourceDoc_Record_ID); } @Override public void setSourceDoc_Table_ID (final int SourceDoc_Table_ID) { if (SourceDoc_Table_ID < 1) set_Value (COLUMNNAME_SourceDoc_Table_ID, null); else set_Value (COLUMNNAME_SourceDoc_Table_ID, SourceDoc_Table_ID); } @Override public int getSourceDoc_Table_ID() { return get_ValueAsInt(COLUMNNAME_SourceDoc_Table_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Shipment_Constraint.java
1
请完成以下Java代码
public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Diagram.class, DI_ELEMENT_DIAGRAM) .namespaceUri(DI_NS) .abstractType(); nameAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_NAME) .build(); documentationAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_DOCUMENTATION) .build(); resolutionAttribute = typeBuilder.doubleAttribute(DI_ATTRIBUTE_RESOLUTION) .build(); idAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_ID) .idAttribute() .build(); typeBuilder.build(); } public DiagramImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); }
public String getDocumentation() { return documentationAttribute.getValue(this); } public void setDocumentation(String documentation) { documentationAttribute.setValue(this, documentation); } public double getResolution() { return resolutionAttribute.getValue(this); } public void setResolution(double resolution) { resolutionAttribute.setValue(this, resolution); } public String getId() { return idAttribute.getValue(this); } public void setId(String id) { idAttribute.setValue(this, id); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\di\DiagramImpl.java
1
请完成以下Java代码
public class ProductDescriptor { public static ProductDescriptor completeForProductIdAndEmptyAttribute(final int productId) { return new ProductDescriptor(productId, AttributesKey.NONE, AttributeSetInstanceId.NONE.getRepoId()); } public static ProductDescriptor forProductAndAttributes( final int productId, @NonNull final AttributesKey attributesKey, final int attributeSetInstanceId) { return new ProductDescriptor(productId, attributesKey, attributeSetInstanceId); } public static ProductDescriptor forProductAndAttributes( final int productId, @NonNull final AttributesKey attributesKey) { return new ProductDescriptor(productId, attributesKey, AttributeSetInstanceId.NONE.getRepoId()); } @Getter int productId; @Getter AttributesKey storageAttributesKey; /** * This ID is only here so that the candidate row's attributes can be displayed properly in the UI. * It may not cause otherwise equal ProductDescriptors to seem as unequal. */
@Getter int attributeSetInstanceId; @JsonCreator public ProductDescriptor( @JsonProperty("productId") final int productId, @JsonProperty("storageAttributesKey") @NonNull final AttributesKey storageAttributesKey, @JsonProperty("attributeSetInstanceId") final int attributeSetInstanceId) { Preconditions.checkArgument(productId > 0, "Given parameter productId=%s needs to be >0", productId); Preconditions.checkArgument(attributeSetInstanceId >= -1, "Given parameter attributeSetInstanceId needs to >=-1"); this.productId = productId; this.storageAttributesKey = storageAttributesKey; if (AttributesKey.NONE.equals(storageAttributesKey) || AttributesKey.ALL.equals(storageAttributesKey) || AttributesKey.OTHER.equals(storageAttributesKey)) { // discard the given attribueSetInstanceId if it is not about a "real" ASI. this.attributeSetInstanceId = 0; } else { this.attributeSetInstanceId = attributeSetInstanceId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\ProductDescriptor.java
1
请完成以下Java代码
private IAllocationRequest createAllocationRequest(final Quantity qty) { final IContextAware contextProvider = getContextInitial(); final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContextForProcessing(contextProvider); huContext.getTrxListeners().addListeners(this._customerListeners); final I_M_InOutLine inOutLine = getSingleInOutLineOrNull(); // ForceQtyAllocation=true, because // * we really want to allocate unload this quantity // * on loading side, HUItemStorage is considering our enforced capacity even if we do force allocation final boolean forceQtyAllocation = true; // // Create Allocation Request // TODO: See about the initial attributes!!! // // Setup initial attribute value defaults // final List<I_M_ReceiptSchedule> receiptSchedules = getReceiptSchedules(); // request = huReceiptScheduleBL.setInitialAttributeValueDefaults(request, receiptSchedules); return AllocationUtils.createQtyRequest( huContext, getSingleProductId(), qty, SystemTime.asZonedDateTime(), inOutLine, // referencedModel, forceQtyAllocation); } private IDocumentLUTUConfigurationManager getLUTUConfigurationManager() { if (_lutuConfigurationManager == null) { final List<I_M_InOutLine> inOutLines = getInOutLines(); _lutuConfigurationManager = huInOutBL.createLUTUConfigurationManager(inOutLines); markNotConfigurable(); } return _lutuConfigurationManager; } /** * @return the LU/TU configuration to be used when generating HUs.
*/ private I_M_HU_LUTU_Configuration getM_HU_LUTU_Configuration() { if (_lutuConfiguration != null) { return _lutuConfiguration; } _lutuConfiguration = getLUTUConfigurationManager().getCurrentLUTUConfigurationOrNull(); Check.assumeNotNull(_lutuConfiguration, "_lutuConfiguration not null"); markNotConfigurable(); return _lutuConfiguration; } private ILUTUProducerAllocationDestination getLUTUProducerAllocationDestination() { if (_lutuProducer != null) { return _lutuProducer; } final I_M_HU_LUTU_Configuration lutuConfiguration = getM_HU_LUTU_Configuration(); _lutuProducer = lutuConfigurationFactory.createLUTUProducerAllocationDestination(lutuConfiguration); markNotConfigurable(); return _lutuProducer; } CustomerReturnLineHUGenerator setIHUTrxListeners(@NonNull final List<IHUTrxListener> customerListeners) { assertConfigurable(); this._customerListeners = ImmutableList.copyOf(customerListeners); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnLineHUGenerator.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class Payment { @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @ManyToOne(fetch = FetchType.LAZY) protected WebUser webUser; protected BigDecimal amount; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;
Payment payment = (Payment) o; return Objects.equals(id, payment.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } protected Payment() { } }
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\hibernateunproxy\Payment.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getHobby() { return hobby; }
public void setHobby(String hobby) { this.hobby = hobby; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getLastLoginIp() { return lastLoginIp; } public void setLastLoginIp(String lastLoginIp) { this.lastLoginIp = lastLoginIp; } @Override public String toString() { return "UserDetail{" + "id=" + id + ", userId=" + userId + ", age=" + age + ", realName='" + realName + '\'' + ", status='" + status + '\'' + ", hobby='" + hobby + '\'' + ", introduction='" + introduction + '\'' + ", lastLoginIp='" + lastLoginIp + '\'' + '}'; } }
repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\model\UserDetail.java
1
请完成以下Java代码
public class ProcessEnginePostEngineBuildConsumer implements Consumer<ProcessEngine> { @Override public void accept(ProcessEngine processEngine) { ProcessEngineConfigurationImpl engineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); if (engineConfiguration.getEngineLifecycleListeners() != null) { for (EngineLifecycleListener engineLifecycleListener : engineConfiguration.getEngineLifecycleListeners()) { engineLifecycleListener.onEngineBuilt(processEngine); } } engineConfiguration.getEventDispatcher().dispatchEvent(FlowableEventBuilder.createGlobalEvent(FlowableEngineEventType.ENGINE_CREATED), engineConfiguration.getEngineCfgKey()); if (engineConfiguration.isHandleProcessEngineExecutorsAfterEngineCreate()) { processEngine.startExecutors(); }
// trigger build of Flowable 5 Engine if (engineConfiguration.isFlowable5CompatibilityEnabled()) { Flowable5CompatibilityHandler flowable5CompatibilityHandler = engineConfiguration.getFlowable5CompatibilityHandler(); if (flowable5CompatibilityHandler != null) { engineConfiguration.getCommandExecutor().execute(commandContext -> { flowable5CompatibilityHandler.getRawProcessEngine(); return null; }); } } engineConfiguration.postProcessEngineInitialisation(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\ProcessEnginePostEngineBuildConsumer.java
1
请完成以下Java代码
public class DelegateExpressionTaskListener implements TaskListener { protected Expression expression; private final List<FieldDeclaration> fieldDeclarations; public DelegateExpressionTaskListener(Expression expression, List<FieldDeclaration> fieldDeclarations) { this.expression = expression; this.fieldDeclarations = fieldDeclarations; } public void notify(DelegateTask delegateTask) { Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, delegateTask, fieldDeclarations); if (delegate instanceof TaskListener) { try { Context.getProcessEngineConfiguration() .getDelegateInterceptor() .handleInvocation(new TaskListenerInvocation((TaskListener) delegate, delegateTask)); } catch (Exception e) { throw new ActivitiException("Exception while invoking TaskListener: " + e.getMessage(), e);
} } else { throw new ActivitiIllegalArgumentException( "Delegate expression " + expression + " did not resolve to an implementation of " + TaskListener.class ); } } /** * returns the expression text for this task listener. Comes in handy if you want to check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\DelegateExpressionTaskListener.java
1
请完成以下Java代码
public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionStrategy) { this.sessionStrategy = sessionStrategy; } /** * Sets the authentication details source. * @param authenticationDetailsSource the authentication details source */ public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required"); this.authenticationDetailsSource = authenticationDetailsSource; } /** * If set to {@code false} (the default) and authentication is successful, the request * will be processed by the next filter in the chain. If {@code true} and * authentication is successful, the filter chain will stop here. * @param shouldStop set to {@code true} to prevent the next filter in the chain from * processing the request after a successful authentication. * @since 1.0.2 */ public void setStopFilterChainOnSuccessfulAuthentication(boolean shouldStop) { this.stopFilterChainOnSuccessfulAuthentication = shouldStop; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the
* {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * @param securityContextHolderStrategy the {@link SecurityContextHolderStrategy} to * use. Cannot be null. */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\kerberos\kerberos-web\src\main\java\org\springframework\security\kerberos\web\authentication\SpnegoAuthenticationProcessingFilter.java
1
请完成以下Java代码
static public BigDecimal YDI( int p_A_ASSET_ID, BigDecimal p_A_ASSET_ADJUSTMENT, double p_A_PERIODNO, String p_POSTINGTYPE,int p_A_ASSET_ACCT_ID) { BigDecimal A_Dep_Adj = new BigDecimal(0.0); StringBuffer sqlB = new StringBuffer ("SELECT A_DEPRECIATION_WORKFILE.A_LIFE_PERIOD, A_DEPRECIATION_WORKFILE.A_PERIOD_POSTED" + " FROM A_DEPRECIATION_WORKFILE" + " WHERE A_DEPRECIATION_WORKFILE.A_ASSET_ID = " + p_A_ASSET_ID + " AND A_DEPRECIATION_WORKFILE.POSTINGTYPE = '" + p_POSTINGTYPE +"'"); //System.out.println("DB150: "+sqlB.toString()); PreparedStatement pstmt = null; pstmt = DB.prepareStatement (sqlB.toString(),null); try { ResultSet rs = pstmt.executeQuery(); while (rs.next()){ A_Dep_Adj = p_A_ASSET_ADJUSTMENT.divide(new BigDecimal(12-p_A_PERIODNO),2, BigDecimal.ROUND_HALF_UP); } //System.out.println("LDI: "+A_Period_Exp); return A_Dep_Adj;
} catch (Exception e) { System.out.println("LDI: "+e); } finally { try { if (pstmt != null) pstmt.close (); } catch (Exception e) {} pstmt = null; } return A_Dep_Adj; } }// Depreciation
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\FA\DepreciationAdj.java
1
请在Spring Boot框架中完成以下Java代码
void setUserDetailsService(ReactiveUserDetailsService userDetailsService) { this.reactiveUserDetailsService = userDetailsService; } @Autowired(required = false) void setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Autowired(required = false) void setAuthenticationManagerPostProcessor( Map<String, ObjectPostProcessor<ReactiveAuthenticationManager>> postProcessors) { if (postProcessors.size() == 1) { this.postProcessor = postProcessors.values().iterator().next(); } this.postProcessor = postProcessors.get("rSocketAuthenticationManagerPostProcessor"); } @Bean(name = RSOCKET_SECURITY_BEAN_NAME) @Scope("prototype") RSocketSecurity rsocketSecurity(ApplicationContext context) {
RSocketSecurity security = new RSocketSecurity().authenticationManager(authenticationManager()); security.setApplicationContext(context); return security; } private ReactiveAuthenticationManager authenticationManager() { if (this.authenticationManager != null) { return this.authenticationManager; } if (this.reactiveUserDetailsService != null) { UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager( this.reactiveUserDetailsService); if (this.passwordEncoder != null) { manager.setPasswordEncoder(this.passwordEncoder); } return this.postProcessor.postProcess(manager); } return null; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurityConfiguration.java
2
请完成以下Java代码
public class IncludeExcludeContentSelector<T> implements ContentSelector<T> { private final Layer layer; private final List<ContentFilter<T>> includes; private final List<ContentFilter<T>> excludes; public IncludeExcludeContentSelector(Layer layer, @Nullable List<ContentFilter<T>> includes, @Nullable List<ContentFilter<T>> excludes) { this(layer, includes, excludes, Function.identity()); } public <S> IncludeExcludeContentSelector(Layer layer, @Nullable List<S> includes, @Nullable List<S> excludes, Function<S, ContentFilter<T>> filterFactory) { Assert.notNull(layer, "'layer' must not be null"); Assert.notNull(filterFactory, "'filterFactory' must not be null"); this.layer = layer; this.includes = (includes != null) ? adapt(includes, filterFactory) : Collections.emptyList(); this.excludes = (excludes != null) ? adapt(excludes, filterFactory) : Collections.emptyList(); } private <S> List<ContentFilter<T>> adapt(List<S> list, Function<S, ContentFilter<T>> mapper) { return list.stream().map(mapper).toList(); } @Override public Layer getLayer() { return this.layer; } @Override public boolean contains(T item) {
return isIncluded(item) && !isExcluded(item); } private boolean isIncluded(T item) { if (this.includes.isEmpty()) { return true; } for (ContentFilter<T> include : this.includes) { if (include.matches(item)) { return true; } } return false; } private boolean isExcluded(T item) { if (this.excludes.isEmpty()) { return false; } for (ContentFilter<T> exclude : this.excludes) { if (exclude.matches(item)) { return true; } } return false; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\layer\IncludeExcludeContentSelector.java
1
请完成以下Java代码
public static <R> Result<R> ofFail(int code, String msg) { Result<R> result = new Result<>(); result.setSuccess(false); result.setCode(code); result.setMsg(msg); return result; } public static <R> Result<R> ofThrowable(int code, Throwable throwable) { Result<R> result = new Result<>(); result.setSuccess(false); result.setCode(code); result.setMsg(throwable.getClass().getName() + ", " + throwable.getMessage()); return result; } public boolean isSuccess() { return success; } public Result<R> setSuccess(boolean success) { this.success = success; return this; } public int getCode() { return code; } public Result<R> setCode(int code) { this.code = code; return this; }
public String getMsg() { return msg; } public Result<R> setMsg(String msg) { this.msg = msg; return this; } public R getData() { return data; } public Result<R> setData(R data) { this.data = data; return this; } @Override public String toString() { return "Result{" + "success=" + success + ", code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\Result.java
1
请在Spring Boot框架中完成以下Java代码
public class MainApplication { private final BookstoreService bookstoreService; public MainApplication(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } public static void main(String[] args) { SpringApplication.run(MainApplication.class, args); } @Bean public ApplicationRunner init() { return args -> { System.out.println("\n\nFetch Author as Streamable:"); bookstoreService.fetchAuthorsAsStreamable(); System.out.println("\n\nFetch Author DTO as Streamable:"); bookstoreService.fetchAuthorsDtoAsStreamable(); System.out.println("\n\nFetch Author by genre and age as Streamable:"); bookstoreService.fetchAuthorsByGenreAndAgeGreaterThan(); System.out.println("\n\nFetch Author by genre or age as Streamable:");
bookstoreService.fetchAuthorsByGenreOrAgeGreaterThan(); System.out.println("\n\nDON'T DO THIS! Fetch all columns just to drop a part of them:"); bookstoreService.fetchAuthorsNames1(); System.out.println("\n\nDO THIS! Fetch only the needed columns:"); bookstoreService.fetchAuthorsNames2(); System.out.println("\n\nDON'T DO THIS! Fetch more rows than needed just to throw away a part of it:"); bookstoreService.fetchAuthorsOlderThanAge1(); System.out.println("\n\nDO THIS! Fetch only the needed rows:"); bookstoreService.fetchAuthorsOlderThanAge2(); System.out.println("\n\nCAUTION! Concatenating two Streamable:"); bookstoreService.fetchAuthorsByGenreConcatAge(); }; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootStreamable\src\main\java\com\bookstore\MainApplication.java
2
请完成以下Java代码
public String toString() { StringBuilder sb = new StringBuilder(); if (namespacePrefix != null) { sb.append(namespacePrefix); if (name != null) { sb.append(":").append(name); } } else { sb.append(name); } if (value != null) { sb.append("=").append(value); } return sb.toString(); }
@Override public DmnExtensionAttribute clone() { DmnExtensionAttribute clone = new DmnExtensionAttribute(); clone.setValues(this); return clone; } public void setValues(DmnExtensionAttribute otherAttribute) { setName(otherAttribute.getName()); setValue(otherAttribute.getValue()); setNamespacePrefix(otherAttribute.getNamespacePrefix()); setNamespace(otherAttribute.getNamespace()); } }
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionAttribute.java
1
请完成以下Java代码
public void signalEventReceivedAsync(String signalName, String executionId) { commandExecutor.execute(new SignalEventReceivedCmd(signalName, executionId, true, null)); } @Override public void messageEventReceived(String messageName, String executionId) { commandExecutor.execute(new MessageEventReceivedCmd(messageName, executionId, null)); } @Override public void messageEventReceived(String messageName, String executionId, Map<String, Object> processVariables) { commandExecutor.execute(new MessageEventReceivedCmd(messageName, executionId, processVariables)); } @Override public void messageEventReceivedAsync(String messageName, String executionId) { commandExecutor.execute(new MessageEventReceivedCmd(messageName, executionId, true)); } @Override public void addEventListener(FlowableEventListener listenerToAdd) { commandExecutor.execute(new AddEventListenerCommand(listenerToAdd)); } @Override public void addEventListener(FlowableEventListener listenerToAdd, FlowableEngineEventType... types) { commandExecutor.execute(new AddEventListenerCommand(listenerToAdd, types)); } @Override public void removeEventListener(FlowableEventListener listenerToRemove) { commandExecutor.execute(new RemoveEventListenerCommand(listenerToRemove)); } @Override public void dispatchEvent(FlowableEvent event) { commandExecutor.execute(new DispatchEventCommand(event)); } @Override public void setProcessInstanceName(String processInstanceId, String name) { commandExecutor.execute(new SetProcessInstanceNameCmd(processInstanceId, name)); }
@Override public List<Event> getProcessInstanceEvents(String processInstanceId) { return commandExecutor.execute(new GetProcessInstanceEventsCmd(processInstanceId)); } @Override public ProcessInstanceBuilder createProcessInstanceBuilder() { return new ProcessInstanceBuilderImpl(this); } public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) { if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) { return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder)); } else if (processInstanceBuilder.getMessageName() != null) { return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder)); } else { throw new ActivitiIllegalArgumentException( "No processDefinitionId, processDefinitionKey nor messageName provided"); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\RuntimeServiceImpl.java
1
请完成以下Java代码
public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); }
/** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_AD_User getSalesRep() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSalesRep_ID(), get_TrxName()); } /** Set Sales Representative. @param SalesRep_ID Sales Representative or Company Agent */ public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Sales Representative. @return Sales Representative or Company Agent */ public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_InvoiceBatch.java
1
请完成以下Java代码
public class CurrentChargesResponse { private String customerId; private BigDecimal amountDue; private List<LineItem> lineItems; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb .append("Current Month Charges: {") .append("\n\tcustomer: ") .append(this.customerId) .append("\n\ttotalAmountDue: ") .append(this.amountDue.setScale(2, RoundingMode.HALF_UP)) .append("\n\tlineItems: ["); for (LineItem li : this.lineItems) { sb .append("\n\t\t{") .append("\n\t\t\tsubscription: ") .append(li.subscriptionId) .append("\n\t\t\tamount: ") .append(li.amount.setScale(2, RoundingMode.HALF_UP)) .append("\n\t\t\tquantity: ")
.append(li.quantity) .append("\n\t\t},"); } sb.append("\n\t]\n}\n"); return sb.toString(); } @NoArgsConstructor(access = AccessLevel.PACKAGE) @AllArgsConstructor(access = AccessLevel.PACKAGE) @Builder @Getter public static class LineItem { private String subscriptionId; private BigDecimal amount; private Integer quantity; } }
repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\model\CurrentChargesResponse.java
1
请完成以下Java代码
public int optimize(double[] x, double f, double[] g) { return optimize(diag_.length, x, f, g, false, 1.0); } public int optimize(int size, double[] x, double f, double[] g, boolean orthant, double C) { int msize = 5; if (w_ == null) { iflag_ = 0; w_ = new double[size * (2 * msize + 1) + 2 * msize]; Arrays.fill(w_, 0.0); diag_ = new double[size]; v_ = new double[size]; if (orthant) { xi_ = new double[size]; } } else if (diag_.length != size || v_.length != size) { System.err.println("size of array is different"); return -1; } else if (orthant && v_.length != size) { System.err.println("size of array is different"); return -1; } int iflag = 0; if (orthant) { iflag = lbfgs_optimize(size, msize, x, f, g, diag_, w_, orthant, C, v_, xi_, iflag_); iflag_ = iflag; } else { iflag = lbfgs_optimize(size,
msize, x, f, g, diag_, w_, orthant, C, g, xi_, iflag_); iflag_ = iflag; } if (iflag < 0) { System.err.println("routine stops with unexpected error"); return -1; } if (iflag == 0) { clear(); return 0; // terminate } return 1; // evaluate next f and g } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\LbfgsOptimizer.java
1
请完成以下Java代码
public synchronized <BT, T extends BT> void registerJUnitBean( @NonNull final Class<BT> beanType, @NonNull final T beanImpl) { assertJUnitMode(); final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>()); if (!beans.contains(beanImpl)) { beans.add(beanImpl); logger.info("JUnit testing: Registered bean {}={}", beanType, beanImpl); } else { logger.info("JUnit testing: Skip registering bean because already registered {}={}", beanType, beanImpl); } } public synchronized <BT, T extends BT> void registerJUnitBeans( @NonNull final Class<BT> beanType, @NonNull final List<T> beansToAdd) { assertJUnitMode(); final ArrayList<Object> beans = map.computeIfAbsent(ClassReference.of(beanType), key -> new ArrayList<>()); beans.addAll(beansToAdd); logger.info("JUnit testing: Registered beans {}={}", beanType, beansToAdd); } public synchronized <T> T getBeanOrNull(@NonNull final Class<T> beanType) { assertJUnitMode(); final ArrayList<Object> beans = map.get(ClassReference.of(beanType)); if (beans == null || beans.isEmpty()) { return null; } if (beans.size() > 1) { logger.warn("Found more than one bean for {} but returning the first one: {}", beanType, beans); } final T beanImpl = castBean(beans.get(0), beanType); logger.debug("JUnit testing Returning manually registered bean: {}", beanImpl); return beanImpl; } private static <T> T castBean(final Object beanImpl, final Class<T> ignoredBeanType) { @SuppressWarnings("unchecked") final T beanImplCasted = (T)beanImpl;
return beanImplCasted; } public synchronized <T> ImmutableList<T> getBeansOfTypeOrNull(@NonNull final Class<T> beanType) { assertJUnitMode(); List<Object> beanObjs = map.get(ClassReference.of(beanType)); if (beanObjs == null) { final List<Object> assignableBeans = map.values() .stream() .filter(Objects::nonNull) .flatMap(Collection::stream) .filter(impl -> beanType.isAssignableFrom(impl.getClass())) .collect(Collectors.toList()); if (assignableBeans.isEmpty()) { return null; } beanObjs = assignableBeans; } return beanObjs .stream() .map(beanObj -> castBean(beanObj, beanType)) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\JUnitBeansMap.java
1
请在Spring Boot框架中完成以下Java代码
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { /** * Gets Logger After LoggingSystem configuration ready * @see LoggingApplicationListener */ final Logger logger = LoggerFactory.getLogger(getClass()); ConfigurableEnvironment environment = event.getEnvironment(); boolean override = environment.getProperty(OVERRIDE_CONFIG_FULL_PROPERTY_NAME, boolean.class, DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE); if (override) { SortedMap<String, Object> dubboProperties = filterDubboProperties(environment);
ConfigUtils.getProperties().putAll(dubboProperties); if (logger.isInfoEnabled()) { logger.info("Dubbo Config was overridden by externalized configuration {}", dubboProperties); } } else { if (logger.isInfoEnabled()) { logger.info("Disable override Dubbo Config caused by property {} = {}", OVERRIDE_CONFIG_FULL_PROPERTY_NAME, override); } } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\context\event\OverrideDubboConfigApplicationListener.java
2
请在Spring Boot框架中完成以下Java代码
public String getProcessDefinitionId() { return processDefinitionId; } @Override public String getScopeId() { return scopeId; } @Override public String getScopeDefinitionId() { return scopeDefinitionId; } @Override public String getSubScopeId() {
return subScopeId; } @Override public String getScopeType() { return scopeType; } @Override public String getTenantId() { return tenantId; } @Override public String toString() { return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")"; } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setDescription(String description) { this.description = description; } @ApiModelProperty(example = "3") public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @ApiModelProperty(example = "dmn-DecisionTableOne.dmn") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } @ApiModelProperty(example = "46aa6b3a-c0a1-11e6-bc93-6ab56fad108a") public String getDeploymentId() { return deploymentId;
} public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "decision_table") public String getDecisionType() { return decisionType; } public void setDecisionType(String decisionType) { this.decisionType = decisionType; } }
repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\repository\DecisionResponse.java
2
请在Spring Boot框架中完成以下Java代码
public RegisteredClientRepository registeredClientRepository() { RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()) .clientId("baeldung_api_key") .clientSecret("baeldung_api_secret") .authorizationGrantType(AuthorizationGrantType.PASSWORD) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .scope("read") .scope("write") .clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build()) .build(); return new InMemoryRegisteredClientRepository(oidcClient); } @Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0 http // Redirect to the login page when not authenticated from the // authorization endpoint .exceptionHandling((exceptions) -> exceptions .defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), new MediaTypeRequestMatcher(MediaType.TEXT_HTML) ) ) // Accept access tokens for User Info and/or Client Registration .oauth2ResourceServer((resourceServer) -> resourceServer .jwt(Customizer.withDefaults()));
return http.build(); } @Bean @Order(2) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ) // Form login handles the redirect to the login page from the // authorization server filter chain .formLogin(Customizer.withDefaults()); return http.build(); } }
repos\tutorials-master\libraries-security-2\src\main\java\com\baeldung\scribejava\oauth\AuthServiceConfig.java
2
请完成以下Java代码
public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference);
} @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_111_v.java
1
请完成以下Java代码
public void setSource(final int productId, final BigDecimal qty) { this.productId = productId; this.qty = qty; } @Override public boolean isValid() { if (productId <= 0) { return false; } if (qty == null || qty.signum() == 0) { return false; } return true; } @Override public void apply(final Object model) { if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OrderLine.class)) { logger.debug("Skip applying because it's not an order line: {}", model); return; } final I_C_OrderLine orderLine = InterfaceWrapperHelper.create(model, I_C_OrderLine.class); apply(orderLine); } private void apply(final I_C_OrderLine orderLine) {
// Note: There is only the product's stocking-UOM.,.the C_UOM can't be changed in the product info UI. // That's why we don't need to convert orderLine.setQtyEntered(qty); orderLine.setQtyOrdered(qty); } @Override public boolean isCreateNewRecord() { return true; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\OrderLineProductQtyGridRowBuilder.java
1
请完成以下Java代码
public class DisableEncodeUrlFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(request, new DisableEncodeUrlResponseWrapper(response)); } /** * Disables URL rewriting for the {@link HttpServletResponse} to prevent including the * session id in URLs which is not considered URL because the session id can be leaked * in things like HTTP access logs. * * @author Rob Winch * @since 5.7 */ private static final class DisableEncodeUrlResponseWrapper extends HttpServletResponseWrapper { /** * Constructs a response adaptor wrapping the given response. * @param response the {@link HttpServletResponse} to be wrapped. * @throws IllegalArgumentException if the response is null */ private DisableEncodeUrlResponseWrapper(HttpServletResponse response) {
super(response); } @Override public String encodeRedirectURL(String url) { return url; } @Override public String encodeURL(String url) { return url; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\DisableEncodeUrlFilter.java
1
请完成以下Java代码
public class ErrorEventDefinition implements Serializable { public static Comparator<ErrorEventDefinition> comparator = new Comparator<ErrorEventDefinition>() { public int compare(ErrorEventDefinition o1, ErrorEventDefinition o2) { return o2.getPrecedence().compareTo(o1.getPrecedence()); } }; private static final long serialVersionUID = 1L; protected final String handlerActivityId; protected String errorCode; protected Integer precedence = 0; public ErrorEventDefinition(String handlerActivityId) { this.handlerActivityId = handlerActivityId; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
public String getHandlerActivityId() { return handlerActivityId; } public Integer getPrecedence() { // handlers with error code take precedence over catchall-handlers return precedence + (errorCode != null ? 1 : 0); } public void setPrecedence(Integer precedence) { this.precedence = precedence; } public boolean catches(String errorCode) { return errorCode == null || this.errorCode == null || this.errorCode.equals(errorCode); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\ErrorEventDefinition.java
1
请完成以下Java代码
public void addPropertyChangeListener(final PropertyChangeListener listener, final Boolean weak) { final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, weak, WeakListenerCreationScope.ForAdding); super.addPropertyChangeListener(weakListener); } @Override public final void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { addPropertyChangeListener(propertyName, listener, WEAK_AUTO); } public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener, final Boolean weak) { final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, weak, WeakListenerCreationScope.ForAdding); super.addPropertyChangeListener(propertyName, weakListener); } @Override public void removePropertyChangeListener(final PropertyChangeListener listener) { super.removePropertyChangeListener(listener); final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, true, WeakListenerCreationScope.ForRemoving); super.removePropertyChangeListener(weakListener); }
@Override public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { super.removePropertyChangeListener(propertyName, listener); final PropertyChangeListener weakListener = createWeakPropertyChangeListener(listener, true, WeakListenerCreationScope.ForRemoving); super.removePropertyChangeListener(propertyName, weakListener); } @Override public String toString() { return MoreObjects.toStringHelper(this) // it's dangerous to output the source, because sometimes the source also holds a reference to this listener, and if it also has this listener in its toString(), then we get a StackOverflow // .add("source (weakly referenced)", debugSourceBeanRef.get()) // debugSourceBeanRef can't be null, otherwise the constructor would have failed .add("listeners", getPropertyChangeListeners()) // i know there should be no method but only fields in toString(), but don't see how else to output this .toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\WeakPropertyChangeSupport.java
1
请完成以下Java代码
public void setParent_HU_Trx_Line(final de.metas.handlingunits.model.I_M_HU_Trx_Line Parent_HU_Trx_Line) { set_ValueFromPO(COLUMNNAME_Parent_HU_Trx_Line_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class, Parent_HU_Trx_Line); } @Override public void setParent_HU_Trx_Line_ID (final int Parent_HU_Trx_Line_ID) { if (Parent_HU_Trx_Line_ID < 1) set_ValueNoCheck (COLUMNNAME_Parent_HU_Trx_Line_ID, null); else set_ValueNoCheck (COLUMNNAME_Parent_HU_Trx_Line_ID, Parent_HU_Trx_Line_ID); } @Override public int getParent_HU_Trx_Line_ID() { return get_ValueAsInt(COLUMNNAME_Parent_HU_Trx_Line_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Trx_Line getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class); } @Override public void setReversalLine(final de.metas.handlingunits.model.I_M_HU_Trx_Line ReversalLine) {
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class, ReversalLine); } @Override public void setReversalLine_ID (final int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID); } @Override public int getReversalLine_ID() { return get_ValueAsInt(COLUMNNAME_ReversalLine_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Item getVHU_Item() { return get_ValueAsPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class); } @Override public void setVHU_Item(final de.metas.handlingunits.model.I_M_HU_Item VHU_Item) { set_ValueFromPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, VHU_Item); } @Override public void setVHU_Item_ID (final int VHU_Item_ID) { if (VHU_Item_ID < 1) set_Value (COLUMNNAME_VHU_Item_ID, null); else set_Value (COLUMNNAME_VHU_Item_ID, VHU_Item_ID); } @Override public int getVHU_Item_ID() { return get_ValueAsInt(COLUMNNAME_VHU_Item_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Line.java
1
请完成以下Java代码
public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsDefaultForPicking (final boolean IsDefaultForPicking) { set_Value (COLUMNNAME_IsDefaultForPicking, IsDefaultForPicking); } @Override public boolean isDefaultForPicking() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultForPicking); } @Override public void setIsDefaultLU (final boolean IsDefaultLU) { set_Value (COLUMNNAME_IsDefaultLU, IsDefaultLU); } @Override public boolean isDefaultLU() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultLU); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null);
else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI.java
1
请完成以下Java代码
public String getExemptReason () { return (String)get_Value(COLUMNNAME_ExemptReason); } /** Set Mandatory Withholding. @param IsMandatoryWithholding Monies must be withheld */ public void setIsMandatoryWithholding (boolean IsMandatoryWithholding) { set_Value (COLUMNNAME_IsMandatoryWithholding, Boolean.valueOf(IsMandatoryWithholding)); } /** Get Mandatory Withholding. @return Monies must be withheld */ public boolean isMandatoryWithholding () { Object oo = get_Value(COLUMNNAME_IsMandatoryWithholding); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Temporary exempt.
@param IsTemporaryExempt Temporarily do not withhold taxes */ public void setIsTemporaryExempt (boolean IsTemporaryExempt) { set_Value (COLUMNNAME_IsTemporaryExempt, Boolean.valueOf(IsTemporaryExempt)); } /** Get Temporary exempt. @return Temporarily do not withhold taxes */ public boolean isTemporaryExempt () { Object oo = get_Value(COLUMNNAME_IsTemporaryExempt); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Withholding.java
1
请完成以下Java代码
public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public org.compiere.model.I_C_ValidCombination getPJ_Asset_A() { return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A) { set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A); } @Override public void setPJ_Asset_Acct (final int PJ_Asset_Acct) { set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct);
} @Override public int getPJ_Asset_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct); } @Override public org.compiere.model.I_C_ValidCombination getPJ_WIP_A() { return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A) { set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A); } @Override public void setPJ_WIP_Acct (final int PJ_WIP_Acct) { set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct); } @Override public int getPJ_WIP_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public List<ProdImageEntity> getProdImageEntityList() { return prodImageEntityList; } public void setProdImageEntityList(List<ProdImageEntity> prodImageEntityList) { this.prodImageEntityList = prodImageEntityList; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public UserEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(UserEntity companyEntity) { this.companyEntity = companyEntity; } public int getSales() { return sales; } public void setSales(int sales) {
this.sales = sales; } @Override public String toString() { return "ProductEntity{" + "id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntity=" + topCateEntity + ", subCategEntity=" + subCategEntity + ", brandEntity=" + brandEntity + ", prodStateEnum=" + prodStateEnum + ", prodImageEntityList=" + prodImageEntityList + ", content='" + content + '\'' + ", companyEntity=" + companyEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java
2
请完成以下Java代码
public static ImmutableDocumentFilterDescriptorsProvider of(final DocumentFilterDescriptor... descriptors) { if (descriptors == null || descriptors.length == 0) { return EMPTY; } return new ImmutableDocumentFilterDescriptorsProvider(Arrays.asList(descriptors)); } public static Builder builder() { return new Builder(); } private static final ImmutableDocumentFilterDescriptorsProvider EMPTY = new ImmutableDocumentFilterDescriptorsProvider(); private final ImmutableMap<String, DocumentFilterDescriptor> descriptorsByFilterId; private ImmutableDocumentFilterDescriptorsProvider(final List<DocumentFilterDescriptor> descriptors) { descriptorsByFilterId = Maps.uniqueIndex(descriptors, DocumentFilterDescriptor::getFilterId); } private ImmutableDocumentFilterDescriptorsProvider() { descriptorsByFilterId = ImmutableMap.of(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(descriptorsByFilterId.keySet()) .toString(); } @Override public Collection<DocumentFilterDescriptor> getAll() { return descriptorsByFilterId.values(); } @Override public DocumentFilterDescriptor getByFilterIdOrNull(final String filterId) { return descriptorsByFilterId.get(filterId); } // // // // //
public static class Builder { private final List<DocumentFilterDescriptor> descriptors = new ArrayList<>(); private Builder() { } public ImmutableDocumentFilterDescriptorsProvider build() { if (descriptors.isEmpty()) { return EMPTY; } return new ImmutableDocumentFilterDescriptorsProvider(descriptors); } public Builder addDescriptor(@NonNull final DocumentFilterDescriptor descriptor) { descriptors.add(descriptor); return this; } public Builder addDescriptors(@NonNull final Collection<DocumentFilterDescriptor> descriptors) { if (descriptors.isEmpty()) { return this; } this.descriptors.addAll(descriptors); return this; } public Builder addDescriptors(@NonNull final DocumentFilterDescriptorsProvider provider) { addDescriptors(provider.getAll()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\ImmutableDocumentFilterDescriptorsProvider.java
1
请完成以下Java代码
public static <T> CommonResult<T> error(Integer code, String message) { Assert.isTrue(!CODE_SUCCESS.equals(code), "code 必须是错误的!"); CommonResult<T> result = new CommonResult<>(); result.code = code; result.message = message; return result; } public static <T> CommonResult<T> success(T data) { CommonResult<T> result = new CommonResult<>(); result.code = CODE_SUCCESS; result.data = data; result.message = ""; return result; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } @JsonIgnore public boolean isSuccess() {
return CODE_SUCCESS.equals(code); } @JsonIgnore public boolean isError() { return !isSuccess(); } @Override public String toString() { return "CommonResult{" + "code=" + code + ", message='" + message + '\'' + ", data=" + data + '}'; } }
repos\SpringBoot-Labs-master\lab-22\lab-22-validation-01\src\main\java\cn\iocoder\springboot\lab22\validation\core\vo\CommonResult.java
1
请在Spring Boot框架中完成以下Java代码
class CorsConfigurationSourceFactoryBean implements FactoryBean<CorsConfigurationSource>, ApplicationContextAware { private static final String HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector"; private ApplicationContext context; @Override public CorsConfigurationSource getObject() { if (!this.context.containsBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME)) { throw new NoSuchBeanDefinitionException(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, "A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME + " of type " + CorsConfigurationSource.class.getName() + " is required to use <cors>. Please ensure Spring Security & Spring " + "MVC are configured in a shared ApplicationContext."); }
return this.context.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, CorsConfigurationSource.class); } @Nullable @Override public Class<?> getObjectType() { return CorsConfigurationSource.class; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\CorsConfigurationSourceFactoryBean.java
2
请完成以下Java代码
public void postProcessBeforeDestruction(final Object bean, final String beanName) throws BeansException { this.process(bean, EventBus::unregister, "destruction"); } @Override public boolean requiresDestruction(Object bean) { return true; } @Override public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { this.process(bean, EventBus::register, "initialization"); return bean; } private void process(final Object bean, final BiConsumer<EventBus, Object> consumer, final String action) { Object proxy = this.getTargetObject(bean); final Subscriber annotation = AnnotationUtils.getAnnotation(proxy.getClass(), Subscriber.class); if (annotation == null) return; this.logger.info("{}: processing bean of type {} during {}", this.getClass().getSimpleName(), proxy.getClass().getName(), action); final String annotationValue = annotation.value(); try { final Expression expression = this.expressionParser.parseExpression(annotationValue); final Object value = expression.getValue(); if (!(value instanceof EventBus)) { this.logger.error("{}: expression {} did not evaluate to an instance of EventBus for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getSimpleName()); return; } final EventBus eventBus = (EventBus)value;
consumer.accept(eventBus, proxy); } catch (ExpressionException ex) { this.logger.error("{}: unable to parse/evaluate expression {} for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getName()); } } private Object getTargetObject(Object proxy) throws BeansException { if (AopUtils.isJdkDynamicProxy(proxy)) { try { return ((Advised)proxy).getTargetSource().getTarget(); } catch (Exception e) { throw new FatalBeanException("Error getting target of JDK proxy", e); } } return proxy; } }
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GuavaEventBusBeanPostProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public Page<Author> fetchNextPage(int page, int size) { return authorRepository.findAll(PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "age"))); } public Page<Author> fetchNextPageByGenre(int page, int size) { return authorRepository.fetchByGenre("History", PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "age"))); } public Page<Author> fetchNextPageByGenreExplicitCount(int page, int size) { return authorRepository.fetchByGenreExplicitCount("History", PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "age"))); }
public Page<Author> fetchNextPageByGenreNative(int page, int size) { return authorRepository.fetchByGenreNative("History", PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "age"))); } public Page<Author> fetchNextPageByGenreNativeExplicitCount(int page, int size) { return authorRepository.fetchByGenreNativeExplicitCount("History", PageRequest.of(page, size, Sort.by(Sort.Direction.ASC, "age"))); } public Page<Author> fetchNextPagePageable(Pageable pageable) { return authorRepository.findAll(pageable); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOffsetPagination\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void saveAll(@NonNull final Collection<I_PP_Order> orders) { orders.forEach(this::save); } @Override public void exportStatusMassUpdate( @NonNull final Map<PPOrderId, APIExportStatus> exportStatuses) { if (exportStatuses.isEmpty()) { return; } final HashMultimap<APIExportStatus, PPOrderId> orderIdsByExportStatus = HashMultimap.create(); for (final Map.Entry<PPOrderId, APIExportStatus> entry : exportStatuses.entrySet()) { orderIdsByExportStatus.put(entry.getValue(), entry.getKey()); } for (final APIExportStatus exportStatus : orderIdsByExportStatus.keySet()) { final Set<PPOrderId> orderIds = orderIdsByExportStatus.get(exportStatus); queryBL.createQueryBuilder(I_PP_Order.class) .addInArrayFilter(I_PP_Order.COLUMNNAME_PP_Order_ID, orderIds) .create() // .updateDirectly() .addSetColumnValue(I_PP_Order.COLUMNNAME_ExportStatus, exportStatus.getCode()) .execute(); } } @Override public IQueryBuilder<I_PP_Order> createQueryForPPOrderSelection(final IQueryFilter<I_PP_Order> userSelectionFilter) { return queryBL .createQueryBuilder(I_PP_Order.class) .filter(userSelectionFilter) .addNotEqualsFilter(I_PP_Order.COLUMNNAME_DocStatus, X_PP_Order.DOCSTATUS_Closed) .addOnlyActiveRecordsFilter() .addOnlyContextClient(); } @NonNull @Override
public ImmutableList<I_PP_OrderCandidate_PP_Order> getPPOrderAllocations(@NonNull final PPOrderId ppOrderId) { return queryBL .createQueryBuilder(I_PP_OrderCandidate_PP_Order.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_OrderCandidate_PP_Order.COLUMNNAME_PP_Order_ID, ppOrderId.getRepoId()) .create() .listImmutable(I_PP_OrderCandidate_PP_Order.class); } @NonNull public ImmutableList<I_PP_Order> getByProductBOMId(@NonNull final ProductBOMId productBOMId) { return queryBL .createQueryBuilder(I_PP_Order.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Order.COLUMNNAME_PP_Product_BOM_ID, productBOMId.getRepoId()) .create() .listImmutable(I_PP_Order.class); } @NonNull public Stream<I_PP_Order> streamDraftedPPOrdersFor(@NonNull final ProductBOMVersionsId bomVersionsId) { final ManufacturingOrderQuery query = ManufacturingOrderQuery.builder() .bomVersionsId(bomVersionsId) .onlyDrafted(true) .build(); final IQueryBuilder<I_PP_Order> ppOrderQueryBuilder = toSqlQueryBuilder(query); //dev-note: make sure there are no material transactions already created final IQuery<I_PP_Cost_Collector> withMaterialTransactionsQuery = queryBL.createQueryBuilder(I_PP_Cost_Collector.class) .addInSubQueryFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, I_PP_Order.COLUMNNAME_PP_Order_ID, ppOrderQueryBuilder.create()) .create(); return ppOrderQueryBuilder .addNotInSubQueryFilter(I_PP_Order.COLUMNNAME_PP_Order_ID, I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, withMaterialTransactionsQuery) .create() .iterateAndStream(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\PPOrderDAO.java
1
请完成以下Java代码
public abstract class FlowElementImpl extends BaseElementImpl implements FlowElement { protected static Attribute<String> nameAttribute; protected static ChildElement<Auditing> auditingChild; protected static ChildElement<Monitoring> monitoringChild; protected static ElementReferenceCollection<CategoryValue, CategoryValueRef> categoryValueRefCollection; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(FlowElement.class, BPMN_ELEMENT_FLOW_ELEMENT) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .abstractType(); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); auditingChild = sequenceBuilder.element(Auditing.class) .build(); monitoringChild = sequenceBuilder.element(Monitoring.class) .build(); categoryValueRefCollection = sequenceBuilder.elementCollection(CategoryValueRef.class) .qNameElementReferenceCollection(CategoryValue.class) .build(); typeBuilder.build(); } public FlowElementImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name);
} public Auditing getAuditing() { return auditingChild.getChild(this); } public void setAuditing(Auditing auditing) { auditingChild.setChild(this, auditing); } public Monitoring getMonitoring() { return monitoringChild.getChild(this); } public void setMonitoring(Monitoring monitoring) { monitoringChild.setChild(this, monitoring); } public Collection<CategoryValue> getCategoryValueRefs() { return categoryValueRefCollection.getReferenceTargetElements(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\FlowElementImpl.java
1
请完成以下Java代码
public class FloatingPointArithmetic { public static void main(String[] args) { double a = 13.22; double b = 4.88; double c = 21.45; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); double sum_ab = a + b; System.out.println("a + b = " + sum_ab); double abc = a + b + c; System.out.println("a + b + c = " + abc); double ab_c = sum_ab + c; System.out.println("ab + c = " + ab_c); double sum_ac = a + c; System.out.println("a + c = " + sum_ac); double acb = a + c + b; System.out.println("a + c + b = " + acb);
double ac_b = sum_ac + b; System.out.println("ac + b = " + ac_b); double ab = 18.1; double ac = 34.67; double sum_ab_c = ab + c; double sum_ac_b = ac + b; System.out.println("ab + c = " + sum_ab_c); System.out.println("ac + b = " + sum_ac_b); BigDecimal d = new BigDecimal(String.valueOf(a)); BigDecimal e = new BigDecimal(String.valueOf(b)); BigDecimal f = new BigDecimal(String.valueOf(c)); BigDecimal def = d.add(e).add(f); BigDecimal dfe = d.add(f).add(e); System.out.println("d + e + f = " + def); System.out.println("d + f + e = " + dfe); } }
repos\tutorials-master\core-java-modules\core-java-numbers-9\src\main\java\com\baeldung\maths\FloatingPointArithmetic.java
1
请完成以下Java代码
public class PP_Cost_Collector { private final IPPOrderBOMBL orderBOMBL = Services.get(IPPOrderBOMBL.class); @Init public void init() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(new org.eevolution.callout.PP_Cost_Collector()); } /** * Validates given cost collector and set missing fields if possible. */ @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }) public void validateAndSetMissingFields(final I_PP_Cost_Collector cc) { // // Set default locator, if not set and we have the warehouse: if (cc.getM_Locator_ID() <= 0 && cc.getM_Warehouse_ID() > 0) { final WarehouseId warehouseId = WarehouseId.ofRepoId(cc.getM_Warehouse_ID()); final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId); cc.setM_Locator_ID(locatorId.getRepoId()); } // // Case: Material Issue and By/Co-Products receipts // => validate against PP_Order_BOMLine which is mandatory final CostCollectorType costCollectorType = CostCollectorType.ofCode(cc.getCostCollectorType()); final PPOrderBOMLineId orderBOMLineId = PPOrderBOMLineId.ofRepoIdOrNull(cc.getPP_Order_BOMLine_ID()); if (costCollectorType.isAnyComponentIssueOrCoProduct(orderBOMLineId)) { if (orderBOMLineId == null) { throw new FillMandatoryException(I_PP_Cost_Collector.COLUMNNAME_PP_Order_BOMLine_ID); }
final UomId bomLineUOMId = orderBOMBL.getBOMLineUOMId(orderBOMLineId); // If no UOM, use the UOM from BOMLine if (cc.getC_UOM_ID() <= 0) { cc.setC_UOM_ID(bomLineUOMId.getRepoId()); } // If Cost Collector UOM differs from BOM Line UOM then throw exception because this conversion is not supported yet if (cc.getC_UOM_ID() != bomLineUOMId.getRepoId()) { throw new LiberoException("@PP_Cost_Collector_ID@ @C_UOM_ID@ <> @PP_Order_BOMLine_ID@ @C_UOM_ID@"); } } // // Case: Activity Control // => validate against PP_Order_Node which is mandatory else if (costCollectorType.isActivityControl()) { if (cc.getPP_Order_Node_ID() <= 0) { throw new FillMandatoryException(I_PP_Cost_Collector.COLUMNNAME_PP_Order_Node_ID); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\validator\PP_Cost_Collector.java
1
请完成以下Java代码
public boolean hasCurrent() { return currentItemSet; } public boolean hasNext() { final int size = list.size(); if (currentIndex < 0) { return size > 0; } else { return currentIndex + 1 < size; } } public I_M_HU next() { // Calculate the next index final int nextIndex; if (currentIndex < 0)
{ nextIndex = 0; } else { nextIndex = currentIndex + 1; } // Make sure the new index is valid final int size = list.size(); if (nextIndex >= size) { throw new NoSuchElementException("index=" + nextIndex + ", size=" + size); } // Update status this.currentIndex = nextIndex; this.currentItem = list.get(nextIndex); this.currentItemSet = true; return currentItem; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUListCursor.java
1
请在Spring Boot框架中完成以下Java代码
public byte[] getVariableData(@ApiParam(name = "caseInstanceId") @PathVariable("caseInstanceId") String caseInstanceId, @ApiParam(name = "variableName") @PathVariable("variableName") String variableName, HttpServletResponse response) { try { byte[] result = null; RestVariable variable = getVariableFromRequest(true, caseInstanceId, variableName); if (CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) { result = (byte[]) variable.getValue(); response.setContentType("application/octet-stream"); } else if (CmmnRestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(buffer); outputStream.writeObject(variable.getValue()); outputStream.close(); result = buffer.toByteArray(); response.setContentType("application/x-java-serialized-object"); } else { throw new FlowableObjectNotFoundException("The variable does not have a binary data stream.", null); } return result; } catch (IOException ioe) { // Re-throw IOException throw new FlowableException("Unexpected exception getting variable data", ioe); } }
public RestVariable getVariableFromRequest(boolean includeBinary, String caseInstanceId, String variableName) { HistoricCaseInstance caseObject = getHistoricCaseInstanceFromRequest(caseInstanceId); HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery() .caseInstanceId(caseObject.getId()) .variableName(variableName) .singleResult(); if (variable == null || variable.getValue() == null) { throw new FlowableObjectNotFoundException("Historic case instance '" + caseInstanceId + "' variable value for " + variableName + " couldn't be found.", VariableInstanceEntity.class); } else { return restResponseFactory.createRestVariable(variableName, variable.getValue(), null, caseInstanceId, CmmnRestResponseFactory.VARIABLE_HISTORY_CASE, includeBinary); } } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceVariableDataResource.java
2
请完成以下Java代码
public final class SpringAuthorizationEventPublisher implements AuthorizationEventPublisher { private final ApplicationEventPublisher eventPublisher; private Predicate<AuthorizationResult> shouldPublishResult = (result) -> !result.isGranted(); /** * Construct this publisher using Spring's {@link ApplicationEventPublisher} * @param eventPublisher */ public SpringAuthorizationEventPublisher(ApplicationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "eventPublisher cannot be null"); this.eventPublisher = eventPublisher; } /** * {@inheritDoc} */ @Override public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication, T object, @Nullable AuthorizationResult result) { if (result == null) { return; } if (!this.shouldPublishResult.test(result)) { return; }
AuthorizationDeniedEvent<T> failure = new AuthorizationDeniedEvent<>(authentication, object, result); this.eventPublisher.publishEvent(failure); } /** * Use this predicate to test whether to publish an event. * * <p> * Since you cannot publish a {@code null} event, checking for null is already * performed before this test is run * @param shouldPublishResult the test to perform on non-{@code null} events * @since 7.0 */ public void setShouldPublishResult(Predicate<AuthorizationResult> shouldPublishResult) { Assert.notNull(shouldPublishResult, "shouldPublishResult cannot be null"); this.shouldPublishResult = shouldPublishResult; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\SpringAuthorizationEventPublisher.java
1
请在Spring Boot框架中完成以下Java代码
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { /** * 用户认证 Manager */ @Autowired private AuthenticationManager authenticationManager; /** * 数据源 DataSource */ @Autowired private DataSource dataSource; @Bean public TokenStore jdbcTokenStore() { return new JdbcTokenStore(dataSource); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .tokenStore(jdbcTokenStore()); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.checkTokenAccess("isAuthenticated()"); // oauthServer.tokenKeyAccess("isAuthenticated()") // .checkTokenAccess("isAuthenticated()");
// oauthServer.tokenKeyAccess("permitAll()") // .checkTokenAccess("permitAll()"); } @Bean public ClientDetailsService jdbcClientDetailsService() { return new JdbcClientDetailsService(dataSource); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.withClientDetails(jdbcClientDetailsService()); } }
repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo11-authorization-server-by-jdbc-store\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\OAuth2AuthorizationServerConfig.java
2
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:db2://localhost:50000/testdb spring.datasource.username=db2inst1 spring.datasource.password=mypassword spring.datasource.driver-class-name=com.ibm.db2.jcc.DB2Driver spring.jpa.database-platform
=org.hibernate.dialect.DB2Dialect spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\resources\application-db2.properties
2
请完成以下Java代码
public Integer getRelatedStatus() { return relatedStatus; } public void setRelatedStatus(Integer relatedStatus) { this.relatedStatus = relatedStatus; } public Integer getHandAddStatus() { return handAddStatus; } public void setHandAddStatus(Integer handAddStatus) { this.handAddStatus = handAddStatus; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productAttributeCategoryId=").append(productAttributeCategoryId); sb.append(", name=").append(name); sb.append(", selectType=").append(selectType); sb.append(", inputType=").append(inputType); sb.append(", inputList=").append(inputList); sb.append(", sort=").append(sort); sb.append(", filterType=").append(filterType); sb.append(", searchType=").append(searchType); sb.append(", relatedStatus=").append(relatedStatus); sb.append(", handAddStatus=").append(handAddStatus); sb.append(", type=").append(type); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttribute.java
1
请在Spring Boot框架中完成以下Java代码
public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "4") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "null") public String getCalledProcessInstanceId() { return calledProcessInstanceId; } public void setCalledProcessInstanceId(String calledProcessInstanceId) { this.calledProcessInstanceId = calledProcessInstanceId; } @ApiModelProperty(example = "fozzie") public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getStartTime() { return startTime;
} public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @ApiModelProperty(example = "86400056") public Long getDurationInMillis() { return durationInMillis; } public void setDurationInMillis(Long durationInMillis) { this.durationInMillis = durationInMillis; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * Type AD_Reference_ID=541892 * Reference name: C_POS_JournalLine_Type */ public static final int TYPE_AD_Reference_ID=541892; /** CashPayment = CASH_PAY */ public static final String TYPE_CashPayment = "CASH_PAY"; /** CardPayment = CARD_PAY */ public static final String TYPE_CardPayment = "CARD_PAY"; /** CashInOut = CASH_INOUT */
public static final String TYPE_CashInOut = "CASH_INOUT"; /** CashClosingDifference = CASH_DIFF */ public static final String TYPE_CashClosingDifference = "CASH_DIFF"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_JournalLine.java
2
请在Spring Boot框架中完成以下Java代码
public class SecSecurityConfig { @Bean public InMemoryUserDetailsManager userDetailsService() { UserDetails user1 = User.withUsername("user1") .password(passwordEncoder().encode("user1Pass")) .roles("USER") .build(); UserDetails admin1 = User.withUsername("admin1") .password(passwordEncoder().encode("admin1Pass")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user1, admin1); } @Bean public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry .requestMatchers(mvc.pattern("/anonymous*")).anonymous() .requestMatchers(mvc.pattern("/login*"), mvc.pattern("/invalidSession*"), mvc.pattern("/sessionExpired*"), mvc.pattern("/foo/**")).permitAll() .anyRequest().authenticated()) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login") .loginProcessingUrl("/login") .successHandler(successHandler()) .failureUrl("/login?error=true")) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.deleteCookies("JSESSIONID")) .rememberMe(httpSecurityRememberMeConfigurer -> httpSecurityRememberMeConfigurer.key("uniqueAndSecret")
.tokenValiditySeconds(86400)) .sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionFixation() .migrateSession().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .invalidSessionUrl("/invalidSession") .maximumSessions(2) .expiredUrl("/sessionExpired")); return http.build(); } private AuthenticationSuccessHandler successHandler() { return new MySimpleUrlAuthenticationSuccessHandler(); } @Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) { return new MvcRequestMatcher.Builder(introspector); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\session\security\config\SecSecurityConfig.java
2