instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } public void setTenantId(String tenantId) {
this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceResponse.java
2
请完成以下Java代码
public RouterFunctions.Builder path(String pattern, Consumer<RouterFunctions.Builder> builderConsumer) { builder.path(pattern, builderConsumer); return this; } @Override public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder filter( HandlerFilterFunction<T, R> filterFunction) { builder.filter(filterFunction); return this; } @Override public RouterFunctions.Builder before(Function<ServerRequest, ServerRequest> requestProcessor) { builder.before(requestProcessor); return this; } @Override public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder after( BiFunction<ServerRequest, T, R> responseProcessor) { builder.after(responseProcessor); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder onError(Predicate<Throwable> predicate, BiFunction<Throwable, ServerRequest, T> responseProvider) { builder.onError(predicate, responseProvider); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder onError(Class<? extends Throwable> exceptionType, BiFunction<Throwable, ServerRequest, T> responseProvider) { builder.onError(exceptionType, responseProvider);
return this; } @Override public RouterFunctions.Builder withAttribute(String name, Object value) { builder.withAttribute(name, value); return this; } @Override public RouterFunctions.Builder withAttributes(Consumer<Map<String, Object>> attributesConsumer) { builder.withAttributes(attributesConsumer); return this; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayRouterFunctionsBuilder.java
1
请完成以下Java代码
public class DocLine_ProjectIssue extends DocLine<Doc_ProjectIssue> { public DocLine_ProjectIssue(I_C_ProjectIssue projectIssue, Doc_ProjectIssue doc) { super(InterfaceWrapperHelper.getPO(projectIssue), doc); setQty(Quantity.of(projectIssue.getMovementQty(), getProductStockingUOM()), true); } public CostAmount getCreateCosts(final AcctSchema as) { if (isReversalLine()) { return services.createReversalCostDetails(CostDetailReverseRequest.builder() .acctSchemaId(as.getId()) .reversalDocumentRef(CostingDocumentRef.ofProjectIssueId(get_ID())) .initialDocumentRef(CostingDocumentRef.ofProjectIssueId(getReversalLine_ID())) .date(getDateAcctAsInstant()) .build()) .getMainAmountToPost(as); } else {
return services.createCostDetail( CostDetailCreateRequest.builder() .acctSchemaId(as.getId()) .clientId(getClientId()) .orgId(getOrgId()) .productId(getProductId()) .attributeSetInstanceId(getAttributeSetInstanceId()) .documentRef(CostingDocumentRef.ofProjectIssueId(get_ID())) .qty(getQty()) .amt(CostAmount.zero(as.getCurrencyId()))// N/A .date(getDateAcctAsInstant()) .build()) .getMainAmountToPost(as); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_ProjectIssue.java
1
请完成以下Java代码
public class VariableListenerSessionData { public static final String VARIABLE_CREATE = "create"; public static final String VARIABLE_UPDATE = "update"; public static final String VARIABLE_DELETE = "delete"; protected String changeType; protected String scopeId; protected String scopeType; protected String scopeDefinitionId; protected List<String> processedElementIds = new ArrayList<>(); public VariableListenerSessionData(String changeType, String scopeId, String scopeType, String scopeDefinitionId) { this.changeType = changeType; this.scopeId = scopeId; this.scopeType = scopeType; this.scopeDefinitionId = scopeDefinitionId; } public VariableListenerSessionData() { } public String getChangeType() { return changeType; } public void setChangeType(String changeType) { this.changeType = changeType; } public String getScopeId() {
return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public boolean containsProcessedElementId(String elementId) { return this.processedElementIds.contains(elementId); } public void addProcessedElementId(String elementId) { this.processedElementIds.add(elementId); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variablelistener\VariableListenerSessionData.java
1
请完成以下Java代码
public int getPage_Offset () { Integer ii = (Integer)get_Value(COLUMNNAME_Page_Offset); if (ii == null) return 0; return ii.intValue(); } /** Set Page_Size. @param Page_Size Page_Size */ @Override public void setPage_Size (int Page_Size) { set_ValueNoCheck (COLUMNNAME_Page_Size, Integer.valueOf(Page_Size)); } /** Get Page_Size. @return Page_Size */ @Override public int getPage_Size () { Integer ii = (Integer)get_Value(COLUMNNAME_Page_Size); if (ii == null) return 0; return ii.intValue(); } /** Set Result_Time. @param Result_Time Result_Time */ @Override public void setResult_Time (java.sql.Timestamp Result_Time) { set_ValueNoCheck (COLUMNNAME_Result_Time, Result_Time); } /** Get Result_Time. @return Result_Time */ @Override public java.sql.Timestamp getResult_Time () { return (java.sql.Timestamp)get_Value(COLUMNNAME_Result_Time); } /** Set Total_Size. @param Total_Size Total_Size */ @Override public void setTotal_Size (int Total_Size)
{ set_ValueNoCheck (COLUMNNAME_Total_Size, Integer.valueOf(Total_Size)); } /** Get Total_Size. @return Total_Size */ @Override public int getTotal_Size () { Integer ii = (Integer)get_Value(COLUMNNAME_Total_Size); if (ii == null) return 0; return ii.intValue(); } /** Set UUID. @param UUID UUID */ @Override public void setUUID (java.lang.String UUID) { set_ValueNoCheck (COLUMNNAME_UUID, UUID); } /** Get UUID. @return UUID */ @Override public java.lang.String getUUID () { return (java.lang.String)get_Value(COLUMNNAME_UUID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection_Pagination.java
1
请在Spring Boot框架中完成以下Java代码
public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @ApiModelProperty(value = "Can be any arbitrary value. When a valid formatted media-type (e.g. application/xml, text/plain) is included, the binary content HTTP response content-type will be set the given value.") public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl;
} @ApiModelProperty(value = "contentUrl:In case the attachment is a link to an external resource, the externalUrl contains the URL to the external content. If the attachment content is present in the Flowable engine, the contentUrl will contain an URL where the binary content can be streamed from.") public String getExternalUrl() { return externalUrl; } public void setExternalUrl(String externalUrl) { this.externalUrl = externalUrl; } public String getContentUrl() { return contentUrl; } public void setContentUrl(String contentUrl) { this.contentUrl = contentUrl; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\AttachmentResponse.java
2
请完成以下Java代码
public PartyType3Code getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link PartyType3Code } * */ public void setTp(PartyType3Code value) { this.tp = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link PartyType4Code } * */ public PartyType4Code getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link PartyType4Code } * */ public void setIssr(PartyType4Code value) { this.issr = value; }
/** * Gets the value of the shrtNm property. * * @return * possible object is * {@link String } * */ public String getShrtNm() { return shrtNm; } /** * Sets the value of the shrtNm property. * * @param value * allowed object is * {@link String } * */ public void setShrtNm(String value) { this.shrtNm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\GenericIdentification32.java
1
请完成以下Java代码
public void setControlBehavior(int controlBehavior) { this.controlBehavior = controlBehavior; } public int getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public void setMaxQueueingTimeMs(int maxQueueingTimeMs) { this.maxQueueingTimeMs = maxQueueingTimeMs; } public int getBurstCount() { return burstCount; } public void setBurstCount(int burstCount) { this.burstCount = burstCount; } public long getDurationInSec() { return durationInSec; } public void setDurationInSec(long durationInSec) { this.durationInSec = durationInSec; } public List<ParamFlowItem> getParamFlowItemList() { return paramFlowItemList; } public void setParamFlowItemList(List<ParamFlowItem> paramFlowItemList) { this.paramFlowItemList = paramFlowItemList; } public Map<Object, Integer> getHotItems() { return hotItems; } public void setHotItems(Map<Object, Integer> hotItems) { this.hotItems = hotItems; } public boolean isClusterMode() { return clusterMode; } public void setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; } public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; }
@Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请完成以下Java代码
public boolean isStorno() { if (storno == null) { return false; } else { return storno; } } /** * Sets the value of the storno property. * * @param value * allowed object is * {@link Boolean } * */ public void setStorno(Boolean value) { this.storno = value; } /** * Gets the value of the copy property. * * @return * possible object is * {@link Boolean } * */ public boolean isCopy() { if (copy == null) { return false; } else { return copy; } } /** * Sets the value of the copy property. * * @param value * allowed object is * {@link Boolean } * */ public void setCopy(Boolean value) {
this.copy = value; } /** * Gets the value of the responseTimestamp property. * */ public int getResponseTimestamp() { return responseTimestamp; } /** * Sets the value of the responseTimestamp property. * */ public void setResponseTimestamp(int value) { this.responseTimestamp = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\PayloadType.java
1
请完成以下Java代码
public String getInitialActivityId() { return initialActivityId; } public void setInitialActivityId(String initialActivityId) { this.initialActivityId = initialActivityId; } public FlowElement getInitialFlowElement() { return initialFlowElement; } public void setInitialFlowElement(FlowElement initialFlowElement) { this.initialFlowElement = initialFlowElement; }
public Process getProcess() { return process; } public void setProcess(Process process) { this.process = process; } public ProcessDefinition getProcessDefinition() { return processDefinition; } public void setProcessDefinition(ProcessDefinition processDefinition) { this.processDefinition = processDefinition; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\AbstractStartProcessInstanceBeforeContext.java
1
请完成以下Java代码
protected void checkElement(String elementName) { int [] tableKeys = X_CM_CStage_Element.getAllIDs("CM_CStage_Element", "CM_CStage_ID=" + this.get_ID() + " AND Name like '" + elementName + "'", get_TrxName()); if (tableKeys==null || tableKeys.length==0) { X_CM_CStage_Element thisElement = new X_CM_CStage_Element(getCtx(), 0, get_TrxName()); thisElement.setAD_Client_ID(getAD_Client_ID()); thisElement.setAD_Org_ID(getAD_Org_ID()); thisElement.setCM_CStage_ID(this.get_ID()); thisElement.setContentHTML(" "); thisElement.setName(elementName); thisElement.save(get_TrxName()); } } /** * Check whether all Template Table records exits * @return true if updated */ protected boolean checkTemplateTable () { int [] tableKeys = X_CM_TemplateTable.getAllIDs("CM_TemplateTable", "CM_Template_ID=" + this.getCM_Template_ID(), get_TrxName()); if (tableKeys!=null) { for (int i=0;i<tableKeys.length;i++) { X_CM_TemplateTable thisTemplateTable = new X_CM_TemplateTable(getCtx(), tableKeys[i], get_TrxName()); int [] existingKeys = X_CM_CStageTTable.getAllIDs("CM_CStageTTable", "CM_TemplateTable_ID=" + thisTemplateTable.get_ID(), get_TrxName());
if (existingKeys==null || existingKeys.length==0) { X_CM_CStageTTable newCStageTTable = new X_CM_CStageTTable(getCtx(), 0, get_TrxName()); newCStageTTable.setAD_Client_ID(getAD_Client_ID()); newCStageTTable.setAD_Org_ID(getAD_Org_ID()); newCStageTTable.setCM_CStage_ID(get_ID()); newCStageTTable.setCM_TemplateTable_ID(thisTemplateTable.get_ID()); newCStageTTable.setDescription(thisTemplateTable.getDescription()); newCStageTTable.setName(thisTemplateTable.getName()); newCStageTTable.setOtherClause(thisTemplateTable.getOtherClause()); newCStageTTable.setWhereClause(thisTemplateTable.getWhereClause()); newCStageTTable.save(); } } } return true; } } // MCStage
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MCStage.java
1
请完成以下Java代码
public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Staled. @param IsStaled Staled */ public void setIsStaled (boolean IsStaled) { set_Value (COLUMNNAME_IsStaled, Boolean.valueOf(IsStaled)); } /** Get Staled. @return Staled */ public boolean isStaled () { Object oo = get_Value(COLUMNNAME_IsStaled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Gueltig. @param IsValid Element ist gueltig */ public void setIsValid (boolean IsValid) { set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid)); } /** Get Gueltig. @return Element ist gueltig
*/ public boolean isValid () { Object oo = get_Value(COLUMNNAME_IsValid); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Refresh Date. @param LastRefreshDate Last Refresh Date */ public void setLastRefreshDate (Timestamp LastRefreshDate) { set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate); } /** Get Last Refresh Date. @return Last Refresh Date */ public Timestamp getLastRefreshDate () { return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate); } /** Set Staled Since. @param StaledSinceDate Staled Since */ public void setStaledSinceDate (Timestamp StaledSinceDate) { set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate); } /** Get Staled Since. @return Staled Since */ public Timestamp getStaledSinceDate () { return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java
1
请完成以下Java代码
protected static void configureAcceptedServerCertificates(final Security security, final SslContextBuilder sslContextBuilder) { try { final Resource trustCertCollection = security.getTrustCertCollection(); final Resource trustStore = security.getTrustStore(); if (trustCertCollection != null) { try (InputStream trustCertCollectionStream = trustCertCollection.getInputStream()) { sslContextBuilder.trustManager(trustCertCollectionStream); } } else if (trustStore != null) { final TrustManagerFactory trustManagerFactory = KeyStoreUtils.loadTrustManagerFactory( security.getTrustStoreFormat(), trustStore, security.getTrustStorePassword()); sslContextBuilder.trustManager(trustManagerFactory); } else { // Use system default } } catch (final Exception e) { throw new IllegalArgumentException("Failed to create SSLContext (TrustStore)", e); } } /** * Converts the given negotiation type to netty's negotiation type. * * @param negotiationType The negotiation type to convert. * @return The converted negotiation type.
*/ // Keep this in sync with NettyChannelFactory#of protected static io.grpc.netty.shaded.io.grpc.netty.NegotiationType of(final NegotiationType negotiationType) { switch (negotiationType) { case PLAINTEXT: return io.grpc.netty.shaded.io.grpc.netty.NegotiationType.PLAINTEXT; case PLAINTEXT_UPGRADE: return io.grpc.netty.shaded.io.grpc.netty.NegotiationType.PLAINTEXT_UPGRADE; case TLS: return io.grpc.netty.shaded.io.grpc.netty.NegotiationType.TLS; default: throw new IllegalArgumentException("Unsupported NegotiationType: " + negotiationType); } } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\channelfactory\ShadedNettyChannelFactory.java
1
请完成以下Java代码
public void setMD_Candidate_QtyDetails_ID (final int MD_Candidate_QtyDetails_ID) { if (MD_Candidate_QtyDetails_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_QtyDetails_ID, MD_Candidate_QtyDetails_ID); } @Override public int getMD_Candidate_QtyDetails_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_QtyDetails_ID); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setStock_MD_Candidate_ID (final int Stock_MD_Candidate_ID) { if (Stock_MD_Candidate_ID < 1) set_Value (COLUMNNAME_Stock_MD_Candidate_ID, null); else set_Value (COLUMNNAME_Stock_MD_Candidate_ID, Stock_MD_Candidate_ID); } @Override public int getStock_MD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_Stock_MD_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_QtyDetails.java
1
请在Spring Boot框架中完成以下Java代码
public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } } public static class StoreProperties { private boolean allowForceCompaction = DiskStoreFactory.DEFAULT_ALLOW_FORCE_COMPACTION; private boolean autoCompact = DiskStoreFactory.DEFAULT_AUTO_COMPACT; private float diskUsageCriticalPercentage = DiskStoreFactory.DEFAULT_DISK_USAGE_CRITICAL_PERCENTAGE; private float diskUsageWarningPercentage = DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE; private int compactionThreshold = DiskStoreFactory.DEFAULT_COMPACTION_THRESHOLD; private int queueSize = DiskStoreFactory.DEFAULT_QUEUE_SIZE; private int writeBufferSize = DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE; private long maxOplogSize = DiskStoreFactory.DEFAULT_MAX_OPLOG_SIZE; private long timeInterval = DiskStoreFactory.DEFAULT_TIME_INTERVAL; private DirectoryProperties[] directoryProperties = {}; public boolean isAllowForceCompaction() { return this.allowForceCompaction; } public void setAllowForceCompaction(boolean allowForceCompaction) { this.allowForceCompaction = allowForceCompaction; } public boolean isAutoCompact() { return this.autoCompact; } public void setAutoCompact(boolean autoCompact) { this.autoCompact = autoCompact; } public int getCompactionThreshold() { return this.compactionThreshold; } public void setCompactionThreshold(int compactionThreshold) { this.compactionThreshold = compactionThreshold; } public DirectoryProperties[] getDirectory() { return this.directoryProperties; } public void setDirectory(DirectoryProperties[] directoryProperties) { this.directoryProperties = directoryProperties; } public float getDiskUsageCriticalPercentage() { return this.diskUsageCriticalPercentage; } public void setDiskUsageCriticalPercentage(float diskUsageCriticalPercentage) { this.diskUsageCriticalPercentage = diskUsageCriticalPercentage; }
public float getDiskUsageWarningPercentage() { return this.diskUsageWarningPercentage; } public void setDiskUsageWarningPercentage(float diskUsageWarningPercentage) { this.diskUsageWarningPercentage = diskUsageWarningPercentage; } public long getMaxOplogSize() { return this.maxOplogSize; } public void setMaxOplogSize(long maxOplogSize) { this.maxOplogSize = maxOplogSize; } public int getQueueSize() { return this.queueSize; } public void setQueueSize(int queueSize) { this.queueSize = queueSize; } public long getTimeInterval() { return this.timeInterval; } public void setTimeInterval(long timeInterval) { this.timeInterval = timeInterval; } public int getWriteBufferSize() { return this.writeBufferSize; } public void setWriteBufferSize(int writeBufferSize) { this.writeBufferSize = writeBufferSize; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java
2
请在Spring Boot框架中完成以下Java代码
public static String rsaEncrypt(String content, String ciphertext) throws Exception { final byte[] PublicKeyBytes = ciphertext.getBytes(); X509Certificate certificate = X509Certificate.getInstance(PublicKeyBytes); PublicKey publicKey = certificate.getPublicKey(); Cipher ci = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE"); ci.init(Cipher.ENCRYPT_MODE, publicKey); return Base64.encode(ci.doFinal(content.getBytes("UTF-8"))); } /** * @param aad encrypt_certificate.associated_data * @param iv encrypt_certificate.nonce * @param cipherText encrypt_certificate.ciphertext * @return 返回ciphertext明文 * @throws Exception */ public static String aesgcmDecrypt(String aad, String iv, String cipherText, String APIv3Secret) throws Exception { final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(APIv3Secret.getBytes(), "AES"); GCMParameterSpec spec = new GCMParameterSpec(128, iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, key, spec); cipher.updateAAD(aad.getBytes()); return new String(cipher.doFinal(Base64.decode(cipherText))); } /** * 文件转MD5Hash * * @param fis * @return */ public static String md5HashCode(InputStream fis) {
try { MessageDigest MD5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[8192]; int length; while ((length = fis.read(buffer)) != -1) { MD5.update(buffer, 0, length); } return new String(Hex.encodeHex(MD5.digest())); } catch (Exception e) { logger.error(e.getMessage()); return null; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\banklink\utils\weixin\WxCommonUtil.java
2
请在Spring Boot框架中完成以下Java代码
public class FeedbackForm { @GetMapping(path = "/feedback") public String getFeedbackForm(Model model) { Feedback feedback = new Feedback(); model.addAttribute("feedback", feedback); return "feedback"; } @PostMapping( path = "/web/feedback", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) public String handleBrowserSubmissions(Feedback feedback) throws Exception { // Save feedback data return "redirect:/feedback/success";
} @GetMapping("/feedback/success") public ResponseEntity<String> getSuccess() { return new ResponseEntity<String>("Thank you for submitting feedback.", HttpStatus.OK); } @PostMapping( path = "/feedback", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) public ResponseEntity<String> handleNonBrowserSubmissions(@RequestParam MultiValueMap paramMap) throws Exception { // Save feedback data return new ResponseEntity<String>("Thank you for submitting feedback", HttpStatus.OK); } }
repos\tutorials-master\spring-web-modules\spring-web-url\src\main\java\com\baeldung\form_submission\controllers\FeedbackForm.java
2
请完成以下Java代码
default List<String> getSubjectTypes() { return getClaimAsStringList(OidcProviderMetadataClaimNames.SUBJECT_TYPES_SUPPORTED); } /** * Returns the {@link JwsAlgorithm JWS} signing algorithms supported for the * {@link OidcIdToken ID Token} to encode the claims in a {@link Jwt} * {@code (id_token_signing_alg_values_supported)}. * @return the {@link JwsAlgorithm JWS} signing algorithms supported for the * {@link OidcIdToken ID Token} */ default List<String> getIdTokenSigningAlgorithms() { return getClaimAsStringList(OidcProviderMetadataClaimNames.ID_TOKEN_SIGNING_ALG_VALUES_SUPPORTED); } /** * Returns the {@code URL} of the OpenID Connect 1.0 UserInfo Endpoint
* {@code (userinfo_endpoint)}. * @return the {@code URL} of the OpenID Connect 1.0 UserInfo Endpoint */ default URL getUserInfoEndpoint() { return getClaimAsURL(OidcProviderMetadataClaimNames.USER_INFO_ENDPOINT); } /** * Returns the {@code URL} of the OpenID Connect 1.0 End Session Endpoint * {@code (end_session_endpoint)}. * @return the {@code URL} of the OpenID Connect 1.0 End Session Endpoint */ default URL getEndSessionEndpoint() { return getClaimAsURL(OidcProviderMetadataClaimNames.END_SESSION_ENDPOINT); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\OidcProviderMetadataClaimAccessor.java
1
请完成以下Java代码
public class SavedCookie implements Serializable { private static final long serialVersionUID = 620L; private final String name; private final String value; private final String domain; private final int maxAge; private final String path; private final boolean secure; public SavedCookie(String name, String value, String domain, int maxAge, String path, boolean secure) { this.name = name; this.value = value; this.domain = domain; this.maxAge = maxAge; this.path = path; this.secure = secure; } public SavedCookie(Cookie cookie) { this(cookie.getName(), cookie.getValue(), cookie.getDomain(), cookie.getMaxAge(), cookie.getPath(), cookie.getSecure()); } public String getName() { return this.name; } public String getValue() { return this.value; } public String getDomain() { return this.domain; } public int getMaxAge() { return this.maxAge;
} public String getPath() { return this.path; } public boolean isSecure() { return this.secure; } public Cookie getCookie() { Cookie cookie = new Cookie(getName(), getValue()); if (getDomain() != null) { cookie.setDomain(getDomain()); } if (getPath() != null) { cookie.setPath(getPath()); } cookie.setMaxAge(getMaxAge()); cookie.setSecure(isSecure()); return cookie; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SavedCookie.java
1
请完成以下Java代码
public static final <E> ListComboBoxModel<E> ofNullable(final Collection<E> list) { if(list == null) { return new ListComboBoxModel<>(); } else { return new ListComboBoxModel<>(list); } } private final List<E> list; private E selected = null; public ListComboBoxModel() { super(); this.list = new ArrayList<>(); } public ListComboBoxModel(final Collection<E> list) { super(); this.list = new ArrayList<>(list); } public ListComboBoxModel(final E[] array) { super(); this.list = new ArrayList<>(Arrays.asList(array)); } @Override public int getSize() { return list.size(); } @Override public E getElementAt(int index) { return list.get(index); } @SuppressWarnings("unchecked") @Override public void setSelectedItem(final Object item) { if (Check.equals(this.selected, item)) { return; } selected = (E)item; fireContentsChanged(this, -1, -1); } private void selectFirstItemIfOnlyOneItemAndNotSelected() { if (selected != null) { return; } if (list.size() != 1) { return; } setSelectedItem(list.get(0)); } @Override public E getSelectedItem() { return selected; } public boolean add(final E item) { final boolean added = list.add(item); fireIntervalAdded(this, list.size() - 1, list.size() - 1); selectFirstItemIfOnlyOneItemAndNotSelected(); return added; } public boolean addAll(Collection<? extends E> c) { if(c == null || c.isEmpty()) { return false; } final int sizeBeforeAdd = list.size(); final boolean added = list.addAll(c); final int sizeAfterAdd = list.size();
// Fire interval added if any final int index0 = sizeBeforeAdd; final int index1 = sizeAfterAdd - 1; if (index0 <= index1) { fireIntervalAdded(this, index0, index1); } selectFirstItemIfOnlyOneItemAndNotSelected(); return added; } /** * @param item * @return <tt>true</tt> if the element was added */ public boolean addIfAbsent(final E item) { if (list.contains(item)) { return false; } return add(item); } public int size() { return list.size(); } public E get(final int index) { return list.get(index); } public void clear() { if (list.isEmpty()) { return; } final int sizeBeforeClear = list.size(); list.clear(); fireIntervalRemoved(this, 0, sizeBeforeClear - 1); } public void set(final Collection<E> items) { clear(); addAll(items); } public void set(final E[] items) { final List<E> itemsAsList; if (items == null || items.length == 0) { itemsAsList = Collections.emptyList(); } else { itemsAsList = Arrays.asList(items); } set(itemsAsList); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\ListComboBoxModel.java
1
请完成以下Java代码
public I_Fact_Acct_Summary retrieveLastMatchingFactAcctSummary(final Properties ctx, final IFactAcctSummaryKey key) { return createFactAcctSummaryQueryForKeyNoDateAcct(ctx, key) .addCompareFilter(I_Fact_Acct_Summary.COLUMN_DateAcct, Operator.LESS_OR_EQUAL, key.getDateAcct()) // .orderBy() .addColumn(I_Fact_Acct_Summary.COLUMN_DateAcct, Direction.Descending, Nulls.Last) .endOrderBy() // .create() .first(I_Fact_Acct_Summary.class); } @Override public IQueryBuilder<I_Fact_Acct_Summary> retrieveCurrentAndNextMatchingFactAcctSummaryQuery(final Properties ctx, final IFactAcctSummaryKey key) { return createFactAcctSummaryQueryForKeyNoDateAcct(ctx, key) .addCompareFilter(I_Fact_Acct_Summary.COLUMN_DateAcct, Operator.GREATER_OR_EQUAL, key.getDateAcct()); } @Override public void updateFactAcctEndingBalanceForTag(final String processingTag) { final String sql = "SELECT " + DB_FUNC_Fact_Acct_EndingBalance_UpdateForTag + "(?)"; final Object[] sqlParams = new Object[] { processingTag }; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited); DB.setParameters(pstmt, sqlParams); rs = pstmt.executeQuery(); if (rs.next()) { final String resultStr = rs.getString(1); Loggables.withLogger(logger, Level.DEBUG).addLog(resultStr); } } catch (final SQLException e) { throw DBException.wrapIfNeeded(e).appendParametersToMessage() .setParameter("sql", sql) .setParameter("sqlParams", sqlParams); } finally { DB.close(rs, pstmt); } } private final class FactAcctLogIterable implements IFactAcctLogIterable { @ToStringBuilder(skip = true) private final Properties ctx; private final String processingTag; public FactAcctLogIterable(final Properties ctx, final String processingTag) { super(); this.ctx = ctx; this.processingTag = processingTag; } @Override public String toString() { return ObjectUtils.toString(this); } @Override
public Properties getCtx() { return ctx; } @Override public String getProcessingTag() { return processingTag; } @Override public void close() { releaseTag(ctx, processingTag); } @Override @NonNull public Iterator<I_Fact_Acct_Log> iterator() { return retrieveForTag(ctx, processingTag); } @Override public void deleteAll() { deleteAllForTag(ctx, processingTag); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\legacy\impl\LegacyFactAcctLogDAO.java
1
请在Spring Boot框架中完成以下Java代码
public void publishUserChangedEvent(@NonNull final MSV3UserChangedBatchEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_UserChangedEvents, event); } public void publishUserChangedEvent(@NonNull final MSV3UserChangedEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_UserChangedEvents, MSV3UserChangedBatchEvent.builder() .event(event) .build()); } public void publishStockAvailabilityUpdatedEvent(@NonNull final MSV3StockAvailabilityUpdatedEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_StockAvailabilityUpdatedEvent, event); }
public void publishProductExcludes(@NonNull final MSV3ProductExcludesUpdateEvent event) { convertAndSend(RabbitMQConfig.QUEUENAME_ProductExcludeUpdatedEvents, event); } public void publishSyncOrderRequest(final MSV3OrderSyncRequest request) { convertAndSend(RabbitMQConfig.QUEUENAME_SyncOrderRequestEvents, request); } public void publishSyncOrderResponse(@NonNull final MSV3OrderSyncResponse response) { convertAndSend(RabbitMQConfig.QUEUENAME_SyncOrderResponseEvents, response); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\service\MSV3ServerPeerService.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, String> getArgs() { return args; } public void setArgs(Map<String, String> args) { this.args = args; } public void addArg(String key, String value) { this.args.put(key, value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterProperties that = (FilterProperties) o; return Objects.equals(name, that.name) && Objects.equals(args, that.args); }
@Override public int hashCode() { return Objects.hash(name, args); } @Override public String toString() { final StringBuilder sb = new StringBuilder("FilterDefinition{"); sb.append("name='").append(name).append('\''); sb.append(", args=").append(args); sb.append('}'); return sb.toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\FilterProperties.java
2
请完成以下Java代码
public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_Container getCM_Container() throws RuntimeException { return (I_CM_Container)MTable.get(getCtx(), I_CM_Container.Table_Name) .getPO(getCM_Container_ID(), get_TrxName()); } /** Set Web Container. @param CM_Container_ID Web Container contains content like images, text etc. */
public void setCM_Container_ID (int CM_Container_ID) { if (CM_Container_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID)); } /** Get Web Container. @return Web Container contains content like images, text etc. */ public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_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_CM_AccessContainer.java
1
请完成以下Java代码
private List<I_S_ExternalReference> listIncludingInactiveBy(final int recordId, @NonNull final IExternalReferenceType type) { return queryBL.createQueryBuilder(I_S_ExternalReference.class) .addEqualsFilter(I_S_ExternalReference.COLUMNNAME_Type, type.getCode()) .addEqualsFilter(I_S_ExternalReference.COLUMNNAME_Record_ID, recordId) .create() .list(); } @NonNull private ExternalReference buildExternalReference(@NonNull final I_S_ExternalReference record) { final IExternalReferenceType type = extractType(record); final ExternalSystem externalSystem = extractSystem(record); return ExternalReference.builder() .externalReferenceId(ExternalReferenceId.ofRepoId(record.getS_ExternalReference_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .externalReference(record.getExternalReference()) .externalReferenceType(type) .externalSystem(externalSystem) .recordId(record.getRecord_ID()) .version(record.getVersion()) .externalReferenceUrl(record.getExternalReferenceURL())
.build(); } private ExternalSystem extractSystem(@NonNull final I_S_ExternalReference record) { return externalSystemRepository.getById(ExternalSystemId.ofRepoId(record.getExternalSystem_ID())); } private IExternalReferenceType extractType(@NonNull final I_S_ExternalReference record) { return externalReferenceTypes.ofCode(record.getType()) .orElseThrow(() -> new AdempiereException("Unknown Type=" + record.getType()) .appendParametersToMessage() .setParameter("type", record.getType()) .setParameter("S_ExternalReference", record)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\ExternalReferenceRepository.java
1
请完成以下Java代码
public double Z() { return 0.0; } public boolean parse() { return true; } public boolean empty() { return true; } public boolean clear() { return true; } public boolean next() { return true; } public String parse(String str) { return ""; } public String toString() { return "";
} public String toString(String result, int size) { return ""; } public String parse(String str, int size) { return ""; } public String parse(String str, int size1, String result, int size2) { return ""; } // set token-level penalty. It would be useful for implementing // Dual decompositon decoding. // e.g. // "Dual Decomposition for Parsing with Non-Projective Head Automata" // Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag public void setPenalty(int i, int j, double penalty) { } public double penalty(int i, int j) { return 0.0; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java
1
请完成以下Java代码
public void storeExternalSystemStatus(@NonNull final StoreExternalSystemStatusRequest request) { final ExternalSystemParentConfig externalSystemParentConfig = externalSystemConfigRepo .getByTypeAndValue(request.getSystemType(), request.getChildSystemConfigValue()) .orElseThrow(() -> new AdempiereException("No external system found by given type and value!") .appendParametersToMessage() .setParameter("externalSystemType", request.getSystemType()) .setParameter("externalSystemChildValue", request.getChildSystemConfigValue())); externalServices.storeExternalSystemStatus(externalSystemParentConfig.getId(), request); } @NonNull public JsonExternalStatusResponse getStatusInfo(@NonNull final ExternalSystemType externalSystemType) { return JsonExternalStatusResponse.builder() .externalStatusResponses(externalServices.getStatusInfo(externalSystemType)) .build(); } @NonNull public JsonExternalSystemInfo getExternalSystemInfo(@NonNull final ExternalSystemType externalSystemType, @NonNull final String childConfigValue) { final Optional<ExternalSystemParentConfig> parentConfig = getByTypeAndValue(externalSystemType, childConfigValue); if (!parentConfig.isPresent()) { throw MissingResourceException.builder() .resourceName("ExternalSystemConfig") .resourceIdentifier("ExternalSystemType=" + externalSystemType + "; childConfigValue=" + childConfigValue) .build(); } return jsonRetriever.retrieveExternalSystemInfo(parentConfig.get()); } @NonNull private InsertRemoteIssueRequest createInsertRemoteIssueRequest(final JsonErrorItem jsonErrorItem, final PInstanceId pInstanceId) { return InsertRemoteIssueRequest.builder() .issueCategory(jsonErrorItem.getIssueCategory()) .issueSummary(StringUtils.isEmpty(jsonErrorItem.getMessage()) ? DEFAULT_ISSUE_SUMMARY : jsonErrorItem.getMessage()) .sourceClassName(jsonErrorItem.getSourceClassName()) .sourceMethodName(jsonErrorItem.getSourceMethodName())
.stacktrace(jsonErrorItem.getStackTrace()) .errorCode(jsonErrorItem.getErrorCode()) .pInstance_ID(pInstanceId) .orgId(RestUtils.retrieveOrgIdOrDefault(jsonErrorItem.getOrgCode())) .build(); } @Nullable public ExternalSystemType getExternalSystemTypeByCodeOrNameOrNull(@Nullable final String value) { final ExternalSystem externalSystem = value != null ? externalSystemRepository.getByLegacyCodeOrValueOrNull(value) : null; return externalSystem != null ? externalSystem.getType() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\externlasystem\ExternalSystemService.java
1
请完成以下Java代码
public static boolean isNew(Object model) { return getGridTab(model).getRecord_ID() <= 0; } public <T> T getDynAttribute(final String attributeName) { if (recordId2dynAttributes == null) { return null; } final int recordId = getGridTab().getRecord_ID(); final Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId); // Cleanup old entries to avoid weird cases // e.g. dynattributes shall be destroyed when user is switching to another record removeOldDynAttributesEntries(recordId); if (dynAttributes == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)dynAttributes.get(attributeName); return value; } public Object setDynAttribute(final String attributeName, final Object value) { Check.assumeNotEmpty(attributeName, "attributeName not empty"); final int recordId = getGridTab().getRecord_ID(); Map<String, Object> dynAttributes = recordId2dynAttributes.get(recordId); if (dynAttributes == null) { dynAttributes = new HashMap<>(); recordId2dynAttributes.put(recordId, dynAttributes); } final Object valueOld = dynAttributes.put(attributeName, value); // Cleanup old entries because in most of the cases we won't use them
removeOldDynAttributesEntries(recordId); // // return the old value return valueOld; } private void removeOldDynAttributesEntries(final int recordIdToKeep) { for (final Iterator<Integer> recordIds = recordId2dynAttributes.keySet().iterator(); recordIds.hasNext();) { final Integer dynAttribute_recordId = recordIds.next(); if (dynAttribute_recordId != null && dynAttribute_recordId == recordIdToKeep) { continue; } recordIds.remove(); } } public final IModelInternalAccessor getModelInternalAccessor() { return modelInternalAccessorSupplier.get(); } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { final GridTabWrapper wrapper = getWrapper(model); return wrapper == null ? false : wrapper.isOldValues(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GridTabWrapper.java
1
请完成以下Java代码
public static LookupDescriptorProvider singleton(@NonNull final LookupDescriptor lookupDescriptor) { return new SingletonLookupDescriptorProvider(lookupDescriptor); } public static LookupDescriptorProvider ofNullableInstance(@Nullable final LookupDescriptor lookupDescriptor) { return lookupDescriptor != null ? singleton(lookupDescriptor) : NULL; } /** * @return provider which calls the given function (memoized) */ public static LookupDescriptorProvider fromMemoizingFunction(final Function<LookupScope, LookupDescriptor> providerFunction) { return new MemoizingFunctionLookupDescriptorProvider(providerFunction); } // // // private static class NullLookupDescriptorProvider implements LookupDescriptorProvider { @Override public Optional<LookupDescriptor> provideForScope(final LookupScope scope) { return Optional.empty(); } } @SuppressWarnings("OptionalUsedAsFieldOrParameterType") @ToString private static class SingletonLookupDescriptorProvider implements LookupDescriptorProvider { private final Optional<LookupDescriptor> lookupDescriptor;
private SingletonLookupDescriptorProvider(@NonNull final LookupDescriptor lookupDescriptor) { this.lookupDescriptor = Optional.of(lookupDescriptor); } @Override public Optional<LookupDescriptor> provideForScope(final LookupScope scope) { return lookupDescriptor; } } @ToString private static class MemoizingFunctionLookupDescriptorProvider implements LookupDescriptorProvider { private final MemoizingFunction<LookupScope, LookupDescriptor> providerFunctionMemoized; private MemoizingFunctionLookupDescriptorProvider(@NonNull final Function<LookupScope, LookupDescriptor> providerFunction) { providerFunctionMemoized = Functions.memoizing(providerFunction); } @Override public Optional<LookupDescriptor> provideForScope(final LookupScope scope) { return Optional.ofNullable(providerFunctionMemoized.apply(scope)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptorProviders.java
1
请完成以下Java代码
protected BigDecimal retrieveQtyInitial() { // Initial storage level BigDecimal qty = BigDecimal.ZERO; // // In case it's an inbound MTransaction (e.g. Vendor Receipts) // then this storage is already full with that qty if (inbound && !reversal) { qty = qty.add(capacityTotal.toBigDecimal()); } // // Iterate all HU transactions and adjust qtyAdd and qtyRemoved Check.assume(HUConstants.DEBUG_07277_saveHUTrxLine, "Saving HU Trx Lines shall be active for MTransactionProductStorage to work"); final ProductId storageProductId = getProductId(); for (final I_M_HU_Trx_Line trxLine : Services.get(IHUTrxDAO.class).retrieveReferencingTrxLines(mtrx)) { // Skip not processed lines if (!trxLine.isProcessed()) { continue; } // Make sure we have the same product if (mtrx.getM_Product_ID() != storageProductId.getRepoId()) { // NOTE: not sure but maybe a log message + continue would be enough throw new AdempiereException("Invalid product for transaction " + mtrx + ": " + " Expected=" + storageProductId + ", Actual=" + mtrx.getM_Product()); } if (trxLine.getM_HU_Item_ID() > 0) { // trxLines which count for us are those which does not have the Ref_HU_Item_ID. // Those who have Ref_HU_Item_ID set those shall be counted on Item Storage. continue; } final BigDecimal trxQtyAbs = convertToStorageUOM(trxLine.getQty(), IHUTrxBL.extractUOMOrNull(trxLine)); final BigDecimal trxQty; if (!reversal) { trxQty = trxQtyAbs;
} else { trxQty = trxQtyAbs; // .negate(); } qty = qty.add(trxQty); } return qty; } public boolean isReversal() { return reversal; } @Override protected Capacity retrieveTotalCapacity() { return capacityTotal; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\MTransactionProductStorage.java
1
请完成以下Java代码
public void onChange(final I_M_Product product) { final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig(); final I_M_Product productOld = InterfaceWrapperHelper.createOld(product, I_M_Product.class); final boolean wasMSV3Product = isMSV3ServerProduct(serverConfig, productOld); final boolean isMSV3Product = isMSV3ServerProduct(serverConfig, product); if (wasMSV3Product == isMSV3Product) { return; } final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); if (isMSV3Product) { runAfterCommit(() -> getStockAvailabilityService().publishProductChangedEvent(productId)); } else { runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId)); } } @ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE) public void onDelete(final I_M_Product product) { final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig(); if (!isMSV3ServerProduct(serverConfig, product)) { return; } final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId)); } private boolean isMSV3ServerProduct(final MSV3ServerConfig serverConfig, final I_M_Product product) { if (!serverConfig.hasProducts()) { return false; } if (!product.isActive())
{ return false; } final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(product.getM_Product_Category_ID()); if (!serverConfig.getProductCategoryIds().contains(productCategoryId)) { return false; } return true; } private MSV3ServerConfigService getServerConfigService() { return Adempiere.getBean(MSV3ServerConfigService.class); } private MSV3StockAvailabilityService getStockAvailabilityService() { return Adempiere.getBean(MSV3StockAvailabilityService.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\M_Product.java
1
请完成以下Java代码
public void deleteAllByUserId(final UserId adUserId) { retrieveNotesByUserId(adUserId) .create() .list() .forEach(this::deleteNotification); } private void deleteNotification(final I_AD_Note notificationPO) { notificationPO.setProcessed(false); InterfaceWrapperHelper.delete(notificationPO); } @Override
public int getUnreadCountByUserId(final UserId adUserId) { return retrieveNotesByUserId(adUserId) .addEqualsFilter(I_AD_Note.COLUMN_Processed, false) .create() .count(); } @Override public int getTotalCountByUserId(final UserId adUserId) { return retrieveNotesByUserId(adUserId) .create() .count(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationRepository.java
1
请完成以下Java代码
protected void configureQuery(ActivityStatisticsQueryImpl query) { checkReadProcessDefinition(query); getAuthorizationManager().configureActivityStatisticsQuery(query); getTenantManager().configureQuery(query); } protected void configureQuery(BatchStatisticsQueryImpl batchQuery) { getAuthorizationManager().configureBatchStatisticsQuery(batchQuery); getTenantManager().configureQuery(batchQuery); } protected void checkReadProcessDefinition(ActivityStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext(); if (isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String processDefinitionId = query.getProcessDefinitionId(); ProcessDefinitionEntity definition = getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); ensureNotNull("no deployed process definition found with id '" + processDefinitionId + "'", "processDefinition", definition); getAuthorizationManager().checkAuthorization(READ, PROCESS_DEFINITION, definition.getKey()); } } public long getStatisticsCountGroupedByDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl decisionRequirementsDefinitionStatisticsQuery) { configureQuery(decisionRequirementsDefinitionStatisticsQuery); return (Long) getDbEntityManager().selectOne("selectDecisionDefinitionStatisticsCount", decisionRequirementsDefinitionStatisticsQuery); } protected void configureQuery(HistoricDecisionInstanceStatisticsQueryImpl decisionRequirementsDefinitionStatisticsQuery) { checkReadDecisionRequirementsDefinition(decisionRequirementsDefinitionStatisticsQuery);
getTenantManager().configureQuery(decisionRequirementsDefinitionStatisticsQuery); } protected void checkReadDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl query) { CommandContext commandContext = getCommandContext(); if (isAuthorizationEnabled() && getCurrentAuthentication() != null && commandContext.isAuthorizationCheckEnabled()) { String decisionRequirementsDefinitionId = query.getDecisionRequirementsDefinitionId(); DecisionRequirementsDefinition definition = getDecisionRequirementsDefinitionManager().findDecisionRequirementsDefinitionById(decisionRequirementsDefinitionId); ensureNotNull("no deployed decision requirements definition found with id '" + decisionRequirementsDefinitionId + "'", "decisionRequirementsDefinition", definition); getAuthorizationManager().checkAuthorization(READ, DECISION_REQUIREMENTS_DEFINITION, definition.getKey()); } } public List<HistoricDecisionInstanceStatistics> getStatisticsGroupedByDecisionRequirementsDefinition(HistoricDecisionInstanceStatisticsQueryImpl query, Page page) { configureQuery(query); return getDbEntityManager().selectList("selectDecisionDefinitionStatistics", query, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\StatisticsManager.java
1
请在Spring Boot框架中完成以下Java代码
public class CategoryServiceImpl implements CategoryService { @Autowired private NewsCategoryMapper newsCategoryMapper; @Override public List<NewsCategory> getAllCategories() { return newsCategoryMapper.findCategoryList(null); } @Override public NewsCategory queryById(Long id) { return newsCategoryMapper.selectByPrimaryKey(id); } @Override public PageResult getCategoryPage(PageQueryUtil pageUtil) { List<NewsCategory> categoryList = newsCategoryMapper.findCategoryList(pageUtil); int total = newsCategoryMapper.getTotalCategories(pageUtil); PageResult pageResult = new PageResult(categoryList, total, pageUtil.getLimit(), pageUtil.getPage()); return pageResult; } @Override public Boolean saveCategory(String categoryName) { /** * 查询是否已存在 */ NewsCategory temp = newsCategoryMapper.selectByCategoryName(categoryName); if (temp == null) { NewsCategory newsCategory = new NewsCategory(); newsCategory.setCategoryName(categoryName); return newsCategoryMapper.insertSelective(newsCategory) > 0; } return false; } @Override public Boolean updateCategory(Long categoryId, String categoryName) {
NewsCategory newsCategory = newsCategoryMapper.selectByPrimaryKey(categoryId); if (newsCategory != null) { newsCategory.setCategoryName(categoryName); return newsCategoryMapper.updateByPrimaryKeySelective(newsCategory) > 0; } return false; } @Override public Boolean deleteBatchByIds(Integer[] ids) { if (ids.length < 1) { return false; } //删除分类数据 return newsCategoryMapper.deleteBatch(ids) > 0; } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\service\impl\CategoryServiceImpl.java
2
请完成以下Java代码
public void setArticleTitle(String articleTitle) { this.articleTitle = articleTitle; } public String getArticleTitle() { return articleTitle; } public void setArticleContent(String articleContent) { this.articleContent = articleContent; } public String getArticleContent() { return articleContent; } public void setAddName(String addName) { this.addName = addName; } public String getAddName() { return addName; }
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\entity\Article.java
1
请完成以下Java代码
private ImmutableSet<PPOrderCandidateId> getSelectedPPOrderCandidateIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isAll()) { return getView().streamByIds(selectedRowIds) .limit(rowsLimit) .map(PP_Order_Candidate_SetStartDate::extractPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } else { return selectedRowIds.stream() .map(PP_Order_Candidate_SetStartDate::toPPOrderCandidateId) .collect(ImmutableSet.toImmutableSet()); } } @NonNull private Timestamp convertParamsToTimestamp() { return Timestamp.valueOf(TimeUtil.asLocalDate(p_Date) .atTime(Integer.parseInt(p_Hour), Integer.parseInt(p_Minute))); }
@NonNull private LookupValue.StringLookupValue toStringLookupValue(final int value) { final String formattedValue = String.format("%02d", value); return LookupValue.StringLookupValue.of(formattedValue, formattedValue); } @NonNull private static PPOrderCandidateId extractPPOrderCandidateId(final IViewRow row) {return toPPOrderCandidateId(row.getId());} @NonNull private static PPOrderCandidateId toPPOrderCandidateId(final DocumentId rowId) {return PPOrderCandidateId.ofRepoId(rowId.toInt());} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.webui\src\main\java\de\metas\manufacturing\webui\process\PP_Order_Candidate_SetStartDate.java
1
请在Spring Boot框架中完成以下Java代码
public User saveUser(User user) { userDao.insert(user, true); return user; } /** * 批量插入用户 * * @param users 用户列表 */ @Override public void saveUserList(List<User> users) { userDao.insertBatch(users); } /** * 根据主键删除用户 * * @param id 主键 */ @Override public void deleteUser(Long id) { userDao.deleteById(id); } /** * 更新用户 * * @param user 用户 * @return 更新后的用户 */ @Override public User updateUser(User user) { if (ObjectUtil.isNull(user)) { throw new RuntimeException("用户id不能为null"); } userDao.updateTemplateById(user); return userDao.single(user.getId()); }
/** * 查询单个用户 * * @param id 主键id * @return 用户信息 */ @Override public User getUser(Long id) { return userDao.single(id); } /** * 查询用户列表 * * @return 用户列表 */ @Override public List<User> getUserList() { return userDao.all(); } /** * 分页查询 * * @param currentPage 当前页 * @param pageSize 每页条数 * @return 分页用户列表 */ @Override public PageQuery<User> getUserByPage(Integer currentPage, Integer pageSize) { return userDao.createLambdaQuery().page(currentPage, pageSize); } }
repos\spring-boot-demo-master\demo-orm-beetlsql\src\main\java\com\xkcoding\orm\beetlsql\service\impl\UserServiceImpl.java
2
请完成以下Java代码
public ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId) { return findById(tenantId, componentId.getId()); } @Override public ComponentDescriptor findByClazz(TenantId tenantId, String clazz) { return DaoUtil.getData(componentDescriptorRepository.findByClazz(clazz)); } @Override public PageData<ComponentDescriptor> findByTypeAndPageLink(TenantId tenantId, ComponentType type, PageLink pageLink) { return DaoUtil.toPageData(componentDescriptorRepository .findByType( type, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<ComponentDescriptor> findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, PageLink pageLink) { return DaoUtil.toPageData(componentDescriptorRepository
.findByScopeAndType( type, scope, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override @Transactional public void deleteById(TenantId tenantId, ComponentDescriptorId componentId) { removeById(tenantId, componentId.getId()); } @Override @Transactional public void deleteByClazz(TenantId tenantId, String clazz) { componentDescriptorRepository.deleteByClazz(clazz); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\component\JpaBaseComponentDescriptorDao.java
1
请完成以下Java代码
public class BaeldungOpenAiCompletion { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println(Consts.INITIAL_MESSAGE); String userMessage = scanner.next(); OpenAIClient client = OpenAIOkHttpClient.fromEnv(); Builder createParams = ChatCompletionCreateParams.builder() .model(ChatModel.GPT_4O_MINI) .addDeveloperMessage(Consts.DEVELOPER_MESSAGE) .addUserMessage(userMessage);
client.chat() .completions() .create(createParams.build()) .choices() .stream() .flatMap(choice -> choice.message() .content() .stream()) .forEach(System.out::println); scanner.close(); } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\openai\BaeldungOpenAiCompletion.java
1
请完成以下Java代码
public TransitionInstance getTransitionInstance() { return transitionInstance; } /** * Else asyncBefore */ public boolean isAsyncAfter() { return jobInstance.isAsyncAfter(); } public boolean isAsyncBefore() { return jobInstance.isAsyncBefore(); } public MigratingJobInstance getJobInstance() { return jobInstance; }
@Override public void setParent(MigratingScopeInstance parentInstance) { if (parentInstance != null && !(parentInstance instanceof MigratingActivityInstance)) { throw MIGRATION_LOGGER.cannotHandleChild(parentInstance, this); } MigratingActivityInstance parentActivityInstance = (MigratingActivityInstance) parentInstance; if (this.parentInstance != null) { ((MigratingActivityInstance) this.parentInstance).removeChild(this); } this.parentInstance = parentActivityInstance; if (parentInstance != null) { parentActivityInstance.addChild(this); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingTransitionInstance.java
1
请完成以下Java代码
private void doLogAction(AuditLog auditLogEntry) { String jsonContent = createElasticJsonRecord(auditLogEntry); HttpEntity entity = new NStringEntity( jsonContent, ContentType.APPLICATION_JSON); Request request = new Request(HttpMethod.POST.name(),String.format("/%s/%s", getIndexName(auditLogEntry.getTenantId()), INDEX_TYPE)); request.setEntity(entity); restClient.performRequestAsync(request, responseListener); } private String createElasticJsonRecord(AuditLog auditLog) { ObjectNode auditLogNode = JacksonUtil.newObjectNode(); auditLogNode.put("postDate", LocalDateTime.now().toString()); auditLogNode.put("id", auditLog.getId().getId().toString()); auditLogNode.put("entityName", auditLog.getEntityName()); auditLogNode.put("tenantId", auditLog.getTenantId().getId().toString()); if (auditLog.getCustomerId() != null) { auditLogNode.put("customerId", auditLog.getCustomerId().getId().toString()); } auditLogNode.put("entityId", auditLog.getEntityId().getId().toString()); auditLogNode.put("entityType", auditLog.getEntityId().getEntityType().name()); auditLogNode.put("userId", auditLog.getUserId().getId().toString()); auditLogNode.put("userName", auditLog.getUserName()); auditLogNode.put("actionType", auditLog.getActionType().name()); if (auditLog.getActionData() != null) { auditLogNode.put("actionData", auditLog.getActionData().toString()); } auditLogNode.put("actionStatus", auditLog.getActionStatus().name()); auditLogNode.put("actionFailureDetails", auditLog.getActionFailureDetails()); return auditLogNode.toString();
} private ResponseListener responseListener = new ResponseListener() { @Override public void onSuccess(Response response) { log.trace("Elasticsearch sink log action method succeeded. Response result [{}]!", response); } @Override public void onFailure(Exception exception) { log.warn("Elasticsearch sink log action method failed!", exception); } }; private String getIndexName(TenantId tenantId) { String indexName = indexPattern; if (indexName.contains(TENANT_PLACEHOLDER) && tenantId != null) { indexName = indexName.replace(TENANT_PLACEHOLDER, tenantId.getId().toString()); } if (indexName.contains(DATE_PLACEHOLDER)) { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat); indexName = indexName.replace(DATE_PLACEHOLDER, now.format(formatter)); } return indexName.toLowerCase(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\audit\sink\ElasticsearchAuditLogSink.java
1
请完成以下Java代码
public void setMarginLeft (int MarginLeft) { set_Value (COLUMNNAME_MarginLeft, Integer.valueOf(MarginLeft)); } /** Get Left Margin. @return Left Space in 1/72 inch */ public int getMarginLeft () { Integer ii = (Integer)get_Value(COLUMNNAME_MarginLeft); if (ii == null) return 0; return ii.intValue(); } /** Set Right Margin. @param MarginRight Right Space in 1/72 inch */ public void setMarginRight (int MarginRight) { set_Value (COLUMNNAME_MarginRight, Integer.valueOf(MarginRight)); } /** Get Right Margin. @return Right Space in 1/72 inch */ public int getMarginRight () { Integer ii = (Integer)get_Value(COLUMNNAME_MarginRight); if (ii == null) return 0; return ii.intValue(); } /** Set Top Margin. @param MarginTop Top Space in 1/72 inch */ public void setMarginTop (int MarginTop) { set_Value (COLUMNNAME_MarginTop, Integer.valueOf(MarginTop)); } /** Get Top Margin. @return Top Space in 1/72 inch */ public int getMarginTop () { Integer ii = (Integer)get_Value(COLUMNNAME_MarginTop); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now.
@return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Size X. @param SizeX X (horizontal) dimension size */ public void setSizeX (BigDecimal SizeX) { set_Value (COLUMNNAME_SizeX, SizeX); } /** Get Size X. @return X (horizontal) dimension size */ public BigDecimal getSizeX () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeX); if (bd == null) return Env.ZERO; return bd; } /** Set Size Y. @param SizeY Y (vertical) dimension size */ public void setSizeY (BigDecimal SizeY) { set_Value (COLUMNNAME_SizeY, SizeY); } /** Get Size Y. @return Y (vertical) dimension size */ public BigDecimal getSizeY () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SizeY); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintPaper.java
1
请完成以下Java代码
public void addBuiltInListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener, int index) { addListenerToMap(listeners, eventName, listener, index); addListenerToMap(builtInListeners, eventName, listener, index); } public void addListener(String eventName, DelegateListener<? extends BaseDelegateExecution> listener, int index) { addListenerToMap(listeners, eventName, listener, index); } protected <T> void addListenerToMap(Map<String, List<T>> listenerMap, String eventName, T listener, int index) { List<T> listeners = listenerMap.get(eventName); if (listeners == null) { listeners = new ArrayList<T>(); listenerMap.put(eventName, listeners); } if (index < 0) { listeners.add(listener); } else { listeners.add(index, listener); } } public void addVariableListener(String eventName, VariableListener<?> listener) { addVariableListener(eventName, listener, -1); } public void addVariableListener(String eventName, VariableListener<?> listener, int index) { addListenerToMap(variableListeners, eventName, listener, index); } public void addBuiltInVariableListener(String eventName, VariableListener<?> listener) { addBuiltInVariableListener(eventName, listener, -1);
} public void addBuiltInVariableListener(String eventName, VariableListener<?> listener, int index) { addListenerToMap(variableListeners, eventName, listener, index); addListenerToMap(builtInVariableListeners, eventName, listener, index); } public Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> getListeners() { return listeners; } public Map<String, List<DelegateListener<? extends BaseDelegateExecution>>> getBuiltInListeners() { return builtInListeners; } public Map<String, List<VariableListener<?>>> getBuiltInVariableListeners() { return builtInVariableListeners; } public Map<String, List<VariableListener<?>>> getVariableListeners() { return variableListeners; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CoreModelElement.java
1
请完成以下Java代码
public class FileSearchExample implements FileVisitor<Path> { private final String fileName; private final Path startDir; public FileSearchExample(String fileName, Path startingDir) { this.fileName = fileName; startDir = startingDir; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.getFileName().toString(); if (this.fileName.equals(fileName)) { System.out.println("File found: " + file.toString()); return TERMINATE; } return CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { System.out.println("Failed to access file: " + file.toString()); return CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
boolean finishedSearch = Files.isSameFile(dir, startDir); if (finishedSearch) { System.out.println("File:" + fileName + " not found"); return TERMINATE; } return CONTINUE; } public static void main(String[] args) throws IOException { Path startingDir = Paths.get("C:/Users/new/Desktop"); FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir); Files.walkFileTree(startingDir, crawler); } }
repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\filevisitor\FileSearchExample.java
1
请完成以下Spring Boot application配置
quarkus.http.root-path=/customerapi/v1 quarkus.hibernate-orm.sql-load-script=import.sql # these aren't actually necessary for Testcontainers # needed to inject from docker compose quarkus.rest-client.order
-api.url=${ORDER_API_URL:} #quarkus.rest-client.order-api.scope=jakarta.inject.Singleton
repos\tutorials-master\quarkus-modules\quarkus-testcontainers\customer-service\src\main\resources\application.properties
2
请完成以下Java代码
public @Nullable PropertySource<?> getPropertySource() { return this.propertySource; } /** * Return the key of the data. * @return the data key */ public String getKey() { return this.key; } /** * Return the key as a lowercase value. * @return the key as a lowercase value * @since 3.5.0 */ public String getLowerCaseKey() { String result = this.lowerCaseKey; if (result == null) { result = this.key.toLowerCase(Locale.getDefault()); this.lowerCaseKey = result; } return result; } /** * Return the value of the data. * @return the data value */ public @Nullable Object getValue() { return this.value;
} /** * Return a new {@link SanitizableData} instance with sanitized value. * @return a new sanitizable data instance. * @since 3.1.0 */ public SanitizableData withSanitizedValue() { return withValue(SANITIZED_VALUE); } /** * Return a new {@link SanitizableData} instance with a different value. * @param value the new value (often {@link #SANITIZED_VALUE} * @return a new sanitizable data instance */ public SanitizableData withValue(@Nullable Object value) { return new SanitizableData(this.propertySource, this.key, value); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\SanitizableData.java
1
请完成以下Java代码
public class BaseTest { protected void initH2db(Connection conn) throws SQLException, ClassNotFoundException, URISyntaxException { Statement st = null; try { String schema = getClass().getResource("/db/schema.sql").toURI().toString().substring(6); String data = getClass().getResource("/db/data.sql").toURI().toString().substring(6); st = conn.createStatement(); // 这一句可以不要 st.execute("drop all objects;"); // 执行初始化语句 st.execute("runscript from '" + schema + "'"); st.execute("runscript from '" + data + "'"); } finally { if (Objects.nonNull(st)) { st.close(); }
} } protected void initH2dbMybatis(SqlSession sqlSession) throws SQLException, ClassNotFoundException, URISyntaxException { Connection conn = sqlSession.getConnection(); try (Statement st = conn.createStatement()) { String schema = getClass().getResource("/db/schema.sql").toURI().toString().substring(6); String data = getClass().getResource("/db/data.sql").toURI().toString().substring(6); // 这一句可以不要 st.execute("drop all objects;"); // 执行初始化语句 st.execute("runscript from '" + schema + "'"); st.execute("runscript from '" + data + "'"); } } }
repos\spring-boot-student-master\spring-boot-student-mybatis\src\main\java\com\xiaolyuh\BaseTest.java
1
请在Spring Boot框架中完成以下Java代码
public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) { return dataManager.findHistoricEntityLinksWithSameRootScopeForScopeIdAndScopeType(scopeId, scopeType, linkType); } @Override public List<HistoricEntityLink> findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType, String linkType) { return dataManager.findHistoricEntityLinksWithSameRootScopeForScopeIdsAndScopeType(scopeIds, scopeType, linkType); } @Override public InternalEntityLinkQuery<HistoricEntityLinkEntity> createInternalHistoricEntityLinkQuery() { return new InternalEntityLinkQueryImpl<>(dataManager::findHistoricEntityLinksByQuery, dataManager::findHistoricEntityLinkByQuery); } @Override public void deleteHistoricEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { dataManager.deleteHistoricEntityLinksByScopeIdAndType(scopeId, scopeType); } @Override public void deleteHistoricEntityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) { dataManager.deleteHistoricEntityLinksByScopeDefinitionIdAndType(scopeDefinitionId, scopeType); }
@Override public void bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(String scopeType, Collection<String> scopeIds) { dataManager.bulkDeleteHistoricEntityLinksForScopeTypeAndScopeIds(scopeType, scopeIds); } @Override public void deleteHistoricEntityLinksForNonExistingProcessInstances() { dataManager.deleteHistoricEntityLinksForNonExistingProcessInstances(); } @Override public void deleteHistoricEntityLinksForNonExistingCaseInstances() { dataManager.deleteHistoricEntityLinksForNonExistingCaseInstances(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\HistoricEntityLinkEntityManagerImpl.java
2
请完成以下Java代码
public java.lang.String getMsgTip() { return get_ValueAsString(COLUMNNAME_MsgTip); } /** * MsgType AD_Reference_ID=103 * Reference name: AD_Message Type */ public static final int MSGTYPE_AD_Reference_ID=103; /** Fehler = E */ public static final String MSGTYPE_Fehler = "E"; /** Information = I */ public static final String MSGTYPE_Information = "I"; /** Menü = M */ public static final String MSGTYPE_Menue = "M"; @Override public void setMsgType (final java.lang.String MsgType) { set_Value (COLUMNNAME_MsgType, MsgType);
} @Override public java.lang.String getMsgType() { return get_ValueAsString(COLUMNNAME_MsgType); } @Override public void setValue (final java.lang.String Value) { set_Value (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_AD_Message.java
1
请完成以下Java代码
public String getArticleStatus() { return get_ValueAsString(COLUMNNAME_ArticleStatus); } /** * AssortmentType AD_Reference_ID=541278 * Reference name: AssortmentType */ public static final int ASSORTMENTTYPE_AD_Reference_ID=541278; /** Unknown = 0 */ public static final String ASSORTMENTTYPE_Unknown = "0"; /** FocusArticle = 1 */ public static final String ASSORTMENTTYPE_FocusArticle = "1"; /** StandardArticle = 2 */ public static final String ASSORTMENTTYPE_StandardArticle = "2"; @Override public void setAssortmentType (final String AssortmentType) { set_Value (COLUMNNAME_AssortmentType, AssortmentType); } @Override public String getAssortmentType() { return get_ValueAsString(COLUMNNAME_AssortmentType); } @Override public void setM_Product_AlbertaArticle_ID (final int M_Product_AlbertaArticle_ID) { if (M_Product_AlbertaArticle_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaArticle_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaArticle_ID, M_Product_AlbertaArticle_ID); } @Override public int getM_Product_AlbertaArticle_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaArticle_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); }
@Override public void setMedicalAidPositionNumber (final @Nullable String MedicalAidPositionNumber) { set_Value (COLUMNNAME_MedicalAidPositionNumber, MedicalAidPositionNumber); } @Override public String getMedicalAidPositionNumber() { return get_ValueAsString(COLUMNNAME_MedicalAidPositionNumber); } /** * PurchaseRating AD_Reference_ID=541279 * Reference name: PurchaseRating */ public static final int PURCHASERATING_AD_Reference_ID=541279; /** A = A */ public static final String PURCHASERATING_A = "A"; /** B = B */ public static final String PURCHASERATING_B = "B"; /** C = C */ public static final String PURCHASERATING_C = "C"; /** D = D */ public static final String PURCHASERATING_D = "D"; /** E = E */ public static final String PURCHASERATING_E = "E"; /** F = F */ public static final String PURCHASERATING_F = "F"; /** G = G */ public static final String PURCHASERATING_G = "G"; @Override public void setPurchaseRating (final @Nullable String PurchaseRating) { set_Value (COLUMNNAME_PurchaseRating, PurchaseRating); } @Override public String getPurchaseRating() { return get_ValueAsString(COLUMNNAME_PurchaseRating); } @Override public void setSize (final @Nullable String Size) { set_Value (COLUMNNAME_Size, Size); } @Override public String getSize() { return get_ValueAsString(COLUMNNAME_Size); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaArticle.java
1
请完成以下Java代码
public Object put(String key, Object value) { if (key == null) { throw new IllegalArgumentException("This map does not support 'null' keys."); } Object variableBefore = businessProcess.getVariable(key); businessProcess.setVariable(key, value); return variableBefore; } @Override public void putAll(Map<? extends String, ? extends Object> m) { for (Map.Entry<? extends String, ? extends Object> newEntry : m.entrySet()) { businessProcess.setVariable(newEntry.getKey(), newEntry.getValue()); } } @Override public int size() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".size() is not supported."); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".isEmpty() is not supported."); } @Override public boolean containsKey(Object key) { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsKey() is not supported."); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsValue() is not supported."); }
@Override public Object remove(Object key) { throw new UnsupportedOperationException("ProcessVariableMap.remove is unsupported. Use ProcessVariableMap.put(key, null)"); } @Override public void clear() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".clear() is not supported."); } @Override public Set<String> keySet() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".keySet() is not supported."); } @Override public Collection<Object> values() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".values() is not supported."); } @Override public Set<Map.Entry<String, Object>> entrySet() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".entrySet() is not supported."); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\ProcessVariableMap.java
1
请完成以下Java代码
public class X_M_Product_Allergen_Trace extends org.compiere.model.PO implements I_M_Product_Allergen_Trace, org.compiere.model.I_Persistent { private static final long serialVersionUID = 272806817L; /** Standard Constructor */ public X_M_Product_Allergen_Trace (final Properties ctx, final int M_Product_Allergen_Trace_ID, @Nullable final String trxName) { super (ctx, M_Product_Allergen_Trace_ID, trxName); } /** Load Constructor */ public X_M_Product_Allergen_Trace (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_M_Allergen_Trace getM_Allergen_Trace() { return get_ValueAsPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class); } @Override public void setM_Allergen_Trace(final org.compiere.model.I_M_Allergen_Trace M_Allergen_Trace) { set_ValueFromPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class, M_Allergen_Trace); } @Override public void setM_Allergen_Trace_ID (final int M_Allergen_Trace_ID) { if (M_Allergen_Trace_ID < 1) set_Value (COLUMNNAME_M_Allergen_Trace_ID, null); else set_Value (COLUMNNAME_M_Allergen_Trace_ID, M_Allergen_Trace_ID); } @Override public int getM_Allergen_Trace_ID() {
return get_ValueAsInt(COLUMNNAME_M_Allergen_Trace_ID); } @Override public void setM_Product_Allergen_Trace_ID (final int M_Product_Allergen_Trace_ID) { if (M_Product_Allergen_Trace_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Allergen_Trace_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Allergen_Trace_ID, M_Product_Allergen_Trace_ID); } @Override public int getM_Product_Allergen_Trace_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Allergen_Trace_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Allergen_Trace.java
1
请在Spring Boot框架中完成以下Java代码
public class M_Warehouse { private final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); @Init public void registerCallouts() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @CalloutMethod(columnNames = I_M_Warehouse.COLUMNNAME_C_BPartner_Location_ID) @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_M_Warehouse.COLUMNNAME_C_BPartner_Location_ID) public void syncLocation(final I_M_Warehouse warehouse) { final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoIdOrNull( BPartnerId.ofRepoIdOrNull(warehouse.getC_BPartner_ID()), warehouse.getC_BPartner_Location_ID() ); if (bPartnerLocationId == null) {
return; } final I_C_BPartner_Location bpLocation = bpartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId); if (bpLocation == null) { return; } warehouse.setC_Location_ID(bpLocation.getC_Location_ID()); } @CalloutMethod(columnNames = I_M_Warehouse.COLUMNNAME_C_BPartner_ID) public void onPartnerChange(final I_M_Warehouse warehouse) { warehouse.setC_Location_ID(-1); warehouse.setC_BPartner_Location_ID(-1); warehouse.setAD_User_ID(-1); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\modelvalidator\M_Warehouse.java
2
请完成以下Java代码
public List<ProcessDefinition> getProcessDefinition() { return processRuntime.processDefinitions(Pageable.of(0, 100)).getContent(); } @Override public void run(String... args) {} @Bean public Connector processTextConnector() { return integrationContext -> { Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables(); String contentToProcess = (String) inBoundVariables.get("fileContent"); // Logic Here to decide if content is approved or not if (contentToProcess.contains("activiti")) { integrationContext.addOutBoundVariable("approved", true); } else { integrationContext.addOutBoundVariable("approved", false); } return integrationContext; }; } @Bean public Connector tagTextConnector() { return integrationContext -> { String contentToTag = (String) integrationContext.getInBoundVariables().get("fileContent"); contentToTag += " :) "; integrationContext.addOutBoundVariable("fileContent", contentToTag);
System.out.println("Final Content: " + contentToTag); return integrationContext; }; } @Bean public Connector discardTextConnector() { return integrationContext -> { String contentToDiscard = (String) integrationContext.getInBoundVariables().get("fileContent"); contentToDiscard += " :( "; integrationContext.addOutBoundVariable("fileContent", contentToDiscard); System.out.println("Final Content: " + contentToDiscard); return integrationContext; }; } }
repos\Activiti-develop\activiti-examples\activiti-api-web-example\src\main\java\org\activiti\examples\DemoApplication.java
1
请完成以下Java代码
public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() {
final StringBuilder sb = new StringBuilder( "{\"Article\":{" ); sb.append( "\"id\":" ) .append( id ); sb.append( ",\"author\":\"" ) .append( author ).append( '\"' ); sb.append( ",\"title\":\"" ) .append( title ).append( '\"' ); sb.append( ",\"content\":\"" ) .append( content ).append( '\"' ); sb.append( "}}" ); return sb.toString(); } }
repos\SpringBootLearning-master (1)\springboot-elasticsearch\src\main\java\com\gf\entity\Article.java
1
请在Spring Boot框架中完成以下Java代码
private Mono<User> findOneWithAuthoritiesBy(String fieldName, Object fieldValue) { return db .sql("SELECT * FROM jhi_user u LEFT JOIN jhi_user_authority ua ON u.id=ua.user_id WHERE u." + fieldName + " = :" + fieldName) .bind(fieldName, fieldValue) .map( (row, metadata) -> Tuples.of(r2dbcConverter.read(User.class, row, metadata), Optional.ofNullable(row.get("authority_name", String.class))) ) .all() .collectList() .filter(l -> !l.isEmpty()) .map(l -> updateUserWithAuthorities(l.get(0).getT1(), l)); } private User updateUserWithAuthorities(User user, List<Tuple2<User, Optional<String>>> tuples) {
user.setAuthorities( tuples .stream() .filter(t -> t.getT2().isPresent()) .map(t -> { Authority authority = new Authority(); authority.setName(t.getT2().orElseThrow()); return authority; }) .collect(Collectors.toSet()) ); return user; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\repository\UserRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class ValidateCodeFilter extends OncePerRequestFilter { @Autowired private AuthenticationFailureHandler authenticationFailureHandler; private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI()) && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) { try { validateCode(new ServletWebRequest(httpServletRequest)); } catch (ValidateCodeException e) { authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e); return; } } filterChain.doFilter(httpServletRequest, httpServletResponse); } private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException { ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE); String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");
if (StringUtils.isBlank(codeInRequest)) { throw new ValidateCodeException("验证码不能为空!"); } if (codeInSession == null) { throw new ValidateCodeException("验证码不存在!"); } if (codeInSession.isExpire()) { sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE); throw new ValidateCodeException("验证码已过期!"); } if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) { throw new ValidateCodeException("验证码不正确!"); } sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE); } }
repos\SpringAll-master\36.Spring-Security-ValidateCode\src\main\java\cc\mrbird\validate\code\ValidateCodeFilter.java
2
请完成以下Java代码
private static ImmutableSet<HuId> extractHUIds(final List<I_M_HU> hus) { return hus.stream().map(hu -> HuId.ofRepoId(hu.getM_HU_ID())).collect(ImmutableSet.toImmutableSet()); } private List<I_M_HU> splitOutOfPickFromHU(final DDOrderMoveSchedule schedule) { // Atm we always take top level HUs // TODO: implement TU level support if (!HuId.equals(huIdToPick, schedule.getPickFromHUId())) { throw new AdempiereException("HU not matching the scheduled one"); } final I_M_HU pickFromHU = handlingUnitsBL.getById(huIdToPick); return ImmutableList.of(pickFromHU); } private MovementId createPickFromMovement(@NonNull final Set<HuId> huIdsToMove) { final HUMovementGenerateRequest request = DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate) .fromLocatorId(schedule.getPickFromLocatorId()) .toLocatorId(getInTransitLocatorId()) .huIdsToMove(huIdsToMove) .build(); return new HUMovementGenerator(request) .createMovement() .getSingleMovementLineId() .getMovementId();
} private LocatorId getInTransitLocatorId() { if (inTransitLocatorIdEffective == null) { inTransitLocatorIdEffective = computeInTransitLocatorId(); } return inTransitLocatorIdEffective; } private LocatorId computeInTransitLocatorId() { if (inTransitLocatorId != null) { return inTransitLocatorId; } final WarehouseId warehouseInTransitId = WarehouseId.ofRepoId(ddOrder.getM_Warehouse_ID()); return warehouseBL.getOrCreateDefaultLocatorId(warehouseInTransitId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\pick_from\DDOrderPickFromCommand.java
1
请完成以下Java代码
public void createMobileApplicationAccess(@NonNull final CreateMobileApplicationAccessRequest request) { final RoleId roleId = request.getRoleId(); final MobileApplicationRepoId applicationId = request.getApplicationId(); I_Mobile_Application_Access accessRecord = queryBL .createQueryBuilder(I_Mobile_Application_Access.class) .addEqualsFilter(I_Mobile_Application_Access.COLUMNNAME_AD_Role_ID, roleId) .addEqualsFilter(I_Mobile_Application_Access.COLUMNNAME_Mobile_Application_ID, applicationId) .create() .firstOnly(I_Mobile_Application_Access.class); if (accessRecord == null) { accessRecord = InterfaceWrapperHelper.newInstance(I_Mobile_Application_Access.class); InterfaceWrapperHelper.setValue(accessRecord, I_Mobile_Application_Access.COLUMNNAME_AD_Client_ID, request.getClientId().getRepoId()); accessRecord.setAD_Org_ID(request.getOrgId().getRepoId()); accessRecord.setAD_Role_ID(roleId.getRepoId()); accessRecord.setMobile_Application_ID(applicationId.getRepoId());
accessRecord.setIsAllowAllActions(true); } accessRecord.setIsActive(true); InterfaceWrapperHelper.save(accessRecord); } public void deleteMobileApplicationAccess(@NonNull final MobileApplicationRepoId applicationId) { queryBL.createQueryBuilder(I_Mobile_Application_Access.class) .addEqualsFilter(I_Mobile_Application_Access.COLUMNNAME_Mobile_Application_ID, applicationId) .create() .delete(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\mobile_application\MobileApplicationPermissionsRepository.java
1
请完成以下Spring Boot application配置
ms.db.driverClassName=com.mysql.jdbc.Driver ms.db.url=jdbc:mysql://localhost:3306/cache?characterEncoding=utf-8&useSSL=false ms.db.username=root ms.db.password=admin ms.db.maxActive=500
logging.level.org.springframework.security= INFO spring.thymeleaf.cache=false
repos\springBoot-master\springboot-SpringSecurity0\src\main\resources\application.properties
2
请完成以下Java代码
/* package */ void collectValidStatusChanged(final IDocumentFieldView documentField) { fieldChangesOf(documentField).setValidStatus(documentField.getValidStatus()); } /* package */void collectDocumentSaveStatusChanged(final DocumentSaveStatus documentSaveStatus) { this.documentSaveStatus = documentSaveStatus; } public DocumentSaveStatus getDocumentSaveStatus() { return documentSaveStatus; } /* package */ void collectDeleted() { deleted = Boolean.TRUE; } public boolean isDeleted() { return deleted != null && deleted; } public List<IncludedDetailInfo> getIncludedDetailInfos() { return ImmutableList.copyOf(includedDetailInfos.values()); } /* package */ final IncludedDetailInfo includedDetailInfo(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return includedDetailInfos.computeIfAbsent(detailId, IncludedDetailInfo::new); } /* package */final Optional<IncludedDetailInfo> includedDetailInfoIfExists(final DetailId detailId) { Check.assumeNotNull(detailId, "Parameter detailId is not null"); return Optional.ofNullable(includedDetailInfos.get(detailId)); } /* package */void collectEvent(final IDocumentFieldChangedEvent event) { final boolean init_isKey = false; final boolean init_publicField = true; final boolean init_advancedField = false; final DocumentFieldWidgetType init_widgetType = event.getWidgetType(); fieldChangesOf(event.getFieldName(), init_isKey, init_publicField, init_advancedField, init_widgetType) .mergeFrom(event); } /* package */ void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning) { fieldChangesOf(documentField).setFieldWarning(fieldWarning); } public static final class IncludedDetailInfo { private final DetailId detailId; private boolean stale = false; private LogicExpressionResult allowNew; private LogicExpressionResult allowDelete; private IncludedDetailInfo(final DetailId detailId) { this.detailId = detailId; } public DetailId getDetailId() { return detailId; } IncludedDetailInfo setStale() { stale = true; return this; } public boolean isStale() { return stale; }
public LogicExpressionResult getAllowNew() { return allowNew; } IncludedDetailInfo setAllowNew(final LogicExpressionResult allowNew) { this.allowNew = allowNew; return this; } public LogicExpressionResult getAllowDelete() { return allowDelete; } IncludedDetailInfo setAllowDelete(final LogicExpressionResult allowDelete) { this.allowDelete = allowDelete; return this; } private void collectFrom(final IncludedDetailInfo from) { if (from.stale) { stale = from.stale; } if (from.allowNew != null) { allowNew = from.allowNew; } if (from.allowDelete != null) { allowDelete = from.allowDelete; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChanges.java
1
请完成以下Java代码
public Builder notBefore(Instant notBefore) { return claim(JwtClaimNames.NBF, notBefore); } /** * Sets the issued at {@code (iat)} claim, which identifies the time at which the * JWT was issued. * @param issuedAt the time at which the JWT was issued * @return the {@link Builder} */ public Builder issuedAt(Instant issuedAt) { return claim(JwtClaimNames.IAT, issuedAt); } /** * Sets the JWT ID {@code (jti)} claim, which provides a unique identifier for the * JWT. * @param jti the unique identifier for the JWT * @return the {@link Builder} */ public Builder id(String jti) { return claim(JwtClaimNames.JTI, jti); } /** * Sets the claim. * @param name the claim name * @param value the claim value * @return the {@link Builder} */ public Builder claim(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.claims.put(name, value); return this; } /** * A {@code Consumer} to be provided access to the claims allowing the ability to * add, replace, or remove. * @param claimsConsumer a {@code Consumer} of the claims */ public Builder claims(Consumer<Map<String, Object>> claimsConsumer) { claimsConsumer.accept(this.claims); return this;
} /** * Builds a new {@link JwtClaimsSet}. * @return a {@link JwtClaimsSet} */ public JwtClaimsSet build() { Assert.notEmpty(this.claims, "claims cannot be empty"); // The value of the 'iss' claim is a String or URL (StringOrURI). // Attempt to convert to URL. Object issuer = this.claims.get(JwtClaimNames.ISS); if (issuer != null) { URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class); if (convertedValue != null) { this.claims.put(JwtClaimNames.ISS, convertedValue); } } return new JwtClaimsSet(this.claims); } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimsSet.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoryJobProcessorContextImpl implements HistoryJobProcessorContext { protected final Phase phase; protected final HistoryJobEntity historyJobEntity; public HistoryJobProcessorContextImpl(Phase phase, HistoryJobEntity historyJobEntity) { this.phase = phase; this.historyJobEntity = historyJobEntity; } @Override public Phase getPhase() { return phase; } @Override public HistoryJobEntity getHistoryJobEntity() { return historyJobEntity; }
@Override public boolean isInPhase(Phase phase) { return this.phase.equals(phase); } @Override public String toString() { return "HistoryJobProcessorContextImpl{" + "phase=" + phase + ", historyJobEntity=" + historyJobEntity + '}'; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobProcessorContextImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getDelisId() { return delisId; } /** * Sets the value of the delisId property. * * @param value * allowed object is * {@link String } * */ public void setDelisId(String value) { this.delisId = value; } /** * Gets the value of the customerUid property. * * @return * possible object is * {@link String } * */ public String getCustomerUid() { return customerUid; } /** * Sets the value of the customerUid property. * * @param value * allowed object is * {@link String } * */ public void setCustomerUid(String value) { this.customerUid = value; } /** * Gets the value of the authToken property. * * @return * possible object is * {@link String }
* */ public String getAuthToken() { return authToken; } /** * Sets the value of the authToken property. * * @param value * allowed object is * {@link String } * */ public void setAuthToken(String value) { this.authToken = value; } /** * Gets the value of the depot property. * * @return * possible object is * {@link String } * */ public String getDepot() { return depot; } /** * Sets the value of the depot property. * * @param value * allowed object is * {@link String } * */ public void setDepot(String value) { this.depot = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\Login.java
2
请完成以下Java代码
public List<Map<String, AttributeValue>> getOrdersAfterDate(String userId, String startDate) { QueryRequest request = QueryRequest.builder() .tableName(TABLE_NAME) .keyConditionExpression("userId = :uid AND orderDate > :startDate") .expressionAttributeValues(Map.of( ":uid", AttributeValue.fromS(userId), ":startDate", AttributeValue.fromS(startDate) )) .build(); return dynamoDb.query(request).items(); } public List<Map<String, AttributeValue>> getOrdersBetweenDates(String userId, String fromDate, String toDate) { QueryRequest request = QueryRequest.builder() .tableName(TABLE_NAME) .keyConditionExpression("userId = :uid AND orderDate BETWEEN :from AND :to") .expressionAttributeValues(Map.of( ":uid", AttributeValue.fromS(userId), ":from", AttributeValue.fromS(fromDate), ":to", AttributeValue.fromS(toDate) )) .build(); return dynamoDb.query(request).items(); } public List<Map<String, AttributeValue>> getOrdersByMonth(String userId, String monthPrefix) { QueryRequest request = QueryRequest.builder() .tableName(TABLE_NAME) .keyConditionExpression("userId = :uid AND begins_with(orderDate, :prefix)") .expressionAttributeValues(Map.of( ":uid", AttributeValue.fromS(userId), ":prefix", AttributeValue.fromS(monthPrefix) )) .build();
return dynamoDb.query(request).items(); } public List<Map<String, AttributeValue>> getAllOrdersPaginated(String userId) { List<Map<String, AttributeValue>> allItems = new ArrayList<>(); Map<String, AttributeValue> lastKey = null; do { QueryRequest.Builder requestBuilder = QueryRequest.builder() .tableName("UserOrders") .keyConditionExpression("userId = :uid") .expressionAttributeValues(Map.of( ":uid", AttributeValue.fromS(userId) )); if (lastKey != null) { requestBuilder.exclusiveStartKey(lastKey); } QueryResponse response = dynamoDb.query(requestBuilder.build()); allItems.addAll(response.items()); lastKey = response.lastEvaluatedKey(); } while (lastKey != null && !lastKey.isEmpty()); return allItems; } }
repos\tutorials-master\aws-modules\aws-dynamodb-v2\src\main\java\com\baeldung\dynamodb\query\UserOrdersRepository.java
1
请完成以下Java代码
public class ClientErrorLoggingFilter extends GenericFilterBean { private static final Logger logger = LogManager.getLogger(ClientErrorLoggingFilter.class); private List<HttpStatus> errorCodes; public ClientErrorLoggingFilter(List<HttpStatus> errorCodes) { this.errorCodes = errorCodes; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); if (auth == null) { chain.doFilter(request, response); return;
} int status = ((HttpServletResponse) response).getStatus(); if (status < 400 || status >= 500) { chain.doFilter(request, response); return; } if (errorCodes == null) { logger.debug("User " + auth.getName() + " encountered error " + status); } else { if (errorCodes.stream() .anyMatch(s -> s.value() == status)) { logger.debug("User " + auth.getName() + " encountered error " + status); } } chain.doFilter(request, response); } }
repos\tutorials-master\spring-security-modules\spring-security-core-3\src\main\java\com\baeldung\dsl\ClientErrorLoggingFilter.java
1
请在Spring Boot框架中完成以下Java代码
public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public ChangeType getType() { return type; } public void setType(ChangeType type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; }
public Date getNoticeTime() { return noticeTime; } public void setNoticeTime(Date noticeTime) { this.noticeTime = noticeTime; } @Override public String toString() { return "ConfigChangeNotice{" + "noticeTime=" + noticeTime + ", appid='" + appid + '\'' + ", type=" + type + ", value='" + value + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\config\ConfigChangeNotice.java
2
请完成以下Java代码
public void setPosition (String Position) { set_Value (COLUMNNAME_Position, Position); } /** Get Position. @return Position */ public String getPosition () { return (String)get_Value(COLUMNNAME_Position); } /** Set Sequence. @param Sequence Sequence */ public void setSequence (BigDecimal Sequence) { set_Value (COLUMNNAME_Sequence, Sequence); } /** Get Sequence. @return Sequence */ public BigDecimal getSequence () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence); if (bd == null) return Env.ZERO; return bd; } /** Set Web Menu.
@param U_WebMenu_ID Web Menu */ public void setU_WebMenu_ID (int U_WebMenu_ID) { if (U_WebMenu_ID < 1) set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null); else set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID)); } /** Get Web Menu. @return Web Menu */ public int getU_WebMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_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_U_WebMenu.java
1
请完成以下Java代码
public HUPIItemProductId getSinglePackToHUPIItemProductId() { return getSingleValue(ScheduledPackageable::getPackToHUPIItemProductId).orElseThrow(() -> new AdempiereException("No single PackToHUPIItemProductId found in " + list)); } public Quantity getQtyToPick() { return list.stream() .map(ScheduledPackageable::getQtyToPick) .reduce(Quantity::add) .orElseThrow(() -> new AdempiereException("No QtyToPick found in " + list)); } public Optional<ShipmentScheduleAndJobScheduleId> getSingleScheduleIdIfUnique() {
final ShipmentScheduleAndJobScheduleIdSet scheduleIds = getScheduleIds(); return scheduleIds.size() == 1 ? Optional.of(scheduleIds.iterator().next()) : Optional.empty(); } public Optional<UomId> getSingleCatchWeightUomIdIfUnique() { final List<UomId> catchWeightUomIds = list.stream() .map(ScheduledPackageable::getCatchWeightUomId) // don't filter out null catch UOMs .distinct() .collect(Collectors.toList()); return catchWeightUomIds.size() == 1 ? Optional.ofNullable(catchWeightUomIds.get(0)) : Optional.empty(); } public Optional<PPOrderId> getSingleManufacturingOrderId() {return getSingleValue(ScheduledPackageable::getPickFromOrderId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageableList.java
1
请完成以下Java代码
public VATCodeMatchingRequest build() { return new VATCodeMatchingRequest(this); } public Builder setC_AcctSchema_ID(final int C_AcctSchema_ID) { this.C_AcctSchema_ID = C_AcctSchema_ID; return this; } public Builder setC_Tax_ID(final int C_Tax_ID) { this.C_Tax_ID = C_Tax_ID; return this;
} public Builder setIsSOTrx(final boolean isSOTrx) { this.isSOTrx = isSOTrx; return this; } public Builder setDate(final Date date) { this.date = date; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\vatcode\VATCodeMatchingRequest.java
1
请完成以下Java代码
public void setM_AttributeValue_ID (int M_AttributeValue_ID) { if (M_AttributeValue_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID)); } /** Get Merkmals-Wert. @return Product Attribute Value */ @Override public int getM_AttributeValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Attribut substitute. @param M_AttributeValue_Mapping_ID Attribut substitute */ @Override public void setM_AttributeValue_Mapping_ID (int M_AttributeValue_Mapping_ID) { if (M_AttributeValue_Mapping_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, Integer.valueOf(M_AttributeValue_Mapping_ID)); } /** Get Attribut substitute. @return Attribut substitute */ @Override public int getM_AttributeValue_Mapping_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_Mapping_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Merkmals-Wert Nach.
@param M_AttributeValue_To_ID Product Attribute Value To */ @Override public void setM_AttributeValue_To_ID (int M_AttributeValue_To_ID) { if (M_AttributeValue_To_ID < 1) set_Value (COLUMNNAME_M_AttributeValue_To_ID, null); else set_Value (COLUMNNAME_M_AttributeValue_To_ID, Integer.valueOf(M_AttributeValue_To_ID)); } /** Get Merkmals-Wert Nach. @return Product Attribute Value To */ @Override public int getM_AttributeValue_To_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_To_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_M_AttributeValue_Mapping.java
1
请在Spring Boot框架中完成以下Java代码
public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } @Nullable public String getPasswordResetKey() { return passwordResetKey; } public void setPasswordResetKey(@Nullable final String passwordResetKey) { this.passwordResetKey = passwordResetKey; }
public void markDeleted() { setDeleted(true); deleted_id = getId(); // FRESH-176: set the delete_id to current ID just to avoid the unique constraint } public void markNotDeleted() { setDeleted(false); deleted_id = null; // FRESH-176: set the delete_id to NULL just to make sure the the unique index is enforced } @Nullable @VisibleForTesting public Long getDeleted_id() { return deleted_id; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\User.java
2
请在Spring Boot框架中完成以下Java代码
public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public Date getCreated() { return created; }
public void setCreated(Date created) { this.created = created; } public String getConfiguration() { return configuration; } public void setConfiguration(String configuration) { this.configuration = configuration; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\EventSubscriptionResponse.java
2
请完成以下Java代码
public String[] getProcessDefinitionKeys() { return processDefinitionKeys; } public String[] getProcessDefinitionKeyNotIn() { return processDefinitionKeyNotIn; } public String getDeploymentId() { return deploymentId; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public String getSubProcessInstanceId() { return subProcessInstanceId; } public SuspensionState getSuspensionState() { return suspensionState; } public void setSuspensionState(SuspensionState suspensionState) { this.suspensionState = suspensionState; } public boolean isWithIncident() { return withIncident; } public String getIncidentId() { return incidentId; } public String getIncidentType() { return incidentType; } public String getIncidentMessage() { return incidentMessage; } public String getIncidentMessageLike() { return incidentMessageLike; } public String getCaseInstanceId() { return caseInstanceId; } public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getSubCaseInstanceId() { return subCaseInstanceId; } public boolean isTenantIdSet() { return isTenantIdSet; } public boolean isRootProcessInstances() { return isRootProcessInstances; }
public boolean isProcessDefinitionWithoutTenantId() { return isProcessDefinitionWithoutTenantId; } public boolean isLeafProcessInstances() { return isLeafProcessInstances; } public String[] getTenantIds() { return tenantIds; } @Override public ProcessInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public ProcessInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
protected final void assertActive(final String errmsg) { assertActive(true, errmsg); } public List<ITrxSavepoint> getActiveSavepoints() { return ImmutableList.copyOf(activeSavepoints); } protected final void assertNotActive(final String errmsg) { assertActive(false, errmsg); } protected void assertActive(final boolean activeExpected, final String errmsg) { final boolean activeActual = isActive(); if (activeActual != activeExpected) { final String errmsgToUse = "Inconsistent transaction state: " + errmsg; throw new TrxException(errmsgToUse + "\n Expected active: " + activeExpected + "\n Actual active: " + activeActual + "\n Trx: " + this); } } private TrxStatus getTrxStatus() { return trxStatus; } private void setTrxStatus(final TrxStatus trxStatus) { final String detailMsg = null; setTrxStatus(trxStatus, detailMsg); } private void setTrxStatus(final TrxStatus trxStatus, @Nullable final String detailMsg) { final TrxStatus trxStatusOld = this.trxStatus; this.trxStatus = trxStatus;
// Log it if (debugLog != null) { final StringBuilder msg = new StringBuilder(); msg.append(trxStatusOld).append("->").append(trxStatus); if (!Check.isEmpty(detailMsg, true)) { msg.append(" (").append(detailMsg).append(")"); } logTrxAction(msg.toString()); } } private void logTrxAction(final String message) { if (debugLog == null) { return; } debugLog.add(message); logger.info("{}: trx action: {}", getTrxName(), message); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrx.java
1
请完成以下Java代码
public final class ViewRowsOrderBy { public static ViewRowsOrderBy of(final DocumentQueryOrderByList orderBys, @NonNull final JSONOptions jsonOpts) { return new ViewRowsOrderBy(orderBys, jsonOpts); } public static ViewRowsOrderBy parseString(final String orderBysListStr, @NonNull final JSONOptions jsonOpts) { final DocumentQueryOrderByList orderBys = DocumentQueryOrderByList.parse(orderBysListStr); return of(orderBys, jsonOpts); } public static ViewRowsOrderBy empty(@NonNull final JSONOptions jsonOpts) { return new ViewRowsOrderBy(DocumentQueryOrderByList.EMPTY, jsonOpts); } private final DocumentQueryOrderByList orderBys; private final JSONOptions jsonOpts; private ViewRowsOrderBy(final DocumentQueryOrderByList orderBys, @NonNull final JSONOptions jsonOpts) { this.orderBys = orderBys != null ? orderBys : DocumentQueryOrderByList.EMPTY; this.jsonOpts = jsonOpts; } public boolean isEmpty() { return orderBys.isEmpty(); } public DocumentQueryOrderByList toDocumentQueryOrderByList() { return orderBys; }
public ViewRowsOrderBy withOrderBys(final DocumentQueryOrderByList orderBys) { if (DocumentQueryOrderByList.equals(this.orderBys, orderBys)) { return this; } else { return new ViewRowsOrderBy(orderBys, jsonOpts); } } public <T extends IViewRow> Comparator<T> toComparator() { return orderBys.toComparator(IViewRow::getFieldValueAsComparable, jsonOpts); } public <T extends IViewRow> Comparator<T> toComparatorOrNull() { return !orderBys.isEmpty() ? toComparator() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowsOrderBy.java
1
请完成以下Java代码
public void setSelected(boolean selected) { final boolean old = m_selected; m_selected = selected; this.pcs.firePropertyChange( "selected", old, m_selected ); } /** * Is Selected * @return true if selected */ public boolean isSelected() { return m_selected; } /** * Set Record_ID * @param record_ID */ public void setRecord_ID(Integer record_ID) { m_record_ID = record_ID; } /** * Get Record ID * @return ID */ public Integer getRecord_ID() { return m_record_ID; } /** * To String * @return String representation
*/ @Override public String toString() { return "IDColumn - ID=" + m_record_ID + ", Selected=" + m_selected; } // toString public void addPropertyChangeListener( PropertyChangeListener listener ) { this.pcs.addPropertyChangeListener( listener ); } public void removePropertyChangeListener( PropertyChangeListener listener ) { this.pcs.removePropertyChangeListener( listener ); } } // IDColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\minigrid\IDColumn.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getChannelType() { return channelType; }
public void setChannelType(String channelType) { this.channelType = channelType; } public String getType() { return type; } public void setType(String type) { this.type = type; } public JsonNode getExtension() { return extension; } public void setExtension(JsonNode extension) { this.extension = extension; } }
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\ChannelModel.java
1
请完成以下Java代码
public class EntityRelationInfo extends EntityRelation { private static final long serialVersionUID = 2807343097519543363L; private String fromName; private String toName; public EntityRelationInfo() { super(); } public EntityRelationInfo(EntityRelation entityRelation) { super(entityRelation); } @Schema(description = "Name of the entity for [from] direction.", accessMode = Schema.AccessMode.READ_ONLY, example = "A4B72CCDFF33") public String getFromName() { return fromName; } public void setFromName(String fromName) { this.fromName = fromName; } @Schema(description = "Name of the entity for [to] direction.", accessMode = Schema.AccessMode.READ_ONLY, example = "A4B72CCDFF35") public String getToName() { return toName; }
public void setToName(String toName) { this.toName = toName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; EntityRelationInfo that = (EntityRelationInfo) o; return toName != null ? toName.equals(that.toName) : that.toName == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (toName != null ? toName.hashCode() : 0); return result; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\relation\EntityRelationInfo.java
1
请完成以下Java代码
public DateSequenceGeneratorBuilder byNthDay(final int day) { return incrementor(CalendarIncrementors.eachNthDay(day)); } public DateSequenceGeneratorBuilder byWeeks(final int week, final DayOfWeek dayOfWeek) { return incrementor(CalendarIncrementors.eachNthWeek(week, dayOfWeek)); } public DateSequenceGeneratorBuilder byMonths(final int months, final int dayOfMonth) { return incrementor(CalendarIncrementors.eachNthMonth(months, dayOfMonth)); } public DateSequenceGeneratorBuilder frequency(@NonNull final Frequency frequency) { incrementor(createCalendarIncrementor(frequency)); exploder(createDateSequenceExploder(frequency)); return this; } private static ICalendarIncrementor createCalendarIncrementor(final Frequency frequency) { if (frequency.isWeekly()) { return CalendarIncrementors.eachNthWeek(frequency.getEveryNthWeek(), DayOfWeek.MONDAY); } else if (frequency.isMonthly()) { return CalendarIncrementors.eachNthMonth(frequency.getEveryNthMonth(), 1); // every given month, 1st day } else { throw new IllegalArgumentException("Frequency type not supported for " + frequency); } }
private static IDateSequenceExploder createDateSequenceExploder(final Frequency frequency) { if (frequency.isWeekly()) { if (frequency.isOnlySomeDaysOfTheWeek()) { return DaysOfWeekExploder.of(frequency.getOnlyDaysOfWeek()); } else { return DaysOfWeekExploder.ALL_DAYS_OF_WEEK; } } else if (frequency.isMonthly()) { return DaysOfMonthExploder.of(frequency.getOnlyDaysOfMonth()); } else { throw new IllegalArgumentException("Frequency type not supported for " + frequency); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DateSequenceGenerator.java
1
请完成以下Java代码
public List<HotelOffer> searchOffers(String city, String checkIn, int nights, int guests) { Objects.requireNonNull(city, "city"); Objects.requireNonNull(checkIn, "checkIn"); LocalDate.parse(checkIn); return inventory.stream() .filter(h -> h.city().equalsIgnoreCase(city)) .filter(h -> h.maxGuests() >= guests) .map(h -> toOffer(h, nights, guests)) .sorted(Comparator.comparingInt(HotelOffer::totalPrice)) .toList(); } public Booking createBooking(String hotelId, String checkIn, int nights, int guests, String guestName) { Objects.requireNonNull(hotelId, "hotelId"); Objects.requireNonNull(checkIn, "checkIn"); Objects.requireNonNull(guestName, "guestName"); LocalDate.parse(checkIn); Hotel hotel = inventory.stream() .filter(h -> h.id().equalsIgnoreCase(hotelId)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Unknown hotelId: " + hotelId)); if (hotel.maxGuests() < guests) { throw new IllegalArgumentException("Guest count exceeds hotel maxGuests"); } HotelOffer offer = toOffer(hotel, nights, guests); return new Booking( "BK-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase(), hotel.id(), hotel.name(), hotel.city(), checkIn, nights, guests, guestName, offer.totalPrice(), "CONFIRMED" ); } private HotelOffer toOffer(Hotel hotel, int nights, int guests) { int perNight = hotel.basePricePerNight() + Math.max(0, guests - 1) * 25; int total = Math.max(1, nights) * perNight; return new HotelOffer(hotel.id(), hotel.name(), hotel.city(), perNight, total, hotel.maxGuests());
} public record Hotel(String id, String name, String city, int basePricePerNight, int maxGuests) { } public record HotelOffer( String hotelId, String hotelName, String city, int pricePerNight, int totalPrice, int maxGuests ) { } public record Booking( String bookingId, String hotelId, String hotelName, String city, String checkIn, int nights, int guests, String guestName, int totalPrice, String status ) { } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HotelService.java
1
请在Spring Boot框架中完成以下Java代码
private boolean anyPathsDontStartWithLeadingSlash(String... patterns) { for (String pattern : patterns) { if (!pattern.startsWith("/")) { return true; } } return false; } /** * <p> * Match when the request URI matches one of {@code patterns}. See * {@link org.springframework.web.util.pattern.PathPattern} for matching rules. * </p> * <p> * If a specific {@link RequestMatcher} must be specified, use * {@link #requestMatchers(RequestMatcher...)} instead * </p> * @param patterns the patterns to match on * @return the object that is chained after creating the {@link RequestMatcher}. * @since 5.8 */ public C requestMatchers(String... patterns) { return requestMatchers(null, patterns); } /** * <p> * Match when the {@link HttpMethod} is {@code method}
* </p> * <p> * If a specific {@link RequestMatcher} must be specified, use * {@link #requestMatchers(RequestMatcher...)} instead * </p> * @param method the {@link HttpMethod} to use or {@code null} for any * {@link HttpMethod}. * @return the object that is chained after creating the {@link RequestMatcher}. * @since 5.8 */ public C requestMatchers(HttpMethod method) { return requestMatchers(method, "/**"); } /** * Subclasses should implement this method for returning the object that is chained to * the creation of the {@link RequestMatcher} instances. * @param requestMatchers the {@link RequestMatcher} instances that were created * @return the chained Object for the subclass which allows association of something * else to the {@link RequestMatcher} */ protected abstract C chainRequestMatchers(List<RequestMatcher> requestMatchers); }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\AbstractRequestMatcherRegistry.java
2
请完成以下Java代码
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { delegate.addPropertyChangeListener(propertyName, listener); } public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) { delegate.removePropertyChangeListener(propertyName, listener); } public PropertyChangeListener[] getPropertyChangeListeners(final String propertyName) { return delegate.getPropertyChangeListeners(propertyName); } public boolean hasListeners(final String propertyName) { return delegate.hasListeners(propertyName); } public final void firePropertyChange(final PropertyChangeEvent event) { if (delayedEvents != null) { delayedEvents.add(event); } else { delegate.firePropertyChange(event); } } public void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue) { final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue); firePropertyChange(event); } public void firePropertyChange(final String propertyName, final int oldValue, final int newValue) { final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue); firePropertyChange(event); } public void firePropertyChange(final String propertyName, final boolean oldValue, final boolean newValue) { final PropertyChangeEvent event = new PropertyChangeEvent(source, propertyName, oldValue, newValue);
firePropertyChange(event); } public void fireIndexedPropertyChange(final String propertyName, final int index, final Object oldValue, final Object newValue) { final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index); firePropertyChange(event); } public void fireIndexedPropertyChange(final String propertyName, final int index, final int oldValue, final int newValue) { final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index); firePropertyChange(event); } public void fireIndexedPropertyChange(final String propertyName, final int index, final boolean oldValue, final boolean newValue) { final IndexedPropertyChangeEvent event = new IndexedPropertyChangeEvent(source, propertyName, oldValue, newValue, index); firePropertyChange(event); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\beans\DelayedPropertyChangeSupport.java
1
请完成以下Java代码
public class SignUtil { /** * 验证签名 * * @param signature * @param timestamp * @param nonce * @return */ public static boolean checkSignature(String token, String signature, String timestamp, String nonce) { String[] arr = new String[]{token, timestamp, nonce}; // 将token、timestamp、nonce三个参数进行字典序排序 Arrays.sort(arr); StringBuilder content = new StringBuilder(); for (int i = 0; i < arr.length; i++) { content.append(arr[i]); } MessageDigest md = null; String tmpStr = null; try { md = MessageDigest.getInstance("SHA-1"); // 将三个参数字符串拼接成一个字符串进行sha1加密 byte[] digest = md.digest(content.toString().getBytes()); tmpStr = byteToStr(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } content = null; // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信 return tmpStr != null && tmpStr.equals(signature.toUpperCase()); } /** * 将字节数组转换为十六进制字符串 * * @param byteArray * @return */
private static String byteToStr(byte[] byteArray) { String strDigest = ""; for (int i = 0; i < byteArray.length; i++) { strDigest += byteToHexStr(byteArray[i]); } return strDigest; } /** * 将字节转换为十六进制字符串 * * @param mByte * @return */ private static String byteToHexStr(byte mByte) { char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; char[] tempArr = new char[2]; tempArr[0] = Digit[(mByte >>> 4) & 0X0F]; tempArr[1] = Digit[mByte & 0X0F]; return new String(tempArr); } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\utils\SignUtil.java
1
请完成以下Java代码
public void setA_Asset_Retirement_ID (int A_Asset_Retirement_ID) { if (A_Asset_Retirement_ID < 1) set_ValueNoCheck (COLUMNNAME_A_Asset_Retirement_ID, null); else set_ValueNoCheck (COLUMNNAME_A_Asset_Retirement_ID, Integer.valueOf(A_Asset_Retirement_ID)); } /** Get Asset Retirement. @return Internally used asset is not longer used. */ public int getA_Asset_Retirement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Retirement_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Retirement_ID())); } /** Set Market value Amount. @param AssetMarketValueAmt Market value of the asset */ public void setAssetMarketValueAmt (BigDecimal AssetMarketValueAmt) { set_Value (COLUMNNAME_AssetMarketValueAmt, AssetMarketValueAmt); } /** Get Market value Amount. @return Market value of the asset */ public BigDecimal getAssetMarketValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetMarketValueAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Asset value.
@param AssetValueAmt Book Value of the asset */ public void setAssetValueAmt (BigDecimal AssetValueAmt) { set_Value (COLUMNNAME_AssetValueAmt, AssetValueAmt); } /** Get Asset value. @return Book Value of the asset */ public BigDecimal getAssetValueAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AssetValueAmt); if (bd == null) return Env.ZERO; return bd; } public I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException { return (I_C_InvoiceLine)MTable.get(getCtx(), I_C_InvoiceLine.Table_Name) .getPO(getC_InvoiceLine_ID(), get_TrxName()); } /** Set Invoice Line. @param C_InvoiceLine_ID Invoice Detail Line */ public void setC_InvoiceLine_ID (int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_Value (COLUMNNAME_C_InvoiceLine_ID, null); else set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID)); } /** Get Invoice Line. @return Invoice Detail Line */ public int getC_InvoiceLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_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_A_Asset_Retirement.java
1
请完成以下Java代码
default OptionalBoolean toOptionalBoolean() { return isConstant() ? OptionalBoolean.ofBoolean(constantValue()) : OptionalBoolean.UNKNOWN; } @Override default boolean isNoResult(final Object result) { // because evaluation is throwing exception in case of failure, the only "no result" would be the NULL return result == null; } @Override default boolean isNullExpression() { // there is no such thing for logic expressions return false; } /** * Compose this logic expression with the given one, using logic AND and return it */ default ILogicExpression and(final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_AND, expression);
} default ILogicExpression andNot(final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_AND, expression.negate()); } /** * Compose this logic expression with the given one, using logic OR and return it */ default ILogicExpression or(final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_OR, expression); } default ILogicExpression negate() { // NOTE: because we don't have unary operator support atm, we will use XOR as : !a = a XOR true //return xor(TRUE); fails, TRUE==null !! return xor(ConstantLogicExpression.TRUE); // works, not null! } default ILogicExpression xor(@NonNull final ILogicExpression expression) { return LogicExpressionBuilder.build(this, LOGIC_OPERATOR_XOR, expression); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\ILogicExpression.java
1
请完成以下Java代码
private Map<String, Object> getAttributes() { return _attributes; } public InfoBuilder setInfoWindow(final I_AD_InfoWindow infoWindow) { _infoWindowDef = infoWindow; if (infoWindow != null) { final String tableName = Services.get(IADInfoWindowBL.class).getTableName(infoWindow); setTableName(tableName); } return this; } private I_AD_InfoWindow getInfoWindow() { if (_infoWindowDef != null) { return _infoWindowDef; } final String tableName = getTableName(); final I_AD_InfoWindow infoWindowFound = Services.get(IADInfoWindowDAO.class).retrieveInfoWindowByTableName(getCtx(), tableName); if (infoWindowFound != null && infoWindowFound.isActive()) { return infoWindowFound; } return null;
} /** * @param iconName icon name (without size and without file extension). */ public InfoBuilder setIconName(final String iconName) { if (Check.isEmpty(iconName, true)) { return setIcon(null); } else { final Image icon = Images.getImage2(iconName + "16"); return setIcon(icon); } } public InfoBuilder setIcon(final Image icon) { this._iconImage = icon; return this; } private Image getIconImage() { return _iconImage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoBuilder.java
1
请完成以下Java代码
public void setData_Export_Audit_Parent(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit_Parent) { set_ValueFromPO(COLUMNNAME_Data_Export_Audit_Parent_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit_Parent); } @Override public void setData_Export_Audit_Parent_ID (final int Data_Export_Audit_Parent_ID) { if (Data_Export_Audit_Parent_ID < 1) set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, null); else set_Value (COLUMNNAME_Data_Export_Audit_Parent_ID, Data_Export_Audit_Parent_ID); } @Override public int getData_Export_Audit_Parent_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Parent_ID); }
@Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit.java
1
请在Spring Boot框架中完成以下Java代码
public class PageIndex { public static PageIndex ofFirstRowAndPageLength(final int firstRow, final int pageLength) { return new PageIndex(firstRow, pageLength); } public static PageIndex getPageContainingRow(final int rowIndex, final int pageLength) { Check.assume(rowIndex >= 0, "rowIndex >= 0"); Check.assume(pageLength > 0, "pageLength > 0"); final int page = rowIndex / pageLength; final int firstRow = page * pageLength;
return ofFirstRowAndPageLength(firstRow, pageLength); } int firstRow; int pageLength; private PageIndex(final int firstRow, final int pageLength) { Check.assume(firstRow >= 0, "firstRow >= 0"); Check.assume(pageLength > 0, "pageLength > 0"); this.firstRow = firstRow; this.pageLength = pageLength; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\util\PageIndex.java
2
请完成以下Java代码
public static String createTweet(String tweet) throws TwitterException { Twitter twitter = getTwitterinstance(); Status status = twitter.updateStatus("creating baeldung API"); return status.getText(); } public static List<String> getTimeLine() throws TwitterException { Twitter twitter = getTwitterinstance(); List<Status> statuses = twitter.getHomeTimeline(); return statuses.stream().map( item -> item.getText()).collect( Collectors.toList()); } public static String sendDirectMessage(String recipientName, String msg) throws TwitterException { Twitter twitter = getTwitterinstance(); DirectMessage message = twitter.sendDirectMessage(recipientName, msg); return message.getText(); } public static List<String> searchtweets() throws TwitterException { Twitter twitter = getTwitterinstance(); Query query = new Query("source:twitter4j baeldung"); QueryResult result = twitter.search(query); List<Status> statuses = result.getTweets(); return statuses.stream().map( item -> item.getText()).collect( Collectors.toList()); } public static void streamFeed() { StatusListener listener = new StatusListener(){ @Override public void onException(Exception e) { e.printStackTrace(); } @Override public void onDeletionNotice(StatusDeletionNotice arg) { System.out.println("Got a status deletion notice id:" + arg.getStatusId()); } @Override public void onScrubGeo(long userId, long upToStatusId) { System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); }
@Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); } @Override public void onStatus(Status status) { System.out.println(status.getUser().getName() + " : " + status.getText()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } }; TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); twitterStream.addListener(listener); twitterStream.sample(); } }
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
1
请完成以下Java代码
public GatewayFilter apply(MapRequestHeaderGatewayFilterFactory.Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String fromHeader = Objects.requireNonNull(config.getFromHeader(), "fromHeader must be set"); String toHeader = Objects.requireNonNull(config.getToHeader(), "toHeader must be set"); if (!exchange.getRequest().getHeaders().containsHeader(fromHeader)) { return chain.filter(exchange); } List<String> headerValues = exchange.getRequest().getHeaders().get(fromHeader); if (headerValues == null) { return chain.filter(exchange); } ServerHttpRequest request = exchange.getRequest() .mutate() .headers(i -> i.addAll(toHeader, headerValues)) .build(); return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() { // @formatter:off String fromHeader = config.getFromHeader(); String toHeader = config.getToHeader(); return filterToStringCreator(MapRequestHeaderGatewayFilterFactory.this) .append(FROM_HEADER_KEY, fromHeader != null ? fromHeader : "") .append(TO_HEADER_KEY, toHeader != null ? toHeader : "") .toString(); // @formatter:on } }; } public static class Config { private @Nullable String fromHeader; private @Nullable String toHeader; public @Nullable String getFromHeader() {
return this.fromHeader; } public Config setFromHeader(String fromHeader) { this.fromHeader = fromHeader; return this; } public @Nullable String getToHeader() { return this.toHeader; } public Config setToHeader(String toHeader) { this.toHeader = toHeader; return this; } @Override public String toString() { // @formatter:off return new ToStringCreator(this) .append("fromHeader", fromHeader) .append("toHeader", toHeader) .toString(); // @formatter:on } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\MapRequestHeaderGatewayFilterFactory.java
1
请完成以下Java代码
public static <T> Stream<List<T>> dice(@NonNull final Stream<T> stream, final int maxChunkSize, @Nullable final Function<T, Object> groupByKeyExtractor) { if (maxChunkSize <= 0) { throw new IllegalArgumentException("chunkSize shall be > 0"); } final PeekIterator<T> streamIterator = IteratorUtils.asPeekIterator(stream.iterator()); return IteratorUtils.stream(() -> readChunkOrNull(streamIterator, maxChunkSize, groupByKeyExtractor)); } @Nullable private static <T> List<T> readChunkOrNull( @NonNull final PeekIterator<T> iterator, final int maxChunkSize, @Nullable final Function<T, Object> groupByKeyExtractor) { Object previousGroupKey = null; boolean isFirstItem = true; final List<T> list = new ArrayList<>(maxChunkSize); while (iterator.hasNext() && list.size() < maxChunkSize) { final T item = iterator.peek(); if(groupByKeyExtractor != null) { final Object groupKey = groupByKeyExtractor.apply(item); if (isFirstItem) { previousGroupKey = groupKey; } else if (!Objects.equals(previousGroupKey, groupKey)) { break; } } list.add(iterator.next()); isFirstItem = false; } return !list.isEmpty() ? list : null; }
/** * Thanks to <a href="https://stackoverflow.com/a/27872852/1012103">https://stackoverflow.com/a/27872852/1012103</a> */ public static <T> Predicate<T> distinctByKey(@NonNull final Function<? super T, Object> keyExtractor) { final Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } @SafeVarargs public static <T> Stream<T> concat(final Stream<T>... streams) { if (streams.length == 0) { return Stream.empty(); } else if (streams.length == 1) { return streams[0]; } else if (streams.length == 2) { return Stream.concat(streams[0], streams[1]); } else { Stream<T> result = streams[0]; for (int i = 1; i < streams.length; i++) { result = Stream.concat(result, streams[i]); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\StreamUtils.java
1
请在Spring Boot框架中完成以下Java代码
public int getMaxTimeBetweenPings() { return this.maxTimeBetweenPings; } public void setMaxTimeBetweenPings(int maxTimeBetweenPings) { this.maxTimeBetweenPings = maxTimeBetweenPings; } public int getMessageTimeToLive() { return this.messageTimeToLive; } public void setMessageTimeToLive(int messageTimeToLive) { this.messageTimeToLive = messageTimeToLive; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public int getSocketBufferSize() { return this.socketBufferSize; } public void setSocketBufferSize(int socketBufferSize) { this.socketBufferSize = socketBufferSize; }
public int getSubscriptionCapacity() { return this.subscriptionCapacity; } public void setSubscriptionCapacity(int subscriptionCapacity) { this.subscriptionCapacity = subscriptionCapacity; } public String getSubscriptionDiskStoreName() { return this.subscriptionDiskStoreName; } public void setSubscriptionDiskStoreName(String subscriptionDiskStoreName) { this.subscriptionDiskStoreName = subscriptionDiskStoreName; } public SubscriptionEvictionPolicy getSubscriptionEvictionPolicy() { return this.subscriptionEvictionPolicy; } public void setSubscriptionEvictionPolicy(SubscriptionEvictionPolicy subscriptionEvictionPolicy) { this.subscriptionEvictionPolicy = subscriptionEvictionPolicy; } public boolean isTcpNoDelay() { return this.tcpNoDelay; } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheServerProperties.java
2
请在Spring Boot框架中完成以下Java代码
abstract class ServiceOrRepairProjectBasedProcess extends JavaProcess { protected final ServiceRepairProjectService projectService = SpringContextHolder.instance.getBean(ServiceRepairProjectService.class); protected ProcessPreconditionsResolution checkIsServiceOrRepairProject(@NonNull final ProjectId projectId) { return projectService.isServiceOrRepair(projectId) ? ProcessPreconditionsResolution.accept() : ProcessPreconditionsResolution.rejectWithInternalReason("not Service/Repair project"); } protected ProjectId getProjectId() { return ProjectId.ofRepoId(getRecord_ID()); } protected ServiceRepairProjectInfo getProject() { final ProjectId projectId = getProjectId(); return projectService.getById(projectId); } protected ServiceRepairProjectTaskId getSingleSelectedTaskId() { return CollectionUtils.singleElement(getSelectedTaskIds()); } protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds() { final ProjectId projectId = getProjectId(); return getSelectedIncludedRecordIds(I_C_Project_Repair_Task.class) .stream() .map(taskRepoId -> ServiceRepairProjectTaskId.ofRepoId(projectId, taskRepoId)) .collect(ImmutableSet.toImmutableSet()); } protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedSparePartsTaskIds(final @NonNull IProcessPreconditionsContext context) { final ImmutableSet<ServiceRepairProjectTaskId> taskIds = getSelectedTaskIds(context);
return projectService.retainIdsOfTypeSpareParts(taskIds); } protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds(final @NonNull IProcessPreconditionsContext context) { final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId()); if (projectId == null) { return ImmutableSet.of(); } return context.getSelectedIncludedRecords() .stream() .filter(recordRef -> I_C_Project_Repair_Task.Table_Name.equals(recordRef.getTableName())) .map(recordRef -> ServiceRepairProjectTaskId.ofRepoId(projectId, recordRef.getRecord_ID())) .collect(ImmutableSet.toImmutableSet()); } protected List<ServiceRepairProjectTask> getSelectedTasks(final @NonNull IProcessPreconditionsContext context) { return projectService.getTasksByIds(getSelectedTaskIds(context)); } protected List<ServiceRepairProjectTask> getSelectedTasks() { return projectService.getTasksByIds(getSelectedTaskIds()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\ServiceOrRepairProjectBasedProcess.java
2
请完成以下Java代码
public int getPP_Order_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed);
} @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_Value (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Line.java
1
请完成以下Java代码
public class ProductVO { /** * 商品编号 */ @JacksonXmlProperty(localName = "id") private Integer id; /** * 商品标题 */ @JacksonXmlProperty(localName = "title") private String title; public Integer getId() { return id; }
public ProductVO setId(Integer id) { this.id = id; return this; } public String getTitle() { return title; } public ProductVO setTitle(String title) { this.title = title; return this; } }
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-02\src\main\java\cn\iocoder\springboot\lab23\springmvc\vo\ProductVO.java
1
请完成以下Java代码
public ZipType getZip() { return zip; } /** * Sets the value of the zip property. * * @param value * allowed object is * {@link ZipType } * */ public void setZip(ZipType value) { this.zip = value; } /** * Gets the value of the city property. * * @return * possible object is * {@link String }
* */ public String getCity() { return city; } /** * Sets the value of the city property. * * @param value * allowed object is * {@link String } * */ public void setCity(String value) { this.city = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\PostalAddressType.java
1
请完成以下Java代码
private static final class GridTabAsPreconditionsContext implements IProcessPreconditionsContext { private final GridTab gridTab; private GridTabAsPreconditionsContext(final GridTab gridTab) { this.gridTab = gridTab; } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(gridTab).toString(); } @Override public AdWindowId getAdWindowId() { return gridTab.getAdWindowId(); } @Override public AdTabId getAdTabId() { return AdTabId.ofRepoId(gridTab.getAD_Tab_ID()); } @Override public String getTableName() { return gridTab.getTableName(); } @Override public <T> T getSelectedModel(final Class<T> modelClass) { return gridTab.getModel(modelClass); } @Override public <T> List<T> getSelectedModels(final Class<T> modelClass) { // backward compatibility return streamSelectedModels(modelClass) .collect(ImmutableList.toImmutableList()); } @NonNull @Override public <T> Stream<T> streamSelectedModels(@NonNull final Class<T> modelClass) { return Stream.of(getSelectedModel(modelClass));
} @Override public int getSingleSelectedRecordId() { return gridTab.getRecord_ID(); } @Override public SelectionSize getSelectionSize() { // backward compatibility return SelectionSize.ofSize(1); } @Override public <T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass) { return gridTab.createCurrentRecordsQueryFilter(recordClass); } } } // GridTab
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTab.java
1
请完成以下Java代码
public final class ExchangeRate { private static final String DEFAULT_PROVIDER = "com.baeldung.rate.spi.YahooFinanceExchangeRateProvider"; //All providers public static List<ExchangeRateProvider> providers() { List<ExchangeRateProvider> services = new ArrayList<>(); ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class); loader.forEach(services::add); return services; } //Default provider public static ExchangeRateProvider provider() { return provider(DEFAULT_PROVIDER);
} //provider by name public static ExchangeRateProvider provider(String providerName) { ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class); Iterator<ExchangeRateProvider> it = loader.iterator(); while (it.hasNext()) { ExchangeRateProvider provider = it.next(); if (providerName.equals(provider.getClass().getName())) { return provider; } } throw new ProviderNotFoundException("Exchange Rate provider " + providerName + " not found"); } }
repos\tutorials-master\core-java-modules\java-spi\exchange-rate-api\src\main\java\com\baeldung\rate\ExchangeRate.java
1
请完成以下Java代码
public LookupValuesList getFieldDropdown(@NonNull final String fieldName) { return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), 20).getValues(); } private LookupDataSource getLookupDataSource(@NonNull final String fieldName) { if (PricingConditionsRow.FIELDNAME_PaymentTerm.equals(fieldName)) { return paymentTermLookup; } else if (PricingConditionsRow.FIELDNAME_BasePriceType.equals(fieldName)) { return priceTypeLookup; } else if (PricingConditionsRow.FIELDNAME_BasePricingSystem.equals(fieldName)) { return pricingSystemLookup; } else if (PricingConditionsRow.FIELDNAME_C_Currency_ID.equals(fieldName)) { return currencyIdLookup; } else {
throw new AdempiereException("Field " + fieldName + " does not exist or it's not a lookup field"); } } public String getTemporaryPriceConditionsColor() { return temporaryPriceConditionsColorCache.getOrLoad(0, this::retrieveTemporaryPriceConditionsColor); } private String retrieveTemporaryPriceConditionsColor() { final ColorId temporaryPriceConditionsColorId = Services.get(IOrderLinePricingConditions.class).getTemporaryPriceConditionsColorId(); return toHexString(Services.get(IColorRepository.class).getColorById(temporaryPriceConditionsColorId)); } private static String toHexString(@Nullable final MFColor color) { if (color == null) { return null; } final Color awtColor = color.toFlatColor().getFlatColor(); return ColorValue.toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowLookups.java
1