instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected Map<String, List<Incident>> groupIncidentIdsByExecutionId(CommandContext commandContext) { List<IncidentEntity> incidents = commandContext.getIncidentManager().findIncidentsByProcessInstance(processInstanceId); Map<String, List<Incident>> result = new HashMap<>(); for (IncidentEntity incidentEntity : incidents) { CollectionUtil.addToMapOfLists(result, incidentEntity.getExecutionId(), incidentEntity); } return result; } protected List<String> getIncidentIds(Map<String, List<Incident>> incidents, PvmExecutionImpl execution) { List<String> incidentIds = new ArrayList<>(); List<Incident> incidentList = incidents.get(execution.getId()); if (incidentList != null) { for (Incident incident : incidentList) { incidentIds.add(incident.getId()); } return incidentIds; } else { return Collections.emptyList(); } } protected List<Incident> getIncidents(Map<String, List<Incident>> incidents, PvmExecutionImpl execution) { List<Incident> incidentList = incidents.get(execution.getId()); if (incidentList != null) { return incidentList;
} else { return Collections.emptyList(); } } public static class ExecutionIdComparator implements Comparator<ExecutionEntity> { public static final ExecutionIdComparator INSTANCE = new ExecutionIdComparator(); @Override public int compare(ExecutionEntity o1, ExecutionEntity o2) { return o1.getId().compareTo(o2.getId()); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetActivityInstanceCmd.java
1
请完成以下Java代码
public void setAD_PInstance(final org.compiere.model.I_AD_PInstance AD_PInstance) { set_ValueFromPO(COLUMNNAME_AD_PInstance_ID, org.compiere.model.I_AD_PInstance.class, AD_PInstance); } @Override public void setAD_PInstance_ID (final int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_Value (COLUMNNAME_AD_PInstance_ID, null); else set_Value (COLUMNNAME_AD_PInstance_ID, AD_PInstance_ID); } @Override public int getAD_PInstance_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID); } @Override public void setC_Async_Batch_ID (final int C_Async_Batch_ID) { if (C_Async_Batch_ID < 1) set_Value (COLUMNNAME_C_Async_Batch_ID, null); else set_Value (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID); } @Override public int getC_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID); } @Override public void setChunkUUID (final @Nullable java.lang.String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID);
} @Override public java.lang.String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_Recompute.java
1
请完成以下Java代码
public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getExternalTaskId() { return externalTaskId; } public void setExternalTaskId(String externalTaskId) { this.externalTaskId = externalTaskId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override public String toString() { return this.getClass().getSimpleName() + "[taskId=" + taskId + ", deploymentId=" + deploymentId + ", processDefinitionKey=" + processDefinitionKey + ", jobId=" + jobId
+ ", jobDefinitionId=" + jobDefinitionId + ", batchId=" + batchId + ", operationId=" + operationId + ", operationType=" + operationType + ", userId=" + userId + ", timestamp=" + timestamp + ", property=" + property + ", orgValue=" + orgValue + ", newValue=" + newValue + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", externalTaskId=" + externalTaskId + ", tenantId=" + tenantId + ", entityType=" + entityType + ", category=" + category + ", annotation=" + annotation + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
1
请完成以下Java代码
public EmptiesMovementProducer newEmptiesMovementProducer() { return EmptiesMovementProducer.newInstance(); } @Override public void generateMovementFromEmptiesInout(@NonNull final I_M_InOut emptiesInOut) { // // Fetch shipment/receipt lines and convert them to packing material line candidates. final List<HUPackingMaterialDocumentLineCandidate> lines = Services.get(IInOutDAO.class).retrieveLines(emptiesInOut, I_M_InOutLine.class) .stream() .map(line -> HUPackingMaterialDocumentLineCandidate.of( loadOutOfTrx(line.getM_Locator_ID(), I_M_Locator.class), loadOutOfTrx(line.getM_Product_ID(), I_M_Product.class), line.getMovementQty().intValueExact())) .collect(GuavaCollectors.toImmutableList()); // // Generate the empties movement newEmptiesMovementProducer() .setEmptiesMovementDirection(emptiesInOut.isSOTrx() ? EmptiesMovementDirection.ToEmptiesWarehouse : EmptiesMovementDirection.FromEmptiesWarehouse) .setReferencedInOutId(emptiesInOut.getM_InOut_ID()) .addCandidates(lines) .createMovements(); } @Override public boolean isEmptiesInOut(@NonNull final I_M_InOut inout) { final I_C_DocType docType = loadOutOfTrx(inout.getC_DocType_ID(), I_C_DocType.class); if (docType == null || docType.getC_DocType_ID() <= 0) { return false; } final String docSubType = docType.getDocSubType(); return X_C_DocType.DOCSUBTYPE_Leergutanlieferung.equals(docSubType) || X_C_DocType.DOCSUBTYPE_Leergutausgabe.equals(docSubType); } @Override
public IReturnsInOutProducer newReturnsInOutProducer(final Properties ctx) { return new EmptiesInOutProducer(ctx); } @Override @Nullable public I_M_InOut createDraftEmptiesInOutFromReceiptSchedule(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final String movementType) { // // Create a draft "empties inout" without any line; // Lines will be created manually by the user. return newReturnsInOutProducer(getCtx()) .setMovementType(movementType) .setMovementDate(SystemTime.asDayTimestamp()) .setC_BPartner(receiptScheduleBL.getC_BPartner_Effective(receiptSchedule)) .setC_BPartner_Location(receiptScheduleBL.getC_BPartner_Location_Effective(receiptSchedule)) .setM_Warehouse(receiptScheduleBL.getM_Warehouse_Effective(receiptSchedule)) .setC_Order(receiptSchedule.getC_Order()) // .dontComplete() .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\impl\HUEmptiesService.java
1
请在Spring Boot框架中完成以下Java代码
public class Post { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @Column(name = "title") private String title; @Column(name = "description") private String description; @OneToMany(cascade = CascadeType.ALL) @JoinColumn( name = "pc_fid", referencedColumnName = "id") List<Comment> comments = new ArrayList<>(); public Post() { } public Post(String title, String description) { super(); this.title = title; this.description = description; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<Comment> getComments() { return comments; } public void setComments(List<Comment> comments) { this.comments = comments; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-one-many-mapping\src\main\java\net\alanbinu\springboot\entity\Post.java
2
请完成以下Java代码
public List<IdentityLink> execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId); if (task == null) { throw new FlowableObjectNotFoundException("task not found"); } List<IdentityLink> identityLinks = (List) task.getIdentityLinks(); // assignee is not part of identity links in the db. // so if there is one, we add it here. // @Tom: we discussed this long on skype and you agreed ;-) // an assignee *is* an identityLink, and so must it be reflected in the API // // Note: we cant move this code to the TaskEntity (which would be cleaner), // since the task.delete cascaded to all associated identityLinks // and of course this leads to exception while trying to delete a non-existing identityLink if (task.getAssignee() != null) { IdentityLinkEntity identityLink = processEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService().createIdentityLink(); identityLink.setUserId(task.getAssignee()); identityLink.setType(IdentityLinkType.ASSIGNEE);
identityLink.setTaskId(task.getId()); identityLinks.add(identityLink); } if (task.getOwner() != null) { IdentityLinkEntity identityLink = processEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkService().createIdentityLink(); identityLink.setUserId(task.getOwner()); identityLink.setTaskId(task.getId()); identityLink.setType(IdentityLinkType.OWNER); identityLinks.add(identityLink); } return identityLinks; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetIdentityLinksForTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
public class EmployeeRepositoryImpl implements EmployeeRepository { private List<Employee> employeeList; public EmployeeRepositoryImpl() { employeeList = new ArrayList<Employee>(); employeeList.add(new Employee(1, "Jane")); employeeList.add(new Employee(2, "Jack")); employeeList.add(new Employee(3, "George")); } public List<Employee> getAllEmployees() { return employeeList; } public Employee getEmployee(int id) { for (Employee emp : employeeList) { if (emp.getId() == id) { return emp; } } throw new EmployeeNotFound(); } public void updateEmployee(Employee employee, int id) { for (Employee emp : employeeList) { if (emp.getId() == id) { emp.setId(employee.getId()); emp.setFirstName(employee.getFirstName()); return; } } throw new EmployeeNotFound(); } public void deleteEmployee(int id) {
for (Employee emp : employeeList) { if (emp.getId() == id) { employeeList.remove(emp); return; } } throw new EmployeeNotFound(); } public void addEmployee(Employee employee) { for (Employee emp : employeeList) { if (emp.getId() == employee.getId()) { throw new EmployeeAlreadyExists(); } } employeeList.add(employee); } }
repos\tutorials-master\spring-web-modules\spring-jersey\src\main\java\com\baeldung\server\repository\EmployeeRepositoryImpl.java
2
请完成以下Java代码
public class SignalEventDefinitionParser extends BaseChildElementParser { public String getElementName() { return ELEMENT_EVENT_SIGNALDEFINITION; } public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception { if (!(parentElement instanceof Event)) { return; } SignalEventDefinition eventDefinition = new SignalEventDefinition(); BpmnXMLUtil.addXMLLocation(eventDefinition, xtr); eventDefinition.setSignalRef(xtr.getAttributeValue(null, ATTRIBUTE_SIGNAL_REF)); eventDefinition.setSignalExpression( xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_SIGNAL_EXPRESSION) ); if (
StringUtils.isNotEmpty( xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_ACTIVITY_ASYNCHRONOUS) ) ) { eventDefinition.setAsync( Boolean.parseBoolean( xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_ACTIVITY_ASYNCHRONOUS) ) ); } BpmnXMLUtil.parseChildElements(ELEMENT_EVENT_SIGNALDEFINITION, eventDefinition, xtr, model); ((Event) parentElement).getEventDefinitions().add(eventDefinition); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\child\SignalEventDefinitionParser.java
1
请在Spring Boot框架中完成以下Java代码
public class MD_Stock { private final ITrxManager trxManager = Services.get(ITrxManager.class); private final AvailableForSalesService availableForSalesService; private final AvailableForSalesConfigRepo availableForSalesConfigRepo; private final AvailableForSalesUtil availableForSalesUtil; public MD_Stock( @NonNull final AvailableForSalesService availableForSalesService, @NonNull final AvailableForSalesConfigRepo availableForSalesConfigRepo, @NonNull final AvailableForSalesUtil availableForSalesUtil) { this.availableForSalesService = availableForSalesService; this.availableForSalesConfigRepo = availableForSalesConfigRepo; this.availableForSalesUtil = availableForSalesUtil; } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }) public void triggerSyncAvailableForSales(@NonNull final I_MD_Stock stockRecord) { final AvailableForSalesConfig config = availableForSalesConfigRepo.getConfig( AvailableForSalesConfigRepo.ConfigQuery.builder() .clientId(ClientId.ofRepoId(stockRecord.getAD_Client_ID())) .orgId(OrgId.ofRepoId(stockRecord.getAD_Org_ID())) .build()); if (!config.isFeatureEnabled())
{ return; // nothing to do } final Properties ctx = Env.copyCtx(InterfaceWrapperHelper.getCtx(stockRecord)); final ProductId productId = ProductId.ofRepoId(stockRecord.getM_Product_ID()); final OrgId orgId = OrgId.ofRepoId(stockRecord.getAD_Org_ID()); final AttributesKey attributesKey = AttributesKey.ofString(stockRecord.getAttributesKey()); final WarehouseId warehouseId = WarehouseId.ofRepoId(stockRecord.getM_Warehouse_ID()); final EnqueueAvailableForSalesRequest enqueueAvailableForSalesRequest = availableForSalesUtil .createRequestWithPreparationDateNow(ctx, config, productId, orgId, attributesKey, warehouseId); trxManager.runAfterCommit(() -> availableForSalesService.enqueueAvailableForSalesRequest(enqueueAvailableForSalesRequest)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\stock\interceptor\MD_Stock.java
2
请在Spring Boot框架中完成以下Java代码
RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory, ObjectProvider<RabbitTemplateCustomizer> customizers) { RabbitTemplate template = new RabbitTemplate(); configurer.configure(template, connectionFactory); customizers.orderedStream().forEach((customizer) -> customizer.customize(template)); return template; } @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnBooleanProperty(name = "spring.rabbitmq.dynamic", matchIfMissing = true) @ConditionalOnMissingBean AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) { return new RabbitAdmin(connectionFactory); }
} @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RabbitMessagingTemplate.class) @ConditionalOnMissingBean(RabbitMessagingTemplate.class) @Import(RabbitTemplateConfiguration.class) protected static class RabbitMessagingTemplateConfiguration { @Bean @ConditionalOnSingleCandidate(RabbitTemplate.class) RabbitMessagingTemplate rabbitMessagingTemplate(RabbitTemplate rabbitTemplate) { return new RabbitMessagingTemplate(rabbitTemplate); } } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitAutoConfiguration.java
2
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Konnektor. @param ImpEx_Connector_ID Konnektor */ public void setImpEx_Connector_ID (int ImpEx_Connector_ID) { if (ImpEx_Connector_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, null); else set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, Integer.valueOf(ImpEx_Connector_ID)); } /** Get Konnektor. @return Konnektor */ public int getImpEx_Connector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_Connector_ID); if (ii == null) return 0; return ii.intValue(); } public de.metas.impex.model.I_ImpEx_ConnectorType getImpEx_ConnectorType() throws RuntimeException { return (de.metas.impex.model.I_ImpEx_ConnectorType)MTable.get(getCtx(), de.metas.impex.model.I_ImpEx_ConnectorType.Table_Name) .getPO(getImpEx_ConnectorType_ID(), get_TrxName()); } /** Set Konnektor-Typ. @param ImpEx_ConnectorType_ID Konnektor-Typ */ public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, null);
else set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID)); } /** Get Konnektor-Typ. @return Konnektor-Typ */ public int getImpEx_ConnectorType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_Connector.java
1
请完成以下Java代码
public void setMovementType (java.lang.String MovementType) { set_ValueNoCheck (COLUMNNAME_MovementType, MovementType); } /** Get Bewegungs-Art. @return Method of moving the inventory */ @Override public java.lang.String getMovementType () { return (java.lang.String)get_Value(COLUMNNAME_MovementType); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Bestands-Transaktion. @param M_Transaction_ID Bestands-Transaktion */ @Override public void setM_Transaction_ID (int M_Transaction_ID) { if (M_Transaction_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Transaction_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Transaction_ID, Integer.valueOf(M_Transaction_ID)); } /** Get Bestands-Transaktion. @return Bestands-Transaktion */ @Override public int getM_Transaction_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_M_Transaction_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.eevolution.model.I_PP_Cost_Collector getPP_Cost_Collector() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class); } @Override public void setPP_Cost_Collector(org.eevolution.model.I_PP_Cost_Collector PP_Cost_Collector) { set_ValueFromPO(COLUMNNAME_PP_Cost_Collector_ID, org.eevolution.model.I_PP_Cost_Collector.class, PP_Cost_Collector); } /** Set Manufacturing Cost Collector. @param PP_Cost_Collector_ID Manufacturing Cost Collector */ @Override public void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID) { if (PP_Cost_Collector_ID < 1) set_Value (COLUMNNAME_PP_Cost_Collector_ID, null); else set_Value (COLUMNNAME_PP_Cost_Collector_ID, Integer.valueOf(PP_Cost_Collector_ID)); } /** Get Manufacturing Cost Collector. @return Manufacturing Cost Collector */ @Override public int getPP_Cost_Collector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Cost_Collector_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Transaction.java
1
请完成以下Java代码
public JSONWriter value(boolean b) throws JSONException { return this.append(b ? "true" : "false"); } /** * Append a double value. * * @param d * A double. * @return this * @throws JSONException * If the number is not finite. */ public JSONWriter value(double d) throws JSONException { return this.value(Double.valueOf(d)); } /** * Append a long value. * * @param l * A long. * @return this * @throws JSONException
*/ public JSONWriter value(long l) throws JSONException { return this.append(Long.toString(l)); } /** * Append an object value. * * @param o * The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an object with a toJSONString() method. * @return this * @throws JSONException * If the value is out of sequence. */ public JSONWriter value(Object o) throws JSONException { return this.append(JSONObject.valueToString(o)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONWriter.java
1
请完成以下Java代码
private void turnOnDynamicAllocation(@NonNull final I_M_PickingSlot pickingSlot) { pickingSlot.setIsDynamic(true); pickingSlotRepository.save(pickingSlot); } private void turnOffDynamicAllocation(@NonNull final I_M_PickingSlot pickingSlot) { final PickingSlotId pickingSlotId = PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID()); final boolean released = releasePickingSlot(ReleasePickingSlotRequest.ofPickingSlotId(pickingSlotId)); if (!released) { throw new AdempiereException(SLOT_CANNOT_BE_RELEASED) .markAsUserValidationError(); } pickingSlot.setIsDynamic(false); pickingSlotRepository.save(pickingSlot); } public PickingSlotQueues getNotEmptyQueues(@NonNull final PickingSlotQueueQuery query) { return pickingSlotQueueRepository.getNotEmptyQueues(query); } public PickingSlotQueue getPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotQueueRepository.getPickingSlotQueue(pickingSlotId); } public void removeFromPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIdsToRemove) { huPickingSlotBL.removeFromPickingSlotQueue(pickingSlotId, huIdsToRemove); } public List<PickingSlotReservation> getPickingSlotReservations(@NonNull Set<PickingSlotId> pickingSlotIds) { return pickingSlotRepository.getByIds(pickingSlotIds) .stream() .map(PickingSlotService::extractReservation) .collect(ImmutableList.toImmutableList()); } private static PickingSlotReservation extractReservation(final I_M_PickingSlot pickingSlot) { return PickingSlotReservation.builder()
.pickingSlotId(PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID())) .reservationValue(extractReservationValue(pickingSlot)) .build(); } private static PickingSlotReservationValue extractReservationValue(final I_M_PickingSlot pickingSlot) { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID()); return PickingSlotReservationValue.builder() .bpartnerId(bpartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(bpartnerId, pickingSlot.getC_BPartner_Location_ID())) .build(); } public void addToPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIds) { huPickingSlotBL.addToPickingSlotQueue(pickingSlotId, huIds); } public PickingSlotQueuesSummary getNotEmptyQueuesSummary(@NonNull final PickingSlotQueueQuery query) { return pickingSlotQueueRepository.getNotEmptyQueuesSummary(query); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotService.java
1
请在Spring Boot框架中完成以下Java代码
public static class TableNameAndAlias { public static TableNameAndAlias ofTableNameAndAlias(final String tableName, final String alias) { return new TableNameAndAlias(tableName, alias); } public static TableNameAndAlias ofTableName(final String tableName) { final String synonym = ""; return new TableNameAndAlias(tableName, synonym); } private final String tableName; private final String alias; private TableNameAndAlias(@NonNull final String tableName, final String alias) { this.tableName = tableName; this.alias = alias != null ? alias : ""; } public String getAliasOrTableName() { return !alias.isEmpty() ? alias : tableName; } public boolean isTrlTable() { return tableName.toUpperCase().endsWith("_TRL"); } } @Value public static final class SqlSelect { private final String sql; private final ImmutableList<TableNameAndAlias> tableNameAndAliases; @Builder private SqlSelect( @NonNull final String sql, @NonNull @Singular final ImmutableList<TableNameAndAlias> tableNameAndAliases) { this.sql = sql; this.tableNameAndAliases = tableNameAndAliases; } public boolean hasWhereClause()
{ return sql.indexOf(" WHERE ") >= 0; } public String getFirstTableAliasOrTableName() { if (tableNameAndAliases.isEmpty()) // TODO check if we still need this check! { return ""; } return tableNameAndAliases.get(0).getAliasOrTableName(); } public String getFirstTableNameOrEmpty() { if (tableNameAndAliases.isEmpty()) { return ""; } return tableNameAndAliases.get(0).getTableName(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\ParsedSql.java
2
请完成以下Java代码
public void handleEvent(ProjectRequestEvent event) { String json = null; try { ProjectRequestDocument document = this.documentFactory.createDocument(event); if (logger.isDebugEnabled()) { logger.debug("Publishing " + document); } json = toJson(document); RequestEntity<String> request = RequestEntity.post(this.requestUrl) .contentType(MediaType.APPLICATION_JSON) .body(json); this.retryTemplate.execute((context) -> { this.restTemplate.exchange(request, String.class); return null; }); } catch (Exception ex) { logger.warn(String.format("Failed to publish stat to index, document follows %n%n%s%n", json), ex); } } private String toJson(ProjectRequestDocument stats) { try { return this.objectMapper.writeValueAsString(stats); } catch (JsonProcessingException ex) { throw new IllegalStateException("Cannot convert to JSON", ex); } } private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } // For testing purposes only protected RestTemplate getRestTemplate() { return this.restTemplate; } protected void updateRequestUrl(URI requestUrl) { this.requestUrl = requestUrl; } private static RestTemplateBuilder configureAuthorization(RestTemplateBuilder restTemplateBuilder, Elastic elastic, UriComponentsBuilder uriComponentsBuilder) {
String userInfo = uriComponentsBuilder.build().getUserInfo(); if (StringUtils.hasText(userInfo)) { String[] credentials = userInfo.split(":"); return restTemplateBuilder.basicAuthentication(credentials[0], credentials[1]); } else if (StringUtils.hasText(elastic.getUsername())) { return restTemplateBuilder.basicAuthentication(elastic.getUsername(), elastic.getPassword()); } return restTemplateBuilder; } private static URI determineEntityUrl(Elastic elastic) { String entityUrl = elastic.getUri() + "/" + elastic.getIndexName() + "/_doc/"; try { return new URI(entityUrl); } catch (URISyntaxException ex) { throw new IllegalStateException("Cannot create entity URL: " + entityUrl, ex); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectGenerationStatPublisher.java
1
请完成以下Java代码
public void setDLM_Referenced_Table(final org.compiere.model.I_AD_Table DLM_Referenced_Table) { set_ValueFromPO(COLUMNNAME_DLM_Referenced_Table_ID, org.compiere.model.I_AD_Table.class, DLM_Referenced_Table); } /** * Set Referenzierte Tabelle. * * @param DLM_Referenced_Table_ID Referenzierte Tabelle */ @Override public void setDLM_Referenced_Table_ID(final int DLM_Referenced_Table_ID) { if (DLM_Referenced_Table_ID < 1) { set_Value(COLUMNNAME_DLM_Referenced_Table_ID, null); } else { set_Value(COLUMNNAME_DLM_Referenced_Table_ID, Integer.valueOf(DLM_Referenced_Table_ID)); } } /** * Get Referenzierte Tabelle. * * @return Referenzierte Tabelle */ @Override public int getDLM_Referenced_Table_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referenced_Table_ID); if (ii == null) { return 0; } return ii.intValue(); } @Override public org.compiere.model.I_AD_Column getDLM_Referencing_Column() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DLM_Referencing_Column_ID, org.compiere.model.I_AD_Column.class); } @Override public void setDLM_Referencing_Column(final org.compiere.model.I_AD_Column DLM_Referencing_Column) { set_ValueFromPO(COLUMNNAME_DLM_Referencing_Column_ID, org.compiere.model.I_AD_Column.class, DLM_Referencing_Column); } /** * Set Referenzierende Spalte. * * @param DLM_Referencing_Column_ID Referenzierende Spalte */ @Override public void setDLM_Referencing_Column_ID(final int DLM_Referencing_Column_ID) { if (DLM_Referencing_Column_ID < 1) { set_Value(COLUMNNAME_DLM_Referencing_Column_ID, null); } else { set_Value(COLUMNNAME_DLM_Referencing_Column_ID, Integer.valueOf(DLM_Referencing_Column_ID));
} } /** * Get Referenzierende Spalte. * * @return Referenzierende Spalte */ @Override public int getDLM_Referencing_Column_ID() { final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Column_ID); if (ii == null) { return 0; } return ii.intValue(); } /** * Set Partitionsgrenze. * * @param IsPartitionBoundary * Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition. */ @Override public void setIsPartitionBoundary(final boolean IsPartitionBoundary) { set_Value(COLUMNNAME_IsPartitionBoundary, Boolean.valueOf(IsPartitionBoundary)); } /** * Get Partitionsgrenze. * * @return Falls ja, dann gehören Datensatze, die über die jeweilige Referenz verknüpft sind nicht zur selben Partition. */ @Override public boolean isPartitionBoundary() { final Object oo = get_Value(COLUMNNAME_IsPartitionBoundary); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Reference.java
1
请完成以下Java代码
public ObjectMapper getObjectMapper() { return objectMapper; } public void setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } // helper functions ////////////////////////////////////////// @SuppressWarnings("unchecked") public JsonNode createJsonNode(Object parameter) { if(parameter instanceof SpinJsonNode) { return (JsonNode) ((SpinJsonNode) parameter).unwrap(); } else if(parameter instanceof String) { return createJsonNode((String) parameter); } else if(parameter instanceof Integer) { return createJsonNode((Integer) parameter); } else if(parameter instanceof Boolean) { return createJsonNode((Boolean) parameter); } else if(parameter instanceof Float) { return createJsonNode((Float) parameter); } else if(parameter instanceof Long) { return createJsonNode((Long) parameter); } else if(parameter instanceof Number) { return createJsonNode(((Number) parameter).doubleValue()); } else if(parameter instanceof List) { return createJsonNode((List<Object>) parameter); } else if(parameter instanceof Map) { return createJsonNode((Map<String, Object>) parameter); } else if (parameter == null) { return createNullJsonNode(); } else { throw LOG.unableToCreateNode(parameter.getClass().getSimpleName()); } } public JsonNode createJsonNode(String parameter) { return objectMapper.getNodeFactory().textNode(parameter); } public JsonNode createJsonNode(Integer parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Float parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Double parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Long parameter) {
return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Boolean parameter) { return objectMapper.getNodeFactory().booleanNode(parameter); } public JsonNode createJsonNode(List<Object> parameter) { if (parameter != null) { ArrayNode node = objectMapper.getNodeFactory().arrayNode(); for(Object entry : parameter) { node.add(createJsonNode(entry)); } return node; } else { return createNullJsonNode(); } } public JsonNode createJsonNode(Map<String, Object> parameter) { if (parameter != null) { ObjectNode node = objectMapper.getNodeFactory().objectNode(); for (Map.Entry<String, Object> entry : parameter.entrySet()) { node.set(entry.getKey(), createJsonNode(entry.getValue())); } return node; } else { return createNullJsonNode(); } } public JsonNode createNullJsonNode() { return objectMapper.getNodeFactory().nullNode(); } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormat.java
1
请完成以下Java代码
public class CriterionUtil { public static String generateEntryCriterionId(HasEntryCriteria hasEntryCriteria) { return "entryCriterion_" + hasEntryCriteria.getId() + "_" + (hasEntryCriteria.getEntryCriteria().size() + 1); } public static String generateExitCriterionId(HasExitCriteria hasExitCriteria) { return "exitCriterion_" + hasExitCriteria.getId() + "_" + (hasExitCriteria.getExitCriteria().size() + 1); } public static boolean planItemHasOneEntryCriterionDependingOnPlanItem(PlanItem planItemToCheck, PlanItem planItem, String event) { List<Criterion> entryCriteria = planItemToCheck.getEntryCriteria(); if (!entryCriteria.isEmpty()) { for (Criterion criterion : entryCriteria) { if (criterionHasOnPartDependingOnPlanItem(criterion, planItem, event)) { return true; } } }
return false; } public static boolean criterionHasOnPartDependingOnPlanItem(Criterion criterion, PlanItem planItem, String event) { Sentry sentry = criterion.getSentry(); if (sentry != null) { for (SentryOnPart sentryOnPart : sentry.getOnParts()) { if (sentryOnPart.getSource().getId().equals(planItem.getId()) && sentryOnPart.getStandardEvent().equals(event)) { return true; } } } return false; } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\util\CriterionUtil.java
1
请完成以下Spring Boot application配置
logging.level.org.springframework=INFO logging.level.com.mkyong=INFO logging.level.root=ERROR # logging.pattern.console=%-5level %logger{36} - %msg%n #logging.level.org.springfram
ework.beans.factory=DEBUG # db.init.enabled=true # spring.profiles.active=dev
repos\spring-boot-master\spring-boot-commandlinerunner\src\main\resources\application.properties
2
请完成以下Java代码
public static NoDataFoundHandlers get() { return INSTANCE; } private NoDataFoundHandlers() { } public NoDataFoundHandlers addHandler(final INoDataFoundHandler handler) { noDataFoundHandlers.add(handler); return this; } /** * Invoke all registered handlers on the given parameters. If one of them returns {@code true}, then this method also returns {@code true}. * In any case, all handlers are invoked. * <p> * Hint: the caller of this method might want to throw a {@link NoDataFoundHandlerRetryRequestException} if this method returned {@code true} to it. */ public boolean invokeHandlers(final String tableName, final Object[] ids, final IContextAware ctx) { boolean atLeastOneHandlerFixedIt = false; for (final INoDataFoundHandler currentHandler : noDataFoundHandlers) { final boolean currentHandlerFixedIt = invokeCurrentHandler(currentHandler, tableName, ids, ctx); if (currentHandlerFixedIt && !atLeastOneHandlerFixedIt) { atLeastOneHandlerFixedIt = true; } } return atLeastOneHandlerFixedIt; } /** * Invoke the current handler, unless the current invocation is already happening within an earlier invocation. * So this method might actually <i>not</i> call the given handler in order to avoid a {@link StackOverflowError} . * * @task https://github.com/metasfresh/metasfresh/issues/1076 */ @VisibleForTesting /* package */ boolean invokeCurrentHandler(final INoDataFoundHandler handler, final String tableName, final Object[] ids, final IContextAware ctx) { final ArrayKeyBuilder keyBuilder = ArrayKey.builder().append(tableName);
for (final Object id : ids) { keyBuilder.append(id); } final ArrayKey key = keyBuilder.build(); final Set<ArrayKey> currentlyInvokedOnRecords = currentlyActiveHandlers.get() .computeIfAbsent(handler, h -> new HashSet<>()); if (!currentlyInvokedOnRecords.add(key)) { logger.debug( "The current handler was already invoked with tableName={} and ids={} earlier in this same stack. Returning to avoid a stack overflowError; key={}; handler={}", tableName, ids, key, handler); return false; } try { return handler.invoke(tableName, ids, ctx); } finally { currentlyInvokedOnRecords.remove(key); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\po\NoDataFoundHandlers.java
1
请完成以下Java代码
private void rankResponseHeaders(final I_C_RfQ rfq, final List<I_C_RfQResponse> rfqResponses) { int ranking = 1; // Responses Ordered by Price for (final I_C_RfQResponse rfqResponse : rfqResponses) { final BigDecimal reponsePrice = rfqResponse.getPrice(); if (reponsePrice != null && reponsePrice.signum() > 0) { if (rfqResponse.isSelectedWinner() != (ranking == 1)) { rfqResponse.setIsSelectedWinner(ranking == 1); } rfqResponse.setRanking(ranking); // ranking++; } else { rfqResponse.setRanking(RANK_Invalid); if (rfqResponse.isSelectedWinner()) { rfqResponse.setIsSelectedWinner(false); } } InterfaceWrapperHelper.save(rfqResponse); logger.debug("rankResponse - {}", rfqResponse); } } private final class RfqResponseLineQtyByNetAmtComparator implements Comparator<I_C_RfQResponseLineQty> { public RfqResponseLineQtyByNetAmtComparator() { super(); } @Override public int compare(final I_C_RfQResponseLineQty q1, final I_C_RfQResponseLineQty q2) { if (q1 == null) { throw new IllegalArgumentException("o1 = null"); } if (q2 == null) { throw new IllegalArgumentException("o2 = null"); }
// if (!rfqBL.isValidAmt(q1)) { return -99; } if (!rfqBL.isValidAmt(q2)) { return +99; } final BigDecimal net1 = rfqBL.calculatePriceWithoutDiscount(q1); if (net1 == null) { return -9; } final BigDecimal net2 = rfqBL.calculatePriceWithoutDiscount(q2); if (net2 == null) { return +9; } return net1.compareTo(net2); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\DefaultRfQResponseRankingStrategy.java
1
请完成以下Java代码
public void setTrx(Trx trx) { this.trx = trx; } public ProcessInfo getProcessInfo() { return pi; } public void setProcessInfo(ProcessInfo pi) { this.pi = pi; } public boolean isSelectionActive() { return m_selectionActive; } public void setSelectionActive(boolean active) { m_selectionActive = active; } public ArrayList<Integer> getSelection() { return selection; } public void setSelection(ArrayList<Integer> selection) { this.selection = selection; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getReportEngineType() { return reportEngineType;
} public void setReportEngineType(int reportEngineType) { this.reportEngineType = reportEngineType; } public MPrintFormat getPrintFormat() { return this.printFormat; } public void setPrintFormat(MPrintFormat printFormat) { this.printFormat = printFormat; } public String getAskPrintMsg() { return askPrintMsg; } public void setAskPrintMsg(String askPrintMsg) { this.askPrintMsg = askPrintMsg; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\GenForm.java
1
请完成以下Java代码
public List<InOutAndLineId> retrieveValidLinesToExport(final ImmutableList<InOutId> selectedShipments) { final ImmutableList<InOutId> validShipments = selectedShipments .stream() .filter(this::isValidShipment) .collect(ImmutableList.toImmutableList()); final List<InOutAndLineId> shipmentLinesToExport = new ArrayList<>(); validShipments .stream() .forEach(shipmentId -> shipmentLinesToExport.addAll(retrieveValidLinesToExport(shipmentId))); return shipmentLinesToExport; } private List<InOutAndLineId> retrieveValidLinesToExport(final InOutId shipmentId) { final IInOutDAO inOutDAO = Services.get(IInOutDAO.class); List<InOutAndLineId> shipmentLines = new ArrayList<>(); final ImmutableList<InOutAndLineId> shipmentLinesToExport = inOutDAO.retrieveLinesForInOutId(shipmentId) .stream() .filter(this::isValidLineToExport) .collect(ImmutableList.toImmutableList()); shipmentLines.addAll(shipmentLinesToExport); return shipmentLines; } private boolean isValidLineToExport(final InOutAndLineId inoutAndLineId) { final IInOutDAO inOutDAO = Services.get(IInOutDAO.class); final InOutLineId inOutLineId = inoutAndLineId.getInOutLineId(); final I_M_InOutLine shipmentLineRecord = inOutDAO.getLineByIdOutOfTrx(inOutLineId, I_M_InOutLine.class); if (shipmentLineRecord.isPackagingMaterial()) { return false; }
if (shipmentLineRecord.getC_OrderLine_ID() <= 0) { return false; } return true; } private boolean isValidShipment(final InOutId shipmentId) { final IInOutBL inOutBL = Services.get(IInOutBL.class); final IInOutDAO inOutDAO = Services.get(IInOutDAO.class); final I_M_InOut shipment = inOutDAO.getById(shipmentId); if (!shipment.isSOTrx()) { return false; } if (inOutBL.isReversal(shipment)) { return false; } final DocStatus shipmentDocStatus = DocStatus.ofCode(shipment.getDocStatus()); if (!shipmentDocStatus.isCompletedOrClosed()) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\process\ShipmentLinesForCustomsInvoiceRepo.java
1
请在Spring Boot框架中完成以下Java代码
public String getBearerToken() { return bearerToken; } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. * * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { this.bearerToken = bearerToken; }
@Override public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams) { if (bearerToken == null) { return; } headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); } private static String upperCaseBearer(String scheme) { return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\invoker\auth\HttpBearerAuth.java
2
请完成以下Java代码
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 String getText() { return text; }
public void setText(String text) { this.text = text; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\returnnull\Post.java
1
请在Spring Boot框架中完成以下Java代码
public int getMaxSize() { return this.maxSize; } public void setMaxSize(int maxSize) { this.maxSize = maxSize; } public @Nullable String getValidationQuery() { return this.validationQuery; } public void setValidationQuery(@Nullable String validationQuery) { this.validationQuery = validationQuery; } public ValidationDepth getValidationDepth() { return this.validationDepth;
} public void setValidationDepth(ValidationDepth validationDepth) { this.validationDepth = validationDepth; } public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\R2dbcProperties.java
2
请完成以下Java代码
public static MRegion get (Properties ctx, int C_Region_ID) { if (s_regions == null || s_regions.size() == 0) loadAllRegions(ctx); String key = String.valueOf(C_Region_ID); MRegion r = s_regions.get(key); if (r != null) return r; r = new MRegion (ctx, C_Region_ID, null); if (r.getC_Region_ID() == C_Region_ID) { s_regions.put(key, r); return r; } return null; } // get /** * Get Default Region * @param ctx context * @return Region or null */ public static MRegion getDefault (Properties ctx) { if (s_regions == null || s_regions.size() == 0) loadAllRegions(ctx); return s_default; } // get /** * Return Array of Regions of Country * @param ctx context * @param C_Country_ID country * @return MRegion Array */ public static MRegion[] getRegions (Properties ctx, int C_Country_ID) { if (s_regions == null || s_regions.size() == 0) loadAllRegions(ctx); ArrayList<MRegion> list = new ArrayList<MRegion>(); Iterator<MRegion> it = s_regions.values().iterator(); while (it.hasNext()) { MRegion r = it.next(); if (r.getC_Country_ID() == C_Country_ID) list.add(r); } // Sort it MRegion[] retValue = new MRegion[list.size()]; list.toArray(retValue); Arrays.sort(retValue, new MRegion(ctx, 0, null)); return retValue; } // getRegions /** Region Cache */ private static CCache<String,MRegion> s_regions = null; /** Default Region */ private static MRegion s_default = null; /** Static Logger */ private static Logger s_log = LogManager.getLogger(MRegion.class); /************************************************************************** * Create empty Region * @param ctx context * @param C_Region_ID id * @param trxName transaction */ public MRegion (Properties ctx, int C_Region_ID, String trxName) { super (ctx, C_Region_ID, trxName); if (C_Region_ID == 0) { } } // MRegion
/** * Create Region from current row in ResultSet * @param ctx context * @param rs result set * @param trxName transaction */ public MRegion (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MRegion /** * Parent Constructor * @param country country * @param regionName Region Name */ public MRegion (MCountry country, String regionName) { super (country.getCtx(), 0, country.get_TrxName()); setC_Country_ID(country.getC_Country_ID()); setName(regionName); } // MRegion /** * Return Name * @return Name */ @Override public String toString() { return getName(); } // toString /** * Compare * @param o1 object 1 * @param o2 object 2 * @return -1,0, 1 */ @Override public int compare(Object o1, Object o2) { String s1 = o1.toString(); if (s1 == null) s1 = ""; String s2 = o2.toString(); if (s2 == null) s2 = ""; return s1.compareTo(s2); } // compare } // MRegion
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegion.java
1
请完成以下Java代码
public Long getBalanceBegin() { return balanceBegin; } public void setBalanceBegin(Long balanceBegin) { this.balanceBegin = balanceBegin; } public Long getBalanceEnd() { return balanceEnd; } public void setBalanceEnd(Long balanceEnd) { this.balanceEnd = balanceEnd; } public String getCreateDateBegin() { return createDateBegin; }
public void setCreateDateBegin(String createDateBegin) { this.createDateBegin = createDateBegin; } public String getCreateDateEnd() { return createDateEnd; } public void setCreateDateEnd(String createDateEnd) { this.createDateEnd = createDateEnd; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\param\AccountPageParam.java
1
请完成以下Java代码
public class MIssue extends X_AD_Issue { public MIssue(Properties ctx, int AD_Issue_ID, String trxName) { super(ctx, AD_Issue_ID, trxName); if (is_new()) { setProcessed(false); // N setSystemStatus(SYSTEMSTATUS_Evaluation); try { init(ctx); } catch (Exception e) { System.err.println("Failed initializing AD_Issue: " + e); e.printStackTrace(); } } } public MIssue(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } private void init(final Properties ctx) { AdIssueFactory.prepareNewIssueRecord(ctx, this); } @Override public String toString() { final StringBuilder sb = new StringBuilder("MIssue["); sb.append(get_ID()) .append("-").append(getIssueSummary()) .append(",Record=").append(getRecord_ID()) .append("]"); return sb.toString(); }
@Override public void setIssueSummary(String IssueSummary) { final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_IssueSummary); super.setIssueSummary(truncateExceptionsRelatedString(IssueSummary, maxLength)); } @Override public void setStackTrace(String StackTrace) { final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_StackTrace); super.setStackTrace(truncateExceptionsRelatedString(StackTrace, maxLength)); } @Override public void setErrorTrace(String ErrorTrace) { final int maxLength = getPOInfo().getFieldLength(COLUMNNAME_ErrorTrace); super.setErrorTrace(truncateExceptionsRelatedString(ErrorTrace, maxLength)); } private static String truncateExceptionsRelatedString(final String string, final int maxLength) { if (string == null || string.isEmpty()) { return string; } String stringNorm = string; stringNorm = stringNorm.replace("java.lang.", ""); stringNorm = stringNorm.replace("java.sql.", ""); // Truncate the string if necessary if (maxLength > 0 && stringNorm.length() > maxLength) { stringNorm = stringNorm.substring(0, maxLength - 1); } return stringNorm; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MIssue.java
1
请在Spring Boot框架中完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Bean public ViewResolver htmlViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); resolver.setContentType("text/html"); resolver.setCharacterEncoding("UTF-8"); resolver.setViewNames(ArrayUtil.array("*.html")); return resolver; } private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); engine.addDialect(new LayoutDialect(new GroupingStrategy())); engine.addDialect(new Java8TimeDialect()); engine.setTemplateResolver(templateResolver); engine.setTemplateEngineMessageSource(messageSource()); return engine; } private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang"); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf-5\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请完成以下Java代码
public class EscalationEventDefinitionFinder implements TreeVisitor<PvmScope> { protected EscalationEventDefinition escalationEventDefinition; protected final String escalationCode; protected final PvmActivity throwEscalationActivity; public EscalationEventDefinitionFinder(String escalationCode, PvmActivity throwEscalationActivity) { this.escalationCode = escalationCode; this.throwEscalationActivity = throwEscalationActivity; } @Override public void visit(PvmScope scope) { List<EscalationEventDefinition> escalationEventDefinitions = scope.getProperties().get(BpmnProperties.ESCALATION_EVENT_DEFINITIONS); this.escalationEventDefinition = findMatchingEscalationEventDefinition(escalationEventDefinitions); } protected EscalationEventDefinition findMatchingEscalationEventDefinition(List<EscalationEventDefinition> escalationEventDefinitions) { for (EscalationEventDefinition escalationEventDefinition : escalationEventDefinitions) { if (isMatchingEscalationCode(escalationEventDefinition) && !isReThrowingEscalationEventSubprocess(escalationEventDefinition)) { return escalationEventDefinition; } } return null; }
protected boolean isMatchingEscalationCode(EscalationEventDefinition escalationEventDefinition) { String escalationCode = escalationEventDefinition.getEscalationCode(); return escalationCode == null || escalationCode.equals(this.escalationCode); } protected boolean isReThrowingEscalationEventSubprocess(EscalationEventDefinition escalationEventDefinition) { PvmActivity escalationHandler = escalationEventDefinition.getEscalationHandler(); return escalationHandler.isSubProcessScope() && escalationHandler.equals(throwEscalationActivity.getFlowScope()); } public EscalationEventDefinition getEscalationEventDefinition() { return escalationEventDefinition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\EscalationEventDefinitionFinder.java
1
请完成以下Java代码
public Criteria andProductAttrNotIn(List<String> values) { addCriterion("product_attr not in", values, "productAttr"); return (Criteria) this; } public Criteria andProductAttrBetween(String value1, String value2) { addCriterion("product_attr between", value1, value2, "productAttr"); return (Criteria) this; } public Criteria andProductAttrNotBetween(String value1, String value2) { addCriterion("product_attr not between", value1, value2, "productAttr"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null;
this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCartItemExample.java
1
请完成以下Java代码
public void on(ProductCountIncrementedEvent event) { this.count++; } @EventSourcingHandler public void on(ProductCountDecrementedEvent event) { this.count--; } @EventSourcingHandler public void on(OrderConfirmedEvent event) { this.orderConfirmed = true; } @Override public boolean equals(Object o) {
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderLine orderLine = (OrderLine) o; return Objects.equals(productId, orderLine.productId) && Objects.equals(count, orderLine.count); } @Override public int hashCode() { return Objects.hash(productId, count); } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\commandmodel\order\OrderLine.java
1
请在Spring Boot框架中完成以下Java代码
public void setIncludeStacktrace(IncludeAttribute includeStacktrace) { this.includeStacktrace = includeStacktrace; } public IncludeAttribute getIncludeMessage() { return this.includeMessage; } public void setIncludeMessage(IncludeAttribute includeMessage) { this.includeMessage = includeMessage; } public IncludeAttribute getIncludeBindingErrors() { return this.includeBindingErrors; } public void setIncludeBindingErrors(IncludeAttribute includeBindingErrors) { this.includeBindingErrors = includeBindingErrors; } public IncludeAttribute getIncludePath() { return this.includePath; } public void setIncludePath(IncludeAttribute includePath) { this.includePath = includePath; } public Whitelabel getWhitelabel() { return this.whitelabel; } /** * Include error attributes options. */ public enum IncludeAttribute { /** * Never add error attribute. */ NEVER, /** * Always add error attribute. */ ALWAYS, /**
* Add error attribute when the appropriate request parameter is not "false". */ ON_PARAM } public static class Whitelabel { /** * Whether to enable the default error page displayed in browsers in case of a * server error. */ private boolean enabled = true; public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\ErrorProperties.java
2
请完成以下Java代码
private void closeResources(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement) { try { resultSet.close(); preparedStatement.close(); connection.close(); logger.info("Resources closed"); } catch (SQLException e) { throw new RuntimeException(e); } } public Stream<CityRecord> getCitiesStreamUsingJOOQ(Connection connection) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(QUERY); connection.setAutoCommit(false); preparedStatement.setFetchSize(5000); ResultSet resultSet = preparedStatement.executeQuery(); return DSL.using(connection) .fetchStream(resultSet) .map(r -> new CityRecord(r.get("NAME", String.class), r.get("COUNTRY", String.class))) .onClose(() -> closeResources(connection, resultSet, preparedStatement)); } public Stream<CityRecord> getCitiesStreamUsingJdbcStream(Connection connection) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(QUERY); connection.setAutoCommit(false);
preparedStatement.setFetchSize(5000); ResultSet resultSet = preparedStatement.executeQuery(); return JdbcStream.stream(resultSet) .map(r -> { try { return createCityRecord(resultSet); } catch (SQLException e) { throw new RuntimeException(e); } }) .onClose(() -> closeResources(connection, resultSet, preparedStatement)); } private CityRecord createCityRecord(ResultSet resultSet) throws SQLException { return new CityRecord(resultSet.getString(1), resultSet.getString(2)); } }
repos\tutorials-master\persistence-modules\core-java-persistence-3\src\main\java\com\baeldung\resultset\streams\JDBCStreamAPIRepository.java
1
请完成以下Java代码
public int getDHL_ShipmentOrderRequest_ID() { return get_ValueAsInt(COLUMNNAME_DHL_ShipmentOrderRequest_ID); } @Override public void setDurationMillis (final int DurationMillis) { set_Value (COLUMNNAME_DurationMillis, DurationMillis); } @Override public int getDurationMillis() { return get_ValueAsInt(COLUMNNAME_DurationMillis); } @Override public void setIsError (final boolean IsError) { set_Value (COLUMNNAME_IsError, IsError); } @Override public boolean isError() { return get_ValueAsBoolean(COLUMNNAME_IsError); } @Override public void setRequestMessage (final @Nullable java.lang.String RequestMessage)
{ set_Value (COLUMNNAME_RequestMessage, RequestMessage); } @Override public java.lang.String getRequestMessage() { return get_ValueAsString(COLUMNNAME_RequestMessage); } @Override public void setResponseMessage (final @Nullable java.lang.String ResponseMessage) { set_Value (COLUMNNAME_ResponseMessage, ResponseMessage); } @Override public java.lang.String getResponseMessage() { return get_ValueAsString(COLUMNNAME_ResponseMessage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_Dhl_ShipmentOrder_Log.java
1
请完成以下Java代码
public static void sendMessageToAll(String message) { for (VxeSocket socketItem : socketPool.values()) { socketItem.sendMessage(message); } } /** * websocket 开启连接 */ @OnOpen public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("pageId") String pageId) { try { this.userId = userId; this.pageId = pageId; this.socketId = userId + pageId; this.session = session; socketPool.put(this.socketId, this); getUserPool(userId).put(this.pageId, this); log.info("【vxeSocket】有新的连接,总数为:" + socketPool.size()); } catch (Exception ignored) { } } /** * websocket 断开连接 */ @OnClose public void onClose() { try { socketPool.remove(this.socketId); getUserPool(this.userId).remove(this.pageId); log.info("【vxeSocket】连接断开,总数为:" + socketPool.size()); } catch (Exception ignored) { } } /** * websocket 收到消息 */ @OnMessage public void onMessage(String message) { // log.info("【vxeSocket】onMessage:" + message); JSONObject json;
try { json = JSON.parseObject(message); } catch (Exception e) { log.warn("【vxeSocket】收到不合法的消息:" + message); return; } String type = json.getString(VxeSocketConst.TYPE); switch (type) { // 心跳检测 case VxeSocketConst.TYPE_HB: this.sendMessage(VxeSocket.packageMessage(type, true)); break; // 更新form数据 case VxeSocketConst.TYPE_UVT: this.handleUpdateForm(json); break; default: log.warn("【vxeSocket】收到不识别的消息类型:" + type); break; } } /** * 处理 UpdateForm 事件 */ private void handleUpdateForm(JSONObject json) { // 将事件转发给所有人 JSONObject data = json.getJSONObject(VxeSocketConst.DATA); VxeSocket.sendMessageToAll(VxeSocket.packageMessage(VxeSocketConst.TYPE_UVT, data)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-module-demo\src\main\java\org\jeecg\modules\demo\mock\vxe\websocket\VxeSocket.java
1
请完成以下Java代码
private void sendUserNotifications( final I_C_Queue_WorkPackage notifiableWP, final SeenPrintPackages seenPrintPackages, final I_C_Async_Batch asyncBatch) { if (seenPrintPackages.isEmpty()) { return; } final INotificationBL notificationBL = Services.get(INotificationBL.class); final IArchiveBL archiveBL = Services.get(IArchiveBL.class); // create notes for print packages final int countExpected = asyncBatch.getCountExpected(); for (final int printPackageId : seenPrintPackages.getPrintPackageIds()) { final TableRecordReference printPackageRef = TableRecordReference.of(I_C_Print_Package.Table_Name, printPackageId); final I_AD_Archive lastArchive = archiveBL.getLastArchiveRecord(printPackageRef).orElse(null); if(lastArchive == null) { continue; } final I_C_Printing_Queue printingQueueItem = dao.retrievePrintingQueue(lastArchive); if (printingQueueItem == null) { continue; } final TableRecordReference printingQueueItemRef = TableRecordReference.of(printingQueueItem); final I_C_Queue_WorkPackage_Notified workpackageNotified = asyncBatchDAO.fetchWorkPackagesNotified(notifiableWP); Check.assumeNotNull(workpackageNotified, "Workpackage notified record is null!"); notificationBL.send(UserNotificationRequest.builder() .topic(Printing_Constants.USER_NOTIFICATIONS_TOPIC) .recipientUserId(UserId.ofRepoId(notifiableWP.getCreatedBy())) .contentADMessage(MSG_Event_PDFGenerated) .contentADMessageParam(notifiableWP.getBatchEnqueuedCount()) .contentADMessageParam(countExpected) .contentADMessageParam(seenPrintPackages.getCounter(printPackageId)) .contentADMessageParam(printingQueueItemRef) .targetAction(TargetRecordAction.ofRecordAndWindow(printingQueueItemRef, WINDOW_ID_PrintingQueue)) .build()); asyncBatchBL.markWorkpackageNotified(workpackageNotified);
// set printing queue to processed printingQueueItem.setProcessed(true); InterfaceWrapperHelper.save(printingQueueItem); } } @lombok.ToString private static class SeenPrintPackages { private final Map<Integer, Integer> countersByPrintPackageId = new HashMap<>(); public boolean isEmpty() { return countersByPrintPackageId.isEmpty(); } public Set<Integer> getPrintPackageIds() { return countersByPrintPackageId.keySet(); } public int getCounter(final int printPackageId) { return countersByPrintPackageId.getOrDefault(printPackageId, 0); } public void incrementCounterForPrintPackageId(final int printPackageId) { final int counter = countersByPrintPackageId.getOrDefault(printPackageId, 0); countersByPrintPackageId.put(printPackageId, counter + 1); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\async\spi\impl\PDFPrintingAsyncBatchListener.java
1
请在Spring Boot框架中完成以下Java代码
public at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType getShipperExtension() { return shipperExtension; } /** * Sets the value of the shipperExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType } * */ public void setShipperExtension(at.erpel.schemas._1p0.documents.extensions.edifact.ShipperExtensionType value) { this.shipperExtension = value; } /** * Gets the value of the erpelShipperExtension property. * * @return * possible object is * {@link CustomType } * */ public CustomType getErpelShipperExtension() {
return erpelShipperExtension; } /** * Sets the value of the erpelShipperExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelShipperExtension(CustomType value) { this.erpelShipperExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\ShipperExtensionType.java
2
请完成以下Java代码
public VariableSerializers removeSerializer(TypedValueSerializer<?> serializer) { serializerList.remove(serializer); serializerMap.remove(serializer.getName()); return this; } public VariableSerializers join(VariableSerializers other) { DefaultVariableSerializers copy = new DefaultVariableSerializers(); // "other" serializers override existing ones if their names match for (TypedValueSerializer<?> thisSerializer : serializerList) { TypedValueSerializer<?> serializer = other.getSerializerByName(thisSerializer.getName()); if (serializer == null) { serializer = thisSerializer; } copy.addSerializer(serializer);
} // add all "other" serializers that did not exist before to the end of the list for (TypedValueSerializer<?> otherSerializer : other.getSerializers()) { if (!copy.serializerMap.containsKey(otherSerializer.getName())) { copy.addSerializer(otherSerializer); } } return copy; } public List<TypedValueSerializer<?>> getSerializers() { return new ArrayList<TypedValueSerializer<?>>(serializerList); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\DefaultVariableSerializers.java
1
请在Spring Boot框架中完成以下Java代码
private ExecuteShellUtil getExecuteShellUtil(String ip) { ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip); if (serverDeployDTO == null) { sendMsg("IP对应服务器信息不存在:" + ip, MsgType.ERROR); throw new BadRequestException("IP对应服务器信息不存在:" + ip); } return new ExecuteShellUtil(ip, serverDeployDTO.getAccount(), serverDeployDTO.getPassword(),serverDeployDTO.getPort()); } private ScpClientUtil getScpClientUtil(String ip) { ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip); if (serverDeployDTO == null) { sendMsg("IP对应服务器信息不存在:" + ip, MsgType.ERROR); throw new BadRequestException("IP对应服务器信息不存在:" + ip); } return ScpClientUtil.getInstance(ip, serverDeployDTO.getPort(), serverDeployDTO.getAccount(), serverDeployDTO.getPassword()); } private void sendResultMsg(boolean result, StringBuilder sb) { if (result) { sb.append("<br>启动成功!");
sendMsg(sb.toString(), MsgType.INFO); } else { sb.append("<br>启动失败!"); sendMsg(sb.toString(), MsgType.ERROR); } } @Override public void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (DeployDto deployDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("应用名称", deployDto.getApp().getName()); map.put("服务器", deployDto.getServers()); map.put("部署日期", deployDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DeployServiceImpl.java
2
请完成以下Java代码
public class MustacheView extends AbstractTemplateView { private @Nullable Compiler compiler; private @Nullable String charset; /** * Set the Mustache compiler to be used by this view. * <p> * Typically this property is not set directly. Instead a single {@link Compiler} is * expected in the Spring application context which is used to compile Mustache * templates. * @param compiler the Mustache compiler */ public void setCompiler(Compiler compiler) { this.compiler = compiler; } /** * Set the charset used for reading Mustache template files. * @param charset the charset to use for reading template files */ public void setCharset(@Nullable String charset) { this.charset = charset; } @Override public boolean checkResource(Locale locale) throws Exception { Resource resource = getResource(); return resource != null; } @Override protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { Resource resource = getResource(); Assert.state(resource != null, "'resource' must not be null"); Template template = createTemplate(resource); if (template != null) { template.execute(model, response.getWriter()); } }
private @Nullable Resource getResource() { ApplicationContext applicationContext = getApplicationContext(); String url = getUrl(); if (applicationContext == null || url == null) { return null; } Resource resource = applicationContext.getResource(url); return (resource.exists()) ? resource : null; } private Template createTemplate(Resource resource) throws IOException { try (Reader reader = getReader(resource)) { Assert.state(this.compiler != null, "'compiler' must not be null"); return this.compiler.compile(reader); } } private Reader getReader(Resource resource) throws IOException { if (this.charset != null) { return new InputStreamReader(resource.getInputStream(), this.charset); } return new InputStreamReader(resource.getInputStream()); } }
repos\spring-boot-4.0.1\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\servlet\view\MustacheView.java
1
请完成以下Java代码
public void setLastname (java.lang.String Lastname) { set_Value (COLUMNNAME_Lastname, Lastname); } /** Get Nachname. @return Nachname */ @Override public java.lang.String getLastname () { return (java.lang.String)get_Value(COLUMNNAME_Lastname); } /** Set Login. @param Login Used for login. See Help. */ @Override public void setLogin (java.lang.String Login) { set_Value (COLUMNNAME_Login, Login); } /** Get Login. @return Used for login. See Help. */ @Override public java.lang.String getLogin () { return (java.lang.String)get_Value(COLUMNNAME_Login); } /** Set Handynummer. @param MobilePhone Handynummer */ @Override public void setMobilePhone (java.lang.String MobilePhone) { set_Value (COLUMNNAME_MobilePhone, MobilePhone); } /** Get Handynummer. @return Handynummer */ @Override public java.lang.String getMobilePhone () { return (java.lang.String)get_Value(COLUMNNAME_MobilePhone); } /** Set Telefon. @param Phone Beschreibt eine Telefon Nummer */ @Override public void setPhone (java.lang.String Phone) { set_Value (COLUMNNAME_Phone, Phone); } /** Get Telefon. @return Beschreibt eine Telefon Nummer */ @Override public java.lang.String getPhone () { return (java.lang.String)get_Value(COLUMNNAME_Phone); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override
public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Role name. @param RoleName Role name */ @Override public void setRoleName (java.lang.String RoleName) { set_Value (COLUMNNAME_RoleName, RoleName); } /** Get Role name. @return Role name */ @Override public java.lang.String getRoleName () { return (java.lang.String)get_Value(COLUMNNAME_RoleName); } /** Set UserValue. @param UserValue UserValue */ @Override public void setUserValue (java.lang.String UserValue) { set_Value (COLUMNNAME_UserValue, UserValue); } /** Get UserValue. @return UserValue */ @Override public java.lang.String getUserValue () { return (java.lang.String)get_Value(COLUMNNAME_UserValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_User.java
1
请完成以下Java代码
public abstract class AbstractDataSourcePoolMetadata<T extends DataSource> implements DataSourcePoolMetadata { private final T dataSource; /** * Create an instance with the data source to use. * @param dataSource the data source */ protected AbstractDataSourcePoolMetadata(T dataSource) { this.dataSource = dataSource; } @Override public @Nullable Float getUsage() { Integer maxSize = getMax(); Integer currentSize = getActive(); if (maxSize == null || currentSize == null) {
return null; } if (maxSize < 0) { return -1f; } if (currentSize == 0) { return 0f; } return (float) currentSize / (float) maxSize; } protected final T getDataSource() { return this.dataSource; } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\AbstractDataSourcePoolMetadata.java
1
请在Spring Boot框架中完成以下Java代码
public class BookRepository { private List<Book> items; @PostConstruct public void init() { Faker faker = new Faker(Locale.ENGLISH); final com.github.javafaker.Book book = faker.book(); this.items = IntStream.range(1, faker.random() .nextInt(10, 20)) .mapToObj(i -> new Book(i, book.title(), book.author(), book.genre())) .collect(Collectors.toList()); } public int getCount() { return items.size(); } public List<Book> getItems() { return items;
} public Optional<Book> getById(int id) { return this.items.stream() .filter(item -> id == item.getId()) .findFirst(); } public void save(int id, Book book) { IntStream.range(0, items.size()) .filter(i -> items.get(i) .getId() == id) .findFirst() .ifPresent(i -> this.items.set(i, book)); } }
repos\tutorials-master\spring-web-modules\spring-5-mvc\src\main\java\com\baeldung\idc\BookRepository.java
2
请完成以下Java代码
private Optional<InvoiceId> retrieveInvoice(final IdentifierString invoiceIdentifier, final OrgId orgId, final DocBaseAndSubType docType) { final InvoiceQuery invoiceQuery = createInvoiceQuery(invoiceIdentifier, orgId, docType); return invoiceDAO.retrieveIdByInvoiceQuery(invoiceQuery); } private InvoiceQuery createInvoiceQuery( @NonNull final IdentifierString identifierString, @NonNull final OrgId orgId, @Nullable final DocBaseAndSubType docType) { final InvoiceQuery.InvoiceQueryBuilder invoiceQueryBuilder = InvoiceQuery.builder() .orgId(orgId) .docType(docType); switch (identifierString.getType()) { case METASFRESH_ID: invoiceQueryBuilder.invoiceId(identifierString.asMetasfreshId().getValue());
break; case EXTERNAL_ID: invoiceQueryBuilder.externalId(identifierString.asExternalId()); break; case DOC: invoiceQueryBuilder.documentNo(identifierString.asDoc()); break; default: throw new AdempiereException("Invalid identifierString: " + identifierString); } return invoiceQueryBuilder.build(); } private Optional<I_AD_Archive> getLastArchive(@NonNull final InvoiceId invoiceId) { return archiveBL.getLastArchiveRecord(TableRecordReference.of(I_C_Invoice.Table_Name, invoiceId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\invoice\impl\JsonInvoiceService.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<TimeBooking> getByIdOptional(@NonNull final TimeBookingId timeBookingId) { return queryBL .createQueryBuilder(I_S_TimeBooking.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_TimeBooking.COLUMNNAME_S_TimeBooking_ID, timeBookingId.getRepoId()) .create() .firstOnlyOptional(I_S_TimeBooking.class) .map(this::buildTimeBooking); } public ImmutableList<TimeBooking> getAllByIssueId(@NonNull final IssueId issueId) { return queryBL .createQueryBuilder(I_S_TimeBooking.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_TimeBooking.COLUMNNAME_S_Issue_ID, issueId.getRepoId()) .create() .list() .stream()
.map(this::buildTimeBooking) .collect(ImmutableList.toImmutableList()); } private TimeBooking buildTimeBooking(@NonNull final I_S_TimeBooking record) { return TimeBooking.builder() .timeBookingId(TimeBookingId.ofRepoId(record.getS_TimeBooking_ID())) .issueId(IssueId.ofRepoId(record.getS_Issue_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .performingUserId(UserId.ofRepoId(record.getAD_User_Performing_ID())) .bookedDate(record.getBookedDate().toInstant()) .bookedSeconds(record.getBookedSeconds().longValue()) .hoursAndMins(record.getHoursAndMinutes()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\TimeBookingRepository.java
2
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "5") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/5") public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(example = "6") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "10") public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } @ApiModelProperty(example = "6") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-task-instances/6") public String getTaskUrl() { return taskUrl; }
public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @ApiModelProperty(example = "variableUpdate") public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } @ApiModelProperty(example = "2") public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } public RestVariable getVariable() { return variable; } public void setVariable(RestVariable variable) { this.variable = variable; } @ApiModelProperty(example = "null") public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } @ApiModelProperty(example = "null") public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java
2
请完成以下Java代码
public static ExecutionEntity getCompensatingExecution(EventSubscriptionEntity eventSubscription) { String configuration = eventSubscription.getConfiguration(); if (configuration != null) { return Context.getCommandContext().getExecutionManager().findExecutionById(configuration); } else { return null; } } private static String getSubscriptionActivityId(ActivityExecution execution, String activityRef) { ActivityImpl activityToCompensate = ((ExecutionEntity) execution).getProcessDefinition().findActivity(activityRef); if (activityToCompensate.isMultiInstance()) {
ActivityImpl flowScope = (ActivityImpl) activityToCompensate.getFlowScope(); return flowScope.getActivityId(); } else { ActivityImpl compensationHandler = activityToCompensate.findCompensationHandler(); if (compensationHandler != null) { return compensationHandler.getActivityId(); } else { // if activityRef = subprocess and subprocess has no compensation handler return activityRef; } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\CompensationUtil.java
1
请完成以下Java代码
public Builder setDescription(final ITranslatableString description) { this.description = description; return this; } public Builder notFoundMessages(@Nullable NotFoundMessages notFoundMessages) { this.notFoundMessages = notFoundMessages; return this; } public Builder addSection(@NonNull final DocumentLayoutSectionDescriptor.Builder sectionBuilderToAdd) { sectionBuilders.add(sectionBuilderToAdd); return this;
} public Builder addSections(@NonNull final Collection<DocumentLayoutSectionDescriptor.Builder> sectionBuildersToAdd) { sectionBuilders.addAll(sectionBuildersToAdd); return this; } public boolean isEmpty() { return sectionBuilders.isEmpty(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSingleRow.java
1
请完成以下Java代码
public PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId) {return configService.getPickingJobOptions(customerId);} @NonNull public List<HuId> getClosedLUs( @NonNull final PickingJob pickingJob, @Nullable final PickingJobLineId lineId) { final Set<HuId> pickedHuIds = pickingJob.getPickedHuIds(lineId); if (pickedHuIds.isEmpty()) { return ImmutableList.of(); } final HuId currentlyOpenedLUId = pickingJob.getLuPickingTarget(lineId) .map(LUPickingTarget::getLuId) .orElse(null); return handlingUnitsBL.getTopLevelHUs(IHandlingUnitsBL.TopLevelHusQuery.builder() .hus(handlingUnitsBL.getByIds(pickedHuIds)) .build()) .stream() .filter(handlingUnitsBL::isLoadingUnit) .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId)
.filter(huId -> !HuId.equals(huId, currentlyOpenedLUId)) .collect(ImmutableList.toImmutableList()); } public PickingSlotSuggestions getPickingSlotsSuggestions(@NonNull final PickingJob pickingJob) { return pickingJobService.getPickingSlotsSuggestions(pickingJob); } public PickingJob pickAll(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return pickingJobService.pickAll(pickingJobId, callerId); } public PickingJobQtyAvailable getQtyAvailable(@NonNull final PickingJobId pickingJobId, final @NonNull UserId callerId) { return pickingJobService.getQtyAvailable(pickingJobId, callerId); } public GetNextEligibleLineToPackResponse getNextEligibleLineToPack(final @NonNull GetNextEligibleLineToPackRequest request) { return pickingJobService.getNextEligibleLineToPack(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\PickingJobRestService.java
1
请在Spring Boot框架中完成以下Java代码
public class DefaultDocumentDescriptorFactory implements DocumentDescriptorFactory { @NonNull private final DataEntrySubTabBindingDescriptorBuilder dataEntrySubTabBindingDescriptorBuilder; @NonNull private final LayoutFactoryProvider layoutFactoryProvider; private final CCache<WindowId, DocumentDescriptor> documentDescriptorsByWindowId = new CCache<>(I_AD_Window.Table_Name + "#DocumentDescriptor", 50); private final CopyOnWriteArraySet<WindowId> unsupportedWindowIds = new CopyOnWriteArraySet<>(); @Override public void invalidateForWindow(@NonNull final WindowId windowId) { documentDescriptorsByWindowId.remove(windowId); } @Override public DocumentDescriptor getDocumentDescriptor(@NonNull final WindowId windowId) { try { return documentDescriptorsByWindowId.getOrLoad(windowId, this::loadDocumentDescriptor); } catch (final Exception e) { throw DocumentLayoutBuildException.wrapIfNeeded(e); } } private DocumentDescriptor loadDocumentDescriptor(final WindowId windowId) { return newLoader(windowId).load();
} private DefaultDocumentDescriptorLoader newLoader(@NonNull final WindowId windowId) { return DefaultDocumentDescriptorLoader.builder() .layoutFactoryProvider(layoutFactoryProvider) .dataEntrySubTabBindingDescriptorBuilder(dataEntrySubTabBindingDescriptorBuilder) .adWindowId(windowId.toAdWindowId()) .build(); } /** * @return {@code false} if the given {@code windowId} * <br> * is {@code null} <br> * or its {@link WindowId#isInt()} returns {@code false} * or it was declared unsupported via {@link #addUnsupportedWindowId(WindowId)}. */ @Override public boolean isWindowIdSupported(@Nullable final WindowId windowId) { return windowId != null && windowId.isInt() && !unsupportedWindowIds.contains(windowId); } /** * Tell this instance that it shall not attempt to work with the given window ID. */ public void addUnsupportedWindowId(@NonNull final WindowId windowId) { unsupportedWindowIds.add(windowId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\DefaultDocumentDescriptorFactory.java
2
请完成以下Java代码
public class SetAnnotationForIncidentCmd implements Command<Void> { protected String incidentId; protected String annotation; public SetAnnotationForIncidentCmd(String incidentId, String annotation) { this.incidentId = incidentId; this.annotation = annotation; } @Override public Void execute(CommandContext commandContext) { EnsureUtil.ensureNotNull(NotValidException.class, "incident id", incidentId); IncidentEntity incident = (IncidentEntity) commandContext.getIncidentManager().findIncidentById(incidentId); EnsureUtil.ensureNotNull(BadUserRequestException.class, "incident", incident); ExecutionEntity execution = null; if (incident.getExecutionId() != null) { execution = commandContext.getExecutionManager().findExecutionById(incident.getExecutionId()); if (execution != null) { // check rights for updating an execution-related incident for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateProcessInstance(execution); } } } incident.setAnnotation(annotation); triggerHistoryEvent(commandContext, incident); String tenantId = execution != null ? execution.getTenantId() : null; if (annotation == null) { commandContext.getOperationLogManager() .logClearIncidentAnnotationOperation(incidentId, tenantId); } else { commandContext.getOperationLogManager() .logSetIncidentAnnotationOperation(incidentId, tenantId); }
return null; } protected void triggerHistoryEvent(CommandContext commandContext, IncidentEntity incident) { HistoryLevel historyLevel = commandContext.getProcessEngineConfiguration().getHistoryLevel(); if (historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_UPDATE, incident)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { HistoricIncidentEventEntity incidentUpdateEvt = (HistoricIncidentEventEntity) producer.createHistoricIncidentUpdateEvt(incident); incidentUpdateEvt.setAnnotation(annotation); return incidentUpdateEvt; } }); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetAnnotationForIncidentCmd.java
1
请完成以下Java代码
public String getProductChanges(@PathVariable int productId) { Product product = storeService.findProductById(productId); QueryBuilder jqlQuery = QueryBuilder.byInstance(product); Changes changes = javers.findChanges(jqlQuery.build()); return javers.getJsonConverter().toJson(changes); } @GetMapping("/products/snapshots") public String getProductSnapshots() { QueryBuilder jqlQuery = QueryBuilder.byClass(Product.class); List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build()); return javers.getJsonConverter().toJson(snapshots); } @GetMapping("/stores/{storeId}/shadows")
public String getStoreShadows(@PathVariable int storeId) { Store store = storeService.findStoreById(storeId); JqlQuery jqlQuery = QueryBuilder.byInstance(store) .withChildValueObjects().build(); List<Shadow<Store>> shadows = javers.findShadows(jqlQuery); return javers.getJsonConverter().toJson(shadows.get(0)); } @GetMapping("/stores/snapshots") public String getStoresSnapshots() { QueryBuilder jqlQuery = QueryBuilder.byClass(Store.class); List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build()); return javers.getJsonConverter().toJson(snapshots); } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\web\StoreController.java
1
请完成以下Java代码
private void createLogMgtPage_CacheReset(final table table) { if (!isAllowCacheReset()) { return; } tr line = new tr(); line.addElement(new th().addElement(CacheMgt.get().toStringX())); line.addElement(new td().addElement(new a(NAME + "?CacheReset=Yes", "Reset Cache"))); table.addElement(line); } private Element createLogMgtPage_LogFiles() { final p containerElement = new p(); containerElement.addElement(new b("All Log Files: ")); // All in dir boolean first = true; for (final File logFile : LogManager.getLogFiles()) { // Skip if is not a file - teo_sarca [ 1726066 ] if (!logFile.isFile()) { continue; } if (!first) { containerElement.addElement(" - "); } final String fileName = logFile.getAbsolutePath(); final a link = new a(NAME + "?Trace=" + encodeURLValue(fileName), logFile.getName()); link.setTarget("_blank"); link.setTitle(fileName); containerElement.addElement(link); final long sizeBytes = logFile.length(); containerElement.addElement(" (" + bytesToString(sizeBytes) + ")"); first = false; } return containerElement; } private static final String encodeURLValue(final String value) { try { return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()); } catch (UnsupportedEncodingException e) { log.warn("Failed encoding '{}'. Returning it as is.", value, e); return value; } } private static final String bytesToString(final long sizeBytes) { if (sizeBytes < 1024) { return sizeBytes + " bytes"; } else { final long sizeKb = sizeBytes / 1024; if (sizeKb < 1024) { return sizeKb + "k"; } else
{ final long sizeMb = sizeKb / 1024; return sizeMb + "M"; } } } /************************************************************************** * Init * * @param config config * @throws javax.servlet.ServletException */ @Override public void init(ServletConfig config) throws ServletException { // NOTE: actually here we are starting all servers m_serverMgr = AdempiereServerMgr.get(); } /** * Destroy */ @Override public void destroy() { log.info("destroy"); m_serverMgr = null; } // destroy /** * Log error/warning * * @param message message * @param e exception */ @Override public void log(final String message, final Throwable e) { if (e == null) { log.warn(message); } log.error(message, e); } // log /** * Log debug * * @param message message */ @Override public void log(String message) { log.debug(message); } // log @Override public String getServletName() { return NAME; } @Override public String getServletInfo() { return "Server Monitor"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ServerMonitor.java
1
请完成以下Java代码
public String getRequestedSessionId() { if (this.requestedSessionId == null) { getRequestedSession(); } return this.requestedSessionId; } @Override public RequestDispatcher getRequestDispatcher(String path) { RequestDispatcher requestDispatcher = super.getRequestDispatcher(path); return new SessionCommittingRequestDispatcher(requestDispatcher); } private S getRequestedSession() { if (!this.requestedSessionCached) { List<String> sessionIds = SessionRepositoryFilter.this.httpSessionIdResolver.resolveSessionIds(this); for (String sessionId : sessionIds) { if (this.requestedSessionId == null) { this.requestedSessionId = sessionId; } S session = SessionRepositoryFilter.this.sessionRepository.findById(sessionId); if (session != null) { this.requestedSession = session; break; } } this.requestedSessionCached = true; } return this.requestedSession; } private void clearRequestedSessionCache() { this.requestedSessionCached = false; this.requestedSession = null; this.requestedSessionId = null; } /** * Allows creating an HttpSession from a Session instance. * * @author Rob Winch * @since 1.0 */ private final class HttpSessionWrapper extends HttpSessionAdapter<S> { HttpSessionWrapper(S session, ServletContext servletContext) { super(session, servletContext); } @Override public void invalidate() { super.invalidate(); SessionRepositoryRequestWrapper.this.requestedSessionInvalidated = true; setCurrentSession(null); clearRequestedSessionCache();
SessionRepositoryFilter.this.sessionRepository.deleteById(getId()); } } /** * Ensures session is committed before issuing an include. * * @since 1.3.4 */ private final class SessionCommittingRequestDispatcher implements RequestDispatcher { private final RequestDispatcher delegate; SessionCommittingRequestDispatcher(RequestDispatcher delegate) { this.delegate = delegate; } @Override public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException { this.delegate.forward(request, response); } @Override public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (!SessionRepositoryRequestWrapper.this.hasCommittedInInclude) { SessionRepositoryRequestWrapper.this.commitSession(); SessionRepositoryRequestWrapper.this.hasCommittedInInclude = true; } this.delegate.include(request, response); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\SessionRepositoryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public BatchPartEntity createBatchPart(BatchEntity parentBatch, String status, String scopeId, String subScopeId, String scopeType) { BatchPartEntity batchPartEntity = dataManager.create(); batchPartEntity.setBatchId(parentBatch.getId()); batchPartEntity.setType(parentBatch.getBatchType()); batchPartEntity.setBatchType(parentBatch.getBatchType()); batchPartEntity.setScopeId(scopeId); batchPartEntity.setSubScopeId(subScopeId); batchPartEntity.setScopeType(scopeType); batchPartEntity.setSearchKey(parentBatch.getBatchSearchKey()); batchPartEntity.setSearchKey2(parentBatch.getBatchSearchKey2()); batchPartEntity.setBatchSearchKey(parentBatch.getBatchSearchKey()); batchPartEntity.setBatchSearchKey2(parentBatch.getBatchSearchKey2()); batchPartEntity.setStatus(status); if (parentBatch.getTenantId() != null) { batchPartEntity.setTenantId(parentBatch.getTenantId()); } batchPartEntity.setCreateTime(getClock().getCurrentTime()); insert(batchPartEntity); return batchPartEntity; } @Override public BatchPartEntity completeBatchPart(String batchPartId, String status, String resultJson) { BatchPartEntity batchPartEntity = getBatchPartEntityManager().findById(batchPartId); batchPartEntity.setCompleteTime(getClock().getCurrentTime()); batchPartEntity.setStatus(status);
batchPartEntity.setResultDocumentJson(resultJson, serviceConfiguration.getEngineName()); return batchPartEntity; } @Override public void deleteBatchPartEntityAndResources(BatchPartEntity batchPartEntity) { ByteArrayRef resultDocRefId = batchPartEntity.getResultDocRefId(); if (resultDocRefId != null && resultDocRefId.getId() != null) { resultDocRefId.delete(serviceConfiguration.getEngineName()); } delete(batchPartEntity); } protected BatchPartEntityManager getBatchPartEntityManager() { return serviceConfiguration.getBatchPartEntityManager(); } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchPartEntityManagerImpl.java
2
请完成以下Java代码
public class MustacheTemplateRenderer implements TemplateRenderer { private final Compiler mustache; private final Function<String, String> keyGenerator; private final Cache templateCache; /** * Create a new instance with the resource prefix and the {@link Cache} to use. * @param resourcePrefix the resource prefix to apply to locate a template based on * its name * @param templateCache the cache to use for compiled templates (can be {@code null} * to not use caching) */ public MustacheTemplateRenderer(String resourcePrefix, Cache templateCache) { String prefix = (resourcePrefix.endsWith("/") ? resourcePrefix : resourcePrefix + "/"); this.mustache = Mustache.compiler().withLoader(mustacheTemplateLoader(prefix)).escapeHTML(false); this.keyGenerator = (name) -> String.format("%s%s", prefix, name); this.templateCache = templateCache; } /** * Create a new instance with the resource prefix to use. * @param resourcePrefix the resource prefix to apply to locate a template based on * its name * @see #MustacheTemplateRenderer(String, Cache) */ public MustacheTemplateRenderer(String resourcePrefix) { this(resourcePrefix, null); } private static TemplateLoader mustacheTemplateLoader(String prefix) { ResourceLoader resourceLoader = new DefaultResourceLoader(); return (name) -> { String location = prefix + name + ".mustache"; return new InputStreamReader(resourceLoader.getResource(location).getInputStream(), StandardCharsets.UTF_8); }; } @Override public String render(String templateName, Map<String, ?> model) { Template template = getTemplate(templateName); return template.execute(model);
} private Template getTemplate(String name) { try { if (this.templateCache != null) { try { return this.templateCache.get(this.keyGenerator.apply(name), () -> loadTemplate(name)); } catch (ValueRetrievalException ex) { throw ex.getCause(); } } return loadTemplate(name); } catch (Throwable ex) { throw new IllegalStateException("Cannot load template " + name, ex); } } private Template loadTemplate(String name) throws Exception { Reader template = this.mustache.loader.getTemplate(name); return this.mustache.compile(template); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\template\MustacheTemplateRenderer.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean getIncludeTaskLocalVariables() { return includeTaskLocalVariables; } public void setIncludeTaskLocalVariables(Boolean includeTaskLocalVariables) { this.includeTaskLocalVariables = includeTaskLocalVariables; } public Boolean getIncludeProcessVariables() { return includeProcessVariables; } public void setIncludeProcessVariables(Boolean includeProcessVariables) { this.includeProcessVariables = includeProcessVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getTaskVariables() { return taskVariables; } public void setTaskVariables(List<QueryVariable> taskVariables) { this.taskVariables = taskVariables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getWithoutProcessInstanceId() { return withoutProcessInstanceId; } public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) { this.withoutProcessInstanceId = withoutProcessInstanceId; } public String getTaskCandidateGroup() { return taskCandidateGroup; } public void setTaskCandidateGroup(String taskCandidateGroup) { this.taskCandidateGroup = taskCandidateGroup; } public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; }
public String getPlanItemInstanceId() { return planItemInstanceId; } public void setPlanItemInstanceId(String planItemInstanceId) { this.planItemInstanceId = planItemInstanceId; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java
2
请完成以下Java代码
public void onSuccess() { } @Override public void onFailure(RuleEngineException e) { } }; void onSuccess(); void onFailure(RuleEngineException e); default void onRateLimit(RuleEngineException e) { onFailure(e); };
/** * Returns 'true' if rule engine is expecting the message to be processed, 'false' otherwise. * message may no longer be valid, if the message pack is already expired/canceled/failed. * * @return 'true' if rule engine is expecting the message to be processed, 'false' otherwise. */ default boolean isMsgValid() { return true; } default void onProcessingStart(RuleNodeInfo ruleNodeInfo) { } default void onProcessingEnd(RuleNodeId ruleNodeId) { } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\queue\TbMsgCallback.java
1
请完成以下Java代码
protected ObjectNode getMsgDataAsObjectNode(TbMsg msg) { var msgDataNode = JacksonUtil.toJsonNode(msg.getData()); if (msgDataNode == null || !msgDataNode.isObject()) { throw new IllegalArgumentException("Message body is not an object!"); } return (ObjectNode) msgDataNode; } protected void enrichMessage(ObjectNode msgData, TbMsgMetaData metaData, KvEntry kvEntry, String targetKey) { if (TbMsgSource.DATA.equals(fetchTo)) { JacksonUtil.addKvEntry(msgData, kvEntry, targetKey); } else if (TbMsgSource.METADATA.equals(fetchTo)) { metaData.putValue(targetKey, kvEntry.getValueAsString()); } } protected TbMsg transformMessage(TbMsg msg, ObjectNode msgDataNode, TbMsgMetaData msgMetaData) { switch (fetchTo) { case DATA: return msg.transform() .data(JacksonUtil.toString(msgDataNode)) .build(); case METADATA: return msg.transform() .metaData(msgMetaData) .build(); default: log.debug("Unexpected FetchTo value: {}. Allowed values: {}", fetchTo, TbMsgSource.values()); return msg; } }
protected TbPair<Boolean, JsonNode> upgradeRuleNodesWithOldPropertyToUseFetchTo( JsonNode oldConfiguration, String oldProperty, String ifTrue, String ifFalse ) throws TbNodeException { var newConfig = (ObjectNode) oldConfiguration; if (!newConfig.has(oldProperty)) { throw new TbNodeException("property to update: '" + oldProperty + "' doesn't exists in configuration!"); } return upgradeConfigurationToUseFetchTo(oldProperty, ifTrue, ifFalse, newConfig); } protected TbPair<Boolean, JsonNode> upgradeConfigurationToUseFetchTo( String oldProperty, String ifTrue, String ifFalse, ObjectNode newConfig ) throws TbNodeException { var value = newConfig.get(oldProperty).asText(); if ("true".equals(value)) { newConfig.remove(oldProperty); newConfig.put(FETCH_TO_PROPERTY_NAME, ifTrue); return new TbPair<>(true, newConfig); } else if ("false".equals(value)) { newConfig.remove(oldProperty); newConfig.put(FETCH_TO_PROPERTY_NAME, ifFalse); return new TbPair<>(true, newConfig); } else { throw new TbNodeException("property to update: '" + oldProperty + "' has unexpected value: " + value + ". Allowed values: true or false!"); } } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractNodeWithFetchTo.java
1
请完成以下Java代码
public DocumentQueryOrderByList getDefaultOrderBys() { return DocumentQueryOrderByList.EMPTY; } @Override public SqlViewRowsWhereClause getSqlWhereClause(final DocumentIdsSelection rowIds, final SqlOptions sqlOpts) { // TODO Auto-generated method stub return null; } @Override public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass) { throw new UnsupportedOperationException(); } @Override public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds) { return rows.streamByIds(rowIds); } @Override public void notifyRecordsChanged( @NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend) { // TODO Auto-generated method stub } @Override public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() { return additionalRelatedProcessDescriptors; } /** * @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}. */ @NonNull public ShipmentScheduleId getCurrentShipmentScheduleId() { return currentShipmentScheduleId; } @Override public void invalidateAll() { rows.invalidateAll(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java
1
请完成以下Java代码
public SetJobRetriesByProcessAsyncBuilder historicProcessInstanceQuery(HistoricProcessInstanceQuery query) { this.historicProcessInstanceQuery = query; return this; } @Override public SetJobRetriesByProcessAsyncBuilder dueDate(Date dueDate) { this.dueDate = dueDate; isDueDateSet = true; return this; } @Override public Batch executeAsync() { validateParameters(); return commandExecutor.execute(new SetJobsRetriesByProcessBatchCmd(processInstanceIds, processInstanceQuery,
historicProcessInstanceQuery, retries, dueDate, isDueDateSet)); } protected void validateParameters() { ensureNotNull("commandExecutor", commandExecutor); ensureNotNull("retries", retries); boolean isProcessInstanceIdsNull = processInstanceIds == null || processInstanceIds.isEmpty(); boolean isProcessInstanceQueryNull = processInstanceQuery == null; boolean isHistoricProcessInstanceQueryNull = historicProcessInstanceQuery == null; if(isProcessInstanceIdsNull && isProcessInstanceQueryNull && isHistoricProcessInstanceQueryNull) { throw LOG.exceptionSettingJobRetriesAsyncNoProcessesSpecified(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\SetJobRetriesByProcessAsyncBuilderImpl.java
1
请完成以下Java代码
public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getUserOperationId() { return userOperationId; } public void setUserOperationId(String userOperationId) { this.userOperationId = userOperationId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { Context
.getCommandContext() .getDbEntityManager() .delete(this); } @Override public String toString() { return this.getClass().getSimpleName() + "[activityInstanceId=" + activityInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", id=" + id + ", tenantId=" + tenantId + ", userOperationId=" + userOperationId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDetailEventEntity.java
1
请完成以下Spring Boot application配置
############### JSP #################### spring.mvc.view.suffix=/WEB-INF/jsp/ spring.mvc.view.prefix=.jsp logging.level.org.springframework=INFO ################### Data Configuration ######################### spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/management?serverTimezone=UTC spring.datasource.username=root spri
ng.datasource.password=posilka2020 ############################Hibernate Configuration ################ spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringMVC+DB\src\main\resources\application.properties
2
请完成以下Java代码
public void afterLoad(final IHUContext huContext, final List<IAllocationResult> loadResults) { for (final IHUTrxListener listener : listeners) { listener.afterLoad(huContext, loadResults); } } @Override public void onUnloadLoadTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onUnloadLoadTransaction(huContext, unloadTrx, loadTrx); } }
@Override public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx) { for (final IHUTrxListener listener : listeners) { listener.onSplitTransaction(huContext, unloadTrx, loadTrx); } } @Override public String toString() { return "CompositeHUTrxListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\CompositeHUTrxListener.java
1
请完成以下Java代码
protected CaseExecutionImpl createCaseExecution(CmmnActivity activity) { CaseExecutionImpl child = newCaseExecution(); // set activity to execute child.setActivity(activity); // handle child/parent-relation child.setParent(this); getCaseExecutionsInternal().add(child); // set case instance child.setCaseInstance(getCaseInstance()); // set case definition child.setCaseDefinition(getCaseDefinition()); return child; } protected CaseExecutionImpl newCaseExecution() { return new CaseExecutionImpl(); } // variables ////////////////////////////////////////////////////////////// protected VariableStore<CoreVariableInstance> getVariableStore() { return (VariableStore) variableStore; } @Override protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() { return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; } @Override protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() { return Collections.emptyList(); } // toString ///////////////////////////////////////////////////////////////// public String toString() { if (isCaseInstanceExecution()) { return "CaseInstance[" + getToStringIdentity() + "]"; } else { return "CmmnExecution["+getToStringIdentity() + "]";
} } protected String getToStringIdentity() { return Integer.toString(System.identityHashCode(this)); } public String getId() { return String.valueOf(System.identityHashCode(this)); } public ProcessEngineServices getProcessEngineServices() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public ProcessEngine getProcessEngine() { throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName()); } public CmmnElement getCmmnModelElementInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } public CmmnModelInstance getCmmnModelInstance() { throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java
1
请完成以下Java代码
public void setWhereClause (java.lang.String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ @Override public java.lang.String getWhereClause () { return (java.lang.String)get_Value(COLUMNNAME_WhereClause); } /** * NotificationSeverity AD_Reference_ID=541947 * Reference name: NotificationSeverity */ public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947; /** Notice = Notice */ public static final String NOTIFICATIONSEVERITY_Notice = "Notice";
/** Warning = Warning */ public static final String NOTIFICATIONSEVERITY_Warning = "Warning"; /** Error = Error */ public static final String NOTIFICATIONSEVERITY_Error = "Error"; @Override public void setNotificationSeverity (final java.lang.String NotificationSeverity) { set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity); } @Override public java.lang.String getNotificationSeverity() { return get_ValueAsString(COLUMNNAME_NotificationSeverity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java
1
请完成以下Java代码
public static boolean equals(VariableContainer variableContainer, String variableName, Object comparedValue) { Object variableValue = getVariableValue(variableContainer, variableName); if (comparedValue != null && variableValue != null) { // Numbers are not necessarily of the expected type due to coming from JUEL, // (eg. variable can be an Integer but JUEL passes a Long). // As such, a specific check for the supported Number variable types of Flowable is done. if (valuesAreNumbers(comparedValue, variableValue)) { if (variableValue instanceof Long) { return ((Number) variableValue).longValue() == ((Number) comparedValue).longValue(); } else if (variableValue instanceof Integer) { return ((Number) variableValue).intValue() == ((Number) comparedValue).intValue(); } else if (variableValue instanceof Double) { return ((Number) variableValue).doubleValue() == ((Number) comparedValue).doubleValue(); } else if (variableValue instanceof Float) { return ((Number) variableValue).floatValue() == ((Number) comparedValue).floatValue(); } else if (variableValue instanceof Short) {
return ((Number) variableValue).shortValue() == ((Number) comparedValue).shortValue(); } // Other subtypes possible (e.g. BigDecimal, AtomicInteger, etc.), will fall back to default comparison } } return defaultEquals(comparedValue, variableValue); } protected static boolean defaultEquals(Object variableValue, Object actualValue) { return Objects.equals(actualValue, variableValue); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\function\VariableEqualsExpressionFunction.java
1
请完成以下Java代码
public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Setup Time. @param SetupTime Setup time before starting Production */ @Override public void setSetupTime (int SetupTime) { set_Value (COLUMNNAME_SetupTime, Integer.valueOf(SetupTime)); } /** Get Setup Time. @return Setup time before starting Production */ @Override public int getSetupTime () { Integer ii = (Integer)get_Value(COLUMNNAME_SetupTime); if (ii == null) return 0; return ii.intValue(); } /** Set Units by Cycles. @param UnitsCycles The Units by Cycles are defined for process type Flow Repetitive Dedicated and indicated the product to be manufactured on a production line for duration unit. */ @Override public void setUnitsCycles (java.math.BigDecimal UnitsCycles) { set_Value (COLUMNNAME_UnitsCycles, UnitsCycles); } /** Get Units by Cycles. @return The Units by Cycles are defined for process type Flow Repetitive Dedicated and indicated the product to be manufactured on a production line for duration unit. */ @Override public java.math.BigDecimal getUnitsCycles () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitsCycles); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Waiting Time. @param WaitingTime Workflow Simulation Waiting time */ @Override public void setWaitingTime (int WaitingTime) { set_Value (COLUMNNAME_WaitingTime, Integer.valueOf(WaitingTime)); } /** Get Waiting Time. @return Workflow Simulation Waiting time */ @Override public int getWaitingTime () { Integer ii = (Integer)get_Value(COLUMNNAME_WaitingTime); if (ii == null) return 0; return ii.intValue(); } /** Set Working Time. @param WorkingTime Workflow Simulation Execution Time */ @Override public void setWorkingTime (int WorkingTime)
{ set_Value (COLUMNNAME_WorkingTime, Integer.valueOf(WorkingTime)); } /** Get Working Time. @return Workflow Simulation Execution Time */ @Override public int getWorkingTime () { Integer ii = (Integer)get_Value(COLUMNNAME_WorkingTime); if (ii == null) return 0; return ii.intValue(); } /** Set Yield %. @param Yield The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public void setYield (int Yield) { set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield)); } /** Get Yield %. @return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent */ @Override public int getYield () { Integer ii = (Integer)get_Value(COLUMNNAME_Yield); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Workflow.java
1
请完成以下Java代码
public boolean isFailedJobsToInclude() { return includeFailedJobs; } public boolean isIncidentsToInclude() { return includeIncidents || includeIncidentsForType != null; } protected void checkQueryOk() { super.checkQueryOk(); if (includeIncidents && includeIncidentsForType != null) { throw new ProcessEngineException("Invalid query: It is not possible to use includeIncident() and includeIncidentForType() to execute one query."); } } // getter/setter for authorization check public List<PermissionCheck> getProcessInstancePermissionChecks() { return processInstancePermissionChecks; } public void setProcessInstancePermissionChecks(List<PermissionCheck> processInstancePermissionChecks) { this.processInstancePermissionChecks = processInstancePermissionChecks; } public void addProcessInstancePermissionCheck(List<PermissionCheck> permissionChecks) { processInstancePermissionChecks.addAll(permissionChecks); } public List<PermissionCheck> getJobPermissionChecks() { return jobPermissionChecks; } public void setJobPermissionChecks(List<PermissionCheck> jobPermissionChecks) {
this.jobPermissionChecks = jobPermissionChecks; } public void addJobPermissionCheck(List<PermissionCheck> permissionChecks) { jobPermissionChecks.addAll(permissionChecks); } public List<PermissionCheck> getIncidentPermissionChecks() { return incidentPermissionChecks; } public void setIncidentPermissionChecks(List<PermissionCheck> incidentPermissionChecks) { this.incidentPermissionChecks = incidentPermissionChecks; } public void addIncidentPermissionCheck(List<PermissionCheck> permissionChecks) { incidentPermissionChecks.addAll(permissionChecks); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\DeploymentStatisticsQueryImpl.java
1
请完成以下Java代码
protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { if (para.getParameter() == null) { continue; } else if (PARAM_SeqNo.equals(para.getParameterName())) { p_SeqNo_From = para.getParameterAsInt(); p_SeqNo_To = para.getParameter_ToAsInt(); } else if (PARAM_Copies.equals(para.getParameterName())) { p_copies = para.getParameterAsInt(); } } final String tableName = getTableName(); if (I_C_Print_Job.Table_Name.equals(tableName)) { p_C_Print_Job_ID = getRecord_ID(); } else if (I_C_Print_Job_Instructions.Table_Name.equals(tableName)) { final int printJobInstructionsId = getRecord_ID(); final I_C_Print_Job_Instructions instructions = InterfaceWrapperHelper.create(getCtx(), printJobInstructionsId, I_C_Print_Job_Instructions.class, ITrx.TRXNAME_None); p_C_Print_Job_ID = instructions.getC_Print_Job_ID(); } } @Override protected String doIt() { if (p_C_Print_Job_ID <= 0) { throw new FillMandatoryException(I_C_Print_Job.COLUMNNAME_C_Print_Job_ID); } if (p_SeqNo_From <= 0) { p_SeqNo_From = IPrintingDAO.SEQNO_First;
} if (p_SeqNo_To <= 0) { p_SeqNo_To = IPrintingDAO.SEQNO_Last; } final UserId adUserToPrintId = UserId.ofRepoIdOrNull(getAD_User_ID()); // create those instructions just for us and don't let some other printing client running with the same user-id snatch it from us. final boolean createWithSpecificHostKey = true; final I_C_Print_Job printJob = InterfaceWrapperHelper.create(getCtx(), p_C_Print_Job_ID, I_C_Print_Job.class, get_TrxName()); final I_C_Print_Job_Line firstLine = printingDAO.retrievePrintJobLine(printJob, p_SeqNo_From); final I_C_Print_Job_Line lastLine = printingDAO.retrievePrintJobLine(printJob, p_SeqNo_To); this.jobInstructions = printJobBL .createPrintJobInstructions(adUserToPrintId, createWithSpecificHostKey, firstLine, lastLine, p_copies); return MSG_OK; } public I_C_Print_Job_Instructions getC_Print_Job_Instructions() { return jobInstructions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\process\C_Print_Job_Instructions_Create.java
1
请在Spring Boot框架中完成以下Java代码
public class PersistenceProductAutoConfiguration { @Autowired private Environment env; public PersistenceProductAutoConfiguration() { super(); } // @Bean public LocalContainerEntityManagerFactoryBean productEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(productDataSource()); em.setPackagesToScan("com.baeldung.multipledb.model.product"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); final HashMap<String, Object> properties = new HashMap<String, Object>(); properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); em.setJpaPropertyMap(properties);
return em; } @Bean @ConfigurationProperties(prefix="spring.second-datasource") public DataSource productDataSource() { return DataSourceBuilder.create().build(); } @Bean public PlatformTransactionManager productTransactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(productEntityManager().getObject()); return transactionManager; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\multipledb\PersistenceProductAutoConfiguration.java
2
请完成以下Java代码
public class FilterContextEditorAction extends AbstractContextMenuAction { public FilterContextEditorAction() { super(); } @Override public String getName() { return "Filter"; } @Override public String getIcon() { return null; // no icon } @Override public boolean isAvailable() { return isGridMode(); } @Override public boolean isRunnable() { return isAvailable(); } @Override public void run() { final GridTab gridTab = getGridTab(); if (gridTab == null) { return; } final GridController gc = getGridController(); if (gc == null) { return; } final GridField gridField = getGridField(); if (gridField == null) { return;
} final String m_columnName = getColumnName(); final Object m_value = getFieldValue(); final VEditor editor = getEditor(); final String columnDisplayName = gridField.getHeader(); final Object valueDisplay = editor == null ? m_value : editor.getDisplay(); final MQuery queryInitial = new MQuery(gridTab.getTableName()); queryInitial.addRestriction(m_columnName, Operator.EQUAL, m_value); Find find = Find.builder() .setParentFrame(null) .setGridTab(gridTab) .setTitle("" + columnDisplayName + "=" + valueDisplay) .setWhereExtended("") .setQuery(queryInitial) .setMinRecords(1) .buildFindDialog(); // final MQuery query = find.getQuery(); find.dispose(); find = null; // Confirmed query if (query != null) { // m_onlyCurrentRows = false; // search history too gridTab.setQuery(query); gc.query(false, 0, GridTabMaxRows.NO_RESTRICTION); // autoSize } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\grid\ed\FilterContextEditorAction.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomMongoConfiguration { @Bean public MongoCustomConversions customConversions() { return new MongoCustomConversions(Collections.singletonList(DocumentToMoneyConverter.INSTANCE)); } @ReadingConverter enum DocumentToMoneyConverter implements Converter<Document, Money> { INSTANCE; @Override public Money convert(Document source) { Document money = source.get("money", Document.class);
return Money.of(getCurrency(money), getAmount(money)); } private CurrencyUnit getCurrency(Document money) { Document currency = money.get("currency", Document.class); String currencyCode = currency.getString("code"); return CurrencyUnit.of(currencyCode); } private BigDecimal getAmount(Document money) { String amount = money.getString("amount"); return BigDecimal.valueOf(Double.parseDouble(amount)); } } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\config\CustomMongoConfiguration.java
2
请完成以下Java代码
public static UserEntityManager getUserEntityManager() { return getUserEntityManager(getCommandContext()); } public static UserEntityManager getUserEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getUserEntityManager(); } public static GroupEntityManager getGroupEntityManager() { return getGroupEntityManager(getCommandContext()); } public static GroupEntityManager getGroupEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getGroupEntityManager(); } public static MembershipEntityManager getMembershipEntityManager() { return getMembershipEntityManager(getCommandContext()); } public static MembershipEntityManager getMembershipEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getMembershipEntityManager(); } public static PrivilegeEntityManager getPrivilegeEntityManager() { return getPrivilegeEntityManager(getCommandContext()); } public static PrivilegeEntityManager getPrivilegeEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getPrivilegeEntityManager(); } public static PrivilegeMappingEntityManager getPrivilegeMappingEntityManager() { return getPrivilegeMappingEntityManager(getCommandContext()); } public static PrivilegeMappingEntityManager getPrivilegeMappingEntityManager(CommandContext commandContext) {
return getIdmEngineConfiguration(commandContext).getPrivilegeMappingEntityManager(); } public static TokenEntityManager getTokenEntityManager() { return getTokenEntityManager(getCommandContext()); } public static TokenEntityManager getTokenEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getTokenEntityManager(); } public static IdentityInfoEntityManager getIdentityInfoEntityManager() { return getIdentityInfoEntityManager(getCommandContext()); } public static IdentityInfoEntityManager getIdentityInfoEntityManager(CommandContext commandContext) { return getIdmEngineConfiguration(commandContext).getIdentityInfoEntityManager(); } public static CommandContext getCommandContext() { return Context.getCommandContext(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\util\CommandContextUtil.java
1
请完成以下Java代码
private void selectFocus(final ICalloutField calloutField) { final I_C_Order order = calloutField.getModel(I_C_Order.class); final Integer bPartnerId = order.getC_BPartner_ID(); final GridTab mTab = getGridTab(calloutField); if (mTab == null) { return; } if (bPartnerId <= 0 && mTab.getField(COLUMNNAME_C_BPartner_ID).isDisplayed(true)) { mTab.getField(COLUMNNAME_C_BPartner_ID).requestFocus(); return; } // received via is not so important anymore, so don't request focus on it // final String receivedVia = order.getReceivedVia(); // if (Util.isEmpty(receivedVia)) { // mTab.getField(RECEIVED_VIA).requestFocus(); // return; // } final Integer shipperId = order.getM_Shipper_ID(); if (shipperId <= 0 && mTab.getField(COLUMNNAME_M_Shipper_ID).isDisplayed(true)) { mTab.getField(COLUMNNAME_M_Shipper_ID).requestFocus(); return; } // // Ask handlers to request focus handlers.requestFocus(mTab); } public static void clearFields(final ICalloutField calloutField, final boolean save) { clearFields(calloutField.getCalloutRecord(), save); }
@Deprecated public static void clearFields(final ICalloutRecord calloutRecord, final boolean save) { final GridTab gridTab = GridTab.fromCalloutRecordOrNull(calloutRecord); if (gridTab == null) { return; } handlers.clearFields(gridTab); if (save) { gridTab.dataSave(true); } } @Deprecated private final static GridTab getGridTab(final ICalloutField calloutField) { final ICalloutRecord calloutRecord = calloutField.getCalloutRecord(); return GridTab.fromCalloutRecordOrNull(calloutRecord); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\OrderFastInput.java
1
请完成以下Java代码
public BooleanWithReason checkAllowDeleteFromDB() { return isNew() ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted from DB"); } public BooleanWithReason checkAllowDelete(final POSPaymentMethod paymentMethod) { if (checkAllowDeleteFromDB().isTrue()) { return BooleanWithReason.TRUE; } else if (paymentMethod.isCash() && isPending()) { return BooleanWithReason.TRUE; }
else if (isCanceled() || isFailed()) { return BooleanWithReason.TRUE; } else { return BooleanWithReason.falseBecause("Payments with status " + this + " cannot be deleted"); } } public boolean isAllowRefund() { return isSuccessful(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPaymentProcessingStatus.java
1
请完成以下Java代码
public int getShelfLifeMinPct() { return get_ValueAsInt(COLUMNNAME_ShelfLifeMinPct); } @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); } @Override public void setUsedForCustomer (final boolean UsedForCustomer) { set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer); } @Override public boolean isUsedForCustomer() { return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer); } @Override public void setUsedForVendor (final boolean UsedForVendor) { set_Value (COLUMNNAME_UsedForVendor, UsedForVendor); }
@Override public boolean isUsedForVendor() { return get_ValueAsBoolean(COLUMNNAME_UsedForVendor); } @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); } @Override public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo) { set_Value (COLUMNNAME_VendorProductNo, VendorProductNo); } @Override public java.lang.String getVendorProductNo() { return get_ValueAsString(COLUMNNAME_VendorProductNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java
1
请完成以下Java代码
public void setReplicationType (final java.lang.String ReplicationType) { set_Value (COLUMNNAME_ReplicationType, ReplicationType); } @Override public java.lang.String getReplicationType() { return get_ValueAsString(COLUMNNAME_ReplicationType); } @Override public void setTableName (final java.lang.String TableName) { set_Value (COLUMNNAME_TableName, TableName); } @Override public java.lang.String getTableName() { return get_ValueAsString(COLUMNNAME_TableName); } @Override public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote) { set_Value (COLUMNNAME_TechnicalNote, TechnicalNote); } @Override public java.lang.String getTechnicalNote() { return get_ValueAsString(COLUMNNAME_TechnicalNote); } /** * TooltipType AD_Reference_ID=541141 * Reference name: TooltipType */ public static final int TOOLTIPTYPE_AD_Reference_ID=541141; /** DescriptionFallbackToTableIdentifier = DTI */ public static final String TOOLTIPTYPE_DescriptionFallbackToTableIdentifier = "DTI"; /** TableIdentifier = T */ public static final String TOOLTIPTYPE_TableIdentifier = "T"; /** Description = D */ public static final String TOOLTIPTYPE_Description = "D"; @Override public void setTooltipType (final java.lang.String TooltipType) { set_Value (COLUMNNAME_TooltipType, TooltipType); } @Override public java.lang.String getTooltipType()
{ return get_ValueAsString(COLUMNNAME_TooltipType); } @Override public void setWEBUI_View_PageLength (final int WEBUI_View_PageLength) { set_Value (COLUMNNAME_WEBUI_View_PageLength, WEBUI_View_PageLength); } @Override public int getWEBUI_View_PageLength() { return get_ValueAsInt(COLUMNNAME_WEBUI_View_PageLength); } /** * WhenChildCloningStrategy AD_Reference_ID=541756 * Reference name: AD_Table_CloningStrategy */ public static final int WHENCHILDCLONINGSTRATEGY_AD_Reference_ID=541756; /** Skip = S */ public static final String WHENCHILDCLONINGSTRATEGY_Skip = "S"; /** AllowCloning = A */ public static final String WHENCHILDCLONINGSTRATEGY_AllowCloning = "A"; /** AlwaysInclude = I */ public static final String WHENCHILDCLONINGSTRATEGY_AlwaysInclude = "I"; @Override public void setWhenChildCloningStrategy (final java.lang.String WhenChildCloningStrategy) { set_Value (COLUMNNAME_WhenChildCloningStrategy, WhenChildCloningStrategy); } @Override public java.lang.String getWhenChildCloningStrategy() { return get_ValueAsString(COLUMNNAME_WhenChildCloningStrategy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table.java
1
请在Spring Boot框架中完成以下Java代码
public class AdminSettingsDataValidator extends DataValidator<AdminSettings> { private final AdminSettingsService adminSettingsService; @Override protected void validateCreate(TenantId tenantId, AdminSettings adminSettings) { AdminSettings existingSettings = adminSettingsService.findAdminSettingsByTenantIdAndKey(tenantId, adminSettings.getKey()); if (existingSettings != null) { throw new DataValidationException("Admin settings with such name already exists!"); } } @Override protected AdminSettings validateUpdate(TenantId tenantId, AdminSettings adminSettings) { AdminSettings existentAdminSettings = adminSettingsService.findAdminSettingsById(tenantId, adminSettings.getId()); if (existentAdminSettings != null) {
if (!existentAdminSettings.getKey().equals(adminSettings.getKey())) { throw new DataValidationException("Changing key of admin settings entry is prohibited!"); } } return existentAdminSettings; } @Override protected void validateDataImpl(TenantId tenantId, AdminSettings adminSettings) { validateString("Key", adminSettings.getKey()); if (adminSettings.getJsonValue() == null) { throw new DataValidationException("Json value should be specified!"); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\AdminSettingsDataValidator.java
2
请完成以下Java代码
public void add(String key) { TermFrequency termFrequency = trie.get(key); if (termFrequency == null) { termFrequency = new TermFrequency(key); trie.put(key, termFrequency); } else { termFrequency.increase(); } } @Override public boolean saveTxtTo(String path) { if ("=".equals(delimeter)) { LinkedList<TermFrequency> termFrequencyLinkedList = new LinkedList<TermFrequency>(); for (Map.Entry<String, TermFrequency> entry : trie.entrySet()) { termFrequencyLinkedList.add(entry.getValue()); } return IOUtil.saveCollectionToTxt(termFrequencyLinkedList, path); } else { ArrayList<String> outList = new ArrayList<String>(size()); for (Map.Entry<String, TermFrequency> entry : trie.entrySet()) { outList.add(entry.getKey() + delimeter + entry.getValue().getFrequency()); } return IOUtil.saveCollectionToTxt(outList, path); } } /** * 仅仅将值保存到文件 * @param path * @return */ public boolean saveKeyTo(String path) { LinkedList<String> keyList = new LinkedList<String>();
for (Map.Entry<String, TermFrequency> entry : trie.entrySet()) { keyList.add(entry.getKey()); } return IOUtil.saveCollectionToTxt(keyList, path); } /** * 按照频率从高到低排序的条目 * @return */ public TreeSet<TermFrequency> values() { TreeSet<TermFrequency> set = new TreeSet<TermFrequency>(Collections.reverseOrder()); for (Map.Entry<String, TermFrequency> entry : entrySet()) { set.add(entry.getValue()); } return set; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\TFDictionary.java
1
请完成以下Java代码
public String getOrgType() { return orgType; } public void setOrgType(String orgType) { this.orgType = orgType; } public String getOrgCode() { return orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getAddress() {
return address; } public void setAddress(String address) { this.address = address; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java
1
请完成以下Java代码
public int getErrorCode() { return errorCode; } public String getSqlState() { return sqlState; } protected boolean equals(int errorCode, String sqlState) { return this.getErrorCode() == errorCode && this.getSqlState().equals(sqlState); } } public static boolean checkDeadlockException(SQLException sqlException) { String sqlState = sqlException.getSQLState(); if (sqlState != null) { sqlState = sqlState.toUpperCase(); } else { return false; } int errorCode = sqlException.getErrorCode(); return MYSQL.equals(errorCode, sqlState) || MSSQL.equals(errorCode, sqlState) || DB2.equals(errorCode, sqlState) || ORACLE.equals(errorCode, sqlState) || POSTGRES.equals(errorCode, sqlState) || H2.equals(errorCode, sqlState); } public static BatchExecutorException findBatchExecutorException(PersistenceException exception) { Throwable cause = exception; do { if (cause instanceof BatchExecutorException) { return (BatchExecutorException) cause; } cause = cause.getCause(); } while (cause != null); return null; } /** * Pass logic, which directly calls MyBatis API. In case a MyBatis exception is thrown, it is * wrapped into a {@link ProcessEngineException} and never propagated directly to an Engine API * call. In some cases, the top-level exception and its message are shown as a response body in * the REST API. Wrapping all MyBatis API calls in our codebase makes sure that the top-level
* exception is always a {@link ProcessEngineException} with a generic message. Like this, SQL * details are never disclosed to potential attackers. * * @param supplier which calls MyBatis API * @param <T> is the type of the return value * @return the value returned by the supplier * @throws ProcessEngineException which wraps the actual exception */ public static <T> T doWithExceptionWrapper(Supplier<T> supplier) { try { return supplier.get(); } catch (Exception ex) { throw wrapPersistenceException(ex); } } public static ProcessEnginePersistenceException wrapPersistenceException(Exception ex) { return new ProcessEnginePersistenceException(PERSISTENCE_EXCEPTION_MESSAGE, ex); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ExceptionUtil.java
1
请完成以下Java代码
public String toString() { return "LPAD[size=" + size + ", padStr=" + padStr + "]"; } private final String buildSql(final String column) { return "LPAD(TRIM(" + column + "), " + size + ", " + DB.TO_STRING(padStr) + ")"; } @Override public @NonNull String getColumnSql(@NonNull String columnName) { return buildSql(columnName); } @Override public String getValueSql(Object value, List<Object> params) { final String valueSql; if (value instanceof ModelColumnNameValue<?>) { final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value; valueSql = modelValue.getColumnName(); }
else { valueSql = "?"; params.add(value); } return buildSql(valueSql); } @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model) { if (value == null) { return null; } final String str = (String)value; // implementation detail: we use `subSequence` because we want to match the Postgres LPAD implementation. The returned string is of the EXACT required length, even if that means the string will be shortened. return StringUtils.leftPad(str.trim(), size, padStr).subSequence(0, size); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\LpadQueryFilterModifier.java
1
请完成以下Java代码
public boolean supports(Class<?> clazz) { return true; } @Override public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { int result = ACCESS_ABSTAIN; for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; if (IS_AUTHENTICATED_FULLY.equals(attribute.getAttribute())) { if (isFullyAuthenticated(authentication)) { return ACCESS_GRANTED; } } if (IS_AUTHENTICATED_REMEMBERED.equals(attribute.getAttribute())) { if (this.authenticationTrustResolver.isRememberMe(authentication)
|| isFullyAuthenticated(authentication)) { return ACCESS_GRANTED; } } if (IS_AUTHENTICATED_ANONYMOUSLY.equals(attribute.getAttribute())) { if (this.authenticationTrustResolver.isAnonymous(authentication) || isFullyAuthenticated(authentication) || this.authenticationTrustResolver.isRememberMe(authentication)) { return ACCESS_GRANTED; } } } } return result; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AuthenticatedVoter.java
1
请在Spring Boot框架中完成以下Java代码
public static ResourcePlanningPrecision ofCodeOrMinute(@Nullable final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); if (codeNorm == null || codeNorm.equals(MINUTE.getCode())) { return MINUTE; } else if (codeNorm.equals(MINUTE_15.getCode())) { return MINUTE_15; } else { throw new AdempiereException("Unknown " + ResourcePlanningPrecision.class + " code: " + codeNorm); } }
@NonNull public ImmutableSet<Integer> getMinutes() { switch (this) { case MINUTE_15: return ImmutableSet.of(0, 15, 30, 45); case MINUTE: return IntStream.rangeClosed(0, 59) .boxed() .collect(ImmutableSet.toImmutableSet()); default: throw new AdempiereException("Unknown " + ResourcePlanningPrecision.class + ": " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\service\ResourcePlanningPrecision.java
2
请完成以下Spring Boot application配置
spring: thymeleaf: mode: HTML5 encoding: UTF-8 cache: false datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring-security?useUni
code=true&characterEncoding=utf-8&useSSL=false username: root password: root
repos\SpringBootLearning-master (1)\springboot-security\src\main\resources\application.yml
2
请完成以下Java代码
public class NativeDeploymentQueryImpl extends AbstractNativeQuery<NativeDeploymentQuery, Deployment> implements NativeDeploymentQuery { private static final long serialVersionUID = 1L; public NativeDeploymentQueryImpl(CommandContext commandContext) { super(commandContext); } public NativeDeploymentQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } // results ////////////////////////////////////////////////////////////////
public List<Deployment> executeList( CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults ) { return commandContext .getDeploymentEntityManager() .findDeploymentsByNativeQuery(parameterMap, firstResult, maxResults); } public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) { return commandContext.getDeploymentEntityManager().findDeploymentCountByNativeQuery(parameterMap); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\NativeDeploymentQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, MetadataReportConfig> getMetadataReports() { return metadataReports; } public void setMetadataReports(Map<String, MetadataReportConfig> metadataReports) { this.metadataReports = metadataReports; } static class Config { /** * Indicates multiple properties binding from externalized configuration or not. */ private boolean multiple = DEFAULT_MULTIPLE_CONFIG_PROPERTY_VALUE; /** * The property name of override Dubbo config */ private boolean override = DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE; public boolean isOverride() { return override; } public void setOverride(boolean override) { this.override = override; } public boolean isMultiple() { return multiple; } public void setMultiple(boolean multiple) { this.multiple = multiple; } }
static class Scan { /** * The basePackages to scan , the multiple-value is delimited by comma * * @see EnableDubbo#scanBasePackages() */ private Set<String> basePackages = new LinkedHashSet<>(); public Set<String> getBasePackages() { return basePackages; } public void setBasePackages(Set<String> basePackages) { this.basePackages = basePackages; } } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\autoconfigure\DubboConfigurationProperties.java
2
请完成以下Java代码
public abstract class AbstractScriptsApplierTemplate implements Runnable { private Logger _logger = LoggerFactory.getLogger(getClass()); protected abstract IScriptFactory createScriptFactory(); protected abstract IScriptScanner createScriptScanner(final IScriptScannerFactory scriptScannerFactory); protected abstract void configureScriptExecutorFactory(final IScriptExecutorFactory scriptExecutorFactory); protected abstract IDatabase createDatabase(); protected abstract IScriptsApplierListener createScriptsApplierListener(); public void setLogger(final Logger logger) { _logger = logger; } public Logger getLogger() { if (_logger == null) { _logger = LoggerFactory.getLogger(getClass()); } return _logger; } @Override public void run() { final Logger logger = getLogger(); // // Setup script scanner factory final IScriptScannerFactory scriptScannerFactory = new ScriptScannerFactory(); scriptScannerFactory.setScriptFactory(createScriptFactory()); // // Setup script executor final IScriptExecutorFactory scriptExecutorFactory = createScriptExecutorFactory(); configureScriptExecutorFactory(scriptExecutorFactory); // // Register Executor to scanner factory, all supported file types // NOTE: if there are no file types registered, script scanner will return nothing scriptScannerFactory.registerScriptScannerClassesFor(scriptExecutorFactory); // // Create script scanner final IScriptScanner scriptScanner = createScriptScanner(scriptScannerFactory); // // Convert scriptScanner to scriptProvider final IScriptsProvider scriptsProvider = new ScriptScannerProviderWrapper(scriptScanner); // // Setup Script Applier final IDatabase database = createDatabase(); final IScriptsApplier scriptsApplier = createScriptApplier(database); scriptsApplier.setScriptExecutorFactory(scriptExecutorFactory);
scriptsApplier.setListener(createScriptsApplierListener()); // // Execute ScriptException error = null; try { scriptsApplier.apply(scriptsProvider); } catch (final ScriptException e) { error = e; // let it fail throw e; } finally { logger.info("Evaluated " + scriptsApplier.getCountAll() + " scripts"); logger.info("Applied " + scriptsApplier.getCountApplied() + " scripts"); logger.info("Ignored " + scriptsApplier.getCountIgnored() + " scripts"); if (error != null) { logger.info("================================================================================================================"); logger.info(error.getLocalizedMessage(), error); } } } protected IScriptExecutorFactory createScriptExecutorFactory() { return new DefaultScriptExecutorFactory(); } /** * Create and returns a new {@link ScriptsApplier} instance. Can be overridden in order to e.g. have no-op Scripts applier. */ protected ScriptsApplier createScriptApplier(final IDatabase database) { return new ScriptsApplier(database); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\AbstractScriptsApplierTemplate.java
1
请完成以下Java代码
private final class StrictFirewallHttpHeaders extends HttpHeaders { private StrictFirewallHttpHeaders(HttpHeaders delegate) { super(delegate); } @Override public @Nullable String getFirst(String headerName) { validateAllowedHeaderName(headerName); String headerValue = super.getFirst(headerName); validateAllowedHeaderValue(headerName, headerValue); return headerValue; } @Override public @Nullable List<String> get(String headerName) { validateAllowedHeaderName(headerName); List<String> headerValues = super.get(headerName); if (headerValues == null) { return headerValues; } for (String headerValue : headerValues) { validateAllowedHeaderValue(headerName, headerValue); } return headerValues; } @Override public Set<String> headerNames() { Set<String> headerNames = super.headerNames(); for (String headerName : headerNames) { validateAllowedHeaderName(headerName); } return headerNames; } } private final class StrictFirewallBuilder implements Builder { private final Builder delegate; private StrictFirewallBuilder(Builder delegate) { this.delegate = delegate; } @Override public Builder method(HttpMethod httpMethod) { return new StrictFirewallBuilder(this.delegate.method(httpMethod)); } @Override public Builder uri(URI uri) { return new StrictFirewallBuilder(this.delegate.uri(uri)); } @Override
public Builder path(String path) { return new StrictFirewallBuilder(this.delegate.path(path)); } @Override public Builder contextPath(String contextPath) { return new StrictFirewallBuilder(this.delegate.contextPath(contextPath)); } @Override public Builder header(String headerName, String... headerValues) { return new StrictFirewallBuilder(this.delegate.header(headerName, headerValues)); } @Override public Builder headers(Consumer<HttpHeaders> headersConsumer) { return new StrictFirewallBuilder(this.delegate.headers(headersConsumer)); } @Override public Builder sslInfo(SslInfo sslInfo) { return new StrictFirewallBuilder(this.delegate.sslInfo(sslInfo)); } @Override public Builder remoteAddress(InetSocketAddress remoteAddress) { return new StrictFirewallBuilder(this.delegate.remoteAddress(remoteAddress)); } @Override public Builder localAddress(InetSocketAddress localAddress) { return new StrictFirewallBuilder(this.delegate.localAddress(localAddress)); } @Override public ServerHttpRequest build() { return new StrictFirewallHttpRequest(this.delegate.build()); } } } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\firewall\StrictServerWebExchangeFirewall.java
1
请完成以下Java代码
protected DeploymentBuilder loadApplicationUpgradeContext(DeploymentBuilder deploymentBuilder) { if (applicationUpgradeContextService != null) { loadProjectManifest(deploymentBuilder); loadEnforcedAppVersion(deploymentBuilder); } return deploymentBuilder; } private void loadProjectManifest(DeploymentBuilder deploymentBuilder) { if (applicationUpgradeContextService.hasProjectManifest()) { try { deploymentBuilder.setProjectManifest(applicationUpgradeContextService.loadProjectManifest()); } catch (IOException e) { LOGGER.warn( "Manifest of application not found. Project release version will not be set for deployment." );
} } } private void loadEnforcedAppVersion(DeploymentBuilder deploymentBuilder) { if (applicationUpgradeContextService.hasEnforcedAppVersion()) { deploymentBuilder.setEnforcedAppVersion(applicationUpgradeContextService.getEnforcedAppVersion()); LOGGER.warn( "Enforced application version set to " + applicationUpgradeContextService.getEnforcedAppVersion().toString() ); } else { LOGGER.warn("Enforced application version not set."); } } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\AbstractAutoDeploymentStrategy.java
1
请完成以下Java代码
public void setComments(List<Comment> comments) { this.comments = comments; } public void setAuthor(User author) { this.author = author; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; }
Post post = (Post) o; return Objects.equals(id, post.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public String toString() { return "Post(id=" + this.getId() + ", content=" + this.getContent() + ", comments=" + this.getComments() + ", author=" + this.getAuthor() + ")"; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Post.java
1
请完成以下Java代码
public PageData<Domain> findByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(domainRepository.findByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public int countDomainByTenantIdAndOauth2Enabled(TenantId tenantId, boolean enabled) { return domainRepository.countByTenantIdAndOauth2Enabled(tenantId.getId(), enabled); } @Override public List<DomainOauth2Client> findOauth2ClientsByDomainId(TenantId tenantId, DomainId domainId) { return DaoUtil.convertDataList(domainOauth2ClientRepository.findAllByDomainId(domainId.getId())); } @Override public void addOauth2Client(DomainOauth2Client domainOauth2Client) { domainOauth2ClientRepository.save(new DomainOauth2ClientEntity(domainOauth2Client)); }
@Override public void removeOauth2Client(DomainOauth2Client domainOauth2Client) { domainOauth2ClientRepository.deleteById(new DomainOauth2ClientCompositeKey(domainOauth2Client.getDomainId().getId(), domainOauth2Client.getOAuth2ClientId().getId())); } @Override public void deleteByTenantId(TenantId tenantId) { domainRepository.deleteByTenantId(tenantId.getId()); } @Override public EntityType getEntityType() { return EntityType.DOMAIN; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\domain\JpaDomainDao.java
1
请完成以下Java代码
public String getCamundaFormKey() { return camundaFormKeyAttribute.getValue(this); } public void setCamundaFormKey(String camundaFormKey) { camundaFormKeyAttribute.setValue(this, camundaFormKey); } public String getCamundaPriority() { return camundaPriorityAttribute.getValue(this); } public void setCamundaPriority(String camundaPriority) { camundaPriorityAttribute.setValue(this, camundaPriority); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(HumanTask.class, CMMN_ELEMENT_HUMAN_TASK) .namespaceUri(CMMN11_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<HumanTask>() { public HumanTask newInstance(ModelTypeInstanceContext instanceContext) { return new HumanTaskImpl(instanceContext); } }); performerRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PERFORMER_REF) .idAttributeReference(Role.class) .build(); /** camunda extensions */ camundaAssigneeAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ASSIGNEE) .namespace(CAMUNDA_NS) .build(); camundaCandidateGroupsAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_GROUPS) .namespace(CAMUNDA_NS) .build(); camundaCandidateUsersAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_USERS) .namespace(CAMUNDA_NS) .build(); camundaDueDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DUE_DATE) .namespace(CAMUNDA_NS) .build(); camundaFollowUpDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FOLLOW_UP_DATE)
.namespace(CAMUNDA_NS) .build(); camundaFormKeyAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FORM_KEY) .namespace(CAMUNDA_NS) .build(); camundaPriorityAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PRIORITY) .namespace(CAMUNDA_NS) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); planningTableCollection = sequenceBuilder.elementCollection(PlanningTable.class) .build(); planningTableChild = sequenceBuilder.element(PlanningTable.class) .minOccurs(0) .maxOccurs(1) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\HumanTaskImpl.java
1
请完成以下Java代码
public EndpointServlet withInitParameters(Map<String, String> initParameters) { Assert.notNull(initParameters, "'initParameters' must not be null"); boolean hasEmptyName = initParameters.keySet().stream().anyMatch((name) -> !StringUtils.hasText(name)); Assert.isTrue(!hasEmptyName, "'initParameters' must not contain empty names"); Map<String, String> mergedInitParameters = new LinkedHashMap<>(this.initParameters); mergedInitParameters.putAll(initParameters); return new EndpointServlet(this.servlet, mergedInitParameters, this.loadOnStartup); } /** * Sets the {@code loadOnStartup} priority that will be set on Servlet registration. * The default value for {@code loadOnStartup} is {@code -1}. * @param loadOnStartup the initialization priority of the Servlet * @return a new instance of {@link EndpointServlet} with the provided * {@code loadOnStartup} value set * @since 2.2.0 * @see Dynamic#setLoadOnStartup(int) */ public EndpointServlet withLoadOnStartup(int loadOnStartup) {
return new EndpointServlet(this.servlet, this.initParameters, loadOnStartup); } Servlet getServlet() { return this.servlet; } Map<String, String> getInitParameters() { return this.initParameters; } int getLoadOnStartup() { return this.loadOnStartup; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\EndpointServlet.java
1
请完成以下Java代码
public class DemoExceptionHandler { private static final String DEFAULT_ERROR_VIEW = "error"; /** * 统一 json 异常处理 * * @param exception JsonException * @return 统一返回 json 格式 */ @ExceptionHandler(value = JsonException.class) @ResponseBody public ApiResponse jsonErrorHandler(JsonException exception) { log.error("【JsonException】:{}", exception.getMessage()); return ApiResponse.ofException(exception); }
/** * 统一 页面 异常处理 * * @param exception PageException * @return 统一跳转到异常页面 */ @ExceptionHandler(value = PageException.class) public ModelAndView pageErrorHandler(PageException exception) { log.error("【DemoPageException】:{}", exception.getMessage()); ModelAndView view = new ModelAndView(); view.addObject("message", exception.getMessage()); view.setViewName(DEFAULT_ERROR_VIEW); return view; } }
repos\spring-boot-demo-master\demo-exception-handler\src\main\java\com\xkcoding\exception\handler\handler\DemoExceptionHandler.java
1
请完成以下Java代码
public void example5_methodReferences() { // Original way without lambdas and method references List<String> names = Arrays.asList("ross", "joey", "chandler"); List<String> upperCaseNames = new ArrayList<>(); for(String name : names) { upperCaseNames.add(name.toUpperCase()); } // Using method reference with stream map operation List<String> petNames = Arrays.asList("ross", "joey", "chandler"); List<String> petUpperCaseNames = petNames .stream() .map(String::toUpperCase) .collect(Collectors.toList()); // Method reference with stream filter List<Animal> pets = Arrays.asList(new Cat(), new Dog(), new Parrot()); List<Animal> onlyDogs = pets .stream() .filter(Dog.class::isInstance) .collect(Collectors.toList()); // Method reference with constructors Set<Animal> onlyDogsSet = pets .stream() .filter(Dog.class::isInstance) .collect(Collectors.toCollection(TreeSet::new)); } public void example6_asserttion() { // Original way without assertions Connection conn = getConnection(); if(conn == null) { throw new RuntimeException("Connection is null"); } // Using assert keyword assert getConnection() != null : "Connection is null"; } private boolean checkSomeCondition() { return new Random().nextBoolean(); } private boolean callRemoteApi() {
return new Random().nextBoolean(); } private Connection getConnection() { return null; } private static interface Animal { } private static class Dog implements Animal { } private static class Cat implements Animal { } private static class Parrot implements Animal { } }
repos\tutorials-master\core-java-modules\core-java-lang-operators-2\src\main\java\com\baeldung\colonexamples\ColonExamples.java
1