instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
private PackingItem getStateOrNull() { final TransactionalPackingItemSupport transactionalSupport = TransactionalPackingItemSupport.getCreate(); if (transactionalSupport == null) { // not running in transaction return null; } return transactionalSupport.getState(this); } /** * Called by API when the transaction is committed. * * @param state */ public void commit(final PackingItem state) {
root.updateFrom(state); } /** * Creates a new instance which wraps a copy of this instances {@link #getDelegate()} value. */ @Override public IPackingItem copy() { return new TransactionalPackingItem(this); } @Override public boolean isSameAs(final IPackingItem item) { return Util.same(this, item); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\TransactionalPackingItem.java
2
请完成以下Java代码
protected boolean isLeapYear(int year) { return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); } protected int getLastDayOfMonth(int monthNum, int year) { switch (monthNum) { case 1: return 31; case 2: return (isLeapYear(year)) ? 29 : 28; case 3: return 31; case 4: return 30; case 5: return 31; case 6: return 30; case 7: return 31; case 8: return 31; case 9: return 30; case 10:
return 31; case 11: return 30; case 12: return 31; default: throw new IllegalArgumentException("Illegal month number: " + monthNum); } } } class ValueSet { public int value; public int pos; }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\CronExpression.java
1
请完成以下Java代码
public BoilerPlateContext getAttributes() { return boilerPlateMenu.getAttributes(); } public void setAttributes(final BoilerPlateContext attributes) { boilerPlateMenu.setAttributes(attributes); } public File getPDF(String fileNamePrefix) { throw new UnsupportedOperationException(); } private void actionPreview() { // final ReportEngine re = getReportEngine(); // ReportCtl.preview(re); File pdf = getPDF(null); if (pdf != null) { Env.startBrowser(pdf.toURI().toString()); } } private Dialog getParentDialog() { Dialog parent = null; Container e = getParent(); while (e != null) { if (e instanceof Dialog) { parent = (Dialog)e; break; } e = e.getParent(); } return parent; } public boolean print() {
throw new UnsupportedOperationException(); } public static boolean isHtml(String s) { if (s == null) return false; String s2 = s.trim().toUpperCase(); return s2.startsWith("<HTML>"); } public static String convertToHtml(String plainText) { if (plainText == null) return null; return plainText.replaceAll("[\r]*\n", "<br/>\n"); } public boolean isResolveVariables() { return boilerPlateMenu.isResolveVariables(); } public void setResolveVariables(boolean isResolveVariables) { boilerPlateMenu.setResolveVariables(isResolveVariables); } public void setEnablePrint(boolean enabled) { butPrint.setEnabled(enabled); butPrint.setVisible(enabled); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
1
请完成以下Java代码
public int nextInt() { ensureAvailableBytes(4); return super.nextInt(); } @Override public char nextChar() { ensureAvailableBytes(2); return super.nextChar(); } @Override public double nextDouble() { ensureAvailableBytes(8); return super.nextDouble(); }
@Override public byte nextByte() { ensureAvailableBytes(1); return super.nextByte(); } @Override public float nextFloat() { ensureAvailableBytes(4); return super.nextFloat(); } protected abstract void ensureAvailableBytes(int size); }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayStream.java
1
请完成以下Java代码
public static CloseableHttpClient setViaSocketFactory() { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( SSLContexts.createDefault(), new String[] { "TLSv1.2", "TLSv1.3" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } public static CloseableHttpClient setTlsVersionPerConnection() { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.createDefault()) { @Override protected void prepareSocket(SSLSocket socket) { String hostname = socket.getInetAddress().getHostName(); if (hostname.endsWith("internal.system.com")) { socket.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }); } else { socket.setEnabledProtocols(new String[] { "TLSv1.3" }); } } }; return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } // To configure the TLS versions for the client, set the https.protocols system property during runtime. // For example: java -Dhttps.protocols=TLSv1.1,TLSv1.2,TLSv1.3 -jar webClient.jar public static CloseableHttpClient setViaSystemProperties() { return HttpClients.createSystem();
// Alternatively: // return HttpClients.custom().useSystemProperties().build(); } public static void main(String[] args) throws IOException { // Alternatively: // CloseableHttpClient httpClient = setTlsVersionPerConnection(); // CloseableHttpClient httpClient = setViaSystemProperties(); try (CloseableHttpClient httpClient = setViaSocketFactory(); CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/"))) { HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); } } }
repos\tutorials-master\apache-httpclient4\src\main\java\com\baeldung\tlsversion\ClientTlsVersionExamples.java
1
请在Spring Boot框架中完成以下Java代码
public class DimensionService { private final ImmutableMap<String, DimensionFactory<?>> factoriesByTableName; public DimensionService(@NonNull final List<DimensionFactory<?>> factories) { factoriesByTableName = Maps.uniqueIndex(factories, DimensionFactory::getHandledTableName); } public Dimension getFromRecord(@NonNull final Object record) { final String tableName = InterfaceWrapperHelper.getModelTableName(record); return getFactory(tableName).getFromRecord(record); } public void updateRecord(@NonNull final Object record, @NonNull final Dimension from)
{ final String tableName = InterfaceWrapperHelper.getModelTableName(record); getFactory(tableName).updateRecord(record, from); } private DimensionFactory<Object> getFactory(final String tableName) { @SuppressWarnings("unchecked") final DimensionFactory<Object> factory = (DimensionFactory<Object>)factoriesByTableName.get(tableName); if(factory == null) { throw new AdempiereException("No "+DimensionFactory.class+" found for "+ tableName); } return factory; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\DimensionService.java
2
请完成以下Java代码
public java.lang.String getESRReferenceNumber() { return get_ValueAsString(COLUMNNAME_ESRReferenceNumber); } @Override public void setIsMainVAT (final boolean IsMainVAT) { set_ValueNoCheck (COLUMNNAME_IsMainVAT, IsMainVAT); } @Override public boolean isMainVAT() { return get_ValueAsBoolean(COLUMNNAME_IsMainVAT); } @Override public void setIsTaxExempt (final boolean IsTaxExempt) { set_ValueNoCheck (COLUMNNAME_IsTaxExempt, IsTaxExempt); } @Override public boolean isTaxExempt() { return get_ValueAsBoolean(COLUMNNAME_IsTaxExempt); } @Override public void setRate (final @Nullable BigDecimal Rate) { set_Value (COLUMNNAME_Rate, Rate); } @Override public BigDecimal getRate() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSurchargeAmt (final BigDecimal SurchargeAmt) { set_ValueNoCheck (COLUMNNAME_SurchargeAmt, SurchargeAmt); } @Override public BigDecimal getSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxAmt (final @Nullable BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxAmtWithSurchargeAmt (final BigDecimal TaxAmtWithSurchargeAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmtWithSurchargeAmt, TaxAmtWithSurchargeAmt); } @Override public BigDecimal getTaxAmtWithSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtWithSurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final @Nullable BigDecimal TaxBaseAmt) { set_Value (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmtWithSurchargeAmt (final BigDecimal TaxBaseAmtWithSurchargeAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmtWithSurchargeAmt, TaxBaseAmtWithSurchargeAmt); } @Override public BigDecimal getTaxBaseAmtWithSurchargeAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmtWithSurchargeAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTotalAmt (final @Nullable BigDecimal TotalAmt) { set_Value (COLUMNNAME_TotalAmt, TotalAmt); } @Override public BigDecimal getTotalAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_901_991_v.java
1
请完成以下Java代码
public class SingleResourceAutoDeploymentStrategy extends AbstractAutoDeploymentStrategy { /** * The deployment mode this strategy handles. */ public static final String DEPLOYMENT_MODE = "single-resource"; public SingleResourceAutoDeploymentStrategy(ApplicationUpgradeContextService applicationUpgradeContextService) { super(applicationUpgradeContextService); } @Override protected String getDeploymentMode() { return DEPLOYMENT_MODE; } @Override public void deployResources( final String deploymentNameHint, final Resource[] resources,
final RepositoryService repositoryService ) { // Create a separate deployment for each resource using the resource // name for (final Resource resource : resources) { final String resourceName = determineResourceName(resource); final DeploymentBuilder deploymentBuilder = repositoryService .createDeployment() .enableDuplicateFiltering() .name(resourceName); deploymentBuilder.addInputStream(resourceName, resource); loadApplicationUpgradeContext(deploymentBuilder).deploy(); } } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\SingleResourceAutoDeploymentStrategy.java
1
请完成以下Java代码
public class EntityTypeComparatorForModifications implements Comparator<Class<?>> { public static final Map<Class<?>, Integer> TYPE_ORDER = new HashMap<Class<?>, Integer>(); static { // 1 TYPE_ORDER.put(IncidentEntity.class, 1); TYPE_ORDER.put(VariableInstanceEntity.class, 1); TYPE_ORDER.put(IdentityLinkEntity.class, 1); TYPE_ORDER.put(EventSubscriptionEntity.class, 1); TYPE_ORDER.put(JobEntity.class, 1); TYPE_ORDER.put(MessageEntity.class, 1); TYPE_ORDER.put(TimerEntity.class, 1); TYPE_ORDER.put(EverLivingJobEntity.class, 1); TYPE_ORDER.put(MembershipEntity.class, 1); TYPE_ORDER.put(TenantMembershipEntity.class, 1); TYPE_ORDER.put(CaseSentryPartEntity.class, 1); TYPE_ORDER.put(ExternalTaskEntity.class, 1); TYPE_ORDER.put(Batch.class, 1); // 2 TYPE_ORDER.put(TenantEntity.class, 2); TYPE_ORDER.put(GroupEntity.class, 2); TYPE_ORDER.put(UserEntity.class, 2); TYPE_ORDER.put(ByteArrayEntity.class, 2); TYPE_ORDER.put(TaskEntity.class, 2); TYPE_ORDER.put(JobDefinition.class, 2); // 3 TYPE_ORDER.put(ExecutionEntity.class, 3); TYPE_ORDER.put(CaseExecutionEntity.class, 3); // 4 TYPE_ORDER.put(ProcessDefinitionEntity.class, 4); TYPE_ORDER.put(CaseDefinitionEntity.class, 4); TYPE_ORDER.put(DecisionDefinitionEntity.class, 4); TYPE_ORDER.put(DecisionRequirementsDefinitionEntity.class, 4); TYPE_ORDER.put(ResourceEntity.class, 4); // 5 TYPE_ORDER.put(DeploymentEntity.class, 5); } public int compare(Class<?> firstEntityType, Class<?> secondEntityType) {
if(firstEntityType == secondEntityType) { return 0; } Integer firstIndex = TYPE_ORDER.get(firstEntityType); Integer secondIndex = TYPE_ORDER.get(secondEntityType); // unknown type happens before / after everything else if(firstIndex == null) { firstIndex = Integer.MAX_VALUE; } if(secondIndex == null) { secondIndex = Integer.MAX_VALUE; } int result = firstIndex.compareTo(secondIndex); if(result == 0) { return firstEntityType.getName().compareTo(secondEntityType.getName()); } else { return result; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\comparator\EntityTypeComparatorForModifications.java
1
请完成以下Java代码
public JWKSet get() { this.rwLock.readLock().lock(); if (shouldRefresh()) { this.rwLock.readLock().unlock(); this.rwLock.writeLock().lock(); try { if (shouldRefresh()) { this.jwkSet = retrieve(this.jwkSetUrl); this.lastUpdatedAt = Instant.now(); } this.rwLock.readLock().lock(); } finally { this.rwLock.writeLock().unlock(); } } try { return this.jwkSet; }
finally { this.rwLock.readLock().unlock(); } } private boolean shouldRefresh() { // Refresh every 5 minutes return (this.jwkSet == null || this.clock.instant().isAfter(this.lastUpdatedAt.plus(5, ChronoUnit.MINUTES))); } } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\X509SelfSignedCertificateVerifier.java
1
请完成以下Java代码
public void setId(Long id) { this.id = id; } public void setName(final String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true;
if (obj == null) return false; if (getClass() != obj.getClass()) return false; Foo other = (Foo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Foo [name=" + name + "]"; } }
repos\tutorials-master\spring-web-modules\spring-5-mvc\src\main\java\com\baeldung\model\Foo.java
1
请完成以下Java代码
public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } @Override public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID) { if (PickFrom_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_PickFrom_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID); } @Override public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setPriorityRule (final @Nullable java.lang.String PriorityRule) { throw new IllegalArgumentException ("PriorityRule is virtual column"); } @Override public java.lang.String getPriorityRule() { return get_ValueAsString(COLUMNNAME_PriorityRule); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setQtyRejectedToPick (final BigDecimal QtyRejectedToPick) { set_Value (COLUMNNAME_QtyRejectedToPick, QtyRejectedToPick); } @Override public BigDecimal getQtyRejectedToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRejectedToPick); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override
public void setRejectReason (final @Nullable java.lang.String RejectReason) { set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } @Override public void setSinglePackage (final boolean SinglePackage) { set_Value (COLUMNNAME_SinglePackage, SinglePackage); } @Override public boolean isSinglePackage() { return get_ValueAsBoolean(COLUMNNAME_SinglePackage); } @Override public void setWorkplaceIndicator_ID (final int WorkplaceIndicator_ID) { throw new IllegalArgumentException ("WorkplaceIndicator_ID is virtual column"); } @Override public int getWorkplaceIndicator_ID() { return get_ValueAsInt(COLUMNNAME_WorkplaceIndicator_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step.java
1
请完成以下Java代码
public void connectInOutLineToSubscriptionProgressIfPossible(@NonNull final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked) { if (hasNoInOutLine(shipmentScheduleQtyPicked)) { return; } final I_M_ShipmentSchedule shipmentSchedule = shipmentScheduleQtyPicked.getM_ShipmentSchedule(); if (hasNoSubscriptionProgress(shipmentSchedule)) { return; } connectInOutLineToSubscriptionProgress(shipmentScheduleQtyPicked); } private boolean hasNoInOutLine(@NonNull final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked) { return shipmentScheduleQtyPicked.getM_InOutLine_ID() <= 0; }
private boolean hasNoSubscriptionProgress(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { return shipmentSchedule.getAD_Table_ID() != getTableId(I_C_SubscriptionProgress.class); } private void connectInOutLineToSubscriptionProgress(@NonNull final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked) { final I_M_ShipmentSchedule shipmentSchedule = shipmentScheduleQtyPicked.getM_ShipmentSchedule(); final I_M_InOutLine inOutLine = create(shipmentScheduleQtyPicked.getM_InOutLine(), I_M_InOutLine.class); inOutLine.setC_SubscriptionProgress_ID(shipmentSchedule.getRecord_ID()); save(inOutLine); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\M_ShipmentSchedule_QtyPicked.java
1
请完成以下Java代码
default void clearThreadState() { } /** * Return true if the offset should be committed for a handled error (no exception * thrown). * @return true to commit. */ default boolean isAckAfterHandle() { return true; } /** * Set to false to prevent the container from committing the offset of a recovered * record (when the error handler does not itself throw an exception). * @param ack false to not commit. */
default void setAckAfterHandle(boolean ack) { throw new UnsupportedOperationException("This error handler does not support setting this property"); } /** * Called when partitions are assigned. * @param consumer the consumer. * @param partitions the newly assigned partitions. * @param publishPause called to publish a consumer paused event. * @since 2.8.9 */ default void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions, Runnable publishPause) { } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonErrorHandler.java
1
请完成以下Java代码
public org.compiere.model.I_R_RequestType getR_RequestType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class); } @Override public void setR_RequestType(org.compiere.model.I_R_RequestType R_RequestType) { set_ValueFromPO(COLUMNNAME_R_RequestType_ID, org.compiere.model.I_R_RequestType.class, R_RequestType); } /** Set Anfrageart. @param R_RequestType_ID Type of request (e.g. Inquiry, Complaint, ..) */ @Override public void setR_RequestType_ID (int R_RequestType_ID) { if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null); else set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID)); } /** Get Anfrageart. @return Type of request (e.g. Inquiry, Complaint, ..) */ @Override public int getR_RequestType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_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_AD_UserBPAccess.java
1
请完成以下Java代码
public Integer getProcessDefinitionVersion() { return processDefinitionVersion; } public void setProcessDefinitionVersion(Integer processDefinitionVersion) { this.processDefinitionVersion = processDefinitionVersion; } public String getCaseDefinitionName() { return caseDefinitionName; } public void setCaseDefinitionName(String caseDefinitionName) { this.caseDefinitionName = caseDefinitionName; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public void setCaseDefinitionKey(String caseDefinitionKey) { this.caseDefinitionKey = caseDefinitionKey; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } public void setId(String id) { this.id = id; } public String getId() {
return id; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public long getSequenceCounter() { return sequenceCounter; } public void setSequenceCounter(long sequenceCounter) { this.sequenceCounter = sequenceCounter; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } // persistent object implementation /////////////// public Object getPersistentState() { // events are immutable return HistoryEvent.class; } // state inspection public boolean isEventOfType(HistoryEventType type) { return type.getEventName().equals(eventType); } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEvent.java
1
请完成以下Java代码
public Date getCreateTime() { return createTime; } public Date getEndTime() { return endTime; } public Long getDurationInMillis() { return durationInMillis; } public Boolean getRequired() { return required; } public Boolean getAvailable() { return available; } public Boolean getEnabled() { return enabled; } public Boolean getDisabled() { return disabled; } public Boolean getActive() { return active; } public Boolean getCompleted() { return completed; } public Boolean getTerminated() { return terminated; }
public static HistoricCaseActivityInstanceDto fromHistoricCaseActivityInstance(HistoricCaseActivityInstance historicCaseActivityInstance) { HistoricCaseActivityInstanceDto dto = new HistoricCaseActivityInstanceDto(); dto.id = historicCaseActivityInstance.getId(); dto.parentCaseActivityInstanceId = historicCaseActivityInstance.getParentCaseActivityInstanceId(); dto.caseActivityId = historicCaseActivityInstance.getCaseActivityId(); dto.caseActivityName = historicCaseActivityInstance.getCaseActivityName(); dto.caseActivityType = historicCaseActivityInstance.getCaseActivityType(); dto.caseDefinitionId = historicCaseActivityInstance.getCaseDefinitionId(); dto.caseInstanceId = historicCaseActivityInstance.getCaseInstanceId(); dto.caseExecutionId = historicCaseActivityInstance.getCaseExecutionId(); dto.taskId = historicCaseActivityInstance.getTaskId(); dto.calledProcessInstanceId = historicCaseActivityInstance.getCalledProcessInstanceId(); dto.calledCaseInstanceId = historicCaseActivityInstance.getCalledCaseInstanceId(); dto.tenantId = historicCaseActivityInstance.getTenantId(); dto.createTime = historicCaseActivityInstance.getCreateTime(); dto.endTime = historicCaseActivityInstance.getEndTime(); dto.durationInMillis = historicCaseActivityInstance.getDurationInMillis(); dto.required = historicCaseActivityInstance.isRequired(); dto.available = historicCaseActivityInstance.isAvailable(); dto.enabled = historicCaseActivityInstance.isEnabled(); dto.disabled = historicCaseActivityInstance.isDisabled(); dto.active = historicCaseActivityInstance.isActive(); dto.completed = historicCaseActivityInstance.isCompleted(); dto.terminated = historicCaseActivityInstance.isTerminated(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseActivityInstanceDto.java
1
请完成以下Java代码
public void setColumnSQL (String ColumnSQL) { set_Value (COLUMNNAME_ColumnSQL, ColumnSQL); } /** Get Column SQL. @return Virtual Column (r/o) */ public String getColumnSQL () { return (String)get_Value(COLUMNNAME_ColumnSQL); } /** EntityType AD_Reference_ID=389 */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entity Type. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entity Type. @return Dictionary Entity Type; Determines ownership and synchronization
*/ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Index_Column.java
1
请完成以下Java代码
public class ForkJoinCountTask extends RecursiveTask<Long> { /** * 阀值 */ private int threshold = 10; /** * 任务的开始值 */ private long start; /** * 任务的结束值 */ private long end; public ForkJoinCountTask(long start, long end) { this.start = start; this.end = end; } @Override protected Long compute() { if (end - start <= threshold) { long count = 0; for (int i = 0; i <= end - start; i++) { count = count + start + i; } System.out.println(Thread.currentThread().getName() + " 小计结果: " + count); return count; } else { // 如果任务大于阈值,就分裂成三个子任务计算
long slip = (end - start) / 3; ForkJoinCountTask oneTask = new ForkJoinCountTask(start, start + slip); ForkJoinCountTask twoTask = new ForkJoinCountTask(start + slip + 1, start + slip * 2); ForkJoinCountTask threeTask = new ForkJoinCountTask(start + slip * 2 + 1, end); // 提交子任务到框架去执行 invokeAll(oneTask, twoTask, threeTask); // 等待子任务执行完,得到其结果,并合并子任务 return oneTask.join() + twoTask.join() + threeTask.join(); } } public static void main(String[] args) { long start = System.currentTimeMillis(); ForkJoinPool pool = new ForkJoinPool(); // 生成一个计算任务,负责计算1+2+3+n ForkJoinCountTask countTask = new ForkJoinCountTask(1, 1000000); // 执行一个任务(同步执行,任务会阻塞在这里直到任务执行完成) pool.invoke(countTask); // 异常检查 if (countTask.isCompletedAbnormally()) { Throwable throwable = countTask.getException(); if (Objects.nonNull(throwable)) { System.out.println(throwable.getMessage()); } } // join方法是一个阻塞方法,会等待任务执行完成 System.out.println("计算为:" + countTask.join() + ", 耗时:" + (System.currentTimeMillis() - start) + "毫秒"); } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\ForkJoinCountTask.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentChangeHandler_Order implements DocumentChangeHandler<I_C_Order> { private final IOrderDAO orderDAO = Services.get(IOrderDAO.class); @NonNull private final CallOrderContractService callOrderContractService; @NonNull private final CallOrderService callOrderService; @NonNull private final CallOrderDetailRepo detailRepo; public DocumentChangeHandler_Order( @NonNull final CallOrderContractService callOrderContractService, @NonNull final CallOrderService callOrderService, @NonNull final CallOrderDetailRepo detailRepo) { this.callOrderContractService = callOrderContractService; this.callOrderService = callOrderService; this.detailRepo = detailRepo; } @Override public void onComplete(final I_C_Order order) { if (!callOrderService.isCallOrder(order)) { return; } final List<I_C_OrderLine> orderLines = orderDAO.retrieveOrderLines(order, I_C_OrderLine.class); for (final I_C_OrderLine callOrderLine : orderLines) { final FlatrateTermId callOrderContractId = callOrderContractService.validateCallOrderLine(callOrderLine, order); final UpsertCallOrderDetailRequest request = UpsertCallOrderDetailRequest.builder() .callOrderContractId(callOrderContractId) .orderLine(callOrderLine) .build(); callOrderService.handleCallOrderDetailUpsert(request);
} } @Override public void onReverse(final I_C_Order model) { throw new AdempiereException("Orders cannot be reversed!"); } @Override public void onReactivate(final I_C_Order order) { if (!callOrderService.isCallOrder(order)) { return; } final OrderId orderId = OrderId.ofRepoId(order.getC_Order_ID()); detailRepo.resetEnteredQtyForOrder(orderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\document\DocumentChangeHandler_Order.java
2
请完成以下Java代码
public class DbBulkOperation extends DbOperation { public DbBulkOperation() { } public DbBulkOperation(DbOperationType operationType, Class<? extends DbEntity> entityType, String statement, Object parameter) { this.operationType = operationType; this.entityType = entityType; this.statement = statement; this.parameter = parameter; } protected String statement; protected Object parameter; @Override public void recycle() { statement = null; parameter = null; super.recycle(); } public Object getParameter() { return parameter; } public void setParameter(Object parameter) { this.parameter = parameter; } public String getStatement() { return statement; } public void setStatement(String statement) { this.statement = statement; } public String toString() { return operationType + " "+ statement +" " +parameter; }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((parameter == null) ? 0 : parameter.hashCode()); result = prime * result + ((statement == null) ? 0 : statement.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DbBulkOperation other = (DbBulkOperation) obj; if (parameter == null) { if (other.parameter != null) return false; } else if (!parameter.equals(other.parameter)) return false; if (statement == null) { if (other.statement != null) return false; } else if (!statement.equals(other.statement)) return false; return true; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbBulkOperation.java
1
请完成以下Java代码
class Vertex { String label; Vertex(String label) { this.label = label; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((label == null) ? 0 : label.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vertex other = (Vertex) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (label == null) { if (other.label != null) return false;
} else if (!label.equals(other.label)) return false; return true; } @Override public String toString() { return label; } private Graph getOuterType() { return Graph.this; } } }
repos\tutorials-master\data-structures\src\main\java\com\baeldung\graph\Graph.java
1
请完成以下Java代码
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_QtyCUsPerTU.equals(parameter.getColumnName())) { final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule(); return getDefaultAvailableQtyToReceive(receiptSchedule); } else { return DEFAULT_VALUE_NOTAVAILABLE; } } @Override protected Stream<I_M_ReceiptSchedule> streamReceiptSchedulesToReceive() { return Stream.of(getM_ReceiptSchedule()); }
private I_M_ReceiptSchedule getM_ReceiptSchedule() { return getRecord(I_M_ReceiptSchedule.class); } @Override protected BigDecimal getEffectiveQtyToReceive(I_M_ReceiptSchedule rs) { if(p_QtyCUsPerTU == null || p_QtyCUsPerTU.signum() <= 0) { throw new FillMandatoryException(PARAM_QtyCUsPerTU); } return p_QtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveCUs_WithParam.java
1
请完成以下Java代码
public class MemberSuspectEvent extends MembershipEvent<MemberSuspectEvent> { private DistributedMember suspectMember; private String reason; /** * Constructs a new instance of {@link MemberSuspectEvent} initialized with the given {@link DistributionManager}. * * @param distributionManager {@link DistributionManager} used as the {@link #getSource() source} of this event; * must not be {@literal null}. * @throws IllegalArgumentException if {@link DistributionManager} is {@literal null}. * @see org.apache.geode.distributed.internal.DistributionManager */ public MemberSuspectEvent(DistributionManager distributionManager) { super(distributionManager); } /** * Returns an {@link Optional} {@link String reason} describing the suspicion of the peer member. * * @return an {@link Optional} {@link String reason} describing the suspicion of the peer member. * @see java.util.Optional */ public Optional<String> getReason() { return Optional.ofNullable(this.reason); } /** * Returns an {@link Optional} {@link DistributedMember} identified as the suspect in the {@link MembershipEvent}. * * @return an {@link Optional} {@link DistributedMember} identified as the suspect in the {@link MembershipEvent}. * @see org.apache.geode.distributed.DistributedMember * @see java.util.Optional */ public Optional<DistributedMember> getSuspectMember() { return Optional.ofNullable(this.suspectMember); } /** * Builder method used to configure the {@link String reason} describing the suspicion of * the {@link DistributedMember suspect member}. * * @param reason {@link String} describing the suspicion of the {@link DistributedMember peer member}; * may be {@literal null}. * @return this {@link MemberSuspectEvent}. * @see #getReason() */ public MemberSuspectEvent withReason(String reason) { this.reason = reason; return this;
} /** * Builder method used to configure the {@link DistributedMember peer member} that is the subject of the suspicion * {@link MembershipEvent}. * * @param suspectMember {@link DistributedMember peer member} that is being suspected; may be {@literal null}. * @return this {@link MemberSuspectEvent}. * @see #getSuspectMember() */ public MemberSuspectEvent withSuspect(DistributedMember suspectMember) { this.suspectMember = suspectMember; return this; } /** * @inheritDoc */ @Override public final Type getType() { return Type.MEMBER_SUSPECT; } }
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\support\MemberSuspectEvent.java
1
请完成以下Java代码
private String getOrLoadLotNoFromSeq(final @NonNull I_M_ReceiptSchedule receiptSchedule) { if (!lotNumberFromSeq.isPresent()) { final I_C_DocType docType = docTypeDAO.getById(DocTypeId.ofRepoId(receiptSchedule.getC_DocType_ID())); final DocSequenceId lotNoSequenceId = DocSequenceId.ofRepoIdOrNull(docType.getLotNo_Sequence_ID()); if (lotNoSequenceId != null) { lotNumberFromSeq = lotNumberBL .getAndIncrementLotNo(LotNoContext.builder() .sequenceId(lotNoSequenceId) .clientId(ClientId.ofRepoId(receiptSchedule.getAD_Client_ID())) .build()); } } return lotNumberFromSeq.orElse(null); } private void setAttributeBBD(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final IAttributeStorage huAttributes) { if (huAttributes.hasAttribute(AttributeConstants.ATTR_BestBeforeDate) && huAttributes.getValueAsLocalDate(AttributeConstants.ATTR_BestBeforeDate) == null && huAttributesBL.isAutomaticallySetBestBeforeDate() && receiptSchedule.getMovementDate() != null ) { final LocalDate bestBeforeDate = computeBestBeforeDate(ProductId.ofRepoId(receiptSchedule.getM_Product_ID()), TimeUtil.asLocalDate(receiptSchedule.getMovementDate())); if (bestBeforeDate != null) { huAttributes.setValue(AttributeConstants.ATTR_BestBeforeDate, bestBeforeDate); huAttributes.saveChangesIfNeeded(); } } }
private void setVendorValueFromReceiptSchedule(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final IAttributeStorage huAttributes) { if (huAttributes.hasAttribute(AttributeConstants.ATTR_Vendor_BPartner_ID) && huAttributes.getValueAsInt(AttributeConstants.ATTR_Vendor_BPartner_ID) > -1) { final int bpId = receiptSchedule.getC_BPartner_ID(); if (bpId > 0) { huAttributes.setValue(AttributeConstants.ATTR_Vendor_BPartner_ID, bpId); huAttributes.setSaveOnChange(true); huAttributes.saveChangesIfNeeded(); } } } @Nullable LocalDate computeBestBeforeDate(@NonNull final ProductId productId, final @NonNull LocalDate datePromised) { final int guaranteeDaysMin = productDAO.getProductGuaranteeDaysMinFallbackProductCategory(productId); if (guaranteeDaysMin <= 0) { return null; } return datePromised.plusDays(guaranteeDaysMin); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\ReceiptScheduleBasedProcess.java
1
请完成以下Java代码
public class UserSpecification implements Specification<User> { private SpecSearchCriteria criteria; public UserSpecification(final SpecSearchCriteria criteria) { super(); this.criteria = criteria; } public SpecSearchCriteria getCriteria() { return criteria; } @Override public Predicate toPredicate(final Root<User> root, final CriteriaQuery<?> query, final CriteriaBuilder builder) { switch (criteria.getOperation()) { case EQUALITY: return builder.equal(root.get(criteria.getKey()), criteria.getValue()); case NEGATION: return builder.notEqual(root.get(criteria.getKey()), criteria.getValue()); case GREATER_THAN: return builder.greaterThan(root.get(criteria.getKey()), criteria.getValue().toString()); case LESS_THAN:
return builder.lessThan(root.get(criteria.getKey()), criteria.getValue().toString()); case LIKE: return builder.like(root.get(criteria.getKey()), criteria.getValue().toString()); case STARTS_WITH: return builder.like(root.get(criteria.getKey()), criteria.getValue() + "%"); case ENDS_WITH: return builder.like(root.get(criteria.getKey()), "%" + criteria.getValue()); case CONTAINS: return builder.like(root.get(criteria.getKey()), "%" + criteria.getValue() + "%"); default: return null; } } }
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\dao\UserSpecification.java
1
请在Spring Boot框架中完成以下Java代码
ExecutableElement getBindConstructor() { if (this.boundConstructors.isEmpty()) { return findBoundConstructor(); } if (this.boundConstructors.size() == 1) { return this.boundConstructors.get(0); } return null; } private ExecutableElement findBoundConstructor() { ExecutableElement boundConstructor = null; for (ExecutableElement candidate : this.constructors) { if (!candidate.getParameters().isEmpty()) { if (boundConstructor != null) { return null; } boundConstructor = candidate; } } return boundConstructor; } static Bindable of(TypeElement type, MetadataGenerationEnvironment env) { List<ExecutableElement> constructors = ElementFilter.constructorsIn(type.getEnclosedElements()); List<ExecutableElement> boundConstructors = getBoundConstructors(type, env, constructors); return new Bindable(type, constructors, boundConstructors); } private static List<ExecutableElement> getBoundConstructors(TypeElement type, MetadataGenerationEnvironment env, List<ExecutableElement> constructors) { ExecutableElement bindConstructor = deduceBindConstructor(type, constructors, env); if (bindConstructor != null) {
return Collections.singletonList(bindConstructor); } return constructors.stream().filter(env::hasConstructorBindingAnnotation).toList(); } private static ExecutableElement deduceBindConstructor(TypeElement type, List<ExecutableElement> constructors, MetadataGenerationEnvironment env) { if (constructors.size() == 1) { ExecutableElement candidate = constructors.get(0); if (!candidate.getParameters().isEmpty() && !env.hasAutowiredAnnotation(candidate)) { if (type.getNestingKind() == NestingKind.MEMBER && candidate.getModifiers().contains(Modifier.PRIVATE)) { return null; } return candidate; } } return null; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\PropertyDescriptorResolver.java
2
请完成以下Java代码
public void set(final K key, final V value) { List<V> values = map.get(key); if (values == null) { values = new ArrayList<V>(); map.put(key, values); } else { values.clear(); } values.add(value); } @Override public List<V> remove(final Object key) { return map.remove(key); } @Override public void putAll(Map<? extends K, ? extends List<V>> m) { map.putAll(m); } @Override public void clear() { map.clear();
} @Override public Set<K> keySet() { return map.keySet(); } @Override public Collection<List<V>> values() { return map.values(); } @Override public Set<Map.Entry<K, List<V>>> entrySet() { return map.entrySet(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MultiValueMap.java
1
请完成以下Java代码
public String getCaption(final String adLanguage) { return caption.translate(adLanguage); } public KPIId getKPIId() { if (kpiSupplier == null) { throw new EntityNotFoundException("No KPI defined for " + this); } else { return kpiSupplier.getKpiId(); } }
public KPI getKPI() { final KPI kpi = kpiSupplier == null ? null : kpiSupplier.get(); if (kpi == null) { throw new EntityNotFoundException("No KPI defined for " + this); } return kpi; } public KPITimeRangeDefaults getTimeRangeDefaults() { final KPI kpi = getKPI(); return timeRangeDefaults.compose(kpi.getTimeRangeDefaults()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboardItem.java
1
请完成以下Java代码
public int getT_Integer() { return get_ValueAsInt(COLUMNNAME_T_Integer); } @Override public void setT_Number (final @Nullable BigDecimal T_Number) { set_Value (COLUMNNAME_T_Number, T_Number); } @Override public BigDecimal getT_Number() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setT_Qty (final @Nullable BigDecimal T_Qty) { set_Value (COLUMNNAME_T_Qty, T_Qty); } @Override public BigDecimal getT_Qty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setT_Time (final @Nullable java.sql.Timestamp T_Time) { set_Value (COLUMNNAME_T_Time, T_Time); } @Override public java.sql.Timestamp getT_Time() { return get_ValueAsTimestamp(COLUMNNAME_T_Time); } @Override public void setTest_ID (final int Test_ID) { if (Test_ID < 1) set_ValueNoCheck (COLUMNNAME_Test_ID, null); else set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID); } @Override public int getTest_ID() { return get_ValueAsInt(COLUMNNAME_Test_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java
1
请完成以下Java代码
private boolean isGranted(String role) { Authentication auth = getAuthentication(); if (this.rolePrefix != null && role != null && !role.startsWith(this.rolePrefix)) { role = this.rolePrefix + role; } if ((auth == null) || (auth.getPrincipal() == null)) { return false; } Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); if (authorities == null) { return false; } for (GrantedAuthority grantedAuthority : authorities) { if (role.equals(grantedAuthority.getAuthority())) { return true; } } return false; } /** * Simple searches for an exactly matching * {@link org.springframework.security.core.GrantedAuthority#getAuthority()}. * <p> * Will always return <code>false</code> if the <code>SecurityContextHolder</code> * contains an <code>Authentication</code> with <code>null</code> * <code>principal</code> and/or <code>GrantedAuthority[]</code> objects. * @param role the <code>GrantedAuthority</code><code>String</code> representation to * check for * @return <code>true</code> if an <b>exact</b> (case sensitive) matching granted * authority is located, <code>false</code> otherwise */ @Override public boolean isUserInRole(String role) {
return isGranted(role); } @Override public String toString() { return "SecurityContextHolderAwareRequestWrapper[ " + getRequest() + "]"; } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestWrapper.java
1
请完成以下Java代码
private void invokeEventListenerWithLogging( @NonNull final IEventListener eventListener, @NonNull final Event event) { try (final EventLogEntryCollector ignored = EventLogEntryCollector.createThreadLocalForEvent(event)) { try { eventListener.onEvent(this, event); } catch (final RuntimeException ex) { if (!Adempiere.isUnitTestMode()) { final EventLogUserService eventLogUserService = SpringContextHolder.instance.getBean(EventLogUserService.class); eventLogUserService .newErrorLogEntry(eventListener.getClass(), ex) .createAndStore(); } else { logger.warn("Got exception while invoking eventListener={} with event={}", eventListener, event, ex); } } } } @Override public EventBusStats getStats() {
return micrometerEventBusStatsCollector.snapshot(); } private void enqueueEvent0(final Event event) { if (Type.LOCAL == topic.getType()) { eventEnqueuer.enqueueLocalEvent(event, topic); } else { eventEnqueuer.enqueueDistributedEvent(event, topic); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBus.java
1
请在Spring Boot框架中完成以下Java代码
public class AD_Attachment_MultiRef { private final ArchiveFileNameService archiveFileNameService; private final IOrderDAO orderDAO = Services.get(IOrderDAO.class); public AD_Attachment_MultiRef(@NonNull final ArchiveFileNameService archiveFileNameService) { this.archiveFileNameService = archiveFileNameService; } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW }, ifColumnsChanged = { I_AD_Attachment_MultiRef.COLUMNNAME_AD_Table_ID, I_AD_Attachment_MultiRef.COLUMNNAME_Record_ID }) public void overrideFileName(@NonNull final I_AD_Attachment_MultiRef record) { final TableRecordReference tableRecordReference = TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()); final I_AD_AttachmentEntry attachmentEntry = record.getAD_AttachmentEntry(); final String fileExtension = Optional.ofNullable(getFileExtension(attachmentEntry.getFileName())) .map(extension -> "." + extension)
.orElse(null); final String fileBaseName = getFileBaseName(attachmentEntry.getFileName()); if (tableRecordReference.getTableName().equals(I_C_Order.Table_Name)) { final I_C_Order order = orderDAO.getById(OrderId.ofRepoId(record.getRecord_ID())); final ArchiveFileNameService.ComputeFileNameRequest computeFileNameRequest = ArchiveFileNameService.ComputeFileNameRequest.builder() .docTypeId(DocTypeId.ofRepoIdOrNull(coalesce(order.getC_DocType_ID(), order.getC_DocTypeTarget_ID()))) .recordReference(tableRecordReference) .documentNo(order.getDocumentNo()) .fileExtension(fileExtension) .suffix(fileBaseName) .build(); record.setFileName_Override(archiveFileNameService.computeFileName(computeFileNameRequest)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\AD_Attachment_MultiRef.java
2
请完成以下Java代码
public IoSpecification getIoSpecification() { return ioSpecificationChild.getChild(this); } public void setIoSpecification(IoSpecification ioSpecification) { ioSpecificationChild.setChild(this, ioSpecification); } public Collection<Property> getProperties() { return propertyCollection.get(this); } public Collection<DataInputAssociation> getDataInputAssociations() { return dataInputAssociationCollection.get(this); }
public Collection<DataOutputAssociation> getDataOutputAssociations() { return dataOutputAssociationCollection.get(this); } public Collection<ResourceRole> getResourceRoles() { return resourceRoleCollection.get(this); } public LoopCharacteristics getLoopCharacteristics() { return loopCharacteristicsChild.getChild(this); } public void setLoopCharacteristics(LoopCharacteristics loopCharacteristics) { loopCharacteristicsChild.setChild(this, loopCharacteristics); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ActivityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class TemperatureMonitor { private final ApplicationEventPublisher applicationEventPublisher; public TemperatureMonitor(ApplicationEventPublisher applicationEventPublisher) { Assert.notNull(applicationEventPublisher, "ApplicationEventPublisher is required"); this.applicationEventPublisher = applicationEventPublisher; } @ContinuousQuery(name = "BoilingTemperatureMonitor", query = "SELECT * FROM /TemperatureReadings WHERE temperature >= 212") public void boilingTemperatureReadings(CqEvent event) { Optional.ofNullable(event) .map(CqEvent::getNewValue) .filter(TemperatureReading.class::isInstance) .map(TemperatureReading.class::cast) .map(it -> new BoilingTemperatureEvent(this, it)) .ifPresent(this.applicationEventPublisher::publishEvent);
} @ContinuousQuery(name = "FreezingTemperatureMonitor", query = "SELECT * FROM /TemperatureReadings WHERE temperature <= 32") public void freezingTemperatureReadings(CqEvent event) { Optional.ofNullable(event) .map(CqEvent::getNewValue) .filter(TemperatureReading.class::isInstance) .map(TemperatureReading.class::cast) .map(it -> new FreezingTemperatureEvent(this, it)) .ifPresent(this.applicationEventPublisher::publishEvent); } } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\boot\actuator\src\main\java\example\app\temp\service\TemperatureMonitor.java
2
请完成以下Java代码
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; CustomUserDetails that = (CustomUserDetails) o; return firstName.equals(that.firstName) && lastName.equals(that.lastName) && email.equals(that.email); } @Override public int hashCode() { return Objects.hash(super.hashCode(), firstName, lastName, email); } public static class Builder { private String firstName; private String lastName; private String email; private String username; private String password; private Collection<? extends GrantedAuthority> authorities; public Builder withFirstName(String firstName) { this.firstName = firstName; return this; } public Builder withLastName(String lastName) { this.lastName = lastName; return this; } public Builder withEmail(String email) {
this.email = email; return this; } public Builder withUsername(String username) { this.username = username; return this; } public Builder withPassword(String password) { this.password = password; return this; } public Builder withAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; return this; } public CustomUserDetails build() { return new CustomUserDetails(this); } } }
repos\tutorials-master\spring-security-modules\spring-security-web-thymeleaf\src\main\java\com\baeldung\customuserdetails\CustomUserDetails.java
1
请完成以下Java代码
public ImmutableList<DocumentId> toImmutableList() { assertNotAll(); if (documentIds.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(documentIds); } @NonNull public <T> ImmutableList<T> toImmutableList(@NonNull final Function<DocumentId, T> mapper) { assertNotAll(); if (documentIds.isEmpty()) { return ImmutableList.of(); } return documentIds.stream().map(mapper).collect(ImmutableList.toImmutableList()); } public Set<Integer> toIntSet() { return toSet(DocumentId::toInt); } public <ID extends RepoIdAware> ImmutableSet<ID> toIds(@NonNull final Function<Integer, ID> idMapper) { return toSet(idMapper.compose(DocumentId::toInt)); } public <ID extends RepoIdAware> ImmutableSet<ID> toIdsFromInt(@NonNull final IntFunction<ID> idMapper) { return toSet(documentId -> idMapper.apply(documentId.toInt())); } /** * Similar to {@link #toIds(Function)} but this returns a list, so it preserves the order */ public <ID extends RepoIdAware> ImmutableList<ID> toIdsList(@NonNull final Function<Integer, ID> idMapper) { return toImmutableList(idMapper.compose(DocumentId::toInt)); } public Set<String> toJsonSet() { if (all) { return ALL_StringSet; } return toSet(DocumentId::toJson); } public SelectionSize toSelectionSize() { if (isAll()) { return SelectionSize.ofAll(); } return SelectionSize.ofSize(size()); } public DocumentIdsSelection addAll(@NonNull final DocumentIdsSelection documentIdsSelection) { if (this.isEmpty()) { return documentIdsSelection;
} else if (documentIdsSelection.isEmpty()) { return this; } if (this.all) { return this; } else if (documentIdsSelection.all) { return documentIdsSelection; } final ImmutableSet<DocumentId> combinedIds = Stream.concat(this.stream(), documentIdsSelection.stream()).collect(ImmutableSet.toImmutableSet()); final DocumentIdsSelection result = DocumentIdsSelection.of(combinedIds); if (this.equals(result)) { return this; } else if (documentIdsSelection.equals(result)) { return documentIdsSelection; } else { return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentIdsSelection.java
1
请完成以下Java代码
public String delete() { return "delete.html"; } @Route(value = "/another-route-example", method = HttpMethod.GET) public String anotherGet() { return "get.html"; } @Route(value = "/allmatch-route-example") public String allmatch() { return "allmatch.html"; } @Route(value = "/triggerInternalServerError") public void triggerInternalServerError() { int x = 1 / 0; } @Route(value = "/triggerBaeldungException") public void triggerBaeldungException() throws BaeldungException { throw new BaeldungException("Foobar Exception to threat differently"); } @Route(value = "/user/foo") public void urlCoveredByNarrowedWebhook(Response response) {
response.text("Check out for the WebHook covering '/user/*' in the logs"); } @GetRoute("/load-configuration-in-a-route") public void loadConfigurationInARoute(Response response) { String authors = WebContext.blade() .env("app.authors", "Unknown authors"); log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors); response.render("index.html"); } @GetRoute("/template-output-test") public void templateOutputTest(Request request, Response response) { request.attribute("name", "Blade"); response.render("template-output-test.html"); } }
repos\tutorials-master\web-modules\blade\src\main\java\com\baeldung\blade\sample\RouteExampleController.java
1
请完成以下Java代码
public class EventSubscriptionInstanceHandler implements MigratingDependentInstanceParseHandler<MigratingActivityInstance, List<EventSubscriptionEntity>> { public static final Set<String> SUPPORTED_EVENT_TYPES = new HashSet<String>(Arrays.asList(EventType.MESSAGE.name(), EventType.SIGNAL.name(), EventType.CONDITONAL.name())); @Override public void handle(MigratingInstanceParseContext parseContext, MigratingActivityInstance owningInstance, List<EventSubscriptionEntity> elements) { Map<String, EventSubscriptionDeclaration> targetDeclarations = getDeclarationsByTriggeringActivity(owningInstance.getTargetScope()); for (EventSubscriptionEntity eventSubscription : elements) { if (!getSupportedEventTypes().contains(eventSubscription.getEventType())) { // ignore unsupported event subscriptions continue; } MigrationInstruction migrationInstruction = parseContext.findSingleMigrationInstruction(eventSubscription.getActivityId()); ActivityImpl targetActivity = parseContext.getTargetActivity(migrationInstruction); if (targetActivity != null && owningInstance.migratesTo(targetActivity.getEventScope())) { // the event subscription is migrated EventSubscriptionDeclaration targetDeclaration = targetDeclarations.remove(targetActivity.getId()); owningInstance.addMigratingDependentInstance( new MigratingEventSubscriptionInstance(eventSubscription, targetActivity, migrationInstruction.isUpdateEventTrigger(), targetDeclaration)); } else { // the event subscription will be removed owningInstance.addRemovingDependentInstance(new MigratingEventSubscriptionInstance(eventSubscription)); } parseContext.consume(eventSubscription); } if (owningInstance.migrates()) { addEmergingEventSubscriptions(owningInstance, targetDeclarations); } }
protected Set<String> getSupportedEventTypes() { return SUPPORTED_EVENT_TYPES; } protected Map<String, EventSubscriptionDeclaration> getDeclarationsByTriggeringActivity(ScopeImpl eventScope) { Map<String, EventSubscriptionDeclaration> declarations = EventSubscriptionDeclaration.getDeclarationsForScope(eventScope); return new HashMap<String, EventSubscriptionDeclaration>(declarations); } protected void addEmergingEventSubscriptions(MigratingActivityInstance owningInstance, Map<String, EventSubscriptionDeclaration> targetDeclarations) { for (String key : targetDeclarations.keySet()) { // the event subscription will be created EventSubscriptionDeclaration declaration = targetDeclarations.get(key); if (!declaration.isStartEvent()) { owningInstance.addEmergingDependentInstance(new MigratingEventSubscriptionInstance(declaration)); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\EventSubscriptionInstanceHandler.java
1
请在Spring Boot框架中完成以下Java代码
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { SecurityUser user = getCurrentUser(); if (user != null && !user.isSystemAdmin()) { try { if (!rateLimitService.checkRateLimit(LimitedApi.REST_REQUESTS_PER_TENANT, user.getTenantId())) { rateLimitExceeded(EntityType.TENANT, response); return; } } catch (TenantProfileNotFoundException e) { log.debug("[{}] Failed to lookup tenant profile", user.getTenantId()); errorResponseHandler.handle(new BadCredentialsException("Failed to lookup tenant profile"), response); return; } if (user.isCustomerUser()) { if (!rateLimitService.checkRateLimit(LimitedApi.REST_REQUESTS_PER_CUSTOMER, user.getTenantId(), user.getCustomerId())) { rateLimitExceeded(EntityType.CUSTOMER, response); return; } } } chain.doFilter(request, response); }
@Override protected boolean shouldNotFilterAsyncDispatch() { return false; } @Override protected boolean shouldNotFilterErrorDispatch() { return false; } private void rateLimitExceeded(EntityType type, HttpServletResponse response) { errorResponseHandler.handle(new TbRateLimitsException(type), response); } protected SecurityUser getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.getPrincipal() instanceof SecurityUser) { return (SecurityUser) authentication.getPrincipal(); } else { return null; } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\config\RateLimitProcessingFilter.java
2
请在Spring Boot框架中完成以下Java代码
public Builder id(String id) { this.id = id; return this; } /** * Use this {@link Consumer} to modify the set of query parameters * * No parameter should be URL-encoded as this will be done when the request is * sent * @param parametersConsumer the {@link Consumer} * @return the {@link Builder} for further configurations */ public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; } /** * Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use
* @return the {@link Builder} for further configurations * @since 5.8 */ public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutRequest} * @return a constructed {@link Saml2LogoutRequest} */ public Saml2LogoutRequest build() { return new Saml2LogoutRequest(this.location, this.binding, this.parameters, this.id, this.registration.getRegistrationId(), this.encoder); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\Saml2LogoutRequest.java
2
请在Spring Boot框架中完成以下Java代码
public class HostKeyConfig { /** * Task https://github.com/metasfresh/metasfresh/issues/1274 */ private static final String PRINTING_WEBUI_HOST_KEY_STORAGE_MODE = "de.metas.printing.webui.HostKeyStorageMode"; @PostConstruct public void setupHostKeyStorage() { Services.registerService(IHttpSessionProvider.class, new SpringHttpSessionProvider()); final IHostKeyBL hostKeyBL = Services.get(IHostKeyBL.class); // when this method is called, there is not DB connection yet. // so provide the storage implementation as a supplier when it's actually needed and when (hopefully) // the system is ready hostKeyBL.setHostKeyStorage(() -> { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final IHostKeyStorage hostKeyStorageImpl; final String hostKeyStorage = sysConfigBL.getValue(PRINTING_WEBUI_HOST_KEY_STORAGE_MODE, "cookies"); if (hostKeyStorage.toLowerCase().startsWith("cookie".toLowerCase())) { hostKeyStorageImpl = new HttpCookieHostKeyStorage(); } else { // https://github.com/metasfresh/metasfresh/issues/1274 hostKeyStorageImpl = new SessionRemoteHostStorage(); }
return hostKeyStorageImpl; }); } private static final class SpringHttpSessionProvider implements IHttpSessionProvider { @Override public HttpServletRequest getCurrentRequest() { return getRequestAttributes().getRequest(); } @Override public HttpServletResponse getCurrentResponse() { return getRequestAttributes().getResponse(); } private ServletRequestAttributes getRequestAttributes() { final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes instanceof ServletRequestAttributes) { return (ServletRequestAttributes)requestAttributes; } else { throw new IllegalStateException("Not called in the context of an HTTP request (" + requestAttributes + ")"); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\HostKeyConfig.java
2
请完成以下Java代码
public SqlAndParams build() { final String sql = this.sql != null ? this.sql.toString() : ""; final Object[] sqlParamsArray = sqlParams != null ? sqlParams.toArray() : null; return new SqlAndParams(sql, sqlParamsArray); } public Builder clear() { sql = null; sqlParams = null; return this; } public boolean isEmpty() { return length() <= 0 && !hasParameters(); } public int length() { return sql != null ? sql.length() : 0; } public boolean hasParameters() { return sqlParams != null && !sqlParams.isEmpty(); } public int getParametersCount() { return sqlParams != null ? sqlParams.size() : 0; } public Builder appendIfHasParameters(@NonNull final CharSequence sql) { if (hasParameters()) { return append(sql); } else { return this; } } public Builder appendIfNotEmpty(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { if (!isEmpty()) { append(sql, sqlParams); } return this; } public Builder append(@NonNull final CharSequence sql, @Nullable final Object... sqlParams) { final List<Object> sqlParamsList = sqlParams != null && sqlParams.length > 0 ? Arrays.asList(sqlParams) : null; return append(sql, sqlParamsList);
} public Builder append(@NonNull final CharSequence sql, @Nullable final List<Object> sqlParams) { if (sql.length() > 0) { if (this.sql == null) { this.sql = new StringBuilder(); } this.sql.append(sql); } if (sqlParams != null && !sqlParams.isEmpty()) { if (this.sqlParams == null) { this.sqlParams = new ArrayList<>(); } this.sqlParams.addAll(sqlParams); } return this; } public Builder append(@NonNull final SqlAndParams other) { return append(other.sql, other.sqlParams); } public Builder append(@NonNull final SqlAndParams.Builder other) { return append(other.sql, other.sqlParams); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParams.java
1
请完成以下Java代码
static class ClickhouseJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements JdbcConnectionDetails { private static final JdbcUrlBuilder jdbcUrlBuilder = new JdbcUrlBuilder("clickhouse", 8123); private final ClickHouseEnvironment environment; private final String jdbcUrl; ClickhouseJdbcDockerComposeConnectionDetails(RunningService service) { super(service); this.environment = new ClickHouseEnvironment(service.env()); this.jdbcUrl = jdbcUrlBuilder.build(service, this.environment.getDatabase()); } @Override public String getUsername() { return this.environment.getUsername();
} @Override public String getPassword() { return this.environment.getPassword(); } @Override public String getJdbcUrl() { return this.jdbcUrl; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\ClickHouseJdbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public String getType() { return TYPE; } @Override public void execute(Job job, String configuration, ExecutionEntity execution, CommandContext commandContext) { String nestedActivityId = TimerEventHandler.getActivityIdFromConfiguration(configuration); ActivityImpl intermediateEventActivity = execution.getProcessDefinition().findActivity(nestedActivityId); if (intermediateEventActivity == null) { throw new ActivitiException("Error while firing timer: intermediate event activity " + nestedActivityId + " not found"); } try { if (commandContext.getEventDispatcher().isEnabled()) { commandContext.getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.TIMER_FIRED, job), EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG); }
if (!execution.getActivity().getId().equals(intermediateEventActivity.getId())) { execution.setActivity(intermediateEventActivity); } execution.signal(null, null); } catch (RuntimeException e) { LogMDC.putMDCExecution(execution); LOGGER.error("exception during timer execution", e); LogMDC.clear(); throw e; } catch (Exception e) { LogMDC.putMDCExecution(execution); LOGGER.error("exception during timer execution", e); LogMDC.clear(); throw new ActivitiException("exception during timer execution: " + e.getMessage(), e); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerCatchIntermediateEventJobHandler.java
1
请完成以下Java代码
private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } /** * Allows selective use of saved requests for a subset of requests. By default any * request will be cached by the {@code saveRequest} method. * <p> * If set, only matching requests will be cached. * @param requestMatcher a request matching strategy which defines which requests * should be cached. */ public void setRequestMatcher(RequestMatcher requestMatcher) { this.requestMatcher = requestMatcher; } /** * If <code>true</code>, indicates that it is permitted to store the target URL and * exception information in a new <code>HttpSession</code> (the default). In * situations where you do not wish to unnecessarily create <code>HttpSession</code>s * - because the user agent will know the failed URL, such as with BASIC or Digest * authentication - you may wish to set this property to <code>false</code>. */ public void setCreateSessionAllowed(boolean createSessionAllowed) { this.createSessionAllowed = createSessionAllowed; }
/** * If the {@code sessionAttrName} property is set, the request is stored in the * session using this attribute name. Default is "SPRING_SECURITY_SAVED_REQUEST". * @param sessionAttrName a new session attribute name. * @since 4.2.1 */ public void setSessionAttrName(String sessionAttrName) { this.sessionAttrName = sessionAttrName; } /** * Specify the name of a query parameter that is added to the URL that specifies the * request cache should be checked in * {@link #getMatchingRequest(HttpServletRequest, HttpServletResponse)} * @param matchingRequestParameterName the parameter name that must be in the request * for {@link #getMatchingRequest(HttpServletRequest, HttpServletResponse)} to check * the session. Default is "continue". */ public void setMatchingRequestParameterName(String matchingRequestParameterName) { this.matchingRequestParameterName = matchingRequestParameterName; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\HttpSessionRequestCache.java
1
请完成以下Java代码
public boolean isLongOperation() { return false; } @Override public boolean isHideWhenNotRunnable() { return true; // hide when not runnable - backward compatibility } protected final String getColumnName() { final GridField gridField = getGridField(); if (gridField == null) { return null; } final String columnName = gridField.getColumnName(); return columnName; } protected final Object getFieldValue() { final IContextMenuActionContext context = getContext(); if (context == null) { return null; } // // Get value when in Grid Mode final VTable vtable = context.getVTable(); final int row = context.getViewRow(); final int column = context.getViewColumn(); if (vtable != null && row >= 0 && column >= 0) { final Object value = vtable.getValueAt(row, column); return value; } // Get value when in single mode else { final GridField gridField = getGridField(); if (gridField == null) { return null; } final Object value = gridField.getValue(); return value; } } protected final GridController getGridController() { final IContextMenuActionContext context = getContext(); if (context == null) { return null; } final VTable vtable = context.getVTable(); final Component comp; if (vtable != null) { comp = vtable; } else {
final VEditor editor = getEditor(); if (editor instanceof Component) { comp = (Component)editor; } else { comp = null; } } Component p = comp; while (p != null) { if (p instanceof GridController) { return (GridController)p; } p = p.getParent(); } return null; } protected final boolean isGridMode() { final GridController gc = getGridController(); if (gc == null) { return false; } final boolean gridMode = !gc.isSingleRow(); return gridMode; } @Override public KeyStroke getKeyStroke() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\AbstractContextMenuAction.java
1
请在Spring Boot框架中完成以下Java代码
public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } @ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @ApiModelProperty(example = "node1") public String getLockOwner() { return lockOwner; } public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; }
@ApiModelProperty(example = "2023-06-03T22:05:05.474+0000") public Date getLockExpirationTime() { return lockExpirationTime; } public void setLockExpirationTime(Date lockExpirationTime) { this.lockExpirationTime = lockExpirationTime; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobResponse.java
2
请完成以下Java代码
public Iterator<I_C_DunningDoc_Line_Source> retrieveDunningDocLineSourcesToWriteOff(final IDunningContext dunningContext) { final List<Object> params = new ArrayList<>(); final StringBuilder whereClause = new StringBuilder(); whereClause.append(I_C_DunningDoc_Line_Source.COLUMNNAME_Processed).append("=?"); params.add(true); whereClause.append(" AND ").append(I_C_DunningDoc_Line_Source.COLUMNNAME_IsWriteOff).append("=?"); params.add(true); whereClause.append(" AND ").append(I_C_DunningDoc_Line_Source.COLUMNNAME_IsWriteOffApplied).append("=?"); params.add(false); return new Query(dunningContext.getCtx(), I_C_DunningDoc_Line_Source.Table_Name, whereClause.toString(), dunningContext.getTrxName()) .setParameters(params) .setOrderBy(I_C_DunningDoc_Line_Source.COLUMNNAME_C_DunningDoc_Line_Source_ID) .setRequiredAccess(Access.WRITE) // in order to write off, we need to update the C_DunningDoc_Line_Source .setOption(Query.OPTION_IteratorBufferSize, 1000) // reducing the number of selects by increasing the buffer/page size .iterate(I_C_DunningDoc_Line_Source.class); } /** * Deletes all active, unprocessed candidates of the given level via DELETE sql statment. * * @param context * @param dunningLevel * @return the number of deleted candidates */ @Override public int deleteNotProcessedCandidates(final IDunningContext context, final I_C_DunningLevel dunningLevel) { final String deleteSQL = "DELETE FROM " + I_C_Dunning_Candidate.Table_Name + " WHERE " + I_C_Dunning_Candidate.COLUMNNAME_IsActive + "='Y' AND " + I_C_Dunning_Candidate.COLUMNNAME_AD_Client_ID + "=? AND " + I_C_Dunning_Candidate.COLUMNNAME_Processed + "='N' AND " + I_C_Dunning_Candidate.COLUMNNAME_C_DunningLevel_ID + "=?"; final int[] result = { 0 };
Services.get(ITrxManager.class).run(context.getTrxName(), context.getTrxRunnerConfig(), new TrxRunnable() { @Override public void run(final String localTrxName) { result[0] = DB.executeUpdateAndThrowExceptionOnFail(deleteSQL, new Object[] { Env.getAD_Client_ID(context.getCtx()), dunningLevel.getC_DunningLevel_ID() }, localTrxName); } }); return result[0]; } @Override public List<I_C_Dunning_Candidate> retrieveProcessedDunningCandidatesForRecord(final Properties ctx, final int tableId, final int recordId, final String trxName) { final StringBuilder whereClause = new StringBuilder(); whereClause.append(I_C_Dunning_Candidate.COLUMNNAME_AD_Table_ID).append("=?") .append(" AND ") .append(I_C_Dunning_Candidate.COLUMNNAME_Record_ID).append("=?") .append(" AND ") .append(I_C_Dunning_Candidate.COLUMNNAME_IsDunningDocProcessed).append("='Y'"); return new Query(ctx, I_C_Dunning_Candidate.Table_Name, whereClause.toString(), trxName) .setParameters(tableId, recordId) .list(I_C_Dunning_Candidate.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningDAO.java
1
请完成以下Spring Boot application配置
com.baeldung.evaluation.model=bespoke-minicheck spring.ai.ollama.chat.options.model=llama3.3 spring.ai.ollama.embedding.options.model=nomic-emb
ed-text spring.ai.ollama.init.pull-model-strategy=when_missing
repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\resources\application-evaluator.properties
2
请完成以下Java代码
private void generateRecomputeTagIfNotSet() { // Do nothing if the recompute tag was already generated if (!InvoiceCandRecomputeTag.isNull(_recomputeTag)) { return; } // Use the recompute tag which was suggested if (!InvoiceCandRecomputeTag.isNull(_recomputeTagToUseForTagging)) { _recomputeTag = _recomputeTagToUseForTagging; return; } // Generate a new recompute tag _recomputeTag = invoiceCandDAO.generateNewRecomputeTag(); } /** * @return recompute tag; never returns null */ final InvoiceCandRecomputeTag getRecomputeTag() { Check.assumeNotNull(_recomputeTag, "_recomputeTag not null"); return _recomputeTag; } @Override public InvoiceCandRecomputeTagger setLockedBy(final ILock lockedBy) { this._lockedBy = lockedBy; return this; } /* package */ILock getLockedBy() { return _lockedBy; } @Override public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag) { _taggedWith = tag; return this; }
@Override public InvoiceCandRecomputeTagger setTaggedWithNoTag() { return setTaggedWith(InvoiceCandRecomputeTag.NULL); } @Override public IInvoiceCandRecomputeTagger setTaggedWithAnyTag() { return setTaggedWith(null); } /* package */ @Nullable InvoiceCandRecomputeTag getTaggedWith() { return _taggedWith; } @Override public InvoiceCandRecomputeTagger setLimit(final int limit) { this._limit = limit; return this; } /* package */int getLimit() { return _limit; } @Override public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds) { this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds; } @Override @Nullable public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds() { return onlyInvoiceCandidateIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java
1
请在Spring Boot框架中完成以下Java代码
public Object deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; GZIPInputStream gzip = null; try { bos = new ByteArrayOutputStream(); byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer( new String(bytes));; bis = new ByteArrayInputStream(compressed); gzip = new GZIPInputStream(bis); byte[] buff = new byte[BUFFER_SIZE]; int n; // uncompress while ((n = gzip.read(buff, 0, BUFFER_SIZE)) > 0) { bos.write(buff, 0, n); } //deserialize Object result = jacksonRedisSerializer.deserialize(bos.toByteArray()); return result;
} catch (Exception e) { throw new SerializationException("Gzip deserizelie error", e); } finally { IOUtils.closeQuietly(bos); IOUtils.closeQuietly(bis); IOUtils.closeQuietly(gzip); } } private static JacksonRedisSerializer<User> getValueSerializer() { JacksonRedisSerializer<User> jackson2JsonRedisSerializer = new JacksonRedisSerializer<>(User.class); ObjectMapper mapper=new ObjectMapper(); jackson2JsonRedisSerializer.setObjectMapper(mapper); return jackson2JsonRedisSerializer; } }
repos\springboot-demo-master\gzip\src\main\java\com\et\gzip\config\CompressRedis.java
2
请在Spring Boot框架中完成以下Java代码
public Scheme getScheme() { return this.scheme; } public void setScheme(Scheme scheme) { this.scheme = scheme; } public @Nullable String getToken() { return this.token; } public void setToken(@Nullable String token) { this.token = token; } public Format getFormat() { return this.format; } public void setFormat(Format format) { this.format = format; } public enum Format { /** * Push metrics in text format. */ TEXT, /** * Push metrics in protobuf format.
*/ PROTOBUF } public enum Scheme { /** * Use HTTP to push metrics. */ HTTP, /** * Use HTTPS to push metrics. */ HTTPS } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\prometheus\PrometheusProperties.java
2
请完成以下Java代码
public <T> T getModel(final Class<T> modelClass) { final Document document = getDocument(); return DocumentInterfaceWrapper.wrap(document, modelClass); } @Override public <T> T getModelBeforeChanges(final Class<T> modelClass) { final Document document = getDocument(); return DocumentInterfaceWrapper.wrapUsingOldValues(document, modelClass); } @Override public Object getValue(final String columnName) { final Document document = getDocument(); return InterfaceWrapperHelper.getValueOrNull(document, columnName); } @Override public String setValue(final String columnName, final Object value) { final Document document = getDocument(); document.setValue(columnName, value, REASON_Value_DirectSetOnCalloutRecord); return ""; } @Override public void dataRefresh() { final Document document = getDocument(); document.refreshFromRepository(); } @Override public void dataRefreshAll()
{ // NOTE: there is no "All" concept here, so we are just refreshing this document final Document document = getDocument(); document.refreshFromRepository(); } @Override public void dataRefreshRecursively() { // TODO dataRefreshRecursively: refresh document and it's children throw new UnsupportedOperationException(); } @Override public boolean dataSave(final boolean manualCmd) { // TODO dataSave: save document but also update the DocumentsCollection! throw new UnsupportedOperationException(); } @Override public boolean isLookupValuesContainingId(@NonNull final String columnName, @NonNull final RepoIdAware id) { //Querying all values because getLookupValueById doesn't take validation rul into consideration. // TODO: Implement possibility to fetch sqllookupbyid with validation rule considered. return getDocument().getFieldLookupValues(columnName).containsId(id); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentAsCalloutRecord.java
1
请完成以下Java代码
public java.sql.Timestamp getSkippedAt() { return get_ValueAsTimestamp(COLUMNNAME_SkippedAt); } @Override public void setSkipped_Count (final int Skipped_Count) { set_Value (COLUMNNAME_Skipped_Count, Skipped_Count); } @Override public int getSkipped_Count() { return get_ValueAsInt(COLUMNNAME_Skipped_Count); } @Override public void setSkipped_First_Time (final @Nullable java.sql.Timestamp Skipped_First_Time) { set_Value (COLUMNNAME_Skipped_First_Time, Skipped_First_Time); } @Override public java.sql.Timestamp getSkipped_First_Time() { return get_ValueAsTimestamp(COLUMNNAME_Skipped_First_Time); } @Override
public void setSkipped_Last_Reason (final @Nullable java.lang.String Skipped_Last_Reason) { set_Value (COLUMNNAME_Skipped_Last_Reason, Skipped_Last_Reason); } @Override public java.lang.String getSkipped_Last_Reason() { return get_ValueAsString(COLUMNNAME_Skipped_Last_Reason); } @Override public void setSkipTimeoutMillis (final int SkipTimeoutMillis) { set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis); } @Override public int getSkipTimeoutMillis() { return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BPartner_Customer_ID (int C_BPartner_Customer_ID) { if (C_BPartner_Customer_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_Customer_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_Customer_ID, Integer.valueOf(C_BPartner_Customer_ID)); } @Override public int getC_BPartner_Customer_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_Customer_ID); } @Override public void setDateProjected (java.sql.Timestamp DateProjected) { set_ValueNoCheck (COLUMNNAME_DateProjected, DateProjected); } @Override public java.sql.Timestamp getDateProjected() { return get_ValueAsTimestamp(COLUMNNAME_DateProjected); } @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Warehouse_ID (int M_Warehouse_ID)
{ if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setQty (java.math.BigDecimal Qty) { set_ValueNoCheck (COLUMNNAME_Qty, Qty); } @Override public java.math.BigDecimal getQty() { BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStorageAttributesKey (java.lang.String StorageAttributesKey) { set_ValueNoCheck (COLUMNNAME_StorageAttributesKey, StorageAttributesKey); } @Override public java.lang.String getStorageAttributesKey() { return (java.lang.String)get_Value(COLUMNNAME_StorageAttributesKey); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_ATP_QueryResult.java
1
请完成以下Spring Boot application配置
## MULTIPART (MultipartProperties) # Enable multipart uploads spring.servlet.multipart.enabled=true # Threshold after which files are written to disk. spring.servlet.multipart.file-size-threshold=2KB # Max file size. spring.servlet.multipart.max-file-size=200MB # Max Request Size
spring.servlet.multipart.max-request-size=215MB ## File Storage Properties file.upload-dir=./uploads server.port=8081
repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-rest-api-example\src\main\resources\application.properties
2
请完成以下Java代码
public class Account { @ValidAlphanumeric private String username; @ValidAlphanumericWithSingleViolation private String password; @ValidLengthOrNumericCharacter private String nickname; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } }
repos\tutorials-master\javaxval-2\src\main\java\com\baeldung\javaxval\constraint\composition\Account.java
1
请完成以下Java代码
public class CustomIntegerArrayType implements UserType<Integer[]> { @Override public int getSqlType() { return Types.ARRAY; } @Override public Class<Integer[]> returnedClass() { return Integer[].class; } @Override public boolean equals(Integer[] x, Integer[] y) { if (x instanceof Integer[] && y instanceof Integer[]) { return Arrays.deepEquals(x, y); } else { return false; } } @Override public int hashCode(Integer[] x) { return Arrays.hashCode(x); } @Override public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { Array array = rs.getArray(position); return array != null ? (Integer[]) array.getArray() : null; } @Override public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException { if (st != null) { if (value != null) { Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value); st.setArray(index, array); } else { st.setNull(index, Types.ARRAY); } } } @Override public Integer[] deepCopy(Integer[] value) { return value != null ? Arrays.copyOf(value, value.length) : null;
} @Override public boolean isMutable() { return false; } @Override public Serializable disassemble(Integer[] value) { return value; } @Override public Integer[] assemble(Serializable cached, Object owner) { return (Integer[]) cached; } @Override public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) { return detached; } }
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\CustomIntegerArrayType.java
1
请在Spring Boot框架中完成以下Java代码
public class UserAssignedRoleId implements RepoIdAware { int repoId; @NonNull UserRoleId userRoleId; @JsonCreator public static UserAssignedRoleId ofRepoId(@NonNull final UserRoleId userRoleId, final int repoId) { return new UserAssignedRoleId(userRoleId, repoId); } @Nullable public static UserAssignedRoleId ofRepoIdOrNull(@Nullable final UserRoleId userRoleId, final int repoId) { return userRoleId != null && repoId > 0 ? new UserAssignedRoleId(userRoleId, repoId) : null; } public static int toRepoId(@Nullable final UserAssignedRoleId repoId) {
return repoId != null ? repoId.getRepoId() : -1; } private UserAssignedRoleId(@NonNull final UserRoleId UserRoleId, final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, (I_C_User_Assigned_Role.COLUMNNAME_C_User_Assigned_Role_ID)); this.userRoleId = UserRoleId; } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\user\role\UserAssignedRoleId.java
2
请完成以下Java代码
public class MUOM extends X_C_UOM { /** * */ private static final long serialVersionUID = -7248044516358949324L; /** * Get Minute C_UOM_ID * * @param ctx context * @return C_UOM_ID for Minute */ public static int getMinute_UOM_ID(Properties ctx) { if (Ini.isSwingClient()) { final Iterator<MUOM> it = s_cache.values().iterator(); while (it.hasNext()) { final MUOM uom = it.next(); if (UOMUtil.isMinute(uom)) { return uom.getC_UOM_ID(); } } } // Server String sql = "SELECT C_UOM_ID FROM C_UOM WHERE IsActive='Y' AND X12DE355=?"; return DB.getSQLValueEx(ITrx.TRXNAME_None, sql, X12DE355.MINUTE.getCode()); } // getMinute_UOM_ID /** * Get Default C_UOM_ID * * @param ctx context for AD_Client * @return C_UOM_ID */ public static int getDefault_UOM_ID(Properties ctx) { String sql = "SELECT C_UOM_ID " + "FROM C_UOM " + "WHERE AD_Client_ID IN (0,?) " + "ORDER BY IsDefault DESC, AD_Client_ID DESC, C_UOM_ID"; return DB.getSQLValue(null, sql, Env.getAD_Client_ID(ctx)); } // getDefault_UOM_ID /*************************************************************************/ /** UOM Cache */ private static CCache<Integer, MUOM> s_cache = new CCache<>(Table_Name, 30); /** * Get UOM from Cache * * @param ctx context * @param C_UOM_ID ID * @return UOM */ @Deprecated public static MUOM get(Properties ctx, int C_UOM_ID) { if (s_cache.size() == 0) { loadUOMs(ctx); } // MUOM uom = s_cache.get(C_UOM_ID); if (uom != null) { return uom; } // uom = new MUOM(ctx, C_UOM_ID, null); s_cache.put(C_UOM_ID, uom); return uom; } // get /** * Get Precision * * @param ctx context * @param C_UOM_ID ID * @return Precision */ @Deprecated public static int getPrecision(Properties ctx, int C_UOM_ID) { if(C_UOM_ID <= 0) {
return 2; } return Services.get(IUOMDAO.class) .getStandardPrecision(UomId.ofRepoId(C_UOM_ID)) .toInt(); } // getPrecision /** * Load All UOMs * * @param ctx context */ private static void loadUOMs(Properties ctx) { List<MUOM> list = new Query(ctx, Table_Name, "IsActive='Y'", null) .setRequiredAccess(Access.READ) .list(MUOM.class); // for (MUOM uom : list) { s_cache.put(uom.get_ID(), uom); } } // loadUOMs public MUOM(Properties ctx, int C_UOM_ID, String trxName) { super(ctx, C_UOM_ID, trxName); if (is_new()) { // setName (null); // setX12DE355 (null); setIsDefault(false); setStdPrecision(2); setCostingPrecision(6); } } // UOM public MUOM(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // UOM } // MUOM
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MUOM.java
1
请完成以下Java代码
public static final VEditorActionButton createActionButton(final String iconName, final JTextField textComponent) { return VEditorActionButton.build(iconName, textComponent); } /** * Setup the UI properties of the inner text field of a {@link VEditor} component. * * @param textField */ public static final void setupInnerTextComponentUI(final JTextField textField) { VEditorInnerTextComponentUI.instance.installUI(textField); } /** * Class used to configure the UI of the inner text component of a {@link VEditor}. * * Also, this class listens the "UI" property change (fired when the L&F is updated) and sets back the properties it customized. * * @author tsa * */ private static final class VEditorInnerTextComponentUI implements PropertyChangeListener { public static final transient VEditorInnerTextComponentUI instance = new VEditorInnerTextComponentUI(); /** Component's UI property */ private static final String PROPERTY_UI = "UI"; private VEditorInnerTextComponentUI() {
super(); } public void installUI(final JComponent comp) { updateUI(comp); comp.addPropertyChangeListener("UI", this); } /** Actually sets the UI properties */ private void updateUI(final JComponent comp) { comp.setBorder(null); comp.setFont(AdempierePLAF.getFont_Field()); comp.setForeground(AdempierePLAF.getTextColor_Normal()); } @Override public void propertyChange(PropertyChangeEvent evt) { if (PROPERTY_UI.equals(evt.getPropertyName())) { final JComponent comp = (JComponent)evt.getSource(); updateUI(comp); } } } private VEditorUtils() { super(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorUtils.java
1
请完成以下Java代码
public double freq(String key) { Integer f = get(key); if (f == null) f = 0; return f / (double) total; } public double freq(char[]... keyArray) { return freq(convert(keyArray)); } public double freq(char... keyArray) { Integer f = d.get(keyArray); if (f == null) f = 0; return f / (double) total; } public Set<String> samples() { return d.keySet(); } void add(String key, int value) { Integer f = get(key); if (f == null) f = 0; f += value; d.put(key, f); total += value; } void add(int value, char... key) { Integer f = d.get(key); if (f == null) f = 0; f += value; d.put(key, f); total += value; } public void add(int value, char[]... keyArray) { add(convert(keyArray), value); } public void add(int value, Collection<char[]> keyArray) { add(convert(keyArray), value); }
private String convert(Collection<char[]> keyArray) { StringBuilder sbKey = new StringBuilder(keyArray.size() * 2); for (char[] key : keyArray) { sbKey.append(key[0]); sbKey.append(key[1]); } return sbKey.toString(); } static private String convert(char[]... keyArray) { StringBuilder sbKey = new StringBuilder(keyArray.length * 2); for (char[] key : keyArray) { sbKey.append(key[0]); sbKey.append(key[1]); } return sbKey.toString(); } @Override public void save(DataOutputStream out) throws Exception { out.writeInt(total); Integer[] valueArray = d.getValueArray(new Integer[0]); out.writeInt(valueArray.length); for (Integer v : valueArray) { out.writeInt(v); } d.save(out); } @Override public boolean load(ByteArray byteArray) { total = byteArray.nextInt(); int size = byteArray.nextInt(); Integer[] valueArray = new Integer[size]; for (int i = 0; i < valueArray.length; ++i) { valueArray[i] = byteArray.nextInt(); } d.load(byteArray, valueArray); return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\frequency\Probability.java
1
请在Spring Boot框架中完成以下Java代码
public class TUPickingTarget { @NonNull String id; @NonNull String caption; // // New TU @Nullable HuPackingInstructionsId tuPIId; boolean isDefaultPacking; // // Existing TU @Nullable HuId tuId; @Nullable HUQRCode tuQRCode; @Builder(toBuilder = true) private TUPickingTarget( @NonNull final String caption, @Nullable final HuPackingInstructionsId tuPIId, final boolean isDefaultPacking, @Nullable HuId tuId, @Nullable HUQRCode tuQRCode) { this.caption = caption; if (tuId != null) { this.tuPIId = null; this.isDefaultPacking = false; this.tuId = tuId; this.tuQRCode = tuQRCode; this.id = "existing-" + tuId.getRepoId(); } else if (tuPIId != null) { this.tuPIId = tuPIId; this.isDefaultPacking = isDefaultPacking; this.tuId = null; this.tuQRCode = null; this.id = "new-" + tuPIId.getRepoId(); } else { throw new AdempiereException("Invalid picking target"); } } public static boolean equals(@Nullable final TUPickingTarget o1, @Nullable final TUPickingTarget o2) { return Objects.equals(o1, o2); }
@NonNull public static TUPickingTarget ofPackingInstructions(@NonNull final HuPackingInstructionsId tuPIId, @NonNull final String caption) { return builder().tuPIId(tuPIId).caption(caption).build(); } public static TUPickingTarget ofExistingHU(@NonNull final HuId luId, @NonNull final HUQRCode qrCode) { return builder().tuId(luId).tuQRCode(qrCode).caption(qrCode.toDisplayableQRCode()).build(); } public boolean isExistingTU() { return tuId != null; } public boolean isNewTU() { return tuId == null && tuPIId != null; } public HuPackingInstructionsId getTuPIIdNotNull() { return Check.assumeNotNull(tuPIId, "TU PI shall be set for {}", this); } public HuId getTuIdNotNull() { return Check.assumeNotNull(tuId, "TU shall be set for {}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\TUPickingTarget.java
2
请在Spring Boot框架中完成以下Java代码
public class DADDI1 { @XmlElement(name = "DOCUMENTID", required = true) protected String documentid; @XmlElement(name = "LINENUMBER", required = true) protected String linenumber; @XmlElement(name = "ADDINFO", required = true) protected String addinfo; /** * Gets the value of the documentid property. * * @return * possible object is * {@link String } * */ public String getDOCUMENTID() { return documentid; } /** * Sets the value of the documentid property. * * @param value * allowed object is * {@link String } * */ public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the linenumber property. * * @return * possible object is * {@link String } * */ public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property.
* * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the addinfo property. * * @return * possible object is * {@link String } * */ public String getADDINFO() { return addinfo; } /** * Sets the value of the addinfo property. * * @param value * allowed object is * {@link String } * */ public void setADDINFO(String value) { this.addinfo = 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\DADDI1.java
2
请完成以下Java代码
public java.lang.String getProjectPhaseName() { return get_ValueAsString(COLUMNNAME_ProjectPhaseName); } @Override public void setProjectTypeName (final @Nullable java.lang.String ProjectTypeName) { set_ValueNoCheck (COLUMNNAME_ProjectTypeName, ProjectTypeName); } @Override public java.lang.String getProjectTypeName() { return get_ValueAsString(COLUMNNAME_ProjectTypeName); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_ValueNoCheck (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name) { set_ValueNoCheck (COLUMNNAME_SalesRep_Name, SalesRep_Name); } @Override public java.lang.String getSalesRep_Name() { return get_ValueAsString(COLUMNNAME_SalesRep_Name);
} @Override public void setTaxID (final java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Header_v.java
1
请完成以下Java代码
public static CellValue ofNumber(final Number number) { return new CellValue(CellValueType.Number, number); } public static CellValue ofBoolean(final boolean bool) { return new CellValue(CellValueType.Boolean, bool); } public static CellValue ofString(final String string) { return new CellValue(CellValueType.String, string); } @NonNull CellValueType type; @NonNull @Getter(AccessLevel.NONE) Object valueObj; public boolean isDate() { return type == CellValueType.Date; } public java.util.Date dateValue() { return TimeUtil.asDate(valueObj); } public boolean isNumber() { return type == CellValueType.Number;
} public double doubleValue() { return ((Number)valueObj).doubleValue(); } public boolean isBoolean() { return type == CellValueType.Boolean; } public boolean booleanValue() { return (boolean)valueObj; } public String stringValue() { return valueObj.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\CellValue.java
1
请完成以下Java代码
public class DefaultDmnEngineAgenda extends AbstractAgenda implements DmnEngineAgenda { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDmnEngineAgenda.class); public DefaultDmnEngineAgenda(CommandContext commandContext) { super(commandContext); } public void addOperation(DmnOperation operation) { operations.addLast(operation); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Planned {}", operation); } } @Override
protected AgendaFutureMaxWaitTimeoutProvider getAgendaFutureMaxWaitTimeoutProvider() { // The DMN engine has no future operations return null; } @Override public void planExecuteDecisionServiceOperation(ExecuteDecisionContext executeDecisionContext, DecisionService decisionService) { addOperation(new ExecuteDecisionServiceOperation(commandContext, executeDecisionContext, decisionService)); } @Override public void planExecuteDecisionOperation(ExecuteDecisionContext executeDecisionContext, Decision decision) { addOperation(new ExecuteDecisionOperation(commandContext, executeDecisionContext, decision)); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\agenda\DefaultDmnEngineAgenda.java
1
请完成以下Java代码
public class SetVariableCmd implements Command<Void> { protected String caseInstanceId; protected String variableName; protected Object variableValue; public SetVariableCmd(String caseInstanceId, String variableName, Object variableValue) { this.caseInstanceId = caseInstanceId; this.variableName = variableName; this.variableValue = variableValue; } @Override public Void execute(CommandContext commandContext) { if (caseInstanceId == null) { throw new FlowableIllegalArgumentException("caseInstanceId is null"); } if (variableName == null) { throw new FlowableIllegalArgumentException("variable name is null"); } CaseInstanceEntity caseInstanceEntity = CommandContextUtil.getCaseInstanceEntityManager(commandContext).findById(caseInstanceId); if (caseInstanceEntity == null) { throw new FlowableObjectNotFoundException("No case instance found for id " + caseInstanceId, CaseInstanceEntity.class); } caseInstanceEntity.setVariable(variableName, variableValue); CmmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext); CmmnDeploymentManager deploymentManager = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getDeploymentManager(); CaseDefinition caseDefinition = deploymentManager.findDeployedCaseDefinitionById(caseInstanceEntity.getCaseDefinitionId()); boolean evaluateVariableEventListener = false; if (caseDefinition != null) { CmmnModel cmmnModel = deploymentManager.resolveCaseDefinition(caseDefinition).getCmmnModel(); for (Case caze : cmmnModel.getCases()) { List<VariableEventListener> variableEventListeners = caze.findPlanItemDefinitionsOfType(VariableEventListener.class); for (VariableEventListener variableEventListener : variableEventListeners) { if (variableName.equals(variableEventListener.getVariableName())) { evaluateVariableEventListener = true; break; }
} if (evaluateVariableEventListener) { break; } } } if (evaluateVariableEventListener) { agenda.planEvaluateVariableEventListenersOperation(caseInstanceId); } agenda.planEvaluateCriteriaOperation(caseInstanceId); return null; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\SetVariableCmd.java
1
请完成以下Java代码
private static void generateOption(Document dbObject, String realField, String key, Object value) throws ParseException { if (key.endsWith("Begin") || key.endsWith("Start")) { String field = realField == null ? key.substring(0, key.length() - 5) : realField; if (dbObject.containsKey(field)) { DBObject obj = (DBObject) dbObject.get(field); obj.put("$gte", value); dbObject.put(field, obj); } else { DBObject gtObject = new BasicDBObject(); gtObject.put("$gte", value); dbObject.put(field, gtObject); } } else if (key.endsWith("End")) { String field = realField == null ? key.substring(0, key.length() - 3) : realField; if (dbObject.containsKey(field)) { DBObject obj = (DBObject) dbObject.get(field); obj.put("$lte", value); dbObject.put(field, obj); } else { DBObject gtObject = new BasicDBObject(); gtObject.put("$lte", value); dbObject.put(field, gtObject); } } else if (key.endsWith("Like")) { String field = realField == null ? key.substring(0, key.length() - 4) : realField; DBObject gtObject = new BasicDBObject(); gtObject.put("$regex", value); dbObject.put(field, gtObject); } else { String field = realField == null ? key : realField; //包含field注解且注解值为List结尾认为是查询数据内包含的数据 if (realField != null && realField.endsWith("Array")) {
//查询数据 DBObject aObject = new BasicDBObject(); aObject.put("$all", new String[]{value.toString()}); dbObject.put(field, aObject); } else if (value.toString().contains(",")) { //批量查询 String[] arr = value.toString().split(","); DBObject aObject = new BasicDBObject(); aObject.put("$in", arr); dbObject.put(field, aObject); } else { dbObject.put(field, value); } } return; } }
repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\util\DBObjectUtil.java
1
请在Spring Boot框架中完成以下Java代码
public Configuration getStreams() { List<String> servers = this.properties.getStreams().getBootstrapServers(); SslBundle sslBundle = getBundle(this.properties.getStreams().getSsl()); String protocol = this.properties.getStreams().getSecurity().getProtocol(); return Configuration.of((servers != null) ? servers : getBootstrapServers(), (sslBundle != null) ? sslBundle : getSslBundle(), (StringUtils.hasLength(protocol)) ? protocol : getSecurityProtocol()); } @Override public Configuration getAdmin() { SslBundle sslBundle = getBundle(this.properties.getAdmin().getSsl()); String protocol = this.properties.getAdmin().getSecurity().getProtocol(); return Configuration.of(getBootstrapServers(), (sslBundle != null) ? sslBundle : getSslBundle(), (StringUtils.hasLength(protocol)) ? protocol : getSecurityProtocol()); } @Override public @Nullable SslBundle getSslBundle() { return getBundle(this.properties.getSsl());
} @Override public @Nullable String getSecurityProtocol() { return this.properties.getSecurity().getProtocol(); } private @Nullable SslBundle getBundle(Ssl ssl) { if (StringUtils.hasLength(ssl.getBundle())) { Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context"); return this.sslBundles.getBundle(ssl.getBundle()); } return null; } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\PropertiesKafkaConnectionDetails.java
2
请完成以下Java代码
public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request) { final I_PP_Order ppOrder = request.getModel(I_PP_Order.class); final PPOrder2InvoiceCandidatesProducer invoiceCandidatesProducer = createInvoiceCandidatesProducer(); final List<de.metas.materialtracking.model.I_C_Invoice_Candidate> invoiceCandidates = invoiceCandidatesProducer.createInvoiceCandidates(ppOrder); final IIsInvoiceCandidateAware isInvoiceCandidateAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(ppOrder, IIsInvoiceCandidateAware.class); if (isInvoiceCandidateAware != null) { // we flag the record, no matter if we actually created an IC or not. This is fine for this handler isInvoiceCandidateAware.setIsInvoiceCandidate(true); InterfaceWrapperHelper.save(isInvoiceCandidateAware); } return InvoiceCandidateGenerateResult.of(this, invoiceCandidates); } @Override public void invalidateCandidatesFor(final Object model) { Check.errorIf(true, "Shall not be called, because we have getOnInvalidateForModelAction()=RECREATE_ASYNC; model: {}", model); } @Override public boolean isUserInChargeUserEditable() { return true; } /** * @param limit how many quality orders to retrieve * @return all PP_Orders which are suitable for invoices and there are no invoice candidates created yet. */ @Override public Iterator<I_PP_Order> retrieveAllModelsWithMissingCandidates(@NonNull final QueryLimit limit) { return dao.retrievePPOrdersWithMissingICs(limit); } /** * Does nothing. */ @Override public void setOrderedData(final I_C_Invoice_Candidate ic) { // nothing to do; the value won't change } /** * <ul> * <li>QtyDelivered := QtyOrdered * <li>DeliveryDate := DateOrdered * <li>M_InOut_ID: untouched * </ul> * * @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate) */ @Override public void setDeliveredData(final I_C_Invoice_Candidate ic)
{ ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially ic.setQtyDeliveredInUOM(ic.getQtyEntered()); ic.setDeliveryDate(ic.getDateOrdered()); } @Override public void setBPartnerData(final I_C_Invoice_Candidate ic) { // nothing to do; the value won't change } /** * @return {@link OnInvalidateForModelAction#RECREATE_ASYNC}. */ @Override public final OnInvalidateForModelAction getOnInvalidateForModelAction() { return OnInvalidateForModelAction.RECREATE_ASYNC; } /* package */boolean isInvoiceable(final Object model) { final I_PP_Order ppOrder = InterfaceWrapperHelper.create(model, I_PP_Order.class); return dao.isInvoiceable(ppOrder); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\PP_Order_MaterialTracking_Handler.java
1
请在Spring Boot框架中完成以下Java代码
static class CaffeineCacheMeterBinderProviderConfiguration { @Bean CaffeineCacheMeterBinderProvider caffeineCacheMeterBinderProvider() { return new CaffeineCacheMeterBinderProvider(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ HazelcastCache.class, Hazelcast.class }) static class HazelcastCacheMeterBinderProviderConfiguration { @Bean HazelcastCacheMeterBinderProvider hazelcastCacheMeterBinderProvider() { return new HazelcastCacheMeterBinderProvider(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ JCacheCache.class, javax.cache.CacheManager.class }) @ConditionalOnMissingBean(JCacheCacheMeterBinderProvider.class) static class JCacheCacheMeterBinderProviderConfiguration {
@Bean JCacheCacheMeterBinderProvider jCacheCacheMeterBinderProvider() { return new JCacheCacheMeterBinderProvider(); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RedisCache.class) static class RedisCacheMeterBinderProviderConfiguration { @Bean RedisCacheMeterBinderProvider redisCacheMeterBinderProvider() { return new RedisCacheMeterBinderProvider(); } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\metrics\CacheMeterBinderProvidersConfiguration.java
2
请完成以下Java代码
public int hashCode() { return Objects.hash(getElementId(), getActivityName(), getActivityType(), getErrorId(), getErrorCode()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BPMNErrorImpl that = (BPMNErrorImpl) o; return ( Objects.equals(getElementId(), that.getElementId()) && Objects.equals(getActivityName(), that.getActivityName()) && Objects.equals(getActivityType(), that.getActivityType()) && Objects.equals(getErrorCode(), that.getErrorCode()) && Objects.equals(getErrorId(), that.getErrorId()) ); }
@Override public String toString() { return ( "BPMNActivityImpl{" + "activityName='" + getActivityName() + '\'' + ", activityType='" + getActivityType() + '\'' + ", elementId='" + getElementId() + '\'' + ", errorId='" + getErrorId() + '\'' + ", errorCode='" + getErrorCode() + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNErrorImpl.java
1
请完成以下Java代码
public Instant getCreationTime() { return this.cached.getCreationTime(); } @Override public void setLastAccessedTime(Instant lastAccessedTime) { this.cached.setLastAccessedTime(lastAccessedTime); this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, getLastAccessedTime().toEpochMilli()); flushIfRequired(); } @Override public Instant getLastAccessedTime() { return this.cached.getLastAccessedTime(); } @Override public void setMaxInactiveInterval(Duration interval) { this.cached.setMaxInactiveInterval(interval); this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) getMaxInactiveInterval().getSeconds()); flushIfRequired(); } @Override public Duration getMaxInactiveInterval() { return this.cached.getMaxInactiveInterval(); } @Override public boolean isExpired() { return this.cached.isExpired(); } private void flushIfRequired() { if (RedisSessionRepository.this.flushMode == FlushMode.IMMEDIATE) { save(); } } private boolean hasChangedSessionId() { return !getId().equals(this.originalSessionId); } private void save() { saveChangeSessionId(); saveDelta(); if (this.isNew) { this.isNew = false; } } private void saveChangeSessionId() {
if (hasChangedSessionId()) { if (!this.isNew) { String originalSessionIdKey = getSessionKey(this.originalSessionId); String sessionIdKey = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, sessionIdKey); } this.originalSessionId = getId(); } } private void saveDelta() { if (this.delta.isEmpty()) { return; } String key = getSessionKey(getId()); RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta)); RedisSessionRepository.this.sessionRedisOperations.expireAt(key, Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli()) .plusSeconds(getMaxInactiveInterval().getSeconds())); this.delta.clear(); } } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionRepository.java
1
请完成以下Java代码
public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public Collection<String> getTo() { return to; } public void setTo(Collection<String> to) { this.to = to; } public Collection<String> getCc() { return cc; } public void setCc(Collection<String> cc) { this.cc = cc; } public Collection<String> getBcc() { return bcc; } public void setBcc(Collection<String> bcc) { this.bcc = bcc; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getPlainContent() { return plainContent; } public void setPlainContent(String plainContent) { this.plainContent = plainContent; } public String getHtmlContent() { return htmlContent; } public void setHtmlContent(String htmlContent) { this.htmlContent = htmlContent; }
public Charset getCharset() { return charset; } public void setCharset(Charset charset) { this.charset = charset; } public Collection<DataSource> getAttachments() { return attachments; } public void setAttachments(Collection<DataSource> attachments) { this.attachments = attachments; } public void addAttachment(DataSource attachment) { if (attachments == null) { attachments = new ArrayList<>(); } attachments.add(attachment); } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public void addHeader(String name, String value) { if (headers == null) { headers = new LinkedHashMap<>(); } headers.put(name, value); } }
repos\flowable-engine-main\modules\flowable-mail\src\main\java\org\flowable\mail\common\api\MailMessage.java
1
请完成以下Java代码
public int getAD_Printer_Matching_ID() { return get_ValueAsInt(COLUMNNAME_AD_Printer_Matching_ID); } @Override public de.metas.printing.model.I_AD_Printer_Tray getAD_Printer_Tray() { return get_ValueAsPO(COLUMNNAME_AD_Printer_Tray_ID, de.metas.printing.model.I_AD_Printer_Tray.class); } @Override public void setAD_Printer_Tray(de.metas.printing.model.I_AD_Printer_Tray AD_Printer_Tray) { set_ValueFromPO(COLUMNNAME_AD_Printer_Tray_ID, de.metas.printing.model.I_AD_Printer_Tray.class, AD_Printer_Tray); } @Override public void setAD_Printer_Tray_ID (int AD_Printer_Tray_ID) { if (AD_Printer_Tray_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, null); else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, Integer.valueOf(AD_Printer_Tray_ID)); } @Override public int getAD_Printer_Tray_ID() { return get_ValueAsInt(COLUMNNAME_AD_Printer_Tray_ID); } @Override public void setAD_PrinterTray_Matching_ID (int AD_PrinterTray_Matching_ID) { if (AD_PrinterTray_Matching_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PrinterTray_Matching_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PrinterTray_Matching_ID, Integer.valueOf(AD_PrinterTray_Matching_ID)); } @Override public int getAD_PrinterTray_Matching_ID() { return get_ValueAsInt(COLUMNNAME_AD_PrinterTray_Matching_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterTray_Matching.java
1
请完成以下Java代码
public Map<String, DestinationInfo> getTopics() { return topics; } public void setTopics(Map<String, DestinationInfo> topics) { this.topics = topics; } // DestinationInfo stores the Exchange name and routing key used // by our producers when posting messages static class DestinationInfo { private String exchange; private String routingKey; public String getExchange() {
return exchange; } public void setExchange(String exchange) { this.exchange = exchange; } public String getRoutingKey() { return routingKey; } public void setRoutingKey(String routingKey) { this.routingKey = routingKey; } } }
repos\tutorials-master\spring-reactive-modules\spring-webflux-amqp\src\main\java\com\baeldung\spring\amqp\DestinationsConfig.java
1
请完成以下Java代码
public int compare(final OLCand o1, final OLCand o2) { return 0; } } private static final class OLCandColumnOrderingComparator implements Comparator<OLCand> { private final OLCandAggregationColumn column; private OLCandColumnOrderingComparator(@NonNull final OLCandAggregationColumn column) { this.column = column; } @Override public int compare(final OLCand o1, final OLCand o2) { final Object val1 = o1.getValueByColumn(column); final Object val2 = o2.getValueByColumn(column); // allow null values if (val1 == val2) { return 0; } if (val1 == null) { return -1; } if (val2 == null) { return 1; } Check.assume(val1.getClass() == val2.getClass(), "{} and {} have the same class", val1, val2);
final Comparable<Object> comparableVal1 = toComparable(val1); final Comparable<Object> comparableVal2 = toComparable(val2); return comparableVal1.compareTo(comparableVal2); } @SuppressWarnings("unchecked") private Comparable<Object> toComparable(final Object value) { return (Comparable<Object>)value; } } @NonNull public String computeHeaderAggregationKey(@NonNull final OLCand olCand) { return getOrderByColumns() .stream() .map(olCand::getValueByColumn) .map(String::valueOf) .collect(Collectors.joining(OrderCandidate_Constants.HEADER_AGGREGATION_KEY_DELIMITER)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandAggregation.java
1
请完成以下Java代码
public class UserPrincipal implements UserDetails { private Long id; private String surname; private String name; private String lastname; private String username; private String city; @JsonIgnore private String email; @JsonIgnore private String password; private Collection<? extends GrantedAuthority> authorities; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return password; } @Override public String getUsername() {
return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return true; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\security\UserPrincipal.java
1
请在Spring Boot框架中完成以下Java代码
public final class MultipartAutoConfiguration { /** * Well-known name for the MultipartResolver object in the bean factory for this * namespace. */ private static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver"; private final MultipartProperties multipartProperties; MultipartAutoConfiguration(MultipartProperties multipartProperties) { this.multipartProperties = multipartProperties; } @Bean
@ConditionalOnMissingBean MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } @Bean(name = MULTIPART_RESOLVER_BEAN_NAME) @ConditionalOnMissingBean(MultipartResolver.class) StandardServletMultipartResolver multipartResolver() { StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver(); multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily()); multipartResolver.setStrictServletCompliance(this.multipartProperties.isStrictServletCompliance()); return multipartResolver; } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\MultipartAutoConfiguration.java
2
请完成以下Java代码
private void init(Window owner, String title, String htmlText, boolean editable) { if (title == null) setTitle(Msg.getMsg(Env.getCtx(), "Editor")); else setTitle(title); // General Layout final CPanel mainPanel = new CPanel(); mainPanel.setLayout(new BorderLayout()); getContentPane().add(mainPanel, BorderLayout.CENTER); mainPanel.add(editor, BorderLayout.CENTER); editor.setPreferredSize(new Dimension(600, 600)); mainPanel.add(confirmPanel, BorderLayout.SOUTH); confirmPanel.setActionListener(this); // setHtmlText(htmlText); } // init /** Logger */ private Logger log = LogManager.getLogger(getClass()); /** The HTML Text */ private String m_text; private final RichTextEditor editor = new RichTextEditor(); private final ConfirmPanel confirmPanel = ConfirmPanel.newWithOKAndCancel(); private boolean m_isPressedOK = false; @Override public void actionPerformed(ActionEvent e) { log.debug("actionPerformed - Text:" + getHtmlText()); if (e.getActionCommand().equals(ConfirmPanel.A_OK)) { m_text = editor.getHtmlText(); m_isPressedOK = true; dispose(); } else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) { dispose(); } }
public String getHtmlText() { String text = m_text; // us315: check if is plain rext if (field instanceof CTextPane) { if ("text/plain".equals(((CTextPane)field).getContentType())) { text = MADBoilerPlate.getPlainText(m_text); log.info("Converted html to plain text: "+text); } } return text; } public void setHtmlText(String htmlText) { m_text = htmlText; editor.setHtmlText(htmlText); } public boolean isPressedOK() { return m_isPressedOK ; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditorDialog.java
1
请完成以下Java代码
public AppDefinition getAppDefinition(String appDefinitionId) { return commandExecutor.execute(new GetDeploymentAppDefinitionCmd(appDefinitionId)); } @Override public AppModel getAppModel(String appDefinitionId) { return commandExecutor.execute(new GetAppModelCmd(appDefinitionId)); } @Override public String convertAppModelToJson(String appDefinitionId) { return commandExecutor.execute(new GetAppModelJsonCmd(appDefinitionId)); } @Override public void deleteDeployment(String deploymentId, boolean cascade) { commandExecutor.execute(new DeleteDeploymentCmd(deploymentId, cascade));
} @Override public AppDeploymentQuery createDeploymentQuery() { return configuration.getAppDeploymentEntityManager().createDeploymentQuery(); } @Override public AppDefinitionQuery createAppDefinitionQuery() { return configuration.getAppDefinitionEntityManager().createAppDefinitionQuery(); } @Override public void setAppDefinitionCategory(String appDefinitionId, String category) { commandExecutor.execute(new SetAppDefinitionCategoryCmd(appDefinitionId, category)); } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\AppRepositoryServiceImpl.java
1
请完成以下Java代码
public String getIcon() { return null; } @Override public KeyStroke getKeyStroke() { return getActionType().getKeyStroke(); } @Override public boolean isAvailable() { return !NullCopyPasteSupportEditor.isNull(getCopyPasteSupport()); } @Override public boolean isRunnable() { return getCopyPasteSupport().isCopyPasteActionAllowed(getActionType());
} @Override public boolean isHideWhenNotRunnable() { return false; // just gray it out } @Override public void run() { getCopyPasteSupport().executeCopyPasteAction(getActionType()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CopyPasteContextMenuAction.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSettingName() { return settingName; } public void setSettingName(String settingName) { this.settingName = settingName; }
public String getSettingValue() { return settingValue; } public void setSettingValue(String settingValue) { this.settingValue = settingValue; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\schemageneration\model\AccountSetting.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = orderService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取订单详情:订单信息、商品信息、操作记录") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderDetail> detail(@PathVariable Long id) { OmsOrderDetail orderDetailResult = orderService.detail(id); return CommonResult.success(orderDetailResult); } @ApiOperation("修改收货人信息") @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) { int count = orderService.updateReceiverInfo(receiverInfoParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改订单费用信息") @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
int count = orderService.updateMoneyInfo(moneyInfoParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("备注订单") @RequestMapping(value = "/update/note", method = RequestMethod.POST) @ResponseBody public CommonResult updateNote(@RequestParam("id") Long id, @RequestParam("note") String note, @RequestParam("status") Integer status) { int count = orderService.updateNote(id, note, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\OmsOrderController.java
2
请在Spring Boot框架中完成以下Java代码
public class Customer { public Customer(){} @Id //@GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "customer" , cascade = CascadeType.ALL) private Set<CustomerOrder> customerOrders; public Customer(Long id, Set<CustomerOrder> customerOrders, String email, LocalDate dob, String name) { this.id = id; this.customerOrders = customerOrders; this.email = email; this.dob = dob; this.name = name; } public void setId(Long id) { this.id = id; } public void setCustomerOrders(Set<CustomerOrder> customerOrders) { this.customerOrders = customerOrders; } @Override public String toString() { return "Patient{" + "id=" + id + ", orders=" + customerOrders + ", email='" + email + '\'' + ", dob=" + dob + ", name='" + name + '\'' + '}'; } public Set<CustomerOrder> getOrders() { return customerOrders; } public void setOrders(Set<CustomerOrder> orders) { this.customerOrders = orders; } @Column private String email; @Column(name = "dob", columnDefinition = "DATE") private LocalDate dob; @Column private String name; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer patient = (Customer) o; return Objects.equals(id, patient.id); }
@Override public int hashCode() { return Objects.hash(id); } public Long getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Customer.java
2
请完成以下Java代码
private boolean wasAnythingIssued(final PPOrderId ppOrderId) { final IPPCostCollectorDAO ppCostCollectorDAO = Services.get(IPPCostCollectorDAO.class); final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class); for (final I_PP_Cost_Collector cc : ppCostCollectorDAO.getCompletedOrClosedByOrderId(ppOrderId)) { if (ppCostCollectorBL.isAnyComponentIssueOrCoProduct(cc) && ppCostCollectorBL.getMovementQty(cc).signum() > 0) { return true; } } return false; } private List<IQualityInvoiceLineGroup> createQualityInvoiceLineGroups( final IMaterialTrackingDocuments materialTrackingDocuments, @SuppressWarnings("rawtypes") final IVendorReceipt vendorReceipt, // only the add() and getModels methods are parameterized and the won't use them here, so it's safe to suppress final IVendorInvoicingInfo vendorInvoicingInfo) { Check.assumeNotNull(materialTrackingDocuments, "materialTrackingDocuments not null"); Check.assumeNotNull(vendorReceipt, "vendorReceipt not null;\nmaterialTrackingDocuments={}", materialTrackingDocuments); final IQualityInspectionOrder qiOrder = materialTrackingDocuments.getQualityInspectionOrderOrNull(); // we can be sure it's not null because if it was then this method would not be called. Check.assumeNotNull(qiOrder, "qiOrder of materialTrackingDocuments {} is not null", materialTrackingDocuments);
final IQualityInvoiceLineGroupsBuilder invoiceLineGroupsBuilder = qualityBasedSpiProviderService .getQualityInvoiceLineGroupsBuilderProvider() .provideBuilderFor(materialTrackingDocuments); // // Configure: Qty received from Vendor (reference Qty) invoiceLineGroupsBuilder.setVendorReceipt(vendorReceipt); // // Configure: pricing context to be used final IPricingContext pricingContext = new PricingContextBuilder() .setVendorInvoicingInfo(vendorInvoicingInfo) .create(); invoiceLineGroupsBuilder.setPricingContext(pricingContext); // // Execute builder and create invoice line groups final List<IQualityInvoiceLineGroup> invoiceLineGroups = invoiceLineGroupsBuilder .create() .getCreatedInvoiceLineGroups(); // Log builder configuration and status logger.info("{}", invoiceLineGroupsBuilder); // // Return created invoice line groups return invoiceLineGroups; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\PPOrder2InvoiceCandidatesProducer.java
1
请完成以下Java代码
private void addDocumentsToIndex( @NonNull final FTSConfig config, @NonNull final ESDocumentToIndexChunk chunk) throws IOException { final RestHighLevelClient elasticsearchClient = configService.elasticsearchClient(); final String esIndexName = config.getEsIndexName(); final BulkRequest bulkRequest = new BulkRequest(); for (final String documentIdToDelete : chunk.getDocumentIdsToDelete()) { bulkRequest.add(new DeleteRequest(esIndexName) .id(documentIdToDelete)); } for (final ESDocumentToIndex documentToIndex : chunk.getDocumentsToIndex()) { bulkRequest.add(new IndexRequest(esIndexName) .id(documentToIndex.getDocumentId()) .source(documentToIndex.getJson(), XContentType.JSON)); } if (bulkRequest.numberOfActions() > 0) { elasticsearchClient.bulk(bulkRequest, RequestOptions.DEFAULT); } } @ToString private static class ConfigAndEvents { @Getter private final FTSConfig config;
@Getter private final ImmutableSet<TableName> sourceTableNames; private final ArrayList<ModelToIndex> events = new ArrayList<>(); private ConfigAndEvents( @NonNull final FTSConfig config, @NonNull final ImmutableSet<TableName> sourceTableNames) { this.config = config; this.sourceTableNames = sourceTableNames; } public void addEvent(final ModelToIndex event) { if (!events.contains(event)) { events.add(event); } } public ImmutableList<ModelToIndex> getEvents() { return ImmutableList.copyOf(events); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\indexer\queue\ModelToIndexEnqueueProcessor.java
1
请完成以下Java代码
protected ObjectNode createOrGetBpmnNode(ObjectNode infoNode) { if (!infoNode.has(BPMN_NODE)) { infoNode.set(BPMN_NODE, processEngineConfiguration.getObjectMapper().createObjectNode()); } return (ObjectNode) infoNode.get(BPMN_NODE); } protected ObjectNode getBpmnNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(BPMN_NODE); } protected void setLocalizationProperty(String language, String id, String propertyName, String propertyValue, ObjectNode infoNode) { ObjectNode localizationNode = createOrGetLocalizationNode(infoNode); if (!localizationNode.has(language)) { localizationNode.set(language, processEngineConfiguration.getObjectMapper().createObjectNode()); } ObjectNode languageNode = (ObjectNode) localizationNode.get(language); if (!languageNode.has(id)) { languageNode.set(id, processEngineConfiguration.getObjectMapper().createObjectNode()); }
((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue); } protected ObjectNode createOrGetLocalizationNode(ObjectNode infoNode) { if (!infoNode.has(LOCALIZATION_NODE)) { infoNode.set(LOCALIZATION_NODE, processEngineConfiguration.getObjectMapper().createObjectNode()); } return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } protected ObjectNode getLocalizationNode(ObjectNode infoNode) { return (ObjectNode) infoNode.get(LOCALIZATION_NODE); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\DynamicBpmnServiceImpl.java
1
请完成以下Java代码
public class EnablePlanItemInstanceOperation extends AbstractChangePlanItemInstanceStateOperation { protected String entryCriterionId; public EnablePlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity, String entryCriterionId) { super(commandContext, planItemInstanceEntity); this.entryCriterionId = entryCriterionId; } @Override public String getLifeCycleTransition() { return PlanItemTransition.ENABLE; } @Override public String getNewState() { return PlanItemInstanceState.ENABLED; }
@Override protected void internalExecute() { // Sentries are not needed to be kept around, as the plan item is being enabled removeSentryRelatedData(); planItemInstanceEntity.setEntryCriterionId(entryCriterionId); planItemInstanceEntity.setLastEnabledTime(getCurrentTime(commandContext)); CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceEnabled(planItemInstanceEntity); } @Override public String getOperationName() { return "[Enable plan item]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\EnablePlanItemInstanceOperation.java
1
请完成以下Java代码
public class BooleanPrimitiveLookup extends Lookup { private boolean[] elements; private final boolean pivot = false; @Setup @Override public void prepare() { elements = new boolean[s]; for (int i = 0; i < s - 1; i++) { elements[i] = true; } elements[s - 1] = pivot; } @TearDown @Override public void clean() { elements = null; } @Benchmark
@BenchmarkMode(Mode.AverageTime) public int findPosition() { int index = 0; while (pivot != elements[index]) { index++; } return index; } @Override public String getSimpleClassName() { return BooleanPrimitiveLookup.class.getSimpleName(); } }
repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\BooleanPrimitiveLookup.java
1
请完成以下Java代码
public long saveNotifyRecord(RpNotifyRecord notifyRecord) { return rpNotifyService.createNotifyRecord(notifyRecord); } /** * 更新商户通知记录.<br/> * * @param id * @param notifyTimes * 通知次数.<br/> * @param status * 通知状态.<br/> * @return 更新结果 */ public void updateNotifyRord(String id, int notifyTimes, String status) { RpNotifyRecord notifyRecord = rpNotifyService.getNotifyRecordById(id); notifyRecord.setNotifyTimes(notifyTimes); notifyRecord.setStatus(status); notifyRecord.setLastNotifyTime(new Date()); rpNotifyService.updateNotifyRecord(notifyRecord); } /** * 创建商户通知日志记录.<br/> * * @param notifyId * 通知记录ID.<br/>
* @param merchantNo * 商户编号.<br/> * @param merchantOrderNo * 商户订单号.<br/> * @param request * 请求信息.<br/> * @param response * 返回信息.<br/> * @param httpStatus * 通知状态(HTTP状态).<br/> * @return 创建结果 */ public long saveNotifyRecordLogs(String notifyId, String merchantNo, String merchantOrderNo, String request, String response, int httpStatus) { RpNotifyRecordLog notifyRecordLog = new RpNotifyRecordLog(); notifyRecordLog.setHttpStatus(httpStatus); notifyRecordLog.setMerchantNo(merchantNo); notifyRecordLog.setMerchantOrderNo(merchantOrderNo); notifyRecordLog.setNotifyId(notifyId); notifyRecordLog.setRequest(request); notifyRecordLog.setResponse(response); notifyRecordLog.setCreateTime(new Date()); notifyRecordLog.setEditTime(new Date()); return rpNotifyService.createNotifyRecordLog(notifyRecordLog); } }
repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\app\notify\core\NotifyPersist.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isReadyForEvents() { return this.readyForEvents; } public void setReadyForEvents(boolean readyForEvents) { this.readyForEvents = readyForEvents; } public int getRetryAttempts() { return this.retryAttempts; } public void setRetryAttempts(int retryAttempts) { this.retryAttempts = retryAttempts; } public String getServerGroup() { return this.serverGroup; } public void setServerGroup(String serverGroup) { this.serverGroup = serverGroup; } public String[] getServers() { return this.servers; } public void setServers(String[] servers) { this.servers = servers; } public int getSocketBufferSize() { return this.socketBufferSize; } public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; } public int getStatisticInterval() { return this.statisticInterval; } public void setStatisticInterval(int statisticInterval) { this.statisticInterval = statisticInterval; }
public int getSubscriptionAckInterval() { return this.subscriptionAckInterval; } public void setSubscriptionAckInterval(int subscriptionAckInterval) { this.subscriptionAckInterval = subscriptionAckInterval; } public boolean isSubscriptionEnabled() { return this.subscriptionEnabled; } public void setSubscriptionEnabled(boolean subscriptionEnabled) { this.subscriptionEnabled = subscriptionEnabled; } public int getSubscriptionMessageTrackingTimeout() { return this.subscriptionMessageTrackingTimeout; } public void setSubscriptionMessageTrackingTimeout(int subscriptionMessageTrackingTimeout) { this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout; } public int getSubscriptionRedundancy() { return this.subscriptionRedundancy; } public void setSubscriptionRedundancy(int subscriptionRedundancy) { this.subscriptionRedundancy = subscriptionRedundancy; } public boolean isThreadLocalConnections() { return this.threadLocalConnections; } public void setThreadLocalConnections(boolean threadLocalConnections) { this.threadLocalConnections = threadLocalConnections; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PoolProperties.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringDocConfig { // 扫描路径 private static final String basePackage = "cn.lanqiao.springboot3.controller"; // 请求头名称 private static final String headerName = "token"; @Bean public GroupedOpenApi group01() { return GroupedOpenApi.builder() .group("group01") .addOperationCustomizer((operation, handlerMethod) -> { operation.addSecurityItem(new SecurityRequirement().addList(headerName)); return operation; }) .packagesToScan(basePackage) .build(); } @Bean public OpenAPI customOpenAPI() { Components components = new Components(); //添加右上角的统一安全认证 components.addSecuritySchemes(headerName, new SecurityScheme() .type(SecurityScheme.Type.APIKEY) .scheme("basic") .name(headerName)
.in(SecurityScheme.In.HEADER) .description("请求头") ); return new OpenAPI() .components(components) .info(apiInfo()); } private Info apiInfo() { Contact contact = new Contact(); contact.setEmail("2449207463@qq.com"); contact.setName("程序员十三"); contact.setUrl("https://juejin.cn/user/3808363978174302"); return new Info() .title("Swagger文档") .version("1.0") .contact(contact) .license(new License().name("Apache 2.0").url("http://springdoc.org")); } }
repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-swagger\src\main\java\cn\lanqiao\springboot3\config\SpringDocConfig.java
2
请完成以下Java代码
protected String doIt() { final HUToReport hu = getHuToReport(); // create selection final List<HuId> distinctHuIds = ImmutableList.of(hu.getHUId()); DB.createT_Selection(getPinstanceId(), distinctHuIds, ITrx.TRXNAME_None); // print final ReportResult label = printLabel(); // preview getResult().setReportData(new ByteArrayResource(label.getReportContent()), buildFilename(), OutputType.PDF.getContentType()); return MSG_OK; } private ExplainedOptional<HULabelConfig> getLabelConfig() { final HUToReport hu = getHuToReport(); return huLabelService.getFirstMatching(HULabelConfigQuery.builder() .sourceDocType(HULabelSourceDocType.Manufacturing) .huUnitType(hu.getHUUnitType()) .bpartnerId(hu.getBPartnerId()) .build()); } @NonNull private HUToReport getHuToReport() { return HUReportAwareViewRowAsHUToReport.of(getSingleSelectedRow()); } private ReportResult printLabel() { final AdProcessId adProcessId = getLabelConfig() .get() .getPrintFormatProcessId(); final PInstanceRequest pinstanceRequest = createPInstanceRequest(adProcessId); final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder() .setCtx(getCtx()) .setProcessCalledFrom(ProcessCalledFrom.WebUI) .setAD_Process_ID(adProcessId) .setAD_PInstance(adPInstanceDAO.getById(pinstanceId)) .setReportLanguage(getProcessInfo().getReportLanguage()) .setJRDesiredOutputType(OutputType.PDF) .build(); final ReportsClient reportsClient = ReportsClient.get(); return reportsClient.report(jasperProcessInfo); } private PInstanceRequest createPInstanceRequest(@NonNull final AdProcessId adProcessId) { return PInstanceRequest.builder() .processId(adProcessId) .processParams(ImmutableList.of( ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId()))) .build(); } private String buildFilename() { final String instance = String.valueOf(getPinstanceId().getRepoId()); final String title = getProcessInfo().getTitle(); return Joiner.on("_").skipNulls().join(instance, title) + ".pdf"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_PrintFinishedGoodsLabel.java
1
请在Spring Boot框架中完成以下Java代码
public class Author implements Serializable { private static final long serialVersionUID = 1L; @Id // This will disable insert batching - AVOID IT! // @GeneratedValue(strategy = GenerationType.IDENTITY) // This will work, but better use the below solution to reduce database roundtrips // @GeneratedValue(strategy = GenerationType.AUTO) // This will allow insert batching and optimizes the identifiers // generation via the hi/lo algorithm which generated in-memory identifiers @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hilo") @GenericGenerator(name = "hilo", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "hilo_sequence"), @Parameter(name = "initial_value", value = "1"), @Parameter(name = "increment_size", value = "10"), @Parameter(name = "optimizer", value = "hilo") }) private Long id; private int age; private String name; private String genre; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name;
} public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Author{" + "id=" + id + ", age=" + age + ", name=" + name + ", genre=" + genre + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchingAndSerial\src\main\java\com\bookstore\entity\Author.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getProductCategoryId() { return productCategoryId; } public void setProductCategoryId(Long productCategoryId) { this.productCategoryId = productCategoryId; } public Long getProductAttributeId() { return productAttributeId; }
public void setProductAttributeId(Long productAttributeId) { this.productAttributeId = productAttributeId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", productCategoryId=").append(productCategoryId); sb.append(", productAttributeId=").append(productAttributeId); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategoryAttributeRelation.java
1
请在Spring Boot框架中完成以下Java代码
public void setSecurityManager(org.apache.geode.security.SecurityManager securityManager) { Assert.notNull(securityManager, "SecurityManager must not be null"); this.securityManager = securityManager; } /** * Returns a reference to the Apache Geode {@link org.apache.geode.security.SecurityManager} instance * delegated to by this {@link SecurityManagerProxy}. * * @return a reference to the underlying {@link org.apache.geode.security.SecurityManager} instance * delegated to by this {@link SecurityManagerProxy}. * @throws IllegalStateException if the configured {@link org.apache.geode.security.SecurityManager} * was not properly configured. * @see org.apache.geode.security.SecurityManager */ protected org.apache.geode.security.SecurityManager getSecurityManager() { Assert.state(this.securityManager != null, "No SecurityManager configured"); return this.securityManager; } @Override public Object authenticate(Properties properties) throws AuthenticationFailedException { return getSecurityManager().authenticate(properties); } @Override public boolean authorize(Object principal, ResourcePermission permission) { return getSecurityManager().authorize(principal, permission); }
@Override public void close() { getSecurityManager().close(); } @Override public void destroy() throws Exception { super.destroy(); INSTANCE.set(null); } @Override public void init(Properties props) { super.init(props); } @Override protected BeanFactory locateBeanFactory() { return this.beanFactory != null ? this.beanFactory : super.locateBeanFactory(); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\security\support\SecurityManagerProxy.java
2
请完成以下Java代码
public Builder singleRowLayout(@NonNull final DocumentLayoutSingleRow.Builder singleRowLayout) { this.singleRowLayout = singleRowLayout; singleRowLayout.setWindowId(windowId); return this; } /** * The default is {@code false} */ public Builder singleRowDetailLayout(final boolean singleRowDetailLayout) { this.singleRowDetailLayout = singleRowDetailLayout; return this; } /* package */ boolean isEmpty() { return (gridLayout == null || !gridLayout.hasElements()) && (singleRowLayout == null || singleRowLayout.isEmpty()); } public Builder queryOnActivate(final boolean queryOnActivate) { this.queryOnActivate = queryOnActivate; return this; } public Builder quickInputSupport(@Nullable final QuickInputSupportDescriptor quickInputSupport) { this.quickInputSupport = quickInputSupport; return this; } @Nullable public QuickInputSupportDescriptor getQuickInputSupport() { return quickInputSupport; } public Builder caption(@NonNull final ITranslatableString caption) { this.caption = caption; return this; }
public Builder description(@NonNull final ITranslatableString description) { this.description = description; return this; } public Builder addSubTabLayout(@NonNull final DocumentLayoutDetailDescriptor subTabLayout) { this.subTabLayouts.add(subTabLayout); return this; } public Builder addAllSubTabLayouts(@NonNull final List<DocumentLayoutDetailDescriptor> subTabLayouts) { this.subTabLayouts.addAll(subTabLayouts); return this; } public Builder newRecordInputMode(@NonNull final IncludedTabNewRecordInputMode newRecordInputMode) { this.newRecordInputMode = newRecordInputMode; return this; } private IncludedTabNewRecordInputMode getNewRecordInputModeEffective() { final boolean hasQuickInputSupport = getQuickInputSupport() != null; return newRecordInputMode.orCompatibleIfAllowQuickInputIs(hasQuickInputSupport); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDetailDescriptor.java
1