instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setC_Period_ID (final int C_Period_ID) { if (C_Period_ID < 1) set_Value (COLUMNNAME_C_Period_ID, null); else set_Value (COLUMNNAME_C_Period_ID, C_Period_ID); } @Override public int getC_Period_ID() { return get_ValueAsInt(COLUMNNAME_C_Period_ID); } @Override public void setDatevAcctExport_ID (final int DatevAcctExport_ID) { if (DatevAcctExport_ID < 1) set_ValueNoCheck (COLUMNNAME_DatevAcctExport_ID, null); else set_ValueNoCheck (COLUMNNAME_DatevAcctExport_ID, DatevAcctExport_ID); } @Override public int getDatevAcctExport_ID() { return get_ValueAsInt(COLUMNNAME_DatevAcctExport_ID); } @Override public void setExportBy_ID (final int ExportBy_ID) { if (ExportBy_ID < 1) set_ValueNoCheck (COLUMNNAME_ExportBy_ID, null); else set_ValueNoCheck (COLUMNNAME_ExportBy_ID, ExportBy_ID); } @Override public int getExportBy_ID() { return get_ValueAsInt(COLUMNNAME_ExportBy_ID); } @Override public void setExportDate (final @Nullable java.sql.Timestamp ExportDate) { set_ValueNoCheck (COLUMNNAME_ExportDate, ExportDate); }
@Override public java.sql.Timestamp getExportDate() { return get_ValueAsTimestamp(COLUMNNAME_ExportDate); } /** * ExportType AD_Reference_ID=541172 * Reference name: DatevExportType */ public static final int EXPORTTYPE_AD_Reference_ID=541172; /** Payment = Payment */ public static final String EXPORTTYPE_Payment = "Payment"; /** Commission Invoice = CommissionInvoice */ public static final String EXPORTTYPE_CommissionInvoice = "CommissionInvoice"; /** Sales Invoice = SalesInvoice */ public static final String EXPORTTYPE_SalesInvoice = "SalesInvoice"; /** Credit Memo = CreditMemo */ public static final String EXPORTTYPE_CreditMemo = "CreditMemo"; @Override public void setExportType (final java.lang.String ExportType) { set_Value (COLUMNNAME_ExportType, ExportType); } @Override public java.lang.String getExportType() { return get_ValueAsString(COLUMNNAME_ExportType); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExport.java
1
请完成以下Java代码
public final class JAXBConstants { private JAXBConstants() { super(); } /** * JAXB Contact Path */ public static final String JAXB_ContextPath = "de.metas.printing.esb.base.jaxb.generated"; public static final DynamicObjectFactory JAXB_ObjectFactory = new DynamicObjectFactory(new de.metas.printing.esb.base.jaxb.generated.ObjectFactory()); /* * AD_PRINTER_HW Formats' Versions */
public static final String PRT_AD_PRINTER_HW_FORMAT_VERSION = "*"; public static final String PRT_AD_PRINTER_HW_MEDIA_SIZE_FORMAT_VERSION = "*"; public static final String PRT_AD_PRINTER_HW_MEDIA_TRAY_FORMAT_VERSION = "*"; /* * C_PRINT_PACKAGE Formats' Versions */ public static final String PRT_C_PRINT_PACKAGE_FORMAT_VERSION = "*"; public static final String PRT_C_PRINT_PACKAGE_INFO_FORMAT_VERSION = "*"; public static final String PRT_C_PRINT_JOB_INSTRUCTIONS_CONFIRM_FORMAT_VERSION = "*"; /* * Misc Formats' Versions */ public static final String PRT_LOGINREQUEST_VERSION = "*"; }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.esb.base\src\main\java\de\metas\printing\esb\base\jaxb\JAXBConstants.java
1
请完成以下Java代码
public void warmUpCacheForHuIds(final Collection<HuId> huIds) { CollectionUtils.getAllOrLoad(husById, huIds, this::retrieveHUs); } private Map<HuId, I_M_HU> retrieveHUs(final Collection<HuId> huIds) { return Maps.uniqueIndex(handlingUnitsBL.getByIds(huIds), HUsLoadingCache::extractHUId); } public HuId getTopLevelHUId(final HuId huId) { return topLevelHUIds.computeIfAbsent(huId, this::retrieveTopLevelHUId); } private HuId retrieveTopLevelHUId(final HuId huId) { final I_M_HU hu = getHUById(huId); final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParentAsLUTUCUPair(hu).getTopLevelHU(); addToCache(topLevelHU); return extractHUId(topLevelHU); } public ImmutableSet<HuId> getVHUIds(final HuId huId) {return vhuIds.computeIfAbsent(huId, this::retrieveVHUIds);} private ImmutableSet<HuId> retrieveVHUIds(final HuId huId) { final I_M_HU hu = getHUById(huId); final List<I_M_HU> vhus = handlingUnitsBL.getVHUs(hu); addToCache(vhus); return extractHUIds(vhus); } private static ImmutableSet<HuId> extractHUIds(final List<I_M_HU> hus) {return hus.stream().map(HUsLoadingCache::extractHUId).collect(ImmutableSet.toImmutableSet());} private static HuId extractHUId(final I_M_HU hu) {return HuId.ofRepoId(hu.getM_HU_ID());} public ImmutableAttributeSet getHUAttributes(final HuId huId)
{ return huAttributesCache.computeIfAbsent(huId, this::retrieveHUAttributes); } private ImmutableAttributeSet retrieveHUAttributes(final HuId huId) { final I_M_HU hu = getHUById(huId); final IAttributeStorage attributes = attributesFactory.getAttributeStorage(hu); return ImmutableAttributeSet.createSubSet(attributes, a -> attributesToConsider.contains(AttributeCode.ofString(a.getValue()))); } public LocatorId getLocatorIdByHuId(final HuId huId) { final I_M_HU hu = getHUById(huId); return IHandlingUnitsBL.extractLocatorId(hu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\HUsLoadingCache.java
1
请完成以下Java代码
public void setAD_Column_ID (final int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID); } @Override public int getAD_Column_ID() { return get_ValueAsInt(COLUMNNAME_AD_Column_ID); } @Override public de.metas.elasticsearch.model.I_ES_FTS_Config_Field getES_FTS_Config_Field() { return get_ValueAsPO(COLUMNNAME_ES_FTS_Config_Field_ID, de.metas.elasticsearch.model.I_ES_FTS_Config_Field.class); } @Override public void setES_FTS_Config_Field(final de.metas.elasticsearch.model.I_ES_FTS_Config_Field ES_FTS_Config_Field) { set_ValueFromPO(COLUMNNAME_ES_FTS_Config_Field_ID, de.metas.elasticsearch.model.I_ES_FTS_Config_Field.class, ES_FTS_Config_Field); } @Override public void setES_FTS_Config_Field_ID (final int ES_FTS_Config_Field_ID) { if (ES_FTS_Config_Field_ID < 1) set_Value (COLUMNNAME_ES_FTS_Config_Field_ID, null); else set_Value (COLUMNNAME_ES_FTS_Config_Field_ID, ES_FTS_Config_Field_ID); } @Override public int getES_FTS_Config_Field_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_Field_ID); } @Override public de.metas.elasticsearch.model.I_ES_FTS_Filter getES_FTS_Filter() { return get_ValueAsPO(COLUMNNAME_ES_FTS_Filter_ID, de.metas.elasticsearch.model.I_ES_FTS_Filter.class); } @Override public void setES_FTS_Filter(final de.metas.elasticsearch.model.I_ES_FTS_Filter ES_FTS_Filter) { set_ValueFromPO(COLUMNNAME_ES_FTS_Filter_ID, de.metas.elasticsearch.model.I_ES_FTS_Filter.class, ES_FTS_Filter); } @Override public void setES_FTS_Filter_ID (final int ES_FTS_Filter_ID) { if (ES_FTS_Filter_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, ES_FTS_Filter_ID); } @Override public int getES_FTS_Filter_ID() {
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_ID); } @Override public void setES_FTS_Filter_JoinColumn_ID (final int ES_FTS_Filter_JoinColumn_ID) { if (ES_FTS_Filter_JoinColumn_ID < 1) set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, null); else set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, ES_FTS_Filter_JoinColumn_ID); } @Override public int getES_FTS_Filter_JoinColumn_ID() { return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_JoinColumn_ID); } @Override public void setIsNullable (final boolean IsNullable) { set_Value (COLUMNNAME_IsNullable, IsNullable); } @Override public boolean isNullable() { return get_ValueAsBoolean(COLUMNNAME_IsNullable); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Filter_JoinColumn.java
1
请完成以下Java代码
public void handleBatch(Exception thrownException, @Nullable ConsumerRecords<?, ?> records, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { if (records == null || records.count() == 0) { this.logger.error(thrownException, "Called with no records; consumer exception"); return; } this.retrying.put(Thread.currentThread(), true); try { ErrorHandlingUtils.retryBatch(thrownException, records, consumer, container, invokeListener, this.backOff, this.seeker, this.recoverer, this.logger, getLogLevel(), this.retryListeners, getExceptionMatcher(), this.reclassifyOnExceptionChange); } finally { this.retrying.remove(Thread.currentThread()); } } @Override public void onPartitionsAssigned(Consumer<?, ?> consumer, Collection<TopicPartition> partitions, Runnable publishPause) { if (Boolean.TRUE.equals(this.retrying.get(Thread.currentThread()))) { consumer.pause(consumer.assignment()); publishPause.run(); } } private final class SeekAfterRecoverFailsOrInterrupted implements CommonErrorHandler { SeekAfterRecoverFailsOrInterrupted() { } @Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer, MessageListenerContainer container, Runnable invokeListener) { data.partitions() .stream() .collect( Collectors.toMap(tp -> tp, tp -> data.records(tp).get(0).offset(), (u, v) -> v, LinkedHashMap::new)) .forEach(consumer::seek); throw new KafkaException("Seek to current after exception", getLogLevel(), thrownException); } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\FallbackBatchErrorHandler.java
1
请完成以下Java代码
private boolean havePage(final int pageIndex) { if (pageIndex < 0 || pageIndex >= getNumberOfPages()) return false; return true; } // havePage /** * Print Copy * * @return true if copy */ public boolean isCopy() { return m_isCopy; } // isCopy /** * Set Copy * * @param isCopy if true document is a copy */ public void setCopy(final boolean isCopy) { m_isCopy = isCopy; } // setCopy /************************************************************************** * Get the doc flavor (Doc Interface) * * @return SERVICE_FORMATTED.PAGEABLE */ @Override public DocFlavor getDocFlavor() { return DocFlavor.SERVICE_FORMATTED.PAGEABLE; } // getDocFlavor /** * Get Print Data (Doc Interface) * * @return this * @throws IOException */ @Override public Object getPrintData() throws IOException { return this; } // getPrintData /** * Get Document Attributes (Doc Interface) * * @return null to obtain all attribute values from the * job's attribute set. */ @Override public DocAttributeSet getAttributes() { return null; } // getAttributes /** * Obtains a reader for extracting character print data from this doc. * (Doc Interface) * * @return null * @throws IOException */
@Override public Reader getReaderForText() throws IOException { return null; } // getReaderForText /** * Obtains an input stream for extracting byte print data from this doc. * (Doc Interface) * * @return null * @throws IOException */ @Override public InputStream getStreamForBytes() throws IOException { return null; } // getStreamForBytes public void setPrintInfo(final ArchiveInfo info) { m_PrintInfo = info; } /** * @return PrintInfo */ public ArchiveInfo getPrintInfo() { return m_PrintInfo; } } // LayoutEngine
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\LayoutEngine.java
1
请完成以下Java代码
public class ASIViewRowAttributesProvider implements IViewRowAttributesProvider { public static ASIViewRowAttributesProvider newInstance(final ASIRepository asiRepository) { return new ASIViewRowAttributesProvider(asiRepository); } private final ASIRepository asiRepository; private final Map<DocumentId, ASIViewRowAttributes> attributesById = new ConcurrentHashMap<>(); private ASIViewRowAttributesProvider(@NonNull final ASIRepository asiRepository) { this.asiRepository = asiRepository; } @Override public IViewRowAttributes getAttributes(final DocumentId rowId_NOTUSED, final DocumentId asiId) { return attributesById.computeIfAbsent(asiId, this::createAttributes); }
private ASIViewRowAttributes createAttributes(final DocumentId asiDocumentId) { final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiDocumentId.toInt()); if (asiId == null) { throw new AdempiereException("Invalid ASI document ID: " + asiDocumentId); } final ASIDocument asiDoc = asiRepository.loadReadonly(asiId); final ASILayout asiLayout = asiDoc.getLayout(); return new ASIViewRowAttributes(asiDoc, asiLayout); } @Override public void invalidateAll() { attributesById.clear(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ASIViewRowAttributesProvider.java
1
请在Spring Boot框架中完成以下Java代码
public class Product { public Product(){} @Id //@GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; public Product(Long id, String productName, Double price, CustomerOrder customerOrder) { this.id = id; this.productName = productName; this.price = price; this.customerOrder = customerOrder; } @Column private String productName; @Column private Double price; @Override public String toString() { return "Dispense{" + "id=" + id + ", productName='" + productName + '\'' + ", price=" + price + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product dispense = (Product) o; return Objects.equals(id, dispense.id); } @Override public int hashCode() { return Objects.hash(id); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProductName() {
return productName; } public void setProductName(String productName) { this.productName = productName; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public CustomerOrder getCustomerOrder() { return customerOrder; } public void setCustomerOrder(CustomerOrder co) { this.customerOrder = co; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="customerorder_id", nullable = false) private CustomerOrder customerOrder; }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\Product.java
2
请完成以下Java代码
public InventoryLine withCounting(@NonNull final InventoryLineCountRequest request) { final ArrayList<InventoryLineHU> newLineHUs = new ArrayList<>(inventoryLineHUs.size() + 1); boolean updated = false; boolean isSingleLineHUPlaceholder = inventoryLineHUs.size() == 1 && inventoryLineHUs.get(0).getId() == null && inventoryLineHUs.get(0).getHuId() == null; if (!isSingleLineHUPlaceholder) { for (InventoryLineHU lineHU : inventoryLineHUs) { if (!updated && HuId.equals(lineHU.getHuId(), request.getHuId())) { newLineHUs.add(lineHU.updatingFrom(request)); updated = true; } else { newLineHUs.add(lineHU); } } } if (!updated) { newLineHUs.add(InventoryLineHU.of(request)); } return toBuilder() .huAggregationType(computeHUAggregationType(newLineHUs, this.huAggregationType)) .qtyCountFixed(computeQtyCountSum(newLineHUs)) .clearInventoryLineHUs() .inventoryLineHUs(newLineHUs) .counted(newLineHUs.stream().allMatch(InventoryLineHU::isCounted)) .build(); } @Nullable
private static HUAggregationType computeHUAggregationType( @NonNull final List<InventoryLineHU> newInventoryLineHUs, @Nullable final HUAggregationType prevHUAggregationType) { return newInventoryLineHUs.size() > 1 ? HUAggregationType.MULTI_HU : prevHUAggregationType; } public boolean isEligibleForCounting() { return !isCounted(); } public InventoryLineHU getInventoryLineHUById(@NonNull final InventoryLineHUId id) { return inventoryLineHUs.stream() .filter(lineHU -> InventoryLineHUId.equals(lineHU.getId(), id)) .findFirst() .orElseThrow(() -> new AdempiereException("No Line HU found for " + id + " in " + this)); } public Optional<InventoryLineHU> getInventoryLineHUByHUId(@NonNull final HuId huId) { return inventoryLineHUs.stream() .filter(lineHU -> HuId.equals(lineHU.getHuId(), huId)) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLine.java
1
请完成以下Java代码
public int getKeepLogDays () { Integer ii = (Integer)get_Value(COLUMNNAME_KeepLogDays); 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); } /** Set Password Info. @param PasswordInfo Password Info */ public void setPasswordInfo (String PasswordInfo) { set_Value (COLUMNNAME_PasswordInfo, PasswordInfo); } /** Get Password Info. @return Password Info */ public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port); if (ii == null)
return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_Processor.java
1
请完成以下Java代码
public static VariableValueDto fromTypedValue(TypedValue typedValue, boolean preferSerializedValue) { VariableValueDto dto = new VariableValueDto(); fromTypedValue(dto, typedValue, preferSerializedValue); return dto; } public static void fromTypedValue(VariableValueDto dto, TypedValue typedValue) { fromTypedValue(dto, typedValue, false); } public static void fromTypedValue(VariableValueDto dto, TypedValue typedValue, boolean preferSerializedValue) { ValueType type = typedValue.getType(); if (type != null) { String typeName = type.getName(); dto.setType(toRestApiTypeName(typeName)); dto.setValueInfo(type.getValueInfo(typedValue)); } if(typedValue instanceof SerializableValue) { SerializableValue serializableValue = (SerializableValue) typedValue; if(serializableValue.isDeserialized() && !preferSerializedValue) { dto.setValue(serializableValue.getValue()); } else { dto.setValue(serializableValue.getValueSerialized()); } } else if(typedValue instanceof FileValue){ //do not set the value for FileValues since we don't want to send megabytes over the network without explicit request } else { dto.setValue(typedValue.getValue()); } } public static String toRestApiTypeName(String name) { return name.substring(0, 1).toUpperCase() + name.substring(1); } public static String fromRestApiTypeName(String name) { return name.substring(0, 1).toLowerCase() + name.substring(1); }
public static VariableValueDto fromFormPart(String type, FormPart binaryDataFormPart) { VariableValueDto dto = new VariableValueDto(); dto.type = type; dto.value = binaryDataFormPart.getBinaryContent(); if (ValueType.FILE.getName().equals(fromRestApiTypeName(type))) { String contentType = binaryDataFormPart.getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } dto.valueInfo = new HashMap<>(); dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_NAME, binaryDataFormPart.getFileName()); MimeType mimeType = null; try { mimeType = new MimeType(contentType); } catch (MimeTypeParseException e) { throw new RestException(Status.BAD_REQUEST, "Invalid mime type given"); } dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_MIME_TYPE, mimeType.getBaseType()); String encoding = mimeType.getParameter("encoding"); if (encoding != null) { dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_ENCODING, encoding); } String transientString = mimeType.getParameter("transient"); boolean isTransient = Boolean.parseBoolean(transientString); if (isTransient) { dto.valueInfo.put(AbstractValueTypeImpl.VALUE_INFO_TRANSIENT, isTransient); } } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\VariableValueDto.java
1
请完成以下Java代码
public void mergeDynamicData(InternalsImpl other) { this.commands = other.commands; this.metrics = other.metrics; } @Override public JdkImpl getJdk() { return jdk; } public void setJdk(JdkImpl jdk) { this.jdk = jdk; } @Override public Set<String> getCamundaIntegration() { return camundaIntegration; } public void setCamundaIntegration(Set<String> camundaIntegration) {
this.camundaIntegration = camundaIntegration; } @Override public LicenseKeyDataImpl getLicenseKey() { return licenseKey; } public void setLicenseKey(LicenseKeyDataImpl licenseKey) { this.licenseKey = licenseKey; } @Override public Set<String> getWebapps() { return webapps; } public void setWebapps(Set<String> webapps) { this.webapps = webapps; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\InternalsImpl.java
1
请完成以下Java代码
public String getSourceRef() { return sourceRef; } public void setSourceRef(String sourceRef) { this.sourceRef = sourceRef; } public String getTargetRef() { return targetRef; } public void setTargetRef(String targetRef) { this.targetRef = targetRef; } public String getSkipExpression() { return skipExpression; } public void setSkipExpression(String skipExpression) { this.skipExpression = skipExpression; } public FlowElement getSourceFlowElement() { return sourceFlowElement; } public void setSourceFlowElement(FlowElement sourceFlowElement) { this.sourceFlowElement = sourceFlowElement; } public FlowElement getTargetFlowElement() { return targetFlowElement; } public void setTargetFlowElement(FlowElement targetFlowElement) { this.targetFlowElement = targetFlowElement;
} public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } public String toString() { return sourceRef + " --> " + targetRef; } public SequenceFlow clone() { SequenceFlow clone = new SequenceFlow(); clone.setValues(this); return clone; } public void setValues(SequenceFlow otherFlow) { super.setValues(otherFlow); setConditionExpression(otherFlow.getConditionExpression()); setSourceRef(otherFlow.getSourceRef()); setTargetRef(otherFlow.getTargetRef()); setSkipExpression(otherFlow.getSkipExpression()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SequenceFlow.java
1
请在Spring Boot框架中完成以下Java代码
public class AppUser { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private long id; private String name; @Column(unique = true) private String username; private String password; private boolean enabled = true; private Date lastLogin; public AppUser() { } public AppUser(String name, String email, String password) { this.username = email; this.name = name; this.password = password; } 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 getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Date getLastLogin() { return lastLogin; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\models\AppUser.java
2
请完成以下Java代码
protected String doIt() { final PricingConditionsBreak pricingConditionsBreak = pricingConditionsRepo.changePricingConditionsBreak(createPricingConditionsBreakChangeRequest(getEditableRow())); patchEditableRow(PricingConditionsRowActions.saved(pricingConditionsBreak)); return MSG_OK; } @Override protected void postProcess(final boolean success) { invalidateView(); } private static PricingConditionsBreakChangeRequest createPricingConditionsBreakChangeRequest(final PricingConditionsRow row) { if (!row.isEditable()) { throw new AdempiereException("Saving not editable rows is not allowed") .setParameter("row", row); } final PricingConditionsId pricingConditionsId = row.getPricingConditionsId();
final PricingConditionsBreak pricingConditionsBreak = row.getPricingConditionsBreak(); final PricingConditionsBreakId updateFromPricingConditionsBreakId = row.getCopiedFromPricingConditionsBreakId(); return preparePricingConditionsBreakChangeRequest(pricingConditionsBreak) .pricingConditionsId(pricingConditionsId) .updateFromPricingConditionsBreakId(updateFromPricingConditionsBreakId) .build(); } private static PricingConditionsBreakChangeRequestBuilder preparePricingConditionsBreakChangeRequest( @NonNull final PricingConditionsBreak pricingConditionsBreak) { return PricingConditionsBreakChangeRequest.builder() .pricingConditionsBreakId(pricingConditionsBreak.getId()) .matchCriteria(pricingConditionsBreak.getMatchCriteria()) .price(pricingConditionsBreak.getPriceSpecification()) .discount(pricingConditionsBreak.getDiscount()) .paymentTermId(Optional.ofNullable(pricingConditionsBreak.getPaymentTermIdOrNull())) .paymentDiscount(Optional.ofNullable(pricingConditionsBreak.getPaymentDiscountOverrideOrNull())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\PricingConditionsView_SaveEditableRow.java
1
请完成以下Java代码
public abstract class AbstractTransactionEvent implements MaterialEvent { private final EventDescriptor eventDescriptor; private final MaterialDescriptor materialDescriptor; @JsonInclude(NON_NULL) private final MinMaxDescriptor minMaxDescriptor; private final Map<Integer, BigDecimal> receiptScheduleIds2Qtys; private final InOutAndLineId receiptId; private final InOutAndLineId shipmentId; private final int transactionId; private final boolean directMovementWarehouse; private final int ppOrderId; private final int ppOrderLineId; private final int ddOrderId; private final int ddOrderLineId; private final int inventoryId; private final int inventoryLineId; private final Collection<HUDescriptor> huOnHandQtyChangeDescriptors; public AbstractTransactionEvent( final EventDescriptor eventDescriptor, final MaterialDescriptor materialDescriptor, @Nullable final MinMaxDescriptor minMaxDescriptor, final Map<Integer, BigDecimal> receiptScheduleIds2Qtys, final InOutAndLineId receiptId, final InOutAndLineId shipmentId, final int ppOrderId, final int ppOrderLineId, final int ddOrderId, final int ddOrderLineId, final int inventoryId, final int inventoryLineId, final int transactionId, final boolean directMovementWarehouse, final Collection<HUDescriptor> huOnHandQtyChangeDescriptors) { this.transactionId = checkIdGreaterThanZero("transactionId", transactionId); this.eventDescriptor = eventDescriptor; this.materialDescriptor = materialDescriptor; this.minMaxDescriptor = minMaxDescriptor; this.huOnHandQtyChangeDescriptors = huOnHandQtyChangeDescriptors; this.receiptScheduleIds2Qtys = receiptScheduleIds2Qtys; this.receiptId = receiptId; this.shipmentId = shipmentId; this.ddOrderId = ddOrderId; this.ddOrderLineId = ddOrderLineId; this.ppOrderId = ppOrderId; this.ppOrderLineId = ppOrderLineId;
// note: they are not yet persisted this.inventoryId = inventoryId; this.inventoryLineId = inventoryLineId; this.directMovementWarehouse = directMovementWarehouse; } /** * Never return {@code null}. */ public abstract BigDecimal getQuantity(); /** * Never return {@code null}. */ public abstract BigDecimal getQuantityDelta(); @OverridingMethodsMustInvokeSuper public void assertValid() { Check.errorIf(eventDescriptor == null, "eventDescriptor may not be null"); Check.errorIf(materialDescriptor == null, "materialDescriptor may not be null"); materialDescriptor.asssertMaterialDescriptorComplete(); } @Nullable @Override public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_M_Transaction.Table_Name, transactionId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\transactions\AbstractTransactionEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class Product { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name = "name") private String name; @Column(name = "description") private String description; @Column(name = "price") private BigDecimal price; @CreationTimestamp private Date createdAt; @CreationTimestamp private Date updatedAt; 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 getDescription() { return description; } public void setDescription(String description) { this.description = description; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
repos\Spring-Boot-Advanced-Projects-main\springboot-crud-hibernate-example\src\main\java\net\alanbinu\springboot\model\Product.java
2
请完成以下Java代码
public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p>
* the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptionPropertyType.java
1
请完成以下Java代码
public Object invoke(MethodInvocation invocation) throws Throwable { return tryConsume(invocation, this::ack, (mac, e) -> { try { int retryCount = tryGetRetryCountOrFail(mac, e); sendToNextRetryQueue(mac, retryCount); } catch (Throwable t) { if (observer != null) { observer.run(); } throw new RuntimeException(t); } }); } void setObserver(Runnable observer) { this.observer = observer; } private Object tryConsume(MethodInvocation invocation, Consumer<MessageAndChannel> successHandler, BiConsumer<MessageAndChannel, Throwable> errorHandler) throws Throwable { MessageAndChannel mac = new MessageAndChannel((Message) invocation.getArguments()[1], (Channel) invocation.getArguments()[0]); Object ret = null; try { ret = invocation.proceed(); successHandler.accept(mac); } catch (Throwable e) { errorHandler.accept(mac, e); } return ret; } private void ack(MessageAndChannel mac) { try { mac.channel.basicAck(mac.message.getMessageProperties() .getDeliveryTag(), false); } catch (Exception e) { throw new RuntimeException(e); } } private int tryGetRetryCountOrFail(MessageAndChannel mac, Throwable originalError) throws Throwable {
MessageProperties props = mac.message.getMessageProperties(); String xRetriedCountHeader = (String) props.getHeader("x-retried-count"); final int xRetriedCount = xRetriedCountHeader == null ? 0 : Integer.valueOf(xRetriedCountHeader); if (retryQueues.retriesExhausted(xRetriedCount)) { mac.channel.basicReject(props.getDeliveryTag(), false); throw originalError; } return xRetriedCount; } private void sendToNextRetryQueue(MessageAndChannel mac, int retryCount) throws Exception { String retryQueueName = retryQueues.getQueueName(retryCount); rabbitTemplate.convertAndSend(retryQueueName, mac.message, m -> { MessageProperties props = m.getMessageProperties(); props.setExpiration(String.valueOf(retryQueues.getTimeToWait(retryCount))); props.setHeader("x-retried-count", String.valueOf(retryCount + 1)); props.setHeader("x-original-exchange", props.getReceivedExchange()); props.setHeader("x-original-routing-key", props.getReceivedRoutingKey()); return m; }); mac.channel.basicReject(mac.message.getMessageProperties() .getDeliveryTag(), false); } private class MessageAndChannel { private Message message; private Channel channel; private MessageAndChannel(Message message, Channel channel) { this.message = message; this.channel = channel; } } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RetryQueuesInterceptor.java
1
请完成以下Java代码
public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("warningMessage", warningMessage) .addValue(list.isEmpty() ? null : list) .toString(); } public Stream<DeviceAccessor> stream() { return list.stream(); } public Stream<DeviceAccessor> stream(final WarehouseId warehouseId) { return stream().filter(deviceAccessor -> deviceAccessor.isAvailableForWarehouse(warehouseId)); } @NonNull public Stream<DeviceAccessor> streamForLocator(final LocatorId locatorId) { return stream().filter(deviceAccessor -> deviceAccessor.isAvailableForLocator(locatorId));
} public DeviceAccessor getByIdOrNull(final DeviceId id) { return byId.get(id); } /** * Convenient (fluent) method to consume the warningMessage if any. */ public void consumeWarningMessageIfAny(final Consumer<String> warningMessageConsumer) { warningMessage.ifPresent(warningMessageConsumer); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceAccessorsList.java
1
请完成以下Java代码
protected List<ProcessInstance> obtainProcessInstances(CommandContext commandContext) { ProcessInstanceQueryImpl query = new ProcessInstanceQueryImpl(); if (processInstanceId != null) { query.processInstanceId(processInstanceId); } else if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } else if (isProcessDefinitionTenantIdSet) { query.processDefinitionKey(processDefinitionKey); if (processDefinitionTenantId != null) { query.tenantIdIn(processDefinitionTenantId); } else { query.withoutTenantId(); } } else { query.processDefinitionKey(processDefinitionKey); } List<ProcessInstance> result = new ArrayList<ProcessInstance>(); result.addAll(commandContext.getExecutionManager().findProcessInstancesByQueryCriteria(query,null)); return result; } @Override protected void logUserOperation(CommandContext commandContext) { PropertyChange propertyChange = new PropertyChange(SUSPENSION_STATE_PROPERTY, null, getNewSuspensionState().getName()); commandContext.getOperationLogManager() .logProcessInstanceOperation(getLogEntryOperation(), processInstanceId, processDefinitionId, processDefinitionKey, Collections.singletonList(propertyChange)); } protected UpdateJobSuspensionStateBuilderImpl createJobCommandBuilder() { UpdateJobSuspensionStateBuilderImpl builder = new UpdateJobSuspensionStateBuilderImpl(); if (processInstanceId != null) { builder.byProcessInstanceId(processInstanceId); } else if (processDefinitionId != null) { builder.byProcessDefinitionId(processDefinitionId);
} else if (processDefinitionKey != null) { builder.byProcessDefinitionKey(processDefinitionKey); if (isProcessDefinitionTenantIdSet && processDefinitionTenantId != null) { return builder.processDefinitionTenantId(processDefinitionTenantId); } else if (isProcessDefinitionTenantIdSet) { return builder.processDefinitionWithoutTenantId(); } } return builder; } @Override protected AbstractSetJobStateCmd getNextCommand() { UpdateJobSuspensionStateBuilderImpl jobCommandBuilder = createJobCommandBuilder(); return getNextCommand(jobCommandBuilder); } protected abstract AbstractSetJobStateCmd getNextCommand(UpdateJobSuspensionStateBuilderImpl jobCommandBuilder); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetProcessInstanceStateCmd.java
1
请完成以下Java代码
public ChildElementCollectionBuilder<T> maxOccurs(int i) { collection.setMaxOccurs(i); return this; } public ChildElementCollectionBuilder<T> minOccurs(int i) { collection.setMinOccurs(i); return this; } public ChildElementCollection<T> build() { return collection; } public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V,T> qNameElementReferenceCollection(Class<V> referenceTargetType) { ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build(); QNameElementReferenceCollectionBuilderImpl<V,T> builder = new QNameElementReferenceCollectionBuilderImpl<V,T>(childElementType, referenceTargetType, collection); setReferenceBuilder(builder); return builder; } public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V, T> idElementReferenceCollection(Class<V> referenceTargetType) { ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build(); ElementReferenceCollectionBuilder<V,T> builder = new ElementReferenceCollectionBuilderImpl<V,T>(childElementType, referenceTargetType, collection); setReferenceBuilder(builder); return builder; } public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V, T> idsElementReferenceCollection(Class<V> referenceTargetType) { ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build(); ElementReferenceCollectionBuilder<V,T> builder = new IdsElementReferenceCollectionBuilderImpl<V,T>(childElementType, referenceTargetType, collection); setReferenceBuilder(builder);
return builder; } public <V extends ModelElementInstance> ElementReferenceCollectionBuilder<V, T> uriElementReferenceCollection(Class<V> referenceTargetType) { ChildElementCollectionImpl<T> collection = (ChildElementCollectionImpl<T>) build(); ElementReferenceCollectionBuilder<V,T> builder = new UriElementReferenceCollectionBuilderImpl<V, T>(childElementType, referenceTargetType, collection); setReferenceBuilder(builder); return builder; } protected void setReferenceBuilder(ElementReferenceCollectionBuilder<?, ?> referenceBuilder) { if (this.referenceBuilder != null) { throw new ModelException("An collection cannot have more than one reference"); } this.referenceBuilder = referenceBuilder; modelBuildOperations.add(referenceBuilder); } public void performModelBuild(Model model) { ModelElementType elementType = model.getType(childElementType); if(elementType == null) { throw new ModelException(parentElementType +" declares undefined child element of type "+childElementType+"."); } parentElementType.registerChildElementType(elementType); parentElementType.registerChildElementCollection(collection); for (ModelBuildOperation modelBuildOperation : modelBuildOperations) { modelBuildOperation.performModelBuild(model); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\child\ChildElementCollectionBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class EdqsConfig { @Value("${queue.edqs.partitions:12}") private int partitions; @Value("${service.edqs.label:}") private String label; @Value("#{'${queue.edqs.partitioning_strategy:tenant}'.toUpperCase()}") private EdqsPartitioningStrategy partitioningStrategy; @Value("${queue.edqs.events_topic:edqs.events}") private String eventsTopic; @Value("${queue.edqs.state_topic:edqs.state}") private String stateTopic; @Value("${queue.edqs.requests_topic:edqs.requests}") private String requestsTopic; @Value("${queue.edqs.responses_topic:edqs.responses}") private String responsesTopic; @Value("${queue.edqs.poll_interval:25}") private long pollInterval; @Value("${queue.edqs.max_pending_requests:10000}") private int maxPendingRequests; @Value("${queue.edqs.max_request_timeout:20000}")
private int maxRequestTimeout; @Value("${queue.edqs.request_executor_size:50}") private int requestExecutorSize; @Value("${queue.edqs.versions_cache_ttl:60}") private int versionsCacheTtl; public String getLabel() { if (partitioningStrategy == EdqsPartitioningStrategy.NONE) { label = "all"; // single set for all instances, so that each instance has all partitions } return label; } public enum EdqsPartitioningStrategy { TENANT, NONE } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\edqs\EdqsConfig.java
2
请完成以下Java代码
void setReadWrite(final boolean readWrite) { this._isReadWrite = readWrite; } public boolean isReadWrite() { return Boolean.TRUE.equals(_isReadWrite); } private void setIsSOTrx(final boolean isSOTrx) { this._isSOTrx = isSOTrx; } public boolean isSOTrx() { return _isSOTrx; } public int getAD_Color_ID() { return AD_Color_ID; } public int getAD_Image_ID() { return AD_Image_ID; } public int getWinWidth() { return WinWidth;
} public int getWinHeight() { return WinHeight; } public String getWindowType() { return WindowType; } private int getBaseTable_ID() { return _BaseTable_ID; } boolean isLoadAllLanguages() { return loadAllLanguages; } boolean isApplyRolePermissions() { return applyRolePermissions; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridWindowVO.java
1
请完成以下Java代码
public Integer getId() { return id; } /** * 设置 主键ID. * * @param id 主键ID. */ public void setId(Integer id) { this.id = id; } /** * 获取 角色ID. * * @return 角色ID. */ public Integer getRoleId() { return roleId; } /** * 设置 角色ID. * * @param roleId 角色ID. */ public void setRoleId(Integer roleId) { this.roleId = roleId; } /** * 获取 权限ID. * * @return 权限ID. */ public Integer getPermissionId() { return permissionId; } /** * 设置 权限ID. * * @param permissionId 权限ID. */ public void setPermissionId(Integer permissionId) { this.permissionId = permissionId;
} /** * 获取 创建时间. * * @return 创建时间. */ public Date getCreatedTime() { return createdTime; } /** * 设置 创建时间. * * @param createdTime 创建时间. */ public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } /** * 获取 更新时间. * * @return 更新时间. */ public Date getUpdatedTime() { return updatedTime; } /** * 设置 更新时间. * * @param updatedTime 更新时间. */ public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } protected Serializable pkVal() { return this.id; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\RolePermission.java
1
请完成以下Java代码
private void proxy() { URI uri = exchange.getRequest().getURI(); appendForwarded(uri); appendXForwarded(uri); } private void appendXForwarded(URI uri) { // Append the legacy headers if they were already added upstream String host = headers.getFirst("x-forwarded-host"); if (host == null) { return; } host = host + "," + uri.getHost(); headers.set("x-forwarded-host", host); String proto = headers.getFirst("x-forwarded-proto"); if (proto == null) { return; } proto = proto + "," + uri.getScheme(); headers.set("x-forwarded-proto", proto); } private void appendForwarded(URI uri) { String forwarded = headers.getFirst("forwarded"); if (forwarded != null) { forwarded = forwarded + ","; } else { forwarded = ""; } forwarded = forwarded + forwarded(uri, exchange.getRequest().getHeaders().getFirst("host")); headers.set("forwarded", forwarded); } private String forwarded(URI uri, @Nullable String hostHeader) { if (StringUtils.hasText(hostHeader)) { return "host=" + hostHeader; } if ("http".equals(uri.getScheme())) { return "host=" + uri.getHost(); } return String.format("host=%s;proto=%s", uri.getHost(), uri.getScheme()); } private @Nullable Publisher<?> body() { Publisher<?> body = this.body; if (body != null) { return body; } body = getRequestBody();
hasBody = true; // even if it's null return body; } /** * Search for the request body if it was already deserialized using * <code>@RequestBody</code>. If it is not found then deserialize it in the same way * that it would have been for a <code>@RequestBody</code>. * @return the request body */ private @Nullable Mono<Object> getRequestBody() { for (String key : bindingContext.getModel().asMap().keySet()) { if (key.startsWith(BindingResult.MODEL_KEY_PREFIX)) { BindingResult result = (BindingResult) bindingContext.getModel().asMap().get(key); Object target = result.getTarget(); if (target != null) { return Mono.just(target); } } } return null; } protected static class BodyGrabber { public Publisher<Object> body(@RequestBody Publisher<Object> body) { return body; } } protected static class BodySender { @ResponseBody public @Nullable Publisher<Object> body() { return null; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webflux\src\main\java\org\springframework\cloud\gateway\webflux\ProxyExchange.java
1
请完成以下Java代码
public Properties getCtx() { return InterfaceWrapperHelper.getCtx(model); } @Override public int get_ID() { return InterfaceWrapperHelper.getId(model); } @Override public int get_Table_ID() { return InterfaceWrapperHelper.getModelTableId(model); } @Override public String get_TrxName() { return InterfaceWrapperHelper.getTrxName(model); } @Override public void set_TrxName(final String trxName) {
InterfaceWrapperHelper.setTrxName(model, trxName); } @Override public boolean isActive() { return model.isActive(); } @Override public Object getModel() { return getDocumentModel(); } @Override public Object getDocumentModel() { return model; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java
1
请完成以下Java代码
public static InvoiceDocBaseType ofSOTrxAndCreditMemo(@NonNull final SOTrx soTrx, final boolean creditMemo) { if (soTrx.isSales()) { return !creditMemo ? CustomerInvoice : CustomerCreditMemo; } else // purchase { return !creditMemo ? VendorInvoice : VendorCreditMemo; } } public static InvoiceDocBaseType ofDocBaseType(@NonNull final DocBaseType docBaseType) { return ofCode(docBaseType.getCode()); } @Override public String getCode() { return getDocBaseType().getCode(); } public boolean isSales() { return getSoTrx().isSales(); } public boolean isPurchase() { return getSoTrx().isPurchase(); } /** * @return is Account Payable (AP), aka purchase * @see #isPurchase()
*/ public boolean isAP() {return isPurchase();} public boolean isCustomerInvoice() { return this == CustomerInvoice; } public boolean isCustomerCreditMemo() { return this == CustomerCreditMemo; } public boolean isVendorCreditMemo() { return this == VendorCreditMemo; } public boolean isIncomingCash() { return (isSales() && !isCreditMemo()) // ARI || (isPurchase() && isCreditMemo()) // APC ; } public boolean isOutgoingCash() { return !isIncomingCash(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceDocBaseType.java
1
请完成以下Java代码
private void onClose(JarFile jarFile) { this.cache.remove(jarFile); } void clearCache() { this.cache.clear(); } /** * Internal cache. */ private static final class Cache { private final Map<JarFileUrlKey, JarFile> jarFileUrlToJarFile = new HashMap<>(); private final Map<JarFile, URL> jarFileToJarFileUrl = new HashMap<>(); /** * Get a {@link JarFile} from the cache given a jar file URL. * @param jarFileUrl the jar file URL * @return the cached {@link JarFile} or {@code null} */ JarFile get(URL jarFileUrl) { JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl); synchronized (this) { return this.jarFileUrlToJarFile.get(urlKey); } } /** * Get a jar file URL from the cache given a jar file. * @param jarFile the jar file * @return the cached {@link URL} or {@code null} */ URL get(JarFile jarFile) { synchronized (this) { return this.jarFileToJarFileUrl.get(jarFile); } } /** * Put the given jar file URL and jar file into the cache if they aren't already * there. * @param jarFileUrl the jar file URL * @param jarFile the jar file * @return {@code true} if the items were added to the cache or {@code false} if
* they were already there */ boolean putIfAbsent(URL jarFileUrl, JarFile jarFile) { JarFileUrlKey urlKey = new JarFileUrlKey(jarFileUrl); synchronized (this) { JarFile cached = this.jarFileUrlToJarFile.get(urlKey); if (cached == null) { this.jarFileUrlToJarFile.put(urlKey, jarFile); this.jarFileToJarFileUrl.put(jarFile, jarFileUrl); return true; } return false; } } /** * Remove the given jar and any related URL file from the cache. * @param jarFile the jar file to remove */ void remove(JarFile jarFile) { synchronized (this) { URL removedUrl = this.jarFileToJarFileUrl.remove(jarFile); if (removedUrl != null) { this.jarFileUrlToJarFile.remove(new JarFileUrlKey(removedUrl)); } } } void clear() { synchronized (this) { this.jarFileToJarFileUrl.clear(); this.jarFileUrlToJarFile.clear(); } } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarFiles.java
1
请完成以下Java代码
protected boolean isQtyProjectedSet() { return _qtyProjectedSet; } protected BigDecimal getQtyProjected() { return _qtyProjected; } @Override public final IQualityInspectionLineBuilder setC_UOM(final I_C_UOM uom) { _uom = uom; _uomSet = true; return this; } protected final I_C_UOM getC_UOM() { if (_uomSet) { return _uom; } else { final IProductionMaterial productionMaterial = getProductionMaterial(); return productionMaterial.getC_UOM(); } } @Override public final IQualityInspectionLineBuilder setPercentage(final BigDecimal percentage) { _percentage = percentage; return this; } private BigDecimal getPercentage() { return _percentage; } @Override public final IQualityInspectionLineBuilder setName(final String name) { _name = name; return this; } protected final String getName() { return _name; }
private IHandlingUnitsInfo getHandlingUnitsInfoToSet() { if (_handlingUnitsInfoSet) { return _handlingUnitsInfo; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfo = handlingUnitsInfo; _handlingUnitsInfoSet = true; return this; } private IHandlingUnitsInfo getHandlingUnitsInfoProjectedToSet() { if (_handlingUnitsInfoProjectedSet) { return _handlingUnitsInfoProjected; } return null; } @Override public IQualityInspectionLineBuilder setHandlingUnitsInfoProjected(final IHandlingUnitsInfo handlingUnitsInfo) { _handlingUnitsInfoProjected = handlingUnitsInfo; _handlingUnitsInfoProjectedSet = true; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLineBuilder.java
1
请完成以下Java代码
public void exportToFile(@NonNull final File file) { try (final FileOutputStream out = new FileOutputStream(file)) { export(out); } catch (final IOException ex) { throw new AdempiereException("Failed exporting to " + file, ex); } } @Value private static final class CellStyleKey { public static CellStyleKey header(final int column) { final int displayType = -1; // N/A final boolean functionRow = false; return new CellStyleKey("header", column, displayType, functionRow); } public static CellStyleKey cell(final int column, final int displayType, final boolean functionRow) { return new CellStyleKey("cell", column, displayType, functionRow); } private final String type;
private final int column; private final int displayType; private final boolean functionRow; private CellStyleKey( final String type, final int column, final int displayType, final boolean functionRow) { this.type = type; this.column = column; this.displayType = displayType; this.functionRow = functionRow; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\AbstractExcelExporter.java
1
请完成以下Java代码
public void paymentDeclined(String transactionId, String cause) { log.info("[I116] Payment declined: transactionId={}, cause={}", transactionId, cause); Workflow.await(() -> payment != null); payment = new PaymentAuthorization( payment.info(), PaymentStatus.DECLINED, payment.orderId(), transactionId, null, cause ); } @Override public void packagePickup(Instant pickupTime) { Workflow.await(() -> shipping != null); shipping = shipping.toStatus(ShippingStatus.SHIPPED, pickupTime, "Package picked up"); } @Override public void packageDelivered(Instant pickupTime) { Workflow.await(() -> shipping != null); shipping = shipping.toStatus(ShippingStatus.DELIVERED, pickupTime, "Package delivered"); } @Override public void packageReturned(Instant pickupTime) { shipping = shipping.toStatus(ShippingStatus.RETURNED, pickupTime, "Package returned"); } @Override public Order getOrder() { return order;
} @Override public Shipping getShipping() { return shipping; } @Override public PaymentAuthorization getPayment() { return payment; } @Override public RefundRequest getRefund() { return refund; } }
repos\tutorials-master\saas-modules\temporal\src\main\java\com\baeldung\temporal\workflows\sboot\order\workflow\OrderWorkflowImpl.java
1
请完成以下Java代码
public List<List<Node>> getNode_() { return node_; } public void setNode_(List<List<Node>> node_) { this.node_ = node_; } public List<Integer> getAnswer_() { return answer_; } public void setAnswer_(List<Integer> answer_) { this.answer_ = answer_; } public List<Integer> getResult_() { return result_; } public void setResult_(List<Integer> result_) { this.result_ = result_; } public static void main(String[] args) throws Exception { if (args.length < 1) { return; } TaggerImpl tagger = new TaggerImpl(Mode.TEST); InputStream stream = null; try { stream = IOUtil.newInputStream(args[0]); } catch (IOException e) { System.err.printf("model not exits for %s", args[0]); return; } if (stream != null && !tagger.open(stream, 2, 0, 1.0)) { System.err.println("open error"); return; } System.out.println("Done reading model"); if (args.length >= 2) { InputStream fis = IOUtil.newInputStream(args[1]);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); while (true) { ReadStatus status = tagger.read(br); if (ReadStatus.ERROR == status) { System.err.println("read error"); return; } else if (ReadStatus.EOF == status) { break; } if (tagger.getX_().isEmpty()) { break; } if (!tagger.parse()) { System.err.println("parse error"); return; } System.out.print(tagger.toString()); } br.close(); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public BigInteger getNetDays() { return netDays; } /** * Sets the value of the netDays property. * * @param value * allowed object is * {@link BigInteger } * */ public void setNetDays(BigInteger value) { this.netDays = value; } /** * Gets the value of the singlevat property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getSinglevat() { return singlevat; } /** * Sets the value of the singlevat property. * * @param value * allowed object is * {@link BigDecimal }
* */ public void setSinglevat(BigDecimal value) { this.singlevat = value; } /** * Gets the value of the taxfree property. * * @return * possible object is * {@link String } * */ public String getTaxfree() { return taxfree; } /** * Sets the value of the taxfree property. * * @param value * allowed object is * {@link String } * */ public void setTaxfree(String value) { this.taxfree = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop120VType.java
2
请在Spring Boot框架中完成以下Java代码
public class Saml2Authentication extends AbstractAuthenticationToken { @Serial private static final long serialVersionUID = 405897702378720477L; private final Object principal; private final String saml2Response; /** * Construct a {@link Saml2Authentication} using the provided parameters * @param principal the logged in user * @param saml2Response the SAML 2.0 response used to authenticate the user * @param authorities the authorities for the logged in user */ public Saml2Authentication(AuthenticatedPrincipal principal, String saml2Response, Collection<? extends GrantedAuthority> authorities) { super(authorities); Assert.notNull(principal, "principal cannot be null"); Assert.hasText(saml2Response, "saml2Response cannot be null"); this.principal = principal; this.saml2Response = saml2Response; setAuthenticated(true); } public Saml2Authentication(Object principal, String saml2Response, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; this.saml2Response = saml2Response; setAuthenticated(true); } Saml2Authentication(Builder<?> builder) { super(builder); this.principal = builder.principal; this.saml2Response = builder.saml2Response; } @Override public Object getPrincipal() { return this.principal; } /** * Returns the SAML response object, as decoded XML. May contain encrypted elements * @return string representation of the SAML Response XML object */ public String getSaml2Response() { return this.saml2Response; }
@Override public Object getCredentials() { return getSaml2Response(); } abstract static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private Object principal; String saml2Response; Builder(Saml2Authentication token) { super(token); this.principal = token.principal; this.saml2Response = token.saml2Response; } @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } void saml2Response(String saml2Response) { this.saml2Response = saml2Response; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2Authentication.java
2
请完成以下Java代码
public CmmnEngineConfiguration setCleanInstancesEndedAfterNumberOfDays(int cleanInstancesEndedAfterNumberOfDays) { return setCleanInstancesEndedAfter(Duration.ofDays(cleanInstancesEndedAfterNumberOfDays)); } public Duration getCleanInstancesEndedAfter() { return cleanInstancesEndedAfter; } public CmmnEngineConfiguration setCleanInstancesEndedAfter(Duration cleanInstancesEndedAfter) { this.cleanInstancesEndedAfter = cleanInstancesEndedAfter; return this; } public int getCleanInstancesBatchSize() { return cleanInstancesBatchSize; } public CmmnEngineConfiguration setCleanInstancesBatchSize(int cleanInstancesBatchSize) { this.cleanInstancesBatchSize = cleanInstancesBatchSize; return this; } public CmmnHistoryCleaningManager getCmmnHistoryCleaningManager() { return cmmnHistoryCleaningManager; } public CmmnEngineConfiguration setCmmnHistoryCleaningManager(CmmnHistoryCleaningManager cmmnHistoryCleaningManager) { this.cmmnHistoryCleaningManager = cmmnHistoryCleaningManager; return this; } public boolean isHandleCmmnEngineExecutorsAfterEngineCreate() { return handleCmmnEngineExecutorsAfterEngineCreate; } public CmmnEngineConfiguration setHandleCmmnEngineExecutorsAfterEngineCreate(boolean handleCmmnEngineExecutorsAfterEngineCreate) { this.handleCmmnEngineExecutorsAfterEngineCreate = handleCmmnEngineExecutorsAfterEngineCreate; return this; } public boolean isAlwaysUseArraysForDmnMultiHitPolicies() { return alwaysUseArraysForDmnMultiHitPolicies; } public CmmnEngineConfiguration setAlwaysUseArraysForDmnMultiHitPolicies(boolean alwaysUseArraysForDmnMultiHitPolicies) { this.alwaysUseArraysForDmnMultiHitPolicies = alwaysUseArraysForDmnMultiHitPolicies; return this; }
public CaseDefinitionLocalizationManager getCaseDefinitionLocalizationManager() { return caseDefinitionLocalizationManager; } public CmmnEngineConfiguration setCaseDefinitionLocalizationManager(CaseDefinitionLocalizationManager caseDefinitionLocalizationManager) { this.caseDefinitionLocalizationManager = caseDefinitionLocalizationManager; return this; } public CaseLocalizationManager getCaseLocalizationManager() { return caseLocalizationManager; } public CmmnEngineConfiguration setCaseLocalizationManager(CaseLocalizationManager caseLocalizationManager) { this.caseLocalizationManager = caseLocalizationManager; return this; } public PlanItemLocalizationManager getPlanItemLocalizationManager() { return planItemLocalizationManager; } public CmmnEngineConfiguration setPlanItemLocalizationManager(PlanItemLocalizationManager planItemLocalizationManager) { this.planItemLocalizationManager = planItemLocalizationManager; return this; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngineConfiguration.java
1
请完成以下Java代码
public void setOneConfigurationPerPI(final boolean oneConfigurationPerPI) { this.oneConfigurationPerPI = oneConfigurationPerPI; } @Override public boolean isOneConfigurationPerPI() { return oneConfigurationPerPI; } @Override public boolean isAllowDifferentCapacities() { return allowDifferentCapacities; } @Override public void setAllowDifferentCapacities(final boolean allowDifferentCapacities) { this.allowDifferentCapacities = allowDifferentCapacities; } @Override public boolean isAllowInfiniteCapacity() { return allowInfiniteCapacity; } @Override public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity) { this.allowInfiniteCapacity = allowInfiniteCapacity; }
@Override public boolean isAllowAnyPartner() { return allowAnyPartner; } @Override public void setAllowAnyPartner(final boolean allowAnyPartner) { this.allowAnyPartner = allowAnyPartner; } @Override public int getM_Product_Packaging_ID() { return packagingProductId; } @Override public void setM_Product_Packaging_ID(final int packagingProductId) { this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java
1
请完成以下Java代码
protected void applyFilters(UserQuery query) { if (id != null) { query.userId(id); } if(idIn != null) { query.userIdIn(idIn); } if (firstName != null) { query.userFirstName(firstName); } if (firstNameLike != null) { query.userFirstNameLike(firstNameLike); } if (lastName != null) { query.userLastName(lastName); } if (lastNameLike != null) { query.userLastNameLike(lastNameLike); } if (email != null) { query.userEmail(email); } if (emailLike != null) { query.userEmailLike(emailLike); } if (memberOfGroup != null) { query.memberOfGroup(memberOfGroup); } if (potentialStarter != null) { query.potentialStarter(potentialStarter); } if (tenantId != null) { query.memberOfTenant(tenantId); }
} @Override protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_USER_ID_VALUE)) { query.orderByUserId(); } else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) { query.orderByUserFirstName(); } else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) { query.orderByUserLastName(); } else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) { query.orderByUserEmail(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java
1
请完成以下Java代码
public void ifDescriptionChanged(ProjectDescription current, BiConsumer<String, String> consumer) { if (!Objects.equals(this.original.getDescription(), current.getDescription())) { consumer.accept(this.original.getDescription(), current.getDescription()); } } /** * Calls the specified consumer if the {@code applicationName} is different on the * original source project description than the specified project description. * @param current the description to test against * @param consumer to call if the property has changed */ public void ifApplicationNameChanged(ProjectDescription current, BiConsumer<String, String> consumer) { if (!Objects.equals(this.original.getApplicationName(), current.getApplicationName())) { consumer.accept(this.original.getApplicationName(), current.getApplicationName()); } } /** * Calls the specified consumer if the {@code packageName} is different on the * original source project description than the specified project description. * @param current the description to test against * @param consumer to call if the property has changed */ public void ifPackageNameChanged(ProjectDescription current, BiConsumer<String, String> consumer) { if (!Objects.equals(this.original.getPackageName(), current.getPackageName())) {
consumer.accept(this.original.getPackageName(), current.getPackageName()); } } /** * Calls the specified consumer if the {@code baseDirectory} is different on the * original source project description than the specified project description. * @param current the description to test against * @param consumer to call if the property has changed */ public void ifBaseDirectoryChanged(ProjectDescription current, BiConsumer<String, String> consumer) { if (!Objects.equals(this.original.getBaseDirectory(), current.getBaseDirectory())) { consumer.accept(this.original.getBaseDirectory(), current.getBaseDirectory()); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\ProjectDescriptionDiff.java
1
请完成以下Java代码
public class UserEvent implements Serializable { private final String userId; private final String eventType; private final long timestamp; private final Address address; public UserEvent(String userId, String eventType, long timestamp, Address address) { this.userId = userId; this.eventType = eventType; this.timestamp = timestamp; this.address = address; } // Getters and setters public String getUserId() { return userId; } public String getEventType() { return eventType; } public long getTimestamp() {
return timestamp; } public Address getAddress() { return address; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserEvent)) return false; UserEvent userEvent = (UserEvent) o; return timestamp == userEvent.timestamp && userId.equals(userEvent.userId) && eventType.equals(userEvent.eventType) && address.equals(userEvent.address); } @Override public int hashCode() { return Objects.hash(userId, eventType, timestamp, address); } }
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\apachefury\event\UserEvent.java
1
请完成以下Java代码
public class NonAlphaNumericChecker { /** * Checks for non-alphanumeric characters in any Unicode Script * @param str - String to check for special characters * @return true if special character found else false */ public static boolean isNonAlphanumericAnyLangScript(String str) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!Character.isLetterOrDigit(c)) { return true; } } return false; } /** * checks for special characters,returns false if any character * found other than the script argument * @param str - String to check for special characters * @param script - Language script * @return true if special character found else false
*/ public static boolean isNonAlphanumericInLangScript(String str, String script) { for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); // script e.g., Character.UnicodeScript.of(c).toString().equalsIgnoreCase(Character.UnicodeScript.LATIN.toString()) if (!Character.UnicodeScript.of(c).toString().equalsIgnoreCase(script) && !Character.isDigit(c)) { return true; } } return false; } /** * checks for special characters in any lang * @param str - String to check for special characters * @return true if special character found else false */ public static boolean isNonAlphanumericAnyLangScriptV2(String str) { return !StringUtils.isAlphanumeric(str); } }
repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\nonalphanumeric\NonAlphaNumericChecker.java
1
请完成以下Java代码
public String getAmtInWords (String amount) throws Exception { if (amount == null) return amount; // int numberOfCommas = 0; int numberOfPeriods = 0; StringBuffer sb = new StringBuffer (); int period = amount.lastIndexOf ('.'); numberOfPeriods = amount.replaceAll("[^\\.]","").length(); int comma = amount.lastIndexOf (','); numberOfCommas = amount.replaceAll("[^,]","").length(); int newpos = 0; String decamt =""; if (comma > period) //like 1.000.000,89 or 1,000,000 or 120,355 (a hundred and twenty 355/1000) { if (period != -1) //like 1.000.000,89 { decamt = amount.substring(comma+1,amount.length()); amount = amount.replaceAll ("\\.", ""); newpos = amount.lastIndexOf (',')+1; } else if ((amount.length()-comma-1) <=2 ) { decamt = amount.substring(comma+1,amount.length()); newpos = comma+1; } else //like 1,000,000 { decamt = ""; amount = amount.replaceAll (",", ""); newpos = 0; } } if (comma < period) //like 1,000.09 or 1.000.000 or 120.355 (a hundred and twenty 355/100) { if ((comma !=-1) | (numberOfPeriods ==1))//like 1,000.09 { decamt = amount.substring(period+1,amount.length()); amount = amount.replaceAll (",", ""); newpos = amount.lastIndexOf ('.')+1; } else //like 1.000.000 { decamt = ""; amount = amount.replaceAll ("\\.", ""); newpos = 0; } } else if ((comma==-1) && (period ==-1)) //like 1000000 { decamt = ""; newpos = 0; } long dollars = 0; long decima = 0; if (newpos !=0) { dollars = Long.parseLong(amount.substring (0, newpos-1)); sb.append (convert (dollars)); decima = Long.parseLong(decamt); sb.append(" phẩy ").append(convert(decima)); } else { dollars = Long.parseLong(amount.substring(0,amount.length())); sb.append (convert(dollars));
} return sb.toString ().replaceAll(" ", " ").replaceAll("linh nghìn", "nghìn").replaceAll("linh triệu","triệu").replaceAll("linh tỉ","tỉ"); } // getAmtInWords /** * Test Print * @param amt amount */ private void print (String amt) { try { System.out.println(amt + " = " + getAmtInWords(amt)); } catch (Exception e) { e.printStackTrace(); } } // print /** * Test * @param args ignored */ public static void main (String[] args) { AmtInWords_VI aiw = new AmtInWords_VI(); // aiw.print (".23"); Error aiw.print ("0.23"); aiw.print ("1.23"); aiw.print ("12,345"); aiw.print ("103.45"); aiw.print ("114,45"); aiw.print ("123.45"); aiw.print ("500000000"); aiw.print ("1234.56"); aiw.print ("12345.78"); aiw.print ("100457.89"); aiw.print ("100,234,578.90"); aiw.print ("12,034,578.90"); aiw.print ("103,004,008.90"); aiw.print ("1,201,034,578.90"); aiw.print ("12,201,034,578.90"); aiw.print ("10220134578"); aiw.print ("1.093.201.034.578"); aiw.print ("100,932,010,345,780"); aiw.print ("109.320.103,48"); } // main } // AmtInWords_VI
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\AmtInWords_VI.java
1
请完成以下Java代码
final class DelimitedStringToArrayConverter implements ConditionalGenericConverter { private final ConversionService conversionService; DelimitedStringToArrayConverter(ConversionService conversionService) { Assert.notNull(conversionService, "'conversionService' must not be null"); this.conversionService = conversionService; } @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(String.class, Object[].class)); } @Override public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { return targetType.getElementTypeDescriptor() == null || this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor()); } @Override public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } return convert((String) source, sourceType, targetType); } private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) {
Delimiter delimiter = targetType.getAnnotation(Delimiter.class); String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ","); TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); Assert.state(elementDescriptor != null, "elementDescriptor is missing"); Object target = Array.newInstance(elementDescriptor.getType(), elements.length); for (int i = 0; i < elements.length; i++) { String sourceElement = elements[i]; Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, elementDescriptor); Array.set(target, i, targetElement); } return target; } private String[] getElements(String source, String delimiter) { return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DelimitedStringToArrayConverter.java
1
请在Spring Boot框架中完成以下Java代码
public Injector<TransactionManager> getTransactionManagerInjector() { return transactionManagerInjector; } public Injector<DataSourceReferenceFactoryService> getDatasourceBinderServiceInjector() { return datasourceBinderServiceInjector; } public InjectedValue<MscRuntimeContainerJobExecutor> getMscRuntimeContainerJobExecutorInjector() { return mscRuntimeContainerJobExecutorInjector; } public static void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration, MscManagedProcessEngineController service, ServiceBuilder<ProcessEngine> serviceBuilder, String jobExecutorName) { ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName()); serviceBuilder.addDependency(ServiceName.JBOSS.append("txn").append("TransactionManager"), TransactionManager.class, service.getTransactionManagerInjector()) .addDependency(datasourceBindInfo.getBinderServiceName(), DataSourceReferenceFactoryService.class, service.getDatasourceBinderServiceInjector()) .addDependency(ServiceNames.forMscRuntimeContainerDelegate(), MscRuntimeContainerDelegate.class, service.getRuntimeContainerDelegateInjector()) .addDependency(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName), MscRuntimeContainerJobExecutor.class, service.getMscRuntimeContainerJobExecutorInjector()) .addDependency(ServiceNames.forMscExecutorService())
.setInitialMode(Mode.ACTIVE); if(processEngineConfiguration.isDefault()) { serviceBuilder.addAliases(ServiceNames.forDefaultProcessEngine()); } JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder, service.getExecutorInjector(), false); } public ProcessEngine getProcessEngine() { return processEngine; } public InjectedValue<ExecutorService> getExecutorInjector() { return executorInjector; } public ManagedProcessEngineMetadata getProcessEngineMetadata() { return processEngineMetadata; } }
repos\camunda-bpm-platform-master\distro\wildfly26\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngineController.java
2
请完成以下Java代码
private void consolidate_FromLUs_ToNewLU(@NonNull final List<I_M_HU> fromLUs, @NonNull final HuPackingInstructionsId luPackingInstructionsId) { throw new UnsupportedOperationException(); // TODO } @SuppressWarnings("unused") private void consolidate_FromLUs_ToExistingLU(@NonNull final List<I_M_HU> fromLUs, @NonNull final HuId luId, @NonNull final HUQRCode luQRCode) { throw new UnsupportedOperationException(); // TODO } private void consolidateFromTUs(@NonNull final List<I_M_HU> fromTUs) { if (fromTUs.isEmpty()) { return; } getCurrentTarget().apply(new HUConsolidationTarget.CaseConsumer() { @Override public void newLU(final HuPackingInstructionsId luPackingInstructionsId) {consolidate_FromTUs_ToNewLU(fromTUs, luPackingInstructionsId);} @Override public void existingLU(final HuId luId, final HUQRCode luQRCode) {consolidate_FromTUs_ToExistingLU(fromTUs, luId);} }); } private void consolidate_FromTUs_ToNewLU(@NonNull final List<I_M_HU> fromTUs, @NonNull final HuPackingInstructionsId luPackingInstructionsId) { if (fromTUs.isEmpty()) { return; } final I_M_HU firstTU = fromTUs.get(0);
final I_M_HU lu = huTransformService.tuToNewLU(firstTU, QtyTU.ONE, luPackingInstructionsId) .getSingleLURecord(); if (fromTUs.size() > 1) { final List<I_M_HU> remainingTUs = fromTUs.subList(1, fromTUs.size()); huTransformService.tusToExistingLU(remainingTUs, lu); } final HuId luId = HuId.ofRepoId(lu.getM_HU_ID()); final HUQRCode qrCode = huQRCodesService.getQRCodeByHuId(luId); setCurrentTarget(HUConsolidationTarget.ofExistingLU(luId, qrCode)); } private void consolidate_FromTUs_ToExistingLU(@NonNull final List<I_M_HU> fromTUs, @NonNull final HuId luId) { huTransformService.tusToExistingLUId(fromTUs, luId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\commands\consolidate\ConsolidateCommand.java
1
请在Spring Boot框架中完成以下Java代码
ProblemDetail handleError(HttpServletRequest request, Throwable error, HttpStatus status, String reason) { String requestURI = request.getRequestURI(); StringBuffer requestURL = request.getRequestURL(); if (requestURL != null) { requestURI = requestURL.toString(); } String method = request.getMethod(); String queryString = StringUtils.hasText(request.getQueryString()) ? "?" + request.getQueryString() : ""; log.error("Failed to process {}: {}{}", method, requestURI, queryString, error); ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(error)); return createProblemDetail(status, reason, error); } ProblemDetail createProblemDetail(HttpStatus status, String reason, Throwable error) { var pd = ProblemDetail.forStatus(status); pd.setTitle(status.getReasonPhrase()); pd.setDetail(error.toString());
pd.setProperty("reason", reason); pd.setProperty("series", status.series()); pd.setProperty("rootCause", ExceptionUtils.getRootCause(error).toString()); pd.setProperty("trace", getTraceParent()); return pd; } String getTraceParent() { Span span = tracer.currentSpan(); if (span == null) { return ""; } return "%s-%s".formatted(span.context().traceId(), span.context().spanId()); } }
repos\spring-boot-web-application-sample-master\common\src\main\java\gt\common\config\CommonExceptionHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class BPartnerId implements RepoIdAware { public final static BPartnerId NONE = BPartnerId.ofRepoId(Integer.MAX_VALUE); int repoId; public static BPartnerId ofRepoId(final int repoId) { return new BPartnerId(repoId); } @Nullable public static BPartnerId ofRepoIdOrNull(@Nullable final Integer repoId) { return repoId != null && repoId > 0 ? new BPartnerId(repoId) : null; } @Nullable public static BPartnerId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new BPartnerId(repoId) : null; } public static Optional<BPartnerId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } @JsonCreator public static BPartnerId ofObject(@NonNull final Object object) {
return RepoIdAwares.ofObject(object, BPartnerId.class, BPartnerId::ofRepoId); } public static int toRepoId(@Nullable final BPartnerId bpartnerId) { return toRepoIdOr(bpartnerId, -1); } public static int toRepoIdOr(@Nullable final BPartnerId bpartnerId, final int defaultValue) { return bpartnerId != null ? bpartnerId.getRepoId() : defaultValue; } private BPartnerId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "C_BPartner_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final BPartnerId o1, @Nullable final BPartnerId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerId.java
2
请完成以下Java代码
public HistoricActivityInstanceQueryImpl orderByHistoricActivityInstanceStartTime() { orderBy(HistoricActivityInstanceQueryProperty.START); return this; } @Override public HistoricActivityInstanceQuery orderByActivityId() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_ID); return this; } @Override public HistoricActivityInstanceQueryImpl orderByActivityName() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_NAME); return this; } @Override public HistoricActivityInstanceQueryImpl orderByActivityType() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_TYPE); return this; } @Override public HistoricActivityInstanceQueryImpl orderByTenantId() { orderBy(HistoricActivityInstanceQueryProperty.TENANT_ID); return this; } @Override public HistoricActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } // getters and setters ////////////////////////////////////////////////////// public String getProcessInstanceId() {
return processInstanceId; } public String getExecutionId() { return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() { return activityType; } public String getAssignee() { return assignee; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请完成以下Java代码
public static final UnlockFailedException wrapIfNeeded(final Exception e) { if (e instanceof UnlockFailedException) { return (UnlockFailedException)e; } else { return new UnlockFailedException("Unlock failed: " + e.getLocalizedMessage(), e); } } public UnlockFailedException(String message) { super(message); } public UnlockFailedException(String message, Throwable cause) { super(message, cause); } public UnlockFailedException setUnlockCommand(final IUnlockCommand unlockCommand) { setParameter("Unlock command", unlockCommand); return this; } @Override public UnlockFailedException setSql(final String sql, final Object[] sqlParams) {
super.setSql(sql, sqlParams); return this; } public UnlockFailedException setRecordToLock(final TableRecordReference recordToLock) { super.setRecord(recordToLock); return this; } @Override public UnlockFailedException setParameter(@NonNull String name, Object value) { super.setParameter(name, value); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\exceptions\UnlockFailedException.java
1
请在Spring Boot框架中完成以下Java代码
public class BulkMoveDeadLetterJobsToHistoryJobsCmd implements Command<Void> { private static final Logger LOGGER = LoggerFactory.getLogger(BulkMoveDeadLetterJobsToHistoryJobsCmd.class); protected JobServiceConfiguration jobServiceConfiguration; protected Collection<String> deadLetterJobIds; protected int retries; public BulkMoveDeadLetterJobsToHistoryJobsCmd(Collection<String> deadLetterJobIds, int retries, JobServiceConfiguration jobServiceConfiguration) { this.deadLetterJobIds = deadLetterJobIds; this.retries = retries; this.jobServiceConfiguration = jobServiceConfiguration; } @Override public Void execute(CommandContext commandContext) {
if (deadLetterJobIds == null) { throw new FlowableIllegalArgumentException("deadLetterJobIds are null"); } DeadLetterJobQueryImpl query = new DeadLetterJobQueryImpl(commandContext, jobServiceConfiguration); query.jobIds(deadLetterJobIds); List<Job> deadLetterJobs = jobServiceConfiguration.getDeadLetterJobEntityManager().findJobsByQueryCriteria(query); for (Job job : deadLetterJobs) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Moving deadletter job to history job table {}", job.getId()); } jobServiceConfiguration.getJobManager().moveDeadLetterJobToHistoryJob((DeadLetterJobEntity) job, retries); } return null; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\BulkMoveDeadLetterJobsToHistoryJobsCmd.java
2
请在Spring Boot框架中完成以下Java代码
public BigDecimal getPlatIncome() { return platIncome; } public void setPlatIncome(BigDecimal platIncome) { this.platIncome = platIncome; } public BigDecimal getFeeRate() { return feeRate; } public void setFeeRate(BigDecimal feeRate) { this.feeRate = feeRate; } public BigDecimal getPlatCost() { return platCost; } public void setPlatCost(BigDecimal platCost) { this.platCost = platCost; } public BigDecimal getPlatProfit() { return platProfit; } public void setPlatProfit(BigDecimal platProfit) { this.platProfit = platProfit; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode == null ? null : payWayCode.trim(); } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName == null ? null : payWayName.trim(); } public Date getPaySuccessTime() { return paySuccessTime;
} public void setPaySuccessTime(Date paySuccessTime) { this.paySuccessTime = paySuccessTime; } public Date getCompleteTime() { return completeTime; } public void setCompleteTime(Date completeTime) { this.completeTime = completeTime; } public String getIsRefund() { return isRefund; } public void setIsRefund(String isRefund) { this.isRefund = isRefund == null ? null : isRefund.trim(); } public Short getRefundTimes() { return refundTimes; } public void setRefundTimes(Short refundTimes) { this.refundTimes = refundTimes; } public BigDecimal getSuccessRefundAmount() { return successRefundAmount; } public void setSuccessRefundAmount(BigDecimal successRefundAmount) { this.successRefundAmount = successRefundAmount; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistakeScratchPool.java
2
请完成以下Java代码
public TimerEntity createTimer(ExecutionEntity execution) { TimerEntity timer = super.createJobInstance(execution); scheduleTimer(timer); return timer; } protected void scheduleTimer(TimerEntity timer) { Context .getCommandContext() .getJobManager() .schedule(timer); } protected ExecutionEntity resolveExecution(ExecutionEntity context) { return context; } @Override protected JobHandlerConfiguration resolveJobHandlerConfiguration(ExecutionEntity context) { return resolveJobHandler().newConfiguration(rawJobHandlerConfiguration); } /** * @return all timers declared in the given scope */ public static Map<String, TimerDeclarationImpl> getDeclarationsForScope(PvmScope scope) { if (scope == null) { return Collections.emptyMap(); } Map<String, TimerDeclarationImpl> result = scope.getProperties().get(BpmnProperties.TIMER_DECLARATIONS); if (result != null) { return result; } else { return Collections.emptyMap(); } }
/** * @return all timeout listeners declared in the given scope */ public static Map<String, Map<String, TimerDeclarationImpl>> getTimeoutListenerDeclarationsForScope(PvmScope scope) { if (scope == null) { return Collections.emptyMap(); } Map<String, Map<String, TimerDeclarationImpl>> result = scope.getProperties().get(BpmnProperties.TIMEOUT_LISTENER_DECLARATIONS); if (result != null) { return result; } else { return Collections.emptyMap(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\TimerDeclarationImpl.java
1
请完成以下Java代码
protected boolean tryAcquire(int arg) { // 获取锁有竞争所以需要使用CAS原子操作 if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } @Override protected boolean tryRelease(int arg) { // 只有获取到锁的线程才会解锁,所以这里没有竞争,直接使用setState方法在来改变同步状态 setState(0); setExclusiveOwnerThread(null); return true; } @Override protected boolean isHeldExclusively() { // 如果货物到锁,当前线程独占 return getState() == 1; } // 返回一个Condition,每个condition都包含了一个condition队列 Condition newCondition() { return new ConditionObject(); } } // 仅需要将操作代理到Sync上即可 private final Sync sync = new Sync(); @Override public void lock() { sync.acquire(1); } @Override public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } @Override public boolean tryLock() { return sync.tryRelease(1); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(time)); } @Override public void unlock() {
sync.release(0); } @Override public Condition newCondition() { return sync.newCondition(); } public static void main(String[] args) { MutexLock lock = new MutexLock(); final User user = new User(); for (int i = 0; i < 100; i++) { new Thread(() -> { lock.lock(); try { user.setAge(user.getAge() + 1); System.out.println(user.getAge()); } finally { lock.unlock(); } }).start(); } } }
repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\MutexLock.java
1
请完成以下Java代码
public String login() { return "login"; } @lombok.Data @lombok.Builder public static class Settings { private final String title; private final String brand; private final String loginIcon; private final String favicon; private final String faviconDanger; private final PollTimer pollTimer; private final UiTheme theme; private final boolean notificationFilterEnabled; private final boolean rememberMeEnabled; private final List<String> availableLanguages; private final List<String> routes; private final List<ExternalView> externalViews; private final List<ViewSettings> viewSettings; private final Boolean enableToasts; private final Boolean hideInstanceUrl; private final Boolean disableInstanceUrl; } @lombok.Data @JsonInclude(Include.NON_EMPTY) public static class ExternalView { /** * Label to be shown in the navbar. */ private final String label; /** * Url for the external view to be linked */ private final String url; /** * Order in the navbar. */ private final Integer order;
/** * Should the page shown as an iframe or open in a new window. */ private final boolean iframe; /** * A list of child views. */ private final List<ExternalView> children; public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) { Assert.hasText(label, "'label' must not be empty"); if (isEmpty(children)) { Assert.hasText(url, "'url' must not be empty"); } this.label = label; this.url = url; this.order = order; this.iframe = iframe; this.children = children; } } @lombok.Data @JsonInclude(Include.NON_EMPTY) public static class ViewSettings { /** * Name of the view to address. */ private final String name; /** * Set view enabled. */ private boolean enabled; public ViewSettings(String name, boolean enabled) { Assert.hasText(name, "'name' must not be empty"); this.name = name; this.enabled = enabled; } } }
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java
1
请完成以下Java代码
public Builder setIsSOTrx(final boolean isSOTrx) { this.isSOTrx = isSOTrx; return this; } public boolean isSOTrx() { return isSOTrx; } public BPartnerId getBPartnerId() { return bpartnerId; } public Builder setBPartnerId(final BPartnerId bpartnerId) { this.bpartnerId = bpartnerId; return this; } public @Nullable BankAccountId getBPartnerBankAccountId() { return bpBankAccountId; } public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId) { this.bpBankAccountId = bpBankAccountId; return this; } public BigDecimal getOpenAmt() { return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO);
} public Builder setOpenAmt(final BigDecimal openAmt) { this._openAmt = openAmt; return this; } public BigDecimal getPayAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(discountAmt); } public BigDecimal getDiscountAmt() { return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO); } public Builder setDiscountAmt(final BigDecimal discountAmt) { this._discountAmt = discountAmt; return this; } public BigDecimal getDifferenceAmt() { final BigDecimal openAmt = getOpenAmt(); final BigDecimal payAmt = getPayAmt(); final BigDecimal discountAmt = getDiscountAmt(); return openAmt.subtract(payAmt).subtract(discountAmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java
1
请完成以下Java代码
public class SerializableCloneableSingleton implements SingletonInterface, Serializable, Cloneable { private static final long serialVersionUID = -1917003064592196223L; private int state; private SerializableCloneableSingleton() { } private static class SingletonHolder { public static final SerializableCloneableSingleton instance = new SerializableCloneableSingleton(); } public static SerializableCloneableSingleton getInstance() { return SingletonHolder.instance; } @Override public String describeMe() { throw new UnsupportedOperationException("Not Supported Here"); } @Override public String passOnLocks(MyLock lock) { throw new UnsupportedOperationException("Not Supported Here"); } @Override public void increment() {
this.state++; } public int getState() { return state; } private Object readResolve() throws ObjectStreamException { return SingletonHolder.instance; } public Object cloneObject() throws CloneNotSupportedException { return this.clone(); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\staticsingletondifference\SerializableCloneableSingleton.java
1
请完成以下Java代码
public CsrfProperties getCsrf() { return csrf; } public void setCsrf(CsrfProperties csrf) { this.csrf = csrf; } public SessionCookieProperties getSessionCookie() { return sessionCookie; } public void setSessionCookie(SessionCookieProperties sessionCookie) { this.sessionCookie = sessionCookie; } public HeaderSecurityProperties getHeaderSecurity() { return headerSecurity; } public void setHeaderSecurity(HeaderSecurityProperties headerSecurity) { this.headerSecurity = headerSecurity; } public AuthenticationProperties getAuth() {
return auth; } public void setAuth(AuthenticationProperties authentication) { this.auth = authentication; } @Override public String toString() { return joinOn(this.getClass()) .add("indexRedirectEnabled=" + indexRedirectEnabled) .add("webjarClasspath='" + webjarClasspath + '\'') .add("securityConfigFile='" + securityConfigFile + '\'') .add("webappPath='" + applicationPath + '\'') .add("csrf='" + csrf + '\'') .add("headerSecurityProperties='" + headerSecurity + '\'') .add("sessionCookie='" + sessionCookie + '\'') .add("auth='" + auth + '\'') .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\WebappProperty.java
1
请完成以下Java代码
public String getProcessInstanceBusinessKeyLike() { return processInstanceBusinessKeyLike; } public Date getDueDate() { return dueDate; } public Date getDueBefore() { return dueBefore; } public Date getDueAfter() { return dueAfter; } public boolean isWithoutDueDate() { return withoutDueDate; } public SuspensionState getSuspensionState() { return suspensionState; } public boolean isIncludeTaskLocalVariables() { return includeTaskLocalVariables; } public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isBothCandidateAndAssigned() { return bothCandidateAndAssigned; }
public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getLocale() { return locale; } public boolean isOrActive() { return orActive; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
public Date getCreationDate() { return creationDate; } public String getCandidateUser() { return candidateUser; } public String getCandidateGroup() { return candidateGroup; } public String getInvolvedUser() { return involvedUser; } public List<String> getInvolvedGroups() { return involvedGroups; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; }
public String getTaskNameLikeIgnoreCase() { return taskNameLikeIgnoreCase; } public String getTaskDescriptionLikeIgnoreCase() { return taskDescriptionLikeIgnoreCase; } public String getTaskOwnerLikeIgnoreCase() { return taskOwnerLikeIgnoreCase; } public String getTaskAssigneeLikeIgnoreCase() { return taskAssigneeLikeIgnoreCase; } public String getLocale() { return locale; } public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class CourseResource { private final CourseJpaRepository courseRepository; public CourseResource(CourseJpaRepository courseRepository) { this.courseRepository = courseRepository; } @GetMapping public List<Course> getAllCourses(@PathVariable String username) { return courseRepository.findAll(); } @GetMapping("/{id}") public Course getCourse(@PathVariable String username, @PathVariable long id) { return courseRepository.findById(id) .orElseThrow(() -> new RuntimeException("Course Not Found with id " + id)); } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteCourse(@PathVariable String username, @PathVariable long id) { courseRepository.deleteById(id); return ResponseEntity.noContent().build(); }
@PutMapping("/{id}") public ResponseEntity<Course> updateCourse(@PathVariable String username, @PathVariable long id, @RequestBody Course course) { course.setUsername(username); var updatedCourse = courseRepository.save(course); return new ResponseEntity<>(updatedCourse, HttpStatus.OK); } @PostMapping public ResponseEntity<Void> createCourse(@PathVariable String username, @RequestBody Course course) { course.setUsername(username); var createdCourse = courseRepository.save(course); URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(createdCourse.getId()) .toUri(); return ResponseEntity.created(uri).build(); } }
repos\spring-boot-examples-master\spring-boot-react-examples\spring-boot-react-jpa-hibernate-with-h2-full-stack\backend-spring-boot-react-jpa-hibernate-with-h2-full-stack\src\main\java\com\in28minutes\fullstack\springboot\jpa\hibernate\springbootjpahibernatewithh2fullstack\course\CourseResource.java
2
请完成以下Java代码
public Class<? extends EventLogEntryEntity> getManagedEntityClass() { return EventLogEntryEntityImpl.class; } @Override public EventLogEntryEntity create() { return new EventLogEntryEntityImpl(); } @Override @SuppressWarnings("unchecked") public List<EventLogEntry> findAllEventLogEntries() { return getDbSqlSession().selectList("selectAllEventLogEntries"); } @Override @SuppressWarnings("unchecked") public List<EventLogEntry> findEventLogEntries(long startLogNr, long pageSize) { Map<String, Object> params = new HashMap<String, Object>(2);
params.put("startLogNr", startLogNr); if (pageSize > 0) { params.put("endLogNr", startLogNr + pageSize + 1); } return getDbSqlSession().selectList("selectEventLogEntries", params); } @Override @SuppressWarnings("unchecked") public List<EventLogEntry> findEventLogEntriesByProcessInstanceId(String processInstanceId) { Map<String, Object> params = new HashMap<String, Object>(2); params.put("processInstanceId", processInstanceId); return getDbSqlSession().selectList("selectEventLogEntriesByProcessInstanceId", params); } @Override public void deleteEventLogEntry(long logNr) { getDbSqlSession().getSqlSession().delete("deleteEventLogEntry", logNr); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisEventLogEntryDataManager.java
1
请完成以下Java代码
private boolean isInvalidType(MethodParameter parameter, @Nullable Object value) { if (value == null) { return false; } Class<?> typeToCheck = parameter.getParameterType(); boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType()); if (isParameterPublisher) { ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter); Class<?> genericType = resolvableType.resolveGeneric(0); if (genericType == null) { return false; } typeToCheck = genericType; } return !typeToCheck.isAssignableFrom(value.getClass()); } /** * Configure CurrentSecurityContext template resolution * <p> * By default, this value is <code>null</code>, which indicates that templates should * not be resolved. * @param templateDefaults - whether to resolve CurrentSecurityContext templates * parameters * @since 6.4 */ public void setTemplateDefaults(AnnotationTemplateExpressionDefaults templateDefaults) { this.useAnnotationTemplate = templateDefaults != null; this.scanner = SecurityAnnotationScanners.requireUnique(CurrentSecurityContext.class, templateDefaults); }
/** * Obtains the specified {@link Annotation} on the specified {@link MethodParameter}. * @param parameter the {@link MethodParameter} to search for an {@link Annotation} * @return the {@link Annotation} that was found or null. */ private @Nullable CurrentSecurityContext findMethodAnnotation(MethodParameter parameter) { if (this.useAnnotationTemplate) { return this.scanner.scan(parameter.getParameter()); } CurrentSecurityContext annotation = parameter.getParameterAnnotation(this.annotationType); if (annotation != null) { return annotation; } Annotation[] annotationsToSearch = parameter.getParameterAnnotations(); for (Annotation toSearch : annotationsToSearch) { annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType); if (annotation != null) { return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize(); } } return null; } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\handler\invocation\reactive\CurrentSecurityContextArgumentResolver.java
1
请完成以下Java代码
public static MSLACriteria get (Properties ctx, int PA_SLA_Criteria_ID, String trxName) { Integer key = new Integer (PA_SLA_Criteria_ID); MSLACriteria retValue = (MSLACriteria) s_cache.get (key); if (retValue != null) return retValue; retValue = new MSLACriteria (ctx, PA_SLA_Criteria_ID, trxName); if (retValue.get_ID () != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer,MSLACriteria> s_cache = new CCache<Integer,MSLACriteria>("PA_SLA_Criteria", 20); /** * Standard Constructor * @param ctx context * @param PA_SLA_Criteria_ID id * @param trxName transaction */ public MSLACriteria (Properties ctx, int PA_SLA_Criteria_ID, String trxName) { super (ctx, PA_SLA_Criteria_ID, trxName); } // MSLACriteria /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MSLACriteria (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MSLACriteria /** * Get Goals of Criteria * @return array of Goals */ public MSLAGoal[] getGoals() { String sql = "SELECT * FROM PA_SLA_Goal " + "WHERE PA_SLA_Criteria_ID=?"; ArrayList<MSLAGoal> list = new ArrayList<MSLAGoal>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, get_TrxName()); pstmt.setInt (1, getPA_SLA_Criteria_ID()); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add(new MSLAGoal(getCtx(), rs, get_TrxName())); rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e)
{ pstmt = null; } MSLAGoal[] retValue = new MSLAGoal[list.size ()]; list.toArray (retValue); return retValue; } // getGoals /** * Create New Instance of SLA Criteria * @return instanciated class * @throws Exception */ public SLACriteria newSLACriteriaInstance() throws Exception { if (getClassname() == null || getClassname().length() == 0) throw new AdempiereSystemError("No SLA Criteria Classname"); try { Class clazz = Class.forName(getClassname()); SLACriteria retValue = (SLACriteria)clazz.newInstance(); return retValue; } catch (Exception e) { throw new AdempiereSystemError("Could not intsnciate SLA Criteria", e); } } // newInstance } // MSLACriteria
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSLACriteria.java
1
请在Spring Boot框架中完成以下Java代码
private PathPatternRequestMatcher.Builder constructRequestMatcherBuilder(ApplicationContext context) { PathPatternRequestMatcherBuilderFactoryBean requestMatcherBuilder = new PathPatternRequestMatcherBuilderFactoryBean(); requestMatcherBuilder.setApplicationContext(context); requestMatcherBuilder.setBeanFactory(context.getAutowireCapableBeanFactory()); requestMatcherBuilder.setBeanName(requestMatcherBuilder.toString()); return ThrowingSupplier.of(requestMatcherBuilder::getObject).get(); } private boolean anyPathsDontStartWithLeadingSlash(String... patterns) { for (String pattern : patterns) { if (!pattern.startsWith("/")) { return true; } } return false; } /** * <p> * Match when the request URI matches one of {@code patterns}. See * {@link org.springframework.web.util.pattern.PathPattern} for matching rules. * </p> * <p> * If a specific {@link RequestMatcher} must be specified, use * {@link #requestMatchers(RequestMatcher...)} instead * </p> * @param patterns the patterns to match on * @return the object that is chained after creating the {@link RequestMatcher}. * @since 5.8 */ public C requestMatchers(String... patterns) { return requestMatchers(null, patterns);
} /** * <p> * Match when the {@link HttpMethod} is {@code method} * </p> * <p> * If a specific {@link RequestMatcher} must be specified, use * {@link #requestMatchers(RequestMatcher...)} instead * </p> * @param method the {@link HttpMethod} to use or {@code null} for any * {@link HttpMethod}. * @return the object that is chained after creating the {@link RequestMatcher}. * @since 5.8 */ public C requestMatchers(HttpMethod method) { return requestMatchers(method, "/**"); } /** * Subclasses should implement this method for returning the object that is chained to * the creation of the {@link RequestMatcher} instances. * @param requestMatchers the {@link RequestMatcher} instances that were created * @return the chained Object for the subclass which allows association of something * else to the {@link RequestMatcher} */ protected abstract C chainRequestMatchers(List<RequestMatcher> requestMatchers); }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\AbstractRequestMatcherRegistry.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getApplicationKey() { return this.applicationKey; } public void setApplicationKey(@Nullable String applicationKey) { this.applicationKey = applicationKey; } public boolean isDescriptions() { return this.descriptions; } public void setDescriptions(boolean descriptions) { this.descriptions = descriptions; } public String getHostTag() {
return this.hostTag; } public void setHostTag(String hostTag) { this.hostTag = hostTag; } public String getUri() { return this.uri; } public void setUri(String uri) { this.uri = uri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\datadog\DatadogProperties.java
2
请完成以下Java代码
public void setIsManual (boolean IsManual) { set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return This is a manual process */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Verbucht. @param Posted Posting status */ @Override public void setPosted (boolean Posted) { set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted)); } /** Get Verbucht. @return Posting status */ @Override public boolean isPosted () { Object oo = get_Value(COLUMNNAME_Posted); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } @Override public org.compiere.model.I_C_AllocationHdr getReversal() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_C_AllocationHdr.class); } @Override public void setReversal(org.compiere.model.I_C_AllocationHdr Reversal) { set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_C_AllocationHdr.class, Reversal); } /** Set Reversal ID. @param Reversal_ID ID of document reversal */ @Override public void setReversal_ID (int Reversal_ID) { if (Reversal_ID < 1) { set_Value (COLUMNNAME_Reversal_ID, null); } else { set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID)); } } /** Get Reversal ID. @return ID of document reversal */ @Override public int getReversal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_ID); if (ii == null) { return 0; } return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationHdr.java
1
请完成以下Java代码
class ContextForAsyncProcessing { @Nullable PInstanceId adPInstanceId; @Default int parentAsyncBatchId = -1; } /** * Creates an instructions record for the given print job. * * @param userToPrintId the user for whom we shall actually do the printing. Note that if this user's printing config forwards to a shared config, then the instructions instance is created for the shared * config's user * @param createWithSpecificHostKey if <code>false</code>, then * <ul> * <li>the given <code>userToPrintId</code> is set to be the user, without considering any forwarding * <li>no hostkey is set to the instructions, meaning that any printing client which has a session with the given <code>userToPrintId</code> can do the printing. * </ul> * Note that even if this is <code>true</code>, it will be ignored if there is no hostkey to be obtained, see {@link IPrintClientsBL#getHostKeyOrNull(java.util.Properties)}.
* @param copies number of copies to print (1 means one printout). */ I_C_Print_Job_Instructions createPrintJobInstructions( UserId userToPrintId, boolean createWithSpecificHostKey, I_C_Print_Job_Line firstLine, I_C_Print_Job_Line lastLine, int copies); String getSummary(I_C_Print_Job printJob); List<I_C_Print_Job_Detail> getCreatePrintJobDetails(I_C_Print_Job_Line printJobLine); /** * Enqueue print job instructions for async pdf printing */ void enqueuePrintJobInstructions(@NonNull I_C_Print_Job_Instructions jobInstructions, AsyncBatchId asyncBatchId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\IPrintJobBL.java
1
请完成以下Java代码
private static Language extractLanguage(final ProcessInfo pi) { // // Get Language from ProcessInfo, if any (08023) Language lang = pi.getReportLanguage(); if (lang != null) { return lang; } // task 09740 // In case the report is not linked to a window but it has C_BPartner_ID as parameter and it is set, take the language of that bpartner // TODO: i think this one is no longer needed because we already checking this case in ProcessInfo.findReportingLanguage() if (lang == null) { final IRangeAwareParams parameterAsIParams = pi.getParameterAsIParams(); final int bPartnerID = parameterAsIParams.getParameterAsInt(I_C_BPartner.COLUMNNAME_C_BPartner_ID, -1); if (bPartnerID > 0) { lang = Services.get(IBPartnerBL.class).getLanguage(pi.getCtx(), bPartnerID); return lang; } } //
// Get Organization Language if any (03040) if (null == lang) { lang = Services.get(ILanguageBL.class).getOrgLanguage(pi.getCtx(), pi.getAD_Org_ID()); } // If we got an Language already, return it if (null != lang) { return lang; } // // Fallback: get it from client context return Env.getLanguage(Env.getCtx()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\de.metas.report.jasper.client\src\main\java\de\metas\report\client\ReportsClient.java
1
请在Spring Boot框架中完成以下Java代码
public String getActivityFontName() { return activityFontName; } public void setActivityFontName(String activityFontName) { this.activityFontName = activityFontName; } public String getLabelFontName() { return labelFontName; } public void setLabelFontName(String labelFontName) { this.labelFontName = labelFontName; } public String getAnnotationFontName() { return annotationFontName; } public void setAnnotationFontName(String annotationFontName) { this.annotationFontName = annotationFontName; } public boolean isFormFieldValidationEnabled() { return formFieldValidationEnabled; } public void setFormFieldValidationEnabled(boolean formFieldValidationEnabled) { this.formFieldValidationEnabled = formFieldValidationEnabled; } public Duration getLockPollRate() { return lockPollRate; } public void setLockPollRate(Duration lockPollRate) { this.lockPollRate = lockPollRate; } public Duration getSchemaLockWaitTime() { return schemaLockWaitTime; } public void setSchemaLockWaitTime(Duration schemaLockWaitTime) { this.schemaLockWaitTime = schemaLockWaitTime; } public boolean isEnableHistoryCleaning() { return enableHistoryCleaning; } public void setEnableHistoryCleaning(boolean enableHistoryCleaning) { this.enableHistoryCleaning = enableHistoryCleaning; }
public String getHistoryCleaningCycle() { return historyCleaningCycle; } public void setHistoryCleaningCycle(String historyCleaningCycle) { this.historyCleaningCycle = historyCleaningCycle; } @Deprecated @DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration") public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) { this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays); } public Duration getHistoryCleaningAfter() { return historyCleaningAfter; } public void setHistoryCleaningAfter(Duration historyCleaningAfter) { this.historyCleaningAfter = historyCleaningAfter; } public int getHistoryCleaningBatchSize() { return historyCleaningBatchSize; } public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) { this.historyCleaningBatchSize = historyCleaningBatchSize; } public String getVariableJsonMapper() { return variableJsonMapper; } public void setVariableJsonMapper(String variableJsonMapper) { this.variableJsonMapper = variableJsonMapper; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; }
public void setNickname(String nickname) { this.nickname = nickname; } public String getRegTime() { return regTime; } public void setRegTime(String regTime) { this.regTime = regTime; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\java\com\neo\domain\User.java
1
请完成以下Java代码
public ObjectId getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) {
this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User book = (User) o; return Objects.equals(id, book.id); } @Override public int hashCode() { return Objects.hash(id); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\multipledb\model\User.java
1
请在Spring Boot框架中完成以下Java代码
public CmmnDeploymentBuilder addCmmnModel(String resourceName, CmmnModel cmmnModel) { // TODO return null; } @Override public CmmnDeploymentBuilder name(String name) { deployment.setName(name); return this; } @Override public CmmnDeploymentBuilder category(String category) { deployment.setCategory(category); return this; } @Override public CmmnDeploymentBuilder key(String key) { deployment.setKey(key); return this; } @Override public CmmnDeploymentBuilder disableSchemaValidation() { this.isCmmn20XsdValidationEnabled = false; return this; } @Override public CmmnDeploymentBuilder tenantId(String tenantId) { deployment.setTenantId(tenantId); return this; }
@Override public CmmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) { deployment.setParentDeploymentId(parentDeploymentId); return this; } @Override public CmmnDeploymentBuilder enableDuplicateFiltering() { this.isDuplicateFilterEnabled = true; return this; } @Override public CmmnDeployment deploy() { return repositoryService.deploy(this); } public CmmnDeploymentEntity getDeployment() { return deployment; } public boolean isCmmnXsdValidationEnabled() { return isCmmn20XsdValidationEnabled; } public boolean isDuplicateFilterEnabled() { return isDuplicateFilterEnabled; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentBuilderImpl.java
2
请完成以下Java代码
public static ImmutableList<HURow> getHURowsFromIncludedRows(final PPOrderLinesView view) { return view.streamByIds(DocumentIdsSelection.ALL) .filter(row -> row.getType().isMainProduct() || row.isReceipt()) .flatMap(row -> row.getIncludedRows().stream()) .map(row -> toHURowOrNull(row)) .filter(Objects::nonNull) .filter(HURow::isTopLevelHU) .filter(HURow::isHuStatusActive) .filter(row -> isEligibleHU(row)) .collect(ImmutableList.toImmutableList()); } public static void pickAndProcessSingleHU(@NonNull final PickRequest pickRequest, @NonNull final ProcessPickingRequest processRequest) { pickHU(pickRequest); processHUs(processRequest); }
public static void pickHU(@NonNull final PickRequest request) { pickingCandidateService.pickHU(request); } public static void processHUs(@NonNull final ProcessPickingRequest request) { pickingCandidateService.processForHUIds(request.getHuIds(), request.getShipmentScheduleId(), OnOverDelivery.ofTakeWholeHUFlag(request.isTakeWholeHU()), request.getPpOrderId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\util\WEBUI_PP_Order_ProcessHelper.java
1
请完成以下Java代码
public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set RMA Type. @param M_RMAType_ID Return Material Authorization Type */ public void setM_RMAType_ID (int M_RMAType_ID) { if (M_RMAType_ID < 1) set_ValueNoCheck (COLUMNNAME_M_RMAType_ID, null); else set_ValueNoCheck (COLUMNNAME_M_RMAType_ID, Integer.valueOf(M_RMAType_ID)); } /** Get RMA Type. @return Return Material Authorization Type */ public int getM_RMAType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_RMAType_ID); if (ii == null) return 0; return ii.intValue(); }
/** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_RMAType.java
1
请在Spring Boot框架中完成以下Java代码
public class Post { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @NotNull @Size(min = 10) @Column(columnDefinition = "longtext") private String post; @NotNull @Size(min = 5, max = 100) @Column(unique = true) private String title; @NotNull @ManyToOne(targetEntity = User.class, optional = false) private User author; @Column(name = "created_at") private Date createdAt; @Column(name = "updated_at") private Date updatedAt; @Transient private Logger logger = Logger.getLogger(getClass().getName()); public Post() { createdAt = new Date(); updatedAt = new Date(); } public Post(String title, String post, User author) { this.title = title; this.post = post; this.author = author; createdAt = new Date(); updatedAt = new Date(); } public int getId() { return id; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public User getAuthor() { return author; }
public void setAuthor(User author) { this.author = author; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { return "title: " + this.title + "\npost: " + this.post + "\nauthor: " + this.author +"\ncreatetdAt: " + this.createdAt + "\nupdatedAt: " + this.updatedAt; } }
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\Post.java
2
请完成以下Java代码
public void cleanTemplate(Integer ID) { cleanTemplate("" + ID); } /** * Clean Template cache for this ID * @param ID ID of template to clean */ public void cleanTemplate(String ID) { runURLRequest("Template", ID); } /** * Empty all Template Caches */ public void emptyTemplate() { runURLRequest("Template", "0"); } /** * Clean ContainerCache for this ID * @param ID for Container to clean */ public void cleanContainer(Integer ID) { cleanContainer("" + ID); } /** * Clean ContainerCache for this ID * @param ID for container to clean */ public void cleanContainer(String ID) { runURLRequest("Container", ID); } /** * Clean ContainerTreeCache for this WebProjectID * @param ID for Container to clean */ public void cleanContainerTree(Integer ID) { cleanContainerTree("" + ID); } /** * Clean ContainerTreeCache for this WebProjectID * @param ID for container to clean */ public void cleanContainerTree(String ID) { runURLRequest("ContainerTree", ID); } /** * Clean Container Element for this ID * @param ID for container element to clean */ public void cleanContainerElement(Integer ID) { cleanContainerElement("" + ID); } /** * Clean Container Element for this ID
* @param ID for container element to clean */ public void cleanContainerElement(String ID) { runURLRequest("ContainerElement", ID); } private void runURLRequest(String cache, String ID) { String thisURL = null; for(int i=0; i<cacheURLs.length; i++) { try { thisURL = "http://" + cacheURLs[i] + "/cache/Service?Cache=" + cache + "&ID=" + ID; URL url = new URL(thisURL); Proxy thisProxy = Proxy.NO_PROXY; URLConnection urlConn = url.openConnection(thisProxy); urlConn.setUseCaches(false); urlConn.connect(); Reader stream = new java.io.InputStreamReader( urlConn.getInputStream()); StringBuffer srvOutput = new StringBuffer(); try { int c; while ( (c=stream.read()) != -1 ) srvOutput.append( (char)c ); } catch (Exception E2) { E2.printStackTrace(); } } catch (IOException E) { if (log!=null) log.warn("Can't clean cache at:" + thisURL + " be carefull, your deployment server may use invalid or old cache data!"); } } } /** * Converts JNP URL to http URL for cache cleanup * @param JNPURL String with JNP URL from Context * @return clean servername */ public static String convertJNPURLToCacheURL(String JNPURL) { if (JNPURL.indexOf("jnp://")>=0) { JNPURL = JNPURL.substring(JNPURL.indexOf("jnp://")+6); } if (JNPURL.indexOf(':')>=0) { JNPURL = JNPURL.substring(0,JNPURL.indexOf(':')); } if (JNPURL.length()>0) { return JNPURL; } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\cm\CacheHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class SocialTokenGranter implements ITokenGranter { public static final String GRANT_TYPE = "social"; private static final Integer AUTH_SUCCESS_CODE = 2000; private final IUserClient userClient; private final SocialProperties socialProperties; @Override public UserInfo grant(TokenParameter tokenParameter) { HttpServletRequest request = WebUtil.getRequest(); String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID); // 开放平台来源 String sourceParameter = request.getParameter("source"); // 匹配是否有别名定义 String source = socialProperties.getAlias().getOrDefault(sourceParameter, sourceParameter); // 开放平台授权码 String code = request.getParameter("code"); // 开放平台状态吗 String state = request.getParameter("state"); // 获取开放平台授权数据 AuthRequest authRequest = SocialUtil.getAuthRequest(source, socialProperties); AuthCallback authCallback = new AuthCallback(); authCallback.setCode(code); authCallback.setState(state); AuthResponse authResponse = authRequest.login(authCallback); AuthUser authUser;
if (authResponse.getCode() == AUTH_SUCCESS_CODE) { authUser = (AuthUser) authResponse.getData(); } else { throw new ServiceException("social grant failure, auth response is not success"); } // 组装数据 UserOauth userOauth = Objects.requireNonNull(BeanUtil.copyProperties(authUser, UserOauth.class)); userOauth.setSource(authUser.getSource()); userOauth.setTenantId(tenantId); userOauth.setUuid(authUser.getUuid()); // 远程调用,获取认证信息 R<UserInfo> result = userClient.userAuthInfo(userOauth); return result.getData(); } }
repos\SpringBlade-master\blade-auth\src\main\java\org\springblade\auth\granter\SocialTokenGranter.java
2
请在Spring Boot框架中完成以下Java代码
public class Repository { private String name; private URL url; private boolean releasesEnabled = true; private boolean snapshotsEnabled; public Repository() { } public Repository(String name, URL url) { this(name, url, true, false); } public Repository(String name, URL url, boolean releasesEnabled, boolean snapshotsEnabled) { this.name = name; this.url = url; this.releasesEnabled = releasesEnabled; this.snapshotsEnabled = snapshotsEnabled; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public URL getUrl() { return this.url; } public void setUrl(URL url) { this.url = url; } public boolean isReleasesEnabled() { return this.releasesEnabled; } public void setReleasesEnabled(boolean releasesEnabled) { this.releasesEnabled = releasesEnabled; } public boolean isSnapshotsEnabled() { return this.snapshotsEnabled; } public void setSnapshotsEnabled(boolean snapshotsEnabled) { this.snapshotsEnabled = snapshotsEnabled; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Repository other = (Repository) obj; if (this.name == null) { if (other.name != null) { return false; } } else if (!this.name.equals(other.name)) { return false; } if (this.releasesEnabled != other.releasesEnabled) {
return false; } if (this.snapshotsEnabled != other.snapshotsEnabled) { return false; } if (this.url == null) { if (other.url != null) { return false; } } else if (!this.url.equals(other.url)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.name == null) ? 0 : this.name.hashCode()); result = prime * result + (this.releasesEnabled ? 1231 : 1237); result = prime * result + (this.snapshotsEnabled ? 1231 : 1237); result = prime * result + ((this.url == null) ? 0 : this.url.hashCode()); return result; } @Override public String toString() { return new StringJoiner(", ", Repository.class.getSimpleName() + "[", "]").add("name='" + this.name + "'") .add("url=" + this.url) .add("releasesEnabled=" + this.releasesEnabled) .add("snapshotsEnabled=" + this.snapshotsEnabled) .toString(); } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Repository.java
2
请完成以下Java代码
public void addDecompressor(String contentEncoding, MessagePostProcessor decompressor) { this.decompressors.put(contentEncoding, decompressor); } /** * Remove the decompressor for this encoding; content will not be decompressed even if the * {@link org.springframework.amqp.core.MessageProperties#SPRING_AUTO_DECOMPRESS} header is true. * @param contentEncoding the content encoding. * @return the decompressor if it was present. */ 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 ResourceOptionsDto availableOperations(UriInfo context) { ResourceOptionsDto dto = new ResourceOptionsDto(); URI uri = context.getBaseUriBuilder() .path(relativeRootResourcePath) .path(AuthorizationRestService.PATH) .path(resourceId) .build(); dto.addReflexiveLink(uri, HttpMethod.GET, "self"); if (isAuthorized(DELETE)) { dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); } if (isAuthorized(UPDATE)) { dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); } return dto; }
// utils ////////////////////////////////////////////////// protected Authorization getDbAuthorization() { Authorization dbAuthorization = authorizationService.createAuthorizationQuery() .authorizationId(resourceId) .singleResult(); if (dbAuthorization == null) { throw new InvalidRequestException(Status.NOT_FOUND, "Authorization with id " + resourceId + " does not exist."); } else { return dbAuthorization; } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\authorization\impl\AuthorizationResourceImpl.java
1
请完成以下Java代码
public void setGL_Budget_ID (int GL_Budget_ID) { if (GL_Budget_ID < 1) set_Value (COLUMNNAME_GL_Budget_ID, null); else set_Value (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID)); } /** Get Budget. @return General Ledger Budget */ public int getGL_Budget_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Before Approval. @param IsBeforeApproval The Check is before the (manual) approval */ public void setIsBeforeApproval (boolean IsBeforeApproval) { set_Value (COLUMNNAME_IsBeforeApproval, Boolean.valueOf(IsBeforeApproval)); } /** Get Before Approval. @return The Check is before the (manual) approval */
public boolean isBeforeApproval () { Object oo = get_Value(COLUMNNAME_IsBeforeApproval); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_BudgetControl.java
1
请完成以下Java代码
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 Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Details. @param TextDetails Details */ public void setTextDetails (String TextDetails) { set_Value (COLUMNNAME_TextDetails, TextDetails);
} /** Get Details. @return Details */ public String getTextDetails () { return (String)get_Value(COLUMNNAME_TextDetails); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } /** Set Topic Action. @param TopicAction Topic Action */ public void setTopicAction (String TopicAction) { set_Value (COLUMNNAME_TopicAction, TopicAction); } /** Get Topic Action. @return Topic Action */ public String getTopicAction () { return (String)get_Value(COLUMNNAME_TopicAction); } /** Set Topic Status. @param TopicStatus Topic Status */ public void setTopicStatus (String TopicStatus) { set_Value (COLUMNNAME_TopicStatus, TopicStatus); } /** Get Topic Status. @return Topic Status */ public String getTopicStatus () { return (String)get_Value(COLUMNNAME_TopicStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Topic.java
1
请完成以下Java代码
public void onChangeCountryName(final I_C_Country country) { setCountryAttributeName(country); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void onDeleteCountry(final I_C_Country country) { setCountryAttributeAsActive(country, false); } private void setCountryAttributeAsActive(final I_C_Country country, final boolean isActive) { final AttributeListValue existingAttributeValue = getAttributeValue(country); if (existingAttributeValue != null) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(existingAttributeValue.getId()) .active(isActive) .build()); } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = { I_C_Country.COLUMNNAME_DisplaySequence, I_C_Country.COLUMNNAME_DisplaySequenceLocal }) public void onChangeCountryDisplaySequence(@NonNull final I_C_Country country) { assertValidDisplaySequences(country); } public void assertValidDisplaySequences(@NonNull final I_C_Country country)
{ AddressDisplaySequence.ofNullable(country.getDisplaySequence()).assertValid(); AddressDisplaySequence.ofNullable(country.getDisplaySequenceLocal()).assertValid(); } private void setCountryAttributeName(@NonNull final I_C_Country country) { final AttributeListValue existingAttributeValue = getAttributeValue(country); if (existingAttributeValue != null) { final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class); attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder() .id(existingAttributeValue.getId()) .name(country.getName()) .build()); } } private AttributeListValue getAttributeValue(final I_C_Country country) { return Services.get(ICountryAttributeDAO.class).retrieveAttributeValue(Env.getCtx(), country, true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\location\interceptor\C_Country.java
1
请完成以下Java代码
public void mouseReleased(final MouseEvent e) { } /** * Set Title * * @param title title */ @Override public void setTitle(String title) { if (title != null) { final int pos = title.indexOf('&'); if (pos != -1 && title.length() > pos) // We have a nemonic { final int mnemonic = title.toUpperCase().charAt(pos + 1); if (mnemonic != ' ') { title = title.substring(0, pos) + title.substring(pos + 1); } } } super.setTitle(title); } // setTitle /** Dispose Action Name */ protected static String ACTION_DISPOSE = "CDialogDispose"; /** Action */ protected static DialogAction s_dialogAction = new DialogAction(ACTION_DISPOSE); /** ALT-EXCAPE */ protected static KeyStroke s_disposeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_PAUSE, InputEvent.ALT_MASK); /** * Adempiere Dialog Action * * @author Jorg Janke * @version $Id: CDialog.java,v 1.3 2006/07/30 00:52:24 jjanke Exp $ */ static class DialogAction extends AbstractAction { /** * */ private static final long serialVersionUID = -1502992970807699945L; DialogAction(final String actionName) { super(actionName); putValue(Action.ACTION_COMMAND_KEY, actionName); } // DialogAction
/** * Action Listener * * @param e event */ @Override public void actionPerformed(final ActionEvent e) { if (ACTION_DISPOSE.equals(e.getActionCommand())) { Object source = e.getSource(); while (source != null) { if (source instanceof Window) { ((Window)source).dispose(); return; } if (source instanceof Container) { source = ((Container)source).getParent(); } else { source = null; } } } else { System.out.println("Action: " + e); } } // actionPerformed } // DialogAction } // CDialog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CDialog.java
1
请完成以下Java代码
public T handleResponse(ClassicHttpResponse response) throws IOException { final StatusLine statusLine = new StatusLine(response); final HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { try { RestException engineException = deserializeResponse(entity, EngineRestExceptionDto.class).toRestException(); int statusCode = statusLine.getStatusCode(); engineException.setHttpStatusCode(statusCode); throw engineException; } finally { EntityUtils.consume(entity); } } return entity == null ? null : handleEntity(entity); } }; } protected <T> T deserializeResponse(HttpEntity httpEntity, Class<T> responseClass) { InputStream inputStream = null; try { inputStream = httpEntity.getContent(); return objectMapper.readValue(inputStream, responseClass); } catch (JsonParseException e) { throw LOG.exceptionWhileParsingJsonObject(responseClass, e); } catch (JsonMappingException e) { throw LOG.exceptionWhileMappingJsonObject(responseClass, e);
} catch (IOException e) { throw LOG.exceptionWhileDeserializingJsonObject(responseClass, e); } finally { IoUtil.closeSilently(inputStream); } } protected ByteArrayEntity serializeRequest(RequestDto dto) { byte[] serializedRequest; try { serializedRequest = objectMapper.writeValueAsBytes(dto); } catch (JsonProcessingException e) { throw LOG.exceptionWhileSerializingJsonObject(dto, e); } ByteArrayEntity byteArrayEntity = null; if (serializedRequest != null) { byteArrayEntity = new ByteArrayEntity(serializedRequest, ContentType.APPLICATION_JSON); } return byteArrayEntity; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\RequestExecutor.java
1
请完成以下Java代码
private static boolean isServletApplication() { for (String servletIndicatorClass : SERVLET_INDICATOR_CLASSES) { if (!ClassUtils.isPresent(servletIndicatorClass, null)) { return false; } } return true; } static class WebApplicationTypeRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { for (String servletIndicatorClass : SERVLET_INDICATOR_CLASSES) { registerTypeIfPresent(servletIndicatorClass, classLoader, hints); } } private void registerTypeIfPresent(String typeName, @Nullable ClassLoader classLoader, RuntimeHints hints) { if (ClassUtils.isPresent(typeName, classLoader)) { hints.reflection().registerType(TypeReference.of(typeName)); } }
} /** * Strategy that may be implemented by a module that can deduce the * {@link WebApplicationType}. * * @since 4.0.1 */ @FunctionalInterface public interface Deducer { /** * Deduce the web application type. * @return the deduced web application type or {@code null} */ @Nullable WebApplicationType deduceWebApplicationType(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\WebApplicationType.java
1
请在Spring Boot框架中完成以下Java代码
public class EDICctop000VType { @XmlElement(name = "C_BPartner_Location_ID") protected BigInteger cbPartnerLocationID; @XmlElement(name = "EDI_cctop_000_v_ID") protected BigInteger ediCctop000VID; @XmlElement(name = "GLN") protected String gln; /** * Gets the value of the cbPartnerLocationID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getCBPartnerLocationID() { return cbPartnerLocationID; } /** * Sets the value of the cbPartnerLocationID property. * * @param value * allowed object is * {@link BigInteger } * */ public void setCBPartnerLocationID(BigInteger value) { this.cbPartnerLocationID = value; } /** * Gets the value of the ediCctop000VID property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getEDICctop000VID() { return ediCctop000VID; } /** * Sets the value of the ediCctop000VID property. *
* @param value * allowed object is * {@link BigInteger } * */ public void setEDICctop000VID(BigInteger value) { this.ediCctop000VID = value; } /** * Gets the value of the gln property. * * @return * possible object is * {@link String } * */ public String getGLN() { return gln; } /** * Sets the value of the gln property. * * @param value * allowed object is * {@link String } * */ public void setGLN(String value) { this.gln = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop000VType.java
2
请在Spring Boot框架中完成以下Java代码
public class VersioningPersonController { @GetMapping("/v1/person") public PersonV1 getFirstVersionOfPerson() { return new PersonV1("Bob Charlie"); } @GetMapping("/v2/person") public PersonV2 getSecondVersionOfPerson() { return new PersonV2(new Name("Bob", "Charlie")); } @GetMapping(path = "/person", params = "version=1") public PersonV1 getFirstVersionOfPersonRequestParameter() { return new PersonV1("Bob Charlie"); } @GetMapping(path = "/person", params = "version=2") public PersonV2 getSecondVersionOfPersonRequestParameter() { return new PersonV2(new Name("Bob", "Charlie")); } @GetMapping(path = "/person/header", headers = "X-API-VERSION=1")
public PersonV1 getFirstVersionOfPersonRequestHeader() { return new PersonV1("Bob Charlie"); } @GetMapping(path = "/person/header", headers = "X-API-VERSION=2") public PersonV2 getSecondVersionOfPersonRequestHeader() { return new PersonV2(new Name("Bob", "Charlie")); } @GetMapping(path = "/person/accept", produces = "application/vnd.company.app-v1+json") public PersonV1 getFirstVersionOfPersonAcceptHeader() { return new PersonV1("Bob Charlie"); } @GetMapping(path = "/person/accept", produces = "application/vnd.company.app-v2+json") public PersonV2 getSecondVersionOfPersonAcceptHeader() { return new PersonV2(new Name("Bob", "Charlie")); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\versioning\VersioningPersonController.java
2
请完成以下Java代码
public class HMMSegment extends CharacterBasedSegment { CharacterBasedGenerativeModel model; public HMMSegment() { this(HanLP.Config.HMMSegmentModelPath); } public HMMSegment(String modelPath) { model = GlobalObjectPool.get(modelPath); if (model != null) return; model = new CharacterBasedGenerativeModel(); long start = System.currentTimeMillis(); logger.info("开始从[ " + modelPath + " ]加载2阶HMM模型"); try { ByteArray byteArray = ByteArray.createByteArray(modelPath); if (byteArray == null) { throw new IllegalArgumentException("HMM分词模型[ " + modelPath + " ]不存在"); } model.load(byteArray); } catch (Exception e) { throw new IllegalArgumentException("发生了异常:" + TextUtility.exceptionToString(e)); } logger.info("加载成功,耗时:" + (System.currentTimeMillis() - start) + " ms"); GlobalObjectPool.put(modelPath, model); } @Override protected List<Term> roughSegSentence(char[] sentence) { char[] tag = model.tag(sentence); List<Term> termList = new LinkedList<Term>(); int offset = 0; for (int i = 0; i < tag.length; offset += 1, ++i) { switch (tag[i]) { case 'b': { int begin = offset; while (tag[i] != 'e') { offset += 1; ++i;
if (i == tag.length) { break; } } if (i == tag.length) { termList.add(new Term(new String(sentence, begin, offset - begin), null)); } else termList.add(new Term(new String(sentence, begin, offset - begin + 1), null)); } break; default: { termList.add(new Term(new String(sentence, offset, 1), null)); } break; } } return termList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\HMM\HMMSegment.java
1
请完成以下Java代码
public void setEnvironment(Environment environment) { if (environment instanceof ConfigurableEnvironment) { this.environment = (ConfigurableEnvironment) environment; } } protected Map<String, Object> resolveBeanMetadata(final Object bean) { final Map<String, Object> beanMetadata = new LinkedHashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && isSimpleType(propertyDescriptor.getPropertyType())) { String name = Introspector.decapitalize(propertyDescriptor.getName()); Object value = readMethod.invoke(bean); beanMetadata.put(name, value); } } } catch (Exception e) { throw new RuntimeException(e); } return beanMetadata;
} protected Map<String, ServiceBean> getServiceBeansMap() { return beansOfTypeIncludingAncestors(applicationContext, ServiceBean.class); } protected ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor() { return applicationContext.getBean(BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class); } protected Map<String, ProtocolConfig> getProtocolConfigsBeanMap() { return beansOfTypeIncludingAncestors(applicationContext, ProtocolConfig.class); } }
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\AbstractDubboMetadata.java
1
请完成以下Java代码
private static Options createOptions() { final Options options = new Options(); // Help { final Option option = new Option("h", "Print this (h)elp message and exit"); option.setArgs(0); option.setArgName("Help"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("dbHost", ""); option.setArgs(1); option.setArgName("Database host name"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("dbPort", ""); option.setArgs(1); option.setArgName("Database port number"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("dbName", ""); option.setArgs(1); option.setArgName("Database name"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("dbUser", ""); option.setArgs(1); option.setArgName("Database user name"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("dbPassword", ""); option.setArgs(1); option.setArgName("Database password"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("rabbitHost", ""); option.setArgs(1); option.setArgName("RabbitMQ host name"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("rabbitPort", ""); option.setArgs(1); option.setArgName("RabbitMQ port number"); option.setRequired(false); options.addOption(option); } { final Option option = new Option("rabbitUser", ""); option.setArgs(1); option.setArgName("RabbitMQ user name");
option.setRequired(false); options.addOption(option); } { final Option option = new Option("rabbitPassword", ""); option.setArgs(1); option.setArgName("RabbitMQ password"); option.setRequired(false); options.addOption(option); } return options; } @Builder @Value @ToString(exclude = { "dbPassword" }) public static class CommandLineOptions { @Nullable String dbHost; @Nullable Integer dbPort; @Nullable String dbName; @Nullable String dbUser; @Nullable String dbPassword; @Nullable String rabbitHost; @Nullable Integer rabbitPort; @Nullable String rabbitUser; @Nullable String rabbitPassword; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\CommandLineParser.java
1
请完成以下Java代码
public int getResultSetType() { return m_resultSetType; } /** * @return transaction name */ public String getTrxName() { return m_trxName; } public final void clearDebugSqlParams() { this.debugSqlParams = null; } public final void setDebugSqlParam(final int parameterIndex, final Object parameterValue) { if (debugSqlParams == null)
{ debugSqlParams = new TreeMap<>(); } debugSqlParams.put(parameterIndex, parameterValue); } public final Map<Integer, Object> getDebugSqlParams() { final Map<Integer, Object> debugSqlParams = this.debugSqlParams; return debugSqlParams == null ? ImmutableMap.of() : debugSqlParams; } public final Map<Integer, Object> getAndClearDebugSqlParams() { final Map<Integer, Object> debugSqlParams = getDebugSqlParams(); clearDebugSqlParams(); return debugSqlParams; } } // CStatementVO
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\CStatementVO.java
1
请完成以下Java代码
public void setHUIterator(final IHUIterator iterator) { delegate.setHUIterator(iterator); } protected IHUIterator getHUIterator() { if (delegate instanceof HUIteratorListenerAdapter) { return ((HUIteratorListenerAdapter)delegate).getHUIterator(); } else { throw new AdempiereException("Cannot get HUIterator from delegate: " + delegate); } } @Override public Result beforeHU(final IMutable<I_M_HU> hu) { return delegate.beforeHU(hu); } @Override public Result afterHU(final I_M_HU hu) { return delegate.afterHU(hu); } @Override public Result beforeHUItem(final IMutable<I_M_HU_Item> item) {
return delegate.beforeHUItem(item); } @Override public Result afterHUItem(final I_M_HU_Item item) { return delegate.afterHUItem(item); } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return delegate.beforeHUItemStorage(itemStorage); } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return delegate.afterHUItemStorage(itemStorage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUIteratorListenerDelegateAdapter.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return new StringBuffer().append(getEmail()).toString(); } }
repos\tutorials-master\web-modules\spark-java\src\main\java\com\baeldung\sparkjava\User.java
1
请完成以下Java代码
private void processPartitions(List<Object> values) { String key = values.get(0) + "|" + values.get(1) + "|" + values.get(2) + "|" + values.get(3); partitions.add(key); } private void processBlock(LineIterator iterator, CQLSSTableWriter writer, File outDir, Function<List<String>, List<Object>> function) { String currentLine; long linesProcessed = 0; while(iterator.hasNext()) { logLinesProcessed(linesProcessed++); currentLine = iterator.nextLine(); if(isBlockFinished(currentLine)) { return; } try { List<String> raw = Arrays.stream(currentLine.trim().split("\t")) .map(String::trim) .collect(Collectors.toList()); List<Object> values = function.apply(raw); if (this.currentWriterCount == 0) { System.out.println(new Date() + " close writer " + new Date()); writer.close(); writer = WriterBuilder.getLatestWriter(outDir); } if (this.castStringIfPossible) { writer.addRow(castToNumericIfPossible(values)); } else { writer.addRow(values); } currentWriterCount++; if (currentWriterCount >= rowPerFile) { currentWriterCount = 0; } } catch (Exception ex) { System.out.println(ex.getMessage() + " -> " + currentLine); } } } private List<Object> castToNumericIfPossible(List<Object> values) { try { if (values.get(6) != null && NumberUtils.isNumber(values.get(6).toString())) { Double casted = NumberUtils.createDouble(values.get(6).toString());
List<Object> numeric = Lists.newArrayList(); numeric.addAll(values); numeric.set(6, null); numeric.set(8, casted); castedOk++; return numeric; } } catch (Throwable th) { castErrors++; } processPartitions(values); return values; } private boolean isBlockFinished(String line) { return StringUtils.isBlank(line) || line.equals("\\."); } private boolean isBlockTsStarted(String line) { return line.startsWith("COPY public.ts_kv ("); } private boolean isBlockLatestStarted(String line) { return line.startsWith("COPY public.ts_kv_latest ("); } }
repos\thingsboard-master\tools\src\main\java\org\thingsboard\client\tools\migrator\PgCaMigrator.java
1
请完成以下Java代码
public void setMaxVolume(final BigDecimal MaxVolume) { set_Value(COLUMNNAME_MaxVolume, MaxVolume); } @Override public BigDecimal getMaxVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxVolume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxWeight(final BigDecimal MaxWeight) { set_Value(COLUMNNAME_MaxWeight, MaxWeight); } @Override public BigDecimal getMaxWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_PackagingContainer_ID(final int M_PackagingContainer_ID) { if (M_PackagingContainer_ID < 1) set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, null); else set_ValueNoCheck(COLUMNNAME_M_PackagingContainer_ID, M_PackagingContainer_ID); } @Override public int getM_PackagingContainer_ID() { return get_ValueAsInt(COLUMNNAME_M_PackagingContainer_ID); } @Override public void setM_Product_ID(final int M_Product_ID) { if (M_Product_ID < 1) set_Value(COLUMNNAME_M_Product_ID, null); else
set_Value(COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @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); } @Override public void setValue(final @Nullable java.lang.String Value) { set_Value(COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setWidth(final @Nullable BigDecimal Width) { set_Value(COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java
1
请完成以下Java代码
public String getAuthToken() { return authToken; } public void setAuthToken(String authToken) { this.authToken = authToken; } public String getMessagingSid() { return messagingSid; } public void setMessagingSid(String messagingSid) { this.messagingSid = messagingSid; } public NewArticleNotification getNewArticleNotification() { return newArticleNotification; } public void setNewArticleNotification(NewArticleNotification newArticleNotification) { this.newArticleNotification = newArticleNotification; }
public class NewArticleNotification { @NotBlank(message = "Content SID must be configured") @Pattern(regexp = "^HX[0-9a-fA-F]{32}$", message = "Invalid content SID format") private String contentSid; public String getContentSid() { return contentSid; } public void setContentSid(String contentSid) { this.contentSid = contentSid; } } }
repos\tutorials-master\saas-modules\twilio-whatsapp\src\main\java\com\baeldung\twilio\whatsapp\TwilioConfigurationProperties.java
1
请完成以下Java代码
public static class TransactionStateSynchronization implements Synchronization { protected final TransactionListener transactionListener; protected final TransactionState transactionState; private final CommandContext commandContext; public TransactionStateSynchronization( TransactionState transactionState, TransactionListener transactionListener, CommandContext commandContext ) { this.transactionState = transactionState; this.transactionListener = transactionListener; this.commandContext = commandContext; } public void beforeCompletion() {
if ( TransactionState.COMMITTING.equals(transactionState) || TransactionState.ROLLINGBACK.equals(transactionState) ) { transactionListener.execute(commandContext); } } public void afterCompletion(int status) { if (Status.STATUS_ROLLEDBACK == status && TransactionState.ROLLED_BACK.equals(transactionState)) { transactionListener.execute(commandContext); } else if (Status.STATUS_COMMITTED == status && TransactionState.COMMITTED.equals(transactionState)) { transactionListener.execute(commandContext); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cfg\jta\JtaTransactionContext.java
1
请在Spring Boot框架中完成以下Java代码
public class PickingJobId implements RepoIdAware { @JsonCreator public static PickingJobId ofRepoId(final int repoId) { return new PickingJobId(repoId); } @Nullable public static PickingJobId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new PickingJobId(repoId) : null; } public static int toRepoId(@Nullable final PickingJobId id) { return id != null ? id.getRepoId() : -1;
} int repoId; private PickingJobId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "M_Picking_Job_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final PickingJobId id1, @Nullable final PickingJobId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobId.java
2
请在Spring Boot框架中完成以下Java代码
public class OnEnabledPredicate extends OnEnabledComponent<RoutePredicateFactory<?>> { @Override protected String normalizeComponentName(Class<? extends RoutePredicateFactory<?>> predicateClass) { return "predicate." + NameUtils.normalizeRoutePredicateNameAsProperty(predicateClass); } @Override protected Class<?> annotationClass() { return ConditionalOnEnabledPredicate.class; } @Override protected Class<? extends RoutePredicateFactory<?>> defaultValueClass() { return DefaultValue.class; }
static class DefaultValue implements RoutePredicateFactory<Object> { @Override public Predicate<ServerWebExchange> apply(Consumer<Object> consumer) { throw new UnsupportedOperationException("class DefaultValue is never meant to be intantiated"); } @Override public Predicate<ServerWebExchange> apply(Object config) { throw new UnsupportedOperationException("class DefaultValue is never meant to be intantiated"); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\conditional\OnEnabledPredicate.java
2