instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class BpartnerPriceListRestController { private final BpartnerPriceListServicesFacade servicesFacade; public BpartnerPriceListRestController( @NonNull final BpartnerPriceListServicesFacade servicesFacade) { this.servicesFacade = servicesFacade; } @GetMapping("/{bpartnerIdentifier}/sales/prices/{countryCode}") public ResponseEntity<JsonResponsePriceList> getSalesPriceList( @ApiParam(required = true, value = BPARTNER_IDENTIFIER_DOC) // @PathVariable("bpartnerIdentifier") // @NonNull final String bpartnerIdentifierStr, // @ApiParam(required = true, value = "Country code (2 letters)") // @PathVariable("countryCode") // @NonNull final String countryCode, // @ApiParam(required = false, value = "Date on which the prices shall be valid. The format is 'yyyy-MM-dd'.") // @RequestParam(name = "date", required = false) // @Nullable final String dateStr) { final IdentifierString bpartnerIdentifier = IdentifierString.of(bpartnerIdentifierStr); return getProductPrices(bpartnerIdentifier, SOTrx.SALES, countryCode, dateStr); } @GetMapping("/{bpartnerIdentifier}/purchase/prices/{countryCode}") public ResponseEntity<JsonResponsePriceList> getPurchasePriceList( @ApiParam(required = true, value = BPARTNER_IDENTIFIER_DOC) // @PathVariable("bpartnerIdentifier") // @NonNull final String bpartnerIdentifierStr, // @ApiParam(required = true, value = "Country code (2 letters)") // @PathVariable("countryCode") // @NonNull final String countryCode, // @ApiParam(required = false, value = "Date on which the prices shall be valid. The format is 'yyyy-MM-dd'.") //
@RequestParam(name = "date", required = false) // @Nullable final String dateStr) { final IdentifierString bpartnerIdentifier = IdentifierString.of(bpartnerIdentifierStr); return getProductPrices(bpartnerIdentifier, SOTrx.PURCHASE, countryCode, dateStr); } private ResponseEntity<JsonResponsePriceList> getProductPrices( @NonNull final IdentifierString bpartnerIdentifier, @NonNull final SOTrx soTrx, @NonNull final String countryCode, @Nullable final String dateStr) { try { final LocalDate date = !Check.isEmpty(dateStr) ? TimeUtil.asLocalDate(dateStr) : SystemTime.asLocalDate(); final JsonResponsePriceList result = GetPriceListCommand.builder() .servicesFacade(servicesFacade) // .bpartnerIdentifier(bpartnerIdentifier) .soTrx(soTrx) .countryCode(countryCode) .date(date) .execute(); return ResponseEntity.ok(result); } catch (final Exception ex) { return ResponseEntity .status(HttpStatus.NOT_FOUND) .body(JsonResponsePriceList.error(ex, Env.getADLanguageOrBaseLanguage())); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListRestController.java
2
请完成以下Java代码
public AlarmCommentId getId() { return super.getId(); } @Schema(description = "Timestamp of the alarm comment creation, in milliseconds", example = "1634058704567", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } public AlarmComment() { super(); } public AlarmComment(AlarmCommentId id) { super(id); }
@Override @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "representing comment text", example = "Please take a look") public String getName() { return comment.toString(); } public AlarmComment(AlarmComment alarmComment) { super(alarmComment.getId()); this.createdTime = alarmComment.getCreatedTime(); this.alarmId = alarmComment.getAlarmId(); this.type = alarmComment.getType(); this.comment = alarmComment.getComment(); this.userId = alarmComment.getUserId(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\AlarmComment.java
1
请在Spring Boot框架中完成以下Java代码
public class ProtoTransportEntityService { private final TransportService transportService; public Device getDeviceById(DeviceId id) { TransportProtos.GetDeviceResponseMsg deviceProto = transportService.getDevice(TransportProtos.GetDeviceRequestMsg.newBuilder() .setDeviceIdMSB(id.getId().getMostSignificantBits()) .setDeviceIdLSB(id.getId().getLeastSignificantBits()) .build()); if (deviceProto == null) { return null; } DeviceProfileId deviceProfileId = new DeviceProfileId(new UUID( deviceProto.getDeviceProfileIdMSB(), deviceProto.getDeviceProfileIdLSB()) ); Device device = new Device(); device.setId(id); device.setDeviceProfileId(deviceProfileId); DeviceTransportConfiguration deviceTransportConfiguration = JacksonUtil.fromBytes( deviceProto.getDeviceTransportConfiguration().toByteArray(), DeviceTransportConfiguration.class); DeviceData deviceData = new DeviceData(); deviceData.setTransportConfiguration(deviceTransportConfiguration); device.setDeviceData(deviceData); return device; } public DeviceCredentials getDeviceCredentialsByDeviceId(DeviceId deviceId) { TransportProtos.GetDeviceCredentialsResponseMsg deviceCredentialsResponse = transportService.getDeviceCredentials( TransportProtos.GetDeviceCredentialsRequestMsg.newBuilder() .setDeviceIdMSB(deviceId.getId().getMostSignificantBits()) .setDeviceIdLSB(deviceId.getId().getLeastSignificantBits()) .build()
); if (deviceCredentialsResponse.hasDeviceCredentialsData()) { return ProtoUtils.fromProto(deviceCredentialsResponse.getDeviceCredentialsData()); } else { throw new IllegalArgumentException("Device credentials not found"); } } public TransportProtos.GetSnmpDevicesResponseMsg getSnmpDevicesIds(int page, int pageSize) { TransportProtos.GetSnmpDevicesRequestMsg requestMsg = TransportProtos.GetSnmpDevicesRequestMsg.newBuilder() .setPage(page) .setPageSize(pageSize) .build(); return transportService.getSnmpDevicesIds(requestMsg); } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\ProtoTransportEntityService.java
2
请完成以下Java代码
private WarehouseId getDistributionNetworkWarehouseDestination(final IContext context) { final int attributeSetInstanceId = context.getM_AttributeSetInstance() == null ? AttributeConstants.M_AttributeSetInstance_ID_None : context.getM_AttributeSetInstance().getM_AttributeSetInstance_ID(); final IProductPlanningDAO productPlanningDAO = Services.get(IProductPlanningDAO.class); final ProductPlanningQuery query = ProductPlanningQuery.builder() .orgId(OrgId.ofRepoId(context.getAD_Org_ID())) .productId(ProductId.ofRepoId(context.getM_Product_ID())) .attributeSetInstanceId(AttributeSetInstanceId.ofRepoId(attributeSetInstanceId)) // no warehouse, no plant .build(); final ProductPlanning productPlanning = productPlanningDAO.find(query).orElse(null); if (productPlanning == null) { return null; } if (productPlanning.getDistributionNetworkId() == null) { return null; }
final DistributionNetworkRepository distributionNetworkRepository = SpringContextHolder.instance.getBean(DistributionNetworkRepository.class); final DistributionNetwork distributionNetwork = distributionNetworkRepository.getById(productPlanning.getDistributionNetworkId()); final List<DistributionNetworkLine> distributionNetworkLines = distributionNetwork.getLinesBySourceWarehouse(WarehouseId.ofRepoId(context.getM_Warehouse_ID())); if (distributionNetworkLines.isEmpty()) { return null; } // the lines are ordered by PriorityNo, M_Shipper_ID final DistributionNetworkLine firstFoundDistributionNetworkLine = distributionNetworkLines.get(0); return firstFoundDistributionNetworkLine.getTargetWarehouseId(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\DefaultFromOrderLineWarehouseDestProvider.java
1
请完成以下Java代码
default void putWindowContext(final String name, final boolean value) { Env.setContext(getCtx(), getWindowNo(), name, value); } default void putContext(final String name, final java.util.Date value) { Env.setContext(getCtx(), getWindowNo(), name, value); } /** * Put to window context. */ default void putContext(final String name, final int value) { Env.setContext(getCtx(), getWindowNo(), name, value); }
default int getGlobalContextAsInt(final String name) { return Env.getContextAsInt(getCtx(), name); } default int getTabInfoContextAsInt(final String name) { return Env.getContextAsInt(getCtx(), getWindowNo(), Env.TAB_INFO, name); } default boolean getContextAsBoolean(final String name) { return DisplayType.toBoolean(Env.getContext(getCtx(), getWindowNo(), name)); } boolean isLookupValuesContainingId(@NonNull RepoIdAware id); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\ICalloutField.java
1
请完成以下Java代码
public String[] getActivityIds() { return activityIds; } public String[] getFailedActivityIds() { return failedActivityIds; } public String[] getExecutionIds() { return executionIds; } public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() { return state; }
public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonShipmentResponse { @JsonProperty("ShpCSID") Integer shpCSID; @JsonProperty("ShpTag") String shpTag; @JsonProperty("InstallationID") String installationID; @JsonProperty("PhysicalInstallationID") String physicalInstallationID; @JsonProperty("Kind") Integer kind; @JsonProperty("ShpNo") String shpNo; @JsonProperty("OrderNo") String orderNo; @JsonProperty("PickupDt") String pickupDt; @JsonProperty("LabelPrintDt") String labelPrintDt; @JsonProperty("SubmitDt") String submitDt; @JsonProperty("Vol") Long vol; @JsonProperty("Weight") Integer weight; @JsonProperty("Height") Integer height; @JsonProperty("Length") Integer length; @JsonProperty("Width") Integer width; @JsonProperty("ActorCSID") Integer actorCSID; @JsonProperty("Temperature") Integer temperature; @JsonProperty("CarriagePayer") Integer carriagePayer; @JsonProperty("CarrierConceptID")
Integer carrierConceptID; @JsonProperty("CarrierCSID") Integer carrierCSID; @JsonProperty("SubcarrierConceptID") Integer subcarrierConceptID; @JsonProperty("SubcarrierCSID") Integer subcarrierCSID; @JsonProperty("ProdConceptID") Integer prodConceptID; @JsonProperty("ProdCSID") Integer prodCSID; @JsonProperty("StackCSID") Integer stackCSID; @JsonProperty("PickupTerminal") String pickupTerminal; @JsonProperty("AgentNo") String agentNo; @JsonProperty("PayerAccountAtCarrier") String payerAccountAtCarrier; @JsonProperty("SenderAccountAtCarrier") String senderAccountAtCarrier; @JsonProperty("Addresses") List<JsonAddress> addresses; @JsonProperty("Lines") List<JsonLine> lines; @JsonProperty("Labels") @Singular List<JsonShipmentResponseLabel> labels; @JsonProperty("ShpDocuments") List<JsonShipmentDocument> shpDocuments; @JsonProperty("CorrelationID") String correlationID; @JsonProperty("Amounts") List<JsonAmount> amounts; @JsonProperty("References") @Singular List<JsonReference> references; }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\json\response\JsonShipmentResponse.java
2
请完成以下Java代码
public class ProcessExtensionResourceFinderDescriptor implements ResourceFinderDescriptor { private boolean checkResources; private String locationPrefix; private List<String> locationSuffixes; public ProcessExtensionResourceFinderDescriptor( boolean checkResources, String locationPrefix, String locationSuffix ) { this.checkResources = checkResources; this.locationPrefix = locationPrefix; locationSuffixes = new ArrayList<>(); locationSuffixes.add(locationSuffix); } @Override public List<String> getLocationSuffixes() { return locationSuffixes; } @Override public String getLocationPrefix() { return locationPrefix; } @Override public boolean shouldLookUpResources() {
return checkResources; } @Override public String getMsgForEmptyResources() { return "No process extensions were found for auto-deployment in the location '" + locationPrefix + "'"; } @Override public String getMsgForResourcesFound(List<String> processExtensionFiles) { return "The following process extension files will be deployed: " + processExtensionFiles; } @Override public void validate(List<Resource> resources) {} }
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\ProcessExtensionResourceFinderDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getNameSrvAddr() { return nameSrvAddr; } public void setNameSrvAddr(String nameSrvAddr) { this.nameSrvAddr = nameSrvAddr; } public String getTestTopic() { return testTopic; } public void setTestTopic(String testTopic) { this.testTopic = testTopic; }
public String getTestGroupId() { return testGroupId; } public void setTestGroupId(String testGroupId) { this.testGroupId = testGroupId; } public String getTestTag() { return testTag; } public void setTestTag(String testTag) { this.testTag = testTag; } }
repos\springBoot-master\springboot-rocketmq-ali\src\main\java\cn\abel\queue\config\ALiMqConfig.java
2
请完成以下Java代码
public static boolean isPangramWithStreams(String str) { if (str == null) return false; // filtered character stream String strUpper = str.toUpperCase(); Stream<Character> filteredCharStream = strUpper.chars() .filter(item -> ((item >= 'A' && item <= 'Z'))) .mapToObj(c -> (char) c); Map<Character, Boolean> alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1)); return (alphabetMap.size() == ALPHABET_COUNT); } public static boolean isPerfectPangram(String str) {
if (str == null) return false; // filtered character stream String strUpper = str.toUpperCase(); Stream<Character> filteredCharStream = strUpper.chars() .filter(item -> ((item >= 'A' && item <= 'Z'))) .mapToObj(c -> (char) c); Map<Character, Long> alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values() .stream() .allMatch(item -> item == 1)); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-5\src\main\java\com\baeldung\pangram\Pangram.java
1
请完成以下Java代码
public void setRate(Rate3 value) { this.rate = value; } /** * Gets the value of the frToDt property. * * @return * possible object is * {@link DateTimePeriodDetails } * */ public DateTimePeriodDetails getFrToDt() { return frToDt; } /** * Sets the value of the frToDt property. * * @param value * allowed object is * {@link DateTimePeriodDetails } * */ public void setFrToDt(DateTimePeriodDetails value) { this.frToDt = value; } /** * Gets the value of the rsn property. * * @return * possible object is * {@link String } * */ public String getRsn() { return rsn; } /** * Sets the value of the rsn property. * * @param value * allowed object is * {@link String } * */ public void setRsn(String value) { this.rsn = value;
} /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxCharges2 } * */ public TaxCharges2 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxCharges2 } * */ public void setTax(TaxCharges2 value) { this.tax = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\InterestRecord1.java
1
请完成以下Java代码
public class ConditionExpressionImpl extends FormalExpressionImpl implements ConditionExpression { protected static Attribute<String> typeAttribute; protected static Attribute<String> camundaResourceAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ConditionExpression.class, BPMN_ELEMENT_CONDITION_EXPRESSION) .namespaceUri(BPMN20_NS) .extendsType(FormalExpression.class) .instanceProvider(new ModelTypeInstanceProvider<ConditionExpression>() { public ConditionExpression newInstance(ModelTypeInstanceContext instanceContext) { return new ConditionExpressionImpl(instanceContext); } }); typeAttribute = typeBuilder.stringAttribute(XSI_ATTRIBUTE_TYPE) .namespace(XSI_NS) .defaultValue("tFormalExpression") .build(); camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE) .namespace(CAMUNDA_NS) .build(); typeBuilder.build(); } public ConditionExpressionImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext); } public String getType() { return typeAttribute.getValue(this); } public void setType(String type) { typeAttribute.setValue(this, type); } public String getCamundaResource() { return camundaResourceAttribute.getValue(this); } public void setCamundaResource(String camundaResource) { camundaResourceAttribute.setValue(this, camundaResource); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConditionExpressionImpl.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Bar other = (Bar) obj; return index == other.index && Objects.equals(name, other.name); } public long getId() { return id; } public int getIndex() { return index; } public String getName() { return name; } @Override public int hashCode() { return Objects.hash(index, name); }
public void setId(final long id) { this.id = id; } public void setIndex(int index) { this.index = index; } public void setName(final String name) { this.name = name; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Bar [name=") .append(name) .append("]"); return builder.toString(); } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Bar.java
1
请完成以下Java代码
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public void setBytes(byte[] bytes) { this.bytes = bytes; } @Override public String toString() { return "ByteArrayEntity[id=" + id + ", name=" + name + ", size=" + (bytes != null ? bytes.length : 0) + "]"; } // Wrapper for a byte array, needed to do byte array comparisons // See https://activiti.atlassian.net/browse/ACT-1524 private static class PersistentState { private final String name; private final byte[] bytes; public PersistentState(String name, byte[] bytes) {
this.name = name; this.bytes = bytes; } public boolean equals(Object obj) { if (obj instanceof PersistentState) { PersistentState other = (PersistentState) obj; return StringUtils.equals(this.name, other.name) && Arrays.equals(this.bytes, other.bytes); } return false; } @Override public int hashCode() { throw new UnsupportedOperationException(); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayEntityImpl.java
1
请完成以下Java代码
protected String doIt() throws Exception { if (p_C_Queue_Processor_ID <= 0) { throw new FillMandatoryException(I_C_Queue_Processor.COLUMNNAME_C_Queue_Processor_ID); } if (action == null) { throw new FillMandatoryException(PARAM_Action); } final I_C_Queue_Processor processorDef = InterfaceWrapperHelper.create(getCtx(), p_C_Queue_Processor_ID, I_C_Queue_Processor.class, ITrx.TRXNAME_None); final IQueueProcessorsExecutor executor = Services.get(IQueueProcessorExecutorService.class).getExecutor(); if (ACTION_START.equals(action)) { executor.addQueueProcessor(processorDef); } else if (ACTION_STOP.equals(action)) {
executor.removeQueueProcessor(p_C_Queue_Processor_ID); } else if (ACTION_RESTART.equals(action)) { executor.removeQueueProcessor(p_C_Queue_Processor_ID); executor.addQueueProcessor(processorDef); } else { throw new AdempiereException("@NotSupported@ @Action@: " + action); } return "OK"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\process\C_Queue_Processor_Manage.java
1
请完成以下Java代码
public void addSourceHU(final @NonNull PPOrderId ppOrderId, final @NonNull HuId huId) { addSourceHUs(ppOrderId, ImmutableSet.of(huId)); } @NonNull private Map<HuId, I_PP_Order_SourceHU> retrieveRecordsIfExist( final @NonNull PPOrderId ppOrderId, final @NonNull Set<HuId> huIds) { return queryBL.createQueryBuilder(I_PP_Order_SourceHU.class) //.addOnlyActiveRecordsFilter() // all .addEqualsFilter(I_PP_Order_SourceHU.COLUMNNAME_PP_Order_ID, ppOrderId) .addInArrayFilter(I_PP_Order_SourceHU.COLUMNNAME_M_HU_ID, huIds) .create() .stream() .collect(ImmutableMap.toImmutableMap(sourceHU -> HuId.ofRepoId(sourceHU.getM_HU_ID()), Function.identity())); } @NonNull public ImmutableSet<HuId> getSourceHUIds(final PPOrderId ppOrderId) {
final List<HuId> huIds = queryBL.createQueryBuilder(I_PP_Order_SourceHU.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_PP_Order_SourceHU.COLUMNNAME_PP_Order_ID, ppOrderId) .create() .listDistinct(I_PP_Order_SourceHU.COLUMNNAME_M_HU_ID, HuId.class); return ImmutableSet.copyOf(huIds); } @NonNull private I_PP_Order_SourceHU initRecord(@NonNull final HuId huId, @NonNull final PPOrderId ppOrderId) { final I_PP_Order_SourceHU record = InterfaceWrapperHelper.newInstance(I_PP_Order_SourceHU.class); record.setPP_Order_ID(ppOrderId.getRepoId()); record.setM_HU_ID(huId.getRepoId()); return record; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHURepository.java
1
请完成以下Java代码
public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public Object getPersistentState() { return ResourceEntity.class; } public void setGenerated(boolean generated) { this.generated = generated; } /** * Indicated whether or not the resource has been generated while deploying rather than * being actual part of the deployment. */ public boolean isGenerated() { return generated; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Date getCreateTime() {
return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", name=" + name + ", deploymentId=" + deploymentId + ", generated=" + generated + ", tenantId=" + tenantId + ", type=" + type + ", createTime=" + createTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ResourceEntity.java
1
请完成以下Java代码
public class ExternalTaskDto { protected String activityId; protected String activityInstanceId; protected String errorMessage; protected String executionId; protected String id; protected Date lockExpirationTime; private Date createTime; protected String processDefinitionId; protected String processDefinitionKey; protected String processDefinitionVersionTag; protected String processInstanceId; protected Integer retries; protected boolean suspended; protected String workerId; protected String topicName; protected String tenantId; protected long priority; protected String businessKey; public String getActivityId() { return activityId; } public String getActivityInstanceId() { return activityInstanceId; } public String getErrorMessage() { return errorMessage; } public String getExecutionId() { return executionId; } public String getId() { return id; } public Date getLockExpirationTime() { return lockExpirationTime; } public Date getCreateTime() { return createTime; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionVersionTag() { return processDefinitionVersionTag; } public String getProcessInstanceId() { return processInstanceId; } public Integer getRetries() { return retries;
} public boolean isSuspended() { return suspended; } public String getWorkerId() { return workerId; } public String getTopicName() { return topicName; } public String getTenantId() { return tenantId; } public long getPriority() { return priority; } public String getBusinessKey() { return businessKey; } public static ExternalTaskDto fromExternalTask(ExternalTask task) { ExternalTaskDto dto = new ExternalTaskDto(); dto.activityId = task.getActivityId(); dto.activityInstanceId = task.getActivityInstanceId(); dto.errorMessage = task.getErrorMessage(); dto.executionId = task.getExecutionId(); dto.id = task.getId(); dto.lockExpirationTime = task.getLockExpirationTime(); dto.createTime = task.getCreateTime(); dto.processDefinitionId = task.getProcessDefinitionId(); dto.processDefinitionKey = task.getProcessDefinitionKey(); dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); dto.processInstanceId = task.getProcessInstanceId(); dto.retries = task.getRetries(); dto.suspended = task.isSuspended(); dto.topicName = task.getTopicName(); dto.workerId = task.getWorkerId(); dto.tenantId = task.getTenantId(); dto.priority = task.getPriority(); dto.businessKey = task.getBusinessKey(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\ExternalTaskDto.java
1
请完成以下Java代码
private boolean isLookupsAppendDescriptionToName() { return sysConfigBL.getBooleanValue(SYSCONFIG_LookupAppendDescriptionToName, true); } private JSONLookupValuesList toJSONLookupValuesList(final LookupValuesList lookupValuesList) { return JSONLookupValuesList.ofLookupValuesList(lookupValuesList, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } private JSONLookupValue toJSONLookupValue(final LookupValue lookupValue) { return JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language(), isLookupsAppendDescriptionToName()); } @GetMapping("/{asiDocId}/field/{attributeName}/dropdown") public JSONLookupValuesList getAttributeDropdown( @PathVariable("asiDocId") final String asiDocIdStr, @PathVariable("attributeName") final String attributeName) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return forASIDocumentReadonly(asiDocId, asiDoc -> asiDoc.getFieldLookupValues(attributeName)) .transform(this::toJSONLookupValuesList); } @PostMapping(value = "/{asiDocId}/complete") public JSONLookupValue complete( @PathVariable("asiDocId") final String asiDocIdStr, @RequestBody final JSONCompleteASIRequest request) { userSession.assertLoggedIn(); final DocumentId asiDocId = DocumentId.of(asiDocIdStr); return Execution.callInNewExecution("complete", () -> completeInTrx(asiDocId, request)) .transform(this::toJSONLookupValue);
} private LookupValue completeInTrx(final DocumentId asiDocId, final JSONCompleteASIRequest request) { return asiRepo.forASIDocumentWritable( asiDocId, NullDocumentChangesCollector.instance, documentsCollection, asiDoc -> { final List<JSONDocumentChangedEvent> events = request.getEvents(); if (events != null && !events.isEmpty()) { asiDoc.processValueChanges(events, REASON_ProcessASIDocumentChanges); } return asiDoc.complete(); }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRestController.java
1
请在Spring Boot框架中完成以下Java代码
public class ImmutableCredentials { private final String authMethod; private final String username; private final String password; @ConstructorBinding public ImmutableCredentials(String authMethod, String username, String password) { this.authMethod = authMethod; this.username = username; this.password = password; } public ImmutableCredentials(String username, String password) { this.username = username; this.password = password;
this.authMethod = "Default"; } public String getAuthMethod() { return authMethod; } public String getUsername() { return username; } public String getPassword() { return password; } }
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\ImmutableCredentials.java
2
请在Spring Boot框架中完成以下Java代码
public String deleteItem(@RequestBody ItemRequest request, @SessionAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART) List<Product> shoppingCart) { Optional<Product> optional = getProductById(products.stream(), request.getId()); if (optional.isPresent()) { Product product = optional.get(); Optional<Product> productInCart = getProductById(shoppingCart.stream(), product.getId()); if(productInCart.isPresent()) { shoppingCart.remove(productInCart.get()); pusher.trigger(PusherConstants.CHANNEL_NAME, "itemRemoved", product); } } return "OK"; } /** * Method that empties the shopping cart * @param model Object from Spring MVC * @return Status string */ @RequestMapping(value = "/cart", method = RequestMethod.DELETE) public String emptyCart(Model model) { model.addAttribute(GeneralConstants.ID_SESSION_SHOPPING_CART, new ArrayList<Product>()); pusher.trigger(PusherConstants.CHANNEL_NAME, "cartEmptied", ""); return "OK";
} /** * Gets a product by its id from a stream * @param stream That contains the product to get * @param id Of the product to get * @return The product wrapped in an Optional object */ private Optional<Product> getProductById(Stream<Product> stream, Long id) { return stream .filter(product -> product.getId().equals(id)) .findFirst(); } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-ShoppingCard\fullstack\backend\src\main\java\com\urunov\controller\web\CartController.java
2
请在Spring Boot框架中完成以下Java代码
public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } /** * Status AD_Reference_ID=541890 * Reference name: C_POS_Order_Status */ public static final int STATUS_AD_Reference_ID=541890; /** Drafted = DR */ public static final String STATUS_Drafted = "DR"; /** WaitingPayment = WP */ public static final String STATUS_WaitingPayment = "WP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; /** Voided = VO */ public static final String STATUS_Voided = "VO"; /** Closed = CL */ public static final String STATUS_Closed = "CL"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() {
return get_ValueAsString(COLUMNNAME_Status); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_Value (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Order.java
2
请完成以下Java代码
public class Customer { private int id; private String name; public Customer(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public int hashCode() {
return id * 20; } @Override public boolean equals(Object obj) { if (obj instanceof Customer) { Customer otherCustomer = (Customer) obj; if (id == otherCustomer.id) return true; } return false; } }
repos\tutorials-master\core-java-modules\core-java-collections-list\src\main\java\com\baeldung\findanelement\Customer.java
1
请完成以下Java代码
public Authentication getAuthentication() { return this.authentication; } public ClientRegistration getClientRegistration() { return this.clientRegistration; } } /** * Default {@link Converter} for redirect uri resolving. * * @since 6.5 */ private final class DefaultRedirectUriResolver implements Converter<RedirectUriParameters, Mono<String>> { @Override
public Mono<String> convert(RedirectUriParameters redirectUriParameters) { // @formatter:off return Mono.just(redirectUriParameters.authentication) .flatMap((authentication) -> { URI endSessionEndpoint = endSessionEndpoint(redirectUriParameters.clientRegistration); if (endSessionEndpoint == null) { return Mono.empty(); } String idToken = idToken(authentication); String postLogoutRedirectUri = postLogoutRedirectUri( redirectUriParameters.serverWebExchange.getRequest(), redirectUriParameters.clientRegistration); return Mono.just(endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri)); }); // @formatter:on } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\web\server\logout\OidcClientInitiatedServerLogoutSuccessHandler.java
1
请完成以下Java代码
public void setPriorityNo (int PriorityNo) { set_Value (COLUMNNAME_PriorityNo, Integer.valueOf(PriorityNo)); } /** Get Relative Priorität. @return Where inventory should be picked from first */ @Override public int getPriorityNo () { Integer ii = (Integer)get_Value(COLUMNNAME_PriorityNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } /** Set Gang. @param X X-Dimension, z.B. Gang */ @Override public void setX (java.lang.String X) { set_Value (COLUMNNAME_X, X); } /** Get Gang. @return X-Dimension, z.B. Gang */ @Override public java.lang.String getX () { return (java.lang.String)get_Value(COLUMNNAME_X); } /** Set Regal. @param X1 Regal */ @Override public void setX1 (java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } /** Get Regal. @return Regal */
@Override public java.lang.String getX1 () { return (java.lang.String)get_Value(COLUMNNAME_X1); } /** Set Fach. @param Y Y-Dimension, z.B. Fach */ @Override public void setY (java.lang.String Y) { set_Value (COLUMNNAME_Y, Y); } /** Get Fach. @return Y-Dimension, z.B. Fach */ @Override public java.lang.String getY () { return (java.lang.String)get_Value(COLUMNNAME_Y); } /** Set Ebene. @param Z Z-Dimension, z.B. Ebene */ @Override public void setZ (java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } /** Get Ebene. @return Z-Dimension, z.B. Ebene */ @Override public java.lang.String getZ () { return (java.lang.String)get_Value(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Locator.java
1
请在Spring Boot框架中完成以下Java代码
public void post() throws URISyntaxException { TestDTO td = new TestDTO(); td.setId(1); td.setName("post"); String url = HOST + POST_URL; HttpHeaders headers = new HttpHeaders(); HttpEntity<TestDTO> httpEntity = new HttpEntity<>(td, headers); ResponseEntity<TestDTO> responseEntity = this.restTemplate.postForEntity(url, httpEntity, TestDTO.class); System.out.println("postForEntity: " + responseEntity.getBody()); TestDTO testDTO = this.restTemplate.postForObject(url, httpEntity, TestDTO.class); System.out.println("postForObject: " + testDTO); ResponseEntity<TestDTO> exchange = this.restTemplate.exchange(url, HttpMethod.POST, httpEntity, TestDTO.class);
System.out.println("exchange: " + exchange.getBody()); } public void post4Form() { String url = HOST + POST_PARAM_URL; HttpHeaders headers = new HttpHeaders(); MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("id", "100"); map.add("name", "post4Form"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, request, String.class); System.out.println("postForEntity: " + responseEntity.getBody()); } }
repos\spring-boot-quick-master\quick-rest-template\src\main\java\com\rest\template\service\RestService.java
2
请完成以下Java代码
private IPricingContext createPricingContext( @NonNull final ProductId productId, @NonNull final BPartnerId vendorId, @NonNull final LocalDate date) { final CountryId countryId = bpartnersRepo.getDefaultShipToLocationCountryIdOrNull(vendorId); final IEditablePricingContext pricingCtx = pricingBL.createPricingContext(); pricingCtx.setProductId(productId); pricingCtx.setQty(BigDecimal.ONE); pricingCtx.setBPartnerId(vendorId); pricingCtx.setCountryId(countryId); pricingCtx.setSOTrx(SOTrx.PURCHASE); pricingCtx.setPriceDate(date); return pricingCtx;
} @Override public PurchaseProfitInfo convertToCurrency(@NonNull final PurchaseProfitInfo profitInfo, @NonNull final CurrencyId currencyIdTo) { return profitInfo.toBuilder() .profitSalesPriceActual(convertToCurrency(profitInfo.getProfitSalesPriceActual(), currencyIdTo)) .profitPurchasePriceActual(convertToCurrency(profitInfo.getProfitPurchasePriceActual(), currencyIdTo)) .purchasePriceActual(convertToCurrency(profitInfo.getPurchasePriceActual(), currencyIdTo)) .build(); } private final Optional<Money> convertToCurrency(final Optional<Money> optionalPrice, final CurrencyId currencyIdTo) { return optionalPrice.map(price -> moneyService.convertMoneyToCurrency(price, currencyIdTo)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\grossprofit\PurchaseProfitInfoServiceImpl.java
1
请完成以下Java代码
public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Anfangsdatum. @param StartDate First effective day (inclusive) */
@Override public void setStartDate (java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Anfangsdatum. @return First effective day (inclusive) */ @Override public java.sql.Timestamp getStartDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_I_Flatrate_Term.java
1
请完成以下Java代码
public void setR_Status(org.compiere.model.I_R_Status R_Status) { set_ValueFromPO(COLUMNNAME_R_Status_ID, org.compiere.model.I_R_Status.class, R_Status); } /** Set Status. @param R_Status_ID Request Status */ @Override public void setR_Status_ID (int R_Status_ID) { if (R_Status_ID < 1) set_Value (COLUMNNAME_R_Status_ID, null); else set_Value (COLUMNNAME_R_Status_ID, Integer.valueOf(R_Status_ID)); } /** Get Status. @return Request Status */ @Override public int getR_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Anfrageart. @param RequestType Anfrageart */ @Override public void setRequestType (java.lang.String RequestType) { set_Value (COLUMNNAME_RequestType, RequestType); } /** Get Anfrageart. @return Anfrageart */ @Override public java.lang.String getRequestType () { return (java.lang.String)get_Value(COLUMNNAME_RequestType); } /** Set Ergebnis. @param Result Result of the action taken */ @Override public void setResult (java.lang.String Result) { set_Value (COLUMNNAME_Result, Result); } /** Get Ergebnis. @return Result of the action taken */ @Override public java.lang.String getResult () { return (java.lang.String)get_Value(COLUMNNAME_Result); } /** Set Status. @param Status Status */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status);
} /** Set Summary. @param Summary Textual summary of this request */ @Override public void setSummary (java.lang.String Summary) { set_Value (COLUMNNAME_Summary, Summary); } /** Get Summary. @return Textual summary of this request */ @Override public java.lang.String getSummary () { return (java.lang.String)get_Value(COLUMNNAME_Summary); } /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Request.java
1
请完成以下Java代码
public static Optional<ProductId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} public static Set<ProductId> ofRepoIds(final Collection<Integer> repoIds) { return repoIds.stream() .filter(repoId -> repoId != null && repoId > 0) .map(ProductId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } public static int toRepoId(@Nullable final ProductId productId) { return productId != null ? productId.getRepoId() : -1; } public static Set<Integer> toRepoIds(final Collection<ProductId> productIds) { return productIds.stream() .filter(Objects::nonNull) .map(ProductId::toRepoId) .collect(ImmutableSet.toImmutableSet()); } public static boolean equals(@Nullable final ProductId o1, @Nullable final ProductId o2) { return Objects.equals(o1, o2); } private ProductId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "productId"); } @Override @JsonValue public int getRepoId() { return repoId; } public String getAsString() {return String.valueOf(getRepoId());} public TableRecordReference toTableRecordReference() { return TableRecordReference.of(I_M_Product.Table_Name, getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\product\ProductId.java
1
请在Spring Boot框架中完成以下Java代码
public void newAuthor() { Book book = new Book(); book.setIsbn("001-JN"); book.setTitle("A History of Ancient Prague"); book.setPrice(45); Author author = new Author(); author.setName("Joana Nimar"); author.setAge(34); author.setGenre("History"); author.setBook(book); authorRepository.save(author); } public void byName() {
Author author = authorRepository.findByName("Joana Nimar"); System.out.println(author); } public void byNameIsbn() { Author author = authorRepository.findByBookIsbn("001-JN"); System.out.println(author); } public void byBookIsbnNativeQuery() { Author author = authorRepository.findByBookIsbnNativeQuery("001-JN"); System.out.println(author); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootJsonToMySQL\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
private static byte[] toByteArray(final List<String> lines) { try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) { lines.stream() .map(s -> s + "\n") .map(s -> s.getBytes(StandardCharsets.UTF_8)) .forEach(bytes -> { try { out.write(bytes); } catch (final IOException ex) { // shall never happen throw AdempiereException.wrapIfNeeded(ex); } }); return out.toByteArray();
} catch (final IOException ex) { // shall never happen throw AdempiereException.wrapIfNeeded(ex); } } private void deleteScript(@NonNull final Path scriptPath) { try { Files.delete(scriptPath); } catch (final IOException ex) { throw new AdempiereException("Failed deleting " + scriptPath, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\rest\MigrationScriptRestControllerTemplate.java
1
请完成以下Java代码
public void setLine (final int Line) { set_Value (COLUMNNAME_Line, Line); } @Override public int getLine() { return get_ValueAsInt(COLUMNNAME_Line); } @Override public void setOpenAmt (final BigDecimal OpenAmt) { set_ValueNoCheck (COLUMNNAME_OpenAmt, OpenAmt); } @Override public BigDecimal getOpenAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPayAmt (final BigDecimal PayAmt) { set_Value (COLUMNNAME_PayAmt, PayAmt); } @Override public BigDecimal getPayAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PayAmt); return bd != null ? bd : BigDecimal.ZERO; } /** * PaymentRule AD_Reference_ID=195 * Reference name: _Payment Rule */ public static final int PAYMENTRULE_AD_Reference_ID=195; /** Cash = B */ public static final String PAYMENTRULE_Cash = "B"; /** CreditCard = K */ public static final String PAYMENTRULE_CreditCard = "K"; /** DirectDeposit = T */ public static final String PAYMENTRULE_DirectDeposit = "T"; /** Check = S */ public static final String PAYMENTRULE_Check = "S";
/** OnCredit = P */ public static final String PAYMENTRULE_OnCredit = "P"; /** DirectDebit = D */ public static final String PAYMENTRULE_DirectDebit = "D"; /** Mixed = M */ public static final String PAYMENTRULE_Mixed = "M"; /** PayPal = L */ public static final String PAYMENTRULE_PayPal = "L"; /** PayPal Extern = V */ public static final String PAYMENTRULE_PayPalExtern = "V"; /** Kreditkarte Extern = U */ public static final String PAYMENTRULE_KreditkarteExtern = "U"; /** Sofortüberweisung = R */ public static final String PAYMENTRULE_Sofortueberweisung = "R"; /** Rückerstattung = E */ public static final String PAYMENTRULE_Rueckerstattung = "E"; /** Verrechnung = F */ public static final String PAYMENTRULE_Verrechnung = "F"; @Override public void setPaymentRule (final java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } @Override public java.lang.String getPaymentRule() { return get_ValueAsString(COLUMNNAME_PaymentRule); } @Override public void setReference (final @Nullable java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } @Override public java.lang.String getReference() { return get_ValueAsString(COLUMNNAME_Reference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelectionLine.java
1
请完成以下Java代码
public PageData<DeviceProfile> findByTenantId(UUID tenantId, PageLink pageLink) { return findDeviceProfiles(TenantId.fromUUID(tenantId), pageLink); } @Override public DeviceProfileId getExternalIdByInternal(DeviceProfileId internalId) { return Optional.ofNullable(deviceProfileRepository.getExternalIdById(internalId.getId())) .map(DeviceProfileId::new).orElse(null); } @Override public DeviceProfile findDefaultEntityByTenantId(UUID tenantId) { return findDefaultDeviceProfile(TenantId.fromUUID(tenantId)); } @Override public List<DeviceProfileInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) { return deviceProfileRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, PageRequest.of(0, limit)); } @Override
public List<DeviceProfileInfo> findByImageLink(String imageLink, int limit) { return deviceProfileRepository.findByImageLink(imageLink, PageRequest.of(0, limit)); } @Override public PageData<DeviceProfile> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findDeviceProfiles(tenantId, pageLink); } @Override public List<DeviceProfileFields> findNextBatch(UUID id, int batchSize) { return deviceProfileRepository.findNextBatch(id, Limit.of(batchSize)); } @Override public EntityType getEntityType() { return EntityType.DEVICE_PROFILE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceProfileDao.java
1
请完成以下Java代码
public Set<Map.Entry<String, Object>> entrySet() { return null; } @Override public Object get(Object key) { return null; } @Override public boolean isEmpty() { return false; } @Override public Set<String> keySet() { return null; } @Override public Object put(String key, Object value) { return null; }
@Override public void putAll(Map<? extends String, ? extends Object> m) { } @Override public Object remove(Object key) { return null; } @Override public int size() { return 0; } @Override public Collection<Object> values() { return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormData.java
1
请完成以下Java代码
private ImmutableSet<String> getAvailableDocActions(final IValidationContext evalCtx) { final DocActionOptionsContext optionsCtx = DocActionOptionsContext.builder() .userRolePermissionsKey(extractUserRolePermissionsKey(evalCtx)) .tableName(extractContextTableName(evalCtx)) .docStatus(extractDocStatus(evalCtx)) .docTypeId(extractDocTypeId(evalCtx)) .processing(extractProcessing(evalCtx)) .orderType(extractOrderType(evalCtx)) .soTrx(extractSOTrx(evalCtx)) .validationContext(evalCtx) .build(); final IDocActionOptionsBL docActionOptionsBL = Services.get(IDocActionOptionsBL.class); docActionOptionsBL.updateDocActions(optionsCtx); return optionsCtx.getDocActions(); } private static UserRolePermissionsKey extractUserRolePermissionsKey(final IValidationContext evalCtx) { return UserRolePermissionsKey.fromEvaluatee(evalCtx, LookupDataSourceContext.PARAM_UserRolePermissionsKey.getName()); } private static String extractContextTableName(final IValidationContext evalCtx) { final String contextTableName = evalCtx.get_ValueAsString(IValidationContext.PARAMETER_ContextTableName); if (Check.isEmpty(contextTableName)) { throw new AdempiereException("Failed getting " + IValidationContext.PARAMETER_ContextTableName + " from " + evalCtx); } return contextTableName; } private static String extractDocStatus(final IValidationContext evalCtx) { return evalCtx.get_ValueAsString(WindowConstants.FIELDNAME_DocStatus); } private static DocTypeId extractDocTypeId(final IValidationContext evalCtx) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(evalCtx.get_ValueAsInt(WindowConstants.FIELDNAME_C_DocType_ID, -1)); if (docTypeId != null) { return docTypeId; } return DocTypeId.ofRepoIdOrNull(evalCtx.get_ValueAsInt(WindowConstants.FIELDNAME_C_DocTypeTarget_ID, -1)); } private static SOTrx extractSOTrx(final IValidationContext evalCtx) { return SOTrx.ofBoolean(evalCtx.get_ValueAsBoolean(WindowConstants.FIELDNAME_IsSOTrx, false));
} private static boolean extractProcessing(final IValidationContext evalCtx) { final Boolean valueAsBoolean = evalCtx.get_ValueAsBoolean(WindowConstants.FIELDNAME_Processing, false); return valueAsBoolean != null && valueAsBoolean; } private static String extractOrderType(final IValidationContext evalCtx) { return evalCtx.get_ValueAsString(WindowConstants.FIELDNAME_OrderType); } @Override public Set<String> getParameters(@Nullable final String contextTableName) { final HashSet<String> parameters = new HashSet<>(PARAMETERS); final IDocActionOptionsBL docActionOptionsBL = Services.get(IDocActionOptionsBL.class); parameters.addAll(docActionOptionsBL.getRequiredParameters(contextTableName)); return parameters; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\DocActionValidationRule.java
1
请完成以下Java代码
public void setDiscontinued(final Boolean discontinued) { this.discontinued = discontinued; this.discontinuedSet = true; } public void setDiscontinuedFrom(final LocalDate discontinuedFrom) { this.discontinuedFrom = discontinuedFrom; this.discontinuedFromSet = true; } public void setActive(final Boolean active) { this.active = active; this.activeSet = true; } public void setStocked(final Boolean stocked) { this.stocked = stocked; this.stockedSet = true; } public void setProductCategoryIdentifier(final String productCategoryIdentifier) { this.productCategoryIdentifier = productCategoryIdentifier; this.productCategoryIdentifierSet = true; } public void setSyncAdvise(final SyncAdvise syncAdvise) {
this.syncAdvise = syncAdvise; } public void setBpartnerProductItems(final List<JsonRequestBPartnerProductUpsert> bpartnerProductItems) { this.bpartnerProductItems = bpartnerProductItems; } public void setProductTaxCategories(final List<JsonRequestProductTaxCategoryUpsert> productTaxCategories) { this.productTaxCategories = productTaxCategories; } public void setUomConversions(final List<JsonRequestUOMConversionUpsert> uomConversions) { this.uomConversions = uomConversions; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProduct.java
1
请完成以下Java代码
public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setScrappedQty (final @Nullable BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); } @Override public BigDecimal getScrappedQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ScrappedQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTargetQty (final @Nullable BigDecimal TargetQty) { set_Value (COLUMNNAME_TargetQty, TargetQty); } @Override public BigDecimal getTargetQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TargetQty); return bd != null ? bd : BigDecimal.ZERO; } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) {
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_OrderLine.java
1
请完成以下Java代码
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { if (StringUtils.equalsIgnoreCase("/login", httpServletRequest.getRequestURI()) && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) { try { validateCode(new ServletWebRequest(httpServletRequest)); } catch (ValidateCodeException e) { authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e); return; } } filterChain.doFilter(httpServletRequest, httpServletResponse); } private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException { ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE); String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode"); if (StringUtils.isBlank(codeInRequest)) { throw new ValidateCodeException("验证码不能为空!"); }
if (codeInSession == null) { throw new ValidateCodeException("验证码不存在!"); } if (codeInSession.isExpire()) { sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE); throw new ValidateCodeException("验证码已过期!"); } if (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), codeInRequest)) { throw new ValidateCodeException("验证码不正确!"); } sessionStrategy.removeAttribute(servletWebRequest, ValidateController.SESSION_KEY_IMAGE_CODE); } }
repos\SpringAll-master\36.Spring-Security-ValidateCode\src\main\java\cc\mrbird\validate\code\ValidateCodeFilter.java
1
请在Spring Boot框架中完成以下Java代码
protected static void validateJsonStructure(JsonNode expectedNode, JsonNode actualNode) { Set<String> expectedFields = new HashSet<>(); Iterator<String> fieldsIterator = expectedNode.fieldNames(); while (fieldsIterator.hasNext()) { expectedFields.add(fieldsIterator.next()); } Set<String> actualFields = new HashSet<>(); fieldsIterator = actualNode.fieldNames(); while (fieldsIterator.hasNext()) { actualFields.add(fieldsIterator.next()); } if (!expectedFields.containsAll(actualFields) || !actualFields.containsAll(expectedFields)) { throw new DataValidationException("Provided json structure is different from stored one '" + actualNode + "'!"); } } protected static void validateQueueName(String name) { validateQueueNameOrTopic(name, NAME); if (DataConstants.CF_QUEUE_NAME.equals(name) || DataConstants.CF_STATES_QUEUE_NAME.equals(name)) { throw new DataValidationException(String.format("The queue name '%s' is not allowed. This name is reserved for internal use. Please choose a different name.", name)); } } protected static void validateQueueTopic(String topic) { validateQueueNameOrTopic(topic, TOPIC); } static void validateQueueNameOrTopic(String value, String fieldName) { if (StringUtils.isEmpty(value) || value.trim().length() == 0) { throw new DataValidationException(String.format("Queue %s should be specified!", fieldName)); } if (!QUEUE_PATTERN.matcher(value).matches()) { throw new DataValidationException(
String.format("Queue %s contains a character other than ASCII alphanumerics, '.', '_' and '-'!", fieldName)); } } public static boolean isValidDomain(String domainName) { if (domainName == null) { return false; } if (LOCALHOST_PATTERN.matcher(domainName).matches()) { return true; } return DOMAIN_PATTERN.matcher(domainName).matches(); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\DataValidator.java
2
请在Spring Boot框架中完成以下Java代码
private Claims getAllClaimsFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Boolean ignoreTokenExpiration(String token) { // here you specify tokens, for that the expiration is ignored return false; } public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername()); }
private String doGenerateToken(Map<String, Object> claims, String subject) { return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact(); } public Boolean canTokenBeRefreshed(String token) { return (!isTokenExpired(token) || ignoreTokenExpiration(token)); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } }
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-boot-jwt-without-JPA\spring-boot-jwt\src\main\java\com\javainuse\config\JwtTokenUtil.java
2
请在Spring Boot框架中完成以下Java代码
public String getIPASSCC18() { return ipasscc18; } /** * Sets the value of the ipasscc18 property. * * @param value * allowed object is * {@link String } * */ public void setIPASSCC18(String value) { this.ipasscc18 = value; } /** * Gets the value of the mhuPackagingCodeText property. * * @return * possible object is * {@link String } * */ public String getMHUPackagingCodeText() { return mhuPackagingCodeText; } /** * Sets the value of the mhuPackagingCodeText property. * * @param value * allowed object is * {@link String } * */ public void setMHUPackagingCodeText(String value) { this.mhuPackagingCodeText = value; } /** * Gets the value of the ediExpDesadvPackItem property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the ediExpDesadvPackItem property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEDIExpDesadvPackItem().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EDIExpDesadvPackItemType } * * */ public List<EDIExpDesadvPackItemType> getEDIExpDesadvPackItem() { if (ediExpDesadvPackItem == null) { ediExpDesadvPackItem = new ArrayList<EDIExpDesadvPackItemType>(); } return this.ediExpDesadvPackItem; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvPackType.java
2
请完成以下Java代码
public class OffsetBasedPageable implements Pageable { private final int limit; private final int offset; private final Sort sort; private OffsetBasedPageable(int limit, int offset, Sort sort) { if (limit < 1) { throw new IllegalArgumentException("Limit must not be less than one"); } if (offset < 0) { throw new IllegalArgumentException("Offset index must not be less than zero"); } this.limit = limit; this.offset = offset; this.sort = sort; } public static Pageable of(int limit, int offset) { return new OffsetBasedPageable(limit, offset, Sort.unsorted()); } public static Pageable of(int limit, int offset, Sort sort) { return new OffsetBasedPageable(limit, offset, sort); } @Override public int getPageNumber() { throw unsupportedOperation(); } @Override public int getPageSize() { return limit; } @Override public long getOffset() { return offset; } @Override
public Sort getSort() { return sort; } @Override public Pageable next() { throw unsupportedOperation(); } @Override public Pageable previousOrFirst() { throw unsupportedOperation(); } @Override public Pageable first() { throw unsupportedOperation(); } @Override public Pageable withPage(int pageNumber) { throw unsupportedOperation(); } @Override public boolean hasPrevious() { throw unsupportedOperation(); } private UnsupportedOperationException unsupportedOperation() { return new UnsupportedOperationException("OffsetBasedPageable has no pages. Contains only offset and page size"); } }
repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\lib\OffsetBasedPageable.java
1
请完成以下Java代码
public static WFActivityStatus computeActivityState(final HUConsolidationJob ignoredJob) { // TODO return WFActivityStatus.NOT_STARTED; } private JsonHUConsolidationJob toJson(@NonNull final HUConsolidationJob job) { final RenderedAddressProvider renderedAddressProvider = documentLocationBL.newRenderedAddressProvider(); final String shipToAddress = renderedAddressProvider.getAddress(job.getShipToBPLocationId()); return JsonHUConsolidationJob.builder() .id(job.getId()) .shipToAddress(shipToAddress) .pickingSlots(toJsonHUConsolidationJobPickingSlots(job.getPickingSlotIds())) .currentTarget(JsonHUConsolidationTarget.ofNullable(job.getCurrentTarget())) .build(); } private ImmutableList<JsonHUConsolidationJobPickingSlot> toJsonHUConsolidationJobPickingSlots(final Set<PickingSlotId> pickingSlotIds) {
if (pickingSlotIds.isEmpty()) { return ImmutableList.of(); } final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions = pickingSlotService.getPickingSlotIdAndCaptions(pickingSlotIds); final PickingSlotQueuesSummary summary = pickingSlotService.getNotEmptyQueuesSummary(PickingSlotQueueQuery.onlyPickingSlotIds(pickingSlotIds)); return pickingSlotIdAndCaptions.stream() .map(pickingSlotIdAndCaption -> JsonHUConsolidationJobPickingSlot.builder() .pickingSlotId(pickingSlotIdAndCaption.getPickingSlotId()) .pickingSlotQRCode(PickingSlotQRCode.ofPickingSlotIdAndCaption(pickingSlotIdAndCaption).toPrintableQRCode().toJsonDisplayableQRCode()) .countHUs(summary.getCountHUs(pickingSlotIdAndCaption.getPickingSlotId()).orElse(0)) .build()) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\workflows_api\activity_handlers\HUConsolidateWFActivityHandler.java
1
请完成以下Java代码
public void onDelete(final I_M_InOut inoutRecord) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord)) { if (!inoutRecord.isSOTrx()) { return; } final IShipmentScheduleInvalidateBL shipmentScheduleInvalidateBL = Services.get(IShipmentScheduleInvalidateBL.class); shipmentScheduleInvalidateBL.invalidateJustForLines(inoutRecord); // make sure that at least the lines themselves are invalidated shipmentScheduleInvalidateBL.notifySegmentsChangedForShipment(inoutRecord); } } @ModelChange(// timings = ModelValidator.TYPE_AFTER_CHANGE, // note: on AFTER_NEW, there can't be any M_ShipmentSchedule_QtyPicked records to update yet, so we don't have to fire ifColumnsChanged = I_M_InOut.COLUMNNAME_Processed) public void updateM_ShipmentSchedule_QtyPicked_Processed(final I_M_InOut inoutRecord) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord))
{ if (!inoutRecord.isSOTrx()) { return; } final IShipmentScheduleAllocDAO shipmentScheduleAllocDAO = Services.get(IShipmentScheduleAllocDAO.class); shipmentScheduleAllocDAO.updateM_ShipmentSchedule_QtyPicked_ProcessedForShipment(inoutRecord); } } @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void closePartiallyShipped_ShipmentSchedules(@NonNull final I_M_InOut inoutRecord) { try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inoutRecord)) { Services.get(IShipmentScheduleBL.class).closePartiallyShipped_ShipmentSchedules(inoutRecord); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_InOut_Shipment.java
1
请完成以下Java代码
public IView createView(@NonNull final CreateViewRequest request) { final ViewId viewId = request.getViewId(); if (!PickingConstants.WINDOWID_PickingView.equals(viewId.getWindowId())) { throw new IllegalArgumentException("Invalid request's windowId: " + request); } final Set<ShipmentScheduleId> shipmentScheduleIds = extractShipmentScheduleIds(request); final PackageableRowsData rowsData = pickingViewRepo.createRowsData(viewId, shipmentScheduleIds); return PackageableView.builder() .viewId(viewId) .rowsData(rowsData) .pickingCandidateService(pickingCandidateService) .barcodeFilterData(extractProductBarcodeFilterData(request).orElse(null)) .build(); } @Builder(builderMethodName = "createViewRequest", builderClassName = "$CreateViewRequestBuilder") private static CreateViewRequest createCreateViewRequest( @NonNull final List<ShipmentScheduleId> shipmentScheduleIds, @Nullable final ProductBarcodeFilterData barcodeFilterData) {
Check.assumeNotEmpty(shipmentScheduleIds, "shipmentScheduleIds"); return CreateViewRequest.builder(PickingConstants.WINDOWID_PickingView) .setFilterOnlyIds(RepoIdAwares.asRepoIds(shipmentScheduleIds)) .setParameter(VIEWPARAM_ProductBarcodeFilterData, barcodeFilterData) .build(); } private static Set<ShipmentScheduleId> extractShipmentScheduleIds(@NonNull final CreateViewRequest request) { return request.getFilterOnlyIds() .stream() .map(ShipmentScheduleId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } private static Optional<ProductBarcodeFilterData> extractProductBarcodeFilterData(@NonNull final CreateViewRequest request) { return Optional.ofNullable(request.getParameterAs(VIEWPARAM_ProductBarcodeFilterData, ProductBarcodeFilterData.class)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableViewFactory.java
1
请完成以下Java代码
public boolean isAuthorized() { return authorizationId != null; } public URL getPayerApproveUrl() { if (payerApproveUrlString == null) { throw new AdempiereException("No payer url"); } try { return new URL(payerApproveUrlString); } catch (MalformedURLException e)
{ throw AdempiereException.wrapIfNeeded(e); } } public PayPalOrder withId(@NonNull final PayPalOrderId id) { if (Objects.equals(this.id, id)) { return this; } else { return toBuilder().id(id).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrder.java
1
请在Spring Boot框架中完成以下Java代码
public CurrencyId getCurrencyId() { return pricingInfo.getCurrencyId(); } public OrderLineDetailCreateRequest computeOrderLineDetailCreateRequest(final ServiceRepairProjectCostCollector costCollector) { final Quantity qty = costCollector.getQtyReservedOrConsumed(); // // Price & Amount precision final Money price; final CurrencyPrecision amountPrecision; if (costCollector.getType().isZeroPrice()) { price = Money.zero(getCurrencyId()); amountPrecision = CurrencyPrecision.TWO; } else { final IPricingResult pricingResult = calculatePrice(costCollector); price = pricingResult.getPriceStdAsMoney(); amountPrecision = pricingResult.getPrecision(); } return OrderLineDetailCreateRequest.builder() .productId(costCollector.getProductId()) .qty(qty) .price(price) .amount(price.multiply(qty.toBigDecimal()).round(amountPrecision)) .build(); } public IPricingResult calculatePrice(@NonNull final ServiceRepairProjectCostCollector costCollector) { final IEditablePricingContext pricingCtx = createPricingContext(costCollector) .setFailIfNotCalculated(); try
{ return pricingBL.calculatePrice(pricingCtx); } catch (final Exception ex) { throw AdempiereException.wrapIfNeeded(ex) .setParameter("pricingInfo", pricingInfo) .setParameter("pricingContext", pricingCtx) .setParameter("costCollector", costCollector); } } private IEditablePricingContext createPricingContext( @NonNull final ServiceRepairProjectCostCollector costCollector) { return pricingBL.createPricingContext() .setFailIfNotCalculated() .setOrgId(pricingInfo.getOrgId()) .setProductId(costCollector.getProductId()) .setBPartnerId(pricingInfo.getShipBPartnerId()) .setQty(costCollector.getQtyReservedOrConsumed()) .setConvertPriceToContextUOM(true) .setSOTrx(SOTrx.SALES) .setPriceDate(pricingInfo.getDatePromised().toLocalDate()) .setPricingSystemId(pricingInfo.getPricingSystemId()) .setPriceListId(pricingInfo.getPriceListId()) .setPriceListVersionId(pricingInfo.getPriceListVersionId()) .setCountryId(pricingInfo.getCountryId()) .setCurrencyId(pricingInfo.getCurrencyId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\ProjectQuotationPriceCalculator.java
2
请完成以下Java代码
public void setC_Root_BPartner_ID (final int C_Root_BPartner_ID) { if (C_Root_BPartner_ID < 1) set_Value (COLUMNNAME_C_Root_BPartner_ID, null); else set_Value (COLUMNNAME_C_Root_BPartner_ID, C_Root_BPartner_ID); } @Override public int getC_Root_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_Root_BPartner_ID); } @Override public void setExternalSystem_Config_Alberta_ID (final int ExternalSystem_Config_Alberta_ID) { if (ExternalSystem_Config_Alberta_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Alberta_ID, ExternalSystem_Config_Alberta_ID); } @Override public int getExternalSystem_Config_Alberta_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Alberta_ID); } @Override public I_ExternalSystem_Config getExternalSystem_Config() { return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class); } @Override public void setExternalSystem_Config(final I_ExternalSystem_Config ExternalSystem_Config) { set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_ID, I_ExternalSystem_Config.class, ExternalSystem_Config); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } @Override public void setExternalSystemValue (final String ExternalSystemValue) { set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue); } @Override public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
} @Override public void setPharmacy_PriceList_ID (final int Pharmacy_PriceList_ID) { if (Pharmacy_PriceList_ID < 1) set_Value (COLUMNNAME_Pharmacy_PriceList_ID, null); else set_Value (COLUMNNAME_Pharmacy_PriceList_ID, Pharmacy_PriceList_ID); } @Override public int getPharmacy_PriceList_ID() { return get_ValueAsInt(COLUMNNAME_Pharmacy_PriceList_ID); } @Override public void setTenant (final String Tenant) { set_Value (COLUMNNAME_Tenant, Tenant); } @Override public String getTenant() { return get_ValueAsString(COLUMNNAME_Tenant); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Alberta.java
1
请完成以下Java代码
public @NonNull InstantAndOrgId getDeliveryDate() {return packageable.getDeliveryDate();} public @Nullable OrderId getSalesOrderId() {return packageable.getSalesOrderId();} public @Nullable String getSalesOrderDocumentNo() {return packageable.getSalesOrderDocumentNo();} public @Nullable OrderAndLineId getSalesOrderAndLineIdOrNull() {return packageable.getSalesOrderAndLineIdOrNull();} public @Nullable WarehouseTypeId getWarehouseTypeId() {return packageable.getWarehouseTypeId();} public boolean isPartiallyPickedOrDelivered() { return packageable.getQtyPickedPlanned().signum() != 0 || packageable.getQtyPickedNotDelivered().signum() != 0 || packageable.getQtyPickedAndDelivered().signum() != 0; } public @NonNull ProductId getProductId() {return packageable.getProductId();} public @NonNull String getProductName() {return packageable.getProductName();} public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();} public @NonNull Quantity getQtyToDeliver() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToDeliver(); }
public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();} public @NonNull Quantity getQtyToPick() { return schedule != null ? schedule.getQtyToPick() : packageable.getQtyToPick(); } public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();} public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();} public @Nullable ShipperId getShipperId() {return packageable.getShipperId();} public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();} public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();} public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java
1
请完成以下Java代码
protected void validateParams(String userId, String groupId, String processDefinitionId) { if (processDefinitionId == null) { throw new FlowableIllegalArgumentException("processDefinitionId is null"); } if (userId == null && groupId == null) { throw new FlowableIllegalArgumentException("userId and groupId cannot both be null"); } } @Override public Void execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ProcessDefinitionEntity processDefinition = processEngineConfiguration.getProcessDefinitionEntityManager().findById(processDefinitionId); if (processDefinition == null) { throw new FlowableObjectNotFoundException("Cannot find process definition with id " + processDefinitionId, ProcessDefinition.class); }
if (Flowable5Util.isFlowable5ProcessDefinition(processDefinition, commandContext)) { Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler(); compatibilityHandler.addCandidateStarter(processDefinitionId, userId, groupId); return null; } IdentityLinkEntity identityLinkEntity = processEngineConfiguration.getIdentityLinkServiceConfiguration() .getIdentityLinkService().createProcessDefinitionIdentityLink(processDefinition.getId(), userId, groupId); processDefinition.getIdentityLinks().add(identityLinkEntity); return null; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\AddIdentityLinkForProcessDefinitionCmd.java
1
请完成以下Java代码
public Double getCollectResultValue() { return collectResultValue; } public void setCollectResultValue(Double collectResultValue) { this.collectResultValue = collectResultValue; } public String getRootDecisionInstanceId() { return rootDecisionInstanceId; } public void setRootDecisionInstanceId(String rootDecisionInstanceId) { this.rootDecisionInstanceId = rootDecisionInstanceId; }
public String getDecisionRequirementsDefinitionId() { return decisionRequirementsDefinitionId; } public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; } public String getDecisionRequirementsDefinitionKey() { return decisionRequirementsDefinitionKey; } public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java
1
请完成以下Java代码
public class BatchSeedJobHandler implements JobHandler<BatchSeedJobConfiguration> { public static final String TYPE = "batch-seed-job"; public String getType() { return TYPE; } public void execute(BatchSeedJobConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { String batchId = configuration.getBatchId(); BatchEntity batch = commandContext.getBatchManager().findBatchById(batchId); ensureNotNull("Batch with id '" + batchId + "' cannot be found", "batch", batch); BatchJobHandler<?> batchJobHandler = commandContext .getProcessEngineConfiguration() .getBatchHandlers() .get(batch.getType()); boolean done = batchJobHandler.createJobs(batch); if (!done) { batch.createSeedJob(); } else { // create monitor job initially without due date to // enable rapid completion of simple batches batch.createMonitorJob(false); } } @Override public BatchSeedJobConfiguration newConfiguration(String canonicalString) {
return new BatchSeedJobConfiguration(canonicalString); } public static class BatchSeedJobConfiguration implements JobHandlerConfiguration { protected String batchId; public BatchSeedJobConfiguration(String batchId) { this.batchId = batchId; } public String getBatchId() { return batchId; } @Override public String toCanonicalString() { return batchId; } } public void onDelete(BatchSeedJobConfiguration configuration, JobEntity jobEntity) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchSeedJobHandler.java
1
请完成以下Java代码
public class WaitingState implements Runnable { public static Thread t1; public static void main(String[] args) { t1 = new Thread(new WaitingState()); t1.start(); } public void run() { Thread t2 = new Thread(new DemoWaitingStateRunnable()); t2.start(); try { t2.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); }
} } class DemoWaitingStateRunnable implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } System.out.println(WaitingState.t1.getState()); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-simple\src\main\java\com\baeldung\concurrent\threadlifecycle\WaitingState.java
1
请在Spring Boot框架中完成以下Java代码
public class DeploymentResourceResponse { private String id; private String url; private String contentUrl; private String mediaType; private String type; public DeploymentResourceResponse(String resourceId, String url, String contentUrl, String mediaType, String type) { setId(resourceId); setUrl(url); setContentUrl(contentUrl); setMediaType(mediaType); this.type = type; if (type == null) { this.type = "resource"; } } @ApiModelProperty(example = "diagrams/my-process.bpmn20.xml") public String getId() { return id; } public void setId(String id) { this.id = id; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(value = "For a single resource contains the actual URL to use for retrieving the binary resource", example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10/resources/diagrams%2Fmy-process.bpmn20.xml") public String getUrl() { return url; } public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl; } @ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10/resourcedata/diagrams%2Fmy-process.bpmn20.xml") public String getContentUrl() { return contentUrl; } public void setMediaType(String mimeType) { this.mediaType = mimeType; } @ApiModelProperty(example = "text/xml", value = "Contains the media-type the resource has. This is resolved using a (pluggable) MediaTypeResolver and contains, by default, a limited number of mime-type mappings.") public String getMediaType() { return mediaType; } public void setType(String type) { this.type = type; } @ApiModelProperty(example = "processDefinition", value = "Type of resource", allowableValues = "resource,processDefinition,processImage") public String getType() { return type; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DeploymentResourceResponse.java
2
请完成以下Java代码
public static String getUsername(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } catch (JWTDecodeException e) { log.error("error:{}", e.getMessage()); return null; } } /** * 生成 token * * @param username 用户名 * @param secret 用户的密码 * @return token
*/ public static String sign(String username, String secret) { try { username = StringUtils.lowerCase(username); Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } catch (Exception e) { log.error("error:{}", e); return null; } } }
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\authentication\JWTUtil.java
1
请完成以下Java代码
public static String getErrorMsg(Throwable e) { // save the exception for displaying to user String msg = e.getLocalizedMessage(); if (Check.isEmpty(msg, true)) { msg = e.getMessage(); } if (Check.isEmpty(msg, true)) { // note that e.g. a NullPointerException doesn't have a nice message msg = dumpStackTraceToString(e); } return msg; } public static String replaceNonDigitCharsWithZero(String stringToModify) { final int size = stringToModify.length(); final StringBuilder stringWithZeros = new StringBuilder(); for (int i = 0; i < size; i++) { final char currentChar = stringToModify.charAt(i);
if (!Character.isDigit(currentChar)) { stringWithZeros.append('0'); } else { stringWithZeros.append(currentChar); } } return stringWithZeros.toString(); } public static int getMinimumOfThree(final int no1, final int no2, final int no3) { return no1 < no2 ? (no1 < no3 ? no1 : no3) : (no2 < no3 ? no2 : no3); } } // Util
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Util.java
1
请完成以下Java代码
public Movie movieByImdbId(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling getinfo for a given ImdbID***"); if (inventory.containsKey(imdbId)) { return inventory.get(imdbId); } else return null; } @POST @Path("/addmovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response addMovie(Movie movie) { System.out.println("*** Calling addMovie ***"); if (null != inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED).entity("Movie is Already in the database.").build(); } inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.CREATED).build(); } @PUT @Path("/updatemovie") @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response updateMovie(Movie movie) { System.out.println("*** Calling updateMovie ***"); if (null == inventory.get(movie.getImdbId())) { return Response.status(Response.Status.NOT_MODIFIED) .entity("Movie is not in the database.\nUnable to Update").build(); } inventory.put(movie.getImdbId(), movie); return Response.status(Response.Status.OK).build();
} @DELETE @Path("/deletemovie") public Response deleteMovie(@QueryParam("imdbId") String imdbId) { System.out.println("*** Calling deleteMovie ***"); if (null == inventory.get(imdbId)) { return Response.status(Response.Status.NOT_FOUND).entity("Movie is not in the database.\nUnable to Delete") .build(); } inventory.remove(imdbId); return Response.status(Response.Status.OK).build(); } @GET @Path("/listmovies") @Produces({ "application/json" }) public List<Movie> listMovies() { return inventory.values().stream().collect(Collectors.toCollection(ArrayList::new)); } }
repos\tutorials-master\web-modules\resteasy\src\main\java\com\baeldung\server\MovieCrudService.java
1
请在Spring Boot框架中完成以下Java代码
protected void executeDelete(CommandContext commandContext) { batchServiceConfiguration.getBatchEntityManager().deleteBatches(this); } @Override @Deprecated public void deleteWithRelatedData() { delete(); } // getters ////////////////////////////////////////// @Override public String getId() { return id; } public String getBatchType() { return batchType; } public Collection<String> getBatchTypes() { return batchTypes; } public String getSearchKey() { return searchKey; }
public String getSearchKey2() { return searchKey2; } public Date getCreateTimeHigherThan() { return createTimeHigherThan; } public Date getCreateTimeLowerThan() { return createTimeLowerThan; } public String getStatus() { return status; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\BatchQueryImpl.java
2
请完成以下Java代码
public ListenerFactory getListenerFactory() { return listenerFactory; } public void setListenerFactory(ListenerFactory listenerFactory) { this.listenerFactory = listenerFactory; } public BpmnParseFactory getBpmnParseFactory() { return bpmnParseFactory; } public void setBpmnParseFactory(BpmnParseFactory bpmnParseFactory) { this.bpmnParseFactory = bpmnParseFactory; } public ExpressionManager getExpressionManager() {
return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } public BpmnParseHandlers getBpmnParserHandlers() { return bpmnParserHandlers; } public void setBpmnParserHandlers(BpmnParseHandlers bpmnParserHandlers) { this.bpmnParserHandlers = bpmnParserHandlers; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\BpmnParser.java
1
请完成以下Java代码
public class EnvironmentEndpointWebExtension { private final EnvironmentEndpoint delegate; private final Show showValues; private final Set<String> roles; public EnvironmentEndpointWebExtension(EnvironmentEndpoint delegate, Show showValues, Set<String> roles) { this.delegate = delegate; this.showValues = showValues; this.roles = roles; } @ReadOperation
public EnvironmentDescriptor environment(SecurityContext securityContext, @Nullable String pattern) { boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles); return this.delegate.getEnvironmentDescriptor(pattern, showUnsanitized); } @ReadOperation public WebEndpointResponse<EnvironmentEntryDescriptor> environmentEntry(SecurityContext securityContext, @Selector String toMatch) { boolean showUnsanitized = this.showValues.isShown(securityContext, this.roles); EnvironmentEntryDescriptor descriptor = this.delegate.getEnvironmentEntryDescriptor(toMatch, showUnsanitized); return (descriptor.getProperty() != null) ? new WebEndpointResponse<>(descriptor, WebEndpointResponse.STATUS_OK) : new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND); } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\env\EnvironmentEndpointWebExtension.java
1
请完成以下Java代码
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); return TimeUtil.asLocalDate(shipmentDeclaration.getDeliveryDate()); } @Override public int getDoc_User_ID(DocumentTableFields docFields) { return extractShipmentDeclaration(docFields).getCreatedBy(); } @Override public String completeIt(DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); shipmentDeclaration.setProcessed(true); shipmentDeclaration.setDocAction(IDocument.ACTION_ReActivate); return IDocument.STATUS_Completed; }
@Override public void reactivateIt(DocumentTableFields docFields) { final I_M_Shipment_Declaration shipmentDeclaration = extractShipmentDeclaration(docFields); shipmentDeclaration.setProcessed(false); shipmentDeclaration.setDocAction(IDocument.ACTION_Complete); } private static I_M_Shipment_Declaration extractShipmentDeclaration(final DocumentTableFields docFields) { return InterfaceWrapperHelper.create(docFields, I_M_Shipment_Declaration.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\document\ShipmentDeclarationDocumentHandler.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Boolean getAllowCredentials() { return this.allowCredentials; } public void setAllowCredentials(@Nullable Boolean allowCredentials) { this.allowCredentials = allowCredentials; } public Duration getMaxAge() { return this.maxAge; } public void setMaxAge(Duration maxAge) { this.maxAge = maxAge; }
public @Nullable CorsConfiguration toCorsConfiguration() { if (CollectionUtils.isEmpty(this.allowedOrigins) && CollectionUtils.isEmpty(this.allowedOriginPatterns)) { return null; } PropertyMapper map = PropertyMapper.get(); CorsConfiguration configuration = new CorsConfiguration(); map.from(this::getAllowedOrigins).to(configuration::setAllowedOrigins); map.from(this::getAllowedOriginPatterns).to(configuration::setAllowedOriginPatterns); map.from(this::getAllowedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedHeaders); map.from(this::getAllowedMethods).whenNot(CollectionUtils::isEmpty).to(configuration::setAllowedMethods); map.from(this::getExposedHeaders).whenNot(CollectionUtils::isEmpty).to(configuration::setExposedHeaders); map.from(this::getMaxAge).as(Duration::getSeconds).to(configuration::setMaxAge); map.from(this::getAllowCredentials).to(configuration::setAllowCredentials); return configuration; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\CorsEndpointProperties.java
2
请完成以下Java代码
public String getLastName() { return lastName; } public String getFirstName() { return firstName; } public long getId() { return id; } public void setLastName(final String lastName) { this.lastName = lastName; } public void setFirstName(final String firstName) { this.firstName = firstName; } public void setId(final long id) { this.id = id; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Employee employee = (Employee) o; if (id != employee.id) { return false; }
if (!Objects.equals(lastName, employee.lastName)) { return false; } return Objects.equals(firstName, employee.firstName); } @Override public int hashCode() { int result = lastName != null ? lastName.hashCode() : 0; result = 31 * result + (firstName != null ? firstName.hashCode() : 0); result = 31 * result + (int) (id ^ (id >>> 32)); return result; } @Override public String toString() { return "User{" + "lastName='" + lastName + '\'' + ", firstName='" + firstName + '\'' + ", id=" + id + '}'; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\jsonignore\nullfields\Employee.java
1
请完成以下Java代码
public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Person [age="); builder.append(age); builder.append(", name="); builder.append(name); builder.append(", email="); builder.append(email); builder.append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((email == null) ? 0 : email.hashCode()); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (email == null) { if (other.email != null) return false; } else if (!email.equals(other.email)) return false; return true; } }
repos\tutorials-master\libraries-3\src\main\java\com\baeldung\nullaway\Person.java
1
请完成以下Java代码
private JSONDashboardItem changeDashboardItem( final DashboardWidgetType widgetType, final UserDashboardItemId itemId, final List<JSONPatchEvent<DashboardItemPatchPath>> events) { userSession.assertLoggedIn(); // // Change the dashboard item final UserDashboardItemChangeRequest request = UserDashboardItemChangeRequest.of(widgetType, itemId, userSession.getAD_Language(), events); final UserDashboardItemChangeResult changeResult = dashboardRepo.changeUserDashboardItem(getUserDashboard().get(), request); // // Notify on websocket final UserDashboard dashboard = getUserDashboard().get();
websocketSender.sendDashboardItemChangedEvent(dashboard, changeResult); // Return the changed item { final UserDashboardItem item = dashboard.getItemById(widgetType, itemId); final UserDashboardItemDataResponse data = dashboardDataService.getData(dashboard.getId()) .getItemData(UserDashboardItemDataRequest.builder() .itemId(item.getId()) .widgetType(widgetType) .context(KPIDataContext.ofUserSession(userSession)) .build()); return JSONDashboardItem.of(item, data, newKPIJsonOptions()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\DashboardRestController.java
1
请完成以下Java代码
public Collection<ProcessClassParamInfo> getParameterInfos() { return parameterInfos.values(); } public List<ProcessClassParamInfo> getParameterInfos(final String parameterName, final boolean parameterTo) { return parameterInfos.get(ProcessClassParamInfo.createParameterUniqueKey(parameterName, parameterTo)); } public List<ProcessClassParamInfo> getParameterInfos(final String parameterName) { final List<ProcessClassParamInfo> params = new ArrayList<>(); params.addAll(parameterInfos.get(ProcessClassParamInfo.createParameterUniqueKey(parameterName, false))); params.addAll(parameterInfos.get(ProcessClassParamInfo.createParameterUniqueKey(parameterName, true))); return params; } /** * @return true if a current record needs to be selected when this process is called from gear/window. * @see Process annotation */ public boolean isExistingCurrentRecordRequiredWhenCalledFromGear() { return existingCurrentRecordRequiredWhenCalledFromGear; } public boolean isAllowedForCurrentProfiles()
{ // No profiles restriction => allowed if (onlyForProfiles == null || onlyForProfiles.length == 0) { return true; } // No application context => allowed (but warn) final ApplicationContext context = SpringContextHolder.instance.getApplicationContext(); if (context == null) { logger.warn("No application context found to determine if {} is allowed for current profiles. Considering allowed", this); return true; } return context.getEnvironment().acceptsProfiles(onlyForProfiles); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessClassInfo.java
1
请在Spring Boot框架中完成以下Java代码
static BackOff getBackOff(Backoff retryTopicBackoff) { PropertyMapper map = PropertyMapper.get(); RetryPolicy.Builder builder = RetryPolicy.builder().maxRetries(Long.MAX_VALUE); map.from(retryTopicBackoff.getDelay()).to(builder::delay); map.from(retryTopicBackoff.getMaxDelay()).when(Predicate.not(Duration::isZero)).to(builder::maxDelay); map.from(retryTopicBackoff.getMultiplier()).to(builder::multiplier); map.from(retryTopicBackoff.getJitter()).when((Predicate.not(Duration::isZero))).to(builder::jitter); return builder.build().getBackOff(); } static void applySslBundle(Map<String, Object> properties, @Nullable SslBundle sslBundle) { if (sslBundle != null) { properties.put(SslConfigs.SSL_ENGINE_FACTORY_CLASS_CONFIG, SslBundleSslEngineFactory.class); properties.put(SslBundle.class.getName(), sslBundle); } } static void applySecurityProtocol(Map<String, Object> properties, @Nullable String securityProtocol) {
if (StringUtils.hasLength(securityProtocol)) { properties.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, securityProtocol); } } static class KafkaRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection().registerType(SslBundleSslEngineFactory.class, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\KafkaAutoConfiguration.java
2
请完成以下Java代码
public class Product { private String name; private double price; private int id; public Product(String name, double price, int id) { super(); this.name = name; this.price = price; this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); long temp; temp = Double.doubleToLongBits(price); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Product other = (Product) obj; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price)) return false; return true; } }
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\springbootmvc\model\Product.java
1
请完成以下Java代码
public void setValueMax (java.lang.String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Wert. @return Maximum Value for a field */ @Override public java.lang.String getValueMax () { return (java.lang.String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Wert. @param ValueMin Minimum Value for a field */ @Override public void setValueMin (java.lang.String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Wert. @return Minimum Value for a field */ @Override public java.lang.String getValueMin () {
return (java.lang.String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public void setVFormat (java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ @Override public java.lang.String getVFormat () { return (java.lang.String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Para.java
1
请完成以下Java代码
public Optional<Quantity> getQtyPicked() { return Optional.ofNullable(pickedTo != null ? pickedTo.getQtyPicked() : null); } public Optional<Quantity> getQtyRejected() { if (pickedTo == null) { return Optional.empty(); } final QtyRejectedWithReason qtyRejected = pickedTo.getQtyRejected(); if (qtyRejected == null) { return Optional.empty(); } return Optional.of(qtyRejected.toQuantity()); } public HuId getPickFromHUId() {return getPickFromHU().getId();} public boolean isPicked() {return pickedTo != null;} public boolean isNotPicked() {return pickedTo == null;} public void assertPicked() { if (!isPicked())
{ throw new AdempiereException("PickFrom was not picked: " + this); } } public PickingJobStepPickFrom assertNotPicked() { if (isPicked()) { throw new AdempiereException("PickFrom already picked: " + this); } return this; } public PickingJobStepPickFrom withPickedEvent(@NonNull final PickingJobStepPickedTo pickedTo) { return withPickedTo(pickedTo); } public PickingJobStepPickFrom withUnPickedEvent(@NonNull PickingJobStepUnpickInfo unpickEvent) { return withPickedTo(pickedTo != null ? pickedTo.removing(unpickEvent.getUnpickedHUs()) : null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobStepPickFrom.java
1
请在Spring Boot框架中完成以下Java代码
public Use getUse() { return this.use; } public static class Use { /** * Use the HTTP header with the given name to obtain the version. */ private @Nullable String header; /** * Use the query parameter with the given name to obtain the version. */ private @Nullable String queryParameter; /** * Use the path segment at the given index to obtain the version. */ private @Nullable Integer pathSegment; /** * Use the media type parameter with the given name to obtain the version. */ private Map<MediaType, String> mediaTypeParameter = new LinkedHashMap<>(); public @Nullable String getHeader() { return this.header; } public void setHeader(@Nullable String header) { this.header = header; } public @Nullable String getQueryParameter() { return this.queryParameter; }
public void setQueryParameter(@Nullable String queryParameter) { this.queryParameter = queryParameter; } public @Nullable Integer getPathSegment() { return this.pathSegment; } public void setPathSegment(@Nullable Integer pathSegment) { this.pathSegment = pathSegment; } public Map<MediaType, String> getMediaTypeParameter() { return this.mediaTypeParameter; } public void setMediaTypeParameter(Map<MediaType, String> mediaTypeParameter) { this.mediaTypeParameter = mediaTypeParameter; } } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\autoconfigure\WebFluxProperties.java
2
请完成以下Java代码
public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID()
{ return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPLU_File (final String PLU_File) { set_Value (COLUMNNAME_PLU_File, PLU_File); } @Override public String getPLU_File() { return get_ValueAsString(COLUMNNAME_PLU_File); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
1
请完成以下Java代码
private boolean isFieldEditable(final String fieldName) { final ViewEditorRenderMode renderMode = getViewEditorRenderModeByFieldName().get(fieldName); return renderMode != null && renderMode.isEditable(); } @Override public DocumentId getId() { return id; } @Override public boolean isProcessed() { return false; } @Nullable @Override public DocumentPath getDocumentPath() { return null; } public ProductId getProductId() { return getProduct().getIdAs(ProductId::ofRepoId); } public String getProductName() { return getProduct().getDisplayName(); } public boolean isQtySet() { final BigDecimal qty = getQty(); return qty != null && qty.signum() != 0; } public ProductsProposalRow withLastShipmentDays(final Integer lastShipmentDays) { if (Objects.equals(this.lastShipmentDays, lastShipmentDays)) { return this; } else
{ return toBuilder().lastShipmentDays(lastShipmentDays).build(); } } public boolean isChanged() { return getProductPriceId() == null || !getPrice().isPriceListPriceUsed(); } public boolean isMatching(@NonNull final ProductsProposalViewFilter filter) { return Check.isEmpty(filter.getProductName()) || getProductName().toLowerCase().contains(filter.getProductName().toLowerCase()); } public ProductsProposalRow withExistingOrderLine(@Nullable final OrderLine existingOrderLine) { if(existingOrderLine == null) { return this; } final Amount existingPrice = Amount.of(existingOrderLine.getPriceEntered(), existingOrderLine.getCurrency().getCurrencyCode()); return toBuilder() .qty(existingOrderLine.isPackingMaterialWithInfiniteCapacity() ? existingOrderLine.getQtyEnteredCU() : BigDecimal.valueOf(existingOrderLine.getQtyEnteredTU())) .price(ProductProposalPrice.builder() .priceListPrice(existingPrice) .build()) .existingOrderLineId(existingOrderLine.getOrderLineId()) .description(existingOrderLine.getDescription()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRow.java
1
请完成以下Java代码
public Object getValue() { if (m_value == null) return null; return new Integer(m_value.getC_Location_ID()); } // getValue /** * Return Editor value * @return value */ public int getC_Location_ID() { if (m_value == null) return 0; return m_value.getC_Location_ID(); } // getC_Location_ID /** * Return Display Value * @return display value */ @Override public String getDisplay() { return m_text.getText(); } // getDisplay /** * ActionListener - Button - Start Dialog * @param e ActionEvent */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == mDelete) { m_value = null; // create new } // final VLocationDialog ld = new VLocationDialog(SwingUtils.getFrame(this), Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Location"), m_value); ld.setVisible(true); Object oldValue = getValue(); m_value = ld.getValue(); // if (e.getSource() == mDelete) ; else if (!ld.isChanged()) return; // Data Binding try { int C_Location_ID = 0; if (m_value != null) C_Location_ID = m_value.getC_Location_ID(); Integer ii = new Integer(C_Location_ID); if (C_Location_ID > 0) fireVetoableChange(m_columnName, oldValue, ii); setValue(ii); if (ii.equals(oldValue) && m_GridTab != null && m_GridField != null) { // force Change - user does not realize that embedded object is already saved. m_GridTab.processFieldChange(m_GridField); } } catch (PropertyVetoException pve) { log.error("VLocation.actionPerformed", pve); } } // actionPerformed /** * Action Listener Interface * @param listener listener */ @Override public void addActionListener(ActionListener listener) { m_text.addActionListener(listener); } // addActionListener @Override
public synchronized void addMouseListener(MouseListener l) { m_text.addMouseListener(l); } /** * Set Field/WindowNo for ValuePreference (NOP) * @param mField Model Field */ @Override public void setField (org.compiere.model.GridField mField) { m_GridField = mField; EditorContextPopupMenu.onGridFieldSet(this); } // setField @Override public GridField getField() { return m_GridField; } // metas @Override public boolean isAutoCommit() { return true; } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VLocation
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocation.java
1
请完成以下Java代码
public class NotificationsSubscription extends AbstractNotificationSubscription<NotificationsSubscriptionUpdate> { private final Map<UUID, Notification> latestUnreadNotifications = new HashMap<>(); private final int limit; private final Set<NotificationType> notificationTypes; @Builder public NotificationsSubscription(String serviceId, String sessionId, int subscriptionId, TenantId tenantId, EntityId entityId, BiConsumer<TbSubscription<NotificationsSubscriptionUpdate>, NotificationsSubscriptionUpdate> updateProcessor, int limit, Set<NotificationType> notificationTypes) { super(serviceId, sessionId, subscriptionId, tenantId, entityId, TbSubscriptionType.NOTIFICATIONS, updateProcessor); this.limit = limit; this.notificationTypes = notificationTypes; } public boolean checkNotificationType(NotificationType type) { return CollectionUtils.isEmpty(notificationTypes) || notificationTypes.contains(type); } public UnreadNotificationsUpdate createFullUpdate() { return UnreadNotificationsUpdate.builder() .cmdId(getSubscriptionId()) .notifications(getSortedNotifications()) .totalUnreadCount(totalUnreadCounter.get()) .sequenceNumber(sequence.incrementAndGet()) .build(); } public List<Notification> getSortedNotifications() { return latestUnreadNotifications.values().stream() .sorted(Comparator.comparing(BaseData::getCreatedTime, Comparator.reverseOrder())) .collect(Collectors.toList()); }
public UnreadNotificationsUpdate createPartialUpdate(Notification notification) { return UnreadNotificationsUpdate.builder() .cmdId(getSubscriptionId()) .update(notification) .totalUnreadCount(totalUnreadCounter.get()) .sequenceNumber(sequence.incrementAndGet()) .build(); } public UnreadNotificationsUpdate createCountUpdate() { return UnreadNotificationsUpdate.builder() .cmdId(getSubscriptionId()) .totalUnreadCount(totalUnreadCounter.get()) .sequenceNumber(sequence.incrementAndGet()) .build(); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\ws\notification\sub\NotificationsSubscription.java
1
请完成以下Java代码
public void execute(DelegateExecution execution) { ThrowEvent throwEvent = (ThrowEvent) execution.getCurrentFlowElement(); /* * From the BPMN 2.0 spec: * * The Activity to be compensated MAY be supplied. * * If an Activity is not supplied, then the compensation is broadcast to all completed Activities in * the current Sub- Process (if present), or the entire Process instance (if at the global level). This “throws” the compensation. */ final String activityRef = compensateEventDefinition.getActivityRef(); CommandContext commandContext = Context.getCommandContext(); EventSubscriptionEntityManager eventSubscriptionEntityManager = commandContext.getEventSubscriptionEntityManager(); List<CompensateEventSubscriptionEntity> eventSubscriptions = new ArrayList<CompensateEventSubscriptionEntity>(); if (StringUtils.isNotEmpty(activityRef)) { // If an activity ref is provided, only that activity is compensated eventSubscriptions.addAll( eventSubscriptionEntityManager.findCompensateEventSubscriptionsByProcessInstanceIdAndActivityId( execution.getProcessInstanceId(), activityRef ) ); } else { // If no activity ref is provided, it is broadcast to the current sub process / process instance Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId()); FlowElementsContainer flowElementsContainer = null; if (throwEvent.getSubProcess() == null) { flowElementsContainer = process; } else { flowElementsContainer = throwEvent.getSubProcess(); } for (FlowElement flowElement : flowElementsContainer.getFlowElements()) { if (flowElement instanceof Activity) { eventSubscriptions.addAll(
eventSubscriptionEntityManager.findCompensateEventSubscriptionsByProcessInstanceIdAndActivityId( execution.getProcessInstanceId(), flowElement.getId() ) ); } } } if (eventSubscriptions.isEmpty()) { leave(execution); } else { // TODO: implement async (waitForCompletion=false in bpmn) ScopeUtil.throwCompensationEvent(eventSubscriptions, execution, false); leave(execution); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateThrowCompensationEventActivityBehavior.java
1
请完成以下Java代码
public static DmnDefinition getDmnDefinitionByDecisionId(String decisionId) { DeploymentManager deploymentManager = CommandContextUtil.getDmnEngineConfiguration().getDeploymentManager(); // This will check the cache in the findDeployedDecisionById and resolveDecisionTable method DecisionEntity decisionTableEntity = deploymentManager.findDeployedDecisionById(decisionId); return deploymentManager.resolveDecision(decisionTableEntity).getDmnDefinition(); } public static DmnDefinition getDmnDefinitionFromCache(String definitionId) { DecisionCacheEntry cacheEntry = CommandContextUtil.getDmnEngineConfiguration().getDefinitionCache().get(definitionId); if (cacheEntry != null) { return cacheEntry.getDmnDefinition(); } return null; } public static DecisionEntity getDecisionTableFromDatabase(String decisionTableId) { DecisionEntityManager decisionTableEntityManager = CommandContextUtil.getDmnEngineConfiguration().getDecisionEntityManager(); DecisionEntity decisionTable = decisionTableEntityManager.findById(decisionTableId); if (decisionTable == null) { throw new FlowableException("No decision table found with id " + decisionTableId); }
return decisionTable; } public static DecisionService getDecisionService(String decisionId) { DmnDefinition dmnDefinition = getDmnDefinitionByDecisionId(decisionId); DecisionService decisionService = dmnDefinition.getDecisionServiceById(decisionId); if (decisionService == null) { throw new FlowableObjectNotFoundException("Could not find decision service with id: " + decisionId); } return decisionService; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\util\DecisionUtil.java
1
请完成以下Java代码
private boolean isMultiValue(Class<?> returnType, @Nullable ReactiveAdapter adapter) { if (Flux.class.isAssignableFrom(returnType)) { return true; } return adapter == null || adapter.isMultiValue(); } private Mono<?> filterSingleValue(Publisher<?> filterTarget, Expression filterExpression, EvaluationContext ctx) { MethodSecurityExpressionOperations rootObject = (MethodSecurityExpressionOperations) ctx.getRootObject() .getValue(); return Mono.from(filterTarget).filterWhen((filterObject) -> { if (rootObject != null) { rootObject.setFilterObject(filterObject); } return ReactiveExpressionUtils.evaluateAsBoolean(filterExpression, ctx); }); } private Flux<?> filterMultiValue(Publisher<?> filterTarget, Expression filterExpression, EvaluationContext ctx) { MethodSecurityExpressionOperations rootObject = (MethodSecurityExpressionOperations) ctx.getRootObject() .getValue(); return Flux.from(filterTarget).filterWhen((filterObject) -> { if (rootObject != null) { rootObject.setFilterObject(filterObject); } return ReactiveExpressionUtils.evaluateAsBoolean(filterExpression, ctx); }); } @Override public Pointcut getPointcut() { return this.pointcut; } @Override public Advice getAdvice() { return this; }
@Override public boolean isPerInstance() { return true; } @Override public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } private static final class FilterTarget { private final Publisher<?> value; private final int index; private FilterTarget(Publisher<?> value, int index) { this.value = value; this.index = index; } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PreFilterAuthorizationReactiveMethodInterceptor.java
1
请完成以下Java代码
private void createFactsForMovementLine(final Fact fact, final DocLine_Movement line) { final AcctSchema as = fact.getAcctSchema(); final MoveCostsResult costs = line.getCreateCosts(as); // // Inventory CR/DR (from locator) final CostAmount outboundCosts = costs.getOutboundAmountToPost(as); fact.createLine() .setDocLine(line) .setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as)) .setAmtSourceDrOrCr(outboundCosts.toMoney()) // from (-) CR .setQty(line.getQty().negate()) // outgoing .locatorId(line.getM_Locator_ID()) .activityId(line.getActivityFromId())
.buildAndAdd(); // // InventoryTo DR/CR (to locator) final CostAmount inboundCosts = costs.getInboundAmountToPost(as); fact.createLine() .setDocLine(line) .setAccount(line.getAccount(ProductAcctType.P_Asset_Acct, as)) .setAmtSourceDrOrCr(inboundCosts.toMoney()) // to (+) DR .setQty(line.getQty()) // incoming .locatorId(line.getM_LocatorTo_ID()) .activityId(line.getActivityId()) .buildAndAdd(); } } // Doc_Movement
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Movement.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRole() { return role; } public void setRole(String role) {
this.role = role; } @Override public int hashCode() { return Objects.hash(id, name); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PersonDto other = (PersonDto) obj; return Objects.equals(id, other.id) && Objects.equals(name, other.name); } }
repos\tutorials-master\persistence-modules\hibernate-jpa-3\src\main\java\com\baeldung\hibernate\union\dto\PersonDto.java
1
请完成以下Java代码
public Iterator<T> iterator() { return new IteratorDecorator<>(this.source.iterator(), this.transform, this.filter); } } public static class IteratorDecorator<U, T> implements Iterator<T> { private final Iterator<U> source; private final Function<U, T> transform; private final Predicate<U> filter; private T next = null; public IteratorDecorator(Iterator<U> source, Function<U, T> transform, Predicate<U> filter) { this.source = source; this.transform = transform; this.filter = filter; } public boolean hasNext() { this.maybeFetchNext(); return next != null; } public T next() { if (next == null) { throw new NoSuchElementException(); } T val = next; next = null; return val; } private void maybeFetchNext() { if (next == null) { if (source.hasNext()) {
U val = source.next(); if (filter.test(val)) { next = transform.apply(val); } } } } public void remove() { throw new UnsupportedOperationException(); } } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\Iterables.java
1
请完成以下Java代码
public EventResourceEntity getEntity() { ensureInitialized(); return entity; } public void delete() { if (!deleted && id != null) { if (entity != null) { // if the entity has been loaded already, // we might as well use the safer optimistic locking delete. CommandContextUtil.getResourceEntityManager().delete(entity); } else { CommandContextUtil.getResourceEntityManager().delete(id); } entity = null; id = null; deleted = true; }
} private void ensureInitialized() { if (id != null && entity == null) { entity = CommandContextUtil.getResourceEntityManager().findById(id); name = entity.getName(); } } public boolean isDeleted() { return deleted; } @Override public String toString() { return "ResourceRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]"); } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ResourceRef.java
1
请完成以下Java代码
public Collection<CaseFileItem> getTargetRefs() { return targetRefCollection.getReferenceTargetElements(this); } public Children getChildren() { return childrenChild.getChild(this); } public void setChildren(Children children) { childrenChild.setChild(this, children); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItem.class, CMMN_ELEMENT_CASE_FILE_ITEM) .namespaceUri(CMMN11_NS) .extendsType(CmmnElement.class) .instanceProvider(new ModelTypeInstanceProvider<CaseFileItem>() { public CaseFileItem newInstance(ModelTypeInstanceContext instanceContext) { return new CaseFileItemImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); multiplicityAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_MULTIPLICITY, MultiplicityEnum.class) .defaultValue(MultiplicityEnum.Unspecified) .build(); definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) .qNameAttributeReference(CaseFileItemDefinition.class) .build(); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .namespace(CMMN10_NS) .idAttributeReference(CaseFileItem.class)
.build(); sourceRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); targetRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REFS) .idAttributeReferenceCollection(CaseFileItem.class, CmmnAttributeElementReferenceCollection.class) .build(); SequenceBuilder sequence = typeBuilder.sequence(); childrenChild = sequence.element(Children.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemImpl.java
1
请完成以下Java代码
public void setExceptionMessage(String exceptionMessage) { this.exceptionMessage = exceptionMessage; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode()); result = prime * result + ((endDate == null) ? 0 : endDate.hashCode()); result = prime * result + ((exceptionMessage == null) ? 0 : exceptionMessage.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + maxIterations; result = prime * result + ((repeat == null) ? 0 : repeat.hashCode()); result = prime * result + retries; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimerPayload other = (TimerPayload) obj; if (dueDate == null) { if (other.dueDate != null) return false; } else if (!dueDate.equals(other.dueDate)) return false; if (endDate == null) { if (other.endDate != null) return false;
} else if (!endDate.equals(other.endDate)) return false; if (exceptionMessage == null) { if (other.exceptionMessage != null) return false; } else if (!exceptionMessage.equals(other.exceptionMessage)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (maxIterations != other.maxIterations) return false; if (repeat == null) { if (other.repeat != null) return false; } else if (!repeat.equals(other.repeat)) return false; if (retries != other.retries) return false; return true; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\TimerPayload.java
1
请在Spring Boot框架中完成以下Java代码
public String login(HttpServletRequest req, UserCredentials cred, RedirectAttributes attr) { if(req.getMethod().equals(RequestMethod.GET.toString())) { return "login"; } else { Subject subject = SecurityUtils.getSubject(); if(!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken( cred.getUsername(), cred.getPassword(), cred.isRememberMe()); try { subject.login(token); } catch (AuthenticationException ae) { ae.printStackTrace(); attr.addFlashAttribute("error", "Invalid Credentials"); return "redirect:/login"; } } return "redirect:/secure"; } } @GetMapping("/secure") public String secure(ModelMap modelMap) { Subject currentUser = SecurityUtils.getSubject(); String role = "", permission = ""; if(currentUser.hasRole("admin")) { role = role + "You are an Admin"; } else if(currentUser.hasRole("editor")) { role = role + "You are an Editor"; } else if(currentUser.hasRole("author")) {
role = role + "You are an Author"; } if(currentUser.isPermitted("articles:compose")) { permission = permission + "You can compose an article, "; } else { permission = permission + "You are not permitted to compose an article!, "; } if(currentUser.isPermitted("articles:save")) { permission = permission + "You can save articles, "; } else { permission = permission + "\nYou can not save articles, "; } if(currentUser.isPermitted("articles:publish")) { permission = permission + "\nYou can publish articles"; } else { permission = permission + "\nYou can not publish articles"; } modelMap.addAttribute("username", currentUser.getPrincipal()); modelMap.addAttribute("permission", permission); modelMap.addAttribute("role", role); return "secure"; } @PostMapping("/logout") public String logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/"; } }
repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\intro\controllers\ShiroSpringController.java
2
请在Spring Boot框架中完成以下Java代码
public List<TimerJobEntity> execute(CommandContext commandContext) { JobServiceConfiguration jobServiceConfiguration = asyncExecutor.getJobServiceConfiguration(); List<String> enabledCategories = jobServiceConfiguration.getEnabledJobCategories(); List<TimerJobEntity> timerJobs = jobServiceConfiguration.getTimerJobEntityManager() .findJobsToExecute(enabledCategories, new Page(0, asyncExecutor.getMaxTimerJobsPerAcquisition())); for (TimerJobEntity job : timerJobs) { lockJob(commandContext, job, asyncExecutor.getTimerLockTimeInMillis(), jobServiceConfiguration); } return timerJobs; } protected void lockJob(CommandContext commandContext, TimerJobEntity job, int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) { // This will use the regular updates flush in the DbSqlSession // This will trigger an optimistic locking exception when two concurrent executors
// try to lock, as the revision will not match. GregorianCalendar jobExpirationTime = calculateLockExpirationTime(lockTimeInMillis, jobServiceConfiguration); job.setLockOwner(asyncExecutor.getLockOwner()); job.setLockExpirationTime(jobExpirationTime.getTime()); } protected GregorianCalendar calculateLockExpirationTime(int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) { GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime()); gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis); return gregorianCalendar; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\AcquireTimerJobsCmd.java
2
请在Spring Boot框架中完成以下Java代码
public class InvoiceRecipientExtensionType { @XmlElement(name = "InvoiceRecipientExtension", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact") protected at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType invoiceRecipientExtension; @XmlElement(name = "ErpelInvoiceRecipientExtension") protected CustomType erpelInvoiceRecipientExtension; /** * Gets the value of the invoiceRecipientExtension property. * * @return * possible object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType } * */ public at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType getInvoiceRecipientExtension() { return invoiceRecipientExtension; } /** * Sets the value of the invoiceRecipientExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType } * */ public void setInvoiceRecipientExtension(at.erpel.schemas._1p0.documents.extensions.edifact.InvoiceRecipientExtensionType value) {
this.invoiceRecipientExtension = value; } /** * Gets the value of the erpelInvoiceRecipientExtension property. * * @return * possible object is * {@link CustomType } * */ public CustomType getErpelInvoiceRecipientExtension() { return erpelInvoiceRecipientExtension; } /** * Sets the value of the erpelInvoiceRecipientExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelInvoiceRecipientExtension(CustomType value) { this.erpelInvoiceRecipientExtension = 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\InvoiceRecipientExtensionType.java
2
请完成以下Java代码
public int getM_Product_ID() { return ProductId.toRepoId(getProductId()); } @Override @Deprecated public void setM_Product_ID(final int productId) { setProductId(ProductId.ofRepoIdOrNull(productId)); } @Override @Deprecated public int getC_UOM_ID() { return UomId.toRepoId(getUomId()); } @Override @Deprecated public void setC_UOM_ID(final int uomId) { setUomId(UomId.ofRepoIdOrNull(uomId)); } @Override @Deprecated public int getM_HU_PI_Item_Product_ID() { return HUPIItemProductId.toRepoId(getPiItemProductId()); } @Override @Deprecated public void setM_HU_PI_Item_Product_ID(final int piItemProductId) { setPiItemProductId(HUPIItemProductId.ofRepoIdOrNull(piItemProductId)); } @Override @Deprecated public int getM_AttributeSetInstance_ID() { return AttributeSetInstanceId.toRepoId(getAsiId()); }
@Override @Deprecated public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { setAsiId(AttributeSetInstanceId.ofRepoIdOrNull(M_AttributeSetInstance_ID)); } @Override @Deprecated public int getC_BPartner_ID() { return BPartnerId.toRepoId(getBpartnerId()); } @Override @Deprecated public void setC_BPartner_ID(final int bpartnerId) { setBpartnerId(BPartnerId.ofRepoIdOrNull(bpartnerId)); } @Override public Optional<BigDecimal> getQtyCUsPerTU() { return Optional.ofNullable(qtyCUsPerTU); } @Override public void setQtyCUsPerTU(final BigDecimal qtyCUsPerTU) { this.qtyCUsPerTU = qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\PlainHUPackingAware.java
1
请完成以下Java代码
public int getIncrementNo () { Integer ii = (Integer)get_Value(COLUMNNAME_IncrementNo); if (ii == null) return 0; return ii.intValue(); } /** Set Lot Control. @param M_LotCtl_ID Product Lot Control */ public void setM_LotCtl_ID (int M_LotCtl_ID) { if (M_LotCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID)); } /** Get Lot Control. @return Product Lot Control */ public int getM_LotCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Prefix. @param Prefix
Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Start No. @param StartNo Starting number/position */ public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java
1
请在Spring Boot框架中完成以下Java代码
private Map<TopicPartition, Long> getProducerOffsets(Map<TopicPartition, Long> consumerGrpOffset) { List<TopicPartition> topicPartitions = new LinkedList<>(); for (Map.Entry<TopicPartition, Long> entry : consumerGrpOffset.entrySet()) { TopicPartition key = entry.getKey(); topicPartitions.add(new TopicPartition(key.topic(), key.partition())); } return consumer.endOffsets(topicPartitions); } public Map<TopicPartition, Long> computeLags( Map<TopicPartition, Long> consumerGrpOffsets, Map<TopicPartition, Long> producerOffsets) { Map<TopicPartition, Long> lags = new HashMap<>(); for (Map.Entry<TopicPartition, Long> entry : consumerGrpOffsets.entrySet()) { Long producerOffset = producerOffsets.get(entry.getKey()); Long consumerOffset = consumerGrpOffsets.get(entry.getKey()); long lag = Math.abs(Math.max(0, producerOffset) - Math.max(0, consumerOffset)); lags.putIfAbsent(entry.getKey(), lag); } return lags; } private AdminClient getAdminClient(String bootstrapServerConfig) { Properties config = new Properties(); config.put( AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServerConfig); return AdminClient.create(config);
} private KafkaConsumer<String, String> getKafkaConsumer( String bootstrapServerConfig) { Properties properties = new Properties(); properties.setProperty( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServerConfig); properties.setProperty( ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty( ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); return new KafkaConsumer<>(properties); } }
repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\monitoring\service\LagAnalyzerService.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getBucketName() { return this.bucketName; } public void setBucketName(@Nullable String bucketName) { this.bucketName = bucketName; } public @Nullable String getScopeName() { return this.scopeName; } public void setScopeName(@Nullable String scopeName) { this.scopeName = scopeName; } public @Nullable Class<?> getFieldNamingStrategy() { return this.fieldNamingStrategy;
} public void setFieldNamingStrategy(@Nullable Class<?> fieldNamingStrategy) { this.fieldNamingStrategy = fieldNamingStrategy; } public String getTypeKey() { return this.typeKey; } public void setTypeKey(String typeKey) { this.typeKey = typeKey; } }
repos\spring-boot-4.0.1\module\spring-boot-data-couchbase\src\main\java\org\springframework\boot\data\couchbase\autoconfigure\DataCouchbaseProperties.java
2
请完成以下Java代码
public void setAuthorityMapper(Function<Map<String, List<String>>, GrantedAuthority> authorityMapper) { Assert.notNull(authorityMapper, "authorityMapper must not be null"); this.authorityMapper = authorityMapper; } /** * Returns the current LDAP template. Method available so that classes extending this * can override the template used * @return the LDAP template * @see org.springframework.security.ldap.SpringSecurityLdapTemplate */ protected SpringSecurityLdapTemplate getLdapTemplate() { return this.ldapTemplate; } /** * Returns the attribute name of the LDAP attribute that will be mapped to the role * name Method available so that classes extending this can override * @return the attribute name used for role mapping * @see #setGroupRoleAttribute(String) */ protected final String getGroupRoleAttribute() { return this.groupRoleAttribute; } /** * Returns the search filter configured for this populator Method available so that * classes extending this can override * @return the search filter * @see #setGroupSearchFilter(String) */ protected final String getGroupSearchFilter() { return this.groupSearchFilter; } /**
* Returns the role prefix used by this populator Method available so that classes * extending this can override * @return the role prefix * @see #setRolePrefix(String) */ protected final String getRolePrefix() { return this.rolePrefix; } /** * Returns true if role names are converted to uppercase Method available so that * classes extending this can override * @return true if role names are converted to uppercase. * @see #setConvertToUpperCase(boolean) */ protected final boolean isConvertToUpperCase() { return this.convertToUpperCase; } /** * Returns the search controls Method available so that classes extending this can * override the search controls used * @return the search controls */ private SearchControls getSearchControls() { return this.searchControls; } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\DefaultLdapAuthoritiesPopulator.java
1
请完成以下Java代码
public PlainCardData1 getPlainCardData() { return plainCardData; } /** * Sets the value of the plainCardData property. * * @param value * allowed object is * {@link PlainCardData1 } * */ public void setPlainCardData(PlainCardData1 value) { this.plainCardData = value; } /** * Gets the value of the cardCtryCd property. * * @return * possible object is * {@link String } * */ public String getCardCtryCd() { return cardCtryCd; } /** * Sets the value of the cardCtryCd property. * * @param value * allowed object is * {@link String } * */ public void setCardCtryCd(String value) { this.cardCtryCd = value; } /** * Gets the value of the cardBrnd property. * * @return * possible object is * {@link GenericIdentification1 } * */ public GenericIdentification1 getCardBrnd() { return cardBrnd; }
/** * Sets the value of the cardBrnd property. * * @param value * allowed object is * {@link GenericIdentification1 } * */ public void setCardBrnd(GenericIdentification1 value) { this.cardBrnd = value; } /** * Gets the value of the addtlCardData property. * * @return * possible object is * {@link String } * */ public String getAddtlCardData() { return addtlCardData; } /** * Sets the value of the addtlCardData property. * * @param value * allowed object is * {@link String } * */ public void setAddtlCardData(String value) { this.addtlCardData = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PaymentCard4.java
1
请完成以下Java代码
public void setM_FreightCostShipper_ID (int M_FreightCostShipper_ID) { if (M_FreightCostShipper_ID < 1) set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, null); else set_ValueNoCheck (COLUMNNAME_M_FreightCostShipper_ID, Integer.valueOf(M_FreightCostShipper_ID)); } /** Get Lieferweg-Versandkosten. @return Lieferweg-Versandkosten */ public int getM_FreightCostShipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCostShipper_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Shipper getM_Shipper() throws RuntimeException { return (I_M_Shipper)MTable.get(getCtx(), I_M_Shipper.Table_Name) .getPO(getM_Shipper_ID(), get_TrxName()); } /** Set Lieferweg. @param M_Shipper_ID Methode oder Art der Warenlieferung */ public void setM_Shipper_ID (int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null);
else set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID)); } /** Get Lieferweg. @return Methode oder Art der Warenlieferung */ public int getM_Shipper_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Gueltig ab. @param ValidFrom Gueltig ab inklusiv (erster Tag) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gueltig ab. @return Gueltig ab inklusiv (erster Tag) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCostShipper.java
1
请完成以下Java代码
public class LifecycleEvent extends Event { private static final long serialVersionUID = -3247420461850911549L; @Builder private LifecycleEvent(TenantId tenantId, UUID entityId, String serviceId, UUID id, long ts, String lcEventType, boolean success, String error) { super(tenantId, entityId, serviceId, id, ts); this.lcEventType = lcEventType; this.success = success; this.error = error; } @Getter private final String lcEventType; @Getter private final boolean success; @Getter @Setter private String error; @Override public EventType getType() { return EventType.LC_EVENT;
} @Override public EventInfo toInfo(EntityType entityType) { EventInfo eventInfo = super.toInfo(entityType); var json = (ObjectNode) eventInfo.getBody(); json.put("event", lcEventType) .put("success", success); if (error != null) { json.put("error", error); } return eventInfo; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\event\LifecycleEvent.java
1
请完成以下Java代码
public class JmxConnectionWrapper { private final Map<String, MBeanAttributeInfo> attributeMap; private final MBeanServerConnection connection; private final ObjectName objectName; public JmxConnectionWrapper(String url, String beanName) throws Exception { objectName = new ObjectName(beanName); connection = JMXConnectorFactory.connect(new JMXServiceURL(url)) .getMBeanServerConnection(); MBeanInfo bean = connection.getMBeanInfo(objectName); MBeanAttributeInfo[] attributes = bean.getAttributes(); this.attributeMap = Stream.of(attributes) .peek(System.out::println) .collect(Collectors.toMap(MBeanAttributeInfo::getName, Function.identity())); } public boolean hasAttribute(String attributeName) { return attributeMap.containsKey(attributeName); } public Object attributeValue(String name, String value) throws Exception { if (value != null) { connection.setAttribute(objectName, new Attribute(name, parse(value))); } return connection.getAttribute(objectName, name); } public Object invoke(String operation) throws Exception {
String[] signature = new String[] {}; Object[] params = new Object[] {}; return connection.invoke(objectName, operation, params, signature); } private static Object parse(String value) { if (value == null) return null; if (value.matches("\\d+")) { return Integer.valueOf(value); } else if (value.trim() .toLowerCase() .matches("true|false")) { return Boolean.valueOf(value); } return value.equals("null") ? null : value; } }
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\jmxshell\custom\JmxConnectionWrapper.java
1
请完成以下Java代码
public MessagePostProcessor removeDecompressor(String contentEncoding) { return this.decompressors.remove(contentEncoding); } /** * Replace all the decompressors. * @param decompressors the decompressors. */ public void setDecompressors(Map<String, MessagePostProcessor> decompressors) { this.decompressors.clear(); this.decompressors.putAll(decompressors); } @Override public Message postProcessMessage(Message message) throws AmqpException { String encoding = message.getMessageProperties().getContentEncoding(); if (encoding == null) { return message; }
int delimAt = encoding.indexOf(':'); if (delimAt < 0) { delimAt = encoding.indexOf(','); } if (delimAt > 0) { encoding = encoding.substring(0, delimAt); } MessagePostProcessor decompressor = this.decompressors.get(encoding); if (decompressor != null) { return decompressor.postProcessMessage(message); } return message; } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\postprocessor\DelegatingDecompressingPostProcessor.java
1
请完成以下Java代码
public class X_AD_WF_Node_Template extends org.compiere.model.PO implements I_AD_WF_Node_Template, org.compiere.model.I_Persistent { private static final long serialVersionUID = -1982377865L; /** Standard Constructor */ public X_AD_WF_Node_Template (final Properties ctx, final int AD_WF_Node_Template_ID, @Nullable final String trxName) { super (ctx, AD_WF_Node_Template_ID, trxName); } /** Load Constructor */ public X_AD_WF_Node_Template (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_WF_Node_Template_ID (final int AD_WF_Node_Template_ID) { if (AD_WF_Node_Template_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Template_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_WF_Node_Template_ID, AD_WF_Node_Template_ID); }
@Override public int getAD_WF_Node_Template_ID() { return get_ValueAsInt(COLUMNNAME_AD_WF_Node_Template_ID); } @Override public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node_Template.java
1
请在Spring Boot框架中完成以下Java代码
private MapConfig initializeDefaultMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig("default"); /* Number of backups. If 1 is set as the backup-count for example, then all entries of the map will be copied to another JVM for fail-safety. Valid numbers are 0 (no backup), 1, 2, 3. */ mapConfig.setBackupCount(jHipsterProperties.getCache().getHazelcast().getBackupCount()); /* Valid values are: NONE (no eviction), LRU (Least Recently Used), LFU (Least Frequently Used). NONE is the default. */ mapConfig.getEvictionConfig().setEvictionPolicy(EvictionPolicy.LRU); /* Maximum size of the map. When max size is reached, map is evicted based on the policy defined. Any integer between 0 and Integer.MAX_VALUE. 0 means Integer.MAX_VALUE. Default is 0. */ mapConfig.getEvictionConfig().setMaxSizePolicy(MaxSizePolicy.USED_HEAP_SIZE); return mapConfig; } private MapConfig initializeDomainMapConfig(JHipsterProperties jHipsterProperties) { MapConfig mapConfig = new MapConfig("com.cars.app.domain.*");
mapConfig.setTimeToLiveSeconds(jHipsterProperties.getCache().getHazelcast().getTimeToLiveSeconds()); return mapConfig; } @Autowired(required = false) public void setGitProperties(GitProperties gitProperties) { this.gitProperties = gitProperties; } @Autowired(required = false) public void setBuildProperties(BuildProperties buildProperties) { this.buildProperties = buildProperties; } @Bean public KeyGenerator keyGenerator() { return new PrefixedKeyGenerator(this.gitProperties, this.buildProperties); } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\config\CacheConfiguration.java
2