instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public String getAndroidVersion() { return androidVersion; } public void setAndroidVersion(String androidVersion) { this.androidVersion = androidVersion; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner;
} public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } public String getApplicationId() { return applicationId; } public void setApplicationId(String applicationId) { this.applicationId = applicationId; } }
repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\PosParam.java
1
请完成以下Java代码
public void delete(SuspendedJobEntity jobEntity) { super.delete(jobEntity); deleteExceptionByteArrayRef(jobEntity); if (jobEntity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) { CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById( jobEntity.getExecutionId() ); if (isExecutionRelatedEntityCountEnabled(executionEntity)) { executionEntity.setSuspendedJobCount(executionEntity.getSuspendedJobCount() - 1); } } // Send event if (getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this) ); } } /** * Deletes a the byte array used to store the exception information. Subclasses may override * to provide custom implementations. */ protected void deleteExceptionByteArrayRef(SuspendedJobEntity jobEntity) { ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef(); if (exceptionByteArrayRef != null) { exceptionByteArrayRef.delete(); } } protected SuspendedJobEntity createSuspendedJob(AbstractJobEntity job) { SuspendedJobEntity newSuspendedJobEntity = create(); newSuspendedJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration()); newSuspendedJobEntity.setJobHandlerType(job.getJobHandlerType());
newSuspendedJobEntity.setExclusive(job.isExclusive()); newSuspendedJobEntity.setRepeat(job.getRepeat()); newSuspendedJobEntity.setRetries(job.getRetries()); newSuspendedJobEntity.setEndDate(job.getEndDate()); newSuspendedJobEntity.setExecutionId(job.getExecutionId()); newSuspendedJobEntity.setProcessInstanceId(job.getProcessInstanceId()); newSuspendedJobEntity.setProcessDefinitionId(job.getProcessDefinitionId()); // Inherit tenant newSuspendedJobEntity.setTenantId(job.getTenantId()); newSuspendedJobEntity.setJobType(job.getJobType()); return newSuspendedJobEntity; } protected SuspendedJobDataManager getDataManager() { return jobDataManager; } public void setJobDataManager(SuspendedJobDataManager jobDataManager) { this.jobDataManager = jobDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\SuspendedJobEntityManagerImpl.java
1
请完成以下Java代码
public String getSkipReason() { return getLocalizedMessage(); } @Override public boolean isSkip() { return true; } @Override public int getSkipTimeoutMillis() { return skipTimeoutMillis;
} @Override public Exception getException() { return this; } /** * No need to fill the log if this exception is thrown. */ protected boolean isLoggedInTrxManager() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\exceptions\WorkpackageSkipRequestException.java
1
请完成以下Java代码
public void setParent_Column_ID (final int Parent_Column_ID) { if (Parent_Column_ID < 1) set_Value (COLUMNNAME_Parent_Column_ID, null); else set_Value (COLUMNNAME_Parent_Column_ID, Parent_Column_ID); } @Override public int getParent_Column_ID() { return get_ValueAsInt(COLUMNNAME_Parent_Column_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setQuickInput_CloseButton_Caption (final @Nullable java.lang.String QuickInput_CloseButton_Caption) { set_Value (COLUMNNAME_QuickInput_CloseButton_Caption, QuickInput_CloseButton_Caption); } @Override public java.lang.String getQuickInput_CloseButton_Caption() { return get_ValueAsString(COLUMNNAME_QuickInput_CloseButton_Caption); } @Override public void setQuickInput_OpenButton_Caption (final @Nullable java.lang.String QuickInput_OpenButton_Caption) { set_Value (COLUMNNAME_QuickInput_OpenButton_Caption, QuickInput_OpenButton_Caption); } @Override public java.lang.String getQuickInput_OpenButton_Caption() { return get_ValueAsString(COLUMNNAME_QuickInput_OpenButton_Caption); } @Override public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic) { set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic); } @Override public java.lang.String getReadOnlyLogic() { return get_ValueAsString(COLUMNNAME_ReadOnlyLogic); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setTabLevel (final int TabLevel) { set_Value (COLUMNNAME_TabLevel, TabLevel); } @Override public int getTabLevel() { return get_ValueAsInt(COLUMNNAME_TabLevel); }
@Override public org.compiere.model.I_AD_Tab getTemplate_Tab() { return get_ValueAsPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class); } @Override public void setTemplate_Tab(final org.compiere.model.I_AD_Tab Template_Tab) { set_ValueFromPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class, Template_Tab); } @Override public void setTemplate_Tab_ID (final int Template_Tab_ID) { if (Template_Tab_ID < 1) set_Value (COLUMNNAME_Template_Tab_ID, null); else set_Value (COLUMNNAME_Template_Tab_ID, Template_Tab_ID); } @Override public int getTemplate_Tab_ID() { return get_ValueAsInt(COLUMNNAME_Template_Tab_ID); } @Override public void setWhereClause (final @Nullable java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } @Override public java.lang.String getWhereClause() { return get_ValueAsString(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tab.java
1
请完成以下Java代码
public int getC_DocType_Correction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_Correction_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class); } @Override public void setC_DocType(org.compiere.model.I_C_DocType C_DocType) { set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType); } /** Set Belegart. @param C_DocType_ID Belegart oder Verarbeitungsvorgaben */ @Override public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Belegart oder Verarbeitungsvorgaben */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DocumentLinesNumber. @param DocumentLinesNumber DocumentLinesNumber */ @Override public void setDocumentLinesNumber (int DocumentLinesNumber) { set_Value (COLUMNNAME_DocumentLinesNumber, Integer.valueOf(DocumentLinesNumber)); } /** Get DocumentLinesNumber. @return DocumentLinesNumber */ @Override public int getDocumentLinesNumber () { Integer ii = (Integer)get_Value(COLUMNNAME_DocumentLinesNumber); if (ii == null) return 0; return ii.intValue(); }
/** Set Abgabemeldung Konfiguration. @param M_Shipment_Declaration_Config_ID Abgabemeldung Konfiguration */ @Override public void setM_Shipment_Declaration_Config_ID (int M_Shipment_Declaration_Config_ID) { if (M_Shipment_Declaration_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, Integer.valueOf(M_Shipment_Declaration_Config_ID)); } /** Get Abgabemeldung Konfiguration. @return Abgabemeldung Konfiguration */ @Override public int getM_Shipment_Declaration_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration_Config.java
1
请在Spring Boot框架中完成以下Java代码
public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public Integer getHistoryTimeToLive() { return historyTimeToLive; } public String getVersionTag(){ return versionTag; } public static DecisionDefinitionDto fromDecisionDefinition(DecisionDefinition definition) { DecisionDefinitionDto dto = new DecisionDefinitionDto(); dto.id = definition.getId(); dto.key = definition.getKey();
dto.category = definition.getCategory(); dto.name = definition.getName(); dto.version = definition.getVersion(); dto.resource = definition.getResourceName(); dto.deploymentId = definition.getDeploymentId(); dto.decisionRequirementsDefinitionId = definition.getDecisionRequirementsDefinitionId(); dto.decisionRequirementsDefinitionKey = definition.getDecisionRequirementsDefinitionKey(); dto.tenantId = definition.getTenantId(); dto.historyTimeToLive = definition.getHistoryTimeToLive(); dto.versionTag = definition.getVersionTag(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DecisionDefinitionDto.java
2
请完成以下Java代码
public class X_AD_TaskInstance extends PO implements I_AD_TaskInstance, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_AD_TaskInstance (Properties ctx, int AD_TaskInstance_ID, String trxName) { super (ctx, AD_TaskInstance_ID, trxName); /** if (AD_TaskInstance_ID == 0) { setAD_Task_ID (0); setAD_TaskInstance_ID (0); } */ } /** Load Constructor */ public X_AD_TaskInstance (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_TaskInstance[") .append(get_ID()).append("]"); return sb.toString(); } /** Set OS Task. @param AD_Task_ID Operation System Task */ public void setAD_Task_ID (int AD_Task_ID) { if (AD_Task_ID < 1) set_Value (COLUMNNAME_AD_Task_ID, null); else set_Value (COLUMNNAME_AD_Task_ID, Integer.valueOf(AD_Task_ID)); } /** Get OS Task. @return Operation System Task */ public int getAD_Task_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Task_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Task Instance. @param AD_TaskInstance_ID Task Instance */ public void setAD_TaskInstance_ID (int AD_TaskInstance_ID) { if (AD_TaskInstance_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_TaskInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_TaskInstance_ID, Integer.valueOf(AD_TaskInstance_ID)); } /** Get Task Instance. @return Task Instance */ public int getAD_TaskInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_TaskInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_TaskInstance_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TaskInstance.java
1
请完成以下Java代码
public void setFreight_Cost_Calc_Price (final BigDecimal Freight_Cost_Calc_Price) { set_Value (COLUMNNAME_Freight_Cost_Calc_Price, Freight_Cost_Calc_Price); } @Override public BigDecimal getFreight_Cost_Calc_Price() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Freight_Cost_Calc_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_DiscountSchema_Calculated_Surcharge_Price_ID (final int M_DiscountSchema_Calculated_Surcharge_Price_ID) { if (M_DiscountSchema_Calculated_Surcharge_Price_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_ID, M_DiscountSchema_Calculated_Surcharge_Price_ID);
} @Override public int getM_DiscountSchema_Calculated_Surcharge_Price_ID() { return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_Price_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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema_Calculated_Surcharge_Price.java
1
请完成以下Java代码
public void save(@NonNull final PPOrderWeightingRun weightingRun) { final PPOrderWeightingRunLoaderAndSaver saver = new PPOrderWeightingRunLoaderAndSaver(); saver.save(weightingRun); } public UomId getUomId(final PPOrderWeightingRunId id) { final PPOrderWeightingRunLoaderAndSaver loader = new PPOrderWeightingRunLoaderAndSaver(); return loader.getUomId(id); } public void updateWhileSaving( @NonNull final I_PP_Order_Weighting_Run record, @NonNull final Consumer<PPOrderWeightingRun> consumer) { final PPOrderWeightingRunId runId = PPOrderWeightingRunLoaderAndSaver.extractId(record); final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver(); loaderAndSaver.addToCacheAndAvoidSaving(record); loaderAndSaver.updateById(runId, consumer); } public void updateById( @NonNull final PPOrderWeightingRunId runId, @NonNull final Consumer<PPOrderWeightingRun> consumer) { final PPOrderWeightingRunLoaderAndSaver loaderAndSaver = new PPOrderWeightingRunLoaderAndSaver(); loaderAndSaver.updateById(runId, consumer);
} public void deleteChecks(final PPOrderWeightingRunId runId) { queryBL.createQueryBuilder(I_PP_Order_Weighting_RunCheck.class) .addEqualsFilter(I_PP_Order_Weighting_RunCheck.COLUMNNAME_PP_Order_Weighting_Run_ID, runId) .create() .delete(); } public PPOrderWeightingRunCheckId addRunCheck( @NonNull final PPOrderWeightingRunId weightingRunId, @NonNull final SeqNo lineNo, @NonNull final Quantity weight, @NonNull final OrgId orgId) { final I_PP_Order_Weighting_RunCheck record = InterfaceWrapperHelper.newInstance(I_PP_Order_Weighting_RunCheck.class); record.setAD_Org_ID(orgId.getRepoId()); record.setPP_Order_Weighting_Run_ID(weightingRunId.getRepoId()); record.setLine(lineNo.toInt()); record.setWeight(weight.toBigDecimal()); record.setC_UOM_ID(weight.getUomId().getRepoId()); InterfaceWrapperHelper.save(record); return PPOrderWeightingRunCheckId.ofRepoId(weightingRunId, record.getPP_Order_Weighting_RunCheck_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunRepository.java
1
请完成以下Java代码
static void removeWithForLoopIncrementIfRemains(List<Integer> list, int element) { for (int i = 0; i < list.size();) { if (Objects.equals(element, list.get(i))) { list.remove(i); } else { i++; } } } static void removeWithForEachLoop(List<Integer> list, int element) { for (Integer number : list) { if (Objects.equals(number, element)) { list.remove(number); } } } static void removeWithIterator(List<Integer> list, int element) { for (Iterator<Integer> i = list.iterator(); i.hasNext();) { Integer number = i.next(); if (Objects.equals(number, element)) { i.remove(); } } } static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) { List<Integer> remainingElements = new ArrayList<>(); for (Integer number : list) { if (!Objects.equals(number, element)) { remainingElements.add(number); } } return remainingElements; } static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) { List<Integer> remainingElements = new ArrayList<>(); for (Integer number : list) {
if (!Objects.equals(number, element)) { remainingElements.add(number); } } list.clear(); list.addAll(remainingElements); } static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) { return list.stream() .filter(e -> !Objects.equals(e, element)) .collect(Collectors.toList()); } static void removeWithRemoveIf(List<Integer> list, Integer element) { list.removeIf(n -> Objects.equals(n, element)); } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\removeall\RemoveAll.java
1
请完成以下Java代码
public Post find(Long id) { EntityManager entityManager = emf.createEntityManager(); Post post = entityManager.find(Post.class, id); entityManager.close(); return post; } public Post findWithEntityGraph(Long id) { EntityManager entityManager = emf.createEntityManager(); EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph"); Map<String, Object> properties = new HashMap<>(); properties.put("jakarta.persistence.fetchgraph", entityGraph); Post post = entityManager.find(Post.class, id, properties); entityManager.close(); return post; } public Post findWithEntityGraph2(Long id) { EntityManager entityManager = emf.createEntityManager(); EntityGraph<Post> entityGraph = entityManager.createEntityGraph(Post.class); entityGraph.addAttributeNodes("subject"); entityGraph.addAttributeNodes("user"); entityGraph.addSubgraph("comments") .addAttributeNodes("user"); Map<String, Object> properties = new HashMap<>(); properties.put("jakarta.persistence.fetchgraph", entityGraph); Post post = entityManager.find(Post.class, id, properties); entityManager.close(); return post; }
public Post findUsingJpql(Long id) { EntityManager entityManager = emf.createEntityManager(); EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); Post post = entityManager.createQuery("Select p from Post p where p.id=:id", Post.class) .setParameter("id", id) .setHint("jakarta.persistence.fetchgraph", entityGraph) .getSingleResult(); entityManager.close(); return post; } public Post findUsingCriteria(Long id) { EntityManager entityManager = emf.createEntityManager(); EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Post> criteriaQuery = criteriaBuilder.createQuery(Post.class); Root<Post> root = criteriaQuery.from(Post.class); criteriaQuery.where(criteriaBuilder.equal(root.<Long>get("id"), id)); TypedQuery<Post> typedQuery = entityManager.createQuery(criteriaQuery); typedQuery.setHint("jakarta.persistence.loadgraph", entityGraph); Post post = typedQuery.getSingleResult(); entityManager.close(); return post; } public void clean() { emf.close(); } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entitygraph\repo\PostRepository.java
1
请完成以下Java代码
public void alreadyDeployed() { logWarn( "016", "Ignoring call of deploy() on process application that is already deployed."); } public void notDeployed() { logWarn( "017", "Calling undeploy() on process application that is not deployed."); } public void couldNotRemoveDefinitionsFromCache(Throwable t) { logError( "018", "Unregistering process application for deployment but could not remove process definitions from deployment cache.", t); } public ProcessEngineException exceptionWhileRegisteringDeploymentsWithJobExecutor(Exception e) { return new ProcessEngineException(exceptionMessage( "019", "Exception while registering deployment with job executor"), e); } public void exceptionWhileUnregisteringDeploymentsWithJobExecutor(Exception e) { logError( "020", "Exceptions while unregistering deployments with job executor", e); } public void registrationSummary(String string) { logInfo( "021",
string); } public void exceptionWhileLoggingRegistrationSummary(Throwable e) { logError( "022", "Exception while logging registration summary", e); } public boolean isContextSwitchLoggable() { return isDebugEnabled(); } public void debugNoTargetProcessApplicationFound(ExecutionEntity execution, ProcessApplicationManager processApplicationManager) { logDebug("023", "No target process application found for Execution[{}], ProcessDefinition[{}], Deployment[{}] Registrations[{}]", execution.getId(), execution.getProcessDefinitionId(), execution.getProcessDefinition().getDeploymentId(), processApplicationManager.getRegistrationSummary()); } public void debugNoTargetProcessApplicationFoundForCaseExecution(CaseExecutionEntity execution, ProcessApplicationManager processApplicationManager) { logDebug("024", "No target process application found for CaseExecution[{}], CaseDefinition[{}], Deployment[{}] Registrations[{}]", execution.getId(), execution.getCaseDefinitionId(), ((CaseDefinitionEntity)execution.getCaseDefinition()).getDeploymentId(), processApplicationManager.getRegistrationSummary()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\ProcessApplicationLogger.java
1
请完成以下Java代码
public String getBICOrBEI() { return bicOrBEI; } /** * Sets the value of the bicOrBEI property. * * @param value * allowed object is * {@link String } * */ public void setBICOrBEI(String value) { this.bicOrBEI = value; } /** * Gets the value of the othr property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the othr property. * * <p>
* For example, to add a new item, do as follows: * <pre> * getOthr().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link GenericOrganisationIdentification1 } * * */ public List<GenericOrganisationIdentification1> getOthr() { if (othr == null) { othr = new ArrayList<GenericOrganisationIdentification1>(); } return this.othr; } }
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\OrganisationIdentification4.java
1
请完成以下Java代码
public class ListTransformer implements FeelToJuelTransformer { public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; // regex to split by comma which does a positive look ahead to ignore commas enclosed in quotes public static final String COMMA_SEPARATOR_REGEX = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"; public boolean canTransform(String feelExpression) { return splitExpression(feelExpression).size() > 1; } public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { List<String> juelExpressions = transformExpressions(transform, feelExpression, inputName); return joinExpressions(juelExpressions); } protected List<String> collectExpressions(String feelExpression) { return splitExpression(feelExpression); } private List<String> splitExpression(String feelExpression) { return Arrays.asList(feelExpression.split(COMMA_SEPARATOR_REGEX, -1)); } protected List<String> transformExpressions(FeelToJuelTransform transform, String feelExpression, String inputName) { List<String> expressions = collectExpressions(feelExpression); List<String> juelExpressions = new ArrayList<String>();
for (String expression : expressions) { if (!expression.trim().isEmpty()) { String juelExpression = transform.transformSimplePositiveUnaryTest(expression, inputName); juelExpressions.add(juelExpression); } else { throw LOG.invalidListExpression(feelExpression); } } return juelExpressions; } protected String joinExpressions(List<String> juelExpressions) { StringBuilder builder = new StringBuilder(); builder.append("(").append(juelExpressions.get(0)).append(")"); for (int i = 1; i < juelExpressions.size(); i++) { builder.append(" || (").append(juelExpressions.get(i)).append(")"); } return builder.toString(); } }
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\transform\ListTransformer.java
1
请完成以下Java代码
public void debugPerformingAtomicOperation(CoreAtomicOperation<?> atomicOperation, CoreExecution e) { logDebug( "003", "Performing atomic operation {} on {}", atomicOperation, e); } public ProcessEngineException duplicateVariableInstanceException(CoreVariableInstance variableInstance) { return new ProcessEngineException(exceptionMessage( "004", "Cannot add variable instance with name {}. Variable already exists", variableInstance.getName() )); } // We left out id 005!
// please skip it unless you backport it to all maintained versions to avoid inconsistencies public ProcessEngineException transientVariableException(String variableName) { return new ProcessEngineException(exceptionMessage( "006", "Cannot set transient variable with name {} to non-transient variable and vice versa.", variableName )); } public ProcessEngineException javaSerializationProhibitedException(String variableName) { return new ProcessEngineException(exceptionMessage("007", MessageFormat.format(ERROR_MSG, variableName))); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\CoreLogger.java
1
请完成以下Java代码
public class SystemEnvironmentOrigin implements Origin { private final String property; public SystemEnvironmentOrigin(String property) { Assert.hasText(property, "'property' must not be empty"); this.property = property; } public String getProperty() { return this.property; } @Override public boolean equals(Object obj) { if (this == obj) { return true; }
if (obj == null || getClass() != obj.getClass()) { return false; } SystemEnvironmentOrigin other = (SystemEnvironmentOrigin) obj; return ObjectUtils.nullSafeEquals(this.property, other.property); } @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(this.property); } @Override public String toString() { return "System Environment Property \"" + this.property + "\""; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\origin\SystemEnvironmentOrigin.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * PickingJobAggregationType AD_Reference_ID=541931 * Reference name: PickingJobAggregationType */ public static final int PICKINGJOBAGGREGATIONTYPE_AD_Reference_ID=541931; /** sales_order = sales_order */ public static final String PICKINGJOBAGGREGATIONTYPE_Sales_order = "sales_order"; /** product = product */ public static final String PICKINGJOBAGGREGATIONTYPE_Product = "product"; /** delivery_location = delivery_location */ public static final String PICKINGJOBAGGREGATIONTYPE_Delivery_location = "delivery_location"; @Override public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType) { set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType); } @Override public java.lang.String getPickingJobAggregationType() { return get_ValueAsString(COLUMNNAME_PickingJobAggregationType); } /** * PickingLineGroupBy AD_Reference_ID=541899 * Reference name: PickingLineGroupByValues */ public static final int PICKINGLINEGROUPBY_AD_Reference_ID=541899; /** Product_Category = product_category */ public static final String PICKINGLINEGROUPBY_Product_Category = "product_category"; @Override public void setPickingLineGroupBy (final @Nullable java.lang.String PickingLineGroupBy) { set_Value (COLUMNNAME_PickingLineGroupBy, PickingLineGroupBy); } @Override public java.lang.String getPickingLineGroupBy() {
return get_ValueAsString(COLUMNNAME_PickingLineGroupBy); } /** * PickingLineSortBy AD_Reference_ID=541900 * Reference name: PickingLineSortByValues */ public static final int PICKINGLINESORTBY_AD_Reference_ID=541900; /** ORDER_LINE_SEQ_NO = ORDER_LINE_SEQ_NO */ public static final String PICKINGLINESORTBY_ORDER_LINE_SEQ_NO = "ORDER_LINE_SEQ_NO"; /** QTY_TO_PICK_ASC = QTY_TO_PICK_ASC */ public static final String PICKINGLINESORTBY_QTY_TO_PICK_ASC = "QTY_TO_PICK_ASC"; /** QTY_TO_PICK_DESC = QTY_TO_PICK_DESC */ public static final String PICKINGLINESORTBY_QTY_TO_PICK_DESC = "QTY_TO_PICK_DESC"; @Override public void setPickingLineSortBy (final @Nullable java.lang.String PickingLineSortBy) { set_Value (COLUMNNAME_PickingLineSortBy, PickingLineSortBy); } @Override public java.lang.String getPickingLineSortBy() { return get_ValueAsString(COLUMNNAME_PickingLineSortBy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking.java
1
请完成以下Java代码
public class EDI_DESADVExport extends AbstractExport<I_EDI_Document> { /** * EXP_Format.Value for exporting InOut EDI documents */ private static final String CST_DESADV_EXP_FORMAT = "EDI_Exp_Desadv"; private final IDesadvDAO desadvDAO = Services.get(IDesadvDAO.class); private final IInOutBL shipmentBL = Services.get(IInOutBL.class); public EDI_DESADVExport(final I_EDI_Desadv desadv, final String tableIdentifier, final ClientId clientId) { super(InterfaceWrapperHelper.create(desadv, I_EDI_Document.class), tableIdentifier, clientId); } @Override public List<Exception> doExport() { final IEDIDocumentBL ediDocumentBL = Services.get(IEDIDocumentBL.class); final I_EDI_Document document = getDocument(); final I_EDI_Desadv desadv = InterfaceWrapperHelper.create(document, I_EDI_Desadv.class); final List<Exception> feedback = ediDocumentBL.isValidDesAdv(desadv); final String EDIStatus = document.getEDI_ExportStatus(); final ValidationState validationState = ediDocumentBL.updateInvalid(document, EDIStatus, feedback, true); // saveLocally=true if (ValidationState.ALREADY_VALID != validationState) { // otherwise, it's either INVALID, or freshly updated (which, keeping the old logic, must be dealt with in one more step) return feedback; } // Mark the document as: EDI starting document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_SendingStarted); InterfaceWrapperHelper.save(document); desadvDAO.retrieveAllInOuts(desadv)
.stream() .peek(shipment -> shipment.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_SendingStarted)) .forEach(shipmentBL::save); try { exportEDI(I_EDI_Desadv.class, EDI_DESADVExport.CST_DESADV_EXP_FORMAT, I_EDI_Desadv.Table_Name, I_EDI_Desadv.COLUMNNAME_EDI_Desadv_ID); } catch (final Exception e) { document.setEDI_ExportStatus(I_EDI_Document_Extension.EDI_EXPORTSTATUS_Error); final ITranslatableString errorMsgTrl = TranslatableStrings.parse(e.getLocalizedMessage()); document.setEDIErrorMsg(errorMsgTrl.translate(Env.getAD_Language())); InterfaceWrapperHelper.save(document); throw AdempiereException .wrapIfNeeded(e) .markAsUserValidationError(); } return Collections.emptyList(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\impl\EDI_DESADVExport.java
1
请完成以下Java代码
public static Date toDate(LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } /** * LocalDate 转 Date * Jdk8 后 不推荐使用 {@link Date} Date * * @param localDate / * @return / */ public static Date toDate(LocalDate localDate) { return toDate(localDate.atTime(LocalTime.now(ZoneId.systemDefault()))); } /** * Date转 LocalDateTime * Jdk8 后 不推荐使用 {@link Date} Date * * @param date / * @return / */ public static LocalDateTime toLocalDateTime(Date date) { return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } /** * 日期 格式化 * * @param localDateTime / * @param patten / * @return / */ public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) { DateTimeFormatter df = DateTimeFormatter.ofPattern(patten); return df.format(localDateTime); } /** * 日期 格式化 * * @param localDateTime / * @param df / * @return / */ public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) { return df.format(localDateTime); } /** * 日期格式化 yyyy-MM-dd HH:mm:ss * * @param localDateTime / * @return /
*/ public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) { return DFY_MD_HMS.format(localDateTime); } /** * 日期格式化 yyyy-MM-dd * * @param localDateTime / * @return / */ public String localDateTimeFormatyMd(LocalDateTime localDateTime) { return DFY_MD.format(localDateTime); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) { return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) { return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime)); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\DateUtil.java
1
请完成以下Java代码
public abstract class AbstractCmmnEventAtomicOperation extends AbstractEventAtomicOperation<CmmnExecution> implements CmmnAtomicOperation { protected CmmnActivity getScope(CmmnExecution execution) { return execution.getActivity(); } public boolean isAsync(CmmnExecution execution) { return false; } protected void eventNotificationsCompleted(CmmnExecution execution) { repetition(execution); preTransitionNotification(execution); performTransitionNotification(execution); postTransitionNotification(execution); } protected void repetition(CmmnExecution execution) { CmmnActivityBehavior behavior = getActivityBehavior(execution); behavior.repeat(execution, getEventName()); } protected void preTransitionNotification(CmmnExecution execution) {
} protected void performTransitionNotification(CmmnExecution execution) { String eventName = getEventName(); CmmnExecution parent = execution.getParent(); if (parent != null) { parent.handleChildTransition(execution, eventName); } } protected void postTransitionNotification(CmmnExecution execution) { // noop } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\operation\AbstractCmmnEventAtomicOperation.java
1
请在Spring Boot框架中完成以下Java代码
public class CLR implements CommandLineRunner { @Autowired UserRepository repository; @Override public void run(String... args) throws Exception { User luke = new User("id-1", "luke"); luke.setFirstname("Luke"); luke.setLastname("Skywalker"); User leia = new User("id-2", "leia"); leia.setFirstname("Leia"); leia.setLastname("Organa"); User han = new User("id-3", "han"); han.setFirstname("Han"); han.setLastname("Solo"); User chewbacca = new User("id-4", "chewbacca"); User yoda = new User("id-5", "yoda"); User vader = new User("id-6", "vader"); vader.setFirstname("Anakin"); vader.setLastname("Skywalker"); User kylo = new User("id-7", "kylo"); kylo.setFirstname("Ben"); kylo.setLastname("Solo"); repository.saveAll(List.of(luke, leia, han, chewbacca, yoda, vader, kylo)); System.out.println("------- annotated multi -------"); System.out.println(repository.usersWithUsernamesStartingWith("l")); System.out.println("------- derived single -------"); System.out.println(repository.findUserByUsername("yoda")); System.out.println("------- derived optional -------"); System.out.println(repository.findOptionalUserByUsername("yoda")); System.out.println("------- derived count -------"); Long count = repository.countUsersByLastnameLike("Sky"); System.out.println("user count " + count); System.out.println("------- derived exists -------"); Boolean exists = repository.existsByUsername("vader");
System.out.println("user exists " + exists); System.out.println("------- derived multi -------"); System.out.println(repository.findUserByLastnameStartingWith("Sky")); System.out.println("------- derived sorted -------"); System.out.println(repository.findUserByLastnameStartingWithOrderByFirstname("Sky")); System.out.println("------- derived page -------"); Page<User> page0 = repository.findUserByLastnameStartingWith("S", PageRequest.of(0, 2)); System.out.println("page0: " + page0); System.out.println("page0.content: " + page0.getContent()); Page<User> page1 = repository.findUserByLastnameStartingWith("S", PageRequest.of(1, 2)); System.out.println("page1: " + page1); System.out.println("page1.content: " + page1.getContent()); System.out.println("------- derived slice -------"); Slice<User> slice0 = repository.findUserByUsernameAfter("luke", PageRequest.of(0, 2)); System.out.println("slice0: " + slice0); System.out.println("slice0.content: " + slice0.getContent()); System.out.println("------- derived top -------"); System.out.println(repository.findTop2UsersByLastnameStartingWith("S")); } }
repos\spring-data-examples-main\jpa\aot-optimization\src\main\java\example\springdata\aot\CLR.java
2
请完成以下Java代码
public Date getFollowUp() { return followUp; } public String getTenantId() { return tenantId; } public Date getRemovalTime() { return removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } /** * Returns task State of history tasks */ public String getTaskState() { return taskState; } public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) { HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto(); dto.id = taskInstance.getId(); dto.processDefinitionKey = taskInstance.getProcessDefinitionKey(); dto.processDefinitionId = taskInstance.getProcessDefinitionId(); dto.processInstanceId = taskInstance.getProcessInstanceId(); dto.executionId = taskInstance.getExecutionId(); dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey(); dto.caseDefinitionId = taskInstance.getCaseDefinitionId(); dto.caseInstanceId = taskInstance.getCaseInstanceId(); dto.caseExecutionId = taskInstance.getCaseExecutionId(); dto.activityInstanceId = taskInstance.getActivityInstanceId(); dto.name = taskInstance.getName();
dto.description = taskInstance.getDescription(); dto.deleteReason = taskInstance.getDeleteReason(); dto.owner = taskInstance.getOwner(); dto.assignee = taskInstance.getAssignee(); dto.startTime = taskInstance.getStartTime(); dto.endTime = taskInstance.getEndTime(); dto.duration = taskInstance.getDurationInMillis(); dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey(); dto.priority = taskInstance.getPriority(); dto.due = taskInstance.getDueDate(); dto.parentTaskId = taskInstance.getParentTaskId(); dto.followUp = taskInstance.getFollowUpDate(); dto.tenantId = taskInstance.getTenantId(); dto.removalTime = taskInstance.getRemovalTime(); dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId(); dto.taskState = taskInstance.getTaskState(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceDto.java
1
请完成以下Java代码
public body getBody() { return m_body; } // getBody /** * Get Head * @return Header */ public head getHead() { return m_head; } // getHead /** * Get Table (no class set) * @return table */ public table getTable() { return m_table; } // getTable /** * Get Table Row (no class set) * @return table row */ public tr getTopRow() { return m_topRow; } // getTopRow /** * Get Table Data Left (no class set) * @return table data */ public td getTopLeft() { return m_topLeft; } // getTopLeft /** * Get Table Data Right (no class set) * @return table data */ public td getTopRight() { return m_topRight; } // getTopRight /** * String representation * @return String */ @Override public String toString() { return m_html.toString(); } // toString /**
* Output Document * @param out out */ public void output (OutputStream out) { m_html.output(out); } // output /** * Output Document * @param out out */ public void output (PrintWriter out) { m_html.output(out); } // output /** * Add Popup Center * @param nowrap set nowrap in td * @return null or center single td */ public td addPopupCenter(boolean nowrap) { if (m_table == null) return null; // td center = new td ("popupCenter", AlignType.CENTER, AlignType.MIDDLE, nowrap); center.setColSpan(2); m_table.addElement(new tr() .addElement(center)); return center; } // addPopupCenter } // WDoc
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebDoc.java
1
请完成以下Java代码
private Set<EntityData<?>> getEntitiesSet(RelationsRepo relations) { Set<EntityData<?>> result = new HashSet<>(); Set<RelationSearchTask> processed = new HashSet<>(); Queue<RelationSearchTask> tasks = new LinkedList<>(); int maxLvl = getMaxLevel() == 0 ? MAXIMUM_QUERY_LEVEL : Math.max(1, getMaxLevel()); for (UUID uuid : getRootEntities()) { tasks.add(new RelationSearchTask(uuid, 0)); } while (!tasks.isEmpty()) { RelationSearchTask task = tasks.poll(); if (processed.add(task)) { var entityLvl = task.lvl + 1; Set<RelationInfo> entities = EntitySearchDirection.FROM.equals(getDirection()) ? relations.getFrom(task.entityId) : relations.getTo(task.entityId); if (isFetchLastLevelOnly() && entities.isEmpty() && task.previous != null && check(task.previous)) { result.add(task.previous.getTarget()); } for (RelationInfo relationInfo : entities) { var entity = relationInfo.getTarget(); if (entity.isEmpty()) { continue; } var entityId = entity.getId(); if (isFetchLastLevelOnly()) { if (entityLvl < maxLvl) { tasks.add(new RelationSearchTask(entityId, entityLvl, relationInfo)); } else if (entityLvl == maxLvl) { if (check(relationInfo)) { if (isMultiRoot()) { ctx.getRelatedParentIdMap().put(entity.getId(), task.entityId); } result.add(entity); } } } else { if (check(relationInfo)) { if (isMultiRoot()) { ctx.getRelatedParentIdMap().put(entity.getId(), task.entityId);
} result.add(entity); } if (entityLvl < maxLvl) { tasks.add(new RelationSearchTask(entityId, entityLvl)); } } } } } return result; } protected abstract boolean check(RelationInfo relationInfo); @RequiredArgsConstructor @EqualsAndHashCode private static class RelationSearchTask { private final UUID entityId; private final int lvl; private final RelationInfo previous; public RelationSearchTask(UUID entityId, int lvl) { this(entityId, lvl, null); } } }
repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\query\processor\AbstractRelationQueryProcessor.java
1
请完成以下Java代码
private void checkPayments(final I_C_BPartner bp) { // See also VMerge.postMerge int changed = 0; final MPayment[] payments = MPayment.getOfBPartner(getCtx(), bp.getC_BPartner_ID(), get_TrxName()); for (final MPayment payment : payments) { if (payment.testAllocation()) { payment.save(); changed++; } } if (changed != 0) { addLog(0, null, new BigDecimal(payments.length), Msg.getElement(getCtx(), "C_Payment_ID") + " - #" + changed); } } // checkPayments /** * Check Invoices *
* @param bp business partner */ private void checkInvoices(final I_C_BPartner bp) { // See also VMerge.postMerge int changed = 0; final MInvoice[] invoices = MInvoice.getOfBPartner(getCtx(), bp.getC_BPartner_ID(), get_TrxName()); for (final MInvoice invoice : invoices) { if (invoice.testAllocation()) { invoice.save(); changed++; } } if (changed != 0) { addLog(0, null, new BigDecimal(invoices.length), Msg.getElement(getCtx(), "C_Invoice_ID") + " - #" + changed); } } // checkInvoices } // BPartnerValidate
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\BPartnerValidate.java
1
请完成以下Java代码
public CmmnElement getCmmnModelElementInstance() { CmmnModelInstance cmmnModelInstance = getCmmnModelInstance(); if(cmmnModelInstance != null) { ModelElementInstance modelElementInstance = cmmnModelInstance.getModelElementById(activityId); try { return (CmmnElement) modelElementInstance; } catch(ClassCastException e) { ModelElementType elementType = modelElementInstance.getElementType(); throw new ProcessEngineException("Cannot cast "+modelElementInstance+" to CmmnElement. " + "Is of type "+elementType.getTypeName() + " Namespace " + elementType.getTypeNamespace(), e); } } else { return null; } } public ProcessEngineServices getProcessEngineServices() { return Context .getProcessEngineConfiguration() .getProcessEngine(); }
public ProcessEngine getProcessEngine() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public String getCaseDefinitionTenantId() { CaseDefinitionEntity caseDefinition = (CaseDefinitionEntity) getCaseDefinition(); return caseDefinition.getTenantId(); } public <T extends CoreExecution> void performOperation(CoreAtomicOperation<T> operation) { Context.getCommandContext() .performOperation((CmmnAtomicOperation) operation, this); } public <T extends CoreExecution> void performOperationSync(CoreAtomicOperation<T> operation) { Context.getCommandContext() .performOperation((CmmnAtomicOperation) operation, this); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseExecutionEntity.java
1
请完成以下Java代码
public String getMainVersion() { return mainVersion; } public boolean matches(String version) { if (version.equals(mainVersion)) { return true; } else if (!alternativeVersionStrings.isEmpty()) { return alternativeVersionStrings.contains(version); } else { return false; } } public boolean equals(Object obj) { if (!(obj instanceof ActivitiVersion)) {
return false; } ActivitiVersion other = (ActivitiVersion) obj; boolean mainVersionEqual = mainVersion.equals(other.mainVersion); if (!mainVersionEqual) { return false; } else { if (alternativeVersionStrings != null) { return alternativeVersionStrings.equals(other.alternativeVersionStrings); } else { return other.alternativeVersionStrings == null; } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\ActivitiVersion.java
1
请完成以下Java代码
protected void deleteTenantMembershipsOfUser(String userId) { getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfUser", userId); } protected void deleteTenantMembershipsOfGroup(String groupId) { getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfGroup", groupId); } protected void deleteTenantMembershipsOfTenant(String tenant) { getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfTenant", tenant); } // authorizations //////////////////////////////////////////////////////////// protected void createDefaultAuthorizations(UserEntity userEntity) { if(Context.getProcessEngineConfiguration().isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().newUser(userEntity)); } } protected void createDefaultAuthorizations(Group group) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().newGroup(group)); } } protected void createDefaultAuthorizations(Tenant tenant) { if (isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newTenant(tenant)); } } protected void createDefaultMembershipAuthorizations(String userId, String groupId) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().groupMembershipCreated(groupId, userId)); } } protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, User user) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, user)); } } protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, Group group) { if(isAuthorizationEnabled()) { saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, group)); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbIdentityServiceProvider.java
1
请完成以下Spring Boot application配置
logging.level.org.springframework: DEBUG app.name=in28Minutes welcome.message=Welcome message from property file! Welcome to ${app.name} basic.v
alue=true basic.message=Welcome to in28minutes basic.number=200
repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\resources\application.properties
2
请完成以下Java代码
public Group newGroup(String groupId) { return getIdmIdentityService().newGroup(groupId); } @Override public User newUser(String userId) { return getIdmIdentityService().newUser(userId); } @Override public void saveGroup(Group group) { getIdmIdentityService().saveGroup(group); } @Override public void saveUser(User user) { getIdmIdentityService().saveUser(user); } @Override public void updateUserPassword(User user) { getIdmIdentityService().updateUserPassword(user); } @Override public UserQuery createUserQuery() { return getIdmIdentityService().createUserQuery(); } @Override public NativeUserQuery createNativeUserQuery() { return getIdmIdentityService().createNativeUserQuery(); } @Override public GroupQuery createGroupQuery() { return getIdmIdentityService().createGroupQuery(); } @Override public NativeGroupQuery createNativeGroupQuery() { return getIdmIdentityService().createNativeGroupQuery(); } @Override public void createMembership(String userId, String groupId) { getIdmIdentityService().createMembership(userId, groupId); } @Override public void deleteGroup(String groupId) { getIdmIdentityService().deleteGroup(groupId); }
@Override public void deleteMembership(String userId, String groupId) { getIdmIdentityService().deleteMembership(userId, groupId); } @Override public boolean checkPassword(String userId, String password) { return getIdmIdentityService().checkPassword(userId, password); } @Override public void deleteUser(String userId) { getIdmIdentityService().deleteUser(userId); } @Override public void setUserPicture(String userId, Picture picture) { getIdmIdentityService().setUserPicture(userId, picture); } public Picture getUserPicture(String userId) { return getIdmIdentityService().getUserPicture(userId); } @Override public void setAuthenticatedUserId(String authenticatedUserId) { Authentication.setAuthenticatedUserId(authenticatedUserId); } @Override public String getUserInfo(String userId, String key) { return getIdmIdentityService().getUserInfo(userId, key); } @Override public List<String> getUserInfoKeys(String userId) { return getIdmIdentityService().getUserInfoKeys(userId); } @Override public void setUserInfo(String userId, String key, String value) { getIdmIdentityService().setUserInfo(userId, key, value); } @Override public void deleteUserInfo(String userId, String key) { getIdmIdentityService().deleteUserInfo(userId, key); } protected IdmIdentityService getIdmIdentityService() { return CommandContextUtil.getIdmIdentityService(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\IdentityServiceImpl.java
1
请完成以下Java代码
public class ActivitiVersion { protected String mainVersion; protected List<String> alternativeVersionStrings; public ActivitiVersion(String mainVersion) { this.mainVersion = mainVersion; this.alternativeVersionStrings = singletonList(mainVersion); } public ActivitiVersion(String mainVersion, List<String> alternativeVersionStrings) { this.mainVersion = mainVersion; this.alternativeVersionStrings = alternativeVersionStrings; } public String getMainVersion() { return mainVersion; } public boolean matches(String version) { if (version.equals(mainVersion)) { return true; } else if (!alternativeVersionStrings.isEmpty()) {
return alternativeVersionStrings.contains(version); } else { return false; } } public boolean equals(Object obj) { if (!(obj instanceof ActivitiVersion)) { return false; } ActivitiVersion other = (ActivitiVersion) obj; boolean mainVersionEqual = mainVersion.equals(other.mainVersion); if (!mainVersionEqual) { return false; } else { if (alternativeVersionStrings != null) { return alternativeVersionStrings.equals(other.alternativeVersionStrings); } else { return other.alternativeVersionStrings == null; } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\ActivitiVersion.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } if (context.isProcessedDocument().isTrue()) { return ProcessPreconditionsResolution.reject(MSG_M_INVENTORY_UPDATE_QTYCOUNT_TO_QTYBOOK_ProcessedDoc);
} return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { final InventoryId inventoryId = InventoryId.ofRepoId(getRecord_ID()); inventoryService.setQtyCountToQtyBookForInventory(inventoryId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\process\M_Inventory_Update_QtyCount_to_QtyBook.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getC_DunningRun_ID())); } /** Set Note. @param Note Optional additional user defined information */ public void setNote (String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Note. @return Optional additional user defined information */ public String getNote () { return (String)get_Value(COLUMNNAME_Note); } /** 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 Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null) return Env.ZERO; return bd; } 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_DunningRunEntry.java
1
请完成以下Java代码
public class DLM_Partition_Inspect extends JavaProcess { @RunOutOfTrx // this process might run for some time and comes with its own trx management @Override protected String doIt() throws Exception { final IQueryBL queryBL = Services.get(IQueryBL.class); final ITrxItemProcessorExecutorService trxItemProcessorExecutorService = Services.get(ITrxItemProcessorExecutorService.class); final ICoordinatorService coordinatorService = Services.get(ICoordinatorService.class); final IDLMService dlmService = Services.get(IDLMService.class); final ICompositeQueryFilter<I_DLM_Partition> dateNextInspectionFilter = queryBL.createCompositeQueryFilter(I_DLM_Partition.class) .setJoinOr() .addEqualsFilter(I_DLM_Partition.COLUMN_DateNextInspection, null) .addCompareFilter(I_DLM_Partition.COLUMN_DateNextInspection, Operator.LESS_OR_EQUAL, SystemTime.asTimestamp()); // gh #1955: prevent an OutOfMemoryError final IQueryFilter<I_DLM_Partition> processFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final Iterator<I_DLM_Partition> partitionsToInspect = queryBL .createQueryBuilder(I_DLM_Partition.class, this) .addOnlyActiveRecordsFilter() .filter(dateNextInspectionFilter) .filter(processFilter) .orderBy().addColumn(I_DLM_Partition.COLUMN_DLM_Partition_ID).endOrderBy() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) .setOption(IQuery.OPTION_IteratorBufferSize, 500) .iterate(I_DLM_Partition.class); trxItemProcessorExecutorService.<I_DLM_Partition, Void> createExecutor()
.setContext(getCtx(), getTrxName()) .setProcessor(new TrxItemProcessorAdapter<I_DLM_Partition, Void>() { @Override public void process(final I_DLM_Partition item) throws Exception { final Partition partition = dlmService.loadPartition(item); final Partition validatedPartition = coordinatorService.inspectPartition(partition); addLog("Inspected partition={} with result={}", partition, validatedPartition); dlmService.storePartition(validatedPartition, false); } }) .setExceptionHandler(LoggableTrxItemExceptionHandler.instance) .process(partitionsToInspect); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\coordinator\process\DLM_Partition_Inspect.java
1
请完成以下Java代码
public final void export(@NonNull final OutputStream out) { final IExportDataSource dataSource = getDataSource(); Check.assumeNotNull(dataSource, "dataSource not null"); Check.assume(ExportStatus.NotStarted.equals(getExportStatus()), "ExportStatus shall be " + ExportStatus.NotStarted + " and not {}", getExportStatus()); IExportDataDestination dataDestination = null; try { // Init dataDestination // NOTE: make sure we are doing this as first thing, because if anything fails, we need to close this "destination" dataDestination = createDataDestination(out); // Init status error = null; setExportStatus(ExportStatus.Running); monitor.exportStarted(this); while (dataSource.hasNext()) { final List<Object> values = dataSource.next(); // for (int i = 1; i <= 3000; i++) // debugging // { appendRow(dataDestination, values); incrementExportedRowCount(); // } } } catch (Exception e) { final AdempiereException ex = new AdempiereException("Error while exporting line " + getExportedRowCount() + ": " + e.getLocalizedMessage(), e); error = ex; throw ex; } finally { close(dataSource); close(dataDestination); dataDestination = null; setExportStatus(ExportStatus.Finished); // Notify the monitor but discard all exceptions because we don't want to throw an "false" exception in finally block try { monitor.exportFinished(this); }
catch (Exception e) { logger.error("Error while invoking monitor(finish): " + e.getLocalizedMessage(), e); } } logger.info("Exported " + getExportedRowCount() + " rows"); } protected abstract void appendRow(IExportDataDestination dataDestination, List<Object> values) throws IOException; protected abstract IExportDataDestination createDataDestination(OutputStream out) throws IOException; /** * Close {@link Closeable} object. * * NOTE: if <code>closeableObj</code> is not implementing {@link Closeable} or is null, nothing will happen * * @param closeableObj */ private static final void close(Object closeableObj) { if (closeableObj instanceof Closeable) { final Closeable closeable = (Closeable)closeableObj; try { closeable.close(); } catch (IOException e) { e.printStackTrace(); // NOPMD by tsa on 3/17/13 1:30 PM } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\AbstractExporter.java
1
请完成以下Java代码
public String getValue(final Object operand) throws ExpressionEvaluationException { // // Case: we deal with a parameter (which we will need to get it from context/source) if (operand instanceof CtxName) { final CtxName ctxName = (CtxName)operand; if (ctxNameValues == null) { ctxNameValues = new LinkedHashMap<>(); } final String value = ctxNameValues.computeIfAbsent(ctxName, this::resolveCtxName); logger.trace("Evaluated context variable {}={}", ctxName, value); return value; } // // Case: we deal with a constant value else { String value = operand.toString(); // we can trim whitespaces in this case; if user really wants to have spaces at the beginning/ending of the // string, he/she shall quote it value = value.trim(); value = stripQuotes(value); return value; } } private String resolveCtxName(final CtxName ctxName) { final String value = ctxName.getValueAsString(params); final boolean valueNotFound = Env.isPropertyValueNull(ctxName.getName(), value); // Give it another try in case it's and ID (backward compatibility) // Handling of ID compare (null => 0) if (valueNotFound && Env.isNumericPropertyName(ctxName.getName())) { final String defaultValue = "0"; logger.trace("Evaluated {}={} (default value)", ctxName, defaultValue); return defaultValue; } if (valueNotFound) { if (onVariableNotFound == OnVariableNotFound.ReturnNoResult) { // i.e. !ignoreUnparsable logger.trace("Evaluated {}=<value not found>", ctxName); return VALUE_NotFound;
} else if (onVariableNotFound == OnVariableNotFound.Fail) { throw ExpressionEvaluationException.newWithPlainMessage("Parameter '" + ctxName.getName() + "' not found in context" + "\n Context: " + params + "\n Evaluator: " + this); } else { throw ExpressionEvaluationException.newWithPlainMessage("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound); } } return value; } @Nullable public Map<CtxName, String> getUsedParameters() { return ctxNameValues; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpressionEvaluator.java
1
请完成以下Java代码
public boolean isDefault() { return false; } @Override public String getTableName() { return I_M_InOut.Table_Name; } @Override public Optional<DocOutBoundRecipients> provideMailRecipient(@NonNull final DocOutboundLogMailRecipientRequest request) { final I_M_InOut inOutRecord = request.getRecordRef() .getModel(I_M_InOut.class); final boolean propagateToDocOutboundLog = orderEmailPropagationSysConfigRepository.isPropagateToDocOutboundLog( ClientAndOrgId.ofClientAndOrg(request.getClientId(), request.getOrgId())); final String inoutEmail = propagateToDocOutboundLog ? inOutRecord.getEMail() : null; final String locationEmail = inoutBL.getLocationEmail(InOutId.ofRepoId(inOutRecord.getM_InOut_ID())); if (inOutRecord.getAD_User_ID() > 0) { final DocOutBoundRecipient inOutUser = recipientRepository.getById(DocOutBoundRecipientId.ofRepoId(inOutRecord.getAD_User_ID())); if (Check.isNotBlank(inoutEmail)) { return DocOutBoundRecipients.optionalOfTo(inOutUser.withEmailAddress(inoutEmail)); } if (Check.isNotBlank(inOutUser.getEmailAddress())) { return DocOutBoundRecipients.optionalOfTo(inOutUser); } if (Check.isNotBlank(locationEmail)) { return DocOutBoundRecipients.optionalOfTo(inOutUser.withEmailAddress(locationEmail)); } } final BPartnerId bpartnerId = BPartnerId.ofRepoId(inOutRecord.getC_BPartner_ID()); final User billContact = bpartnerBL.retrieveContactOrNull( IBPartnerBL.RetrieveContactRequest .builder() .bpartnerId(bpartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, inOutRecord.getC_BPartner_Location_ID())) .contactType(IBPartnerBL.RetrieveContactRequest.ContactType.BILL_TO_DEFAULT) .build()); if (billContact != null && billContact.getId() != null) { final DocOutBoundRecipientId recipientId = DocOutBoundRecipientId.ofRepoId(billContact.getId().getRepoId()); final DocOutBoundRecipient docOutBoundRecipient = recipientRepository.getById(recipientId); if (Check.isNotBlank(inoutEmail)) { return DocOutBoundRecipients.optionalOfTo(docOutBoundRecipient.withEmailAddress(inoutEmail)); } if (Check.isNotBlank(locationEmail)) { return DocOutBoundRecipients.optionalOfTo(docOutBoundRecipient.withEmailAddress(locationEmail)); } if (Check.isNotBlank(docOutBoundRecipient.getEmailAddress())) { return DocOutBoundRecipients.optionalOfTo(docOutBoundRecipient); } } return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\mailrecipient\impl\InOutDocOutboundLogMailRecipientProvider.java
1
请完成以下Java代码
public int getElementId() { return resource.getElementId(); } @Override public boolean hasAccess(final Access access) { return accesses.contains(access); } public boolean hasReadAccess() { return accesses.contains(Access.READ); } public boolean hasWriteAccess() { return accesses.contains(Access.WRITE); } @Nullable public Boolean getReadWriteBoolean() { if (hasAccess(Access.WRITE)) { return Boolean.TRUE; } else if (hasAccess(Access.READ)) { return Boolean.FALSE; } else { return null; } } @Override public ElementPermission mergeWith(final Permission permissionFrom) { final ElementPermission elementPermissionFrom = PermissionInternalUtils.checkCompatibleAndCastToTarget(this, permissionFrom);
return withAccesses(ImmutableSet.<Access>builder() .addAll(this.accesses) .addAll(elementPermissionFrom.accesses) .build()); } private ElementPermission withAccesses(@NonNull final ImmutableSet<Access> accesses) { return !Objects.equals(this.accesses, accesses) ? new ElementPermission(this.resource, accesses) : this; } public ElementPermission withResource(@NonNull final ElementResource resource) { return !Objects.equals(this.resource, resource) ? new ElementPermission(resource, this.accesses) : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementPermission.java
1
请在Spring Boot框架中完成以下Java代码
public boolean matches(HttpServletRequest request) { try { return this.bearerTokenResolver.resolve(request) != null; } catch (OAuth2AuthenticationException ex) { return false; } } } static final class BearerTokenAuthenticationRequestMatcher implements RequestMatcher { private final AuthenticationConverter authenticationConverter; BearerTokenAuthenticationRequestMatcher() { this.authenticationConverter = new BearerTokenAuthenticationConverter(); } BearerTokenAuthenticationRequestMatcher(AuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter; } @Override public boolean matches(HttpServletRequest request) { try { return this.authenticationConverter.convert(request) != null; } catch (OAuth2AuthenticationException ex) { return false; } } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ResourceServerBeanDefinitionParser.java
2
请完成以下Java代码
public void setTaskCompleterVariableName(String taskCompleterVariableName) { this.taskCompleterVariableName = taskCompleterVariableName; } @Override public UserTask clone() { UserTask clone = new UserTask(); clone.setValues(this); return clone; } public void setValues(UserTask otherElement) { super.setValues(otherElement); setAssignee(otherElement.getAssignee()); setOwner(otherElement.getOwner()); setFormKey(otherElement.getFormKey()); setSameDeployment(otherElement.isSameDeployment()); setDueDate(otherElement.getDueDate()); setPriority(otherElement.getPriority()); setCategory(otherElement.getCategory()); setTaskIdVariableName(otherElement.getTaskIdVariableName()); setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName()); setExtensionId(otherElement.getExtensionId()); setSkipExpression(otherElement.getSkipExpression());
setValidateFormFields(otherElement.getValidateFormFields()); setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups())); setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers())); setCustomGroupIdentityLinks(otherElement.customGroupIdentityLinks); setCustomUserIdentityLinks(otherElement.customUserIdentityLinks); formProperties = new ArrayList<>(); if (otherElement.getFormProperties() != null && !otherElement.getFormProperties().isEmpty()) { for (FormProperty property : otherElement.getFormProperties()) { formProperties.add(property.clone()); } } taskListeners = new ArrayList<>(); if (otherElement.getTaskListeners() != null && !otherElement.getTaskListeners().isEmpty()) { for (FlowableListener listener : otherElement.getTaskListeners()) { taskListeners.add(listener.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\UserTask.java
1
请完成以下Java代码
public void setRemote_Addr (String Remote_Addr) { set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr); } /** Get Remote Addr. @return Remote Address */ public String getRemote_Addr () { return (String)get_Value(COLUMNNAME_Remote_Addr); } /** Set Remote Host. @param Remote_Host Remote host Info */ public void setRemote_Host (String Remote_Host) { set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host); } /** Get Remote Host. @return Remote host Info */ public String getRemote_Host () { return (String)get_Value(COLUMNNAME_Remote_Host); } /** Set Serial No. @param SerNo Product Serial Number */ public void setSerNo (String SerNo) { set_ValueNoCheck (COLUMNNAME_SerNo, SerNo); } /** Get Serial No. @return Product Serial Number */ public String getSerNo () { return (String)get_Value(COLUMNNAME_SerNo); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org
*/ public void setURL (String URL) { set_ValueNoCheck (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } /** Set Version No. @param VersionNo Version Number */ public void setVersionNo (String VersionNo) { set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo); } /** Get Version No. @return Version Number */ public String getVersionNo () { return (String)get_Value(COLUMNNAME_VersionNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Delivery.java
1
请完成以下Java代码
private static URI extractUriOrNull(final I_AD_AttachmentEntry entryRecord) { final String url = entryRecord.getURL(); if (Check.isEmpty(url, true)) { return null; } try { return new URI(url); } catch (final URISyntaxException ex) { throw new AdempiereException("Invalid URL: " + url, ex) .setParameter("entryRecord", entryRecord); } } public void syncToRecord(
@NonNull final AttachmentEntry attachmentEntry, @NonNull final I_AD_AttachmentEntry attachmentEntryRecord) { attachmentEntryRecord.setFileName(attachmentEntry.getFilename()); attachmentEntryRecord.setType(attachmentEntry.getType().getCode()); attachmentEntryRecord.setFileName(attachmentEntry.getFilename()); if (attachmentEntry.getUrl() != null) { attachmentEntryRecord.setURL(attachmentEntry.getUrl().toString()); } else { attachmentEntryRecord.setURL(null); } attachmentEntryRecord.setTags(attachmentEntry.getTags().getTagsAsString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryFactory.java
1
请在Spring Boot框架中完成以下Java代码
public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setMaxPoolSize(5); taskExecutor.setCorePoolSize(5); taskExecutor.setQueueCapacity(5); taskExecutor.afterPropertiesSet(); return taskExecutor; } @Bean(name = "jobRepository") public JobRepository getJobRepository() throws Exception { JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); factory.setDataSource(dataSource()); factory.setTransactionManager(getTransactionManager()); // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); return factory.getObject(); } @Bean(name = "dataSource") public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2) .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql") .build(); } @Bean(name = "transactionManager") public PlatformTransactionManager getTransactionManager() { return new ResourcelessTransactionManager(); } @Bean(name = "jobLauncher") public JobLauncher getJobLauncher() throws Exception { TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher(); // SimpleJobLauncher's methods Throws Generic Exception, // it would have been better to have a specific one jobLauncher.setJobRepository(getJobRepository()); jobLauncher.afterPropertiesSet(); return jobLauncher; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\partitioner\SpringBatchPartitionConfig.java
2
请在Spring Boot框架中完成以下Java代码
public class ScreenshotService { private final ScreenshotRepository screenshotRepository; public ScreenshotService(ScreenshotRepository screenshotRepository) { this.screenshotRepository = screenshotRepository; } public void saveScreenshotInUTC() { TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); Screenshot screenshot = new Screenshot(); screenshot.setName("Screenshot-1"); screenshot.setCreateOn(new Timestamp( ZonedDateTime.of(2018, 3, 30, 10, 15, 55, 0,
ZoneId.of("UTC") ).toInstant().toEpochMilli() )); System.out.println("Timestamp epoch milliseconds before insert: " + screenshot.getCreateOn().getTime()); screenshotRepository.save(screenshot); } public void displayScreenshotInUTC() { Screenshot fetchScreenshot = screenshotRepository.findByName("Screenshot-1"); System.out.println("Timestamp epoch milliseconds after fetching: " + fetchScreenshot.getCreateOn().getTime()); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootUTCTimezone\src\main\java\com\app\service\ScreenshotService.java
2
请完成以下Java代码
private int createOrUpdateSubscriptionProgress() { final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); try (final IAutoCloseable createMissingScheds = shipmentScheduleBL.postponeMissingSchedsCreationUntilClose()) { return createOrUpdateSubscriptionProgress0(); } } private int createOrUpdateSubscriptionProgress0() { int errorCount = 0; int count = 0; final Iterator<I_C_Flatrate_Term> termsToEvaluate = retrieveTermsToEvaluate(); while (termsToEvaluate.hasNext()) { final I_C_Flatrate_Term term = termsToEvaluate.next(); if (invokeEvalCurrentSPs(term)) { count++; } else { errorCount++; } } addLog(errorCount + " errors on updating subscriptions"); return count; } private Iterator<I_C_Flatrate_Term> retrieveTermsToEvaluate() { final Iterator<I_C_Flatrate_Term> termsToEval = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Flatrate_Term.class) .addOnlyContextClient(getCtx()) .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Type_Conditions, X_C_Flatrate_Term.TYPE_CONDITIONS_Subscription) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, X_C_Flatrate_Term.CONTRACTSTATUS_DeliveryPause, X_C_Flatrate_Term.CONTRACTSTATUS_Running, X_C_Flatrate_Term.CONTRACTSTATUS_Waiting, X_C_Flatrate_Term.CONTRACTSTATUS_EndingContract) .addInArrayFilter(I_C_Flatrate_Term.COLUMNNAME_DocStatus, IDocument.STATUS_Closed, IDocument.STATUS_Completed) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate).addColumn(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID).endOrderBy() .create() .iterate(I_C_Flatrate_Term.class); return termsToEval; } private boolean invokeEvalCurrentSPs(final I_C_Flatrate_Term flatrateTerm) { final Mutable<Boolean> success = new Mutable<>(false); Services.get(ITrxManager.class).runInNewTrx(() -> { try { subscriptionBL.evalCurrentSPs(flatrateTerm, currentDate); success.setValue(true); } catch (final AdempiereException e) { addLog("Error updating " + flatrateTerm + ": " + e.getMessage()); } }); return success.getValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\process\C_SubscriptionProgress_Evaluate.java
1
请在Spring Boot框架中完成以下Java代码
GeodeCacheServersHealthIndicator cacheServersHealthIndicator(GemFireCache gemfireCache) { return new GeodeCacheServersHealthIndicator(gemfireCache); } @Bean("GeodeGatewayReceiversHealthIndicator") GeodeGatewayReceiversHealthIndicator gatewayReceiversHealthIndicator(GemFireCache gemfireCache) { return new GeodeGatewayReceiversHealthIndicator(gemfireCache); } @Bean("GeodeGatewaySendersHealthIndicator") GeodeGatewaySendersHealthIndicator gatewaySendersHealthIndicator(GemFireCache gemfireCache) { return new GeodeGatewaySendersHealthIndicator(gemfireCache); } @Bean BeanPostProcessor cacheServerLoadProbeWrappingBeanPostProcessor() { return new BeanPostProcessor() { @Nullable @Override @SuppressWarnings("all") public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServerFactoryBean) { CacheServerFactoryBean cacheServerFactoryBean = (CacheServerFactoryBean) bean; ServerLoadProbe serverLoadProbe = ObjectUtils.<ServerLoadProbe>get(bean, "serverLoadProbe"); if (serverLoadProbe != null) { cacheServerFactoryBean.setServerLoadProbe(wrap(serverLoadProbe)); } } return bean; } @Nullable @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof CacheServer) { CacheServer cacheServer = (CacheServer) bean; Optional.ofNullable(cacheServer.getLoadProbe()) .filter(it -> !(it instanceof ActuatorServerLoadProbeWrapper)) .filter(it -> cacheServer.getLoadPollInterval() > 0)
.filter(it -> !cacheServer.isRunning()) .ifPresent(serverLoadProbe -> cacheServer.setLoadProbe(new ActuatorServerLoadProbeWrapper(serverLoadProbe))); } return bean; } private ServerLoadProbe wrap(ServerLoadProbe serverLoadProbe) { return new ActuatorServerLoadProbeWrapper(serverLoadProbe); } }; } public static final class PeerCacheCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Cache peerCache = CacheUtils.getCache(); ClientCache clientCache = CacheUtils.getClientCache(); return peerCache != null || clientCache == null; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator-autoconfigure\src\main\java\org\springframework\geode\boot\actuate\autoconfigure\config\PeerCacheHealthIndicatorConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteByScopeIdAndScopeType(String scopeId, String scopeType) { Map<String, Object> params = new HashMap<>(3); params.put("scopeId", scopeId); params.put("scopeType", scopeType); bulkDelete("deleteVariablesByScopeIdAndScopeType", variableInstanceByScopeIdAndScopeTypeMatcher, params); } @Override public void deleteByScopeIdAndScopeTypes(String scopeId, Collection<String> scopeTypes) { if (scopeTypes.size() == 1) { deleteByScopeIdAndScopeType(scopeId, scopeTypes.iterator().next()); return; } Map<String, Object> params = new HashMap<>(3); params.put("scopeId", scopeId); params.put("scopeTypes", scopeTypes); bulkDelete("deleteVariablesByScopeIdAndScopeTypes", variableInstanceByScopeIdAndScopeTypesMatcher, params);
} @Override public void deleteBySubScopeIdAndScopeTypes(String subScopeId, Collection<String> scopeTypes) { Map<String, Object> params = new HashMap<>(3); params.put("subScopeId", subScopeId); params.put("scopeTypes", scopeTypes); bulkDelete("deleteVariablesBySubScopeIdAndScopeTypes", variableInstanceBySubScopeIdAndScopeTypesMatcher, params); } @Override protected IdGenerator getIdGenerator() { return variableServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\data\impl\MybatisVariableInstanceDataManager.java
2
请完成以下Java代码
public <T> T get_ValueAsObject(final String variableName) { if (excludeVariableName.equals(variableName)) { return null; } return parent.get_ValueAsObject(variableName); } @Nullable @Override public String get_ValueAsString(final String variableName) { if (excludeVariableName.equals(variableName)) { return null; } return parent.get_ValueAsString(variableName); } @Override public Optional<Object> get_ValueIfExists(final @NonNull String variableName, final @NonNull Class<?> targetType) { if (excludeVariableName.equals(variableName)) { return Optional.empty(); } return parent.get_ValueIfExists(variableName, targetType); } } @ToString private static class RangeAwareParamsAsEvaluatee implements Evaluatee2 { private final IRangeAwareParams params; private RangeAwareParamsAsEvaluatee(@NonNull final IRangeAwareParams params) { this.params = params; } @Override public boolean has_Variable(final String variableName) { return params.hasParameter(variableName); } @SuppressWarnings("unchecked") @Override public <T> T get_ValueAsObject(final String variableName) { return (T)params.getParameterAsObject(variableName); } @Override public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue) { final BigDecimal value = params.getParameterAsBigDecimal(variableName); return value != null ? value : defaultValue; }
@Override public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED) { return params.getParameterAsBool(variableName); } @Override public Date get_ValueAsDate(final String variableName, final Date defaultValue) { final Timestamp value = params.getParameterAsTimestamp(variableName); return value != null ? value : defaultValue; } @Override public Integer get_ValueAsInt(final String variableName, final Integer defaultValue) { final int defaultValueInt = defaultValue != null ? defaultValue : 0; return params.getParameterAsInt(variableName, defaultValueInt); } @Override public String get_ValueAsString(final String variableName) { return params.getParameterAsString(variableName); } @Override public String get_ValueOldAsString(final String variableName) { return get_ValueAsString(variableName); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java
1
请在Spring Boot框架中完成以下Java代码
public DeploymentResourceDto getDeploymentResource(String resourceId) { List<DeploymentResourceDto> deploymentResources = getDeploymentResources(); for (DeploymentResourceDto deploymentResource : deploymentResources) { if (deploymentResource.getId().equals(resourceId)) { return deploymentResource; } } throw new InvalidRequestException(Status.NOT_FOUND, "Deployment resource with resource id '" + resourceId + "' for deployment id '" + deploymentId + "' does not exist."); } public Response getDeploymentResourceData(String resourceId) { RepositoryService repositoryService = engine.getRepositoryService(); InputStream resourceAsStream = repositoryService.getResourceAsStreamById(deploymentId, resourceId); if (resourceAsStream != null) { DeploymentResourceDto resource = getDeploymentResource(resourceId); String name = resource.getName(); String filename = null; String mediaType = null; if (name != null) { name = name.replace("\\", "/"); String[] filenameParts = name.split("/"); if (filenameParts.length > 0) { int idx = filenameParts.length-1; filename = filenameParts[idx]; } String[] extensionParts = name.split("\\."); if (extensionParts.length > 0) { int idx = extensionParts.length-1; String extension = extensionParts[idx]; if (extension != null) { mediaType = MEDIA_TYPE_MAPPING.get(extension); }
} } if (filename == null) { filename = "data"; } if (mediaType == null) { mediaType = MediaType.APPLICATION_OCTET_STREAM; } return Response .ok(resourceAsStream, mediaType) .header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(filename)) .build(); } else { throw new InvalidRequestException(Status.NOT_FOUND, "Deployment resource '" + resourceId + "' for deployment id '" + deploymentId + "' does not exist."); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\DeploymentResourcesResourceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Long getRoleId() { return roleId; } /** * 角色ID * * @return */ public void setRoleId(Long roleId) { this.roleId = roleId; } /** * 操作员ID * * @return */ public Long getOperatorId() {
return operatorId; } /** * 操作员ID * * @return */ public void setOperatorId(Long operatorId) { this.operatorId = operatorId; } public PmsOperatorRole() { } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperatorRole.java
2
请完成以下Java代码
public class DBRes_sv extends ListResourceBundle { /** Data */ static final Object[][] contents = new String[][] { { "CConnectionDialog", "Anslutning till Server" }, { "Name", "Namn" }, { "AppsHost", "Applikationsserver" }, { "AppsPort", "Serverport" }, { "TestApps", "Testa anslutning" }, { "DBHost", "Databasserver" }, { "DBPort", "Databasport" }, { "DBName", "Databasnamn" }, { "DBUidPwd", "Anv\u00e4ndarnamn / l\u00f6senord" }, { "ViaFirewall", "Via brandv\u00e4gg" }, { "FWHost", "Adress brandv\u00e4gg" }, { "FWPort", "Port p\u00e5 brandv\u00e4gg" }, { "TestConnection", "Testa databasanslutning" }, { "Type", "Databastyp" }, { "BequeathConnection", "Efterl\u00e4mna anslutning" },
{ "Overwrite", "Skriv \u00f6ver" }, { "ConnectionProfile", "Anslutningstyp" }, { "LAN", "LAN" }, { "TerminalServer", "Terminal Server" }, { "VPN", "VPN" }, { "WAN", "WAN" }, { "ConnectionError", "Anslutningsfel" }, { "ServerNotActive", "Server ej aktiv" } }; /** * Get Contsnts * @return contents */ public Object[][] getContents() { return contents; } // getContent } // Res
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_sv.java
1
请完成以下Java代码
public class SpeedTokenizer { /** * 预置分词器 */ public static final Segment SEGMENT = new DoubleArrayTrieSegment(); public static List<Term> segment(String text) { return SEGMENT.seg(text.toCharArray()); } /** * 分词 * @param text 文本 * @return 分词结果 */ public static List<Term> segment(char[] text) { return SEGMENT.seg(text); } /** * 切分为句子形式 * @param text 文本 * @return 句子列表 */ public static List<List<Term>> seg2sentence(String text)
{ return SEGMENT.seg2sentence(text); } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) { return SEGMENT.seg2sentence(text, shortest); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\SpeedTokenizer.java
1
请完成以下Java代码
public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } /** Set MSV3_VerfuegbarkeitsanfrageEinzelne. @param MSV3_VerfuegbarkeitsanfrageEinzelne_ID MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public void setMSV3_VerfuegbarkeitsanfrageEinzelne_ID (int MSV3_VerfuegbarkeitsanfrageEinzelne_ID) {
if (MSV3_VerfuegbarkeitsanfrageEinzelne_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID, Integer.valueOf(MSV3_VerfuegbarkeitsanfrageEinzelne_ID)); } /** Get MSV3_VerfuegbarkeitsanfrageEinzelne. @return MSV3_VerfuegbarkeitsanfrageEinzelne */ @Override public int getMSV3_VerfuegbarkeitsanfrageEinzelne_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsanfrageEinzelne_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitsanfrageEinzelne.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Server Process. @param IsServerProcess Run this Process on Server only */ public void setIsServerProcess (boolean IsServerProcess) { set_Value (COLUMNNAME_IsServerProcess, Boolean.valueOf(IsServerProcess)); } /** Get Server Process. @return Run this Process on Server only */ public boolean isServerProcess () { Object oo = get_Value(COLUMNNAME_IsServerProcess); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name);
} /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set OS Command. @param OS_Command Operating System Command */ public void setOS_Command (String OS_Command) { set_Value (COLUMNNAME_OS_Command, OS_Command); } /** Get OS Command. @return Operating System Command */ public String getOS_Command () { return (String)get_Value(COLUMNNAME_OS_Command); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Task.java
1
请在Spring Boot框架中完成以下Java代码
public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { Assert.notNull(relayStateResolver, "relayStateResolver cannot be null"); this.delegate.setRelayStateResolver(relayStateResolver); } public static final class AuthnRequestContext { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final AuthnRequest authnRequest; public AuthnRequestContext(HttpServletRequest request, RelyingPartyRegistration registration, AuthnRequest authnRequest) { this.request = request; this.registration = registration; this.authnRequest = authnRequest; }
public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public AuthnRequest getAuthnRequest() { return this.authnRequest; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\OpenSaml5AuthenticationRequestResolver.java
2
请完成以下Java代码
private Mono<Void> logout(WebFilterExchange webFilterExchange, Authentication authentication) { logger.debug(LogMessage.format("Logging out user '%s' and transferring to logout destination", authentication)); return this.logoutHandler.logout(webFilterExchange, authentication) .then(this.logoutSuccessHandler.onLogoutSuccess(webFilterExchange, authentication)) .contextWrite(ReactiveSecurityContextHolder.clearContext()); } /** * Sets the {@link ServerLogoutSuccessHandler}. The default is * {@link RedirectServerLogoutSuccessHandler}. * @param logoutSuccessHandler the handler to use */ public void setLogoutSuccessHandler(ServerLogoutSuccessHandler logoutSuccessHandler) { Assert.notNull(logoutSuccessHandler, "logoutSuccessHandler cannot be null"); this.logoutSuccessHandler = logoutSuccessHandler; }
/** * Sets the {@link ServerLogoutHandler}. The default is * {@link SecurityContextServerLogoutHandler}. * @param logoutHandler The handler to use */ public void setLogoutHandler(ServerLogoutHandler logoutHandler) { Assert.notNull(logoutHandler, "logoutHandler must not be null"); this.logoutHandler = logoutHandler; } public void setRequiresLogoutMatcher(ServerWebExchangeMatcher requiresLogoutMatcher) { Assert.notNull(requiresLogoutMatcher, "requiresLogoutMatcher must not be null"); this.requiresLogout = requiresLogoutMatcher; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\authentication\logout\LogoutWebFilter.java
1
请完成以下Java代码
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; }
public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "Name: " + this.name + "\nEmail: " + this.email; } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\User.java
1
请完成以下Java代码
public class DeleteHistoricDecisionInstancesJobHandler extends AbstractBatchJobHandler<BatchConfiguration> { public static final BatchJobDeclaration JOB_DECLARATION = new BatchJobDeclaration(Batch.TYPE_HISTORIC_DECISION_INSTANCE_DELETION); @Override public String getType() { return Batch.TYPE_HISTORIC_DECISION_INSTANCE_DELETION; } protected DeleteHistoricDecisionInstanceBatchConfigurationJsonConverter getJsonConverterInstance() { return DeleteHistoricDecisionInstanceBatchConfigurationJsonConverter.INSTANCE; } @Override public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() { return JOB_DECLARATION; }
@Override protected BatchConfiguration createJobConfiguration(BatchConfiguration configuration, List<String> decisionIdsForJob) { return new BatchConfiguration(decisionIdsForJob); } @Override public void executeHandler(BatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { commandContext.executeWithOperationLogPrevented( new DeleteHistoricDecisionInstancesBulkCmd(batchConfiguration.getIds())); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\batch\DeleteHistoricDecisionInstancesJobHandler.java
1
请完成以下Java代码
protected void doRelease(UUID scriptId) { String scriptHash = scriptIdToHash.remove(scriptId); if (scriptHash != null) { lock.lock(); try { if (!scriptIdToHash.containsValue(scriptHash)) { scriptMap.remove(scriptHash); compiledScriptsCache.invalidate(scriptHash); } } finally { lock.unlock(); } } } private static Serializable compileScript(String scriptBody) throws CompileException { return MVEL.compileExpression(scriptBody, new ParserContext()); } @SuppressWarnings("UnstableApiUsage")
protected String hash(String scriptBody, String[] argNames) { Hasher hasher = Hashing.murmur3_128().newHasher(); hasher.putUnencodedChars(scriptBody); for (String argName : argNames) { hasher.putString(argName, StandardCharsets.UTF_8); } return hasher.hash().toString(); } @Override protected long getMaxEvalRequestsTimeout() { return maxInvokeRequestsTimeout * 2; } @Override protected StatsType getStatsType() { return StatsType.TBEL_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\tbel\DefaultTbelInvokeService.java
1
请完成以下Java代码
public static Set<String> combineNER(String[] nerArray, NERTagSet tagSet) { Set<String> result = new LinkedHashSet<String>(); int begin = 0; String prePos = NERTagSet.posOf(nerArray[0]); for (int i = 1; i < nerArray.length; i++) { if (nerArray[i].charAt(0) == tagSet.B_TAG_CHAR || nerArray[i].charAt(0) == tagSet.S_TAG_CHAR || nerArray[i].charAt(0) == tagSet.O_TAG_CHAR) { if (i - begin > 1) result.add(String.format("%d\t%d\t%s", begin, i, prePos)); begin = i; } prePos = NERTagSet.posOf(nerArray[i]); } if (nerArray.length - 1 - begin >= 1) { result.add(String.format("%d\t%d\t%s", begin, nerArray.length, prePos)); } return result; } public static String[][] reshapeNER(List<String[]> ner) { String[] wordArray = new String[ner.size()]; String[] posArray = new String[ner.size()]; String[] nerArray = new String[ner.size()]; reshapeNER(ner, wordArray, posArray, nerArray); return new String[][]{wordArray, posArray, nerArray}; }
public static void reshapeNER(List<String[]> collector, String[] wordArray, String[] posArray, String[] tagArray) { int i = 0; for (String[] tuple : collector) { wordArray[i] = tuple[0]; posArray[i] = tuple[1]; tagArray[i] = tuple[2]; ++i; } } public static void printNERScore(Map<String, double[]> scores) { System.out.printf("%4s\t%6s\t%6s\t%6s\n", "NER", "P", "R", "F1"); for (Map.Entry<String, double[]> entry : scores.entrySet()) { String type = entry.getKey(); double[] s = entry.getValue(); System.out.printf("%4s\t%6.2f\t%6.2f\t%6.2f\n", type, s[0], s[1], s[2]); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\utility\Utility.java
1
请完成以下Java代码
public String getSize() { return size; } public void setSize(String size) { this.size = size; } public int getSpeedKmPerS() { return speedKmPerS; } public void setSpeedKmPerS(int speedKmPerS) { this.speedKmPerS = speedKmPerS; } } class Coordinates { @JsonProperty("latitude") private double latitude; @JsonProperty("longitude") private double longitude;
public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
repos\tutorials-master\json-modules\json-operations\src\main\java\com\baeldung\sorting\SolarEvent.java
1
请在Spring Boot框架中完成以下Java代码
public Foo findById(@PathVariable final long id) { final Foo foo = myfoos.get(id); if (foo == null) { throw new ResourceNotFoundException(); } return foo; } // API - write @RequestMapping(method = RequestMethod.PUT, value = "/{id}") @ResponseStatus(HttpStatus.OK) @ResponseBody public Foo updateFoo(@PathVariable("id") final long id, @RequestBody final Foo foo) { myfoos.put(id, foo); return foo; } @RequestMapping(method = RequestMethod.PATCH, value = "/{id}") @ResponseStatus(HttpStatus.OK) public void updateFoo2(@PathVariable("id") final long id, @RequestBody final Foo foo) {
myfoos.put(id, foo); } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo createFoo(@RequestBody final Foo foo, HttpServletResponse response) { myfoos.put(foo.getId(), foo); response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentRequest() .path("/" + foo.getId()) .toUriString()); return foo; } @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") @ResponseStatus(HttpStatus.OK) public void deleteById(@PathVariable final long id) { myfoos.remove(id); } }
repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\MyFooController.java
2
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .addValue(classname) .toString(); } public Class<T> getReferencedClass() { // Get if not expired { final WeakReference<Class<T>> weakRef = clazzRef.get(); final Class<T> clazz = weakRef != null ? weakRef.get() : null; if (clazz != null) { return clazz; }
} // Load the class try { @SuppressWarnings("unchecked") final Class<T> clazzNew = (Class<T>)Thread.currentThread().getContextClassLoader().loadClass(classname); clazzRef.set(new WeakReference<>(clazzNew)); return clazzNew; } catch (final ClassNotFoundException ex) { throw new IllegalStateException("Cannot load expired class: " + classname, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\ClassReference.java
1
请完成以下Java代码
public String[] tag(String... words) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.tag(words); } @Override public String[] tag(List<String> wordList) { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.tag(wordList); }
@Override public NERTagSet getNERTagSet() { LexicalAnalyzer analyzer = getAnalyzer(); if (analyzer == null) throw new IllegalStateException("流水线中没有LexicalAnalyzerPipe"); return analyzer.getNERTagSet(); } @Override public Sentence analyze(String sentence) { return new Sentence(flow(sentence)); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\LexicalAnalyzerPipeline.java
1
请完成以下Java代码
public List<I_C_Queue_WorkPackage> retrieveWorkPackages(@NonNull final I_C_Async_Batch asyncBatch, @Nullable final String trxName) { return retrieveWorkPackages(asyncBatch, trxName, null); } @Override public List<I_C_Queue_WorkPackage_Notified> retrieveWorkPackagesNotified(final I_C_Async_Batch asyncBatch, final boolean notified) { final Properties ctx = InterfaceWrapperHelper.getCtx(asyncBatch); final String trxName = InterfaceWrapperHelper.getTrxName(asyncBatch); final List<Object> params = new ArrayList<Object>(); final StringBuffer whereClause = new StringBuffer(); whereClause.append(I_C_Queue_WorkPackage_Notified.COLUMNNAME_C_Async_Batch_ID + " = ? "); params.add(asyncBatch.getC_Async_Batch_ID()); whereClause.append(" AND " + I_C_Queue_WorkPackage_Notified.COLUMNNAME_IsNotified + " = ? "); params.add(notified); return new Query(ctx, I_C_Queue_WorkPackage_Notified.Table_Name, whereClause.toString(), trxName) .setOnlyActiveRecords(true) .setParameters(params) .setOrderBy(I_C_Queue_WorkPackage_Notified.COLUMNNAME_BachWorkpackageSeqNo) .list(I_C_Queue_WorkPackage_Notified.class); }
@Override public I_C_Queue_WorkPackage_Notified fetchWorkPackagesNotified(final I_C_Queue_WorkPackage workPackage) { final Properties ctx = InterfaceWrapperHelper.getCtx(workPackage); final String trxName = InterfaceWrapperHelper.getTrxName(workPackage); final List<Object> params = new ArrayList<Object>(); final StringBuffer whereClause = new StringBuffer(); whereClause.append(I_C_Queue_WorkPackage_Notified.COLUMNNAME_C_Queue_WorkPackage_ID + " = ? "); params.add(workPackage.getC_Queue_WorkPackage_ID()); return new Query(ctx, I_C_Queue_WorkPackage_Notified.Table_Name, whereClause.toString(), trxName) .setOnlyActiveRecords(true) .setParameters(params) .firstOnly(I_C_Queue_WorkPackage_Notified.class); } @Override public void setPInstance_IDAndSave(@NonNull final I_C_Async_Batch asyncBatch, @NonNull final PInstanceId pInstanceId) { asyncBatch.setAD_PInstance_ID(pInstanceId.getRepoId()); InterfaceWrapperHelper.save(asyncBatch); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchDAO.java
1
请完成以下Java代码
protected String getSelectSQL(String search, int caretPosition, List<Object> params) { if (caretPosition > 0 && caretPosition < search.length()) { search = new StringBuffer(search).insert(caretPosition, "%").toString(); } String searchSQL = StringUtils.stripDiacritics(search.toUpperCase()); if (!searchSQL.endsWith("%")) { searchSQL += "%"; } final DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); final String sql_strRep = "sp.SponsorNo || ' - VP - ' || bp.name"; final String sql = "SELECT sp.SponsorNo, bp.Name, sp.C_Sponsor_ID, " + sql_strRep + " as string_rep" + " FROM C_Sponsor_Salesrep ssr" + " LEFT JOIN C_Sponsor sp ON (ssr.C_Sponsor_ID = sp.C_Sponsor_ID)" + " LEFT JOIN C_BPartner bp ON (ssr.C_BPartner_ID = bp.C_BPartner_ID)" + " WHERE (sp.SponsorNo LIKE ?" + " OR upper(bp.Name) LIKE ?)" + " AND '" + df.format(Env.getContextAsDate(Env.getCtx(), "#Date")) + "' BETWEEN ssr.Validfrom AND ssr.Validto" + " ORDER BY sp.SponsorNo" ; params.add(searchSQL); // SponsorNo params.add(searchSQL); // Name // return sql; } @Override protected Object fetchUserObject(ResultSet rs) throws SQLException {
int sponsorID = rs.getInt("C_Sponsor_ID"); String sponsorNo = rs.getString("SponsorNo"); String name = rs.getString("Name"); SponsorNoObject o = new SponsorNoObject(sponsorID, sponsorNo, name); o.setStringRepresentation(rs.getString("string_rep")); return o; } @Override protected boolean isMatching(Object userObject, String search) { // return super.isMatching(userObject, search); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\SponsorNoAutoCompleter.java
1
请完成以下Java代码
public class C_Flatrate_Term_Change extends C_Flatrate_Term_Change_Base { private final IQueryBL queryBL = Services.get(IQueryBL.class); @Override @RunOutOfTrx protected void prepare() { final IQueryBuilder<I_C_Flatrate_Term> queryBuilder = createQueryBuilder(); final int selectionCount = createSelection(queryBuilder, getPinstanceId()); if (selectionCount <= 0) { throw new AdempiereException("@NoSelection@"); } } @Override protected Iterable<I_C_Flatrate_Term> getFlatrateTermsToChange() { return retrieveSelection(getPinstanceId()); } private IQueryBuilder<I_C_Flatrate_Term> createQueryBuilder() { final IQueryFilter<I_C_Flatrate_Term> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_C_Flatrate_Term.class)
.filter(userSelectionFilter) .addOnlyActiveRecordsFilter() .addOnlyContextClient(); } private Iterable<I_C_Flatrate_Term> retrieveSelection(final PInstanceId adPInstanceId) { return () -> queryBL .createQueryBuilder(I_C_Flatrate_Term.class) .setOnlySelection(adPInstanceId) .orderBy() .addColumn(I_C_Flatrate_Term.COLUMN_C_Flatrate_Term_ID) .endOrderBy() .create() .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false) .setOption(IQuery.OPTION_IteratorBufferSize, 50) .iterate(I_C_Flatrate_Term.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Flatrate_Term_Change.java
1
请在Spring Boot框架中完成以下Java代码
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { /** * Configure security to allow access to the /me endpoint only if the OAuth * authorization returns "read" scope.<br> * <br> * * If you look at * {@link OAuthConfiguration#configure(org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer)} * to check that by default the authorization server allows "read" scope * only. */ @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http .requestMatchers().antMatchers("/me") .and() .authorizeRequests() .antMatchers("/me").access("#oauth2.hasScope('read')"); // @formatter:on } /**
* Id of the resource that you are letting the client have access to. * Supposing you have another api ("say api2"), then you can customize the * access within resource server to define what api is for what resource id. * <br> * <br> * * So suppose you have 2 APIs, then you can define 2 resource servers. * <ol> * <li>Client 1 has been configured for access to resourceid1, so he can * only access "api1" if the resource server configures the resourceid to * "api1".</li> * <li>Client 1 can't access resource server 2 since it has configured the * resource id to "api2" * </li> * </ol> * */ @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("apis"); } }
repos\spring-boot-microservices-master\auth-server\src\main\java\com\rohitghatol\microservice\auth\config\ResourceServerConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class ScheduledAnnotationExample { @Scheduled(fixedDelay = 1000) public void scheduleFixedDelayTask() { } @Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}") public void scheduleFixedDelayTaskUsingExpression() { } @Scheduled(fixedDelay = 1000, initialDelay = 2000) public void scheduleFixedDelayWithInitialDelayTask() { } @Scheduled(fixedRate = 1000) public void scheduleFixedRateTask() { } @Scheduled(fixedRateString = "${fixedRate.in.milliseconds}") public void scheduleFixedRateTaskUsingExpression() { } @Scheduled(fixedDelay = 1000, initialDelay = 1000) public void scheduleFixedRateWithInitialDelayTask() {
long now = System.currentTimeMillis() / 1000; System.out.println("Fixed rate task with one second initial delay - " + now); } /** * Scheduled task is executed at 10:15 AM on the 15th day of every month */ @Scheduled(cron = "0 15 10 15 * ?") public void scheduleTaskUsingCronExpression() { long now = System.currentTimeMillis() / 1000; System.out.println("schedule tasks using cron jobs - " + now); } @Scheduled(cron = "${cron.expression}") public void scheduleTaskUsingExternalizedCronExpression() { } }
repos\tutorials-master\spring-scheduling\src\main\java\com\baeldung\scheduling\ScheduledAnnotationExample.java
2
请完成以下Java代码
public class UncheckedConversion { public static List getRawList() { List result = new ArrayList(); result.add("I am the 1st String."); result.add("I am the 2nd String."); result.add("I am the 3rd String."); return result; } public static List getRawListWithMixedTypes() { List result = new ArrayList(); result.add("I am the 1st String."); result.add("I am the 2nd String."); result.add("I am the 3rd String."); result.add(new Date()); return result; } public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> rawCollection) {
List<T> result = new ArrayList<>(rawCollection.size()); for (Object o : rawCollection) { try { result.add(clazz.cast(o)); } catch (ClassCastException e) { // log the exception or other error handling } } return result; } public static <T> List<T> castList2(Class<? extends T> clazz, Collection<?> rawCollection) throws ClassCastException { List<T> result = new ArrayList<>(rawCollection.size()); for (Object o : rawCollection) { result.add(clazz.cast(o)); } return result; } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-generics-2\src\main\java\com\baeldung\uncheckedconversion\UncheckedConversion.java
1
请完成以下Java代码
public class ChannelProcessingFilter extends GenericFilterBean { @SuppressWarnings("NullAway.Init") private ChannelDecisionManager channelDecisionManager; @SuppressWarnings("NullAway.Init") private FilterInvocationSecurityMetadataSource securityMetadataSource; @Override public void afterPropertiesSet() { Assert.notNull(this.securityMetadataSource, "securityMetadataSource must be specified"); Assert.notNull(this.channelDecisionManager, "channelDecisionManager must be specified"); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAllConfigAttributes(); if (attributes == null) { this.logger.warn("Could not validate configuration attributes as the " + "FilterInvocationSecurityMetadataSource did not return any attributes"); return; } Set<ConfigAttribute> unsupportedAttributes = getUnsupportedAttributes(attributes); Assert.isTrue(unsupportedAttributes.isEmpty(), () -> "Unsupported configuration attributes: " + unsupportedAttributes); this.logger.info("Validated configuration attributes"); } private Set<ConfigAttribute> getUnsupportedAttributes(Collection<ConfigAttribute> attrDefs) { Set<ConfigAttribute> unsupportedAttributes = new HashSet<>(); for (ConfigAttribute attr : attrDefs) { if (!this.channelDecisionManager.supports(attr)) { unsupportedAttributes.add(attr); } } return unsupportedAttributes; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; FilterInvocation filterInvocation = new FilterInvocation(request, response, chain); Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAttributes(filterInvocation);
if (attributes != null) { this.logger.debug(LogMessage.format("Request: %s; ConfigAttributes: %s", filterInvocation, attributes)); this.channelDecisionManager.decide(filterInvocation, attributes); @Nullable HttpServletResponse channelResponse = filterInvocation.getResponse(); Assert.notNull(channelResponse, "HttpServletResponse is required"); if (channelResponse.isCommitted()) { return; } } chain.doFilter(request, response); } protected @Nullable ChannelDecisionManager getChannelDecisionManager() { return this.channelDecisionManager; } protected FilterInvocationSecurityMetadataSource getSecurityMetadataSource() { return this.securityMetadataSource; } public void setChannelDecisionManager(ChannelDecisionManager channelDecisionManager) { this.channelDecisionManager = channelDecisionManager; } public void setSecurityMetadataSource( FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource) { this.securityMetadataSource = filterInvocationSecurityMetadataSource; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\ChannelProcessingFilter.java
1
请在Spring Boot框架中完成以下Java代码
public DDTDQ1 getDDTDQ1() { return ddtdq1; } /** * Sets the value of the ddtdq1 property. * * @param value * allowed object is * {@link DDTDQ1 } * */ public void setDDTDQ1(DDTDQ1 value) { this.ddtdq1 = value; } /** * Gets the value of the dprdq1 property. * * @return * possible object is * {@link DPRDQ1 } * */ public DPRDQ1 getDPRDQ1() { return dprdq1;
} /** * Sets the value of the dprdq1 property. * * @param value * allowed object is * {@link DPRDQ1 } * */ public void setDPRDQ1(DPRDQ1 value) { this.dprdq1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DQUAN1.java
2
请完成以下Java代码
public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText) { this.parent = parent; this.infoColumn = infoColumn; } @Override public I_AD_InfoColumn getAD_InfoColumn() { return infoColumn; } @Override public int getParameterCount() { return 1; } @Override public String getLabel(int index) { if (index == 0) return Msg.translate(Env.getCtx(), "search"); return null; } @Override public Object getParameterToComponent(int index) { return null; } @Override public String[] getWhereClauses(List<Object> params) { final List<String> whereClauses = new ArrayList<String>(); String search = getText(); if (!(search.equals("") || search.equals("%"))) { // search = search.trim(); // metas: Permutationen ueber alle Search-Kombinationen // z.B. 3 Tokens ergeben 3! Moeglichkeiten als Ergebnis. if (search.contains(" ")) { StringTokenizer st = new StringTokenizer(search, " "); int tokens = st.countTokens(); String input[] = new String[tokens]; Permutation perm = new Permutation(); perm.setMaxIndex(tokens - 1); for (int token = 0; token < tokens; token++) { input[token] = st.nextToken(); } perm.permute(input, tokens - 1); Iterator<String> itr = perm.getResult().iterator(); while (itr.hasNext()) { search = ("%" + itr.next() + "%").replace(" ", "%"); whereClauses.add("UPPER(bpcs.Search) LIKE UPPER(?)");
params.add(search); log.debug("Search: " + search); } } else { if (!search.startsWith("%")) search = "%" + search; // metas-2009_0021_AP1_CR064: end if (!search.endsWith("%")) search += "%"; whereClauses.add("UPPER(bpcs.Search) LIKE UPPER(?)"); params.add(search); log.debug("Search(2): " + search); } // list.add ("UPPER(bpcs.Search) LIKE ?"); // metas ende } return whereClauses.toArray(new String[whereClauses.size()]); } public IInfoSimple getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPSearchAbstract.java
1
请完成以下Spring Boot application配置
management.health.ldap.enabled=false ldap.partitionSuffix=dc=example,dc=com ldap.partition=example ldap.principal=uid=admin,ou=system ldap.pa
ssword=secret ldap.port=18889 ldap.urls=ldap://localhost:18889
repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\resources\application.properties
2
请完成以下Java代码
public boolean isSequential() { return isSequentialAttribute.getValue(this); } public void setSequential(boolean sequential) { isSequentialAttribute.setValue(this, sequential); } public MultiInstanceFlowCondition getBehavior() { return behaviorAttribute.getValue(this); } public void setBehavior(MultiInstanceFlowCondition behavior) { behaviorAttribute.setValue(this, behavior); } public EventDefinition getOneBehaviorEventRef() { return oneBehaviorEventRefAttribute.getReferenceTargetElement(this); } public void setOneBehaviorEventRef(EventDefinition oneBehaviorEventRef) { oneBehaviorEventRefAttribute.setReferenceTargetElement(this, oneBehaviorEventRef); } public EventDefinition getNoneBehaviorEventRef() { return noneBehaviorEventRefAttribute.getReferenceTargetElement(this); } public void setNoneBehaviorEventRef(EventDefinition noneBehaviorEventRef) { noneBehaviorEventRefAttribute.setReferenceTargetElement(this, noneBehaviorEventRef); } public boolean isCamundaAsyncBefore() { return camundaAsyncBefore.getValue(this); } public void setCamundaAsyncBefore(boolean isCamundaAsyncBefore) { camundaAsyncBefore.setValue(this, isCamundaAsyncBefore); } public boolean isCamundaAsyncAfter() { return camundaAsyncAfter.getValue(this); } public void setCamundaAsyncAfter(boolean isCamundaAsyncAfter) { camundaAsyncAfter.setValue(this, isCamundaAsyncAfter); } public boolean isCamundaExclusive() { return camundaExclusive.getValue(this);
} public void setCamundaExclusive(boolean isCamundaExclusive) { camundaExclusive.setValue(this, isCamundaExclusive); } public String getCamundaCollection() { return camundaCollection.getValue(this); } public void setCamundaCollection(String expression) { camundaCollection.setValue(this, expression); } public String getCamundaElementVariable() { return camundaElementVariable.getValue(this); } public void setCamundaElementVariable(String variableName) { camundaElementVariable.setValue(this, variableName); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MultiInstanceLoopCharacteristicsImpl.java
1
请完成以下Java代码
protected String getAlreadyFilteredAttributeName() { return this.alreadyFilteredAttributeName; } /** * Typically an ERROR dispatch happens after the REQUEST dispatch completes, and the * filter chain starts anew. On some servers however the ERROR dispatch may be nested * within the REQUEST dispatch, e.g. as a result of calling {@code sendError} on the * response. In that case we are still in the filter chain, on the same thread, but * the request and response have been switched to the original, unwrapped ones. * <p> * Sub-classes may use this method to filter such nested ERROR dispatches and re-apply * wrapping on the request or response. {@code ThreadLocal} context, if any, should * still be active as we are still nested within the filter chain. * @param request the request * @param response the response * @param filterChain the filter chain * @throws ServletException if request is not HTTP request * @throws IOException in case of I/O operation exception */ protected void doFilterNestedErrorDispatch(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { doFilter(request, response, filterChain); } /** * Same contract as for {@code doFilter}, but guaranteed to be just invoked once per * request within a single request thread. * <p> * Provides HttpServletRequest and HttpServletResponse arguments instead of the * default ServletRequest and ServletResponse ones.
* @param request the request * @param response the response * @param filterChain the FilterChain * @throws ServletException thrown when a non-I/O exception has occurred * @throws IOException thrown when an I/O exception of some sort has occurred * @see Filter#doFilter */ protected abstract void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException; @Override public void init(FilterConfig config) { } @Override public void destroy() { } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\OncePerRequestFilter.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public org.compiere.model.I_C_Activity getParent_Activity() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class); } @Override public void setParent_Activity(org.compiere.model.I_C_Activity Parent_Activity) { set_ValueFromPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class, Parent_Activity); } /** Set Hauptkostenstelle. @param Parent_Activity_ID Hauptkostenstelle */ @Override public void setParent_Activity_ID (int Parent_Activity_ID) { if (Parent_Activity_ID < 1) set_Value (COLUMNNAME_Parent_Activity_ID, null); else set_Value (COLUMNNAME_Parent_Activity_ID, Integer.valueOf(Parent_Activity_ID)); } /** Get Hauptkostenstelle. @return Hauptkostenstelle */ @Override public int getParent_Activity_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_Activity_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Activity.java
1
请完成以下Java代码
public class ChangePlanItemDefinitionWithNewTargetIdsMapping { protected String existingPlanItemDefinitionId; protected String newPlanItemId; protected String newPlanItemDefinitionId; public ChangePlanItemDefinitionWithNewTargetIdsMapping(String existingPlanItemDefinitionId, String newPlanItemId, String newPlanItemDefinitionId) { this.existingPlanItemDefinitionId = existingPlanItemDefinitionId; this.newPlanItemId = newPlanItemId; this.newPlanItemDefinitionId = newPlanItemDefinitionId; } public String getExistingPlanItemDefinitionId() { return existingPlanItemDefinitionId; } public void setExistingPlanItemDefinitionId(String existingPlanItemDefinitionId) { this.existingPlanItemDefinitionId = existingPlanItemDefinitionId;
} public String getNewPlanItemId() { return newPlanItemId; } public void setNewPlanItemId(String newPlanItemId) { this.newPlanItemId = newPlanItemId; } public String getNewPlanItemDefinitionId() { return newPlanItemDefinitionId; } public void setNewPlanItemDefinitionId(String newPlanItemDefinitionId) { this.newPlanItemDefinitionId = newPlanItemDefinitionId; } }
repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\ChangePlanItemDefinitionWithNewTargetIdsMapping.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductReduceStockDTO { /** * 商品编号 */ private Long productId; /** * 数量 */ private Integer amount; public Long getProductId() { return productId; }
public ProductReduceStockDTO setProductId(Long productId) { this.productId = productId; return this; } public Integer getAmount() { return amount; } public ProductReduceStockDTO setAmount(Integer amount) { this.amount = amount; return this; } }
repos\SpringBoot-Labs-master\lab-52\lab-52-seata-at-httpclient-demo\lab-52-seata-at-httpclient-demo-product-service\src\main\java\cn\iocoder\springboot\lab52\productservice\dto\ProductReduceStockDTO.java
2
请完成以下Java代码
public String asString() { return "messaging.consumer.id"; } }, /** * Messaging partition. */ MESSAGING_PARTITION { @Override @NonNull public String asString() { return "messaging.kafka.source.partition"; } }, /** * Messaging message offset. */ MESSAGING_OFFSET { @Override @NonNull public String asString() { return "messaging.kafka.message.offset"; } }, } /** * Default {@link KafkaListenerObservationConvention} for Kafka listener key values. */ public static class DefaultKafkaListenerObservationConvention implements KafkaListenerObservationConvention { /** * A singleton instance of the convention. */ public static final DefaultKafkaListenerObservationConvention INSTANCE = new DefaultKafkaListenerObservationConvention(); @Override @NonNull public KeyValues getLowCardinalityKeyValues(KafkaRecordReceiverContext context) { String groupId = context.getGroupId(); KeyValues keyValues = KeyValues.of( ListenerLowCardinalityTags.LISTENER_ID.withValue(context.getListenerId()), ListenerLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"), ListenerLowCardinalityTags.MESSAGING_OPERATION.withValue("process"), ListenerLowCardinalityTags.MESSAGING_SOURCE_NAME.withValue(context.getSource()), ListenerLowCardinalityTags.MESSAGING_SOURCE_KIND.withValue("topic") ); if (StringUtils.hasText(groupId)) { keyValues = keyValues .and(ListenerLowCardinalityTags.MESSAGING_CONSUMER_GROUP.withValue(groupId)); } return keyValues; } @Override @NonNull public KeyValues getHighCardinalityKeyValues(KafkaRecordReceiverContext context) { String clientId = context.getClientId();
String consumerId = getConsumerId(context.getGroupId(), clientId); KeyValues keyValues = KeyValues.of( ListenerHighCardinalityTags.MESSAGING_PARTITION.withValue(context.getPartition()), ListenerHighCardinalityTags.MESSAGING_OFFSET.withValue(context.getOffset()) ); if (StringUtils.hasText(clientId)) { keyValues = keyValues .and(ListenerHighCardinalityTags.MESSAGING_CLIENT_ID.withValue(clientId)); } if (StringUtils.hasText(consumerId)) { keyValues = keyValues .and(ListenerHighCardinalityTags.MESSAGING_CONSUMER_ID.withValue(consumerId)); } return keyValues; } @Override public String getContextualName(KafkaRecordReceiverContext context) { return context.getSource() + " process"; } private static @Nullable String getConsumerId(@Nullable String groupId, @Nullable String clientId) { if (StringUtils.hasText(groupId)) { if (StringUtils.hasText(clientId)) { return groupId + " - " + clientId; } return groupId; } return clientId; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaListenerObservation.java
1
请完成以下Java代码
public class DefaultEventRegistryChangeDetectionExecutor implements EventRegistryChangeDetectionExecutor { protected EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager; protected long initialDelayInMs; protected long delayInMs; protected ScheduledExecutorService scheduledExecutorService; protected String threadName = "flowable-event-registry-change-detector-%d"; protected Runnable changeDetectionRunnable; public DefaultEventRegistryChangeDetectionExecutor(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager, long initialDelayInMs, long delayInMs) { this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager; this.initialDelayInMs = initialDelayInMs; this.delayInMs = delayInMs; } @Override public void initialize() { this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new BasicThreadFactory.Builder().namingPattern(threadName).build()); this.changeDetectionRunnable = createChangeDetectionRunnable(); this.scheduledExecutorService.scheduleAtFixedRate(this.changeDetectionRunnable, initialDelayInMs, delayInMs, TimeUnit.MILLISECONDS); } @Override public void shutdown() { if (scheduledExecutorService != null) { scheduledExecutorService.shutdown(); } } protected Runnable createChangeDetectionRunnable() { return new EventRegistryChangeDetectionRunnable(eventRegistryChangeDetectionManager); } public ScheduledExecutorService getScheduledExecutorService() { return scheduledExecutorService; } public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; }
public String getThreadName() { return threadName; } public void setThreadName(String threadName) { this.threadName = threadName; } public Runnable getChangeDetectionRunnable() { return changeDetectionRunnable; } public void setChangeDetectionRunnable(Runnable changeDetectionRunnable) { this.changeDetectionRunnable = changeDetectionRunnable; } public EventRegistryChangeDetectionManager getEventRegistryChangeDetectionManager() { return eventRegistryChangeDetectionManager; } @Override public void setEventRegistryChangeDetectionManager(EventRegistryChangeDetectionManager eventRegistryChangeDetectionManager) { this.eventRegistryChangeDetectionManager = eventRegistryChangeDetectionManager; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\management\DefaultEventRegistryChangeDetectionExecutor.java
1
请完成以下Java代码
public FormattedMsgWithAdIssueId extractMsgAndAdIssue(@NonNull final String msg, final Object... msgParameters) { final IErrorManager errorManager = Services.get(IErrorManager.class); final Throwable exception = LoggableWithThrowableUtil.extractThrowable(msgParameters); Object[] msgParametersEffective = msgParameters; AdIssueId adIssueId = null; if (exception != null) { try { adIssueId = errorManager.createIssue(exception); msgParametersEffective = LoggableWithThrowableUtil.removeLastElement(msgParameters); } catch (final Exception createIssueException) { createIssueException.addSuppressed(exception); logger.warn("Failed creating AD_Issue for exception: Skip creating the AD_Issue.", createIssueException); } } // String messageFormatted; try { messageFormatted = StringUtils.formatMessage(msg, msgParametersEffective); } catch (final Exception formatMessageException) { logger.warn("Failed creating log entry for msg={} and msgParametes={}. Creating a fallback one instead", msg, msgParametersEffective, formatMessageException); messageFormatted = (msg != null ? msg : "") + (msgParameters != null && msgParameters.length > 0 ? " -- parameters: " + Arrays.asList(msgParameters) : ""); } return new FormattedMsgWithAdIssueId(messageFormatted, Optional.ofNullable(adIssueId)); }
private Throwable extractThrowable(final Object[] msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return null; } final Object lastEntry = msgParameters[msgParameters.length - 1]; return lastEntry instanceof Throwable ? (Throwable)lastEntry : null; } private Object[] removeLastElement(final Object[] msgParameters) { if (msgParameters == null || msgParameters.length == 0) { return msgParameters; } final int newLen = msgParameters.length - 1; final Object[] msgParametersNew = new Object[newLen]; System.arraycopy(msgParameters, 0, msgParametersNew, 0, newLen); return msgParametersNew; } @Value public static class FormattedMsgWithAdIssueId { String formattedMessage; Optional<AdIssueId> adIsueId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\LoggableWithThrowableUtil.java
1
请完成以下Java代码
protected void executeInternal(CommandContext commandContext, DeploymentEntity deployment) { String oldTenantId = deployment.getTenantId(); deployment.setTenantId(newTenantId); // Doing process instances, executions and tasks with direct SQL updates // (otherwise would not be performant) commandContext .getProcessDefinitionEntityManager() .updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId); commandContext.getExecutionEntityManager().updateExecutionTenantIdForDeployment(deploymentId, newTenantId); commandContext.getTaskEntityManager().updateTaskTenantIdForDeployment(deploymentId, newTenantId); commandContext.getJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getTimerJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getSuspendedJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getDeadLetterJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getEventSubscriptionEntityManager().updateEventSubscriptionTenantId(oldTenantId, newTenantId); // Doing process definitions in memory, cause we need to clear the process definition cache List<ProcessDefinition> processDefinitions = new ProcessDefinitionQueryImpl().deploymentId(deploymentId).list(); for (ProcessDefinition processDefinition : processDefinitions) { commandContext .getProcessEngineConfiguration() .getProcessDefinitionCache() .remove(processDefinition.getId()); } // Clear process definition cache commandContext.getProcessEngineConfiguration().getProcessDefinitionCache().clear(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ChangeDeploymentTenantIdCmd.java
1
请完成以下Java代码
public void addOutputLocal(CallableElementParameter output) { outputsLocal.add(output); } public void addOutputs(List<CallableElementParameter> outputs) { this.outputs.addAll(outputs); } public VariableMap getOutputVariables(VariableScope calledElementScope) { List<CallableElementParameter> outputs = getOutputs(); return getVariables(outputs, calledElementScope); } public VariableMap getOutputVariablesLocal(VariableScope calledElementScope) { List<CallableElementParameter> outputs = getOutputsLocal(); return getVariables(outputs, calledElementScope); }
// variables ////////////////////////////////////////////////////////////////// protected VariableMap getVariables(List<CallableElementParameter> params, VariableScope variableScope) { VariableMap result = Variables.createVariables(); for (CallableElementParameter param : params) { param.applyTo(variableScope, result); } return result; } // deployment id ////////////////////////////////////////////////////////////// }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CallableElement.java
1
请完成以下Java代码
public class CommentDto extends LinkableDto { protected String id; protected String userId; protected Date time; protected String taskId; protected String message; protected Date removalTime; protected String rootProcessInstanceId; protected String processInstanceId; public CommentDto() { } public String getId() { return id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalDate) { this.removalTime = removalDate; } public String getRootProcessInstanceId() { return rootProcessInstanceId;
} public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getProcessInstanceId() { return this.processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public static CommentDto fromComment(Comment comment) { CommentDto dto = new CommentDto(); dto.id = comment.getId(); dto.userId = comment.getUserId(); dto.time = comment.getTime(); dto.taskId = comment.getTaskId(); dto.message = comment.getFullMessage(); dto.removalTime = comment.getRemovalTime(); dto.rootProcessInstanceId = comment.getRootProcessInstanceId(); dto.processInstanceId = comment.getProcessInstanceId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\CommentDto.java
1
请完成以下Java代码
public final int getBPartnerId() { return bPartnerId; } public final void setBPartnerId(int partnerId) { bPartnerId = partnerId; } public final Timestamp getDatePromised() { return datePromised; } public final void setDatePromised(Timestamp datePromised) { this.datePromised = datePromised; } public final boolean isIncludeWhenIncompleteInOutExists() { return isIncludeWhenIncompleteInOutExists; } public final void setIncludeWhenIncompleteInOutExists(boolean isUnconfirmedInOut) { this.isIncludeWhenIncompleteInOutExists = isUnconfirmedInOut; } public final boolean isConsolidateDocument() { return consolidateDocument; } public final void setConsolidateDocument(boolean consolidateDocument) { this.consolidateDocument = consolidateDocument; } public final Timestamp getMovementDate() { return movementDate; } public final void setMovementDate(Timestamp dateShipped) { this.movementDate = dateShipped;
} public final boolean isPreferBPartner() { return preferBPartner; } public final void setPreferBPartner(boolean preferBPartner) { this.preferBPartner = preferBPartner; } public final boolean isIgnorePostageFreeamount() { return ignorePostageFreeamount; } public final void setIgnorePostageFreeamount(boolean ignorePostageFreeamount) { this.ignorePostageFreeamount = ignorePostageFreeamount; } public Set<Integer> getSelectedOrderLineIds() { return selectedOrderLineIds; } public void setSelectedOrderLineIds(Set<Integer> selectedOrderLineIds) { this.selectedOrderLineIds = selectedOrderLineIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\shipment\ShipmentParams.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_WF_Node_Template_ID (final int AD_WF_Node_Template_ID) { if (AD_WF_Node_Template_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Template_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Template_ID, AD_WF_Node_Template_ID); } @Override public int getAD_WF_Node_Template_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Template_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() {
return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Template.java
1
请完成以下Java代码
public IAttributeStorageFactory createHUAttributeStorageFactory() { final IHUStorageFactory huStorageFactory = Services.get(IHandlingUnitsBL.class).getStorageFactory(); return createHUAttributeStorageFactory(huStorageFactory, HUAttributesDAO.instance); } @Override public IAttributeStorageFactory createHUAttributeStorageFactory(@NonNull final IHUStorageFactory huStorageFactory) { return createHUAttributeStorageFactory(huStorageFactory, HUAttributesDAO.instance); } @Override public IAttributeStorageFactory createHUAttributeStorageFactory( @NonNull final IHUStorageFactory huStorageFactory, @NonNull final IHUAttributesDAO huAttributesDAO) { final IAttributeStorageFactory factory = prepareHUAttributeStorageFactory(huAttributesDAO); factory.setHUStorageFactory(huStorageFactory); return factory; } @Override public IAttributeStorageFactory prepareHUAttributeStorageFactory(@NonNull final IHUAttributesDAO huAttributesDAO) { final CompositeAttributeStorageFactory factory = new CompositeAttributeStorageFactory(); factory.setHUAttributesDAO(huAttributesDAO); factory.addAttributeStorageFactoryClasses(attributeStorageFactories); for (final IAttributeStorageListener attributeStorageListener : attributeStorageListeners) { factory.addAttributeStorageListener(attributeStorageListener); } return factory; } @Override public void addAttributeStorageFactory(@NonNull final Class<? extends IAttributeStorageFactory> attributeStorageFactoryClass) { final boolean added = attributeStorageFactories.addIfAbsent(attributeStorageFactoryClass);
if (added) { logger.info("Registered: {}", attributeStorageFactoryClass); } else { logger.warn("Already registered: {}", attributeStorageFactoryClass); } } @Override public void addAttributeStorageListener(@NonNull final IAttributeStorageListener attributeStorageListener) { attributeStorageListeners.add(attributeStorageListener); logger.info("Registered: {}", attributeStorageListener); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AttributeStorageFactoryService.java
1
请完成以下Java代码
public static GlobalQRCode ofString(@NonNull final String string) { return parse(string).orThrow(); } public static GlobalQRCode ofBase64Encoded(@NonNull final String string) { final byte[] bytes = BaseEncoding.base64().decode(string); return ofString(new String(bytes, StandardCharsets.UTF_8)); } public static GlobalQRCodeParseResult parse(@NonNull final String string) { String remainingString = string; // // Extract type final GlobalQRCodeType type; { int idx = remainingString.indexOf(SEPARATOR); if (idx <= 0) { return GlobalQRCodeParseResult.error("Invalid global QR code(1): " + string); } type = GlobalQRCodeType.ofString(remainingString.substring(0, idx)); remainingString = remainingString.substring(idx + 1); } // // Extract version final GlobalQRCodeVersion version; { int idx = remainingString.indexOf(SEPARATOR); if (idx <= 0) { return GlobalQRCodeParseResult.error("Invalid global QR code(2): " + string); } version = GlobalQRCodeVersion.ofString(remainingString.substring(0, idx)); remainingString = remainingString.substring(idx + 1); } // // Payload final String payloadAsJson = remainingString; //
return GlobalQRCodeParseResult.ok(builder() .type(type) .version(version) .payloadAsJson(payloadAsJson) .build()); } public <T> T getPayloadAs(@NonNull final Class<T> type) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(payloadAsJson, type); } catch (JsonProcessingException e) { throw Check.mkEx("Failed converting payload to `" + type + "`: " + payloadAsJson, e); } } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return type.toJson() + SEPARATOR + version + SEPARATOR + payloadAsJson; } public static boolean equals(@Nullable GlobalQRCode o1, @Nullable GlobalQRCode o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCode.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getAvailableBalance() { return this.balance.subtract(unbalance); } /** * 获取实际可结算金额 * * @return */ public BigDecimal getAvailableSettAmount() { BigDecimal subSettAmount = this.settAmount.subtract(unbalance); if (getAvailableBalance().compareTo(subSettAmount) == -1) { return getAvailableBalance(); } return subSettAmount; } /** * 验证可用余额是否足够 * * @param amount * @return */ public boolean availableBalanceIsEnough(BigDecimal amount) { return this.getAvailableBalance().compareTo(amount) >= 0; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo == null ? null : accountNo.trim(); } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public BigDecimal getUnbalance() { return unbalance; } public void setUnbalance(BigDecimal unbalance) { this.unbalance = unbalance; } public BigDecimal getSecurityMoney() { return securityMoney; } public void setSecurityMoney(BigDecimal securityMoney) { this.securityMoney = securityMoney; } public BigDecimal getTotalIncome() { return totalIncome; } public void setTotalIncome(BigDecimal totalIncome) { this.totalIncome = totalIncome; } public BigDecimal getTotalExpend() { return totalExpend; } public void setTotalExpend(BigDecimal totalExpend) { this.totalExpend = totalExpend; } public BigDecimal getTodayIncome() { return todayIncome; }
public void setTodayIncome(BigDecimal todayIncome) { this.todayIncome = todayIncome; } public BigDecimal getTodayExpend() { return todayExpend; } public void setTodayExpend(BigDecimal todayExpend) { this.todayExpend = todayExpend; } public String getAccountType() { return accountType; } public void setAccountType(String accountType) { this.accountType = accountType == null ? null : accountType.trim(); } public BigDecimal getSettAmount() { return settAmount; } public void setSettAmount(BigDecimal settAmount) { this.settAmount = settAmount; } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java
2
请完成以下Java代码
public List<SwaggerResource> get() { List<SwaggerResource> resources = new ArrayList<>(); List<String> routeHosts = new ArrayList<>(); // 获取所有可用的host:serviceId routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null) .filter(route -> !self.equals(route.getUri().getHost())) .subscribe(route ->{ // 代码逻辑说明: 过滤掉无效路由,避免接口文档报错无法打开 boolean hasRoute=checkRoute(route.getId()); if(hasRoute){ routeHosts.add(route.getUri().getHost()); } }); // 记录已经添加过的server,存在同一个应用注册了多个服务在nacos上 Set<String> dealed = new HashSet<>(); routeHosts.forEach(instance -> { // 拼接url String url = "/" + instance.toLowerCase() + SWAGGER2URL; if (!dealed.contains(url)) { dealed.add(url); log.info(" Gateway add SwaggerResource: {}",url); SwaggerResource swaggerResource = new SwaggerResource(); swaggerResource.setUrl(url); swaggerResource.setSwaggerVersion("2.0"); swaggerResource.setName(instance); //Swagger排除不展示的服务 if(!ArrayUtil.contains(excludeServiceIds,instance)){ resources.add(swaggerResource); } } }); return resources; } /** * 检测nacos中是否有健康实例 * @param routeId
* @return */ private Boolean checkRoute(String routeId) { Boolean hasRoute = false; try { //修复使用带命名空间启动网关swagger看不到接口文档的问题 Properties properties=new Properties(); properties.setProperty("serverAddr",serverAddr); if(namespace!=null && !"".equals(namespace)){ log.info("nacos.discovery.namespace = {}", namespace); properties.setProperty("namespace",namespace); } if(username!=null && !"".equals(username)){ properties.setProperty("username",username); } if(password!=null && !"".equals(password)){ properties.setProperty("password",password); } //【issues/5115】因swagger文档导致gateway内存溢出 if (this.naming == null) { this.naming = NamingFactory.createNamingService(properties); } log.info(" config.group : {}", group); List<Instance> list = this.naming.selectInstances(routeId, group , true); if (ObjectUtil.isNotEmpty(list)) { hasRoute = true; } } catch (Exception e) { e.printStackTrace(); } return hasRoute; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\handler\swagger\MySwaggerResourceProvider.java
1
请完成以下Java代码
public IHUStorageDAO getHUStorageDAO() { return getHUStorageFactory().getHUStorageDAO(); } @Override public IHUStorageFactory getHUStorageFactory() { return huStorageFactory; } @Override public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { this.huStorageFactory = huStorageFactory;
for (final IAttributeStorageFactory factory : factories) { factory.setHUStorageFactory(huStorageFactory); } } @Override public void flush() { for (final IAttributeStorageFactory factory : factories) { factory.flush(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageFactory.java
1
请完成以下Java代码
void startBookBatchUpdateRollBack(int size) { jdbcTemplate.execute("CREATE TABLE books(" + "id SERIAL, name VARCHAR(255), price NUMERIC(15, 2))"); List<Book> books = new ArrayList(); for (int count = 0; count < size; count++) { if (count == 500) { // create a invalid data for id 500, test rollback // name allow 255, this book has length of 300 books.add(new Book(NameGenerator.randomName(300), new BigDecimal(1.99))); continue; } books.add(new Book(NameGenerator.randomName(20), new BigDecimal(1.99))); } try { // with @Transactional, any error, entire batch will be roll back bookRepository.batchInsert(books, 100); } catch (Exception e) { System.err.println(e.getMessage()); } List<Book> bookFromDatabase = bookRepository.findAll(); // count = 0 , id 500 error, roll back all log.info("Total books: {}", bookFromDatabase.size()); } void startBookBatchUpdateApp(int size) { //jdbcTemplate.execute("DROP TABLE books IF EXISTS"); jdbcTemplate.execute("CREATE TABLE books(" + "id SERIAL, name VARCHAR(255), price NUMERIC(15, 2))"); List<Book> books = new ArrayList(); for (int count = 0; count < size; count++) { books.add(new Book(NameGenerator.randomName(20), new BigDecimal(1.99))); } // batch insert bookRepository.batchInsert(books); List<Book> bookFromDatabase = bookRepository.findAll();
// count log.info("Total books: {}", bookFromDatabase.size()); // random log.info("{}", bookRepository.findById(2L).orElseThrow(IllegalArgumentException::new)); log.info("{}", bookRepository.findById(500L).orElseThrow(IllegalArgumentException::new)); // update all books to 9.99 bookFromDatabase.forEach(x -> x.setPrice(new BigDecimal(9.99))); // batch update bookRepository.batchUpdate(bookFromDatabase); List<Book> updatedList = bookRepository.findAll(); // count log.info("Total books: {}", updatedList.size()); // random log.info("{}", bookRepository.findById(2L).orElseThrow(IllegalArgumentException::new)); log.info("{}", bookRepository.findById(500L).orElseThrow(IllegalArgumentException::new)); } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\StartApplication.java
1
请完成以下Java代码
public class C_Invoice_Candidate_Update extends JavaProcess { // services private final transient IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class); private boolean p_IsFullUpdate = false; @Override protected void prepare() { p_IsFullUpdate = getParameterAsIParams().getParameterAsBool("IsFullUpdate"); } @Override @RunOutOfTrx protected String doIt() throws Exception { final Properties ctx = getCtx(); Check.assume(Env.getAD_Client_ID(ctx) > 0, "No point in calling this process with AD_Client_ID=0"); // // Create the updater final InvoiceCandRecomputeTag recomputeTag = InvoiceCandRecomputeTag.ofPInstanceId(getPinstanceId()); final IInvoiceCandInvalidUpdater updater = invoiceCandBL.updateInvalid()
.setContext(ctx, getTrxName()) .setTaggedWithNoTag() .setRecomputeTagToUse(recomputeTag); if (p_IsFullUpdate) { updater.setTaggedWithAnyTag(); } // // Execute the updater updater.update(); return "@Success@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_Candidate_Update.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isEnabled() { // // Get the DeveloperMode sysconfig // NOTE: this method shall be as less disruptive as possible, so // if there is no database connection or retrieving the sysconfig fails for some reason simply return false, // but never ever fail. try { if (Adempiere.isUnitTestMode()) { return true; } if (!DB.isConnected()) { return false; } return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_DeveloperMode, false); } catch (final Exception e) { logger.warn("Failed retrieving the DeveloperMode sysconfig. Considering not enabled.", e); return false; } } @Override public Optional<File> getDevelopmentWorkspaceDir() { final String dirStr = Services.get(ISysConfigBL.class).getValue(SYSCONFIG_DevelopmentWorkspaceDir); if (dirStr == null || Check.isBlank(dirStr) || "-".equals(dirStr.trim())) { return Optional.empty(); }
final File dir = new File(dirStr.trim()); return Optional.of(dir); } @Override public void executeAsSystem(final ContextRunnable runnable) { final Properties sysCtx = Env.createSysContext(Env.getCtx()); DB.saveConstraints(); try (final IAutoCloseable ignored = Env.switchContext(sysCtx); final IAutoCloseable ignored1 = MigrationScriptFileLoggerHolder.temporaryEnabledLoggingToNewFile()) { DB.getConstraints().addAllowedTrxNamePrefix(ITrx.TRXNAME_PREFIX_LOCAL); DB.getConstraints().incMaxTrx(1); runnable.run(sysCtx); } finally { DB.restoreConstraints(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\DeveloperModeBL.java
2
请完成以下Java代码
public void migrateDependentEntities() { jobInstance.migrateState(); jobInstance.migrateDependentEntities(); for (MigratingInstance dependentInstance : migratingDependentInstances) { dependentInstance.migrateState(); dependentInstance.migrateDependentEntities(); } } public TransitionInstance getTransitionInstance() { return transitionInstance; } /** * Else asyncBefore */ public boolean isAsyncAfter() { return jobInstance.isAsyncAfter(); } public boolean isAsyncBefore() { return jobInstance.isAsyncBefore(); } public MigratingJobInstance getJobInstance() { return jobInstance; } @Override public void setParent(MigratingScopeInstance parentInstance) { if (parentInstance != null && !(parentInstance instanceof MigratingActivityInstance)) {
throw MIGRATION_LOGGER.cannotHandleChild(parentInstance, this); } MigratingActivityInstance parentActivityInstance = (MigratingActivityInstance) parentInstance; if (this.parentInstance != null) { ((MigratingActivityInstance) this.parentInstance).removeChild(this); } this.parentInstance = parentActivityInstance; if (parentInstance != null) { parentActivityInstance.addChild(this); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingTransitionInstance.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } @Override public String getOwner() { return ownerId; } @Override public String getAssignee() { return assigneeId; } @Override public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } @Override public String getOutcome() { return outcome; } @Override public Map<String, Object> getStartFormVariables() { return startFormVariables; } @Override public String getCallbackId() { return this.callbackId; } @Override public String getCallbackType() { return this.callbackType; } @Override
public String getReferenceId() { return referenceId; } @Override public String getReferenceType() { return referenceType; } @Override public String getParentId() { return this.parentId; } @Override public boolean isFallbackToDefaultTenant() { return this.fallbackToDefaultTenant; } @Override public boolean isStartWithForm() { return this.startWithForm; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceBuilderImpl.java
1
请完成以下Java代码
public ProcessEngineConfigurationImpl setTelemetryData(TelemetryDataImpl telemetryData) { this.telemetryData = telemetryData; return this; } public boolean isReevaluateTimeCycleWhenDue() { return reevaluateTimeCycleWhenDue; } public ProcessEngineConfigurationImpl setReevaluateTimeCycleWhenDue(boolean reevaluateTimeCycleWhenDue) { this.reevaluateTimeCycleWhenDue = reevaluateTimeCycleWhenDue; return this; } public int getRemovalTimeUpdateChunkSize() { return removalTimeUpdateChunkSize; } public ProcessEngineConfigurationImpl setRemovalTimeUpdateChunkSize(int removalTimeUpdateChunkSize) { this.removalTimeUpdateChunkSize = removalTimeUpdateChunkSize; return this; } /** * @return a exception code interceptor. The interceptor is not registered in case
* {@code disableExceptionCode} is configured to {@code true}. */ protected ExceptionCodeInterceptor getExceptionCodeInterceptor() { return new ExceptionCodeInterceptor(builtinExceptionCodeProvider, customExceptionCodeProvider); } public DiagnosticsRegistry getDiagnosticsRegistry() { return diagnosticsRegistry; } public ProcessEngineConfiguration setDiagnosticsRegistry(DiagnosticsRegistry diagnosticsRegistry) { this.diagnosticsRegistry = diagnosticsRegistry; return this; } public boolean isLegacyJobRetryBehaviorEnabled() { return legacyJobRetryBehaviorEnabled; } public ProcessEngineConfiguration setLegacyJobRetryBehaviorEnabled(boolean legacyJobRetryBehaviorEnabled) { this.legacyJobRetryBehaviorEnabled = legacyJobRetryBehaviorEnabled; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请完成以下Java代码
public void setIsAllowAllActions (final boolean IsAllowAllActions) { set_Value (COLUMNNAME_IsAllowAllActions, IsAllowAllActions); } @Override public boolean isAllowAllActions() { return get_ValueAsBoolean(COLUMNNAME_IsAllowAllActions); } @Override public void setMobile_Application_Access_ID (final int Mobile_Application_Access_ID) { if (Mobile_Application_Access_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_Access_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_Access_ID, Mobile_Application_Access_ID); } @Override
public int getMobile_Application_Access_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_Access_ID); } @Override public void setMobile_Application_ID (final int Mobile_Application_ID) { if (Mobile_Application_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID); } @Override public int getMobile_Application_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Access.java
1
请完成以下Java代码
public int compare(final T o1, final T o2) { final int cardinality1 = cardinality(o1); final int cardinality2 = cardinality(o2); return cardinality1 - cardinality2; } private final int cardinality(final T item) { final int cardinality = cardinalityList.indexOf(item); // If item was not found in our cardinality list, return MAX_VALUE // => not found items will be comsidered last ones if (cardinality < 0) { return Integer.MAX_VALUE; } return cardinality; } public static final class Builder<T> { private List<T> cardinalityList; Builder() { super(); } public CardinalityOrderComparator<T> build() { return new CardinalityOrderComparator<>(this); } /** * Convenient method to copy and sort a given list. * * @param list
* @return sorted list (as a new copy) */ public List<T> copyAndSort(final List<T> list) { final CardinalityOrderComparator<T> comparator = build(); final List<T> listSorted = new ArrayList<>(list); Collections.sort(listSorted, comparator); return listSorted; } /** * Sets the list of all items. * When sorting, this is the list which will give the cardinality of a given item (i.e. the indexOf). * * WARNING: the given cardinality list will be used on line, as it is and it won't be copied, because we don't know what indexOf implementation to use. * So, please make sure you are not chaning the list in meantime. * * @param cardinalityList * @return */ public Builder<T> setCardinalityList(final List<T> cardinalityList) { this.cardinalityList = cardinalityList; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\comparator\CardinalityOrderComparator.java
1