instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class TodosService { private final TodoEntityMapper mapper; private final TodosRepository repo; /** * Gibt die Anzahl an Datensätzen zurück. * @return die Anzahl an Datensätzen */ long count() { return repo.count(); } /** * Gibt alle Todos zurück. * * @return eine unveränderliche Collection */ public Collection<Todo> findAll() { return repo.findAll().stream() .map(mapper::map) .collect(toList()); } /** * Durchsucht die Todos nach einer ID. * * @param id die ID * @return das Suchergebnis */ public Optional<Todo> findById(long id) { return repo.findById(id) .map(mapper::map); } /** * Fügt ein Item in den Datenbestand hinzu. Dabei wird eine ID generiert. * * @param item das anzulegende Item (ohne ID) * @return das gespeicherte Item (mit ID) * @throws IllegalArgumentException wenn das Item null oder die ID bereits belegt ist */ public Todo create(Todo item) { if (null == item || null != item.id()) { throw new IllegalArgumentException("item must exist without any id"); } return mapper.map(repo.save(mapper.map(item))); } /** * Aktualisiert ein Item im Datenbestand. * * @param item das zu ändernde Item mit ID * @throws IllegalArgumentException * wenn das Item oder dessen ID nicht belegt ist * @throws NotFoundException * wenn das Element mit der ID nicht gefunden wird */ public void update(Todo item) {
if (null == item || null == item.id()) { throw new IllegalArgumentException("item must exist with an id"); } // remove separat, um nicht neue Einträge hinzuzufügen (put allein würde auch ersetzen) if (repo.existsById(item.id())) { repo.save(mapper.map(item)); } else { throw new NotFoundException(); } } /** * Entfernt ein Item aus dem Datenbestand. * * @param id die ID des zu löschenden Items * @throws NotFoundException * wenn das Element mit der ID nicht gefunden wird */ public void delete(long id) { if (repo.existsById(id)) { repo.deleteById(id); } else { throw new NotFoundException(); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\sample\control\TodosService.java
2
请完成以下Java代码
public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set 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 Exclude. @param IsExclude Exclude access to the data - if not selected Include access to the data */ public void setIsExclude (boolean IsExclude) { set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude)); } /** Get Exclude. @return Exclude access to the data - if not selected Include access to the data */ public boolean isExclude () { Object oo = get_Value(COLUMNNAME_IsExclude); 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_CM_AccessProfile.java
1
请完成以下Java代码
public CalloutException setCalloutExecutorIfAbsent(final ICalloutExecutor calloutExecutor) { if (this.calloutExecutor == null) { setCalloutExecutor(calloutExecutor); } return this; } public CalloutException setField(final ICalloutField field) { this.field = field; setParameter("field", field); return this; }
public CalloutException setFieldIfAbsent(final ICalloutField field) { if (this.field == null) { setField(field); } return this; } public ICalloutField getCalloutField() { return field; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\exceptions\CalloutException.java
1
请完成以下Java代码
public void updateUOMFromHeaderToChecks() { assertNotProcessed(); for (final PPOrderWeightingRunCheck check : checks) { check.setUomId(targetWeight.getUomId()); } } private void assertNotProcessed() { if (isProcessed) { throw new AdempiereException("Already processed"); } }
public I_C_UOM getUOM() { return targetWeight.getUOM(); } public SeqNo getNextLineNo() { final SeqNo lastLineNo = checks.stream() .map(PPOrderWeightingRunCheck::getLineNo) .max(Comparator.naturalOrder()) .orElseGet(() -> SeqNo.ofInt(0)); return lastLineNo.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRun.java
1
请完成以下Java代码
public Integer getMaxPercentPerOrder() { return maxPercentPerOrder; } public void setMaxPercentPerOrder(Integer maxPercentPerOrder) { this.maxPercentPerOrder = maxPercentPerOrder; } public Integer getUseUnit() { return useUnit; } public void setUseUnit(Integer useUnit) { this.useUnit = useUnit; } public Integer getCouponStatus() { return couponStatus; } public void setCouponStatus(Integer couponStatus) {
this.couponStatus = couponStatus; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", deductionPerAmount=").append(deductionPerAmount); sb.append(", maxPercentPerOrder=").append(maxPercentPerOrder); sb.append(", useUnit=").append(useUnit); sb.append(", couponStatus=").append(couponStatus); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsIntegrationConsumeSetting.java
1
请完成以下Java代码
public String getRootCauseIncidentProcessInstanceId() { return rootCauseIncidentProcessInstanceId; } public void setRootCauseIncidentProcessInstanceId(String rootCauseIncidentProcessInstanceId) { this.rootCauseIncidentProcessInstanceId = rootCauseIncidentProcessInstanceId; } public String getRootCauseIncidentProcessDefinitionId() { return rootCauseIncidentProcessDefinitionId; } public void setRootCauseIncidentProcessDefinitionId(String rootCauseIncidentProcessDefinitionId) { this.rootCauseIncidentProcessDefinitionId = rootCauseIncidentProcessDefinitionId; } public String getRootCauseIncidentActivityId() { return rootCauseIncidentActivityId; } public void setRootCauseIncidentActivityId(String rootCauseIncidentActivityId) { this.rootCauseIncidentActivityId = rootCauseIncidentActivityId; } public String getRootCauseIncidentFailedActivityId() {
return rootCauseIncidentFailedActivityId; } public void setRootCauseIncidentFailedActivityId(String rootCauseIncidentFailedActivityId) { this.rootCauseIncidentFailedActivityId = rootCauseIncidentFailedActivityId; } public String getRootCauseIncidentConfiguration() { return rootCauseIncidentConfiguration; } public void setRootCauseIncidentConfiguration(String rootCauseIncidentConfiguration) { this.rootCauseIncidentConfiguration = rootCauseIncidentConfiguration; } public String getRootCauseIncidentMessage() { return rootCauseIncidentMessage; } public void setRootCauseIncidentMessage(String rootCauseIncidentMessage) { this.rootCauseIncidentMessage = rootCauseIncidentMessage; } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\IncidentDto.java
1
请完成以下Java代码
public String getCamundaResultVariable() { return camundaResultVariableAttribute.getValue(this); } public void setCamundaResultVariable(String camundaResultVariable) { camundaResultVariableAttribute.setValue(this, camundaResultVariable); } public String getCamundaTopic() { return camundaTopicAttribute.getValue(this); } public void setCamundaTopic(String camundaTopic) { camundaTopicAttribute.setValue(this, camundaTopic); } public String getCamundaType() { return camundaTypeAttribute.getValue(this); } public void setCamundaType(String camundaType) { camundaTypeAttribute.setValue(this, camundaType); } public String getCamundaDecisionRef() { return camundaDecisionRefAttribute.getValue(this); } public void setCamundaDecisionRef(String camundaDecisionRef) { camundaDecisionRefAttribute.setValue(this, camundaDecisionRef); } public String getCamundaDecisionRefBinding() { return camundaDecisionRefBindingAttribute.getValue(this); } public void setCamundaDecisionRefBinding(String camundaDecisionRefBinding) { camundaDecisionRefBindingAttribute.setValue(this, camundaDecisionRefBinding); } public String getCamundaDecisionRefVersion() { return camundaDecisionRefVersionAttribute.getValue(this); } public void setCamundaDecisionRefVersion(String camundaDecisionRefVersion) { camundaDecisionRefVersionAttribute.setValue(this, camundaDecisionRefVersion); }
public String getCamundaDecisionRefVersionTag() { return camundaDecisionRefVersionTagAttribute.getValue(this); } public void setCamundaDecisionRefVersionTag(String camundaDecisionRefVersionTag) { camundaDecisionRefVersionTagAttribute.setValue(this, camundaDecisionRefVersionTag); } @Override public String getCamundaMapDecisionResult() { return camundaMapDecisionResultAttribute.getValue(this); } @Override public void setCamundaMapDecisionResult(String camundaMapDecisionResult) { camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult); } public String getCamundaDecisionRefTenantId() { return camundaDecisionRefTenantIdAttribute.getValue(this); } public void setCamundaDecisionRefTenantId(String tenantId) { camundaDecisionRefTenantIdAttribute.setValue(this, tenantId); } @Override public String getCamundaTaskPriority() { return camundaTaskPriorityAttribute.getValue(this); } @Override public void setCamundaTaskPriority(String taskPriority) { camundaTaskPriorityAttribute.setValue(this, taskPriority); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BusinessRuleTaskImpl.java
1
请完成以下Java代码
public class C_Invoice_Line_Alloc { /** * Updates invoice line's QtyTU by summing up the invoice candidate's QtyTUs. * * @param invoiceLineAlloc * @task http://dewiki908/mediawiki/index.php/08469_Produzentenabrechnung:_Quantity_of_LU_wrong_%28100093568946%29 */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE }) public void updateQtyTU(final I_C_Invoice_Line_Alloc invoiceLineAlloc) { final IProductBL productBL = Services.get(IProductBL.class); // // Get Invoice Line if (invoiceLineAlloc.getC_InvoiceLine_ID() <= 0) { return; // shouldn't happen, but it's not really our business } final I_C_InvoiceLine invoiceLine = InterfaceWrapperHelper.create(invoiceLineAlloc.getC_InvoiceLine(), I_C_InvoiceLine.class); final boolean isFreightCost = productBL .getProductType(ProductId.ofRepoId(invoiceLine.getM_Product_ID())) .isFreightCost(); if (isFreightCost) { // the freight cost doesn't need any Qty TU invoiceLine.setQtyEnteredTU(BigDecimal.ZERO); save(invoiceLine); return; } // 08469 final BigDecimal qtyTUs; final I_M_InOutLine iol = InterfaceWrapperHelper.create(invoiceLine.getM_InOutLine(), I_M_InOutLine.class); if (iol != null) { qtyTUs = iol.getQtyEnteredTU(); } //
// Update Invoice Line else { qtyTUs = calculateQtyTUsFromInvoiceCandidates(invoiceLine); } invoiceLine.setQtyEnteredTU(qtyTUs); save(invoiceLine); } private final BigDecimal calculateQtyTUsFromInvoiceCandidates(final I_C_InvoiceLine invoiceLine) { BigDecimal qtyEnteredTU = BigDecimal.ZERO; final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class); final List<I_C_Invoice_Candidate> icForIl = invoiceCandDAO.retrieveIcForIl(invoiceLine); for (final I_C_Invoice_Candidate ic : icForIl) { final de.metas.handlingunits.model.I_C_Invoice_Candidate icExt = InterfaceWrapperHelper.create(ic, de.metas.handlingunits.model.I_C_Invoice_Candidate.class); final BigDecimal icQtyEnteredTU = icExt.getQtyEnteredTU(); if (icQtyEnteredTU != null) // safety { qtyEnteredTU = qtyEnteredTU.add(icQtyEnteredTU); } } return qtyEnteredTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\C_Invoice_Line_Alloc.java
1
请在Spring Boot框架中完成以下Java代码
public String getLayoutID() { return layoutID; } /** * Sets the value of the layoutID property. * * @param value * allowed object is * {@link String } * */ public void setLayoutID(String value) { this.layoutID = value; } /** * Indicates whether an amount of 0 shall be shown or not. * * @return * possible object is * {@link Boolean } * */ public Boolean isSuppressZero() { return suppressZero; } /** * Sets the value of the suppressZero property. * * @param value * allowed object is * {@link Boolean } * */ public void setSuppressZero(Boolean value) { this.suppressZero = value; } /** * Gets the value of the presentationDetailsExtension property. *
* @return * possible object is * {@link PresentationDetailsExtensionType } * */ public PresentationDetailsExtensionType getPresentationDetailsExtension() { return presentationDetailsExtension; } /** * Sets the value of the presentationDetailsExtension property. * * @param value * allowed object is * {@link PresentationDetailsExtensionType } * */ public void setPresentationDetailsExtension(PresentationDetailsExtensionType value) { this.presentationDetailsExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PresentationDetailsType.java
2
请完成以下Java代码
public MapFormat setArguments(final Map<String, ?> map) { if (map == null) { _argumentsMap = Collections.emptyMap(); } else { _argumentsMap = new HashMap<>(map); } return this; } /** Pre-compiled pattern */ private static final class Pattern { private static final int BUFSIZE = 255; /** Offsets to {} expressions */ private final int[] offsets; /** Keys enclosed by {} brackets */ private final String[] arguments; /** Max used offset */ private int maxOffset; private final String patternPrepared; public Pattern(final String patternStr, final String leftDelimiter, final String rightDelimiter, final boolean exactMatch) { super(); int idx = 0; int offnum = -1; final StringBuffer outpat = new StringBuffer(); offsets = new int[BUFSIZE]; arguments = new String[BUFSIZE]; maxOffset = -1; while (true) { int rightDelimiterIdx = -1; final int leftDelimiterIdx = patternStr.indexOf(leftDelimiter, idx); if (leftDelimiterIdx >= 0) { rightDelimiterIdx = patternStr.indexOf(rightDelimiter, leftDelimiterIdx + leftDelimiter.length()); } else { break; } if (++offnum >= BUFSIZE) { throw new IllegalArgumentException("TooManyArguments"); }
if (rightDelimiterIdx < 0) { if (exactMatch) { throw new IllegalArgumentException("UnmatchedBraces"); } else { break; } } outpat.append(patternStr.substring(idx, leftDelimiterIdx)); offsets[offnum] = outpat.length(); arguments[offnum] = patternStr.substring(leftDelimiterIdx + leftDelimiter.length(), rightDelimiterIdx); idx = rightDelimiterIdx + rightDelimiter.length(); maxOffset++; } outpat.append(patternStr.substring(idx)); patternPrepared = outpat.toString(); } public String substring(final int beginIndex, final int endIndex) { return patternPrepared.substring(beginIndex, endIndex); } public int length() { return patternPrepared.length(); } public int getMaxOffset() { return maxOffset; } public int getOffsetIndex(final int i) { return offsets[i]; } public String getArgument(final int i) { return arguments[i]; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\util\MapFormat.java
1
请完成以下Java代码
public WFProcess setTUPickingTarget( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @Nullable final TUPickingTarget target, @NonNull final UserId callerId) { return changeWFProcessById( wfProcessId, (wfProcess, pickingJob) -> { wfProcess.assertHasAccess(callerId); return pickingJobRestService.setTUPickingTarget(pickingJob, lineId, target); }); } public WFProcess closeLUPickingTarget( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @NonNull final UserId callerId) { return changeWFProcessById( wfProcessId, (wfProcess, pickingJob) -> { wfProcess.assertHasAccess(callerId); return pickingJobRestService.closeLUAndTUPickingTargets(pickingJob, lineId); }); } public WFProcess closeTUPickingTarget( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @NonNull final UserId callerId) { return changeWFProcessById( wfProcessId, (wfProcess, pickingJob) -> { wfProcess.assertHasAccess(callerId); return pickingJobRestService.closeTUPickingTarget(pickingJob, lineId); }); } public boolean hasClosedLUs( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @NonNull final UserId callerId) { return !getClosedLUs(wfProcessId, lineId, callerId).isEmpty(); }
@NonNull public List<HuId> getClosedLUs( @NonNull final WFProcessId wfProcessId, @Nullable final PickingJobLineId lineId, @NonNull final UserId callerId) { final WFProcess wfProcess = getWFProcessById(wfProcessId); wfProcess.assertHasAccess(callerId); final PickingJob pickingJob = getPickingJob(wfProcess); return pickingJobRestService.getClosedLUs(pickingJob, lineId); } public WFProcess pickAll(@NonNull final WFProcessId wfProcessId, @NonNull final UserId callerId) { final PickingJobId pickingJobId = toPickingJobId(wfProcessId); final PickingJob pickingJob = pickingJobRestService.pickAll(pickingJobId, callerId); return toWFProcess(pickingJob); } public PickingJobQtyAvailable getQtyAvailable(final WFProcessId wfProcessId, final @NotNull UserId callerId) { final PickingJobId pickingJobId = toPickingJobId(wfProcessId); return pickingJobRestService.getQtyAvailable(pickingJobId, callerId); } public JsonGetNextEligibleLineResponse getNextEligibleLineToPack(final @NonNull JsonGetNextEligibleLineRequest request, final @NotNull UserId callerId) { final GetNextEligibleLineToPackResponse response = pickingJobRestService.getNextEligibleLineToPack( GetNextEligibleLineToPackRequest.builder() .callerId(callerId) .pickingJobId(toPickingJobId(request.getWfProcessId())) .excludeLineId(request.getExcludeLineId()) .huScannedCode(request.getHuScannedCode()) .build() ); return JsonGetNextEligibleLineResponse.builder() .lineId(response.getLineId()) .logs(response.getLogs()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\PickingMobileApplication.java
1
请在Spring Boot框架中完成以下Java代码
public class SystemInfoServiceImpl implements SystemInfoService { private static final Logger LOG = LoggerFactory.getLogger(SystemInfoServiceImpl.class); private final static String SERVICE_PREFIX = "/services/system"; private final HttpClient httpClient; private final ObjectMapper mapper; private String baseUri; public SystemInfoServiceImpl(HttpClient httpClient, String baseUri, ObjectMapper mapper) { this.httpClient = httpClient; this.baseUri = baseUri + SERVICE_PREFIX; this.mapper = mapper; } @Override public SystemInfo getSystemInfo() throws ServiceException { try { HttpRequest request = HttpRequest.newBuilder()
.GET() .uri(URI.create(baseUri + "/version")) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { throw new ServiceException("Http status: " + response.statusCode()); } return mapper.readValue(response.body(), SystemInfo.class); } catch (Exception e) { LOG.error("ERROR: ", e); throw new ServiceException(e); } } }
repos\spring-examples-java-17\spring-bank\bank-client\src\main\java\itx\examples\springbank\client\service\SystemInfoServiceImpl.java
2
请完成以下Java代码
public class DefaultClockImpl implements org.activiti.engine.runtime.Clock { private static volatile Calendar CURRENT_TIME; @Override public void setCurrentTime(Date currentTime) { Calendar time = null; if (currentTime != null) { time = new GregorianCalendar(); time.setTime(currentTime); } setCurrentCalendar(time); } @Override public void setCurrentCalendar(Calendar currentTime) { CURRENT_TIME = currentTime; } @Override public void reset() { CURRENT_TIME = null; }
@Override public Date getCurrentTime() { return CURRENT_TIME == null ? new Date() : CURRENT_TIME.getTime(); } @Override public Calendar getCurrentCalendar() { return CURRENT_TIME == null ? new GregorianCalendar() : (Calendar) CURRENT_TIME.clone(); } @Override public Calendar getCurrentCalendar(TimeZone timeZone) { return TimeZoneUtil.convertToTimeZone(getCurrentCalendar(), timeZone); } @Override public TimeZone getCurrentTimeZone() { return getCurrentCalendar().getTimeZone(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\DefaultClockImpl.java
1
请完成以下Java代码
public class Movie { @Id @GeneratedValue Long id; private String title; private int released; private String tagline; @Relationship(type = "ACTED_IN", direction = INCOMING) private List<Role> roles; public Movie() { } public String getTitle() { return title; } public int getReleased() { return released; } public String getTagline() { return tagline; } public Collection<Role> getRoles() { return roles; }
public void setTitle(String title) { this.title = title; } public void setReleased(int released) { this.released = released; } public void setTagline(String tagline) { this.tagline = tagline; } public void setRoles(List<Role> roles) { this.roles = roles; } }
repos\tutorials-master\persistence-modules\neo4j\src\main\java\com\baeldung\neo4j\domain\Movie.java
1
请在Spring Boot框架中完成以下Java代码
public class PageDescriptorRepository { public PageDescriptor getBy(@NonNull final String completePageId) { final PageIdentifier pageIdentifier = PageIdentifier.ofCombinedString(completePageId); final I_T_Query_Selection_Pagination pageDescriptorRecord = Services .get(IQueryBL.class) .createQueryBuilder(I_T_Query_Selection_Pagination.class) .addEqualsFilter(I_T_Query_Selection_Pagination.COLUMN_UUID, pageIdentifier.getSelectionUid()) .addEqualsFilter(I_T_Query_Selection_Pagination.COLUMN_Page_Identifier, pageIdentifier.getPageUid()) .create() .firstOnly(I_T_Query_Selection_Pagination.class); if (pageDescriptorRecord == null) { throw new PageNotFoundException(completePageId); } return PageDescriptor.builder() .selectionUid(pageDescriptorRecord.getUUID()) .selectionTime(TimeUtil.asInstant(pageDescriptorRecord.getResult_Time()))
.totalSize(pageDescriptorRecord.getTotal_Size()) .pageSize(pageDescriptorRecord.getPage_Size()) .offset(pageDescriptorRecord.getPage_Offset()) .pageUid(pageDescriptorRecord.getPage_Identifier()) .build(); } public void save(@NonNull final PageDescriptor pageDescriptor) { final PageIdentifier pageIdentifier = pageDescriptor.getPageIdentifier(); final I_T_Query_Selection_Pagination record = newInstance(I_T_Query_Selection_Pagination.class); record.setUUID(pageIdentifier.getSelectionUid()); record.setResult_Time(TimeUtil.asTimestamp(pageDescriptor.getSelectionTime())); record.setTotal_Size(pageDescriptor.getTotalSize()); record.setPage_Size(pageDescriptor.getPageSize()); record.setPage_Offset(pageDescriptor.getOffset()); record.setPage_Identifier(pageIdentifier.getPageUid()); saveRecord(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\PageDescriptorRepository.java
2
请在Spring Boot框架中完成以下Java代码
public static class KeyStoreProperties { private String password; private String type; public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } } public static class SslCertificateProperties { @NestedConfigurationProperty private SslCertificateAliasProperties alias = new SslCertificateAliasProperties(); public SslCertificateAliasProperties getAlias() { return this.alias; } } public static class SslCertificateAliasProperties { private String all; private String cluster; private String defaultAlias; private String gateway; private String jmx; private String locator; private String server; private String web; public String getAll() { return this.all; } public void setAll(String all) { this.all = all; } public String getCluster() { return this.cluster; } public void setCluster(String cluster) { this.cluster = cluster; } public String getDefaultAlias() { return this.defaultAlias; } public void setDefaultAlias(String defaultAlias) { this.defaultAlias = defaultAlias; }
public String getGateway() { return this.gateway; } public void setGateway(String gateway) { this.gateway = gateway; } public String getJmx() { return this.jmx; } public void setJmx(String jmx) { this.jmx = jmx; } public String getLocator() { return this.locator; } public void setLocator(String locator) { this.locator = locator; } public String getServer() { return this.server; } public void setServer(String server) { this.server = server; } public String getWeb() { return this.web; } public void setWeb(String web) { this.web = web; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java
2
请完成以下Java代码
public IProductStorage getProductStorage(final ProductId productId, final I_C_UOM uom, final ZonedDateTime date) { return new HUItemProductStorage(this, productId, uom, date); } @Override public List<IProductStorage> getProductStorages(final ZonedDateTime date) { final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item); final List<IProductStorage> result = new ArrayList<>(storages.size()); for (final I_M_HU_Item_Storage storage : storages) { final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID()); final I_C_UOM uom = extractUOM(storage); final HUItemProductStorage productStorage = new HUItemProductStorage(this, productId, uom, date); result.add(productStorage); } return result; } private I_C_UOM extractUOM(final I_M_HU_Item_Storage storage) { return Services.get(IUOMDAO.class).getById(storage.getC_UOM_ID()); } @Override public boolean isEmpty() { final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item); for (final I_M_HU_Item_Storage storage : storages) { if (!isEmpty(storage)) { return false; } } return true; } private boolean isEmpty(final I_M_HU_Item_Storage storage) { final BigDecimal qty = storage.getQty();
if (qty.signum() != 0) { return false; } return true; } @Override public boolean isEmpty(final ProductId productId) { final I_M_HU_Item_Storage storage = dao.retrieveItemStorage(item, productId); if (storage == null) { return true; } return isEmpty(storage); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemStorage.java
1
请完成以下Java代码
public Set<String> getWhiteListedClasses() { return whiteListedClasses; } public SecureJavascriptConfigurator setWhiteListedClasses(Set<String> whiteListedClasses) { this.whiteListedClasses = whiteListedClasses; return this; } public SecureJavascriptConfigurator addWhiteListedClass(String whiteListedClass) { if (this.whiteListedClasses == null) { this.whiteListedClasses = new HashSet<>(); } this.whiteListedClasses.add(whiteListedClass); return this; } public long getMaxScriptExecutionTime() { return maxScriptExecutionTime; } public SecureJavascriptConfigurator setMaxScriptExecutionTime(long maxScriptExecutionTime) { this.maxScriptExecutionTime = maxScriptExecutionTime; return this; } public int getNrOfInstructionsBeforeStateCheckCallback() { return nrOfInstructionsBeforeStateCheckCallback; } public SecureJavascriptConfigurator setNrOfInstructionsBeforeStateCheckCallback(int nrOfInstructionsBeforeStateCheckCallback) { this.nrOfInstructionsBeforeStateCheckCallback = nrOfInstructionsBeforeStateCheckCallback; return this; } public int getMaxStackDepth() { return maxStackDepth; } public SecureJavascriptConfigurator setMaxStackDepth(int maxStackDepth) { this.maxStackDepth = maxStackDepth; return this;
} public long getMaxMemoryUsed() { return maxMemoryUsed; } public SecureJavascriptConfigurator setMaxMemoryUsed(long maxMemoryUsed) { this.maxMemoryUsed = maxMemoryUsed; return this; } public int getScriptOptimizationLevel() { return scriptOptimizationLevel; } public SecureJavascriptConfigurator setScriptOptimizationLevel(int scriptOptimizationLevel) { this.scriptOptimizationLevel = scriptOptimizationLevel; return this; } public SecureScriptContextFactory getSecureScriptContextFactory() { return secureScriptContextFactory; } public static SecureScriptClassShutter getSecureScriptClassShutter() { return secureScriptClassShutter; } public SecureJavascriptConfigurator setEnableAccessToBeans(boolean enableAccessToBeans) { this.enableAccessToBeans = enableAccessToBeans; return this; } public boolean isEnableAccessToBeans() { return enableAccessToBeans; } }
repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\SecureJavascriptConfigurator.java
1
请完成以下Java代码
public String getCamundaId() { return camundaIdAttribute.getValue(this); } public void setCamundaId(String camundaId) { camundaIdAttribute.setValue(this, camundaId); } public String getCamundaLabel() { return camundaLabelAttribute.getValue(this); } public void setCamundaLabel(String camundaLabel) { camundaLabelAttribute.setValue(this, camundaLabel); } public String getCamundaType() { return camundaTypeAttribute.getValue(this); } public void setCamundaType(String camundaType) { camundaTypeAttribute.setValue(this, camundaType); } public String getCamundaDatePattern() { return camundaDatePatternAttribute.getValue(this); } public void setCamundaDatePattern(String camundaDatePattern) { camundaDatePatternAttribute.setValue(this, camundaDatePattern); } public String getCamundaDefaultValue() { return camundaDefaultValueAttribute.getValue(this); } public void setCamundaDefaultValue(String camundaDefaultValue) { camundaDefaultValueAttribute.setValue(this, camundaDefaultValue); } public CamundaProperties getCamundaProperties() { return camundaPropertiesChild.getChild(this);
} public void setCamundaProperties(CamundaProperties camundaProperties) { camundaPropertiesChild.setChild(this, camundaProperties); } public CamundaValidation getCamundaValidation() { return camundaValidationChild.getChild(this); } public void setCamundaValidation(CamundaValidation camundaValidation) { camundaValidationChild.setChild(this, camundaValidation); } public Collection<CamundaValue> getCamundaValues() { return camundaValueCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaFormFieldImpl.java
1
请完成以下Java代码
public BigDecimal getFeeForProducedMaterial(final I_M_Product m_Product, final BigDecimal percentage) { final List<BigDecimal> percentages = new ArrayList<>(feeProductPercentage2fee.keySet()); // iterating from first to 2nd-last for (int i = 0; i < percentages.size() - 1; i++) { final BigDecimal currentPercentage = percentages.get(i); final BigDecimal nextPercentage = percentages.get(i + 1); if (currentPercentage.compareTo(percentage) <= 0 && nextPercentage.compareTo(percentage) > 0) { // found it: 'percentage' is in the interval that starts with 'currentPercentage' return feeProductPercentage2fee.get(currentPercentage); } } final BigDecimal lastInterval = percentages.get(percentages.size() - 1); return feeProductPercentage2fee.get(lastInterval); } @Override public Currency getCurrency() { return currencyDAO.getByCurrencyCode(CURRENCY_ISO); } public static void setOverallNumberOfInvoicings(final int overallNumberOfInvoicings) { HardCodedQualityBasedConfig.overallNumberOfInvoicings = overallNumberOfInvoicings; } @Override public int getOverallNumberOfInvoicings() { return overallNumberOfInvoicings; } public static void setQualityAdjustmentActive(final boolean qualityAdjustmentOn) { HardCodedQualityBasedConfig.qualityAdjustmentsActive = qualityAdjustmentOn; }
@Override public I_M_Product getRegularPPOrderProduct() { final IContextAware ctxAware = getContext(); return productPA.retrieveProduct(ctxAware.getCtx(), M_PRODUCT_REGULAR_PP_ORDER_VALUE, true, // throwExIfProductNotFound ctxAware.getTrxName()); } /** * @return the date that was set with {@link #setValidToDate(Timestamp)}, or falls back to "now plus 2 months". Never returns <code>null</code>. */ @Override public Timestamp getValidToDate() { if (validToDate == null) { return TimeUtil.addMonths(SystemTime.asDate(), 2); } return validToDate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\HardCodedQualityBasedConfig.java
1
请完成以下Java代码
private Instance[] readInstance(String corpus, FeatureMap featureMap) { IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(corpus); List<Instance> instanceList = new LinkedList<Instance>(); for (String line : lineIterator) { String[] cells = line.split(","); String text = cells[0], label = cells[1]; List<Integer> x = extractFeature(text, featureMap); int y = featureMap.tagSet.add(label); if (y == 0) y = -1; // 感知机标签约定为±1 else if (y > 1) throw new IllegalArgumentException("类别数大于2,目前只支持二分类。"); instanceList.add(new Instance(x, y)); } return instanceList.toArray(new Instance[0]); } /** * 特征提取 * * @param text 文本 * @param featureMap 特征映射 * @return 特征向量 */ protected abstract List<Integer> extractFeature(String text, FeatureMap featureMap); /** * 向特征向量插入特征 * * @param feature 特征 * @param featureMap 特征映射 * @param featureList 特征向量 */ protected static void addFeature(String feature, FeatureMap featureMap, List<Integer> featureList) { int featureId = featureMap.idOf(feature); if (featureId != -1) featureList.add(featureId); } /** * 样本 */ static class Instance { /** * 特征向量 */ List<Integer> x; /** * 标签 */ int y;
public Instance(List<Integer> x, int y) { this.x = x; this.y = y; } } /** * 准确率度量 */ static class BinaryClassificationFMeasure { float P, R, F1; public BinaryClassificationFMeasure(float p, float r, float f1) { P = p; R = r; F1 = f1; } @Override public String toString() { return String.format("P=%.2f R=%.2f F1=%.2f", P, R, F1); } } public LinearModel getModel() { return model; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronClassifier.java
1
请完成以下Java代码
public void setDivideRate (java.math.BigDecimal DivideRate) { set_Value (COLUMNNAME_DivideRate, DivideRate); } /** Get Divisor. @return Der Divisor ist der Kehrwert des Umrechnungsfaktors. */ @Override public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ziel ist Catch-Maßeinheit. @param IsCatchUOMForProduct Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public void setIsCatchUOMForProduct (boolean IsCatchUOMForProduct) { set_Value (COLUMNNAME_IsCatchUOMForProduct, Boolean.valueOf(IsCatchUOMForProduct)); } /** Get Ziel ist Catch-Maßeinheit. @return Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public boolean isCatchUOMForProduct () { Object oo = get_Value(COLUMNNAME_IsCatchUOMForProduct); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UOM_Conversion.java
1
请在Spring Boot框架中完成以下Java代码
public class UserJpaResource { private UserRepository userRepository; private PostRepository postRepository; public UserJpaResource(UserRepository userRepository, PostRepository postRepository) { this.userRepository = userRepository; this.postRepository = postRepository; } @GetMapping("/jpa/users") public List<User> retrieveAllUsers() { return userRepository.findAll(); } //http://localhost:8080/users //EntityModel //WebMvcLinkBuilder @GetMapping("/jpa/users/{id}") public EntityModel<User> retrieveUser(@PathVariable int id) { Optional<User> user = userRepository.findById(id); if(user.isEmpty()) throw new UserNotFoundException("id:"+id); EntityModel<User> entityModel = EntityModel.of(user.get()); WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUsers()); entityModel.add(link.withRel("all-users")); return entityModel; } @DeleteMapping("/jpa/users/{id}") public void deleteUser(@PathVariable int id) { userRepository.deleteById(id); } @GetMapping("/jpa/users/{id}/posts") public List<Post> retrievePostsForUser(@PathVariable int id) { Optional<User> user = userRepository.findById(id); if(user.isEmpty()) throw new UserNotFoundException("id:"+id);
return user.get().getPosts(); } @PostMapping("/jpa/users") public ResponseEntity<User> createUser(@Valid @RequestBody User user) { User savedUser = userRepository.save(user); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedUser.getId()) .toUri(); return ResponseEntity.created(location).build(); } @PostMapping("/jpa/users/{id}/posts") public ResponseEntity<Object> createPostForUser(@PathVariable int id, @Valid @RequestBody Post post) { Optional<User> user = userRepository.findById(id); if(user.isEmpty()) throw new UserNotFoundException("id:"+id); post.setUser(user.get()); Post savedPost = postRepository.save(post); URI location = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(savedPost.getId()) .toUri(); return ResponseEntity.created(location).build(); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\UserJpaResource.java
2
请完成以下Java代码
public FlowableScriptEvaluationRequest scopeContainer(VariableContainer scopeContainer) { this.scopeContainer = scopeContainer; return this; } @Override public FlowableScriptEvaluationRequest inputVariableContainer(VariableContainer inputVariableContainer) { this.inputVariableContainer = inputVariableContainer; return this; } @Override public FlowableScriptEvaluationRequest storeScriptVariables() { this.storeScriptVariables = true; return this; } @Override public ScriptEvaluation evaluate() throws FlowableScriptException { if (StringUtils.isEmpty(language)) { throw new FlowableIllegalArgumentException("language is required"); } if (StringUtils.isEmpty(script)) { throw new FlowableIllegalArgumentException("script is required");
} ScriptEngine scriptEngine = getEngineByName(language); Bindings bindings = createBindings(); try { Object result = scriptEngine.eval(script, bindings); return new ScriptEvaluationImpl(resolver, result); } catch (ScriptException e) { throw new FlowableScriptException(e.getMessage(), e); } } protected Bindings createBindings() { return new ScriptBindings(Collections.singletonList(resolver), scopeContainer, inputVariableContainer, storeScriptVariables); } } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\JSR223FlowableScriptEngine.java
1
请完成以下Java代码
public void invalidateCandidate(final I_C_Invoice_Line_Alloc ila) { Services.get(IInvoiceCandDAO.class).invalidateCand(ila.getC_Invoice_Candidate()); } /** * Making sure that the invoiced qty is not above invoice candidate's the invoiceable qty, i.e. <code>QtyToInvoice + QtyInvoiced</code>. * In the absence of any bugs, this would not be the case, but this method makes sure. * * @param ila */ @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_BEFORE_DELETE }) public void checkConsistency(final I_C_Invoice_Line_Alloc ila) { // Commented out for now, interferes with 05420 // // final I_C_Invoice_Candidate ic = ila.getC_Invoice_Candidate(); // // if (ic.isToRecompute() || ic.isToClear()) // { // return; // }
// // final BigDecimal invoicedQty = // new Query(InterfaceWrapperHelper.getCtx(ila), I_C_Invoice_Line_Alloc.Table_Name, I_C_Invoice_Line_Alloc.COLUMNNAME_C_Invoice_Candidate_ID + "=?", // InterfaceWrapperHelper.getTrxName(ila)) // .setParameters(ila.getC_Invoice_Candidate_ID()) // .setOnlyActiveRecords(true) // .setClient_ID() // .sum(I_C_Invoice_Line_Alloc.COLUMNNAME_QtyInvoiced); // // final BigDecimal maxQty = ic.getQtyToInvoice().add(ic.getQtyInvoiced()); // // Check.assume(invoicedQty.compareTo(maxQty) <= 0, // ic + " has QtyToInvoice + QtyInvoiced = " + maxQty + " but the QtyInvoiced of all C_Invoice_Line_Allocs sums up to " + invoicedQty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_Invoice_Line_Alloc.java
1
请完成以下Java代码
public String getSelectSqlPart_BaseLang() { return "SELECT " + (isNumericKey ? keyColumn.getAsString() : "NULL") // 1 - Key + "," + (!isNumericKey ? keyColumn.getAsString() : "NULL") // 2 - Value + "," + displayColumnSQL_BaseLang // 3 - Display + "," + activeColumnSQL // 4 - IsActive + "," + (descriptionColumnSQL_BaseLang != null ? descriptionColumnSQL_BaseLang : "NULL") // 5 - Description + "," + (hasEntityTypeColumn ? tableName + ".EntityType" : "NULL") // 6 - EntityType + " FROM " + sqlFromPart.getSqlFrom_BaseLang(); } @NonNull public String getSelectSqlPart_Trl() { return "SELECT " + (isNumericKey ? keyColumn.getAsString() : "NULL") // 1 - Key + "," + (!isNumericKey ? keyColumn.getAsString() : "NULL") // 2 - Value + "," + displayColumnSQL_Trl // 3 - Display + "," + activeColumnSQL // 4 - IsActive + "," + (descriptionColumnSQL_Trl != null ? descriptionColumnSQL_Trl : "NULL") // 5 - Description + "," + (hasEntityTypeColumn ? tableName + ".EntityType" : "NULL") // 6 - EntityType + " FROM " + sqlFromPart.getSqlFrom_Trl(); } public TranslatableParameterizedString getDisplayColumnSql() { return TranslatableParameterizedString.of(CTXNAME_AD_Language, displayColumnSQL_BaseLang, displayColumnSQL_Trl); }
public TranslatableParameterizedString getDescriptionColumnSql() { if (!Check.isBlank(descriptionColumnSQL_BaseLang)) { return TranslatableParameterizedString.of(CTXNAME_AD_Language, descriptionColumnSQL_BaseLang, descriptionColumnSQL_Trl); } else { return TranslatableParameterizedString.EMPTY; } } public int getEntityTypeQueryColumnIndex() {return isHasEntityTypeColumn() ? COLUMNINDEX_EntityType : -1;} } } // MLookupInfo
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookupInfo.java
1
请完成以下Java代码
private static IQuery<I_C_SubscriptionProgress> createRecipienRecordsQuery(@NonNull final ChangeRecipientsRequest changeRecipientsRequest) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_C_SubscriptionProgress> query = queryBL.createQueryBuilder(I_C_SubscriptionProgress.class) .addOnlyActiveRecordsFilter(); if (changeRecipientsRequest.isIsPermanentRecipient()) { final Timestamp now = SystemTime.asDayTimestamp(); query.addCompareFilter(I_C_SubscriptionProgress.COLUMN_EventDate, Operator.GREATER_OR_EQUAL, now); } else { query.addCompareFilter(I_C_SubscriptionProgress.COLUMN_EventDate, Operator.GREATER_OR_EQUAL, changeRecipientsRequest.getDateFrom()); query.addCompareFilter(I_C_SubscriptionProgress.COLUMN_EventDate, Operator.LESS_OR_EQUAL, changeRecipientsRequest.getDateTo()); } return query.addEqualsFilter(I_C_SubscriptionProgress.COLUMN_C_Flatrate_Term_ID, changeRecipientsRequest.getTerm().getC_Flatrate_Term_ID()) .addEqualsFilter(I_C_SubscriptionProgress.COLUMN_EventType, X_C_SubscriptionProgress.EVENTTYPE_Delivery) .addNotEqualsFilter(I_C_SubscriptionProgress.COLUMN_Status, X_C_SubscriptionProgress.STATUS_Done) .create(); } private static void updateSubScriptionProgressFromRequest( @NonNull final I_C_SubscriptionProgress subscriptionProgress, @NonNull final ChangeRecipientsRequest request) { subscriptionProgress.setDropShip_BPartner_ID(request.getDropShip_BPartner_ID()); subscriptionProgress.setDropShip_Location_ID(request.getDropShip_Location_ID()); subscriptionProgress.setDropShip_User_ID(request.getDropShip_User_ID()); save(subscriptionProgress); } private static void updateShipmentScheduleFromRequest( @NonNull final I_C_SubscriptionProgress subscriptionProgress, @NonNull final ChangeRecipientsRequest changeRecipientsRequest) { final I_M_ShipmentSchedule shipmentSchedule = InterfaceWrapperHelper.load(subscriptionProgress.getM_ShipmentSchedule_ID(), I_M_ShipmentSchedule.class);
ShipmentScheduleDocumentLocationAdapterFactory .mainLocationAdapter(shipmentSchedule) .setFrom(extractDropShipLocation(changeRecipientsRequest)); save(shipmentSchedule); } @NonNull private static DocumentLocation extractDropShipLocation(final @NonNull ChangeRecipientsRequest changeRecipientsRequest) { final BPartnerId dropShipBPartnerId = BPartnerId.ofRepoId(changeRecipientsRequest.getDropShip_BPartner_ID()); return DocumentLocation.builder() .bpartnerId(dropShipBPartnerId) .bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(dropShipBPartnerId, changeRecipientsRequest.getDropShip_Location_ID())) .contactId(BPartnerContactId.ofRepoIdOrNull(dropShipBPartnerId, changeRecipientsRequest.getDropShip_User_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\ChangeRecipient.java
1
请完成以下Java代码
public ProcessDefinitionEntity findLatestDefinitionByKey(String key) { return findLatestProcessDefinitionByKey(key); } @Override public ProcessDefinitionEntity findLatestDefinitionById(String id) { return findLatestProcessDefinitionById(id); } @Override public ProcessDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) { return getDbEntityManager().getCachedEntity(ProcessDefinitionEntity.class, definitionId); } @Override public ProcessDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) { return findLatestProcessDefinitionByKeyAndTenantId(definitionKey, tenantId);
} @Override public ProcessDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) { return findProcessDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) { return findProcessDefinitionByKeyVersionTagAndTenantId(definitionKey, definitionVersionTag, tenantId); } @Override public ProcessDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) { return findProcessDefinitionByDeploymentAndKey(deploymentId, definitionKey); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessDefinitionManager.java
1
请完成以下Java代码
private void writeLineToStream( @NonNull final String csvLine, @NonNull final DataOutputStream dataOutputStream) { try { final byte[] bytes = (csvLine + "\n").getBytes(DerKurierConstants.CSV_DATA_CHARSET); dataOutputStream.write(bytes); } catch (final IOException e) { throw new AdempiereException("IOException writing cvsLine to dataOutputStream", e).appendParametersToMessage() .setParameter("csvLine", csvLine) .setParameter("dataOutputStream", dataOutputStream); } } public static LinkedHashSet<String> readLinesFromArray(@NonNull final byte[] bytes) { final InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(bytes), DerKurierConstants.CSV_DATA_CHARSET);
try (final BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { final LinkedHashSet<String> result = new LinkedHashSet<>(); for (String line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) { result.add(line); } return result; } catch (IOException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierDeliveryOrderService.java
1
请完成以下Java代码
public Money getCOGSBySalesOrderId( @NonNull final OrderLineId salesOrderLineId, @NonNull final AcctSchemaId acctSchemaId) { final List<FactAcctQuery> factAcctQueries = getLineIdsByOrderLineIds(ImmutableSet.of(salesOrderLineId)) .stream() .map(inoutAndLineId -> FactAcctQuery.builder() .acctSchemaId(acctSchemaId) .accountConceptualName(AccountConceptualName.ofString(I_M_Product_Acct.COLUMNNAME_P_COGS_Acct)) .tableName(I_M_InOut.Table_Name) .recordId(inoutAndLineId.getInOutId().getRepoId()) .lineId(inoutAndLineId.getInOutLineId().getRepoId()) .build()) .collect(Collectors.toList()); return factAcctBL.getAcctBalance(factAcctQueries) .orElseGet(() -> Money.zero(acctSchemaBL.getAcctCurrencyId(acctSchemaId))); } @Override public ImmutableSet<I_M_InOut> getNotVoidedNotReversedForOrderId(@NonNull final OrderId orderId) { final InOutQuery query = InOutQuery.builder() .orderId(orderId) .excludeDocStatuses(ImmutableSet.of(DocStatus.Voided, DocStatus.Reversed)) .build(); return inOutDAO.retrieveByQuery(query).collect(ImmutableSet.toImmutableSet()); } @Override public void setShipperId(@NonNull final I_M_InOut inout) { inout.setM_Shipper_ID(ShipperId.toRepoId(findShipperId(inout))); }
private ShipperId findShipperId(@NonNull final I_M_InOut inout) { if (inout.getDropShip_BPartner_ID() > 0 && inout.getDropShip_Location_ID() > 0) { final Optional<ShipperId> deliveryAddressShipperId = bpartnerDAO.getShipperIdByBPLocationId(BPartnerLocationId.ofRepoId(inout.getDropShip_BPartner_ID(), inout.getDropShip_Location_ID())); if (deliveryAddressShipperId.isPresent()) { return deliveryAddressShipperId.get(); // we are done } } return bpartnerDAO.getShipperId(CoalesceUtil.coalesceSuppliersNotNull( () -> BPartnerId.ofRepoIdOrNull(inout.getDropShip_BPartner_ID()), () -> BPartnerId.ofRepoIdOrNull(inout.getC_BPartner_ID()))); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\impl\InOutBL.java
1
请完成以下Java代码
public class InvoicePaySchedule { @NonNull @Getter private final ImmutableList<InvoicePayScheduleLine> lines; @NonNull @Getter private final InvoiceId invoiceId; private InvoicePaySchedule(@NonNull final List<InvoicePayScheduleLine> lines) { if (lines.isEmpty()) { throw AdempiereException.noLines(); } this.lines = ImmutableList.copyOf(lines); this.invoiceId = CollectionUtils.extractSingleElement(lines, InvoicePayScheduleLine::getInvoiceId); } public static InvoicePaySchedule ofList(@NonNull final List<InvoicePayScheduleLine> lines) { return new InvoicePaySchedule(lines); } public static Optional<InvoicePaySchedule> optionalOfList(@NonNull final List<InvoicePayScheduleLine> lines) { return lines.isEmpty() ? Optional.empty() : Optional.of(ofList(lines)); } public static Collector<InvoicePayScheduleLine, ?, Optional<InvoicePaySchedule>> collect() { return GuavaCollectors.collectUsingListAccumulator(InvoicePaySchedule::optionalOfList); } public boolean isValid() { return lines.stream().allMatch(InvoicePayScheduleLine::isValid); } public boolean validate(@NonNull final Money invoiceGrandTotal) { final boolean isValid = computeIsValid(invoiceGrandTotal); markAsValid(isValid); return isValid;
} private boolean computeIsValid(@NonNull final Money invoiceGrandTotal) { final Money totalDue = getTotalDueAmt(); return invoiceGrandTotal.isEqualByComparingTo(totalDue); } private void markAsValid(final boolean isValid) { lines.forEach(line -> line.setValid(isValid)); } private Money getTotalDueAmt() { return getLines() .stream() .map(InvoicePayScheduleLine::getDueAmount) .reduce(Money::add) .orElseThrow(() -> new AdempiereException("No lines")); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\InvoicePaySchedule.java
1
请完成以下Java代码
public SignalEventReceivedBuilder executionId(String executionId) { ensureNotNull("executionId", executionId); this.executionId = executionId; return this; } @Override public SignalEventReceivedBuilder tenantId(String tenantId) { ensureNotNull( "The tenant-id cannot be null. Use 'withoutTenantId()' if you want to send the signal to a process definition or an execution which has no tenant-id.", "tenantId", tenantId); this.tenantId = tenantId; isTenantIdSet = true; return this; } @Override public SignalEventReceivedBuilder withoutTenantId() { // tenant-id is null isTenantIdSet = true; return this; } @Override public void send() { if (executionId != null && isTenantIdSet) { throw LOG.exceptionDeliverSignalToSingleExecutionWithTenantId(); } SignalEventReceivedCmd command = new SignalEventReceivedCmd(this); commandExecutor.execute(command); } public String getSignalName() { return signalName; }
public String getExecutionId() { return executionId; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } public VariableMap getVariables() { return variables; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\SignalEventReceivedBuilderImpl.java
1
请完成以下Java代码
public class DocumentAttachmentRestControllerHelper { @NonNull public static ResponseEntity<StreamingResponseBody> extractResponseEntryFromData(@NonNull final IDocumentAttachmentEntry entry) { if (entry.getData() == null) { throw new EntityNotFoundException("No attachment found") .setParameter("entry", entry) .setParameter("reason", "data is null or empty"); } final String entryFilename = entry.getFilename(); final String entryContentType = entry.getContentType(); final StreamingResponseBody entryData = outputStream -> { outputStream.write(entry.getData()); }; final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(entryContentType)); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + entryFilename + "\""); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); return new ResponseEntity<>(entryData, headers, HttpStatus.OK); } @NonNull public static ResponseEntity<StreamingResponseBody> extractResponseEntryFromURL(@NonNull final IDocumentAttachmentEntry entry) { final StreamingResponseBody responseBody = outputStream -> { outputStream.write(new byte[] {}); }; final HttpHeaders headers = new HttpHeaders(); headers.setLocation(entry.getUrl()); // forward to attachment entry's URL final ResponseEntity<StreamingResponseBody> response = new ResponseEntity<>(responseBody, headers, HttpStatus.FOUND); return response; } @NonNull public static ResponseEntity<StreamingResponseBody> extractResponseEntryFromLocalFileURL(@NonNull final IDocumentAttachmentEntry attachmentEntry)
{ final String contentType = attachmentEntry.getContentType(); final String filename = attachmentEntry.getFilename(); URL url = null; StreamingResponseBody responseBody = null; try { url = attachmentEntry.getUrl().toURL(); responseBody = streamFile(url); } catch (IOException e) { e.printStackTrace(); } final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(contentType)); headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); return new ResponseEntity<>(responseBody, headers, HttpStatus.OK); } @NonNull private StreamingResponseBody streamFile(@NonNull final URL url) throws IOException { final Path filePath = FileUtil.getFilePath(url); final StreamingResponseBody responseBody = outputStream -> { Files.copy(filePath, outputStream); }; return responseBody; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentRestControllerHelper.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult<CommonPage<OmsOrderDetail>> list(@RequestParam Integer status, @RequestParam(required = false, defaultValue = "1") Integer pageNum, @RequestParam(required = false, defaultValue = "5") Integer pageSize) { CommonPage<OmsOrderDetail> orderPage = portalOrderService.list(status,pageNum,pageSize); return CommonResult.success(orderPage); } @ApiOperation("根据ID获取订单详情") @RequestMapping(value = "/detail/{orderId}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderDetail> detail(@PathVariable Long orderId) { OmsOrderDetail orderDetail = portalOrderService.detail(orderId); return CommonResult.success(orderDetail); } @ApiOperation("用户取消订单") @RequestMapping(value = "/cancelUserOrder", method = RequestMethod.POST) @ResponseBody public CommonResult cancelUserOrder(Long orderId) { portalOrderService.cancelOrder(orderId); return CommonResult.success(null); }
@ApiOperation("用户确认收货") @RequestMapping(value = "/confirmReceiveOrder", method = RequestMethod.POST) @ResponseBody public CommonResult confirmReceiveOrder(Long orderId) { portalOrderService.confirmReceiveOrder(orderId); return CommonResult.success(null); } @ApiOperation("用户删除订单") @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST) @ResponseBody public CommonResult deleteOrder(Long orderId) { portalOrderService.deleteOrder(orderId); return CommonResult.success(null); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\OmsPortalOrderController.java
2
请完成以下Java代码
public void setScale(final int percent) { int step; for (step = 0; step < zoomFactors.length - 1; step++) { if (zoomFactors[step] * 100 >= percent) { break; } } setScaleStep(step); } public boolean loadPDF(final byte[] data) { return loadPDF(new ByteArrayInputStream(data)); } public boolean loadPDF(final InputStream is) { if (tmpFile != null) { tmpFile.delete(); } try { tmpFile = File.createTempFile("adempiere", ".pdf"); tmpFile.deleteOnExit(); } catch (IOException e) { e.printStackTrace(); return false; } try { final OutputStream os = new FileOutputStream(tmpFile); try { final byte[] buffer = new byte[32768]; for (int read; (read = is.read(buffer)) != -1; ) { os.write(buffer, 0, read); }
} catch (IOException e) { e.printStackTrace(); } finally { os.close(); } } catch (IOException e) { e.printStackTrace(); } return loadPDF(tmpFile.getAbsolutePath()); } @Override protected void finalize() throws Throwable { if (tmpFile != null) { tmpFile.delete(); } decoder.closePdfFile(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\pdf\viewer\PDFViewerBean.java
1
请完成以下Java代码
public MTree build() { return new MTree(this); } public Builder setCtx(final Properties ctx) { this.ctx = ctx; return this; } public Properties getCtx() { Check.assumeNotNull(ctx, "Parameter ctx is not null"); return ctx; } public Builder setUserRolePermissions(final IUserRolePermissions userRolePermissions) { this.userRolePermissions = userRolePermissions; return this; } public IUserRolePermissions getUserRolePermissions() { if (userRolePermissions == null) { return Env.getUserRolePermissions(getCtx()); } return userRolePermissions; } public Builder setAD_Tree_ID(final int AD_Tree_ID) { this.AD_Tree_ID = AD_Tree_ID; return this; } public int getAD_Tree_ID() { if (AD_Tree_ID <= 0) { throw new IllegalArgumentException("Param 'AD_Tree_ID' may not be null"); } return AD_Tree_ID; } public Builder setTrxName(@Nullable final String trxName) { this.trxName = trxName; return this; } @Nullable public String getTrxName() { return trxName; } /** * @param editable True, if tree can be modified * - includes inactive and empty summary nodes */ public Builder setEditable(final boolean editable) { this.editable = editable; return this; } public boolean isEditable() { return editable; } /** * @param clientTree the tree is displayed on the java client (not on web) */ public Builder setClientTree(final boolean clientTree) { this.clientTree = clientTree;
return this; } public boolean isClientTree() { return clientTree; } public Builder setAllNodes(final boolean allNodes) { this.allNodes = allNodes; return this; } public boolean isAllNodes() { return allNodes; } public Builder setLanguage(final String adLanguage) { this.adLanguage = adLanguage; return this; } private String getAD_Language() { if (adLanguage == null) { return Env.getADLanguageOrBaseLanguage(getCtx()); } return adLanguage; } } } // MTree
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTree.java
1
请完成以下Java代码
private void checkIsSameSeller(Map<String, Integer> prodIdCountMap) { // 获取prodcutID集合 Set<String> productIdSet = prodIdCountMap.keySet(); // 构造查询请求 List<ProdQueryReq> prodQueryReqList = buildOrderQueryReq(productIdSet); // 查询 Set<String> companyIdSet = query(prodQueryReqList); // 校验 if (companyIdSet.size() > 1) { throw new CommonBizException(ExpCodeEnum.SELLER_DIFFERENT); } } /** * 构造查询请求 * @param productIdSet 产品ID集合 * @return 查询请求列表 */ private List<ProdQueryReq> buildOrderQueryReq(Set<String> productIdSet) { List<ProdQueryReq> prodQueryReqList = Lists.newArrayList(); for (String productId : productIdSet) { ProdQueryReq prodQueryReq = new ProdQueryReq(); prodQueryReq.setId(productId); prodQueryReqList.add(prodQueryReq); }
return prodQueryReqList; } /** * 根据产品ID查询产品列表 * @param prodQueryReqList 产品查询请求 * @return 产品所属公司的ID */ private Set<String> query(List<ProdQueryReq> prodQueryReqList) { Set<String> companyIdSet = Sets.newHashSet(); for (ProdQueryReq prodQueryReq : prodQueryReqList) { ProductEntity productEntity = productService.findProducts(prodQueryReq).getData().get(0); companyIdSet.add(productEntity.getCompanyEntity().getId()); } return companyIdSet; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\checkparam\PlaceOrderCheckParamComponent.java
1
请完成以下Java代码
public ActivityImpl getSource() { return source; } public void setDestination(ActivityImpl destination) { this.destination = destination; destination.getIncomingTransitions().add(this); } public void addExecutionListener(ExecutionListener executionListener) { if (executionListeners == null) { executionListeners = new ArrayList<>(); } executionListeners.add(executionListener); } @Override public String toString() { return "(" + source.getId() + ")--" + (id != null ? id + "-->(" : ">(") + destination.getId() + ")"; } @SuppressWarnings("unchecked") public List<ExecutionListener> getExecutionListeners() { if (executionListeners == null) { return Collections.EMPTY_LIST; } return executionListeners; } // getters and setters ////////////////////////////////////////////////////// protected void setSource(ActivityImpl source) { this.source = source; }
@Override public ActivityImpl getDestination() { return destination; } public void setExecutionListeners(List<ExecutionListener> executionListeners) { this.executionListeners = executionListeners; } public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } @Override public Expression getSkipExpression() { return skipExpression; } public void setSkipExpression(Expression skipExpression) { this.skipExpression = skipExpression; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\TransitionImpl.java
1
请完成以下Java代码
public static void getOrDefault() { HashMap<String, Product> productsByName = new HashMap<>(); Product chocolate = new Product("chocolate", "something sweet"); Product defaultProduct = productsByName.getOrDefault("horse carriage", chocolate); Product bike = productsByName.getOrDefault("E-Bike", chocolate); //Prior to Java 8: Product bike2 = productsByName.containsKey("E-Bike") ? productsByName.get("E-Bike") : chocolate; Product defaultProduct2 = productsByName.containsKey("horse carriage") ? productsByName.get("horse carriage") : chocolate; } public static void putIfAbsent() { HashMap<String, Product> productsByName = new HashMap<>(); Product chocolate = new Product("chocolate", "something sweet"); productsByName.putIfAbsent("E-Bike", chocolate); //Prior to Java 8: if(productsByName.containsKey("E-Bike")) { productsByName.put("E-Bike", chocolate); } } public static void merge() { HashMap<String, Product> productsByName = new HashMap<>(); Product eBike2 = new Product("E-Bike", "A bike with a battery"); eBike2.getTags().add("sport"); productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct); //Prior to Java 8: if(productsByName.containsKey("E-Bike")) { productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2); } else {
productsByName.put("E-Bike", eBike2); } } public static void compute() { HashMap<String, Product> productsByName = new HashMap<>(); Product eBike2 = new Product("E-Bike", "A bike with a battery"); productsByName.compute("E-Bike", (k,v) -> { if(v != null) { return v.addTagsOfOtherProduct(eBike2); } else { return eBike2; } }); //Prior to Java 8: if(productsByName.containsKey("E-Bike")) { productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2); } else { productsByName.put("E-Bike", eBike2); } } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\hashmapguide\Product.java
1
请完成以下Java代码
protected void applyFilters(HistoricTaskInstanceReport reportQuery) { if (completedBefore != null) { reportQuery.completedBefore(completedBefore); } if (completedAfter != null) { reportQuery.completedAfter(completedAfter); } if(REPORT_TYPE_DURATION.equals(reportType)) { if(periodUnit == null) { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "periodUnit is null"); } } } protected HistoricTaskInstanceReport createNewReportQuery(ProcessEngine engine) { return engine.getHistoryService().createHistoricTaskInstanceReport();
} public List<HistoricTaskInstanceReportResult> executeCompletedReport(ProcessEngine engine) { HistoricTaskInstanceReport reportQuery = createNewReportQuery(engine); applyFilters(reportQuery); if(PROCESS_DEFINITION.equals(groupby)) { return reportQuery.countByProcessDefinitionKey(); } else if( TASK_NAME.equals(groupby) ){ return reportQuery.countByTaskName(); } else { throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupby); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceReportQueryDto.java
1
请完成以下Java代码
public CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } public void setCmmnEngineConfiguration(CmmnEngineConfiguration cmmnEngineConfiguration) { this.cmmnEngineConfiguration = cmmnEngineConfiguration; } @Override public CmmnRuntimeService getCmmnRuntimeService() { return cmmnRuntimeService; } public void setCmmnRuntimeService(CmmnRuntimeService cmmnRuntimeService) { this.cmmnRuntimeService = cmmnRuntimeService; } @Override public DynamicCmmnService getDynamicCmmnService() { return dynamicCmmnService; } public void setDynamicCmmnService(DynamicCmmnService dynamicCmmnService) { this.dynamicCmmnService = dynamicCmmnService; } @Override public CmmnTaskService getCmmnTaskService() { return cmmnTaskService; } public void setCmmnTaskService(CmmnTaskService cmmnTaskService) { this.cmmnTaskService = cmmnTaskService; } @Override public CmmnManagementService getCmmnManagementService() { return cmmnManagementService; } public void setCmmnManagementService(CmmnManagementService cmmnManagementService) { this.cmmnManagementService = cmmnManagementService; } @Override public CmmnRepositoryService getCmmnRepositoryService() { return cmmnRepositoryService; }
public void setCmmnRepositoryService(CmmnRepositoryService cmmnRepositoryService) { this.cmmnRepositoryService = cmmnRepositoryService; } @Override public CmmnHistoryService getCmmnHistoryService() { return cmmnHistoryService; } public void setCmmnHistoryService(CmmnHistoryService cmmnHistoryService) { this.cmmnHistoryService = cmmnHistoryService; } @Override public CmmnMigrationService getCmmnMigrationService() { return cmmnMigrationService; } public void setCmmnMigrationService(CmmnMigrationService cmmnMigrationService) { this.cmmnMigrationService = cmmnMigrationService; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnEngineImpl.java
1
请在Spring Boot框架中完成以下Java代码
public IBarDao barJpaDao() { return new BarJpaDao(); } @Bean public IBarDao barHibernateDao() { return new BarDao(); } @Bean public IBarAuditableDao barHibernateAuditableDao() { return new BarAuditableDao(); } @Bean public IFooDao fooHibernateDao() { return new FooDao(); } @Bean public IFooAuditableDao fooHibernateAuditableDao() {
return new FooAuditableDao(); } private final Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", "true"); // hibernateProperties.setProperty("hibernate.format_sql", "true"); hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); // Envers properties hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); return hibernateProperties; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\hibernate\audit\PersistenceConfig.java
2
请完成以下Java代码
public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!isRequestValid(request)) { filterChain.doFilter(request, response); return; } RecordableServletHttpRequest sourceRequest = new RecordableServletHttpRequest(request); HttpExchange.Started startedHttpExchange = HttpExchange.start(sourceRequest); int status = HttpStatus.INTERNAL_SERVER_ERROR.value(); try { filterChain.doFilter(request, response); status = response.getStatus(); } finally { RecordableServletHttpResponse sourceResponse = new RecordableServletHttpResponse(response, status); HttpExchange finishedExchange = startedHttpExchange.finish(sourceResponse, request::getUserPrincipal, () -> getSessionId(request), this.includes); this.repository.add(finishedExchange); } }
private boolean isRequestValid(HttpServletRequest request) { try { new URI(request.getRequestURL().toString()); return true; } catch (URISyntaxException ex) { return false; } } private @Nullable String getSessionId(HttpServletRequest request) { HttpSession session = request.getSession(false); return (session != null) ? session.getId() : null; } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\actuate\web\exchanges\HttpExchangesFilter.java
1
请完成以下Java代码
public String getDocumentNo() { return documentNo; } public static final class Builder { private String docBaseType; private String docSubType; private boolean soTrx; private boolean hasChanges; private boolean docNoControlled; private String documentNo; private Builder() { super(); } public DocumentNoInfo build() { return new DocumentNoInfo(this); } public Builder setDocumentNo(final String documentNo) { this.documentNo = documentNo; return this; } public Builder setDocBaseType(final String docBaseType) {
this.docBaseType = docBaseType; return this; } public Builder setDocSubType(final String docSubType) { this.docSubType = docSubType; return this; } public Builder setHasChanges(final boolean hasChanges) { this.hasChanges = hasChanges; return this; } public Builder setDocNoControlled(final boolean docNoControlled) { this.docNoControlled = docNoControlled; return this; } public Builder setIsSOTrx(final boolean isSOTrx) { soTrx = isSOTrx; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoInfo.java
1
请完成以下Java代码
private static RepoIdAwareDescriptor createRepoIdAwareDescriptor(final Class<? extends RepoIdAware> repoIdClass) { try { final Method ofRepoIdMethod = getMethodOrNull(repoIdClass, "ofRepoId", int.class); if (ofRepoIdMethod == null) { throw Check.newException("No method ofRepoId(int) found for " + repoIdClass); } Method ofRepoIdOrNullMethod = getMethodOrNull(repoIdClass, "ofRepoIdOrNull", int.class); if (ofRepoIdOrNullMethod == null) { ofRepoIdOrNullMethod = getMethodOrNull(repoIdClass, "ofRepoIdOrNull", Integer.class); } if (ofRepoIdOrNullMethod == null) { throw Check.newException("No method ofRepoIdOrNull(int) or ofRepoIdOrNull(Integer) found for " + repoIdClass); } final Method ofRepoIdOrNullMethodFinal = ofRepoIdOrNullMethod; return RepoIdAwareDescriptor.builder() .ofRepoIdFunction(repoId -> { try { return (RepoIdAware)ofRepoIdMethod.invoke(null, repoId); } catch (final Exception ex) { throw mkEx("Failed invoking " + ofRepoIdMethod + " with repoId=" + repoId, ex); } }) .ofRepoIdOrNullFunction(repoId -> { try { return (RepoIdAware)ofRepoIdOrNullMethodFinal.invoke(null, repoId); } catch (final Exception ex) { throw mkEx("Failed invoking " + ofRepoIdOrNullMethodFinal + " with repoId=" + repoId, ex); } }) .build(); } catch (final Exception ex) { final RuntimeException ex2 = Check.newException("Failed extracting " + RepoIdAwareDescriptor.class + " from " + repoIdClass); ex2.initCause(ex); throw ex2; } } @Nullable private static Method getMethodOrNull( @NonNull final Class<? extends RepoIdAware> repoIdClass, @NonNull final String methodName, final Class<?>... parameterTypes) { try { return repoIdClass.getMethod(methodName, parameterTypes); } catch (final NoSuchMethodException e) { return null; } catch (final SecurityException e) { throw new RuntimeException(e); }
} private static RuntimeException mkEx(final String msg, final Throwable cause) { final RuntimeException ex = Check.newException(msg); if (cause != null) { ex.initCause(cause); } return ex; } private static final ConcurrentHashMap<Class<? extends RepoIdAware>, RepoIdAwareDescriptor> repoIdAwareDescriptors = new ConcurrentHashMap<>(); @Value @Builder @VisibleForTesting static class RepoIdAwareDescriptor { @NonNull IntFunction<RepoIdAware> ofRepoIdFunction; @NonNull IntFunction<RepoIdAware> ofRepoIdOrNullFunction; } public static <T, R extends RepoIdAware> Comparator<T> comparingNullsLast(@NonNull final Function<T, R> keyMapper) { return Comparator.comparing(keyMapper, Comparator.nullsLast(Comparator.naturalOrder())); } public static <T extends RepoIdAware> boolean equals(@Nullable final T id1, @Nullable final T id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\RepoIdAwares.java
1
请在Spring Boot框架中完成以下Java代码
public StringToDateConverter stringToDateConverter() { return new StringToDateConverter(); } @Bean public DateToStringConverter dateToStringConverter() { return new DateToStringConverter(); } @Bean public StringToLocalDateTimeConverter stringToLocalDateTimeConverter() { return new StringToLocalDateTimeConverter(); } @Bean public LocalDateTimeToStringConverter localDateTimeToStringConverter() { return new LocalDateTimeToStringConverter(); } @Bean public StringToLocalDateConverter stringToLocalDateConverter() { return new StringToLocalDateConverter(); } @Bean public LocalDateToStringConverter localDateToStringConverter() { return new LocalDateToStringConverter(); } @Bean public StringToListConverter sringToListConverter(@Lazy ObjectMapper objectMapper) { return new StringToListConverter(objectMapper); } @Bean
public ListToStringConverter listToStringConverter(@Lazy ObjectMapper objectMapper) { return new ListToStringConverter(objectMapper); } @Bean public StringToSetConverter stringToSetConverter(@Lazy ObjectMapper objectMapper) { return new StringToSetConverter(objectMapper); } @Bean public SetToStringConverter setToStringConverter(@Lazy ObjectMapper objectMapper) { return new SetToStringConverter(objectMapper); } @Bean public StringToObjectValueConverter stringToObjectValueConverter(@Lazy ObjectMapper objectMapper) { return new StringToObjectValueConverter(objectMapper); } @Bean public ObjectValueToStringConverter objectValueToStringConverter(@Lazy ObjectMapper objectMapper) { return new ObjectValueToStringConverter(objectMapper); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\conf\impl\ProcessModelAutoConfiguration.java
2
请完成以下Java代码
public static class GetProductCategoriesCommandBuilder { public JsonGetProductCategoriesResponse execute() { return _build().execute(); } } public JsonGetProductCategoriesResponse execute() { final ImmutableList<JsonProductCategory> productCategories = servicesFacade.streamAllProductCategories() .map(this::toJsonProductCategory) .collect(ImmutableList.toImmutableList()); return JsonGetProductCategoriesResponse.builder() .productCategories(productCategories) .build(); }
private JsonProductCategory toJsonProductCategory(final I_M_Product_Category record) { final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(record); return JsonProductCategory.builder() .id(ProductCategoryId.ofRepoId(record.getM_Product_Category_ID())) .value(record.getValue()) .name(trls.getColumnTrl(I_M_Product_Category.COLUMNNAME_Name, record.getName()).translate(adLanguage)) .description(trls.getColumnTrl(I_M_Product_Category.COLUMNNAME_Description, record.getDescription()).translate(adLanguage)) .parentProductCategoryId(ProductCategoryId.ofRepoIdOrNull(record.getM_Product_Category_Parent_ID())) .defaultCategory(record.isDefault()) .createdUpdatedInfo(servicesFacade.extractCreatedUpdatedInfo(record)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\command\GetProductCategoriesCommand.java
1
请在Spring Boot框架中完成以下Java代码
public List<HistoryJob> findHistoryJobsByQueryCriteria(HistoryJobQueryImpl jobQuery) { return dataManager.findHistoryJobsByQueryCriteria(jobQuery); } @Override public long findHistoryJobCountByQueryCriteria(HistoryJobQueryImpl jobQuery) { return dataManager.findHistoryJobCountByQueryCriteria(jobQuery); } @Override public void delete(HistoryJobEntity jobEntity) { super.delete(jobEntity, false); deleteByteArrayRef(jobEntity.getExceptionByteArrayRef()); deleteByteArrayRef(jobEntity.getAdvancedJobHandlerConfigurationByteArrayRef());
deleteByteArrayRef(jobEntity.getCustomValuesByteArrayRef()); // Send event FlowableEventDispatcher eventDispatcher = getEventDispatcher(); if (eventDispatcher != null && getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_DELETED, jobEntity), serviceConfiguration.getEngineName()); } } @Override public void deleteNoCascade(HistoryJobEntity historyJobEntity) { super.delete(historyJobEntity); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityManagerImpl.java
2
请完成以下Java代码
public static String desEncrypt(String source) throws Exception { Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); DESKeySpec desKeySpec = getDesKeySpec(source); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV); return byte2hex(cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase(); } /** * 对称解密 */ public static String desDecrypt(String source) throws Exception { Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); byte[] src = hex2byte(source.getBytes(StandardCharsets.UTF_8)); DESKeySpec desKeySpec = getDesKeySpec(source); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); cipher.init(Cipher.DECRYPT_MODE, secretKey, IV); byte[] retByte = cipher.doFinal(src); return new String(retByte); } private static String byte2hex(byte[] inStr) { String stmp; StringBuilder out = new StringBuilder(inStr.length * 2); for (byte b : inStr) { stmp = Integer.toHexString(b & 0xFF); if (stmp.length() == 1) { out.append("0").append(stmp); } else { out.append(stmp); } } return out.toString();
} private static byte[] hex2byte(byte[] b) { int size = 2; if ((b.length % size) != 0) { throw new IllegalArgumentException("长度不是偶数"); } byte[] b2 = new byte[b.length / 2]; for (int n = 0; n < b.length; n += size) { String item = new String(b, n, 2); b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\EncryptUtils.java
1
请在Spring Boot框架中完成以下Java代码
public static class Packages { /** * Whether to trust all packages. */ private @Nullable Boolean trustAll; /** * List of specific packages to trust (when not trusting all packages). */ private List<String> trusted = new ArrayList<>(); public @Nullable Boolean getTrustAll() { return this.trustAll; }
public void setTrustAll(@Nullable Boolean trustAll) { this.trustAll = trustAll; } public List<String> getTrusted() { return this.trusted; } public void setTrusted(List<String> trusted) { this.trusted = trusted; } } }
repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java
2
请完成以下Java代码
public I_M_Product getM_Product() { return Services.get(IOLCandEffectiveValuesBL.class).getM_Product_Effective(olCand); } @Override public int getM_Product_ID() { final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class); return ProductId.toRepoId(olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand)); } @Override public I_M_AttributeSetInstance getM_AttributeSetInstance() { return olCand.getM_AttributeSetInstance(); } @Override public int getM_AttributeSetInstance_ID() { return olCand.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi) { olCand.setM_AttributeSetInstance(asi);
} @Override public String toString() { return "IAttributeSetInstanceAware[" + olCand.toString() + "]"; } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } }; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\OLCandASIAwareFactory.java
1
请完成以下Java代码
public Optional<UOMConversionRate> getRateIfExists(@NonNull final UomId fromUomId, @NonNull final UomId toUomId) { return Optional.ofNullable(getRateOrNull(fromUomId, toUomId)); } @Nullable private UOMConversionRate getRateOrNull(@NonNull final UomId fromUomId, @NonNull final UomId toUomId) { if (fromUomId.equals(toUomId)) { return UOMConversionRate.one(fromUomId); } final FromAndToUomIds key = FromAndToUomIds.builder() .fromUomId(fromUomId) .toUomId(toUomId) .build(); final UOMConversionRate directRate = rates.get(key); if (directRate != null) { return directRate; } final UOMConversionRate invertedRate = rates.get(key.invert()); if (invertedRate != null) { return invertedRate.invert(); } return null; } public boolean isEmpty() { return rates.isEmpty(); } public ImmutableSet<UomId> getCatchUomIds() { if (rates.isEmpty()) {
return ImmutableSet.of(); } return rates.values() .stream() .filter(UOMConversionRate::isCatchUOMForProduct) .map(UOMConversionRate::getToUomId) .collect(ImmutableSet.toImmutableSet()); } private static FromAndToUomIds toFromAndToUomIds(final UOMConversionRate conversion) { return FromAndToUomIds.builder() .fromUomId(conversion.getFromUomId()) .toUomId(conversion.getToUomId()) .build(); } @Value @Builder public static class FromAndToUomIds { @NonNull UomId fromUomId; @NonNull UomId toUomId; public FromAndToUomIds invert() { return builder().fromUomId(toUomId).toUomId(fromUomId).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionsMap.java
1
请完成以下Java代码
public class InformationRequirementImpl extends DmnModelElementInstanceImpl implements InformationRequirement { protected static ElementReference<Decision, RequiredDecisionReference> requiredDecisionRef; protected static ElementReference<InputData, RequiredInputReference> requiredInputRef; public InformationRequirementImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Decision getRequiredDecision() { return requiredDecisionRef.getReferenceTargetElement(this); } public void setRequiredDecision(Decision requiredDecision) { requiredDecisionRef.setReferenceTargetElement(this, requiredDecision); } public InputData getRequiredInput() { return requiredInputRef.getReferenceTargetElement(this); } public void setRequiredInput(InputData requiredInput) { requiredInputRef.setReferenceTargetElement(this, requiredInput); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InformationRequirement.class, DMN_ELEMENT_INFORMATION_REQUIREMENT) .namespaceUri(LATEST_DMN_NS)
.instanceProvider(new ModelTypeInstanceProvider<InformationRequirement>() { public InformationRequirement newInstance(ModelTypeInstanceContext instanceContext) { return new InformationRequirementImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); requiredDecisionRef = sequenceBuilder.element(RequiredDecisionReference.class) .uriElementReference(Decision.class) .build(); requiredInputRef = sequenceBuilder.element(RequiredInputReference.class) .uriElementReference(InputData.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\InformationRequirementImpl.java
1
请完成以下Java代码
public int getM_Shipment_Declaration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (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 Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @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; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration.java
1
请完成以下Java代码
public <T extends TypedValue> T getVariableTyped(String variableName) { return null; } public <T extends TypedValue> T getVariableTyped(String variableName, boolean deserializeObjectValue) { return null; } public <T extends TypedValue> T getVariableLocalTyped(String variableName) { return null; } public <T extends TypedValue> T getVariableLocalTyped(String variableName, boolean deserializeObjectValue) { return null; } @SuppressWarnings("unchecked") public Set<String> getVariableNames() { return Collections.EMPTY_SET; } public Set<String> getVariableNamesLocal() { return null; } public void setVariable(String variableName, Object value) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariableLocal(String variableName, Object value) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariables(Map<String, ? extends Object> variables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public void setVariablesLocal(Map<String, ? extends Object> variables) { throw new UnsupportedOperationException("No execution active, no variables can be set"); } public boolean hasVariables() { return false; } public boolean hasVariablesLocal() { return false; } public boolean hasVariable(String variableName) { return false; } public boolean hasVariableLocal(String variableName) { return false; } public void removeVariable(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariableLocal(String variableName) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariables() { throw new UnsupportedOperationException("No execution active, no variables can be removed");
} public void removeVariablesLocal() { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariables(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public void removeVariablesLocal(Collection<String> variableNames) { throw new UnsupportedOperationException("No execution active, no variables can be removed"); } public Map<String, CoreVariableInstance> getVariableInstances() { return Collections.emptyMap(); } public CoreVariableInstance getVariableInstance(String name) { return null; } public Map<String, CoreVariableInstance> getVariableInstancesLocal() { return Collections.emptyMap(); } public CoreVariableInstance getVariableInstanceLocal(String name) { return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\StartProcessVariableScope.java
1
请完成以下Java代码
public void setMultiLine_LinesCount (final int MultiLine_LinesCount) { set_Value (COLUMNNAME_MultiLine_LinesCount, MultiLine_LinesCount); } @Override public int getMultiLine_LinesCount() { return get_ValueAsInt(COLUMNNAME_MultiLine_LinesCount); } @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 setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSeqNo_SideList (final int SeqNo_SideList) { set_Value (COLUMNNAME_SeqNo_SideList, SeqNo_SideList); } @Override public int getSeqNo_SideList() { return get_ValueAsInt(COLUMNNAME_SeqNo_SideList); } @Override public void setUIStyle (final @Nullable java.lang.String UIStyle) { set_Value (COLUMNNAME_UIStyle, UIStyle); } @Override public java.lang.String getUIStyle() { return get_ValueAsString(COLUMNNAME_UIStyle); } /** * ViewEditMode AD_Reference_ID=541263
* Reference name: ViewEditMode */ public static final int VIEWEDITMODE_AD_Reference_ID=541263; /** Never = N */ public static final String VIEWEDITMODE_Never = "N"; /** OnDemand = D */ public static final String VIEWEDITMODE_OnDemand = "D"; /** Always = Y */ public static final String VIEWEDITMODE_Always = "Y"; @Override public void setViewEditMode (final @Nullable java.lang.String ViewEditMode) { set_Value (COLUMNNAME_ViewEditMode, ViewEditMode); } @Override public java.lang.String getViewEditMode() { return get_ValueAsString(COLUMNNAME_ViewEditMode); } /** * WidgetSize AD_Reference_ID=540724 * Reference name: WidgetSize_WEBUI */ public static final int WIDGETSIZE_AD_Reference_ID=540724; /** Small = S */ public static final String WIDGETSIZE_Small = "S"; /** Medium = M */ public static final String WIDGETSIZE_Medium = "M"; /** Large = L */ public static final String WIDGETSIZE_Large = "L"; /** ExtraLarge = XL */ public static final String WIDGETSIZE_ExtraLarge = "XL"; /** XXL = XXL */ public static final String WIDGETSIZE_XXL = "XXL"; @Override public void setWidgetSize (final @Nullable java.lang.String WidgetSize) { set_Value (COLUMNNAME_WidgetSize, WidgetSize); } @Override public java.lang.String getWidgetSize() { return get_ValueAsString(COLUMNNAME_WidgetSize); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Element.java
1
请完成以下Java代码
public class SolrProductDO { /** * ID 主键 */ @Id @Indexed(name = "id", type = "int") private Integer id; /** * SPU 名字 */ @Indexed(name = "name", type = "string") private String name; /** * 描述 */ @Indexed(name = "description", type = "string") private String description; /** * 分类编号 */ @Indexed(name = "cid", type = "cid") private Integer cid; /** * 分类名 */ @Indexed(name = "category_name", type = "string") private String categoryName; public Integer getId() { return id; } public SolrProductDO setId(Integer id) { this.id = id; return this; } public String getName() { return name; } public SolrProductDO setName(String name) { this.name = name; return this; } public String getDescription() { return description; } public SolrProductDO setDescription(String description) { this.description = description; return this; }
public Integer getCid() { return cid; } public SolrProductDO setCid(Integer cid) { this.cid = cid; return this; } public String getCategoryName() { return categoryName; } public SolrProductDO setCategoryName(String categoryName) { this.categoryName = categoryName; return this; } @Override public String toString() { return "SolrProductDO{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", cid=" + cid + ", categoryName='" + categoryName + '\'' + '}'; } }
repos\SpringBoot-Labs-master\lab-66\lab-66-spring-data-solr\src\main\java\cn\iocoder\springboot\lab15\springdatasolr\dataobject\SolrProductDO.java
1
请完成以下Java代码
public class MSchedulerPara extends X_AD_Scheduler_Para { /** * */ private static final long serialVersionUID = -703173920039087748L; /** * Standard Constructor * @param ctx context * @param AD_Scheduler_Para_ID id * @param trxName transaction */ public MSchedulerPara (Properties ctx, int AD_Scheduler_Para_ID, String trxName) { super (ctx, AD_Scheduler_Para_ID, trxName); } // MSchedulerPara /** * Load Constructor * @param ctx context * @param rs result set * @param trxName transaction */ public MSchedulerPara (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MSchedulerPara /** * Get Parameter Column Name * @return column name */ private String getColumnName() { final I_AD_Process_Para adProcessPara = getAD_Process_Para();
return adProcessPara == null ? null : adProcessPara.getColumnName(); } /** * String Representation * @return info */ @Override public String toString() { StringBuilder sb = new StringBuilder("MSchedulerPara["); sb.append(get_ID()).append("-") .append(getColumnName()).append("=").append(getParameterDefault()) .append("]"); return sb.toString(); } // toString } // MSchedulerPara
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSchedulerPara.java
1
请完成以下Java代码
public boolean getNeedLineBreak () { boolean linebreak = true; java.util.Enumeration en = elements (); // if this tag has one child, and it's a String, then don't // do any linebreaks to preserve whitespace while (en.hasMoreElements ()) { Object obj = en.nextElement (); if (obj instanceof StringElement) { linebreak = false; break; } } return linebreak; }
public boolean getBeginEndModifierDefined () { boolean answer = false; if (!this.getNeedClosingTag ()) answer = true; return answer; } public char getBeginEndModifier () { return '/'; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\XML.java
1
请完成以下Java代码
private static HUQRCodeGenerateRequest.Attribute toHUQRCodeGenerateRequestAttribute(final ImmutableAttributeSet attributes, AttributeCode attributeCode) { final AttributeId attributeId = attributes.getAttributeIdByCode(attributeCode); final HUQRCodeGenerateRequest.Attribute.AttributeBuilder resultBuilder = HUQRCodeGenerateRequest.Attribute.builder() .attributeId(attributeId); return attributes.getAttributeValueType(attributeCode) .map(new AttributeValueType.CaseMapper<HUQRCodeGenerateRequest.Attribute>() { @Override public HUQRCodeGenerateRequest.Attribute string() { return resultBuilder.valueString(attributes.getValueAsString(attributeCode)).build(); } @Override public HUQRCodeGenerateRequest.Attribute number() { return resultBuilder.valueNumber(attributes.getValueAsBigDecimal(attributeCode)).build(); } @Override public HUQRCodeGenerateRequest.Attribute date() {
return resultBuilder.valueDate(attributes.getValueAsLocalDate(attributeCode)).build(); } @Override public HUQRCodeGenerateRequest.Attribute list() { return resultBuilder.valueListId(attributes.getAttributeValueIdOrNull(attributeCode)).build(); } }); } @Override public void logout(final @NonNull UserId userId) { abortAll(userId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\ManufacturingMobileApplication.java
1
请完成以下Java代码
public void setTo(String value) { this.to = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="via" use="required" type="{http://www.forum-datenaustausch.ch/invoice}eanPartyType" /&gt; * &lt;attribute name="sequence_id" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedShort" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Via { @XmlAttribute(name = "via", required = true) protected String via; @XmlAttribute(name = "sequence_id", required = true) @XmlSchemaType(name = "unsignedShort") protected int sequenceId; /** * Gets the value of the via property. * * @return * possible object is * {@link String } * */
public String getVia() { return via; } /** * Sets the value of the via property. * * @param value * allowed object is * {@link String } * */ public void setVia(String value) { this.via = value; } /** * Gets the value of the sequenceId property. * */ public int getSequenceId() { return sequenceId; } /** * Sets the value of the sequenceId property. * */ public void setSequenceId(int value) { this.sequenceId = value; } } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TransportType.java
1
请在Spring Boot框架中完成以下Java代码
public class ReceiverUpsert { /** * Note that for now we don't include the email's active status, because the remote system is the source of truth for that. */ public static ReceiverUpsert of(@NonNull final ContactPerson contactPerson) { final long nowAsUnixTimestamp = SystemTime.asInstant().getEpochSecond(); final Integer id = StringUtils.trimBlankToOptional(contactPerson.getRemoteId()).map(Integer::parseInt).orElse(null); final boolean isNew = id == null || id <= 0; final Long registered = isNew ? nowAsUnixTimestamp : null; final Long activated; final DeactivatedOnRemotePlatform deactivatedOnRemotePlatform = contactPerson.getDeactivatedOnRemotePlatform(); if (deactivatedOnRemotePlatform.isYes()) { activated = 0L; } else if (deactivatedOnRemotePlatform.isNo()) { activated = nowAsUnixTimestamp; } else // unknown { activated = isNew ? nowAsUnixTimestamp : null; } return builder() .id(id) .email(contactPerson.getEmailAddressStringOrNull())
.registered(registered) .activated(activated) .build(); } @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable Integer id; @NonNull String email; @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable Long registered; @JsonInclude(JsonInclude.Include.NON_NULL) @Nullable Long activated; }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\restapi\models\ReceiverUpsert.java
2
请完成以下Java代码
public void setScriptScannerFactory(IScriptScannerFactory scriptScannerFactory) { internalScanner.setScriptScannerFactory(scriptScannerFactory); } @Override public IScriptScannerFactory getScriptScannerFactory() { return internalScanner.getScriptScannerFactory(); } @Override public IScriptScannerFactory getScriptScannerFactoryToUse() { return internalScanner.getScriptScannerFactoryToUse(); } @Override public IScriptFactory getScriptFactory() { return internalScanner.getScriptFactory(); } @Override public void setScriptFactory(IScriptFactory scriptFactory) { internalScanner.setScriptFactory(scriptFactory); }
@Override public IScriptFactory getScriptFactoryToUse() { return internalScanner.getScriptFactoryToUse(); } @Override public boolean hasNext() { return internalScanner.hasNext(); } @Override public IScript next() { return internalScanner.next(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\AbstractScriptDecoratorAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public void setLOCATIONCODE(String value) { this.locationcode = value; } /** * Gets the value of the locationname property. * * @return * possible object is * {@link String } * */ public String getLOCATIONNAME() { return locationname; } /** * Sets the value of the locationname property. * * @param value * allowed object is * {@link String } * */ public void setLOCATIONNAME(String value) { this.locationname = value; } /** * Gets the value of the drfad1 property. * * @return * possible object is * {@link DRFAD1 } * */ public DRFAD1 getDRFAD1() { return drfad1; } /** * Sets the value of the drfad1 property. * * @param value * allowed object is * {@link DRFAD1 } * */ public void setDRFAD1(DRFAD1 value) {
this.drfad1 = value; } /** * Gets the value of the dctad1 property. * * @return * possible object is * {@link DCTAD1 } * */ public DCTAD1 getDCTAD1() { return dctad1; } /** * Sets the value of the dctad1 property. * * @param value * allowed object is * {@link DCTAD1 } * */ public void setDCTAD1(DCTAD1 value) { this.dctad1 = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DADRE1.java
2
请在Spring Boot框架中完成以下Java代码
public void setOccurredAfter(Date occurredAfter) { this.occurredAfter = occurredAfter; } public Date getExitBefore() { return exitBefore; } public void setExitBefore(Date exitBefore) { this.exitBefore = exitBefore; } public Date getExitAfter() { return exitAfter; } public void setExitAfter(Date exitAfter) { this.exitAfter = exitAfter; } public Date getEndedBefore() { return endedBefore; } public void setEndedBefore(Date endedBefore) { this.endedBefore = endedBefore; } public Date getEndedAfter() { return endedAfter; } public void setEndedAfter(Date endedAfter) { this.endedAfter = endedAfter; } public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public String getTenantId() {
return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } public Boolean getIncludeLocalVariables() { return includeLocalVariables; } public void setIncludeLocalVariables(Boolean includeLocalVariables) { this.includeLocalVariables = includeLocalVariables; } public Set<String> getCaseInstanceIds() { return caseInstanceIds; } public void setCaseInstanceIds(Set<String> caseInstanceIds) { this.caseInstanceIds = caseInstanceIds; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceQueryRequest.java
2
请完成以下Java代码
public Object getTrxReferencedModel() { return referenceModel; } protected IProductStorage getStorage() { return storage; } @Override public IAllocationSource createAllocationSource(final I_M_HU hu) { return HUListAllocationSourceDestination.of(hu); } @Override public boolean isReadOnly()
{ return readonly; } @Override public void setReadOnly(final boolean readonly) { this.readonly = readonly; } @Override public I_M_HU_Item getInnerHUItem() { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUDocumentLine.java
1
请完成以下Java代码
public static StatusInfo valueOf(String statusCode, @Nullable Map<String, ?> details) { return new StatusInfo(statusCode, details); } public static StatusInfo valueOf(String statusCode) { return valueOf(statusCode, null); } public static StatusInfo ofUnknown() { return valueOf(STATUS_UNKNOWN, null); } public static StatusInfo ofUp() { return ofUp(null); } public static StatusInfo ofDown() { return ofDown(null); } public static StatusInfo ofOffline() { return ofOffline(null); } public static StatusInfo ofUp(@Nullable Map<String, Object> details) { return valueOf(STATUS_UP, details); } public static StatusInfo ofDown(@Nullable Map<String, Object> details) { return valueOf(STATUS_DOWN, details); } public static StatusInfo ofOffline(@Nullable Map<String, Object> details) { return valueOf(STATUS_OFFLINE, details); } public Map<String, Object> getDetails() { return Collections.unmodifiableMap(details); } public boolean isUp() { return STATUS_UP.equals(status);
} public boolean isOffline() { return STATUS_OFFLINE.equals(status); } public boolean isDown() { return STATUS_DOWN.equals(status); } public boolean isUnknown() { return STATUS_UNKNOWN.equals(status); } public static Comparator<String> severity() { return Comparator.comparingInt(STATUS_ORDER::indexOf); } @SuppressWarnings("unchecked") public static StatusInfo from(Map<String, ?> body) { Map<String, ?> details = Collections.emptyMap(); /* * Key "details" is present when accessing Spring Boot Actuator Health using * Accept-Header {@link org.springframework.boot.actuate.endpoint.ApiVersion#V2}. */ if (body.containsKey("details")) { details = (Map<String, ?>) body.get("details"); } else if (body.containsKey("components")) { details = (Map<String, ?>) body.get("components"); } return StatusInfo.valueOf((String) body.get("status"), details); } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\StatusInfo.java
1
请完成以下Java代码
public static String encodeSHAString(String str) { return encode(str, "SHA"); } /** * 用base64算法进行加密 * * @param str * 需要加密的字符串 * @return base64加密后的结果 */ public static String encodeBase64String(String str) { BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(str.getBytes()); } /** * 用base64算法进行解密 * * @param str * 需要解密的字符串 * @return base64解密后的结果 * @throws IOException */ public static String decodeBase64String(String str) throws IOException { BASE64Decoder encoder = new BASE64Decoder(); return new String(encoder.decodeBuffer(str)); } private static String encode(String str, String method) { MessageDigest mdInst = null; // 把密文转换成十六进制的字符串形式 // 单线程用StringBuilder,速度快 多线程用stringbuffer,安全 StringBuilder dstr = new StringBuilder(); try { // 获得MD5摘要算法的 MessageDigest对象 mdInst = MessageDigest.getInstance(method); // 使用指定的字节更新摘要
mdInst.update(str.getBytes()); // 获得密文 byte[] md = mdInst.digest(); for (int i = 0; i < md.length; i++) { int tmp = md[i]; if (tmp < 0) { tmp += 256; } if (tmp < 16) { dstr.append("0"); } dstr.append(Integer.toHexString(tmp)); } } catch (NoSuchAlgorithmException e) { LOG.error(e); } return dstr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\EncryptUtil.java
1
请完成以下Java代码
public String[] partOfSpeechTag(List<String> wordList) { if (posTagger == null) { throw new IllegalStateException("未提供词性标注模型"); } return tag(wordList); } /** * 命名实体识别 * * @param wordArray * @param posArray * @return */ public String[] namedEntityRecognize(String[] wordArray, String[] posArray) { if (neRecognizer == null) { throw new IllegalStateException("未提供命名实体识别模型"); } return recognize(wordArray, posArray); } /** * 在线学习 * * @param segmentedTaggedSentence 已分词、标好词性和命名实体的人民日报2014格式的句子 * @return 是否学习成果(失败的原因是句子格式不合法) */ public boolean learn(String segmentedTaggedSentence) { Sentence sentence = Sentence.create(segmentedTaggedSentence); return learn(sentence); } /** * 在线学习 * * @param sentence 已分词、标好词性和命名实体的人民日报2014格式的句子 * @return 是否学习成果(失败的原因是句子格式不合法) */ public boolean learn(Sentence sentence) { CharTable.normalize(sentence); if (!getPerceptronSegmenter().learn(sentence)) return false; if (posTagger != null && !getPerceptronPOSTagger().learn(sentence)) return false; if (neRecognizer != null && !getPerceptionNERecognizer().learn(sentence)) return false; return true;
} /** * 获取分词器 * * @return */ public PerceptronSegmenter getPerceptronSegmenter() { return (PerceptronSegmenter) segmenter; } /** * 获取词性标注器 * * @return */ public PerceptronPOSTagger getPerceptronPOSTagger() { return (PerceptronPOSTagger) posTagger; } /** * 获取命名实体识别器 * * @return */ public PerceptronNERecognizer getPerceptionNERecognizer() { return (PerceptronNERecognizer) neRecognizer; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronLexicalAnalyzer.java
1
请完成以下Java代码
public class MWorkflowProcessor extends X_AD_WorkflowProcessor implements AdempiereProcessor { /** * */ private static final long serialVersionUID = 9164558879064747427L; /** * Get Active * * @param ctx context * @return active processors */ public static MWorkflowProcessor[] getActive(Properties ctx) { List<MWorkflowProcessor> list = new Query(ctx, Table_Name, null, null) .setOnlyActiveRecords(true) .list(MWorkflowProcessor.class); MWorkflowProcessor[] retValue = new MWorkflowProcessor[list.size()]; list.toArray(retValue); return retValue; } // getActive /************************************************************************** * Standard Constructor * * @param ctx context * @param AD_WorkflowProcessor_ID id * @param trxName transaction */ public MWorkflowProcessor(Properties ctx, int AD_WorkflowProcessor_ID, String trxName) { super(ctx, AD_WorkflowProcessor_ID, trxName); } // MWorkflowProcessor /** * Load Constructor * * @param ctx context * @param rs result set * @param trxName transaction */ public MWorkflowProcessor(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MWorkflowProcessor /** * Get Server ID * * @return id */ @Override public String getServerID() { return "WorkflowProcessor" + get_ID();
} // getServerID /** * Get Date Next Run * * @param requery requery * @return date next run */ @Override public Timestamp getDateNextRun(boolean requery) { if (requery) load(get_TrxName()); return getDateNextRun(); } // getDateNextRun /** * Get Logs * * @return logs */ @Override public AdempiereProcessorLog[] getLogs() { List<MWorkflowProcessorLog> list = new Query(getCtx(), MWorkflowProcessorLog.Table_Name, "AD_WorkflowProcessor_ID=?", get_TrxName()) .setParameters(new Object[] { getAD_WorkflowProcessor_ID() }) .setOrderBy("Created DESC") .list(MWorkflowProcessorLog.class); MWorkflowProcessorLog[] retValue = new MWorkflowProcessorLog[list.size()]; list.toArray(retValue); return retValue; } // getLogs /** * Delete old Request Log * * @return number of records */ public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_WorkflowProcessorLog " + "WHERE AD_WorkflowProcessor_ID=" + getAD_WorkflowProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MWorkflowProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\wf\MWorkflowProcessor.java
1
请完成以下Java代码
public Optional<String> getLookupTableName() { return Optional.of(labelsTableName); } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } @Override public boolean isCached() { return true; } @Override @Nullable public String getCachePrefix() { return null; // not important because isCached() returns false } @Override public void cacheInvalidate() { labelsValuesLookupDataSource.cacheInvalidate(); } @Override public boolean isHighVolume() { return false; } @Override public LookupSource getLookupSourceType() { return LookupSource.lookup; } @Override public boolean hasParameters() { return true; } @Override public Set<String> getDependsOnFieldNames() { return CtxNames.toNames(parameters); } @Override public boolean isNumericKey() { return false; } @Override public LookupDataSourceFetcher getLookupDataSourceFetcher() { return this; } @Override public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return LookupDataSourceContext.builder(tableName) .putFilterById(IdsToFilter.ofSingleValue(id)); } @Override public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx) { final Object id = evalCtx.getSingleIdToFilterAsObject(); if (id == null) { throw new IllegalStateException("No ID provided in " + evalCtx); } return labelsValuesLookupDataSource.findById(id); } @Override
public LookupDataSourceContext.Builder newContextForFetchingList() { return LookupDataSourceContext.builder(tableName) .setRequiredParameters(parameters) .requiresAD_Language() .requiresUserRolePermissionsKey(); } @Override public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx) { final String filter = evalCtx.getFilter(); return labelsValuesLookupDataSource.findEntities(evalCtx, filter); } public Set<Object> normalizeStringIds(final Set<String> stringIds) { if (stringIds.isEmpty()) { return ImmutableSet.of(); } if (isLabelsValuesUseNumericKey()) { return stringIds.stream() .map(LabelsLookup::convertToInt) .collect(ImmutableSet.toImmutableSet()); } else { return ImmutableSet.copyOf(stringIds); } } private static int convertToInt(final String stringId) { try { return Integer.parseInt(stringId); } catch (final Exception ex) { throw new AdempiereException("Failed converting `" + stringId + "` to int.", ex); } } public ColumnSql getSqlForFetchingValueIdsByLinkId(@NonNull final String tableNameOrAlias) { final String sql = "SELECT array_agg(" + labelsValueColumnName + ")" + " FROM " + labelsTableName + " WHERE " + labelsLinkColumnName + "=" + tableNameOrAlias + "." + linkColumnName + " AND IsActive='Y'"; return ColumnSql.ofSql(sql, tableNameOrAlias); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LabelsLookup.java
1
请在Spring Boot框架中完成以下Java代码
private void increaseMainMetric(String request, int status) { Map<Integer, Integer> statusMap = metricMap.get(request); if (statusMap == null) { statusMap = new ConcurrentHashMap<>(); } Integer count = statusMap.get(status); if (count == null) { count = 1; } else { count++; } statusMap.put(status, count); metricMap.put(request, statusMap); } private void increaseStatusMetric(int status) { statusMetric.merge(status, 1, Integer::sum); }
private void updateTimeMap(int status) { final String time = DATE_FORMAT.format(new Date()); Map<Integer, Integer> statusMap = timeMap.get(time); if (statusMap == null) { statusMap = new ConcurrentHashMap<>(); } Integer count = statusMap.get(status); if (count == null) { count = 1; } else { count++; } statusMap.put(status, count); timeMap.put(time, statusMap); } }
repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\java\com\baeldung\metrics\service\InMemoryMetricService.java
2
请完成以下Java代码
private static List<PackageItem> getHuStorageListOrNull(@Nullable final InOutId inOutId) { if (inOutId == null) { return ImmutableList.of(); } return Services.get(IQueryBL.class) .createQueryBuilder(I_M_InOutLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_InOutLine.COLUMNNAME_M_InOut_ID, inOutId) .create() .stream() .map(PurchaseOrderToShipperTransportationRepository::toPackageItem) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } @Nullable private static PackageItem toPackageItem(@NonNull final I_M_InOutLine inOutLine) { final ProductId productId = ProductId.ofRepoIdOrNull(inOutLine.getM_Product_ID()); final OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(inOutLine.getC_OrderLine_ID()); if (productId == null || orderLineId == null) { return null; } return PackageItem.builder() .productId(productId) .quantity(Quantitys.of(inOutLine.getMovementQty(), UomId.ofRepoId(inOutLine.getC_UOM_ID()))) .orderAndLineId(OrderAndLineId.of(OrderId.ofRepoId(inOutLine.getC_Order_ID()), orderLineId)) .build(); } public Collection<I_M_ShippingPackage> getBy(final @NonNull ShippingPackageQuery query) { return toShippingPackageQueryBuilder(query) .create() .list(); }
private IQuery<I_M_Package> toPackageSqlQuery(final @NonNull ShippingPackageQuery query) { final IQueryBuilder<I_M_ShippingPackage> builder = toShippingPackageQueryBuilder(query); return builder.andCollect(I_M_ShippingPackage.COLUMN_M_Package_ID) .create(); } private IQueryBuilder<I_M_ShippingPackage> toShippingPackageQueryBuilder(final @NonNull ShippingPackageQuery query) { if(query.getOrderIds().isEmpty() && query.getOrderLineIds().isEmpty()) { return queryBL.createQueryBuilder(I_M_ShippingPackage.class) .filter(ConstantQueryFilter.of(false)); } final IQueryBuilder<I_M_ShippingPackage> builder = queryBL.createQueryBuilder(I_M_ShippingPackage.class) .addOnlyActiveRecordsFilter(); final Collection<OrderId> orderIds = query.getOrderIds(); if (!orderIds.isEmpty()) { builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_Order_ID, orderIds); } final Collection<OrderLineId> orderLineIds = query.getOrderLineIds(); if (!orderLineIds.isEmpty()) { builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_OrderLine_ID, orderLineIds); } return builder; } public void deleteBy(@NonNull final ShippingPackageQuery query) { deleteFromShipperTransportation(toPackageSqlQuery(query).listIds(PackageId::ofRepoId)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\PurchaseOrderToShipperTransportationRepository.java
1
请完成以下Java代码
public static DmnManagementService getDmnManagementService(AbstractEngineConfiguration engineConfiguration) { DmnManagementService dmnManagementService = null; DmnEngineConfigurationApi dmnEngineConfiguration = getDmnEngineConfiguration(engineConfiguration); if (dmnEngineConfiguration != null) { dmnManagementService = dmnEngineConfiguration.getDmnManagementService(); } return dmnManagementService; } // FORM ENGINE public static FormEngineConfigurationApi getFormEngineConfiguration(AbstractEngineConfiguration engineConfiguration) { return (FormEngineConfigurationApi) engineConfiguration.getEngineConfigurations().get(EngineConfigurationConstants.KEY_FORM_ENGINE_CONFIG); } public static FormRepositoryService getFormRepositoryService(ProcessEngineConfiguration processEngineConfiguration) { FormRepositoryService formRepositoryService = null; FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(processEngineConfiguration); if (formEngineConfiguration != null) { formRepositoryService = formEngineConfiguration.getFormRepositoryService(); } return formRepositoryService; } public static FormService getFormService(AbstractEngineConfiguration engineConfiguration) { FormService formService = null; FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(engineConfiguration); if (formEngineConfiguration != null) { formService = formEngineConfiguration.getFormService(); } return formService; }
public static FormManagementService getFormManagementService(AbstractEngineConfiguration engineConfiguration) { FormManagementService formManagementService = null; FormEngineConfigurationApi formEngineConfiguration = getFormEngineConfiguration(engineConfiguration); if (formEngineConfiguration != null) { formManagementService = formEngineConfiguration.getFormManagementService(); } return formManagementService; } // CONTENT ENGINE public static ContentEngineConfigurationApi getContentEngineConfiguration(AbstractEngineConfiguration engineConfiguration) { return (ContentEngineConfigurationApi) engineConfiguration.getEngineConfigurations().get(EngineConfigurationConstants.KEY_CONTENT_ENGINE_CONFIG); } public static ContentService getContentService(AbstractEngineConfiguration engineConfiguration) { ContentService contentService = null; ContentEngineConfigurationApi contentEngineConfiguration = getContentEngineConfiguration(engineConfiguration); if (contentEngineConfiguration != null) { contentService = contentEngineConfiguration.getContentService(); } return contentService; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\EngineServiceUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class Config { @Bean("h2DataSource") public DataSource dataSource() { HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:h2:mem:mydb;MODE=LEGACY"); config.setUsername("sa"); config.setPassword(""); config.setDriverClassName("org.h2.Driver"); return new HikariDataSource(config); } @Bean("h2EntityManagerFactory") public EntityManagerFactory entityManagerFactory(@Qualifier("h2DataSource") DataSource dataSource) { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setGenerateDdl(false); LocalContainerEntityManagerFactoryBean managerFactoryBean = new LocalContainerEntityManagerFactoryBean();
managerFactoryBean.setJpaVendorAdapter(vendorAdapter); managerFactoryBean.setPackagesToScan(Config.class.getPackage() .getName()); managerFactoryBean.setDataSource(dataSource); Properties properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); properties.setProperty("hibernate.show_sql", "true"); properties.setProperty("hibernate.format_sql", "true"); managerFactoryBean.setJpaProperties(properties); managerFactoryBean.afterPropertiesSet(); return managerFactoryBean.getObject(); } }
repos\tutorials-master\persistence-modules\read-only-transactions\src\main\java\com\baeldung\readonlytransactions\h2\Config.java
2
请完成以下Java代码
public void onReject() { } @Override public void onTimeout() { if (onTimeout != null) { onTimeout.accept(msgId); } } @Override public void onCancel() { } @Override public void onReadyToSend() { } @Override public void onConnecting() { } @Override public void onDtlsRetransmission(int flight) { } @Override public void onSent(boolean retransmission) { } @Override public void onSendError(Throwable error) {
} @Override public void onResponseHandlingError(Throwable cause) { } @Override public void onContextEstablished(EndpointContext endpointContext) { } @Override public void onTransferComplete() { } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\TbCoapMessageObserver.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + copies; result = prime * result + ((format == null) ? 0 : format.hashCode()); result = prime * result + pageCount; result = prime * result + ((printJobInstructionsID == null) ? 0 : printJobInstructionsID.hashCode()); result = prime * result + ((printPackageId == null) ? 0 : printPackageId.hashCode()); result = prime * result + ((printPackageInfos == null) ? 0 : printPackageInfos.hashCode()); result = prime * result + ((transactionId == null) ? 0 : transactionId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PrintPackage other = (PrintPackage)obj; if (copies != other.copies) return false; if (format == null) { if (other.format != null) return false; } else if (!format.equals(other.format)) return false; if (pageCount != other.pageCount) return false; if (printJobInstructionsID == null)
{ if (other.printJobInstructionsID != null) return false; } else if (!printJobInstructionsID.equals(other.printJobInstructionsID)) return false; if (printPackageId == null) { if (other.printPackageId != null) return false; } else if (!printPackageId.equals(other.printPackageId)) return false; if (printPackageInfos == null) { if (other.printPackageInfos != null) return false; } else if (!printPackageInfos.equals(other.printPackageInfos)) return false; if (transactionId == null) { if (other.transactionId != null) return false; } else if (!transactionId.equals(other.transactionId)) return false; return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackage.java
1
请完成以下Java代码
public void onQtyCU_Set_Callout(final I_DD_OrderLine ddOrderLine) { // update QtyTU updateQtyPacks(ddOrderLine); } private void updateQtyPacks(final I_DD_OrderLine ddOrderLine) { final IHUPackingAware packingAware = new DDOrderLineHUPackingAware(ddOrderLine); Services.get(IHUPackingAwareBL.class).setQtyTU(packingAware); } private void updateQtyCU(final I_DD_OrderLine ddOrderLine) { final IHUPackingAware packingAware = new DDOrderLineHUPackingAware(ddOrderLine); // if the QtyTU was set to 0 or deleted, do nothing if (packingAware.getQtyTU().signum() <= 0) {
return; } // if the QtyTU was changed but there is no M_HU_PI_Item_Product set, do nothing if (packingAware.getM_HU_PI_Item_Product_ID() <= 0) { return; } // update the QtyCU only if the QtyTU requires it. If the QtyCU is already fine and fits the QtyTU and M_HU_PI_Item_Product, leave it like it is. final QtyTU qtyPacks = QtyTU.ofBigDecimal(packingAware.getQtyTU()); final Quantity qtyCU = Quantitys.of(packingAware.getQty(), UomId.ofRepoId(packingAware.getC_UOM_ID())); Services.get(IHUPackingAwareBL.class).updateQtyIfNeeded(packingAware, qtyPacks.toInt(), qtyCU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\interceptor\DD_OrderLine.java
1
请完成以下Java代码
public final String getWebsocketEndpoint() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); return userNotificationsService.getWebsocketEndpoint(adUserId).getAsString(); } @GetMapping("/all") public JSONNotificationsList getNotifications( @RequestParam(name = "limit", defaultValue = "-1") final int limit // ) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); final UserNotificationsList notifications = userNotificationsService.getNotifications(adUserId, QueryLimit.ofInt(limit)); final JSONOptions jsonOpts = JSONOptions.of(userSession); return JSONNotificationsList.of(notifications, jsonOpts); } @GetMapping("/unreadCount") public int getNotificationsUnreadCount() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); return userNotificationsService.getNotificationsUnreadCount(adUserId); } @PutMapping("/{notificationId}/read") public void markAsRead(@PathVariable("notificationId") final String notificationId) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.markNotificationAsRead(adUserId, notificationId); } @PutMapping("/all/read") public void markAllAsRead() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.markAllNotificationsAsRead(adUserId); } @DeleteMapping("/{notificationId}") public void deleteById(@PathVariable("notificationId") final String notificationId) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.deleteNotification(adUserId, notificationId); }
@DeleteMapping public void deleteByIds(@RequestParam(name = "ids") final String notificationIdsListStr) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); final List<String> notificationIds = Splitter.on(",") .trimResults() .omitEmptyStrings() .splitToList(notificationIdsListStr); if (notificationIds.isEmpty()) { throw new AdempiereException("No IDs provided"); } notificationIds.forEach(notificationId -> userNotificationsService.deleteNotification(adUserId, notificationId)); } @DeleteMapping("/all") public void deleteAll() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.deleteAllNotification(adUserId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\NotificationRestController.java
1
请在Spring Boot框架中完成以下Java代码
public class DebeziumConnectorConfig { /** * Database details. */ @Value("${customer.datasource.host}") private String customerDbHost; @Value("${customer.datasource.database}") private String customerDbName; @Value("${customer.datasource.port}") private String customerDbPort; @Value("${customer.datasource.username}") private String customerDbUsername; @Value("${customer.datasource.password}") private String customerDbPassword; /** * Customer Database Connector Configuration */ @Bean public io.debezium.config.Configuration customerConnector() throws IOException { File offsetStorageTempFile = File.createTempFile("offsets_", ".dat"); File dbHistoryTempFile = File.createTempFile("dbhistory_", ".dat"); return io.debezium.config.Configuration.create() .with("name", "customer-mysql-connector") .with("connector.class", "io.debezium.connector.mysql.MySqlConnector")
.with("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore") .with("offset.storage.file.filename", offsetStorageTempFile.getAbsolutePath()) .with("offset.flush.interval.ms", "60000") .with("database.hostname", customerDbHost) .with("database.port", customerDbPort) .with("database.user", customerDbUsername) .with("database.password", customerDbPassword) .with("database.dbname", customerDbName) .with("database.include.list", customerDbName) .with("include.schema.changes", "false") .with("database.allowPublicKeyRetrieval", "true") .with("database.server.id", "10181") .with("database.server.name", "customer-mysql-db-server") .with("database.history", "io.debezium.relational.history.FileDatabaseHistory") .with("database.history.file.filename", dbHistoryTempFile.getAbsolutePath()) .build(); } }
repos\tutorials-master\libraries-data-db\src\main\java\com\baeldung\libraries\debezium\config\DebeziumConnectorConfig.java
2
请完成以下Java代码
public final class InterceptorOrder { /** * The order value for interceptors that should be executed first. This is equivalent to * {@link Ordered#HIGHEST_PRECEDENCE}. */ public static final int ORDER_FIRST = Ordered.HIGHEST_PRECEDENCE; /** * The order value for global exception handling interceptors. */ public static final int ORDER_GLOBAL_EXCEPTION_HANDLING = 0; /** * The order value for tracing and metrics collecting interceptors. */ public static final int ORDER_TRACING_METRICS = 2500; /** * The order value for interceptors related security exception handling. */ public static final int ORDER_SECURITY_EXCEPTION_HANDLING = 5000; /** * The order value for security interceptors related to authentication. */ public static final int ORDER_SECURITY_AUTHENTICATION = 5100; /** * The order value for security interceptors related to authorization checks. */ public static final int ORDER_SECURITY_AUTHORISATION = 5200; /** * The order value for interceptors that should be executed last. This is equivalent to * {@link Ordered#LOWEST_PRECEDENCE}. This is the default for interceptors without specified priority. */ public static final int ORDER_LAST = Ordered.LOWEST_PRECEDENCE; /** * Creates a new Comparator that takes {@link Order} annotations on bean factory methods into account. * * @param context The application context to get the bean factory annotations form. * @param beanType The type of the bean you wish to sort. * @return A newly created comparator for beans. */ public static Comparator<Object> beanFactoryAwareOrderComparator(final ApplicationContext context, final Class<?> beanType) { final Map<?, String> beans = HashBiMap.create(context.getBeansOfType(beanType)).inverse(); return OrderComparator.INSTANCE.withSourceProvider(bean -> {
// The AnnotationAwareOrderComparator does not have the "withSourceProvider" method // The OrderComparator.withSourceProvider does not properly account for the annotations final Integer priority = AnnotationAwareOrderComparator.INSTANCE.getPriority(bean); if (priority != null) { return (Ordered) () -> priority; } // Consult the bean factory method for annotations final String beanName = beans.get(bean); if (beanName != null) { final Order order = context.findAnnotationOnBean(beanName, Order.class); if (order != null) { return (Ordered) order::value; } } // Nothing present return null; }); } private InterceptorOrder() {} }
repos\grpc-spring-master\grpc-common-spring-boot\src\main\java\net\devh\boot\grpc\common\util\InterceptorOrder.java
1
请完成以下Java代码
public Boolean isBold() { return isBoldAttribute.getValue(this); } public void setBold(boolean isBold) { isBoldAttribute.setValue(this, isBold); } public Boolean isItalic() { return isItalicAttribute.getValue(this); } public void setItalic(boolean isItalic) { isItalicAttribute.setValue(this, isItalic); } public Boolean isUnderline() {
return isUnderlineAttribute.getValue(this); } public void SetUnderline(boolean isUnderline) { isUnderlineAttribute.setValue(this, isUnderline); } public Boolean isStrikeThrough() { return isStrikeTroughAttribute.getValue(this); } public void setStrikeTrough(boolean isStrikeTrough) { isStrikeTroughAttribute.setValue(this, isStrikeTrough); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\dc\FontImpl.java
1
请完成以下Java代码
public void invalidateLayout(Container target) { } // invalidateLayout /*************************************************************************/ /** * Check target components and add components, which don't have no constraints * @param target target */ private void checkComponents (Container target) { int size = target.getComponentCount(); for (int i = 0; i < size; i++) { Component comp = target.getComponent(i); if (!m_data.containsValue(comp)) m_data.put(null, comp); } } // checkComponents /** * Get Number of Rows * @return no pf rows */ public int getRowCount() { return m_data.getMaxRow()+1; } // getRowCount /** * Get Number of Columns * @return no of cols */ public int getColCount() { return m_data.getMaxCol()+1; } // getColCount /** * Set Horizontal Space (top, between rows, button)
* @param spaceH horizontal space (top, between rows, button) */ public void setSpaceH (int spaceH) { m_spaceH = spaceH; } // setSpaceH /** * Get Horizontal Space (top, between rows, button) * @return spaceH horizontal space (top, between rows, button) */ public int getSpaceH() { return m_spaceH; } // getSpaceH /** * Set Vertical Space (left, between columns, right) * @param spaceV vertical space (left, between columns, right) */ public void setSpaceV(int spaceV) { m_spaceV = spaceV; } // setSpaceV /** * Get Vertical Space (left, between columns, right) * @return spaceV vertical space (left, between columns, right) */ public int getSpaceV() { return m_spaceV; } // getSpaceV } // ALayout
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALayout.java
1
请完成以下Java代码
public boolean containsWordWithLabel(String label) { return findFirstWordByLabel(label) != null; } /** * 转换为简单单词列表 * * @return */ public List<Word> toSimpleWordList() { List<Word> wordList = new LinkedList<Word>(); for (IWord word : this.wordList) { if (word instanceof CompoundWord) { wordList.addAll(((CompoundWord) word).innerList); } else { wordList.add((Word) word); } } return wordList; } /** * 获取所有单词构成的数组 * * @return */ public String[] toWordArray() { List<Word> wordList = toSimpleWordList(); String[] wordArray = new String[wordList.size()]; Iterator<Word> iterator = wordList.iterator(); for (int i = 0; i < wordArray.length; i++) { wordArray[i] = iterator.next().value; } return wordArray; } /** * word pos * * @return */ public String[][] toWordTagArray() { List<Word> wordList = toSimpleWordList(); String[][] pair = new String[2][wordList.size()]; Iterator<Word> iterator = wordList.iterator(); for (int i = 0; i < pair[0].length; i++) { Word word = iterator.next(); pair[0][i] = word.value; pair[1][i] = word.label; } return pair; }
/** * word pos ner * * @param tagSet * @return */ public String[][] toWordTagNerArray(NERTagSet tagSet) { List<String[]> tupleList = Utility.convertSentenceToNER(this, tagSet); String[][] result = new String[3][tupleList.size()]; Iterator<String[]> iterator = tupleList.iterator(); for (int i = 0; i < result[0].length; i++) { String[] tuple = iterator.next(); for (int j = 0; j < 3; ++j) { result[j][i] = tuple[j]; } } return result; } public Sentence mergeCompoundWords() { ListIterator<IWord> listIterator = wordList.listIterator(); while (listIterator.hasNext()) { IWord word = listIterator.next(); if (word instanceof CompoundWord) { listIterator.set(new Word(word.getValue(), word.getLabel())); } } return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sentence sentence = (Sentence) o; return toString().equals(sentence.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\Sentence.java
1
请完成以下Java代码
public static double percentage(double current, double total) { return current / total * 100.; } public static double average(double array[]) { double sum = 0; for (int i = 0; i < array.length; i++) sum += array[i]; return sum / array.length; } /** * 使用log-sum-exp技巧来归一化一组对数值 * * @param predictionScores */ public static void normalizeExp(Map<String, Double> predictionScores) { Set<Map.Entry<String, Double>> entrySet = predictionScores.entrySet(); double max = Double.NEGATIVE_INFINITY; for (Map.Entry<String, Double> entry : entrySet) { max = Math.max(max, entry.getValue()); } double sum = 0.0; //通过减去最大值防止浮点数溢出 for (Map.Entry<String, Double> entry : entrySet) { Double value = Math.exp(entry.getValue() - max); entry.setValue(value); sum += value; } if (sum != 0.0) { for (Map.Entry<String, Double> entry : entrySet) { predictionScores.put(entry.getKey(), entry.getValue() / sum); } } } public static void normalizeExp(double[] predictionScores) { double max = Double.NEGATIVE_INFINITY; for (double value : predictionScores) { max = Math.max(max, value); } double sum = 0.0; //通过减去最大值防止浮点数溢出 for (int i = 0; i < predictionScores.length; i++) { predictionScores[i] = Math.exp(predictionScores[i] - max); sum += predictionScores[i]; }
if (sum != 0.0) { for (int i = 0; i < predictionScores.length; i++) { predictionScores[i] /= sum; } } } /** * 从一个词到另一个词的词的花费 * * @param from 前面的词 * @param to 后面的词 * @return 分数 */ public static double calculateWeight(Vertex from, Vertex to) { int fFrom = from.getAttribute().totalFrequency; int fBigram = CoreBiGramTableDictionary.getBiFrequency(from.wordID, to.wordID); int fTo = to.getAttribute().totalFrequency; // logger.info(String.format("%5s frequency:%6d, %s fBigram:%3d, weight:%.2f", from.word, frequency, from.word + "@" + to.word, fBigram, value)); return -Math.log(Predefine.lambda * (Predefine.myu * fBigram / (fFrom + 1) + 1 - Predefine.myu) + (1 - Predefine.lambda) * fTo / Predefine.TOTAL_FREQUENCY); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\MathUtility.java
1
请完成以下Java代码
public void setProductId(Long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductSn() { return productSn; } public void setProductSn(String productSn) { this.productSn = productSn; } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", couponId=").append(couponId); sb.append(", productId=").append(productId); sb.append(", productName=").append(productName); sb.append(", productSn=").append(productSn); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponProductRelation.java
1
请在Spring Boot框架中完成以下Java代码
class SumUpPaymentProcessor implements POSPaymentProcessor { @NonNull private final IErrorManager errorManager = Services.get(IErrorManager.class); @NonNull private final WebuiURLs webuiURLs = WebuiURLs.newInstance(); @NonNull private final SumUpService sumUpService; @Override public POSPaymentProcessorType getType() {return POSPaymentProcessorType.SumUp;} @Override public POSPaymentProcessResponse process(@NonNull final POSPaymentProcessRequest request) { try { final SumUpConfig sumUpConfig = getSumUpConfig(request.getPaymentProcessorConfig()); final SumUpTransaction sumUpTrx = sumUpService.cardReaderCheckout( SumUpCardReaderCheckoutRequest.builder() .configId(sumUpConfig.getId()) .cardReaderId(sumUpConfig.getDefaultCardReaderExternalIdNotNull()) .amount(request.getAmount()) .callbackUrl(getCallbackUrl()) .clientAndOrgId(request.getClientAndOrgId()) .posRef(SumUpUtils.toPOSRef(request.getPosOrderAndPaymentId())) .build() ); return SumUpUtils.extractProcessResponse(sumUpTrx); } catch (final Exception ex) { final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex); return POSPaymentProcessResponse.error( request.getPaymentProcessorConfig(), AdempiereException.extractMessage(metasfreshException), errorManager.createIssue(metasfreshException) ); } } private SumUpConfig getSumUpConfig(@NonNull final POSTerminalPaymentProcessorConfig paymentProcessorConfig) { Check.assumeEquals(paymentProcessorConfig.getType(), POSPaymentProcessorType.SumUp, "payment processor type is SumUp: {}", paymentProcessorConfig);
final SumUpConfigId sumUpConfigId = Check.assumeNotNull(paymentProcessorConfig.getSumUpConfigId(), "sumUpConfigId is set for {}", paymentProcessorConfig); return sumUpService.getConfig(sumUpConfigId); } @Nullable private String getCallbackUrl() { final String appApiUrl = webuiURLs.getAppApiUrl(); if (appApiUrl == null) { return null; } return appApiUrl + SumUp.ENDPOINT_PaymentCheckoutCallback; } @Override public POSPaymentProcessResponse refund(@NonNull final POSRefundRequest request) { final SumUpPOSRef posRef = SumUpUtils.toPOSRef(request.getPosOrderAndPaymentId()); final SumUpTransaction trx = sumUpService.refundTransaction(posRef); return SumUpUtils.extractProcessResponse(trx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\payment_gateway\sumup\SumUpPaymentProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getPayType() { return payType; } public void setPayType(String payType) { this.payType = payType; } public Integer getNumberOfStages() { return numberOfStages; }
public void setNumberOfStages(Integer numberOfStages) { this.numberOfStages = numberOfStages; } @Override public String toString() { return "ScanPayRequestBo{" + "payKey='" + payKey + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", orderPeriod=" + orderPeriod + ", returnUrl='" + returnUrl + '\'' + ", notifyUrl='" + notifyUrl + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + ", numberOfStages=" + numberOfStages + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ScanPayRequestBo.java
2
请完成以下Java代码
public static BaseSearcher getSearcher(char[] charArray) { return new Searcher(charArray); } static class Searcher extends BaseSearcher<CoreDictionary.Attribute> { /** * 分词从何处开始,这是一个状态 */ int begin; private LinkedList<Map.Entry<String, CoreDictionary.Attribute>> entryList; protected Searcher(char[] c) { super(c); entryList = new LinkedList<Map.Entry<String, CoreDictionary.Attribute>>(); } protected Searcher(String text) { super(text); entryList = new LinkedList<Map.Entry<String, CoreDictionary.Attribute>>(); } @Override public Map.Entry<String, CoreDictionary.Attribute> next() { // 保证首次调用找到一个词语 while (entryList.size() == 0 && begin < c.length) { entryList = DEFAULT.trie.commonPrefixSearchWithValue(c, begin); ++begin; } // 之后调用仅在缓存用完的时候调用一次 if (entryList.size() == 0 && begin < c.length) { entryList = DEFAULT.trie.commonPrefixSearchWithValue(c, begin); ++begin; } if (entryList.size() == 0) { return null; } Map.Entry<String, CoreDictionary.Attribute> result = entryList.getFirst(); entryList.removeFirst(); offset = begin - 1; return result; } } /** * 获取词典对应的trie树 * * @return * @deprecated 谨慎操作,有可能废弃此接口 */ public static BinTrie<CoreDictionary.Attribute> getTrie() { return DEFAULT.getTrie(); } /** * 解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构) *
* @param text 文本 * @param processor 处理器 */ public static void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { DEFAULT.parseText(text, processor); } /** * 解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构) * * @param text 文本 * @param processor 处理器 */ public static void parseText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { DEFAULT.parseText(text, processor); } /** * 最长匹配 * * @param text 文本 * @param processor 处理器 */ public static void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor) { DEFAULT.parseLongestText(text, processor); } /** * 热更新(重新加载)<br> * 集群环境(或其他IOAdapter)需要自行删除缓存文件(路径 = HanLP.Config.CustomDictionaryPath[0] + Predefine.BIN_EXT) * * @return 是否加载成功 */ public static boolean reload() { return DEFAULT.reload(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CustomDictionary.java
1
请完成以下Java代码
private List<I_M_HU> splitOutOfPickFromHU(final DDOrderMoveSchedule schedule) { // Atm we always take top level HUs // TODO: implement TU level support if (!HuId.equals(huIdToPick, schedule.getPickFromHUId())) { throw new AdempiereException("HU not matching the scheduled one"); } final I_M_HU pickFromHU = handlingUnitsBL.getById(huIdToPick); return ImmutableList.of(pickFromHU); } private MovementId createPickFromMovement(@NonNull final Set<HuId> huIdsToMove) { final HUMovementGenerateRequest request = DDOrderMovementHelper.prepareMovementGenerateRequest(ddOrder, schedule.getDdOrderLineId()) .movementDate(movementDate) .fromLocatorId(schedule.getPickFromLocatorId()) .toLocatorId(getInTransitLocatorId()) .huIdsToMove(huIdsToMove) .build(); return new HUMovementGenerator(request) .createMovement() .getSingleMovementLineId()
.getMovementId(); } private LocatorId getInTransitLocatorId() { if (inTransitLocatorIdEffective == null) { inTransitLocatorIdEffective = computeInTransitLocatorId(); } return inTransitLocatorIdEffective; } private LocatorId computeInTransitLocatorId() { if (inTransitLocatorId != null) { return inTransitLocatorId; } final WarehouseId warehouseInTransitId = WarehouseId.ofRepoId(ddOrder.getM_Warehouse_ID()); return warehouseBL.getOrCreateDefaultLocatorId(warehouseInTransitId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\pick_from\DDOrderPickFromCommand.java
1
请完成以下Java代码
public Predicate<DocumentLayoutElementDescriptor> documentLayoutElementFilter() { if (_documentLayoutElementFilter == null) { _documentLayoutElementFilter = isShowAdvancedFields() ? FILTER_DocumentLayoutElementDescriptor_ALL : FILTER_DocumentLayoutElementDescriptor_BASIC; } return _documentLayoutElementFilter; } private static final Predicate<DocumentLayoutElementDescriptor> FILTER_DocumentLayoutElementDescriptor_BASIC = new Predicate<DocumentLayoutElementDescriptor>() { @Override public String toString() { return "basic layout elements"; } @Override public boolean test(final DocumentLayoutElementDescriptor layoutElement) { return !layoutElement.isAdvancedField(); } }; private static final Predicate<DocumentLayoutElementDescriptor> FILTER_DocumentLayoutElementDescriptor_ALL = new Predicate<DocumentLayoutElementDescriptor>() {
@Override public String toString() { return "all layout elements"; } @Override public boolean test(final DocumentLayoutElementDescriptor layoutElement) { return true; } }; public String getAdLanguage() { return getJsonOpts().getAdLanguage(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentLayoutOptions.java
1
请完成以下Java代码
public static String getAppPath(ServletContext servletContext) { String applicationPath = (String) servletContext.getAttribute(APP_PATH_ATTR_NAME); if (applicationPath == null) { return ""; } else { return applicationPath; } } /** * Sets an application path into Spring Boot's servlet context. * * @param applicationPath to be set into Spring Boot's servlet context * @param servletContext of Spring Boot the application path should be set into */ public static void setAppPath(String applicationPath, ServletContext servletContext) { servletContext.setAttribute(APP_PATH_ATTR_NAME, applicationPath); } /** * @return whether the web application has already successfully been sent to * the engine as telemetry info or not. */ public static boolean isTelemetryDataSentAlready(String webappName, String engineName, ServletContext servletContext) { return servletContext.getAttribute(buildTelemetrySentAttribute(webappName, engineName)) != null; } /** * Marks the web application as successfully sent to the engine as telemetry * info */ public static void setTelemetryDataSent(String webappName, String engineName, ServletContext servletContext) { servletContext.setAttribute(buildTelemetrySentAttribute(webappName, engineName), true); } protected static String buildTelemetrySentAttribute(String webappName, String engineName) {
return SUCCESSFUL_ET_ATTR_NAME + "." + webappName + "." + engineName; } /** * Sets {@param cacheTimeToLive} in the {@link AuthenticationFilter} to be used on initial login authentication. * See {@link AuthenticationFilter#doFilter(ServletRequest, ServletResponse, FilterChain)} */ public static void setCacheTTLForLogin(long cacheTimeToLive, ServletContext servletContext) { servletContext.setAttribute(AUTH_CACHE_TTL_ATTR_NAME, cacheTimeToLive); } /** * Returns {@code authCacheValidationTime} from servlet context to be used on initial login authentication. * See {@link UserAuthenticationResource#doLogin(String, String, String, String)} */ public static Date getAuthCacheValidationTime(ServletContext servletContext) { Long cacheTimeToLive = (Long) servletContext.getAttribute(AUTH_CACHE_TTL_ATTR_NAME); if (cacheTimeToLive != null) { return new Date(ClockUtil.getCurrentTime().getTime() + cacheTimeToLive); } else { return null; } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\util\ServletContextUtil.java
1
请完成以下Java代码
public boolean hasResponseQtys(final I_C_RfQResponseLine rfqResponseLine) { return retrieveResponseQtysQuery(rfqResponseLine) .create() .anyMatch(); } @Override public I_C_RfQResponseLineQty retrieveResponseQty(final I_C_RfQResponseLine rfqResponseLine, final Date date) { Check.assumeNotNull(date, "date not null"); final Date day = TimeUtil.trunc(date, TimeUtil.TRUNC_DAY); final I_C_RfQResponseLineQty rfqResponseLineQty = retrieveResponseQtysQuery(rfqResponseLine) .addEqualsFilter(I_C_RfQResponseLineQty.COLUMN_DatePromised, day) .create() .firstOnly(I_C_RfQResponseLineQty.class); // optimization if (rfqResponseLineQty != null) { rfqResponseLineQty.setC_RfQResponseLine(rfqResponseLine); } return rfqResponseLineQty; } private IQueryBuilder<I_C_RfQResponseLineQty> retrieveResponseQtysQuery(final I_C_RfQResponseLine responseLine) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_RfQResponseLineQty.class, responseLine) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_RfQResponseLineQty.COLUMN_C_RfQResponseLine_ID, responseLine.getC_RfQResponseLine_ID()) .orderBy() .addColumn(I_C_RfQResponseLineQty.COLUMN_C_RfQResponseLineQty_ID) .endOrderBy(); } @Override public BigDecimal calculateQtyPromised(final I_C_RfQResponseLine rfqResponseLine) { final BigDecimal qtyPromised = retrieveResponseQtysQuery(rfqResponseLine)
.create() .aggregate(I_C_RfQResponseLineQty.COLUMNNAME_QtyPromised, Aggregate.SUM, BigDecimal.class); if(qtyPromised == null) { return BigDecimal.ZERO; } return NumberUtils.stripTrailingDecimalZeros(qtyPromised); } @Override public boolean hasQtyRequiered(final I_C_RfQResponse rfqResponse) { return retrieveResponseLinesQuery(rfqResponse) .addNotEqualsFilter(I_C_RfQResponseLine.COLUMNNAME_QtyRequiered, BigDecimal.ZERO) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqDAO.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LegacyReference legacyReference = (LegacyReference)o; return Objects.equals(this.legacyItemId, legacyReference.legacyItemId) && Objects.equals(this.legacyTransactionId, legacyReference.legacyTransactionId); } @Override public int hashCode() { return Objects.hash(legacyItemId, legacyTransactionId); } @Override public String toString()
{ StringBuilder sb = new StringBuilder(); sb.append("class LegacyReference {\n"); sb.append(" legacyItemId: ").append(toIndentedString(legacyItemId)).append("\n"); sb.append(" legacyTransactionId: ").append(toIndentedString(legacyTransactionId)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LegacyReference.java
2
请完成以下Java代码
public class PaymentsToReconcileView_Reconcile extends PaymentsToReconcileViewBasedProcess { private final IBankStatementPaymentBL bankStatmentPaymentBL = Services.get(IBankStatementPaymentBL.class); @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { return reconcilePayments().checkCanExecute(); } @Override protected String doIt() { reconcilePayments().execute(); // NOTE: usually this would not be needed but it seems frontend has some problems to refresh the left side view invalidateBankStatementReconciliationView();
return MSG_OK; } private ReconcilePaymentsCommand reconcilePayments() { return ReconcilePaymentsCommand.builder() .msgBL(msgBL) .bankStatmentPaymentBL(bankStatmentPaymentBL) // .request(ReconcilePaymentsRequest.builder() .selectedBankStatementLine(getSingleSelectedBankStatementRowOrNull()) .selectedPaymentsToReconcile(getSelectedPaymentToReconcileRows()) .build()) // .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\process\PaymentsToReconcileView_Reconcile.java
1
请完成以下Java代码
public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private Object principal; private Object credentials; protected Builder(TestingAuthenticationToken token) { super(token); this.principal = token.principal; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; }
@Override public B credentials(@Nullable Object credentials) { Assert.notNull(credentials, "credentials cannot be null"); this.credentials = credentials; return (B) this; } @Override public TestingAuthenticationToken build() { return new TestingAuthenticationToken(this); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\TestingAuthenticationToken.java
1
请完成以下Java代码
public Map<String, Map<String, Object>> getFlowElementLocalVariableMap() { return flowElementLocalVariableMap; } public void setFlowElementLocalVariableMap(Map<String, Map<String, Object>> flowElementLocalVariableMap) { this.flowElementLocalVariableMap = flowElementLocalVariableMap; } public void addLocalVariableMap(String activityId, Map<String, Object> localVariables) { this.flowElementLocalVariableMap.put(activityId, localVariables); } public static class FlowElementMoveEntry { protected FlowElement originalFlowElement;
protected FlowElement newFlowElement; public FlowElementMoveEntry(FlowElement originalFlowElement, FlowElement newFlowElement) { this.originalFlowElement = originalFlowElement; this.newFlowElement = newFlowElement; } public FlowElement getOriginalFlowElement() { return originalFlowElement; } public FlowElement getNewFlowElement() { return newFlowElement; } } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\MoveExecutionEntityContainer.java
1
请完成以下Java代码
public void setHighestCpuUsage(Double highestCpuUsage) { this.highestCpuUsage = highestCpuUsage; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; }
public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } @Override public SystemRule toRule() { SystemRule rule = new SystemRule(); rule.setHighestSystemLoad(highestSystemLoad); rule.setAvgRt(avgRt); rule.setMaxThread(maxThread); rule.setQps(qps); rule.setHighestCpuUsage(highestCpuUsage); return rule; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\SystemRuleEntity.java
1
请完成以下Java代码
public class IoBindingImpl extends BaseElementImpl implements IoBinding { protected static AttributeReference<Operation> operationRefAttribute; protected static AttributeReference<DataInput> inputDataRefAttribute; protected static AttributeReference<DataOutput> outputDataRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(IoBinding.class, BPMN_ELEMENT_IO_BINDING) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<IoBinding>() { public IoBinding newInstance(ModelTypeInstanceContext instanceContext) { return new IoBindingImpl(instanceContext); } }); operationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OPERATION_REF) .required() .qNameAttributeReference(Operation.class) .build(); inputDataRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_INPUT_DATA_REF) .required() .idAttributeReference(DataInput.class) .build(); outputDataRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OUTPUT_DATA_REF) .required() .idAttributeReference(DataOutput.class) .build(); typeBuilder.build(); }
public IoBindingImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } public DataInput getInputData() { return inputDataRefAttribute.getReferenceTargetElement(this); } public void setInputData(DataInput inputData) { inputDataRefAttribute.setReferenceTargetElement(this, inputData); } public DataOutput getOutputData() { return outputDataRefAttribute.getReferenceTargetElement(this); } public void setOutputData(DataOutput dataOutput) { outputDataRefAttribute.setReferenceTargetElement(this, dataOutput); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\IoBindingImpl.java
1
请完成以下Java代码
private I_M_MatchPO createMatchPO(final I_C_InvoiceLine iLine, final Timestamp dateTrx, final BigDecimal qty) { final I_M_MatchPO matchPO = newInstance(I_M_MatchPO.class); matchPO.setAD_Org_ID(iLine.getAD_Org_ID()); matchPO.setC_InvoiceLine(iLine); if (iLine.getC_OrderLine_ID() != 0) { matchPO.setC_OrderLine_ID(iLine.getC_OrderLine_ID()); } if (dateTrx != null) { matchPO.setDateTrx(dateTrx); } matchPO.setM_Product_ID(iLine.getM_Product_ID()); matchPO.setM_AttributeSetInstance_ID(iLine.getM_AttributeSetInstance_ID()); matchPO.setQty(qty); matchPO.setProcessed(true); // auto return matchPO; } // MMatchPO private static DocumentPostRequest toDocumentPostRequest(final I_M_MatchPO matchPO) { return DocumentPostRequest.builder() .record(TableRecordReference.of(I_M_MatchPO.Table_Name, matchPO.getM_MatchPO_ID())) .clientId(ClientId.ofRepoId(matchPO.getAD_Client_ID())) .build(); } @Override public void unlink(@NonNull final OrderLineId orderLineId, @NonNull final InvoiceAndLineId invoiceAndLineId) { for (final I_M_MatchPO matchPO : matchPODAO.getByOrderLineAndInvoiceLine(orderLineId, invoiceAndLineId)) { if (matchPO.getM_InOutLine_ID() <= 0) { matchPO.setProcessed(false); InterfaceWrapperHelper.delete(matchPO); } else { matchPO.setC_InvoiceLine_ID(-1); InterfaceWrapperHelper.save(matchPO); } } } @Override public void unlink(@NonNull final InOutId inoutId) { for (final I_M_MatchPO matchPO : matchPODAO.getByReceiptId(inoutId))
{ if (matchPO.getC_InvoiceLine_ID() <= 0) { matchPO.setProcessed(false); InterfaceWrapperHelper.delete(matchPO); } else { matchPO.setM_InOutLine_ID(-1); InterfaceWrapperHelper.save(matchPO); } } } @Override public void unlink(@NonNull final InvoiceId invoiceId) { for (final I_M_MatchPO matchPO : matchPODAO.getByInvoiceId(invoiceId)) { if (matchPO.getM_InOutLine_ID() <= 0) { matchPO.setProcessed(false); InterfaceWrapperHelper.delete(matchPO); } else { matchPO.setC_InvoiceLine_ID(-1); InterfaceWrapperHelper.save(matchPO); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\MatchPOBL.java
1