instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public org.compiere.model.I_AD_Sequence getAD_Sequence_ProjectValue() { return get_ValueAsPO(COLUMNNAME_AD_Sequence_ProjectValue_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setAD_Sequence_ProjectValue(final org.compiere.model.I_AD_Sequence AD_Sequence_ProjectValue) { set_ValueFromPO(COLUMNNAME_AD_Sequence_ProjectValue_ID, org.compiere.model.I_AD_Sequence.class, AD_Sequence_ProjectValue); } @Override public void setAD_Sequence_ProjectValue_ID (final int AD_Sequence_ProjectValue_ID) { if (AD_Sequence_ProjectValue_ID < 1) set_Value (COLUMNNAME_AD_Sequence_ProjectValue_ID, null); else set_Value (COLUMNNAME_AD_Sequence_ProjectValue_ID, AD_Sequence_ProjectValue_ID); } @Override public int getAD_Sequence_ProjectValue_ID() { return get_ValueAsInt(COLUMNNAME_AD_Sequence_ProjectValue_ID); } @Override public void setC_ProjectType_ID (final int C_ProjectType_ID) { if (C_ProjectType_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ProjectType_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ProjectType_ID, C_ProjectType_ID); } @Override public int getC_ProjectType_ID() { return get_ValueAsInt(COLUMNNAME_C_ProjectType_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setHelp (final @Nullable java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
@Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * ProjectCategory AD_Reference_ID=288 * Reference name: C_ProjectType Category */ public static final int PROJECTCATEGORY_AD_Reference_ID=288; /** General = N */ public static final String PROJECTCATEGORY_General = "N"; /** AssetProject = A */ public static final String PROJECTCATEGORY_AssetProject = "A"; /** WorkOrderJob = W */ public static final String PROJECTCATEGORY_WorkOrderJob = "W"; /** ServiceChargeProject = S */ public static final String PROJECTCATEGORY_ServiceChargeProject = "S"; /** ServiceOrRepair = R */ public static final String PROJECTCATEGORY_ServiceOrRepair = "R"; /** SalesPurchaseOrder = O */ public static final String PROJECTCATEGORY_SalesPurchaseOrder = "O"; @Override public void setProjectCategory (final java.lang.String ProjectCategory) { set_ValueNoCheck (COLUMNNAME_ProjectCategory, ProjectCategory); } @Override public java.lang.String getProjectCategory() { return get_ValueAsString(COLUMNNAME_ProjectCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectType.java
1
请完成以下Java代码
public void setAD_Language (String AD_Language) { set_Value (COLUMNNAME_AD_Language, AD_Language); } /** Get Language. @return Language for this entity */ public String getAD_Language () { return (String)get_Value(COLUMNNAME_AD_Language); } /** Set Knowledge Synonym. @param K_Synonym_ID Knowlege Keyword Synonym */ public void setK_Synonym_ID (int K_Synonym_ID) { if (K_Synonym_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Synonym_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Synonym_ID, Integer.valueOf(K_Synonym_ID)); } /** Get Knowledge Synonym. @return Knowlege Keyword Synonym */ public int getK_Synonym_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Synonym_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name);
} /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Synonym Name. @param SynonymName The synonym for the name */ public void setSynonymName (String SynonymName) { set_Value (COLUMNNAME_SynonymName, SynonymName); } /** Get Synonym Name. @return The synonym for the name */ public String getSynonymName () { return (String)get_Value(COLUMNNAME_SynonymName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Synonym.java
1
请完成以下Java代码
public abstract class SequentialByEntityIdTbRuleEngineSubmitStrategy extends AbstractTbRuleEngineSubmitStrategy { private volatile BiConsumer<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgConsumer; private volatile ConcurrentMap<UUID, EntityId> msgToEntityIdMap = new ConcurrentHashMap<>(); private volatile ConcurrentMap<EntityId, Queue<IdMsgPair<TransportProtos.ToRuleEngineMsg>>> entityIdToListMap = new ConcurrentHashMap<>(); public SequentialByEntityIdTbRuleEngineSubmitStrategy(String queueName) { super(queueName); } @Override public void init(List<TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgs) { super.init(msgs); initMaps(); } @Override public void submitAttempt(BiConsumer<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> msgConsumer) { this.msgConsumer = msgConsumer; entityIdToListMap.forEach((entityId, queue) -> { IdMsgPair<TransportProtos.ToRuleEngineMsg> msg = queue.peek(); if (msg != null) { msgConsumer.accept(msg.uuid, msg.msg); } }); } @Override public void update(ConcurrentMap<UUID, TbProtoQueueMsg<TransportProtos.ToRuleEngineMsg>> reprocessMap) { super.update(reprocessMap); initMaps(); } @Override protected void doOnSuccess(UUID id) { EntityId entityId = msgToEntityIdMap.get(id); if (entityId != null) { Queue<IdMsgPair<TransportProtos.ToRuleEngineMsg>> queue = entityIdToListMap.get(entityId); if (queue != null) { IdMsgPair<TransportProtos.ToRuleEngineMsg> next = null; synchronized (queue) {
IdMsgPair<TransportProtos.ToRuleEngineMsg> expected = queue.peek(); if (expected != null && expected.uuid.equals(id)) { queue.poll(); next = queue.peek(); } } if (next != null) { msgConsumer.accept(next.uuid, next.msg); } } } } private void initMaps() { msgToEntityIdMap.clear(); entityIdToListMap.clear(); for (IdMsgPair<TransportProtos.ToRuleEngineMsg> pair : orderedMsgList) { EntityId entityId = getEntityId(pair.msg.getValue()); if (entityId != null) { msgToEntityIdMap.put(pair.uuid, entityId); entityIdToListMap.computeIfAbsent(entityId, id -> new LinkedList<>()).add(pair); } } } protected abstract EntityId getEntityId(TransportProtos.ToRuleEngineMsg msg); }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\processing\SequentialByEntityIdTbRuleEngineSubmitStrategy.java
1
请完成以下Java代码
public class RuleNodeToRuleChainTellNextMsg extends TbRuleEngineActorMsg implements Serializable { @Serial private static final long serialVersionUID = 4577026446412871820L; private final RuleChainId ruleChainId; private final RuleNodeId originator; private final Set<String> relationTypes; private final String failureMessage; public RuleNodeToRuleChainTellNextMsg(RuleChainId ruleChainId, RuleNodeId originator, Set<String> relationTypes, TbMsg tbMsg, String failureMessage) { super(tbMsg); this.ruleChainId = ruleChainId; this.originator = originator; this.relationTypes = relationTypes;
this.failureMessage = failureMessage; } @Override public void onTbActorStopped(TbActorStopReason reason) { String message = reason == TbActorStopReason.STOPPED ? String.format("Rule chain [%s] stopped", ruleChainId.getId()) : String.format("Failed to initialize rule chain [%s]!", ruleChainId.getId()); msg.getCallback().onFailure(new RuleEngineException(message)); } @Override public MsgType getMsgType() { return MsgType.RULE_TO_RULE_CHAIN_TELL_NEXT_MSG; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleNodeToRuleChainTellNextMsg.java
1
请完成以下Java代码
public void remove() { throw new UnsupportedOperationException(); } @Override public void setScriptScannerFactory(final IScriptScannerFactory scriptScannerFactory) { // NOTE: null is allowed this.scriptScannerFactory = scriptScannerFactory; } @Override public IScriptScannerFactory getScriptScannerFactory() { return scriptScannerFactory; } @Override public IScriptScannerFactory getScriptScannerFactoryToUse() { if (scriptScannerFactory != null) { return scriptScannerFactory; } if (parentScanner != null) { return parentScanner.getScriptScannerFactoryToUse(); } throw new ScriptException(" No " + IScriptScannerFactory.class + " defined for " + this + "."); } @Override public IScriptFactory getScriptFactory() { return scriptFactory; } @Override public void setScriptFactory(final IScriptFactory scriptFactory) {
this.scriptFactory = scriptFactory; } @Override public IScriptFactory getScriptFactoryToUse() { // // If there is an script factory defined on this level, return it { final IScriptFactory scriptFactory = getScriptFactory(); if (scriptFactory != null) { return scriptFactory; } } // // Ask parent script scanner if (parentScanner != null) { final IScriptFactory scriptFactory = parentScanner.getScriptFactoryToUse(); if (scriptFactory != null) { return scriptFactory; } } // // Ask Script Scanner Factory for IScriptFactory { final IScriptScannerFactory scriptScannerFactory = getScriptScannerFactoryToUse(); final IScriptFactory scriptFactory = scriptScannerFactory.getScriptFactoryToUse(); return scriptFactory; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\AbstractScriptScanner.java
1
请完成以下Java代码
protected void validateAndSwitchVersionOfExecution( CommandContext commandContext, ExecutionEntity execution, ProcessDefinition newProcessDefinition ) { // check that the new process definition version contains the current activity org.activiti.bpmn.model.Process process = ProcessDefinitionUtil.getProcess(newProcessDefinition.getId()); if (execution.getActivityId() != null && process.getFlowElement(execution.getActivityId(), true) == null) { throw new ActivitiException( "The new process definition " + "(key = '" + newProcessDefinition.getKey() + "') " + "does not contain the current activity " + "(id = '" + execution.getActivityId() + "') " + "of the process instance " + "(id = '" + processInstanceId + "')." );
} // switch the process instance to the new process definition version execution.setProcessDefinitionId(newProcessDefinition.getId()); execution.setProcessDefinitionName(newProcessDefinition.getName()); execution.setProcessDefinitionKey(newProcessDefinition.getKey()); // and change possible existing tasks (as the process definition id is stored there too) List<TaskEntity> tasks = commandContext.getTaskEntityManager().findTasksByExecutionId(execution.getId()); for (TaskEntity taskEntity : tasks) { taskEntity.setProcessDefinitionId(newProcessDefinition.getId()); commandContext .getHistoryManager() .recordTaskProcessDefinitionChange(taskEntity.getId(), newProcessDefinition.getId()); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SetProcessDefinitionVersionCmd.java
1
请完成以下Java代码
public void addListener(final IFacetsPoolListener listener) { Check.assumeNotNull(listener, "listener not null"); listeners.addIfAbsent(listener); } public void removeListener(final IFacetsPoolListener listener) { listeners.remove(listener); } @Override public void onFacetsInit() { for (final IFacetsPoolListener listener : listeners)
{ listener.onFacetsInit(); } } @Override public void onFacetExecute(final IFacet<?> facet) { for (final IFacetsPoolListener listener : listeners) { listener.onFacetExecute(facet); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\CompositeFacetsPoolListener.java
1
请在Spring Boot框架中完成以下Java代码
private static void assumeCarrierProductSet(@NonNull final I_M_ShipmentSchedule shipmentSchedule) { if(CarrierProductId.ofRepoIdOrNull(shipmentSchedule.getCarrier_Product_ID()) == null) { throw new AdempiereException(ERROR_CARRIER_PRODUCT_NOT_SET, shipmentSchedule.getM_ShipmentSchedule_ID()); } } private @NonNull Quantity computeQtyToPick(final PickingJobSchedule jobSchedule) { final I_C_UOM uom = jobSchedule.getQtyToPick().getUOM(); final BigDecimal qtyToPickBD = request.getQtyToPickBD(); if (qtyToPickBD != null) { return Quantity.of(qtyToPickBD, uom); } else { return jobSchedule.getQtyToPick(); } }
private Quantity computeQtyToPick(final I_M_ShipmentSchedule shipmentSchedule) { final Quantity qtyRemainingToScheduleForPicking = shipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentSchedule); final BigDecimal qtyToPickBD = request.getQtyToPickBD(); if (qtyToPickBD != null) { return Quantity.of(qtyToPickBD, qtyRemainingToScheduleForPicking.getUOM()); } else { return qtyRemainingToScheduleForPicking; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job_schedule\service\commands\CreateOrUpdatePickingJobSchedulesCommand.java
2
请完成以下Java代码
public TaskQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } TaskQueryImpl orQuery = new TaskQueryImpl(); orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public TaskQuery 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); }
@Override public TaskQuery matchVariableNamesIgnoreCase() { this.variableNamesIgnoreCase = true; for (TaskQueryVariableValue variable : this.variables) { variable.setVariableNameIgnoreCase(true); } return this; } @Override public TaskQuery matchVariableValuesIgnoreCase() { this.variableValuesIgnoreCase = true; for (TaskQueryVariableValue variable : this.variables) { variable.setVariableValueIgnoreCase(true); } return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
public class StockEstimateCreatedEvent extends AbstractStockEstimateEvent { public static final String TYPE = "StockEstimateCreatedEvent"; @JsonCreator @Builder public StockEstimateCreatedEvent( @NonNull @JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor, @NonNull @JsonProperty("materialDescriptor") final MaterialDescriptor materialDescriptor, @NonNull @JsonProperty("date") final Instant date, @JsonProperty("plantId") final int plantId, @JsonProperty("freshQtyOnHandId") final int freshQtyOnHandId, @JsonProperty("freshQtyOnHandLineId") final int freshQtyOnHandLineId, @Nullable @JsonProperty("qtyStockEstimateSeqNo") final Integer qtyStockEstimateSeqNo, @NonNull @JsonProperty("eventDate") final Instant eventDate ) { super(eventDescriptor, materialDescriptor, date, plantId,
freshQtyOnHandId, freshQtyOnHandLineId, qtyStockEstimateSeqNo, eventDate); } @Override public BigDecimal getQuantityDelta() { return getMaterialDescriptor().getQuantity(); } @Override public String getEventName() {return TYPE;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\stockestimate\StockEstimateCreatedEvent.java
1
请完成以下Java代码
public Set<String> findSimilar(String contextVariable) { final ImmutableSet.Builder<String> result = ImmutableSet.builder(); contextVariables.stream() .filter(item -> isSimilar(item, contextVariable)) .forEach(result::add); if (parent != null) { result.addAll(parent.findSimilar(contextVariable)); } return result.build(); } private static boolean isSimilar(@NonNull String contextVariable1, @NonNull String contextVariable2) { return contextVariable1.equalsIgnoreCase(contextVariable2); } public boolean contains(@NonNull final String contextVariable) { if (contextVariables.contains(contextVariable)) { return true; } if (knownMissing.contains(contextVariable)) { return true; } return parent != null && parent.contains(contextVariable);
} @Override @Deprecated public String toString() {return toSummaryString();} public String toSummaryString() { StringBuilder sb = new StringBuilder(); sb.append(name).append(":"); sb.append("\n\tContext variables: ").append(String.join(",", contextVariables)); if (!knownMissing.isEmpty()) { sb.append("\n\tKnown missing context variables: ").append(String.join(",", knownMissing)); } if (parent != null) { sb.append("\n--- parent: ----\n"); sb.append(parent.toSummaryString()); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariables.java
1
请完成以下Java代码
private URI toURI(ADHyperlink link) { String urlParams = encodeParams(link.getParameters()); String urlStr = PROTOCOL + "://" + HOST + "/" + link.getAction().toString() + "?" + urlParams; try { return new URI(urlStr); } catch (URISyntaxException e) { throw new AdempiereException(e); } } private String encode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e)
{ throw new AdempiereException(e); } } private String decode(String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AdempiereException(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\util\ADHyperlinkBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public String getServiceValue() { return "LocalFileSyncBPartners"; } @Override public String getExternalSystemTypeCode() { return PCM_SYSTEM_NAME; } @Override public String getEnableCommand() { return START_BPARTNER_SYNC_LOCAL_FILE_ROUTE; } @Override public String getDisableCommand() {
return STOP_BPARTNER_SYNC_LOCAL_FILE_ROUTE; } @NonNull public String getStartBPartnerRouteId() { return getExternalSystemTypeCode() + "-" + getEnableCommand(); } @NonNull public String getStopBPartnerRouteId() { return getExternalSystemTypeCode() + "-" + getDisableCommand(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\bpartner\LocalFileBPartnerSyncServicePCMRouteBuilder.java
2
请在Spring Boot框架中完成以下Java代码
private static Saml2X509Credential getSaml2VerificationCredential(String certificateLocation) { return getSaml2Credential(certificateLocation, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); } private static Saml2X509Credential getSaml2EncryptionCredential(String certificateLocation) { return getSaml2Credential(certificateLocation, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); } private static Saml2X509Credential getSaml2SigningCredential(String privateKeyLocation, String certificateLocation) { return getSaml2Credential(privateKeyLocation, certificateLocation, Saml2X509Credential.Saml2X509CredentialType.SIGNING); } private static Saml2X509Credential getSaml2DecryptionCredential(String privateKeyLocation, String certificateLocation) { return getSaml2Credential(privateKeyLocation, certificateLocation, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } private static Saml2X509Credential getSaml2Credential(String privateKeyLocation, String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { RSAPrivateKey privateKey = readPrivateKey(privateKeyLocation); X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(privateKey, certificate, credentialType); } private static Saml2X509Credential getSaml2Credential(String certificateLocation, Saml2X509Credential.Saml2X509CredentialType credentialType) { X509Certificate certificate = readCertificate(certificateLocation); return new Saml2X509Credential(certificate, credentialType);
} private static RSAPrivateKey readPrivateKey(String privateKeyLocation) { Resource privateKey = resourceLoader.getResource(privateKeyLocation); try (InputStream inputStream = privateKey.getInputStream()) { return RsaKeyConverters.pkcs8().convert(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static X509Certificate readCertificate(String certificateLocation) { Resource certificate = resourceLoader.getResource(certificateLocation); try (InputStream inputStream = certificate.getInputStream()) { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static String resolveAttribute(ParserContext pc, String value) { return pc.getReaderContext().getEnvironment().resolvePlaceholders(value); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\saml2\RelyingPartyRegistrationsBeanDefinitionParser.java
2
请完成以下Java代码
private ViewRowIdsOrderedSelection createSelectionFromSelection( @NonNull final ViewRowIdsOrderedSelection fromSelection, @Nullable final DocumentQueryOrderByList orderBys) { final ViewEvaluationCtx viewEvaluationCtx = getViewEvaluationCtx(); final SqlDocumentFilterConverterContext filterConverterContext = SqlDocumentFilterConverterContext.builder() .userRolePermissionsKey(viewEvaluationCtx.getPermissionsKey()) .build(); return viewDataRepository.createOrderedSelectionFromSelection( viewEvaluationCtx, fromSelection, DocumentFilterList.EMPTY, orderBys, filterConverterContext);
} public Set<DocumentId> retainExistingRowIds(@NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } return viewDataRepository.retrieveRowIdsMatchingFilters( viewId, DocumentFilterList.EMPTY, rowIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelectionsHolder.java
1
请在Spring Boot框架中完成以下Java代码
public UserDetailsBuilder authorities(List<? extends GrantedAuthority> authorities) { this.user.authorities(authorities); return this; } /** * Populates the authorities. This attribute is required. * @param authorities the authorities for this user (i.e. ROLE_USER, ROLE_ADMIN, * etc). Cannot be null, or contain null values * @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate * additional attributes for this user) * @see #roles(String...) */ public UserDetailsBuilder authorities(String... authorities) { this.user.authorities(authorities); return this; } /** * Defines if the account is expired or not. Default is false. * @param accountExpired true if the account is expired, false otherwise * @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate * additional attributes for this user) */ public UserDetailsBuilder accountExpired(boolean accountExpired) { this.user.accountExpired(accountExpired); return this; } /** * Defines if the account is locked or not. Default is false. * @param accountLocked true if the account is locked, false otherwise * @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate * additional attributes for this user) */ public UserDetailsBuilder accountLocked(boolean accountLocked) { this.user.accountLocked(accountLocked); return this; } /** * Defines if the credentials are expired or not. Default is false. * @param credentialsExpired true if the credentials are expired, false otherwise * @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate * additional attributes for this user) */ public UserDetailsBuilder credentialsExpired(boolean credentialsExpired) { this.user.credentialsExpired(credentialsExpired);
return this; } /** * Defines if the account is disabled or not. Default is false. * @param disabled true if the account is disabled, false otherwise * @return the {@link UserDetailsBuilder} for method chaining (i.e. to populate * additional attributes for this user) */ public UserDetailsBuilder disabled(boolean disabled) { this.user.disabled(disabled); return this; } UserDetails build() { return this.user.build(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\provisioning\UserDetailsManagerConfigurer.java
2
请完成以下Java代码
public class JsonUserDashboardItemAddRequest { int kpiId; @Default int position = -1; // // Optional params String caption; JSONInterval interval; JSONWhen when; @AllArgsConstructor @Getter public static enum JSONInterval { week("P-7D"); private final String esTimeRange; }
@AllArgsConstructor @Getter public enum JSONWhen { now(null), lastWeek("P-7D"); private final String esTimeRangeEnd; } @JsonPOJOBuilder(withPrefix = "") public static class JsonUserDashboardItemAddRequestBuilder { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JsonUserDashboardItemAddRequest.java
1
请完成以下Java代码
public void setMatchingMessageTypes(Set<SimpMessageType> matchingMessageTypes) { Assert.notEmpty(matchingMessageTypes, "matchingMessageTypes cannot be null or empty"); this.matchingMessageTypes = matchingMessageTypes; } @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { if (message == null) { return message; } SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders()); if (!this.matchingMessageTypes.contains(messageType)) { return message; } Map<String, Object> sessionHeaders = SimpMessageHeaderAccessor.getSessionAttributes(message.getHeaders()); String sessionId = (sessionHeaders != null) ? (String) sessionHeaders.get(SPRING_SESSION_ID_ATTR_NAME) : null; if (sessionId != null) { S session = this.sessionRepository.findById(sessionId); if (session != null) { // update the last accessed time session.setLastAccessedTime(Instant.now()); this.sessionRepository.save(session); } } return message; } @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) { if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; HttpSession session = servletRequest.getServletRequest().getSession(false); if (session != null) { setSessionId(attributes, session.getId()); } } return true; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) { } public static String getSessionId(Map<String, Object> attributes) { return (String) attributes.get(SPRING_SESSION_ID_ATTR_NAME); } public static void setSessionId(Map<String, Object> attributes, String sessionId) { attributes.put(SPRING_SESSION_ID_ATTR_NAME, sessionId); } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\socket\server\SessionRepositoryMessageInterceptor.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId;
} public Map<String, VariableValueDto> getVariables() { return variables; } public void setVariables(Map<String, VariableValueDto> variables) { this.variables = variables; } public boolean isWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\SignalDto.java
1
请完成以下Java代码
public void init() throws Exception { log.info("Setting resource leak detector level to {}", leakDetectorLevel); ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase())); log.info("Starting MQTT transport..."); bossGroup = new NioEventLoopGroup(bossGroupThreadCount); workerGroup = new NioEventLoopGroup(workerGroupThreadCount); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new MqttTransportServerInitializer(context, false)) .childOption(ChannelOption.SO_KEEPALIVE, keepAlive); serverChannel = b.bind(host, port).sync().channel(); if (sslEnabled) { b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new MqttTransportServerInitializer(context, true)) .childOption(ChannelOption.SO_KEEPALIVE, keepAlive); sslServerChannel = b.bind(sslHost, sslPort).sync().channel(); } log.info("Mqtt transport started!");
} @PreDestroy public void shutdown() throws InterruptedException { log.info("Stopping MQTT transport!"); try { serverChannel.close().sync(); if (sslEnabled) { sslServerChannel.close().sync(); } } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } log.info("MQTT transport stopped!"); } @Override public String getName() { return DataConstants.MQTT_TRANSPORT_NAME; } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\MqttTransportService.java
1
请完成以下Java代码
public void setShortDescription (final @Nullable java.lang.String ShortDescription) { set_Value (COLUMNNAME_ShortDescription, ShortDescription); } @Override public java.lang.String getShortDescription() { return get_ValueAsString(COLUMNNAME_ShortDescription); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } @Override public void setTaxID (final @Nullable java.lang.String TaxID) { set_Value (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setURL (final @Nullable java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } @Override
public java.lang.String getURL() { return get_ValueAsString(COLUMNNAME_URL); } @Override public void setURL3 (final @Nullable java.lang.String URL3) { set_Value (COLUMNNAME_URL3, URL3); } @Override public java.lang.String getURL3() { return get_ValueAsString(COLUMNNAME_URL3); } @Override public void setVendorCategory (final @Nullable java.lang.String VendorCategory) { set_Value (COLUMNNAME_VendorCategory, VendorCategory); } @Override public java.lang.String getVendorCategory() { return get_ValueAsString(COLUMNNAME_VendorCategory); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_BPartner.java
1
请完成以下Java代码
public ActivityInstanceQueryImpl orderByActivityInstanceId() { orderBy(ActivityInstanceQueryProperty.ACTIVITY_INSTANCE_ID); return this; } @Override public ActivityInstanceQueryImpl orderByProcessDefinitionId() { orderBy(ActivityInstanceQueryProperty.PROCESS_DEFINITION_ID); return this; } @Override public ActivityInstanceQueryImpl orderByProcessInstanceId() { orderBy(ActivityInstanceQueryProperty.PROCESS_INSTANCE_ID); return this; } @Override public ActivityInstanceQueryImpl orderByActivityInstanceStartTime() { orderBy(ActivityInstanceQueryProperty.START); return this; } @Override public ActivityInstanceQuery orderByActivityId() { orderBy(ActivityInstanceQueryProperty.ACTIVITY_ID); return this; } @Override public ActivityInstanceQueryImpl orderByActivityName() { orderBy(ActivityInstanceQueryProperty.ACTIVITY_NAME); return this; } @Override public ActivityInstanceQueryImpl orderByActivityType() { orderBy(ActivityInstanceQueryProperty.ACTIVITY_TYPE); return this; } @Override public ActivityInstanceQueryImpl orderByTenantId() { orderBy(ActivityInstanceQueryProperty.TENANT_ID); return this; } @Override public ActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } // getters and setters // ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; }
public String getAssignee() { return assignee; } public String getCompletedBy() { return completedBy; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public Collection<String> getProcessInstanceIds() { return processInstanceIds; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ActivityInstanceQueryImpl.java
1
请完成以下Java代码
public void setText(String text) { this.text = text; } public void setAuthor(User author) { this.author = author; } public void setPost(Post post) { this.post = post; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) {
return false; } Comment comment = (Comment) o; return Objects.equals(id, comment.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Comment(id=" + this.getId() + ", text=" + this.getText() + ", author=" + this.getAuthor() + ", post=" + this.getPost() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Comment.java
1
请完成以下Java代码
boolean shouldSkip(@Nullable ClassLoader classLoader, DockerComposeProperties.Skip properties) { if (properties.isInTests() && hasAtLeastOneRequiredClass(classLoader)) { Thread thread = Thread.currentThread(); for (StackTraceElement element : thread.getStackTrace()) { if (isSkippedStackElement(element)) { return true; } } } return false; } private boolean hasAtLeastOneRequiredClass(@Nullable ClassLoader classLoader) { for (String requiredClass : REQUIRED_CLASSES) { if (ClassUtils.isPresent(requiredClass, classLoader)) {
return true; } } return false; } private static boolean isSkippedStackElement(StackTraceElement element) { for (String skipped : SKIPPED_STACK_ELEMENTS) { if (element.getClassName().startsWith(skipped)) { return true; } } return false; } }
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeSkipCheck.java
1
请完成以下Spring Boot application配置
server: port: 8080 spring: jersey: application-path: /odata jpa: defer-datasource-initialization: true show-sql: true open-in-view: false hibernate: ddl-auto: update properties:
hibernate: globally_quoted_identifiers: true sql: init: mode: always
repos\tutorials-master\apache-olingo\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class CommentJdbcRepositoryAdapter implements CommentRepository { private final CommentJdbcRepository repository; private final CommentAssemblyJdbcRepository assemblyRepository; private final CommentMapper commentMapper; @Override public Optional<Comment> findById(long id) { return repository.findById(id) .map(commentMapper::toDomain); } @Override public Optional<CommentAssembly> findAssemblyById(Long userId, long id) { return assemblyRepository.findById(id, userId) .map(commentMapper::toDomain); } @Override public List<CommentAssembly> findAllAssemblyByArticleId(Long userId, long articleId) { return assemblyRepository.findAllByArticleId(articleId, userId).stream() .map(commentMapper::toDomain) .toList(); } @Override public Comment save(Comment comment) { var entity = commentMapper.fromDomain(comment); var saved = repository.save(entity); return commentMapper.toDomain(saved); } @Override public void deleteById(long id) { repository.deleteById(id); } @Override public void deleteAllByArticleId(long articleId) { repository.deleteAllByArticleId(articleId); }
@Mapper(config = MappingConfig.class) interface CommentMapper { Comment toDomain(CommentJdbcEntity source); CommentJdbcEntity fromDomain(Comment source); @Mapping(target = "author", source = "source") CommentAssembly toDomain(CommentAssemblyJdbcEntity source); default Profile profile(CommentAssemblyJdbcEntity source) { return new Profile(source.authorUsername(), source.authorBio(), source.authorImage(), source.authorFollowing()); } } }
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\CommentJdbcRepositoryAdapter.java
2
请完成以下Java代码
public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCantonlev() { return cantonlev; } public void setCantonlev(String cantonlev) { this.cantonlev = cantonlev; } public String getTaxorgcode() { return taxorgcode; } public void setTaxorgcode(String taxorgcode) { this.taxorgcode = taxorgcode; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getUsing() { return using; } public void setUsing(String using) { this.using = using; } public String getUsingdate() { return usingdate; } public void setUsingdate(String usingdate) { this.usingdate = usingdate; } public Integer getLevel() { return level; }
public void setLevel(Integer level) { this.level = level; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public String getQrcantonid() { return qrcantonid; } public void setQrcantonid(String qrcantonid) { this.qrcantonid = qrcantonid; } public String getDeclare() { return declare; } public void setDeclare(String declare) { this.declare = declare; } public String getDeclareisend() { return declareisend; } public void setDeclareisend(String declareisend) { this.declareisend = declareisend; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\canton\Canton.java
1
请完成以下Java代码
boolean isSorted(int[] array, int length) { if (array == null || length < 2) return true; if (array[length - 2] > array[length - 1]) return false; return isSorted(array, length - 1); } boolean isSorted(int[] array) { for (int i = 0; i < array.length - 1; i++) { if (array[i] > array[i + 1]) return false; } return true; } boolean isSorted(Comparable[] array, int length) { if (array == null || length < 2) return true; if (array[length - 2].compareTo(array[length - 1]) > 0) return false; return isSorted(array, length - 1); } boolean isSorted(Comparable[] array) { for (int i = 0; i < array.length - 1; ++i) { if (array[i].compareTo(array[i + 1]) > 0) return false; } return true; }
boolean isSorted(Object[] array, Comparator comparator) { for (int i = 0; i < array.length - 1; ++i) { if (comparator.compare(array[i], (array[i + 1])) > 0) return false; } return true; } boolean isSorted(Object[] array, Comparator comparator, int length) { if (array == null || length < 2) return true; if (comparator.compare(array[length - 2], array[length - 1]) > 0) return false; return isSorted(array, comparator, length - 1); } }
repos\tutorials-master\core-java-modules\core-java-arrays-sorting\src\main\java\com\baeldung\array\SortedArrayChecker.java
1
请完成以下Java代码
public class Photo { @Id private String id; private String title; private Binary image; public Photo(String title) { super(); this.title = title; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; } public Binary getImage() { return image; } public void setImage(Binary image) { this.image = image; } @Override public String toString() { return "Photo [id=" + id + ", title=" + title + ", image=" + image + "]"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\file\models\Photo.java
1
请完成以下Java代码
public class Hotel implements Serializable { private static final long serialVersionUID = 1L; private Long city; private String name; private String address; private String zip; public Long getCity() { return city; } public void setCity(Long city) { this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } @Override public String toString() { return getCity() + "," + getName() + "," + getAddress() + "," + getZip(); } }
repos\pagehelper-spring-boot-master\pagehelper-spring-boot-samples\pagehelper-spring-boot-sample-xml\src\main\java\tk\mybatis\pagehelper\domain\Hotel.java
1
请完成以下Java代码
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); }
/** Set UI Style. @param UIStyle UI Style */ @Override public void setUIStyle (java.lang.String UIStyle) { set_Value (COLUMNNAME_UIStyle, UIStyle); } /** Get UI Style. @return UI Style */ @Override public java.lang.String getUIStyle () { return (java.lang.String)get_Value(COLUMNNAME_UIStyle); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementGroup.java
1
请完成以下Spring Boot application配置
#spring: # application: # name: demo-application management: endpoint: # Metrics 端点配置项 metrics: enabled: true # 是否开启。默认为 true 开启。 # Metrics 的具体配置项,对应 MetricsProperties 配置类 metrics: # 设置指定前缀的指标是否开启 enable: xxx: false # 通用 tag tags: application: demo-application endpoints: # Actuator HTTP 配置项,对应 WebEndpointProperties 配置类 web: base-path: /actuator # Actua
tor 提供的 API 接口的根目录。默认为 /actuator exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 exclude: # 在 include 的基础上,需要排除的端点。通过设置 * ,可以排除所有端点。
repos\SpringBoot-Labs-master\lab-34\lab-34-actuator-demo-metrics\src\main\resources\application.yaml
2
请完成以下Java代码
private boolean isSameLine() { return sameLine; } /** * Default: {@link #DEFAULT_SameLine} * * @param sameLine If true, the new Field will be added in the same line. */ public VPanelFormFieldBuilder setSameLine(boolean sameLine) { this.sameLine = sameLine; return this; } private boolean isMandatory() { return mandatory; } /** * Default: {@link #DEFAULT_Mandatory} * * @param mandatory true if this field shall be marked as mandatory */ public VPanelFormFieldBuilder setMandatory(boolean mandatory) { this.mandatory = mandatory; return this; } private boolean isAutocomplete() { if (autocomplete != null) { return autocomplete; } // if Search, always auto-complete if (DisplayType.Search == displayType) { return true; } return false; } public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete) { this.autocomplete = autocomplete; return this; } private int getAD_Column_ID() { // not set is allowed return AD_Column_ID; } /** * @param AD_Column_ID Column for lookups. */ public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID) {
this.AD_Column_ID = AD_Column_ID; return this; } public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName) { return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID()); } private EventListener getEditorListener() { // null allowed return editorListener; } /** * @param listener VetoableChangeListener that gets called if the field is changed. */ public VPanelFormFieldBuilder setEditorListener(EventListener listener) { this.editorListener = listener; return this; } public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel) { this.bindEditorToModel = bindEditorToModel; return this; } public VPanelFormFieldBuilder setReadOnly(boolean readOnly) { this.readOnly = readOnly; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
1
请完成以下Java代码
private static Instant fromObjectToInstant(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, Instant.class, DateTimeConverters::fromJsonToInstant, (object) -> TimeUtil.asInstant(object, zoneId)); } @Nullable private static <T> T fromObjectTo( @NonNull final Object valueObj, @NonNull final Class<T> type, @NonNull final Function<String, T> fromJsonConverter, @NonNull final Function<Object, T> fromObjectConverter) { if (type.isInstance(valueObj)) { return type.cast(valueObj); } else if (valueObj instanceof CharSequence) { final String json = valueObj.toString().trim(); if (json.isEmpty()) {
return null; } if (json.length() == 21 && json.charAt(10) == ' ') // json string - possible in JDBC format (`2016-06-11 00:00:00.0`) { final Timestamp timestamp = Timestamp.valueOf(json); return fromObjectConverter.apply(timestamp); } else { return fromJsonConverter.apply(json); } } else { return fromObjectConverter.apply(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\DateTimeConverters.java
1
请完成以下Java代码
public void setS_Training_Class_ID (int S_Training_Class_ID) { if (S_Training_Class_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, Integer.valueOf(S_Training_Class_ID)); } /** Get Training Class. @return The actual training class instance */ public int getS_Training_Class_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_Class_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_Training getS_Training() throws RuntimeException { return (I_S_Training)MTable.get(getCtx(), I_S_Training.Table_Name) .getPO(getS_Training_ID(), get_TrxName()); } /** Set Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID)
{ if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_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_S_Training_Class.java
1
请在Spring Boot框架中完成以下Java代码
public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getCompletedBy() { return completedBy; } public void setCompletedBy(String completedBy) { this.completedBy = completedBy; } public String getExtraValue() { return extraValue; } public void setExtraValue(String extraValue) { this.extraValue = extraValue; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId;
} public void setTenantId(String tenantId) { this.tenantId = tenantId; } public void setLocalVariables(List<RestVariable> localVariables){ this.localVariables = localVariables; } public List<RestVariable> getLocalVariables() { return localVariables; } public void addLocalVariable(RestVariable restVariable) { localVariables.add(restVariable); } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getLimitParamName() { return this.limitParamName; } public void setLimitParamName(@Nullable String limitParamName) { this.limitParamName = limitParamName; } public @Nullable String getSortParamName() { return this.sortParamName; } public void setSortParamName(@Nullable String sortParamName) { this.sortParamName = sortParamName; } public RepositoryDetectionStrategies getDetectionStrategy() { return this.detectionStrategy; } public void setDetectionStrategy(RepositoryDetectionStrategies detectionStrategy) { this.detectionStrategy = detectionStrategy; } public @Nullable MediaType getDefaultMediaType() { return this.defaultMediaType; } public void setDefaultMediaType(@Nullable MediaType defaultMediaType) { this.defaultMediaType = defaultMediaType; } public @Nullable Boolean getReturnBodyOnCreate() { return this.returnBodyOnCreate; } public void setReturnBodyOnCreate(@Nullable Boolean returnBodyOnCreate) { this.returnBodyOnCreate = returnBodyOnCreate; } public @Nullable Boolean getReturnBodyOnUpdate() { return this.returnBodyOnUpdate; } public void setReturnBodyOnUpdate(@Nullable Boolean returnBodyOnUpdate) { this.returnBodyOnUpdate = returnBodyOnUpdate;
} public @Nullable Boolean getEnableEnumTranslation() { return this.enableEnumTranslation; } public void setEnableEnumTranslation(@Nullable Boolean enableEnumTranslation) { this.enableEnumTranslation = enableEnumTranslation; } public void applyTo(RepositoryRestConfiguration rest) { PropertyMapper map = PropertyMapper.get(); map.from(this::getBasePath).to(rest::setBasePath); map.from(this::getDefaultPageSize).to(rest::setDefaultPageSize); map.from(this::getMaxPageSize).to(rest::setMaxPageSize); map.from(this::getPageParamName).to(rest::setPageParamName); map.from(this::getLimitParamName).to(rest::setLimitParamName); map.from(this::getSortParamName).to(rest::setSortParamName); map.from(this::getDetectionStrategy).to(rest::setRepositoryDetectionStrategy); map.from(this::getDefaultMediaType).to(rest::setDefaultMediaType); map.from(this::getReturnBodyOnCreate).to(rest::setReturnBodyOnCreate); map.from(this::getReturnBodyOnUpdate).to(rest::setReturnBodyOnUpdate); map.from(this::getEnableEnumTranslation).to(rest::setEnableEnumTranslation); } }
repos\spring-boot-4.0.1\module\spring-boot-data-rest\src\main\java\org\springframework\boot\data\rest\autoconfigure\DataRestProperties.java
2
请在Spring Boot框架中完成以下Java代码
public void setProcessEngine(ProcessEngine processEngine) { this.processEngine = processEngine; } private void configureDefaultActivitiRegistry(String registryBeanName, BeanDefinitionRegistry registry) { if (!beanAlreadyConfigured(registry, registryBeanName, ActivitiStateHandlerRegistry.class)) { String registryName =ActivitiStateHandlerRegistry.class.getName(); log.info( "registering a " + registryName + " instance under bean name "+ ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME+ "."); RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); rootBeanDefinition.setBeanClassName( registryName ); rootBeanDefinition.getPropertyValues().addPropertyValue("processEngine", this.processEngine); BeanDefinitionHolder holder = new BeanDefinitionHolder(rootBeanDefinition, registryBeanName); BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); } } public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; configureDefaultActivitiRegistry(ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME, registry);
} else { log.info("BeanFactory is not a BeanDefinitionRegistry. The default '" + ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME + "' cannot be configured."); } } private boolean beanAlreadyConfigured(BeanDefinitionRegistry registry, String beanName, Class clz) { if (registry.isBeanNameInUse(beanName)) { BeanDefinition bDef = registry.getBeanDefinition(beanName); if (bDef.getBeanClassName().equals(clz.getName())) { return true; // so the beans already registered, and of the right type. so we assume the user is overriding our configuration } else { throw new IllegalStateException("The bean name '" + beanName + "' is reserved."); } } return false; } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\config\xml\StateHandlerAnnotationBeanFactoryPostProcessor.java
2
请完成以下Java代码
public void collectAddedRowId(@NonNull final DocumentId rowId) { if (addedRowIds == null) { addedRowIds = new HashSet<>(); } addedRowIds.add(rowId); } @Override public Set<DocumentId> getAddedRowIds() { final HashSet<DocumentId> addedRowIds = this.addedRowIds; return addedRowIds != null ? addedRowIds : ImmutableSet.of(); } @Override public boolean hasAddedRows() { final HashSet<DocumentId> addedRowIds = this.addedRowIds; return addedRowIds != null && !addedRowIds.isEmpty(); } @Override public void collectRemovedRowIds(final Collection<DocumentId> rowIds) { if (removedRowIds == null) { removedRowIds = new HashSet<>(rowIds); } else { removedRowIds.addAll(rowIds); } }
@Override public Set<DocumentId> getRemovedRowIds() { final HashSet<DocumentId> removedRowIds = this.removedRowIds; return removedRowIds != null ? removedRowIds : ImmutableSet.of(); } @Override public void collectChangedRowIds(final Collection<DocumentId> rowIds) { if (changedRowIds == null) { changedRowIds = new HashSet<>(rowIds); } else { changedRowIds.addAll(rowIds); } } @Override public Set<DocumentId> getChangedRowIds() { final HashSet<DocumentId> changedRowIds = this.changedRowIds; return changedRowIds != null ? changedRowIds : ImmutableSet.of(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\AddRemoveChangedRowIdsCollector.java
1
请完成以下Java代码
public class RonCooSignUtil { private static final Log LOG = LogFactory.getLog(RonCooSignUtil.class); private RonCooSignUtil() { } /** * @param timeStamp * @param userName * @param userPwd * @return */ public static String getSign(String token, long timeStamp, String userName) { String[] arr = new String[] { token, String.valueOf(timeStamp), userName }; // 将token、timestamp、nonce、userPwd三个参数进行字典序排序 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) { LOG.error(e); } return tmpStr; } /**
* 将字节数组转换为十六进制字符串 * * @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\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\utils\RonCooSignUtil.java
1
请完成以下Java代码
public class EntryDetails1 { @XmlElement(name = "Btch") protected BatchInformation2 btch; @XmlElement(name = "TxDtls") protected List<EntryTransaction2> txDtls; /** * Gets the value of the btch property. * * @return * possible object is * {@link BatchInformation2 } * */ public BatchInformation2 getBtch() { return btch; } /** * Sets the value of the btch property. * * @param value * allowed object is * {@link BatchInformation2 } * */ public void setBtch(BatchInformation2 value) { this.btch = value; } /** * Gets the value of the txDtls property. *
* <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the txDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTxDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EntryTransaction2 } * * */ public List<EntryTransaction2> getTxDtls() { if (txDtls == null) { txDtls = new ArrayList<EntryTransaction2>(); } return this.txDtls; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\EntryDetails1.java
1
请完成以下Java代码
public class EvaluateToActivatePlanItemInstanceOperation extends AbstractEvaluationCriteriaOperation { protected PlanItemInstanceEntity planItemInstanceEntity; public EvaluateToActivatePlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { super(commandContext, planItemInstanceEntity.getCaseInstanceId(), null, null); this.planItemInstanceEntity = planItemInstanceEntity; } @Override public void run() { PlanItemEvaluationResult evaluationResult = new PlanItemEvaluationResult(); evaluateForActivation(planItemInstanceEntity, planItemInstanceEntity, evaluationResult); if (!evaluationResult.isCriteriaChanged()) { // the plan item was not (yet) activated, so set its state to available as there must be a entry sentry with a condition which might be satisfied later planItemInstanceEntity.setState(PlanItemInstanceState.AVAILABLE); } } @Override
public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[Evaluate To Activate] plan item instance "); stringBuilder.append(planItemInstanceEntity.getId()); if (planItemLifeCycleEvent != null) { stringBuilder.append(" with transition '").append(planItemLifeCycleEvent.getTransition()).append("' having fired"); if (planItemLifeCycleEvent.getPlanItem() != null) { stringBuilder.append(" for ").append(planItemLifeCycleEvent.getPlanItem()); } } return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\EvaluateToActivatePlanItemInstanceOperation.java
1
请在Spring Boot框架中完成以下Java代码
public Long saveCity(City city) { City cityResult = cityRepository.save(city); return cityResult.getId(); } @Override public List<City> searchCity(Integer pageNumber, Integer pageSize, String searchContent) { // 校验分页参数 if (pageSize == null || pageSize <= 0) { pageSize = PAGE_SIZE; } if (pageNumber == null || pageNumber < DEFAULT_PAGE_NUMBER) { pageNumber = DEFAULT_PAGE_NUMBER; } LOGGER.info("\n searchCity: searchContent [" + searchContent + "] \n "); // 构建搜索查询 SearchQuery searchQuery = getCitySearchQuery(pageNumber,pageSize,searchContent); LOGGER.info("\n searchCity: searchContent [" + searchContent + "] \n DSL = \n " + searchQuery.getQuery().toString()); Page<City> cityPage = cityRepository.search(searchQuery); return cityPage.getContent(); } /** * 根据搜索词构造搜索查询语句 * * 代码流程: * - 权重分查询 * - 短语匹配 * - 设置权重分最小值 * - 设置分页参数 * * @param pageNumber 当前页码 * @param pageSize 每页大小 * @param searchContent 搜索内容 * @return */
private SearchQuery getCitySearchQuery(Integer pageNumber, Integer pageSize,String searchContent) { // 短语匹配到的搜索词,求和模式累加权重分 // 权重分查询 https://www.elastic.co/guide/cn/elasticsearch/guide/current/function-score-query.html // - 短语匹配 https://www.elastic.co/guide/cn/elasticsearch/guide/current/phrase-matching.html // - 字段对应权重分设置,可以优化成 enum // - 由于无相关性的分值默认为 1 ,设置权重分最小值为 10 FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery() .add(QueryBuilders.matchPhraseQuery("name", searchContent), ScoreFunctionBuilders.weightFactorFunction(1000)) .add(QueryBuilders.matchPhraseQuery("description", searchContent), ScoreFunctionBuilders.weightFactorFunction(500)) .scoreMode(SCORE_MODE_SUM).setMinScore(MIN_SCORE); // 分页参数 Pageable pageable = new PageRequest(pageNumber, pageSize); return new NativeSearchQueryBuilder() .withPageable(pageable) .withQuery(functionScoreQueryBuilder).build(); } }
repos\springboot-learning-example-master\spring-data-elasticsearch-query\src\main\java\org\spring\springboot\service\impl\CityESServiceImpl.java
2
请完成以下Java代码
public Long getId() { return id; } public Email getEmail() { return email; } public UserName getName() { return profile.getUserName(); } String getBio() { return profile.getBio(); }
Image getImage() { return profile.getImage(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final var user = (User) o; return email.equals(user.email); } @Override public int hashCode() { return Objects.hash(email); } }
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\User.java
1
请完成以下Java代码
public void preInit(SpringProcessEngineConfiguration processEngineConfiguration) { if (!property.isTask() && !property.isExecution() && !property.isHistory()) { logger.info("EVENTING-002: Camunda Spring Boot Eventing Plugin is found, but disabled via property."); return; } if (property.isTask() || property.isExecution()) { logger.info("EVENTING-001: Initialized Camunda Spring Boot Eventing Engine Plugin."); if (property.isTask()) { logger.info("EVENTING-003: Task events will be published as Spring Events."); } else { logger.info("EVENTING-004: Task eventing is disabled via property."); } if (property.isExecution()) { logger.info("EVENTING-005: Execution events will be published as Spring Events."); } else { logger.info("EVENTING-006: Execution eventing is disabled via property."); } if (property.isSkippable()) { logger.info("EVENTING-009: Listeners will not be invoked if a skipCustomListeners API parameter is set to true by user."); } else { logger.info("EVENTING-009: Listeners will always be invoked regardless of skipCustomListeners API parameters."); } // register parse listener
processEngineConfiguration.getCustomPostBPMNParseListeners().add(new PublishDelegateParseListener(this.publisher, property)); } if (property.isHistory()) { logger.info("EVENTING-007: History events will be published as Spring events."); // register composite DB event handler. processEngineConfiguration.getCustomHistoryEventHandlers() .add(new PublishHistoryEventHandler(this.publisher)); } else { logger.info("EVENTING-008: History eventing is disabled via property."); } } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\EventPublisherPlugin.java
1
请完成以下Java代码
public void setApiKey (final String ApiKey) { set_Value (COLUMNNAME_ApiKey, ApiKey); } @Override public String getApiKey() { return get_ValueAsString(COLUMNNAME_ApiKey); } @Override public void setBaseURL (final String BaseURL) { set_Value (COLUMNNAME_BaseURL, BaseURL); } @Override public String getBaseURL() { return get_ValueAsString(COLUMNNAME_BaseURL); } @Override public void setC_Root_BPartner_ID (final int C_Root_BPartner_ID) { if (C_Root_BPartner_ID < 1) set_Value (COLUMNNAME_C_Root_BPartner_ID, null); else set_Value (COLUMNNAME_C_Root_BPartner_ID, C_Root_BPartner_ID); } @Override public int getC_Root_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_Root_BPartner_ID); } @Override public void setExternalSystem_Config_Alberta_ID (final int ExternalSystem_Config_Alberta_ID) { if (ExternalSystem_Config_Alberta_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, ExternalSystem_Config_Alberta_ID); } @Override public int getExternalSystem_Config_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Alberta_ID); } @Override public I_ExternalSystem_Config getExternalSystem_Config() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class); } @Override public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override
public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setPharmacy_PriceList_ID (final int Pharmacy_PriceList_ID) { if (Pharmacy_PriceList_ID < 1) set_Value (COLUMNNAME_Pharmacy_PriceList_ID, null); else set_Value (COLUMNNAME_Pharmacy_PriceList_ID, Pharmacy_PriceList_ID); } @Override public int getPharmacy_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_Pharmacy_PriceList_ID); } @Override public void setTenant (final String Tenant) { set_Value (COLUMNNAME_Tenant, Tenant); } @Override public String getTenant() { return get_ValueAsString(COLUMNNAME_Tenant); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Alberta.java
1
请完成以下Java代码
public void eventCancelledByEventGateway(DelegateExecution execution) { deleteEventSubscription(execution); CommandContextUtil.getExecutionEntityManager().deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL, false); } protected ExecutionEntity deleteEventSubscription(DelegateExecution execution) { ExecutionEntity executionEntity = (ExecutionEntity) execution; Object eventInstance = execution.getTransientVariables().get(EventConstants.EVENT_INSTANCE); if (eventInstance instanceof EventInstance) { EventInstanceBpmnUtil.handleEventInstanceOutParameters(execution, execution.getCurrentFlowElement(), (EventInstance) eventInstance); } CommandContext commandContext = Context.getCommandContext(); ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
EventSubscriptionService eventSubscriptionService = processEngineConfiguration.getEventSubscriptionServiceConfiguration().getEventSubscriptionService(); List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions(); String eventDefinitionKey = getEventDefinitionKey(commandContext, executionEntity); for (EventSubscriptionEntity eventSubscription : eventSubscriptions) { if (Objects.equals(eventDefinitionKey, eventSubscription.getEventType())) { eventSubscriptionService.deleteEventSubscription(eventSubscription); CountingEntityUtil.handleDeleteEventSubscriptionEntityCount(eventSubscription); } } return executionEntity; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\IntermediateCatchEventRegistryEventActivityBehavior.java
1
请在Spring Boot框架中完成以下Java代码
public String getUPC() { return upc; } /** * Sets the value of the upc property. * * @param value * allowed object is * {@link String } * */ public void setUPC(String value) { this.upc = value; } /** * Gets the value of the gln property. * * @return * possible object is * {@link String } *
*/ public String getGLN() { return gln; } /** * Sets the value of the gln property. * * @param value * allowed object is * {@link String } * */ public void setGLN(String value) { this.gln = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIMHUPIItemProductLookupUPCVType.java
2
请完成以下Java代码
public class ListPodsWithFieldSelectors { private static final Logger log = LoggerFactory.getLogger(ListPodsWithFieldSelectors.class); /** * @param args */ public static void main(String[] args) throws Exception { ApiClient client = Config.defaultClient(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(message -> log.info(message)); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient newClient = client.getHttpClient() .newBuilder() .addInterceptor(interceptor) .readTimeout(0, TimeUnit.SECONDS) .build(); client.setHttpClient(newClient); CoreV1Api api = new CoreV1Api(client); String fs = createSelector(args); V1PodList items = api.listPodForAllNamespaces(null, null, fs, null, null, null, null, null, 10, false);
items.getItems() .stream() .map((pod) -> pod.getMetadata().getName() ) .forEach((name) -> System.out.println("name=" + name)); } private static String createSelector(String[] args) { StringBuilder b = new StringBuilder(); for( int i = 0 ; i < args.length; i++ ) { if( b.length() > 0 ) { b.append(','); } b.append(args[i]); } return b.toString(); } }
repos\tutorials-master\kubernetes-modules\k8s-intro\src\main\java\com\baeldung\kubernetes\intro\ListPodsWithFieldSelectors.java
1
请完成以下Java代码
public String getDescription(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); String description = adProcessTrl.getDescription(); if (Services.get(IDeveloperModeBL.class).isEnabled()) { if (description == null) { description = ""; } else { description += "\n - "; } description += "Classname:" + adProcess.getClassname() + ", ID=" + adProcess.getAD_Process_ID(); } return description; } public String getHelp(final String adLanguage) { final I_AD_Process adProcess = adProcessSupplier.get(); final I_AD_Process adProcessTrl = InterfaceWrapperHelper.translate(adProcess, I_AD_Process.class, adLanguage); return adProcessTrl.getHelp(); } public Icon getIcon() { final I_AD_Process adProcess = adProcessSupplier.get(); final String iconName; if (adProcess.getAD_Form_ID() > 0) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_WINDOW); } else if (adProcess.getAD_Workflow_ID() > 0) {
iconName = MTreeNode.getIconName(MTreeNode.TYPE_WORKFLOW); } else if (adProcess.isReport()) { iconName = MTreeNode.getIconName(MTreeNode.TYPE_REPORT); } else { iconName = MTreeNode.getIconName(MTreeNode.TYPE_PROCESS); } return Images.getImageIcon2(iconName); } private ProcessPreconditionsResolution getPreconditionsResolution() { return preconditionsResolutionSupplier.get(); } public boolean isEnabled() { return getPreconditionsResolution().isAccepted(); } public boolean isSilentRejection() { return getPreconditionsResolution().isInternal(); } public boolean isDisabled() { return getPreconditionsResolution().isRejected(); } public String getDisabledReason(final String adLanguage) { return getPreconditionsResolution().getRejectReason().translate(adLanguage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ui\SwingRelatedProcessDescriptor.java
1
请完成以下Java代码
private static DocumentFilterParam createAutoFilterParam(final DocumentFilterParamDescriptor filterParamDescriptor) { final Object value; if (filterParamDescriptor.isAutoFilterInitialValueIsDateNow()) { final DocumentFieldWidgetType widgetType = filterParamDescriptor.getWidgetType(); if (widgetType == DocumentFieldWidgetType.LocalDate) { value = SystemTime.asLocalDate(); } else { value = de.metas.common.util.time.SystemTime.asZonedDateTime(); } } else if (filterParamDescriptor.isAutoFilterInitialValueIsCurrentLoggedUser()) { // FIXME: we shall get the current logged user or context as parameter final UserId loggedUserId = Env.getLoggedUserId(); value = filterParamDescriptor.getLookupDataSource() .get() // we assume we always have a lookup data source .findById(loggedUserId); } else { value = filterParamDescriptor.getAutoFilterInitialValue(); } return DocumentFilterParam.builder() .setFieldName(filterParamDescriptor.getFieldName()) .setOperator(Operator.EQUAL) .setValue(value) .build(); } @Override public DefaultView filterView( @NonNull final IView view, @NonNull final JSONFilterViewRequest filterViewRequest, @NonNull final Supplier<IViewsRepository> viewsRepo_NOTUSED) { return filterView(DefaultView.cast(view), filterViewRequest); } private DefaultView filterView( @NonNull final DefaultView view,
@NonNull final JSONFilterViewRequest filterViewRequest) { final DocumentFilterDescriptorsProvider filterDescriptors = view.getViewDataRepository().getViewFilterDescriptors(); final DocumentFilterList newFilters = filterViewRequest.getFiltersUnwrapped(filterDescriptors); // final DocumentFilterList newFiltersExcludingFacets = newFilters.retainOnlyNonFacetFilters(); // // final DocumentFilterList currentFiltersExcludingFacets = view.getFilters().retainOnlyNonFacetFilters(); // // if (DocumentFilterList.equals(currentFiltersExcludingFacets, newFiltersExcludingFacets)) // { // // TODO // throw new AdempiereException("TODO"); // } // else { return createView(CreateViewRequest.filterViewBuilder(view) .setFilters(newFilters) .build()); } } public SqlViewKeyColumnNamesMap getKeyColumnNamesMap(@NonNull final WindowId windowId) { final SqlViewBinding sqlBindings = viewLayouts.getViewBinding(windowId, DocumentFieldDescriptor.Characteristic.PublicField, ViewProfileId.NULL); return sqlBindings.getSqlViewKeyColumnNamesMap(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\SqlViewFactory.java
1
请完成以下Java代码
public VPanelLayoutCallback createFieldsPanelLayoutCallback() { final VPanelLayoutCallback layoutCallback = new VPanelLayoutCallback(); layoutCallback.setEnforceSameSizeOnAllLabels(true); // all labels shall have the same size layoutCallback.setLabelMinWidth(labelMinWidth); layoutCallback.setLabelMaxWidth(labelMaxWidth); layoutCallback.setFieldMaxWidth(fieldMinWidth); layoutCallback.setFieldMaxWidth(fieldMaxWidth); return layoutCallback; } public CC createFieldLabelConstraints(final boolean sameLine) { final CC constraints = new CC() .alignX("trailing") // align label to right, near the editor field ; if (!sameLine) { constraints.newline(); } return constraints; }
public CC createFieldEditorConstraints(final GridFieldLayoutConstraints gridFieldConstraints) { final CC constraints = new CC() .alignX("leading") .pushX() .growX(); if (gridFieldConstraints.getSpanX() > 1) { final int spanX = gridFieldConstraints.getSpanX() * 2 - 1; constraints.setSpanX(spanX); } if (gridFieldConstraints.getSpanY() > 1) { constraints.setSpanY(gridFieldConstraints.getSpanY()); } return constraints; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelLayoutFactory.java
1
请完成以下Java代码
default Optional<BPartnerLocationAndCaptureId> getBPartnerLocationAndCaptureIdIfExists() { return BPartnerLocationAndCaptureId.optionalOfRepoId(getC_BPartner_ID(), getC_BPartner_Location_ID(), getC_BPartner_Location_Value_ID()); } default Optional<BPartnerContactId> getBPartnerContactId() { return Optional.ofNullable(BPartnerContactId.ofRepoIdOrNull(getC_BPartner_ID(), getAD_User_ID())); } @Override default void setRenderedAddressAndCapturedLocation(@NonNull final RenderedAddressAndCapturedLocation from) { setC_BPartner_Location_Value_ID(LocationId.toRepoId(from.getCapturedLocationId())); setRenderedAddress(from); } @Override default void setRenderedAddress(@NonNull final RenderedAddressAndCapturedLocation from) { setBPartnerAddress(from.getRenderedAddress()); } default DocumentLocation toDocumentLocation() { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(getC_BPartner_ID()); return DocumentLocation.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(bpartnerId, getC_BPartner_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, getAD_User_ID())) .locationId(LocationId.ofRepoIdOrNull(getC_BPartner_Location_Value_ID())) .bpartnerAddress(getBPartnerAddress()) .build(); }
default void setFrom(@NonNull final DocumentLocation from) { setC_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); setC_BPartner_Location_ID(BPartnerLocationId.toRepoId(from.getBpartnerLocationId())); setC_BPartner_Location_Value_ID(LocationId.toRepoId(from.getLocationId())); setAD_User_ID(BPartnerContactId.toRepoId(from.getContactId())); setBPartnerAddress(from.getBpartnerAddress()); } default void setFrom(@NonNull final BPartnerInfo from) { setC_BPartner_ID(BPartnerId.toRepoId(from.getBpartnerId())); setC_BPartner_Location_ID(BPartnerLocationId.toRepoId(from.getBpartnerLocationId())); setC_BPartner_Location_Value_ID(LocationId.toRepoId(from.getLocationId())); setAD_User_ID(BPartnerContactId.toRepoId(from.getContactId())); setBPartnerAddress(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\adapter\IDocumentLocationAdapter.java
1
请完成以下Java代码
public String getPrintJobName() { return printJobName; } public void setPrintJobName(final String printJobName) { this.printJobName = printJobName; } public Printable getPrintable() { return printable; } public void setPrintable(final Printable printable) { this.printable = printable; } public int getNumPages()
{ return numPages; } public void setNumPages(final int numPages) { this.numPages = numPages; } @Override public String toString() { return "PrintPackageRequest [" + "printPackage=" + printPackage + ", printPackageInfo=" + printPackageInfo + ", attributes=" + attributes + ", printService=" + printService + ", printJobName=" + printJobName + ", printable=" + printable + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintPackageRequest.java
1
请完成以下Java代码
public void setZero() { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = 0.; } } } public void save(DataOutputStream out) throws Exception { out.writeInt(m); out.writeInt(n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { out.writeDouble(A[i][j]); } }
} public boolean load(ByteArray byteArray) { m = byteArray.nextInt(); n = byteArray.nextInt(); A = new double[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { A[i][j] = byteArray.nextDouble(); } } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Matrix.java
1
请完成以下Java代码
public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public org.compiere.model.I_C_OrderLine getC_OrderLine() { return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class); } @Override public void setC_OrderLine(final org.compiere.model.I_C_OrderLine C_OrderLine) { set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine); } @Override public void setC_OrderLine_ID (final int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID); } @Override public int getC_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID); } @Override public org.compiere.model.I_M_InOutLine getM_InOutLine() { return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class); } @Override public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine) { set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine); } @Override public void setM_InOutLine_ID (final int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID); } @Override public int getM_InOutLine_ID()
{ return get_ValueAsInt(COLUMNNAME_M_InOutLine_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 setProductNo (final @Nullable java.lang.String ProductNo) { set_Value (COLUMNNAME_ProductNo, ProductNo); } @Override public java.lang.String getProductNo() { return get_ValueAsString(COLUMNNAME_ProductNo); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_Value (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Product_v.java
1
请在Spring Boot框架中完成以下Java代码
class PropertiesLdapConnectionDetails implements LdapConnectionDetails { private final LdapProperties properties; private final Environment environment; PropertiesLdapConnectionDetails(LdapProperties properties, Environment environment) { this.properties = properties; this.environment = environment; } @Override public String[] getUrls() { return this.properties.determineUrls(this.environment); }
@Override public @Nullable String getBase() { return this.properties.getBase(); } @Override public @Nullable String getUsername() { return this.properties.getUsername(); } @Override public @Nullable String getPassword() { return this.properties.getPassword(); } }
repos\spring-boot-4.0.1\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\PropertiesLdapConnectionDetails.java
2
请完成以下Java代码
public String restxAdminPassword() { return "4780"; } @Provides public ConfigSupplier appConfigSupplier(ConfigLoader configLoader) { // Load settings.properties in restx.demo package as a set of config entries return configLoader.fromResource("web-modules/restx/demo/settings"); } @Provides public CredentialsStrategy credentialsStrategy() { return new BCryptCredentialsStrategy(); } @Provides public BasicPrincipalAuthenticator basicPrincipalAuthenticator( SecuritySettings securitySettings, CredentialsStrategy credentialsStrategy, @Named("restx.admin.passwordHash") String defaultAdminPasswordHash, ObjectMapper mapper) { return new StdBasicPrincipalAuthenticator(new StdUserService<>( // use file based users repository. // Developer's note: prefer another storage mechanism for your users if you need real user management // and better perf new FileBasedUserRepository<>( StdUser.class, // this is the class for the User objects, that you can get in your app code // with RestxSession.current().getPrincipal().get() // it can be a custom user class, it just need to be json deserializable mapper, // this is the default restx admin, useful to access the restx admin console. // if one user with restx-admin role is defined in the repository, this default user won't be
// available anymore new StdUser("admin", ImmutableSet.<String>of("*")), // the path where users are stored Paths.get("data/users.json"), // the path where credentials are stored. isolating both is a good practice in terms of security // it is strongly recommended to follow this approach even if you use your own repository Paths.get("data/credentials.json"), // tells that we want to reload the files dynamically if they are touched. // this has a performance impact, if you know your users / credentials never change without a // restart you can disable this to get better perfs true), credentialsStrategy, defaultAdminPasswordHash), securitySettings); } }
repos\tutorials-master\web-modules\restx\src\main\java\restx\demo\AppModule.java
1
请完成以下Java代码
public class BPPurchaseSchedule { @Getter private final LocalDate validFrom; private static final LocalDate DEFAULT_VALID_FROM = LocalDate.MIN; @Getter private final Frequency frequency; private static final LocalTime DEFAULT_PREPARATION_TIME = LocalTime.of(23, 59); private final ImmutableMap<DayOfWeek, LocalTime> dailyPreparationTimes; @Getter private final Duration reminderTime; @Getter private final BPartnerId bpartnerId; @Getter private final CalendarId nonBusinessDaysCalendarId; /** might be null, if the BPPurchaseSchedule wasn't stored yet */ @Getter BPPurchaseScheduleId bpPurchaseScheduleId; @Builder(toBuilder = true) private BPPurchaseSchedule( final BPPurchaseScheduleId bpPurchaseScheduleId, final LocalDate validFrom, @NonNull final Frequency frequency, @Singular @NonNull final ImmutableMap<DayOfWeek, LocalTime> dailyPreparationTimes, @NonNull final Duration reminderTime, @NonNull final BPartnerId bpartnerId, @Nullable final CalendarId nonBusinessDaysCalendarId) { Check.assume(!reminderTime.isNegative(), "reminderTime shall be >= 0 but it was {}", reminderTime); this.validFrom = validFrom != null ? validFrom : DEFAULT_VALID_FROM; this.frequency = frequency; this.dailyPreparationTimes = dailyPreparationTimes; this.reminderTime = reminderTime; this.bpPurchaseScheduleId = bpPurchaseScheduleId; this.bpartnerId = bpartnerId; this.nonBusinessDaysCalendarId = nonBusinessDaysCalendarId; }
public LocalTime getPreparationTime(final DayOfWeek dayOfWeek) { return dailyPreparationTimes.getOrDefault(dayOfWeek, DEFAULT_PREPARATION_TIME); } public LocalDateTime applyTimeTo(@NonNull final LocalDate date) { final LocalTime time = getPreparationTime(date.getDayOfWeek()); return LocalDateTime.of(date, time); } public Optional<LocalDateTime> calculateReminderDateTime(final LocalDateTime purchaseDate) { if (reminderTime.isZero()) { return Optional.empty(); } return Optional.of(purchaseDate.minus(reminderTime)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\BPPurchaseSchedule.java
1
请完成以下Java代码
public void setField(final GridField mField) { m_field = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField /** Grid Field */ private GridField m_field = null; /** * Get Field * * @return gridField */ @Override public GridField getField() { return m_field; } // getField @Override public void keyPressed(final KeyEvent e) { } @Override public void keyTyped(final KeyEvent e) { } /** * Key Released. if Escape Restore old Text * * @param e event * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent) */ @Override public void keyReleased(final KeyEvent e) { if (LogManager.isLevelFinest()) { log.trace("Key=" + e.getKeyCode() + " - " + e.getKeyChar() + " -> " + m_text.getText());
} // ESC if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { m_text.setText(m_initialText); } else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED) { return; } m_setting = true; try { String clear = m_text.getText(); if (clear.length() > m_fieldLength) { clear = clear.substring(0, m_fieldLength); } fireVetoableChange(m_columnName, m_oldText, clear); } catch (final PropertyVetoException pve) { } m_setting = false; } // metas @Override public boolean isAutoCommit() { return true; } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VFile
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VFile.java
1
请完成以下Java代码
public class Book { private String isbn; private String title; private String auto; public Book(String isbn, String title, String auto) { this.isbn = isbn; this.title = title; this.auto = auto; } public String getAuto() { return auto; } public void setAuto(String auto) { this.auto = auto; } public String getIsbn() { return isbn;
} public void setIsbn(String isbn) { this.isbn = isbn; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Book{" + "isbn='" + isbn + '\'' + ", title='" + title + '\'' + ", auto='" + auto + '\'' + '}'; } }
repos\spring-boot-quick-master\quick-cache\src\main\java\com\quick\cache\entity\Book.java
1
请完成以下Java代码
public class ChangeDeploymentTenantIdCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; protected String deploymentId; protected String newTenantId; public ChangeDeploymentTenantIdCmd(String deploymentId, String newTenantId) { this.deploymentId = deploymentId; this.newTenantId = newTenantId; } public Void execute(CommandContext commandContext) { if (deploymentId == null) { throw new ActivitiIllegalArgumentException("deploymentId is null"); } // Update all entities DeploymentEntity deployment = commandContext.getDeploymentEntityManager().findById(deploymentId); if (deployment == null) { throw new ActivitiObjectNotFoundException( "Could not find deployment with id " + deploymentId, Deployment.class ); } executeInternal(commandContext, deployment); return null; }
protected void executeInternal(CommandContext commandContext, DeploymentEntity deployment) { String oldTenantId = deployment.getTenantId(); deployment.setTenantId(newTenantId); // Doing process instances, executions and tasks with direct SQL updates // (otherwise would not be performant) commandContext .getProcessDefinitionEntityManager() .updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId); commandContext.getExecutionEntityManager().updateExecutionTenantIdForDeployment(deploymentId, newTenantId); commandContext.getTaskEntityManager().updateTaskTenantIdForDeployment(deploymentId, newTenantId); commandContext.getJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getTimerJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getSuspendedJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getDeadLetterJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId); commandContext.getEventSubscriptionEntityManager().updateEventSubscriptionTenantId(oldTenantId, newTenantId); // Doing process definitions in memory, cause we need to clear the process definition cache List<ProcessDefinition> processDefinitions = new ProcessDefinitionQueryImpl().deploymentId(deploymentId).list(); for (ProcessDefinition processDefinition : processDefinitions) { commandContext .getProcessEngineConfiguration() .getProcessDefinitionCache() .remove(processDefinition.getId()); } // Clear process definition cache commandContext.getProcessEngineConfiguration().getProcessDefinitionCache().clear(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ChangeDeploymentTenantIdCmd.java
1
请完成以下Java代码
private static List<PrintPackageInfo> mkPrintPackageInfoList(final List<PRTCPrintPackageInfoType> printPckgInfosAD) { final List<PrintPackageInfo> printPckgInfosPC = new ArrayList<PrintPackageInfo>(); for (final PRTCPrintPackageInfoType printPckgInfoAD : printPckgInfosAD) { final PrintPackageInfo printPckgInfoPC = new PrintPackageInfo(); printPckgInfoPC.setPrintService(printPckgInfoAD.getPrintServiceName()); printPckgInfoPC.setTray(printPckgInfoAD.getTrayName()); printPckgInfoPC.setTrayNumber( printPckgInfoAD.getTrayNumber() == null ? -1 : printPckgInfoAD.getTrayNumber().intValue()); printPckgInfoPC.setPageFrom(toInt(printPckgInfoAD.getPageFrom(), 0)); printPckgInfoPC.setPageTo(toInt(printPckgInfoAD.getPageTo(), 0));
printPckgInfoPC.setCalX(printPckgInfoAD.getCalX() == null ? 0 : printPckgInfoAD.getCalX().intValue()); printPckgInfoPC.setCalY(printPckgInfoAD.getCalY() == null ? 0 : printPckgInfoAD.getCalY().intValue()); printPckgInfosPC.add(printPckgInfoPC); } return printPckgInfosPC; } private static int toInt(BigInteger value, int defaultValue) { return value == null ? defaultValue : value.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\inout\bean\PRTCPrintPackageTypeConverter.java
1
请完成以下Java代码
public class DefaultSecurityParameterNameDiscoverer extends PrioritizedParameterNameDiscoverer { private static final String DATA_PARAM_CLASSNAME = "org.springframework.data.repository.query.Param"; private static final boolean DATA_PARAM_PRESENT = ClassUtils.isPresent(DATA_PARAM_CLASSNAME, DefaultSecurityParameterNameDiscoverer.class.getClassLoader()); /** * Creates a new instance with only the default {@link ParameterNameDiscoverer} * instances. */ public DefaultSecurityParameterNameDiscoverer() { this(Collections.emptyList()); } /** * Creates a new instance that first tries the passed in * {@link ParameterNameDiscoverer} instances. * @param parameterNameDiscovers the {@link ParameterNameDiscoverer} before trying the
* defaults. Cannot be null. */ @SuppressWarnings("unchecked") public DefaultSecurityParameterNameDiscoverer(List<? extends ParameterNameDiscoverer> parameterNameDiscovers) { Assert.notNull(parameterNameDiscovers, "parameterNameDiscovers cannot be null"); for (ParameterNameDiscoverer discover : parameterNameDiscovers) { addDiscoverer(discover); } Set<String> annotationClassesToUse = new HashSet<>(2); annotationClassesToUse.add("org.springframework.security.access.method.P"); annotationClassesToUse.add(P.class.getName()); if (DATA_PARAM_PRESENT) { annotationClassesToUse.add(DATA_PARAM_CLASSNAME); } addDiscoverer(new AnnotationParameterNameDiscoverer(annotationClassesToUse)); addDiscoverer(new DefaultParameterNameDiscoverer()); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\core\parameters\DefaultSecurityParameterNameDiscoverer.java
1
请完成以下Java代码
public ITranslatableString getValueAsTranslatableString() { switch (valueType) { case STRING: case LIST: { final String valueStr = getValueAsString(); return TranslatableStrings.anyLanguage(valueStr); } case NUMBER: { final BigDecimal valueBD = getValueAsBigDecimal(); return valueBD != null ? TranslatableStrings.number(valueBD, de.metas.common.util.NumberUtils.isInteger(valueBD) ? DisplayType.Integer : DisplayType.Number) : TranslatableStrings.empty(); }
case DATE: { final LocalDate valueDate = getValueAsLocalDate(); return valueDate != null ? TranslatableStrings.date(valueDate, DisplayType.Date) : TranslatableStrings.empty(); } default: { return TranslatableStrings.empty(); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\Attribute.java
1
请完成以下Java代码
public class DatabasePurgeReport implements PurgeReporting<Long> { /** * Key: table name * Value: entity count */ Map<String, Long> deletedEntities = new HashMap<String, Long>(); boolean dbContainsLicenseKey; @Override public void addPurgeInformation(String key, Long value) { deletedEntities.put(key, value); } @Override public Map<String, Long> getPurgeReport() { return deletedEntities; } @Override public String getPurgeReportAsString() { StringBuilder builder = new StringBuilder(); for (String key : deletedEntities.keySet()) { builder.append("Table: ").append(key) .append(" contains: ").append(getReportValue(key)) .append(" rows\n"); } return builder.toString(); } @Override public Long getReportValue(String key) { return deletedEntities.get(key); } @Override
public boolean containsReport(String key) { return deletedEntities.containsKey(key); } public boolean isEmpty() { return deletedEntities.isEmpty(); } public boolean isDbContainsLicenseKey() { return dbContainsLicenseKey; } public void setDbContainsLicenseKey(boolean dbContainsLicenseKey) { this.dbContainsLicenseKey = dbContainsLicenseKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\DatabasePurgeReport.java
1
请完成以下Java代码
public class AlarmSubscriptionUpdate { @Getter private int errorCode; @Getter private String errorMsg; @Getter private AlarmInfo alarm; @Getter private boolean alarmDeleted; public AlarmSubscriptionUpdate(AlarmInfo alarm) { this(alarm, false); } public AlarmSubscriptionUpdate(AlarmInfo alarm, boolean alarmDeleted) { super();
this.alarm = alarm; this.alarmDeleted = alarmDeleted; } public AlarmSubscriptionUpdate(SubscriptionErrorCode errorCode) { this(errorCode, null); } public AlarmSubscriptionUpdate(SubscriptionErrorCode errorCode, String errorMsg) { super(); this.errorCode = errorCode.getCode(); this.errorMsg = errorMsg != null ? errorMsg : errorCode.getDefaultMsg(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\telemetry\sub\AlarmSubscriptionUpdate.java
1
请完成以下Java代码
private void notifyImportDone( @NonNull final ActualImportRecordsResult result, @NonNull final UserId recipientUserId) { try { final String targetTableName = result.getTargetTableName(); final String windowName = adTableDAO.retrieveWindowName(Env.getCtx(), targetTableName); notificationBL.send(UserNotificationRequest.builder() .topic(USER_NOTIFICATIONS_TOPIC) .recipientUserId(recipientUserId) .contentADMessage(MSG_Event_RecordsImported) .contentADMessageParam(result.getCountInsertsIntoTargetTableString()) .contentADMessageParam(result.getCountUpdatesIntoTargetTableString()) .contentADMessageParam(windowName)
.build()); } catch (final Exception ex) { logger.warn("Failed notifying user '{}' about {}. Ignored.", recipientUserId, result, ex); } } public int deleteImportRecords(@NonNull final ImportDataDeleteRequest request) { return importProcessFactory.newImportProcessForTableName(request.getImportTableName()) .setParameters(request.getAdditionalParameters()) .deleteImportRecords(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\DataImportService.java
1
请完成以下Java代码
public static class QuantitySerializer extends StdSerializer<Quantity> { private static final long serialVersionUID = -8292209848527230256L; public QuantitySerializer() { super(Quantity.class); } @Override public void serialize(final Quantity value, final JsonGenerator gen, final SerializerProvider provider) throws IOException { gen.writeStartObject(); final String qtyStr = value.toBigDecimal().toString(); final int uomId = value.getUomId().getRepoId(); gen.writeFieldName("qty"); gen.writeString(qtyStr);
gen.writeFieldName("uomId"); gen.writeNumber(uomId); final String sourceQtyStr = value.getSourceQty().toString(); final int sourceUomId = value.getSourceUomId().getRepoId(); if (!qtyStr.equals(sourceQtyStr) || uomId != sourceUomId) { gen.writeFieldName("sourceQty"); gen.writeString(sourceQtyStr); gen.writeFieldName("sourceUomId"); gen.writeNumber(sourceUomId); } gen.writeEndObject(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantitys.java
1
请在Spring Boot框架中完成以下Java代码
public class InventoryService { private final InventoryRepository inventoryRepository; private final LocationRepository locationRepository; public InventoryService(InventoryRepository inventoryRepository, LocationRepository locationRepository) { this.inventoryRepository = inventoryRepository; this.locationRepository = locationRepository; } @Transactional public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) { Optional<Vehicle> existingVehicle = this.inventoryRepository.findById(vin); if (existingVehicle.isPresent()) { Map<String, Object> params = new HashMap<>(); params.put("vin", vin); throw new VehicleAlreadyPresentException("Failed to add vehicle. Vehicle with vin already present.", params); } Vehicle vehicle = Vehicle.builder() .vin(vin) .year(year) .make(make) .model(model) .location(location) .trim(trim) .build(); this.locationRepository.save(location);
return this.inventoryRepository.save(vehicle); } public List<Vehicle> searchAll() { return this.inventoryRepository.findAll(); } public List<Vehicle> searchByLocation(String zipcode) { if (StringUtils.hasText(zipcode) || zipcode.length() != 5) { throw new InvalidInputException("Invalid zipcode " + zipcode + " provided."); } return this.locationRepository.findById(zipcode) .map(Location::getVehicles) .orElse(new ArrayList<>()); } public Vehicle searchByVin(String vin) { return this.inventoryRepository.findById(vin) .orElseThrow(() -> new VehicleNotFoundException("Vehicle with vin: " + vin + " not found.")); } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql\src\main\java\com\baeldung\graphql\error\handling\service\InventoryService.java
2
请完成以下Java代码
public class SetAppDefinitionCategoryCmd implements Command<Void> { protected String appDefinitionId; protected String category; public SetAppDefinitionCategoryCmd(String appDefinitionId, String category) { this.appDefinitionId = appDefinitionId; this.category = category; } @Override public Void execute(CommandContext commandContext) { if (appDefinitionId == null) { throw new FlowableIllegalArgumentException("App definition id is null"); } AppDefinitionEntity appDefinition = CommandContextUtil.getAppDefinitionEntityManager(commandContext).findById(appDefinitionId);
if (appDefinition == null) { throw new FlowableObjectNotFoundException("No app definition found for id = '" + appDefinitionId + "'", AppDefinition.class); } // Update category appDefinition.setCategory(category); // Remove app definition from cache, it will be refetch later DeploymentCache<AppDefinitionCacheEntry> appDefinitionCache = CommandContextUtil.getAppEngineConfiguration(commandContext).getAppDefinitionCache(); if (appDefinitionCache != null) { appDefinitionCache.remove(appDefinitionId); } return null; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\cmd\SetAppDefinitionCategoryCmd.java
1
请完成以下Java代码
public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Date getTime() { return getStartTime(); } @Override public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public Long getWorkTimeInMillis() { if (endTime == null || claimTime == null) { return null; } return endTime.getTime() - claimTime.getTime(); } public Map<String, Object> getTaskLocalVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityImpl.java
1
请完成以下Java代码
public static ITypeStage builder() { return new Builder(); } /** * Definition of a stage for staged builder. */ public interface ITypeStage { /** * Builder method for type parameter. * @param type field to set * @return builder */ public IValueStage type(String type); } /** * Definition of a stage for staged builder. */ public interface IValueStage { /** * Builder method for value parameter. * @param value field to set * @return builder */ public IBuildStage value(String value); } /** * Definition of a stage for staged builder. */ public interface IBuildStage { /** * Builder method of the builder. * @return built class */ public ProcessVariableValue build(); }
/** * Builder to build {@link ProcessVariableValue}. */ public static final class Builder implements ITypeStage, IValueStage, IBuildStage { private String type; private String value; private Builder() {} @Override public IValueStage type(String type) { this.type = type; return this; } @Override public IBuildStage value(String value) { this.value = value; return this; } @Override public ProcessVariableValue build() { return new ProcessVariableValue(this); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessVariableValue.java
1
请完成以下Java代码
public class BookScraper implements PageProcessor { private Site site = Site.me().setRetryTimes(3).setSleepTime(1000); private final List<Book> books = new ArrayList<>(); @Override public void process(Page page) { var bookNodes = page.getHtml().css("article.product_pod"); for (int i = 0; i < Math.min(10, bookNodes.nodes().size()); i++) { var book = bookNodes.nodes().get(i); String title = book.css("h3 a", "title").get(); String price = book.css(".price_color", "text").get(); books.add(new Book(title, price)); } } @Override public Site getSite() { return site; }
public List<Book> getBooks() { return Collections.unmodifiableList(books); } public static void main(String[] args) { BookScraper bookScraper = new BookScraper(); Spider.create(bookScraper) .addUrl("https://books.toscrape.com/") .thread(1) .run(); bookScraper.getBooks().forEach(book -> System.out.println("Title: " + book.getTitle() + " | Price: " + book.getPrice())); } }
repos\tutorials-master\libraries-7\src\main\java\com\baeldung\webmagic\BookScraper.java
1
请完成以下Java代码
public class CodeSnippets { static Cluster loadClusterWithDefaultEnvironment() { return CouchbaseCluster.create("localhost"); } static Cluster loadClusterWithCustomEnvironment() { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build(); return CouchbaseCluster.create(env, "localhost"); } static Bucket loadDefaultBucketWithBlankPassword(Cluster cluster) { return cluster.openBucket(); } static Bucket loadBaeldungBucket(Cluster cluster) { return cluster.openBucket("baeldung", ""); } static JsonDocument insertExample(Bucket bucket) { JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago"); String id = UUID.randomUUID().toString(); JsonDocument document = JsonDocument.create(id, content); JsonDocument inserted = bucket.insert(document); return inserted; } static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); content.put("homeTown", "Kansas City"); JsonDocument upserted = bucket.upsert(document); return upserted; } static JsonDocument replaceExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); content.put("homeTown", "Milwaukee"); JsonDocument replaced = bucket.replace(document); return replaced; } static JsonDocument removeExample(Bucket bucket, String id) { JsonDocument removed = bucket.remove(id); return removed; }
static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) { try { return bucket.get(id); } catch (CouchbaseException e) { List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST); if (!list.isEmpty()) { return list.get(0); } } return null; } static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) { long maxCasValue = -1; JsonDocument latest = null; for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { if (replica.cas() > maxCasValue) { latest = replica; maxCasValue = replica.cas(); } } return latest; } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\intro\CodeSnippets.java
1
请完成以下Java代码
public void setC_AcctSchema_ID (final int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID); } @Override public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public org.compiere.model.I_C_ValidCombination getPJ_Asset_A() { return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A) { set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A); } @Override public void setPJ_Asset_Acct (final int PJ_Asset_Acct) { set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct); } @Override public int getPJ_Asset_Acct()
{ return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct); } @Override public org.compiere.model.I_C_ValidCombination getPJ_WIP_A() { return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A) { set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A); } @Override public void setPJ_WIP_Acct (final int PJ_WIP_Acct) { set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct); } @Override public int getPJ_WIP_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java
1
请完成以下Java代码
private HttpHeaders getHeaders(@NonNull final ContentCachingResponseWrapper responseWrapper) { final HttpHeaders responseHeaders = new HttpHeaders(); final Collection<String> headerNames = responseWrapper.getHeaderNames(); if (headerNames == null || headerNames.isEmpty()) { return responseHeaders; } headerNames.forEach(headerName -> responseHeaders.addAll(headerName, new ArrayList<>(responseWrapper.getHeaders(headerName)))); return responseHeaders; } @Nullable private static MediaType getContentType(final @NonNull ContentCachingResponseWrapper responseWrapper) { final String contentType = StringUtils.trimBlankToNull(responseWrapper.getContentType()); return contentType != null ? MediaType.parseMediaType(contentType) : null; } @Nullable private static MediaType getContentType(final @Nullable HttpHeaders httpHeaders) { return httpHeaders != null ? httpHeaders.getContentType() : null; } @NonNull private static Charset getCharset(final @NonNull ContentCachingResponseWrapper responseWrapper) { final String charset = StringUtils.trimBlankToNull(responseWrapper.getCharacterEncoding()); return charset != null ? Charset.forName(charset) : StandardCharsets.UTF_8; } @Nullable private Object getBody(@NonNull final ContentCachingResponseWrapper responseWrapper) { if (responseWrapper.getContentSize() <= 0) { return null; } final MediaType contentType = getContentType(responseWrapper); if (contentType == null) { return null; } else if (contentType.includes(MediaType.TEXT_PLAIN)) { return new String(responseWrapper.getContentAsByteArray()); } else if (contentType.includes(MediaType.APPLICATION_JSON)) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(responseWrapper.getContentAsByteArray(), Object.class); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } } else { return responseWrapper.getContentAsByteArray(); } }
@Nullable private Object getBody(@Nullable final HttpHeaders httpHeaders, @Nullable final String bodyCandidate) { if (bodyCandidate == null) { return null; } final MediaType contentType = getContentType(httpHeaders); if (contentType == null) { return null; } else if (contentType.includes(MediaType.TEXT_PLAIN)) { return bodyCandidate; } else if (contentType.includes(MediaType.APPLICATION_JSON)) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(bodyCandidate, Object.class); } catch (final IOException e) { throw AdempiereException.wrapIfNeeded(e); } } else { return bodyCandidate; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponseMapper.java
1
请完成以下Java代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 为每个请求设置唯一标示到MDC容器中 setMdc(request); try { // 执行后续操作 chain.doFilter(request, response); } finally { try { MDC.remove(MdcConstant.SESSION_KEY); MDC.remove(MdcConstant.REQUEST_KEY); } catch (Exception e) { logger.warn(e.getMessage(), e); } } } @Override
public void init(FilterConfig arg0) throws ServletException { } /** * 为每个请求设置唯一标示到MDC容器中 */ private void setMdc(ServletRequest request) { try { // 设置SessionId String requestId = UUID.randomUUID().toString().replace("-", ""); MDC.put(MdcConstant.SESSION_KEY, "userId"); MDC.put(MdcConstant.REQUEST_KEY, requestId); } catch (Exception e) { logger.warn(e.getMessage(), e); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\interceptors\TrackFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class Product { @Id private int id; private String name; private double price; public Product() { super(); } private Product(int id, String name, double price) { super(); this.id = id; this.name = name; this.price = price; } public static Product from(int id, String name, double price) { return new Product(id, name, price); } public int getId() { return id; } public void setId(final int id) { this.id = id; } public String getName() { return name; }
public void setName(final String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(final double price) { this.price = price; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Product [name=") .append(name) .append(", id=") .append(id) .append("]"); return builder.toString(); } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\multipledb\model\product\Product.java
2
请完成以下Java代码
public class SuffixDictionary { BinTrie<Integer> trie; public SuffixDictionary() { trie = new BinTrie<Integer>(); } /** * 添加一个词语 * @param word */ public void add(String word) { word = reverse(word); trie.put(word, word.length()); } public void addAll(String total) { for (int i = 0; i < total.length(); ++i) { add(String.valueOf(total.charAt(i))); } } public void addAll(String[] total) { for (String single : total) { add(single); } } /** * 查找是否有该后缀 * @param suffix * @return */ public int get(String suffix) { suffix = reverse(suffix); Integer length = trie.get(suffix); if (length == null) return 0; return length; } /**
* 词语是否以该词典中的某个单词结尾 * @param word * @return */ public boolean endsWith(String word) { word = reverse(word); return trie.commonPrefixSearchWithValue(word).size() > 0; } /** * 获取最长的后缀 * @param word * @return */ public int getLongestSuffixLength(String word) { word = reverse(word); LinkedList<Map.Entry<String, Integer>> suffixList = trie.commonPrefixSearchWithValue(word); if (suffixList.size() == 0) return 0; return suffixList.getLast().getValue(); } private static String reverse(String word) { return new StringBuilder(word).reverse().toString(); } /** * 键值对 * @return */ public Set<Map.Entry<String, Integer>> entrySet() { Set<Map.Entry<String, Integer>> treeSet = new LinkedHashSet<Map.Entry<String, Integer>>(); for (Map.Entry<String, Integer> entry : trie.entrySet()) { treeSet.add(new AbstractMap.SimpleEntry<String, Integer>(reverse(entry.getKey()), entry.getValue())); } return treeSet; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SuffixDictionary.java
1
请在Spring Boot框架中完成以下Java代码
public String getAttachmentPrefix(String defaultValue) { return null; } @Override public MADBoilerPlate getDefaultTextPreset() { return null; } @Override public String getExportFilePrefix() { return null; } @Override public I_AD_User getFrom() { return null; } @Override public String getMessage() {
return null; } @Override public String getSubject() { return null; } @Override public String getTitle() { return null; } @Override public String getTo() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\EmptyEmailParams.java
2
请完成以下Java代码
private static ExternalSystem fromRecord(@NonNull final I_ExternalSystem externalSystemRecord) { return ExternalSystem.builder() .id(ExternalSystemId.ofRepoId(externalSystemRecord.getExternalSystem_ID())) .type(ExternalSystemType.ofValue(externalSystemRecord.getValue())) .name(externalSystemRecord.getName()) .build(); } public ExternalSystem create(@NonNull final ExternalSystemCreateRequest request) { final I_ExternalSystem record = InterfaceWrapperHelper.newInstance(I_ExternalSystem.class); record.setName(request.getName()); record.setValue(request.getType().getValue()); InterfaceWrapperHelper.save(record);
return fromRecord(record); } @Nullable public ExternalSystem getByLegacyCodeOrValueOrNull(@NonNull final String value) { final ExternalSystemMap map = getMap(); return CoalesceUtil.coalesceSuppliers( () -> map.getByTypeOrNull(ExternalSystemType.ofValue(value)), () -> { final ExternalSystemType externalSystemType = ExternalSystemType.ofLegacyCodeOrNull(value); return externalSystemType != null ? map.getByTypeOrNull(externalSystemType) : null; } ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemRepository.java
1
请完成以下Java代码
public int getCB_CashTransfer_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_CB_CashTransfer_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCB_Differences_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getCB_Differences_Acct(), get_TrxName()); } /** Set Cash Book Differences. @param CB_Differences_Acct Cash Book Differences Account */ public void setCB_Differences_Acct (int CB_Differences_Acct) { set_Value (COLUMNNAME_CB_Differences_Acct, Integer.valueOf(CB_Differences_Acct)); } /** Get Cash Book Differences. @return Cash Book Differences Account */ public int getCB_Differences_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_CB_Differences_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCB_Expense_A() throws RuntimeException { return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getCB_Expense_Acct(), get_TrxName()); } /** Set Cash Book Expense. @param CB_Expense_Acct Cash Book Expense Account */ public void setCB_Expense_Acct (int CB_Expense_Acct) { set_Value (COLUMNNAME_CB_Expense_Acct, Integer.valueOf(CB_Expense_Acct)); } /** Get Cash Book Expense. @return Cash Book Expense Account */ public int getCB_Expense_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_CB_Expense_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_ValidCombination getCB_Receipt_A() throws RuntimeException {
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name) .getPO(getCB_Receipt_Acct(), get_TrxName()); } /** Set Cash Book Receipt. @param CB_Receipt_Acct Cash Book Receipts Account */ public void setCB_Receipt_Acct (int CB_Receipt_Acct) { set_Value (COLUMNNAME_CB_Receipt_Acct, Integer.valueOf(CB_Receipt_Acct)); } /** Get Cash Book Receipt. @return Cash Book Receipts Account */ public int getCB_Receipt_Acct () { Integer ii = (Integer)get_Value(COLUMNNAME_CB_Receipt_Acct); if (ii == null) return 0; return ii.intValue(); } public I_C_CashBook getC_CashBook() throws RuntimeException { return (I_C_CashBook)MTable.get(getCtx(), I_C_CashBook.Table_Name) .getPO(getC_CashBook_ID(), get_TrxName()); } /** Set Cash Book. @param C_CashBook_ID Cash Book for recording petty cash transactions */ public void setC_CashBook_ID (int C_CashBook_ID) { if (C_CashBook_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID)); } /** Get Cash Book. @return Cash Book for recording petty cash transactions */ public int getC_CashBook_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook_Acct.java
1
请在Spring Boot框架中完成以下Java代码
public class ItemType { @XmlElement(name = "TaxedAmount", required = true) protected BigDecimal taxedAmount; @XmlElement(name = "TaxRate", required = true) protected TaxRateType taxRate; @XmlElement(name = "Amount", required = true) protected BigDecimal amount; @XmlElement(name = "DomesticAmount") protected DomesticAmountType domesticAmount; @XmlElement(name = "Description") protected String description; /** * The base amount for the tax (= the amount the tax must be applied to). * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxedAmount() { return taxedAmount; } /** * Sets the value of the taxedAmount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxedAmount(BigDecimal value) { this.taxedAmount = value; } /** * The tax rate. * * @return * possible object is * {@link TaxRateType } * */ public TaxRateType getTaxRate() { return taxRate; } /** * Sets the value of the taxRate property. * * @param value * allowed object is * {@link TaxRateType } * */ public void setTaxRate(TaxRateType value) { this.taxRate = value; } /** * The tax amount. Calculated using: taxed amount x tax rate = tax amount. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setAmount(BigDecimal value) { this.amount = value; } /**
* The tax amount in the domestic currency. The domestic currency != invoice currency. * * @return * possible object is * {@link DomesticAmountType } * */ public DomesticAmountType getDomesticAmount() { return domesticAmount; } /** * Sets the value of the domesticAmount property. * * @param value * allowed object is * {@link DomesticAmountType } * */ public void setDomesticAmount(DomesticAmountType value) { this.domesticAmount = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ItemType.java
2
请完成以下Java代码
public class UnitTestServiceNamePolicy extends DefaultServiceNamePolicy implements IServiceNameAutoDetectPolicy { @Override public String getServiceImplementationClassName(Class<? extends IService> clazz) { final String servicePackageName = clazz.getPackage().getName() + ".impl."; String serviceClassName; if (clazz.getSimpleName().startsWith("I")) serviceClassName = clazz.getSimpleName().substring(1); else serviceClassName = clazz.getSimpleName(); final String plainServiceClassNameFQ = servicePackageName + "Plain" + serviceClassName;
try { Thread.currentThread().getContextClassLoader().loadClass(plainServiceClassNameFQ); return plainServiceClassNameFQ; } catch (ClassNotFoundException e) { // logger.debug("No Plain/Unit service found for "+clazz+". Tried "+plainServiceClassNameFQ); // Plain Service not found, use original one // TODO also try to load return super.getServiceImplementationClassName(clazz); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\UnitTestServiceNamePolicy.java
1
请完成以下Java代码
public class Node<V> extends BaseNode { @Override protected boolean addChild(BaseNode node) { boolean add = false; if (child == null) { child = new BaseNode[0]; } int index = ArrayTool.binarySearch(child, node); if (index >= 0) { BaseNode target = child[index]; switch (node.status) { case UNDEFINED_0: if (target.status != Status.NOT_WORD_1) { target.status = Status.NOT_WORD_1; target.value = null; add = true; } break; case NOT_WORD_1: if (target.status == Status.WORD_END_3) { target.status = Status.WORD_MIDDLE_2; } break; case WORD_END_3: if (target.status != Status.WORD_END_3) { target.status = Status.WORD_MIDDLE_2; } if (target.getValue() == null) { add = true; } target.setValue(node.getValue()); break; }
} else { BaseNode newChild[] = new BaseNode[child.length + 1]; int insert = -(index + 1); System.arraycopy(child, 0, newChild, 0, insert); System.arraycopy(child, insert, newChild, insert + 1, child.length - insert); newChild[insert] = node; child = newChild; add = true; } return add; } /** * @param c 节点的字符 * @param status 节点状态 * @param value 值 */ public Node(char c, Status status, V value) { this.c = c; this.status = status; this.value = value; } public Node() { } @Override public BaseNode getChild(char c) { if (child == null) return null; int index = ArrayTool.binarySearch(child, c); if (index < 0) return null; return child[index]; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\Node.java
1
请完成以下Java代码
private Optional<DocOutboundConfig> getDocOutboundConfig() { if (_docOutboundConfig == null) { _docOutboundConfig = retrieveDocOutboundConfig(); } return _docOutboundConfig; } private Optional<DocOutboundConfig> retrieveDocOutboundConfig() { final DocOutboundConfig docOutboundConfig = docOutboundConfigService.retrieveConfigForModel(getRecord()); logger.debug("Using config: {}", docOutboundConfig); return Optional.ofNullable(docOutboundConfig); } private Optional<PrintFormatId> getPrintFormatId() { // Favor the Report Process if any if (reportProcessId != null) { return Optional.empty(); }
// Then check the print format else if (printFormatId != null) { return Optional.of(printFormatId); } // Else, fallback to doc outbound config else { return getDocOutboundConfig().map(DocOutboundConfig::getPrintFormatId); } } @NonNull private Optional<String> getCCPath() { return getDocOutboundConfig().map(DocOutboundConfig::getCcPath); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\DefaultModelArchiver.java
1
请完成以下Java代码
public String handleConstraintViolationException(ConstraintViolationException e) { StringBuilder message = new StringBuilder(); Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); for (ConstraintViolation<?> violation : violations) { Path path = violation.getPropertyPath(); String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), "."); message.append(pathArr[1]).append(violation.getMessage()).append(","); } message = new StringBuilder(message.substring(0, message.length() - 1)); return message.toString(); } /** * 统一处理请求参数校验(实体对象传参) * * @param e BindException
* @return FebsResponse */ @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public String validExceptionHandler(BindException e) { StringBuilder message = new StringBuilder(); List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); for (FieldError error : fieldErrors) { message.append(error.getField()).append(error.getDefaultMessage()).append(","); } message = new StringBuilder(message.substring(0, message.length() - 1)); return message.toString(); } }
repos\SpringAll-master\46.Spring-Boot-Hibernate-Validator\src\main\java\com\example\demo\handler\GlobalExceptionHandler.java
1
请完成以下Java代码
protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_B_TopicCategory[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Topic Category. @param B_TopicCategory_ID Auction Topic Category */ public void setB_TopicCategory_ID (int B_TopicCategory_ID) { if (B_TopicCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_B_TopicCategory_ID, Integer.valueOf(B_TopicCategory_ID)); } /** Get Topic Category. @return Auction Topic Category */ public int getB_TopicCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicCategory_ID); if (ii == null) return 0; return ii.intValue(); } public I_B_TopicType getB_TopicType() throws RuntimeException { return (I_B_TopicType)MTable.get(getCtx(), I_B_TopicType.Table_Name) .getPO(getB_TopicType_ID(), get_TrxName()); } /** Set Topic Type. @param B_TopicType_ID Auction Topic Type */ public void setB_TopicType_ID (int B_TopicType_ID) { if (B_TopicType_ID < 1) set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, null); else set_ValueNoCheck (COLUMNNAME_B_TopicType_ID, Integer.valueOf(B_TopicType_ID)); } /** Get Topic Type. @return Auction Topic Type
*/ public int getB_TopicType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_B_TopicType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_TopicCategory.java
1
请完成以下Java代码
public void invalidateAll() { invalidate(DocumentIdsSelection.ALL); // nothing } @Override public void invalidate(final DocumentIdsSelection rowIds) { final ImmutableSet<PaymentId> paymentIds = rowsHolder .getRecordIdsToRefresh(rowIds, PaymentRow::convertDocumentIdToPaymentId); final List<PaymentRow> newRows = repository.getPaymentRowsListByPaymentId(paymentIds, evaluationDate); rowsHolder.compute(rows -> rows .replacingRows(rowIds, newRows) .removingRowId(PaymentRow.DEFAULT_PAYMENT_ROW.getId()) .addingRowIfEmpty(PaymentRow.DEFAULT_PAYMENT_ROW));
} public void addPayment(@NonNull final PaymentId paymentId) { final PaymentRow row = repository.getPaymentRowByPaymentId(paymentId, evaluationDate).orElse(null); if (row == null) { throw new AdempiereException("@PaymentNotOpen@"); } rowsHolder.compute(rows -> rows .addingRow(row) .removingRowId(PaymentRow.DEFAULT_PAYMENT_ROW.getId()) .addingRowIfEmpty(PaymentRow.DEFAULT_PAYMENT_ROW)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\PaymentRows.java
1
请完成以下Java代码
int numKeys() { return _keys.length; } /** * 根据id获取key * @param id * @return */ byte[] getKey(int id) { return _keys[id]; } /** * 获取某个key的某一个字节 * @param keyId key的id * @param byteId 字节的下标(第几个字节) * @return 字节,返回0表示越界了 */ byte getKeyByte(int keyId, int byteId) { if (byteId >= _keys[keyId].length) { return 0; } return _keys[keyId][byteId]; } /** * 是否含有值 * @return */ boolean hasValues() { return _values != null;
} /** * 根据下标获取值 * @param id * @return */ int getValue(int id) { if (hasValues()) { return _values[id]; } return id; } /** * 键 */ private byte[][] _keys; /** * 值 */ private int _values[]; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\Keyset.java
1
请在Spring Boot框架中完成以下Java代码
public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String role; protected User() { } public User(String name, String role) { super(); this.name = name; this.role = role; }
public Long getId() { return id; } public String getName() { return name; } public String getRole() { return role; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", role=" + role + "]"; } }
repos\spring-boot-examples-master\spring-boot-rest-services\src\main\java\com\in28minutes\springboot\jpa\User.java
2
请完成以下Java代码
class FontStyle { /** * Create FontStyle * @param name * @param id */ public FontStyle(String name, int id) { m_name = name; m_id = id; } // FontStyle private String m_name; private int m_id; /** * Get Name
* @return name */ @Override public String toString() { return m_name; } // getName /** * Get int value of Font Style * @return id */ public int getID() { return m_id; } // getID } // FontStyle
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\FontChooser.java
1
请完成以下Java代码
public void setM_Securpharm_Config_ID (int M_Securpharm_Config_ID) { if (M_Securpharm_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Securpharm_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Securpharm_Config_ID, Integer.valueOf(M_Securpharm_Config_ID)); } /** Get SecurPharm Einstellungen. @return SecurPharm Einstellungen */ @Override public int getM_Securpharm_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Pharma REST API URL. @param PharmaRestApiBaseURL Pharma REST API URL */ @Override public void setPharmaRestApiBaseURL (java.lang.String PharmaRestApiBaseURL) { set_Value (COLUMNNAME_PharmaRestApiBaseURL, PharmaRestApiBaseURL); } /** Get Pharma REST API URL. @return Pharma REST API URL */ @Override public java.lang.String getPharmaRestApiBaseURL () { return (java.lang.String)get_Value(COLUMNNAME_PharmaRestApiBaseURL); } /** Set Support Benutzer. @param Support_User_ID Benutzer für Benachrichtigungen */
@Override public void setSupport_User_ID (int Support_User_ID) { if (Support_User_ID < 1) set_Value (COLUMNNAME_Support_User_ID, null); else set_Value (COLUMNNAME_Support_User_ID, Integer.valueOf(Support_User_ID)); } /** Get Support Benutzer. @return Benutzer für Benachrichtigungen */ @Override public int getSupport_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Support_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set TAN Passwort. @param TanPassword TAN Passwort benutzt für Authentifizierung */ @Override public void setTanPassword (java.lang.String TanPassword) { set_Value (COLUMNNAME_TanPassword, TanPassword); } /** Get TAN Passwort. @return TAN Passwort benutzt für Authentifizierung */ @Override public java.lang.String getTanPassword () { return (java.lang.String)get_Value(COLUMNNAME_TanPassword); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Config.java
1
请完成以下Java代码
public String uppercaseResponse(String body) { return "Hello: " + body; } @Get("/exception") @ExceptionHandler(ConflictExceptionHandler.class) public String exception() { throw new IllegalStateException(); } static class JsonBody { String name; int score; public JsonBody() {} public JsonBody(String name, int score) { this.name = name; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } static class UppercasingRequestConverter implements RequestConverterFunction { @Override public Object convertRequest(ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType, ParameterizedType expectedParameterizedResultType) throws Exception { if (expectedResultType.isAssignableFrom(String.class)) { return request.content(StandardCharsets.UTF_8).toUpperCase();
} return RequestConverterFunction.fallthrough(); } } static class UppercasingResponseConverter implements ResponseConverterFunction { @Override public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers, @Nullable Object result, HttpHeaders trailers) { if (result instanceof String) { return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, ((String) result).toUpperCase(), trailers); } return ResponseConverterFunction.fallthrough(); } } static class ConflictExceptionHandler implements ExceptionHandlerFunction { @Override public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) { if (cause instanceof IllegalStateException) { return HttpResponse.of(HttpStatus.CONFLICT); } return ExceptionHandlerFunction.fallthrough(); } } } }
repos\tutorials-master\server-modules\armeria\src\main\java\com\baeldung\armeria\AnnotatedServer.java
1
请完成以下Java代码
public EventModelBuilder payload(String name, String type) { eventPayloadDefinitions.put(name, new EventPayload(name, type)); return this; } @Override public EventModelBuilder metaParameter(String name, String type) { EventPayload payload = new EventPayload(name, type); payload.setMetaParameter(true); eventPayloadDefinitions.put(name, payload); return this; } @Override public EventModelBuilder fullPayload(String name) { eventPayloadDefinitions.put(name, EventPayload.fullPayload(name)); return this; } @Override public EventModel createEventModel() { return buildEventModel(); } @Override public EventDeployment deploy() { if (resourceName == null) { throw new FlowableIllegalArgumentException("A resource name is mandatory"); } EventModel eventModel = buildEventModel(); return eventRepository.createDeployment() .name(deploymentName) .addEventDefinition(resourceName, eventJsonConverter.convertToJson(eventModel))
.category(category) .parentDeploymentId(parentDeploymentId) .tenantId(deploymentTenantId) .deploy(); } protected EventModel buildEventModel() { EventModel eventModel = new EventModel(); if (StringUtils.isNotEmpty(key)) { eventModel.setKey(key); } else { throw new FlowableIllegalArgumentException("An event definition key is mandatory"); } eventModel.setPayload(eventPayloadDefinitions.values()); return eventModel; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\EventModelBuilderImpl.java
1
请完成以下Java代码
public void setValue (final Object value) { if (value instanceof CConnection) { m_value = (CConnection)value; } else { m_value = null; } setDisplay(); } // setValue /** * Return Editor value * @return current value */ @Override public CConnection getValue() { return m_value; } // getValue /** * Return Display Value * @return displayed String value */ @Override public String getDisplay() { if (m_value == null) return ""; return m_value.getDbHost(); } // getDisplay /** * Update Display with Connection info */ public void setDisplay() { m_text.setText(getDisplay()); final boolean isDatabaseOK = m_value != null && m_value.isDatabaseOK(); // Mark the text field as error if both AppsServer and DB connections are not established setBackground(!isDatabaseOK); // Mark the connection indicator button as error if any of AppsServer or DB connection is not established. btnConnection.setBackground(isDatabaseOK ? AdempierePLAF.getFieldBackground_Normal() : AdempierePLAF.getFieldBackground_Error()); } /** * Add Action Listener */ public synchronized void addActionListener(final ActionListener l) { listenerList.add(ActionListener.class, l); } // addActionListener /** * Fire Action Performed */ private void fireActionPerformed() { ActionEvent e = null; ActionListener[] listeners = listenerList.getListeners(ActionListener.class); for (int i = 0; i < listeners.length; i++) { if (e == null) e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "actionPerformed"); listeners[i].actionPerformed(e); } } // fireActionPerformed private void actionEditConnection() { if (!isEnabled() || !m_rw) { return;
} setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { final CConnection connection = getValue(); final CConnectionDialog dialog = new CConnectionDialog(connection); if (dialog.isCancel()) { return; } final CConnection connectionNew = dialog.getConnection(); setValue(connectionNew); DB.setDBTarget(connectionNew); fireActionPerformed(); } finally { setCursor(Cursor.getDefaultCursor()); } } /** * MouseListener */ private class CConnectionEditor_MouseListener extends MouseAdapter { /** Mouse Clicked - Open connection editor */ @Override public void mouseClicked(final MouseEvent e) { if (m_active) return; m_active = true; try { actionEditConnection(); } finally { m_active = false; } } private boolean m_active = false; } } // CConnectionEditor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionEditor.java
1
请完成以下Java代码
public NimbusJwtEncoder build() { return new NimbusJwtEncoder(this.builder.build()); } } /** * A builder for creating {@link NimbusJwtEncoder} instances configured with a * {@link ECPublicKey} and {@link ECPrivateKey}. * <p> * This builder is used to create a {@link NimbusJwtEncoder} * * @since 7.0 */ public static final class EcKeyPairJwtEncoderBuilder { private static final ThrowingBiFunction<ECPublicKey, ECPrivateKey, ECKey.Builder> defaultKid = JWKS::signingWithEc; private final ECKey.Builder builder; private EcKeyPairJwtEncoderBuilder(ECPublicKey publicKey, ECPrivateKey privateKey) { Assert.notNull(publicKey, "publicKey cannot be null"); Assert.notNull(privateKey, "privateKey cannot be null"); Curve curve = Curve.forECParameterSpec(publicKey.getParams()); Assert.notNull(curve, "Unable to determine Curve for EC public key."); this.builder = defaultKid.apply(publicKey, privateKey); }
/** * Post-process the {@link JWK} using the given {@link Consumer}. For example, you * may use this to override the default {@code kid} * @param jwkPostProcessor the post-processor to use * @return this builder instance for method chaining */ public EcKeyPairJwtEncoderBuilder jwkPostProcessor(Consumer<ECKey.Builder> jwkPostProcessor) { Assert.notNull(jwkPostProcessor, "jwkPostProcessor cannot be null"); jwkPostProcessor.accept(this.builder); return this; } /** * Builds the {@link NimbusJwtEncoder} instance. * @return the configured {@link NimbusJwtEncoder} */ public NimbusJwtEncoder build() { return new NimbusJwtEncoder(this.builder.build()); } } }
repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\NimbusJwtEncoder.java
1
请完成以下Java代码
public boolean similar(HiddenMarkovModel model) { if (!similar(start_probability, model.start_probability)) return false; for (int i = 0; i < transition_probability.length; i++) { if (!similar(transition_probability[i], model.transition_probability[i])) return false; if (!similar(emission_probability[i], model.emission_probability[i])) return false; } return true; } protected static boolean similar(float[] A, float[] B) { final float eta = 1e-2f; for (int i = 0; i < A.length; i++) if (Math.abs(A[i] - B[i]) > eta) return false; return true; } protected static Object deepCopy(Object object) { if (object == null) { return null; } try
{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); oos.close(); bos.close(); byte[] byteData = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); return new ObjectInputStream(bais).readObject(); } catch (Exception e) { throw new RuntimeException(e); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HiddenMarkovModel.java
1
请完成以下Java代码
public tr getTopRow() { return m_topRow; } // getTopRow /** * Get Table Data Left (no class set) * @return table data */ public td getTopLeft() { return m_topLeft; } // getTopLeft /** * Get Table Data Right (no class set) * @return table data */ public td getTopRight() { return m_topRight; } // getTopRight /** * String representation * @return String */ @Override public String toString() { return m_html.toString(); } // toString /** * Output Document * @param out out */ public void output (OutputStream out)
{ m_html.output(out); } // output /** * Output Document * @param out out */ public void output (PrintWriter out) { m_html.output(out); } // output /** * Add Popup Center * @param nowrap set nowrap in td * @return null or center single td */ public td addPopupCenter(boolean nowrap) { if (m_table == null) return null; // td center = new td ("popupCenter", AlignType.CENTER, AlignType.MIDDLE, nowrap); center.setColSpan(2); m_table.addElement(new tr() .addElement(center)); return center; } // addPopupCenter } // WDoc
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebDoc.java
1