instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
private void initializeSocketForBroadcasting() throws SocketException { socket = new DatagramSocket(); socket.setBroadcast(true); } private void copyMessageOnBuffer(String msg) { buf = msg.getBytes(); } private void broadcastPacket(InetAddress address) throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); } private int receivePackets() throws IOException { int serversDiscovered = 0;
while (serversDiscovered != expectedServerCount) { receivePacket(); serversDiscovered++; } return serversDiscovered; } private void receivePacket() throws IOException { DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); } public void close() { socket.close(); } }
repos\tutorials-master\core-java-modules\core-java-networking-5\src\main\java\com\baeldung\networking\udp\broadcast\BroadcastingClient.java
1
请完成以下Java代码
public BigDecimal getA_Purchase_Price () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Purchase_Price); if (bd == null) return Env.ZERO; return bd; } /** Set Business Partner . @param C_BPartner_ID Identifies a Business Partner */ public void setC_BPartner_ID (int C_BPartner_ID) { if (C_BPartner_ID < 1) set_Value (COLUMNNAME_C_BPartner_ID, null); else set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID)); } /** Get Business Partner . @return Identifies a Business Partner */ public int getC_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID); if (ii == null)
return 0; return ii.intValue(); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Fin.java
1
请完成以下Java代码
private <T> List<String> appendImports(Stream<T> candidates, Function<T, Collection<String>> mapping) { return candidates.map(mapping).flatMap(Collection::stream).collect(Collectors.toList()); } private String getUnqualifiedName(String name) { if (!name.contains(".")) { return name; } return name.substring(name.lastIndexOf(".") + 1); } private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) { if (name == null || !name.contains(".")) { return false; } String packageName = name.substring(0, name.lastIndexOf('.')); return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName); } static class GroovyFormattingOptions implements FormattingOptions { @Override public String statementSeparator() { return "";
} @Override public CodeBlock arrayOf(CodeBlock... values) { return CodeBlock.of("[ $L ]", CodeBlock.join(Arrays.asList(values), ", ")); } @Override public CodeBlock classReference(ClassName className) { return CodeBlock.of("$T", className); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovySourceCodeWriter.java
1
请完成以下Java代码
public final String toString() { StringBuffer sb = new StringBuffer(); if ( getCodeset() != null ) { if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return (sb.toString()); } else { if (doctype != null) sb.append (doctype.toString()); sb.append (html.toString()); return(sb.toString()); } } /** Override the toString() method so that it prints something meaningful. */ public final String toString(String codeset) { StringBuffer sb = new StringBuffer(); if (doctype != null)
sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return(sb.toString()); } /** Allows the document to be cloned. Doesn't return an instance of document returns instance of html. NOTE: If you have a doctype set, then it will be lost. Feel free to submit a patch to fix this. It isn't trivial. */ public Object clone() { return(html.clone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlDocument.java
1
请在Spring Boot框架中完成以下Java代码
public String getPayType() { return payType; } public void setPayType(String payType) { this.payType = payType; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl; } @Override public String toString() { return "ProgramPayRequestBo{" + "payKey='" + payKey + '\'' + ", openId='" + openId + '\'' + ", productName='" + productName + '\'' + ", orderNo='" + orderNo + '\'' + ", orderPrice=" + orderPrice + ", orderIp='" + orderIp + '\'' + ", orderDate='" + orderDate + '\'' + ", orderTime='" + orderTime + '\'' + ", notifyUrl='" + notifyUrl + '\'' + ", sign='" + sign + '\'' + ", remark='" + remark + '\'' + ", payType='" + payType + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ProgramPayRequestBo.java
2
请完成以下Java代码
public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName can't be null"); this.headerName = headerName; } /** * Sets the cookie path * @param cookiePath The cookie path */ public void setCookiePath(String cookiePath) { this.cookiePath = cookiePath; } private CsrfToken createCsrfToken() { return createCsrfToken(createNewToken());
} private CsrfToken createCsrfToken(String tokenValue) { return new DefaultCsrfToken(this.headerName, this.parameterName, tokenValue); } private String createNewToken() { return UUID.randomUUID().toString(); } private String getRequestContext(ServerHttpRequest request) { String contextPath = request.getPath().contextPath().value(); return StringUtils.hasLength(contextPath) ? contextPath : "/"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CookieServerCsrfTokenRepository.java
1
请完成以下Java代码
public long reset(final CacheInvalidateMultiRequest multiRequest) { final ITrxManager trxManager = Services.get(ITrxManager.class); final ITrx currentTrx = trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.ReturnTrxNone); if (trxManager.isNull(currentTrx)) { async.execute(() -> resetNow(extractTableNames(multiRequest))); } else { final TableNamesToResetCollector collector = currentTrx.getProperty(TRXPROP_TableNamesToInvalidate, trx -> { final TableNamesToResetCollector c = new TableNamesToResetCollector(); trx.getTrxListenerManager() .newEventListener(TrxEventTiming.AFTER_COMMIT) .registerHandlingMethod(innerTrx -> { final Set<String> tableNames = c.toSet(); if (tableNames.isEmpty()) { return; } async.execute(() -> resetNow(tableNames)); }); return c; }); collector.addTableNames(extractTableNames(multiRequest)); } return 1; // not relevant } private Set<String> extractTableNames(final CacheInvalidateMultiRequest multiRequest) { if (multiRequest.isResetAll()) { // not relevant for our lookups return ImmutableSet.of(); } return multiRequest.getRequests() .stream() .filter(request -> !request.isAll()) // not relevant for our lookups .map(CacheInvalidateRequest::getTableNameEffective) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } private void resetNow(final Set<String> tableNames) {
if (tableNames.isEmpty()) { return; } lookupDataSourceFactory.cacheInvalidateOnRecordsChanged(tableNames); } private static final class TableNamesToResetCollector { private final Set<String> tableNames = new HashSet<>(); public Set<String> toSet() { return ImmutableSet.copyOf(tableNames); } public void addTableNames(final Collection<String> tableNamesToAdd) { tableNames.addAll(tableNamesToAdd); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupCacheInvalidationDispatcher.java
1
请完成以下Java代码
public String getName() { return getActionType().getAD_Message(); } @Override public String getIcon() { return null; } @Override public KeyStroke getKeyStroke() { return getActionType().getKeyStroke(); } @Override public boolean isAvailable() { return !NullCopyPasteSupportEditor.isNull(getCopyPasteSupport()); } @Override
public boolean isRunnable() { return getCopyPasteSupport().isCopyPasteActionAllowed(getActionType()); } @Override public boolean isHideWhenNotRunnable() { return false; // just gray it out } @Override public void run() { getCopyPasteSupport().executeCopyPasteAction(getActionType()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CopyPasteContextMenuAction.java
1
请完成以下Java代码
public Builder setC_Activity_ID(final int C_Activity_ID) { setSegmentValue(AcctSegmentType.Activity, C_Activity_ID); return this; } public Builder setSalesOrderId(final int C_OrderSO_ID) { setSegmentValue(AcctSegmentType.SalesOrder, C_OrderSO_ID); return this; } public Builder setUser1_ID(final int user1_ID) { setSegmentValue(AcctSegmentType.UserList1, user1_ID); return this; } public Builder setUser2_ID(final int user2_ID) { setSegmentValue(AcctSegmentType.UserList2, user2_ID); return this; } public Builder setUserElement1_ID(final int userElement1_ID) { setSegmentValue(AcctSegmentType.UserElement1, userElement1_ID); return this; } public Builder setUserElement2_ID(final int userElement2_ID) { setSegmentValue(AcctSegmentType.UserElement2, userElement2_ID); return this; } public Builder setUserElementString1(final String userElementString1) { setSegmentValue(AcctSegmentType.UserElementString1, userElementString1); return this; } public Builder setUserElementString2(final String userElementString2) { setSegmentValue(AcctSegmentType.UserElementString2, userElementString2); return this; } public Builder setUserElementString3(final String userElementString3) { setSegmentValue(AcctSegmentType.UserElementString3, userElementString3); return this; }
public Builder setUserElementString4(final String userElementString4) { setSegmentValue(AcctSegmentType.UserElementString4, userElementString4); return this; } public Builder setUserElementString5(final String userElementString5) { setSegmentValue(AcctSegmentType.UserElementString5, userElementString5); return this; } public Builder setUserElementString6(final String userElementString6) { setSegmentValue(AcctSegmentType.UserElementString6, userElementString6); return this; } public Builder setUserElementString7(final String userElementString7) { setSegmentValue(AcctSegmentType.UserElementString7, userElementString7); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountDimension.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductsAttachFileProcessor implements Processor { @Override public void process(final Exchange exchange) { final PushBOMsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_PUSH_BOMs_CONTEXT, PushBOMsRouteContext.class); if (Check.isBlank(context.getExportDirectoriesBasePath())) { exchange.getIn().setBody(null); return; } final JsonBOM jsonBOM = context.getJsonBOM(); final JsonAttachmentRequest attachmentRequest = getAttachmentRequest(jsonBOM, context.getExportDirectoriesBasePath()); exchange.getIn().setBody(attachmentRequest); } @Nullable private JsonAttachmentRequest getAttachmentRequest( @NonNull final JsonBOM jsonBOM, @NonNull final String basePathForExportDirectories) { final String filePath = jsonBOM.getAttachmentFilePath(); if (Check.isBlank(filePath)) {
return null; } final String bpartnerMetasfreshId = jsonBOM.getBPartnerMetasfreshId(); if (Check.isBlank(bpartnerMetasfreshId)) { throw new RuntimeCamelException("Missing METASFRESHID! ARTNRID=" + jsonBOM.getProductId()); } final JsonExternalReferenceTarget targetBPartner = JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_BPARTNER, bpartnerMetasfreshId); final JsonExternalReferenceTarget targetProduct = JsonExternalReferenceTarget.ofTypeAndId(EXTERNAL_REF_TYPE_PRODUCT, ExternalIdentifierFormat.asExternalIdentifier(jsonBOM.getProductId())); final JsonAttachment attachment = JsonAttachmentUtil.createLocalFileJsonAttachment(basePathForExportDirectories, filePath); return JsonAttachmentRequest.builder() .targets(ImmutableList.of(targetBPartner, targetProduct)) .orgCode(getAuthOrgCode()) .attachment(attachment) .build(); } @NonNull private String getAuthOrgCode() { return ((TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials()).getOrgCode(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\processor\ProductsAttachFileProcessor.java
2
请完成以下Java代码
public void setM_HU_LUTU_Configuration_ID (final int M_HU_LUTU_Configuration_ID) { if (M_HU_LUTU_Configuration_ID < 1) set_Value (COLUMNNAME_M_HU_LUTU_Configuration_ID, null); else set_Value (COLUMNNAME_M_HU_LUTU_Configuration_ID, M_HU_LUTU_Configuration_ID); } @Override public int getM_HU_LUTU_Configuration_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_LUTU_Configuration_ID); } @Override public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID) { if (M_HU_PI_Item_Product_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Item_Product_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID); } @Override public int getM_HU_PI_Item_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_ID); } @Override public de.metas.handlingunits.model.I_M_HU_PI_Version getM_HU_PI_Version() { return get_ValueAsPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class); } @Override public void setM_HU_PI_Version(final de.metas.handlingunits.model.I_M_HU_PI_Version M_HU_PI_Version) { set_ValueFromPO(COLUMNNAME_M_HU_PI_Version_ID, de.metas.handlingunits.model.I_M_HU_PI_Version.class, M_HU_PI_Version); } @Override public void setM_HU_PI_Version_ID (final int M_HU_PI_Version_ID) { if (M_HU_PI_Version_ID < 1) set_Value (COLUMNNAME_M_HU_PI_Version_ID, null); else set_Value (COLUMNNAME_M_HU_PI_Version_ID, M_HU_PI_Version_ID); } @Override public int getM_HU_PI_Version_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_Version_ID); } @Override public void setM_HU_Snapshot_ID (final int M_HU_Snapshot_ID) { if (M_HU_Snapshot_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_Snapshot_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_Snapshot_ID, M_HU_Snapshot_ID); } @Override
public int getM_HU_Snapshot_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_Snapshot_ID); } @Override public void setM_Locator_ID (final int M_Locator_ID) { if (M_Locator_ID < 1) set_Value (COLUMNNAME_M_Locator_ID, null); else set_Value (COLUMNNAME_M_Locator_ID, M_Locator_ID); } @Override public int getM_Locator_ID() { return get_ValueAsInt(COLUMNNAME_M_Locator_ID); } @Override public void setSnapshot_UUID (final java.lang.String Snapshot_UUID) { set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID); } @Override public java.lang.String getSnapshot_UUID() { return get_ValueAsString(COLUMNNAME_Snapshot_UUID); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Snapshot.java
1
请完成以下Java代码
public class PlainEventEnqueuer implements EventEnqueuer { private final EventsQueue eventsQueue = new EventsQueue(); @Override public void enqueueDistributedEvent(final Event event, final Topic topic) { eventsQueue.enqueue(event, topic); } @Override public void enqueueLocalEvent(final Event event, final Topic topic) { eventsQueue.enqueue(event, topic); } private static class EventsQueue { private final LinkedBlockingQueue<ImmutablePair<Event, Topic>> eventsQueue = new LinkedBlockingQueue<>(); private final IEventBusFactory busFactory = Services.get(IEventBusFactory.class); private void enqueue(@NonNull final Event event, @NonNull final Topic topic)
{ eventsQueue.add(ImmutablePair.of(event, topic)); processQueue(); } private synchronized void processQueue() { while (!eventsQueue.isEmpty()) { final ImmutablePair<Event, Topic> eventAndTopic = eventsQueue.poll(); final IEventBus eventBus = busFactory.getEventBus(eventAndTopic.getRight()); eventBus.processEvent(eventAndTopic.getLeft()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\PlainEventEnqueuer.java
1
请完成以下Java代码
public Aggregation retrieveAggregation(@CacheCtx final Properties ctx, @NonNull final AggregationId aggregationId) { // // Load aggregation definition final I_C_Aggregation aggregationDef = InterfaceWrapperHelper.create(ctx, AggregationId.toRepoId(aggregationId), I_C_Aggregation.class, ITrx.TRXNAME_None); if (aggregationDef == null) { throw new AdempiereException("@NotFound@ @C_Aggregation_ID@ (ID=" + aggregationId + ")"); } return new C_Aggregation2AggregationBuilder(this) .setC_Aggregation(aggregationDef) .build(); } @Override public void checkIncludedAggregationCycles(final I_C_AggregationItem aggregationItemDef) { final Map<Integer, I_C_Aggregation> trace = new LinkedHashMap<>(); checkIncludedAggregationCycles(aggregationItemDef, trace); } private final void checkIncludedAggregationCycles(final I_C_AggregationItem aggregationItemDef, final Map<Integer, I_C_Aggregation> trace) { Check.assumeNotNull(aggregationItemDef, "aggregationItemDef not null"); final String itemType = aggregationItemDef.getType(); if (!X_C_AggregationItem.TYPE_IncludedAggregation.equals(itemType)) { return; } final int includedAggregationId = aggregationItemDef.getIncluded_Aggregation_ID(); if (includedAggregationId <= 0)
{ return; } if (trace.containsKey(includedAggregationId)) { throw new AdempiereException("Cycle detected: " + trace.values()); } final I_C_Aggregation includedAggregationDef = aggregationItemDef.getC_Aggregation(); trace.put(includedAggregationId, includedAggregationDef); final List<I_C_AggregationItem> includedAggregationItemsDef = retrieveAllItems(includedAggregationDef); for (final I_C_AggregationItem includedAggregationItemDef : includedAggregationItemsDef) { checkIncludedAggregationCycles(includedAggregationItemDef, trace); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\AggregationDAO.java
1
请完成以下Java代码
public MinMaxDescriptor getFromWarehouseMinMaxDescriptor() {return getDdOrderCandidate().getFromWarehouseMinMaxDescriptor();} @Nullable @JsonIgnore public ResourceId getTargetPlantId() {return getDdOrderCandidate().getTargetPlantId();} @NonNull @JsonIgnore public WarehouseId getTargetWarehouseId() {return getDdOrderCandidate().getTargetWarehouseId();} @NonNull @JsonIgnore public WarehouseId getSourceWarehouseId() {return getDdOrderCandidate().getSourceWarehouseId();} @NonNull @JsonIgnore public ShipperId getShipperId() {return getDdOrderCandidate().getShipperId();} @NonNull @JsonIgnore public SupplyRequiredDescriptor getSupplyRequiredDescriptorNotNull() {return Check.assumeNotNull(getSupplyRequiredDescriptor(), "supplyRequiredDescriptor shall be set for " + this);} @Nullable @JsonIgnore public ProductPlanningId getProductPlanningId() {return getDdOrderCandidate().getProductPlanningId();} @Nullable @JsonIgnore public DistributionNetworkAndLineId getDistributionNetworkAndLineId() {return getDdOrderCandidate().getDistributionNetworkAndLineId();}
@Nullable @JsonIgnore public MaterialDispoGroupId getMaterialDispoGroupId() {return getDdOrderCandidate().getMaterialDispoGroupId();} @Nullable @JsonIgnore public PPOrderRef getForwardPPOrderRef() {return getDdOrderCandidate().getForwardPPOrderRef();} @JsonIgnore public int getExistingDDOrderCandidateId() {return getDdOrderCandidate().getExitingDDOrderCandidateId();} @Nullable public TableRecordReference getSourceTableReference() { return TableRecordReference.ofNullable(I_DD_Order_Candidate.Table_Name,ddOrderCandidate.getExitingDDOrderCandidateId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\AbstractDDOrderCandidateEvent.java
1
请完成以下Java代码
public int addWord(String word) { assert word != null; char[] charArray = word.toCharArray(); Integer id = wordId.get(charArray); if (id == null) { id = wordId.size(); wordId.put(charArray, id); idWord.add(word); assert idWord.size() == wordId.size(); } return id; } public Integer getId(String word) { return wordId.get(word); } public String getWord(int id) { assert 0 <= id; assert id <= idWord.size(); return idWord.get(id); } public int size()
{ return idWord.size(); } public String[] getWordIdArray() { String[] wordIdArray = new String[idWord.size()]; if (idWord.isEmpty()) return wordIdArray; int p = -1; Iterator<String> iterator = idWord.iterator(); while (iterator.hasNext()) { wordIdArray[++p] = iterator.next(); } return wordIdArray; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\Lexicon.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Arrays.asList(NAME_KEY); } @Override public GatewayFilter apply(NameConfig config) { // AbstractChangeRequestUriGatewayFilterFactory.apply() returns // OrderedGatewayFilter OrderedGatewayFilter gatewayFilter = (OrderedGatewayFilter) super.apply(config); return new OrderedGatewayFilter(gatewayFilter, gatewayFilter.getOrder()) { @Override public String toString() { String name = Objects.requireNonNull(config.getName(), "name must not be null"); return filterToStringCreator(RequestHeaderToRequestUriGatewayFilterFactory.this).append("name", name) .toString(); } }; }
@Override protected Optional<URI> determineRequestUri(ServerWebExchange exchange, NameConfig config) { String name = Objects.requireNonNull(config.getName(), "name must not be null"); String requestUrl = exchange.getRequest().getHeaders().getFirst(name); return Optional.ofNullable(requestUrl).map(url -> { try { URI uri = URI.create(url); uri.toURL(); // validate url return uri; } catch (IllegalArgumentException | MalformedURLException e) { log.info("Request url is invalid : url={}, error={}", requestUrl, e.getMessage()); return null; } }); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestHeaderToRequestUriGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public Recipient save(String accountName, Recipient recipient) { recipient.setAccountName(accountName); recipient.getScheduledNotifications().values() .forEach(settings -> { if (settings.getLastNotified() == null) { settings.setLastNotified(new Date()); } }); repository.save(recipient); log.info("recipient {} settings has been updated", recipient); return recipient; } /** * {@inheritDoc} */ @Override
public List<Recipient> findReadyToNotify(NotificationType type) { switch (type) { case BACKUP: return repository.findReadyForBackup(); case REMIND: return repository.findReadyForRemind(); default: throw new IllegalArgumentException(); } } /** * {@inheritDoc} */ @Override public void markNotified(NotificationType type, Recipient recipient) { recipient.getScheduledNotifications().get(type).setLastNotified(new Date()); repository.save(recipient); } }
repos\piggymetrics-master\notification-service\src\main\java\com\piggymetrics\notification\service\RecipientServiceImpl.java
2
请完成以下Java代码
protected Integer getVersion(CmmnActivityExecution execution) { CmmnExecution caseExecution = (CmmnExecution) execution; return getCallableElement().getVersion(caseExecution); } protected String getDeploymentId(CmmnActivityExecution execution) { return getCallableElement().getDeploymentId(); } protected CallableElementBinding getBinding() { return getCallableElement().getBinding(); } protected boolean isLatestBinding() { return getCallableElement().isLatestBinding();
} protected boolean isDeploymentBinding() { return getCallableElement().isDeploymentBinding(); } protected boolean isVersionBinding() { return getCallableElement().isVersionBinding(); } protected boolean isVersionTagBinding() { return getCallableElement().isVersionTagBinding(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\CallingTaskActivityBehavior.java
1
请完成以下Java代码
public void run(final String localTrxName) throws Exception { final PlainContextAware localCtx = PlainContextAware.newWithTrxName(ctx.getCtx(), localTrxName); final TableRecordReference reference = TableRecordReference.of(tableName, (int)ids[0]); final IDLMAware model = reference.getModel(localCtx, IDLMAware.class); if (model == null) { logger.info("Unable to load record for reference={}; returning false.", reference); return; } if (model.getDLM_Level() == IMigratorService.DLM_Level_LIVE) { logger.info("The record could be loaded, but already had DLM_Level={}; returning false; reference={}; ", IMigratorService.DLM_Level_LIVE, reference); return; } logger.info("Setting DLM_Level to {} for {}", IMigratorService.DLM_Level_LIVE, reference);
model.setDLM_Level(IMigratorService.DLM_Level_LIVE); InterfaceWrapperHelper.save(model); unArchiveWorked.setValue(true); } }); return unArchiveWorked.getValue(); } catch (final Exception e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\po\UnArchiveRecordHandler.java
1
请完成以下Java代码
public BBANCodeEntryType getCodeType() { return codeType; } public void setCodeType(BBANCodeEntryType codeType) { this.codeType = codeType; } /** * Basic Bank Account Number Entry Types. */ public enum BBANCodeEntryType { bank_code, branch_code,
account_number, national_check_digit, account_type, owener_account_type, seqNo } public enum EntryCharacterType { n, // Digits (numeric characters 0 to 9 only) a, // Upper case letters (alphabetic characters A-Z only) c // upper and lower case alphanumeric characters (A-Z, a-z and 0-9) } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\wrapper\BBANStructureEntry.java
1
请完成以下Java代码
protected void writePlanItemDefinitionSpecificAttributes(Stage stage, XMLStreamWriter xtw) throws Exception { super.writePlanItemDefinitionSpecificAttributes(stage, xtw); if (StringUtils.isNotEmpty(stage.getFormKey())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_KEY, stage.getFormKey()); } if (!stage.isSameDeployment()) { // default is true xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_SAME_DEPLOYMENT, "false"); } if (StringUtils.isNotEmpty(stage.getValidateFormFields())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FIELD_VALIDATION, stage.getValidateFormFields()); } if (stage.isAutoComplete()) { xtw.writeAttribute(ATTRIBUTE_IS_AUTO_COMPLETE, Boolean.toString(stage.isAutoComplete())); } if (StringUtils.isNotEmpty(stage.getAutoCompleteCondition())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_AUTO_COMPLETE_CONDITION, stage.getAutoCompleteCondition()); } if (stage.getDisplayOrder() != null) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_DISPLAY_ORDER, String.valueOf(stage.getDisplayOrder())); } if (StringUtils.isNotEmpty(stage.getIncludeInStageOverview()) && !"true".equalsIgnoreCase(stage.getIncludeInStageOverview())) { // if it's missing, it's true by default xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_INCLUDE_IN_STAGE_OVERVIEW, stage.getIncludeInStageOverview()); } if (StringUtils.isNotEmpty(stage.getBusinessStatus())) { xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_BUSINESS_STATUS, stage.getBusinessStatus()); } }
@Override protected void writePlanItemDefinitionBody(CmmnModel model, Stage stage, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception { super.writePlanItemDefinitionBody(model, stage, xtw, options); for (PlanItem planItem : stage.getPlanItems()) { PlanItemExport.writePlanItem(model, planItem, xtw); } for (Sentry sentry : stage.getSentries()) { SentryExport.writeSentry(model, sentry, xtw); } for (PlanItemDefinition planItemDefinition : stage.getPlanItemDefinitions()) { PlanItemDefinitionExport.writePlanItemDefinition(model, planItemDefinition, xtw, options); } if (stage.isPlanModel() && stage.getExitCriteria() != null && !stage.getExitCriteria().isEmpty()) { CriteriaExport.writeCriteriaElements(ELEMENT_EXIT_CRITERION, stage.getExitCriteria(), xtw); } } }
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\StageExport.java
1
请完成以下Java代码
public class X_T_BoilerPlate_Spool extends org.compiere.model.PO implements I_T_BoilerPlate_Spool, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = 317800812L; /** Standard Constructor */ public X_T_BoilerPlate_Spool (Properties ctx, int T_BoilerPlate_Spool_ID, String trxName) { super (ctx, T_BoilerPlate_Spool_ID, trxName); /** if (T_BoilerPlate_Spool_ID == 0) { setAD_PInstance_ID (0); setMsgText (null); setSeqNo (0); // 10 } */ } /** Load Constructor */ public X_T_BoilerPlate_Spool (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public String toString() { StringBuffer sb = new StringBuffer ("X_T_BoilerPlate_Spool[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Process Instance. @param AD_PInstance_ID Instance of the process */ @Override public void setAD_PInstance_ID (int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_PInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_PInstance_ID, Integer.valueOf(AD_PInstance_ID)); }
/** Get Process Instance. @return Instance of the process */ @Override public int getAD_PInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_PInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Message Text. @param MsgText Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_T_BoilerPlate_Spool.java
1
请完成以下Java代码
private void fillProcessDefinitionData(HistoricIdentityLinkLogEventEntity event, IdentityLink identityLink) { String processDefinitionId = identityLink.getProcessDefId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(identityLink.getProcessDefId()); } } private void fillProcessDefinitionData(HistoryEvent event, ExecutionEntity execution) { String processDefinitionId = execution.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(execution.getProcessDefinitionId()); event.setProcessDefinitionKey(execution.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoricIncidentEventEntity event, Incident incident) { String processDefinitionId = incident.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(incident.getProcessDefinitionId()); } } private void fillProcessDefinitionData(HistoryEvent event, UserOperationLogContextEntry userOperationLogContextEntry) {
String processDefinitionId = userOperationLogContextEntry.getProcessDefinitionId(); if (processDefinitionId != null) { fillProcessDefinitionData(event, processDefinitionId); } else { event.setProcessDefinitionId(userOperationLogContextEntry.getProcessDefinitionId()); event.setProcessDefinitionKey(userOperationLogContextEntry.getProcessDefinitionKey()); } } private void fillProcessDefinitionData(HistoryEvent event, String processDefinitionId) { ProcessDefinitionEntity entity = this.getProcessDefinitionEntity(processDefinitionId); if (entity != null) { event.setProcessDefinitionId(entity.getId()); event.setProcessDefinitionKey(entity.getKey()); event.setProcessDefinitionVersion(entity.getVersion()); event.setProcessDefinitionName(entity.getName()); } } protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) { DbEntityManager dbEntityManager = (Context.getCommandContext() != null) ? Context.getCommandContext().getDbEntityManager() : null; if (dbEntityManager != null) { return dbEntityManager .selectById(ProcessDefinitionEntity.class, processDefinitionId); } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultHistoryEventProducer.java
1
请完成以下Java代码
private int getFixedWidth(final TableColumn column) { if (tableColumnFixedWidthCallback == null) { return -1; } return tableColumnFixedWidthCallback.getWidth(column); } /** * Class used to store column attributes when the column it is hidden. We need those informations to restore the column in case it is unhide. */ private final class ColumnAttributes { protected TableCellEditor cellEditor; protected TableCellRenderer cellRenderer; // protected Object headerValue; protected int minWidth; protected int maxWidth; protected int preferredWidth; } @Override public Object getModelValueAt(int rowIndexModel, int columnIndexModel) { return getModel().getValueAt(rowIndexModel, columnIndexModel); } private ITableColorProvider colorProvider = new DefaultTableColorProvider(); @Override public void setColorProvider(final ITableColorProvider colorProvider) { Check.assumeNotNull(colorProvider, "colorProvider not null"); this.colorProvider = colorProvider; } @Override public ITableColorProvider getColorProvider() { return colorProvider; } @Override public void setModel(final TableModel dataModel) { super.setModel(dataModel); if (modelRowSorter == null)
{ // i.e. we are in JTable constructor and modelRowSorter was not yet set // => do nothing } else if (!modelRowSorter.isEnabled()) { setupViewRowSorter(); } } private final void setupViewRowSorter() { final TableModel model = getModel(); viewRowSorter.setModel(model); if (modelRowSorter != null) { viewRowSorter.setSortKeys(modelRowSorter.getSortKeys()); } setRowSorter(viewRowSorter); viewRowSorter.sort(); } } // CTable
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTable.java
1
请完成以下Java代码
public Date getTokenDate() { return tokenDate; } public Date getTokenDateBefore() { return tokenDateBefore; } public Date getTokenDateAfter() { return tokenDateAfter; } public String getIpAddress() { return ipAddress; } public String getIpAddressLike() { return ipAddressLike; } public String getUserAgent() { return userAgent; } public String getUserAgentLike() { return userAgentLike; }
public String getUserId() { return userId; } public String getUserIdLike() { return userIdLike; } public String getTokenData() { return tokenData; } public String getTokenDataLike() { return tokenDataLike; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\TokenQueryImpl.java
1
请完成以下Java代码
public void deleteNotificationTemplateById(TenantId tenantId, NotificationTemplateId id) { deleteEntity(tenantId, id, false); } @Override public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { if (!force) { if (notificationRequestDao.existsByTenantIdAndStatusAndTemplateId(tenantId, NotificationRequestStatus.SCHEDULED, (NotificationTemplateId) id)) { throw new IllegalArgumentException("Notification template is referenced by scheduled notification request"); } if (tenantId.isSysTenantId()) { NotificationTemplate notificationTemplate = findNotificationTemplateById(tenantId, (NotificationTemplateId) id); if (notificationTemplate.getNotificationType().isSystem()) { throw new IllegalArgumentException("System notification template cannot be deleted"); } } } try { notificationTemplateDao.removeById(tenantId, id.getId()); } catch (Exception e) { checkConstraintViolation(e, Map.of( "fk_notification_rule_template_id", "Notification template is referenced by notification rule" )); throw e; } eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build()); }
@Override public void deleteNotificationTemplatesByTenantId(TenantId tenantId) { notificationTemplateDao.removeByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) { deleteNotificationTemplatesByTenantId(tenantId); } @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findNotificationTemplateById(tenantId, new NotificationTemplateId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(notificationTemplateDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_TEMPLATE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationTemplateService.java
1
请完成以下Java代码
public void setRetryAfterDays (java.math.BigDecimal RetryAfterDays) { set_Value (COLUMNNAME_RetryAfterDays, RetryAfterDays); } /** Get Creditpass-Prüfung wiederholen . @return Creditpass-Prüfung wiederholen */ @Override public java.math.BigDecimal getRetryAfterDays () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RetryAfterDays); if (bd == null) return BigDecimal.ZERO; return bd; } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override
public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_Config.java
1
请完成以下Java代码
public class X_CM_AccessListBPGroup extends PO implements I_CM_AccessListBPGroup, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_CM_AccessListBPGroup (Properties ctx, int CM_AccessListBPGroup_ID, String trxName) { super (ctx, CM_AccessListBPGroup_ID, trxName); /** if (CM_AccessListBPGroup_ID == 0) { setC_BP_Group_ID (0); setCM_AccessProfile_ID (0); } */ } /** Load Constructor */ public X_CM_AccessListBPGroup (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_CM_AccessListBPGroup[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_BP_Group getC_BP_Group() throws RuntimeException { return (I_C_BP_Group)MTable.get(getCtx(), I_C_BP_Group.Table_Name) .getPO(getC_BP_Group_ID(), get_TrxName()); }
/** Set Business Partner Group. @param C_BP_Group_ID Business Partner Group */ public void setC_BP_Group_ID (int C_BP_Group_ID) { if (C_BP_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BP_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BP_Group_ID, Integer.valueOf(C_BP_Group_ID)); } /** Get Business Partner Group. @return Business Partner Group */ public int getC_BP_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_Group_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile */ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_AccessListBPGroup.java
1
请在Spring Boot框架中完成以下Java代码
public class PaymentConditionsExtensionType { @XmlElement(name = "DiscountDuration") protected Object discountDuration; @XmlElement(name = "PaymentCondition") protected String paymentCondition; @XmlElement(name = "PaymentMeans") protected String paymentMeans; /** * Gets the value of the discountDuration property. * * @return * possible object is * {@link Object } * */ public Object getDiscountDuration() { return discountDuration; } /** * Sets the value of the discountDuration property. * * @param value * allowed object is * {@link Object } * */ public void setDiscountDuration(Object value) { this.discountDuration = value; } /** * Contitions which apply for the payment. Please use EDIFACT code list values. (PAI 4439) * * @return * possible object is * {@link String } * */ public String getPaymentCondition() { return paymentCondition; } /** * Sets the value of the paymentCondition property. * * @param value * allowed object is
* {@link String } * */ public void setPaymentCondition(String value) { this.paymentCondition = value; } /** * Payment means coded. Please use EDIFACT code list values. (PAI 4461) * * @return * possible object is * {@link String } * */ public String getPaymentMeans() { return paymentMeans; } /** * Sets the value of the paymentMeans property. * * @param value * allowed object is * {@link String } * */ public void setPaymentMeans(String value) { this.paymentMeans = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PaymentConditionsExtensionType.java
2
请完成以下Java代码
public Map<String, String> getContext() { userSession.assertLoggedIn(); final LinkedHashMap<String, String> map = new LinkedHashMap<>(); final Properties ctx = Env.getCtx(); final ArrayList<String> keys = new ArrayList<>(ctx.stringPropertyNames()); Collections.sort(keys); for (final String key : keys) { final String value = ctx.getProperty(key); map.put(key, value); } return map; } @GetMapping("/stressTest/massCacheInvalidation") public void stressTest_massCacheInvalidation( @RequestParam(name = "tableName") @NonNull final String tableName, @RequestParam(name = "eventsCount", defaultValue = "1000") final int eventsCount, @RequestParam(name = "batchSize", defaultValue = "10") final int batchSize) { userSession.assertLoggedIn(); Check.assumeGreaterThanZero(eventsCount, "eventsCount"); Check.assumeGreaterThanZero(batchSize, "batchSize"); final CacheMgt cacheMgt = CacheMgt.get(); final int tableSize = DB.getSQLValueEx(ITrx.TRXNAME_None, "SELECT COUNT(1) FROM " + tableName); if (tableSize <= 0) { throw new AdempiereException("Table " + tableName + " is empty"); } if (tableSize < batchSize) { throw new AdempiereException("Table size(" + tableSize + ") shall be bigger than batch size(" + batchSize + ")"); } int countEventsGenerated = 0; final ArrayList<CacheInvalidateRequest> buffer = new ArrayList<>(batchSize); while (countEventsGenerated <= eventsCount) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement("SELECT " + tableName + "_ID FROM " + tableName + " ORDER BY " + tableName + "_ID", ITrx.TRXNAME_None); rs = pstmt.executeQuery(); while (rs.next()) { if (buffer.size() >= batchSize) { final Stopwatch stopwatch = Stopwatch.createStarted(); cacheMgt.reset(CacheInvalidateMultiRequest.of(buffer)); stopwatch.stop();
// logger.info("Sent a CacheInvalidateMultiRequest of {} events. So far we sent {} of {}. It took {}.", // buffer.size(), countEventsGenerated, eventsCount, stopwatch); buffer.clear(); } final int recordId = rs.getInt(1); buffer.add(CacheInvalidateRequest.rootRecord(tableName, recordId)); countEventsGenerated++; } } catch (final SQLException ex) { throw new DBException(ex); } finally { DB.close(rs, pstmt); } } if (buffer.size() >= batchSize) { cacheMgt.reset(CacheInvalidateMultiRequest.of(buffer)); buffer.clear(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\debug\DebugRestController.java
1
请在Spring Boot框架中完成以下Java代码
public Result save(@RequestBody Article article, @TokenToUser AdminUser loginUser) { if (article.getAddName()==null){ return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "作者不能为空!"); } if (loginUser == null) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!"); } if (articleService.save(article) > 0) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("添加失败"); } } /** * 修改 */ @RequestMapping(value = "/update", method = RequestMethod.PUT) public Result update(@RequestBody Article article, @TokenToUser AdminUser loginUser) { if (loginUser == null) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!"); } if (articleService.update(article) > 0) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("修改失败");
} } /** * 删除 */ @RequestMapping(value = "/delete", method = RequestMethod.DELETE) public Result delete(@RequestBody Integer[] ids, @TokenToUser AdminUser loginUser) { if (loginUser == null) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_NOT_LOGIN, "未登录!"); } if (ids.length < 1) { return ResultGenerator.genErrorResult(Constants.RESULT_CODE_PARAM_ERROR, "参数异常!"); } if (articleService.deleteBatch(ids) > 0) { return ResultGenerator.genSuccessResult(); } else { return ResultGenerator.genFailResult("删除失败"); } } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\controller\ArticleController.java
2
请完成以下Java代码
public class PersonBuilder { private String jsonString; private SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); public PersonBuilder(String jsonString) { this.jsonString = jsonString; } public Person build() throws IOException, ParseException { JsonReader reader = Json.createReader(new StringReader(jsonString)); JsonObject jsonObject = reader.readObject(); Person person = new Person(); person.setFirstName(jsonObject.getString("firstName"));
person.setLastName(jsonObject.getString("lastName")); person.setBirthdate(dateFormat.parse(jsonObject.getString("birthdate"))); JsonArray emailsJson = jsonObject.getJsonArray("emails"); List<String> emails = emailsJson.getValuesAs(JsonString.class).stream() .map(JsonString::getString) .collect(Collectors.toList()); person.setEmails(emails); return person; } }
repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\json\PersonBuilder.java
1
请完成以下Java代码
public class ReverseDraftIssues { private final transient IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); private final transient IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class); private final transient IHUPPOrderQtyDAO huPPOrderQtyDAO = Services.get(IHUPPOrderQtyDAO.class); private final transient IPPOrderProductAttributeDAO ppOrderProductAttributeDAO = Services.get(IPPOrderProductAttributeDAO.class); private final transient IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); private final transient SourceHUsService sourceHuService = SourceHUsService.get(); public void reverseDraftIssue(@NonNull final I_PP_Order_Qty candidate) { if (candidate.isProcessed()) { throw new HUException("Cannot reverse candidate because it's already processed: " + candidate); } final I_M_HU huToIssue = candidate.getM_HU(); final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(candidate); final IHUContext huContext = handlingUnitsBL.createMutableHUContext(contextProvider); huStatusBL.setHUStatus(huContext, huToIssue, X_M_HU.HUSTATUS_Active);
handlingUnitsDAO.saveHU(huToIssue); // Delete PP_Order_ProductAttributes for issue candidate's HU ppOrderProductAttributeDAO.deleteForHU(candidate.getPP_Order_ID(), huToIssue.getM_HU_ID()); // // Delete the candidate huPPOrderQtyDAO.delete(candidate); // Make sure the HU is marked as source final HuId huId = HuId.ofRepoId(huToIssue.getM_HU_ID()); if (!SourceHUsService.get().isHuOrAnyParentSourceHu(huId)) sourceHuService.addSourceHuMarker(huId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\hu_pporder_issue_producer\ReverseDraftIssues.java
1
请在Spring Boot框架中完成以下Java代码
public String getContent() { return content; } public void setContent(String content) { this.content = content; } public UserEntity getCompanyEntity() { return companyEntity; } public void setCompanyEntity(UserEntity companyEntity) { this.companyEntity = companyEntity; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; } @Override public String toString() { return "ProductEntity{" +
"id='" + id + '\'' + ", prodName='" + prodName + '\'' + ", marketPrice='" + marketPrice + '\'' + ", shopPrice='" + shopPrice + '\'' + ", stock=" + stock + ", sales=" + sales + ", weight='" + weight + '\'' + ", topCateEntity=" + topCateEntity + ", subCategEntity=" + subCategEntity + ", brandEntity=" + brandEntity + ", prodStateEnum=" + prodStateEnum + ", prodImageEntityList=" + prodImageEntityList + ", content='" + content + '\'' + ", companyEntity=" + companyEntity + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java
2
请在Spring Boot框架中完成以下Java代码
public void updateLinesOnSchemaChanged(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { final int phonecallSchemaTableId = getTableId(I_C_Phonecall_Schema.class); final PhonecallSchemaId phonecallSchemaId = phonecallSchemaVersionId.getPhonecallSchemaId(); final List<I_C_Phonecall_Schema_Version_Line> linesWithDifferentSchema = retrieveLinesWithDifferentSchemas(phonecallSchemaVersionId); final ImmutableSet<Integer> schemasToInvalidate = linesWithDifferentSchema.stream() .map(line -> line.getC_Phonecall_Schema_ID()) .collect(ImmutableSet.toImmutableSet()); for (final I_C_Phonecall_Schema_Version_Line line : linesWithDifferentSchema) { line.setC_Phonecall_Schema_ID(phonecallSchemaId.getRepoId()); saveRecord(line); } schemasToInvalidate.stream() .forEach(schemaId -> schemas.resetForRecordId(TableRecordReference.of(phonecallSchemaTableId, schemaId))); schemas.resetForRecordId(TableRecordReference.of(phonecallSchemaTableId, phonecallSchemaId.getRepoId())); } private List<I_C_Phonecall_Schema_Version_Line> retrieveLinesWithDifferentSchemas(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Phonecall_Schema_Version_Line.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Phonecall_Schema_Version_Line.COLUMNNAME_C_Phonecall_Schema_Version_ID, phonecallSchemaVersionId) .addNotEqualsFilter(I_C_Phonecall_Schema_Version_Line.COLUMNNAME_C_Phonecall_Schema_ID, phonecallSchemaVersionId.getPhonecallSchemaId()) .create() .list();
} public void updateSchedulesOnSchemaChanged(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { final PhonecallSchemaId phonecallSchemaId = phonecallSchemaVersionId.getPhonecallSchemaId(); final List<I_C_Phonecall_Schedule> schedulesWithDifferentSchema = retrieveSchedulesWithDifferentSchemas(phonecallSchemaVersionId); for (final I_C_Phonecall_Schedule schedule : schedulesWithDifferentSchema) { schedule.setC_Phonecall_Schema_ID(phonecallSchemaId.getRepoId()); saveRecord(schedule); } } private List<I_C_Phonecall_Schedule> retrieveSchedulesWithDifferentSchemas(@NonNull final PhonecallSchemaVersionId phonecallSchemaVersionId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_Phonecall_Schedule.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Phonecall_Schedule.COLUMNNAME_C_Phonecall_Schema_Version_ID, phonecallSchemaVersionId) .addNotEqualsFilter(I_C_Phonecall_Schedule.COLUMNNAME_C_Phonecall_Schema_ID, phonecallSchemaVersionId.getPhonecallSchemaId()) .create() .list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\service\PhonecallSchemaRepository.java
2
请完成以下Java代码
public void updateCurrencyRate(final I_GL_Journal glJournal) { // // Extract data from source Journal final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID()); if (currencyId == null) { // not set yet return; } final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID()); final Instant dateAcct = glJournal.getDateAcct() != null ? glJournal.getDateAcct().toInstant() : SystemTime.asInstant(); final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID()); final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID()); final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(glJournal.getC_AcctSchema_ID()); final AcctSchema acctSchema = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId); // // Calculate currency rate final BigDecimal currencyRate; if (acctSchema != null) { currencyRate = Services.get(ICurrencyBL.class).getCurrencyRateIfExists( currencyId, acctSchema.getCurrencyId(),
dateAcct, conversionTypeId, adClientId, adOrgId) .map(CurrencyRate::getConversionRate) .orElse(BigDecimal.ZERO); } else { currencyRate = BigDecimal.ONE; } // glJournal.setCurrencyRate(currencyRate); } // Old/missing callouts // "GL_Journal";"C_Period_ID";"org.compiere.model.CalloutGLJournal.period" // "GL_Journal";"DateAcct";"org.compiere.model.CalloutGLJournal.period" }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_Journal.java
1
请在Spring Boot框架中完成以下Java代码
public Builder authnRequestsSigned(Boolean authnRequestsSigned) { this.authnRequestsSigned = authnRequestsSigned; return this; } /** * Apply this {@link Consumer} to further configure the Asserting Party metadata * @param assertingPartyMetadata The {@link Consumer} to apply * @return the {@link Builder} for further configuration * @since 6.4 */ public Builder assertingPartyMetadata(Consumer<AssertingPartyMetadata.Builder<?>> assertingPartyMetadata) { assertingPartyMetadata.accept(this.assertingPartyMetadataBuilder); return this; } /** * Constructs a RelyingPartyRegistration object based on the builder * configurations * @return a RelyingPartyRegistration instance */ public RelyingPartyRegistration build() { if (this.singleLogoutServiceResponseLocation == null) { this.singleLogoutServiceResponseLocation = this.singleLogoutServiceLocation; }
if (this.singleLogoutServiceBindings.isEmpty()) { this.singleLogoutServiceBindings.add(Saml2MessageBinding.POST); } AssertingPartyMetadata party = this.assertingPartyMetadataBuilder.build(); return new RelyingPartyRegistration(this.registrationId, this.entityId, this.assertionConsumerServiceLocation, this.assertionConsumerServiceBinding, this.singleLogoutServiceLocation, this.singleLogoutServiceResponseLocation, this.singleLogoutServiceBindings, party, this.nameIdFormat, this.authnRequestsSigned, this.decryptionX509Credentials, this.signingX509Credentials); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\RelyingPartyRegistration.java
2
请在Spring Boot框架中完成以下Java代码
public static class Remoteip { /** * Internal proxies that are to be trusted. Can be set as a comma separate list of * CIDR or as a regular expression. */ private String internalProxies = "192.168.0.0/16, 172.16.0.0/12, 169.254.0.0/16, fc00::/7, " + "10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, fe80::/10, ::1/128"; /** * Header that holds the incoming protocol, usually named "X-Forwarded-Proto". */ private @Nullable String protocolHeader; /** * Value of the protocol header indicating whether the incoming request uses SSL. */ private String protocolHeaderHttpsValue = "https"; /** * Name of the HTTP header from which the remote host is extracted. */ private String hostHeader = "X-Forwarded-Host"; /** * Name of the HTTP header used to override the original port value. */ private String portHeader = "X-Forwarded-Port"; /** * Name of the HTTP header from which the remote IP is extracted. For instance, * 'X-FORWARDED-FOR'. */ private @Nullable String remoteIpHeader; /** * Regular expression defining proxies that are trusted when they appear in the * "remote-ip-header" header. */ private @Nullable String trustedProxies; public String getInternalProxies() { return this.internalProxies; } public void setInternalProxies(String internalProxies) { this.internalProxies = internalProxies; } public @Nullable String getProtocolHeader() { return this.protocolHeader; } public void setProtocolHeader(@Nullable String protocolHeader) { this.protocolHeader = protocolHeader; } public String getProtocolHeaderHttpsValue() { return this.protocolHeaderHttpsValue; }
public String getHostHeader() { return this.hostHeader; } public void setHostHeader(String hostHeader) { this.hostHeader = hostHeader; } public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) { this.protocolHeaderHttpsValue = protocolHeaderHttpsValue; } public String getPortHeader() { return this.portHeader; } public void setPortHeader(String portHeader) { this.portHeader = portHeader; } public @Nullable String getRemoteIpHeader() { return this.remoteIpHeader; } public void setRemoteIpHeader(@Nullable String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } public @Nullable String getTrustedProxies() { return this.trustedProxies; } public void setTrustedProxies(@Nullable String trustedProxies) { this.trustedProxies = trustedProxies; } } /** * When to use APR. */ public enum UseApr { /** * Always use APR and fail if it's not available. */ ALWAYS, /** * Use APR if it is available. */ WHEN_AVAILABLE, /** * Never use APR. */ NEVER } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\TomcatServerProperties.java
2
请完成以下Java代码
protected void process(String deviceName, Consumer<T> onSuccess, Consumer<Throwable> onFailure) { ListenableFuture<T> deviceCtxFuture = onDeviceConnect(deviceName, DEFAULT_DEVICE_TYPE); process(deviceCtxFuture, onSuccess, onFailure); } @SneakyThrows protected <T> void process(ListenableFuture<T> deviceCtxFuture, Consumer<T> onSuccess, Consumer<Throwable> onFailure) { if (deviceCtxFuture.isDone()) { onSuccess.accept(deviceCtxFuture.get()); } else { DonAsynchron.withCallback(deviceCtxFuture, onSuccess, onFailure, context.getExecutor()); } } protected void processFailure(int msgId, String deviceName, String msgType, AtomicBoolean ackSent, Throwable t) { if (DataConstants.MAXIMUM_NUMBER_OF_DEVICES_REACHED.equals(t.getMessage())) { processFailure(msgId, deviceName, msgType, ackSent, MqttReasonCodes.PubAck.QUOTA_EXCEEDED, t); } else { processFailure(msgId, deviceName, msgType, ackSent, MqttReasonCodes.PubAck.UNSPECIFIED_ERROR, t); } } protected void processFailure(int msgId, String deviceName, String msgType, AtomicBoolean ackSent, MqttReasonCodes.PubAck pubAck, Throwable t) { log.debug("[{}][{}][{}] Failed to process device {} command: [{}]", gateway.getTenantId(), gateway.getDeviceId(), sessionId, msgType, deviceName, t); if (ackSent.compareAndSet(false, true)) {
ack(msgId, pubAck); } } private void closeDeviceSession(String deviceName, MqttReasonCodes.Disconnect returnCode) { try { if (MqttVersion.MQTT_5.equals(deviceSessionCtx.getMqttVersion())) { MqttTransportAdaptor adaptor = deviceSessionCtx.getPayloadAdaptor(); int returnCodeValue = returnCode.byteValue() & 0xFF; Optional<MqttMessage> deviceDisconnectPublishMsg = adaptor.convertToGatewayDeviceDisconnectPublish(deviceSessionCtx, deviceName, returnCodeValue); deviceDisconnectPublishMsg.ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); } } catch (Exception e) { log.trace("Failed to send device disconnect to gateway session", e); } } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\session\AbstractGatewaySessionHandler.java
1
请完成以下Java代码
private void syncPriceEnteredOverrideToCandidate( @NonNull final NewManualInvoiceCandidateBuilder candidate, @NonNull final ProductId productId, @NonNull final JsonCreateInvoiceCandidatesRequestItem item) { final JsonPrice priceEnteredOverride = item.getPriceEnteredOverride(); final ProductPrice price = createProductPriceOrNull(priceEnteredOverride, productId, item); candidate.priceEnteredOverride(price); } private ProductPrice createProductPriceOrNull( @Nullable final JsonPrice jsonPrice, @NonNull final ProductId productId, @NonNull final JsonCreateInvoiceCandidatesRequestItem item) { if (jsonPrice == null) { return null; } final CurrencyId currencyId = lookupCurrencyId(jsonPrice); final UomId priceUomId = lookupUomId( X12DE355.ofNullableCode(jsonPrice.getPriceUomCode()), productId, item); final ProductPrice price = ProductPrice.builder() .money(Money.of(jsonPrice.getValue(), currencyId)) .productId(productId) .uomId(priceUomId) .build(); return price; } private CurrencyId lookupCurrencyId(@NonNull final JsonPrice jsonPrice) { final CurrencyId result = currencyService.getCurrencyId(jsonPrice.getCurrencyCode()); if (result == null) { throw MissingResourceException.builder().resourceName("currency").resourceIdentifier(jsonPrice.getPriceUomCode()).parentResource(jsonPrice).build(); } return result; } private UomId lookupUomId( @Nullable final X12DE355 uomCode, @NonNull final ProductId productId, @NonNull final JsonCreateInvoiceCandidatesRequestItem item) { if (uomCode == null) { return productBL.getStockUOMId(productId); }
final UomId priceUomId; try { priceUomId = uomDAO.getUomIdByX12DE355(uomCode); } catch (final AdempiereException e) { throw MissingResourceException.builder().resourceName("uom").resourceIdentifier("priceUomCode").parentResource(item).cause(e).build(); } return priceUomId; } private InvoiceCandidateLookupKey createInvoiceCandidateLookupKey(@NonNull final JsonCreateInvoiceCandidatesRequestItem item) { try { return InvoiceCandidateLookupKey.builder() .externalHeaderId(JsonExternalIds.toExternalIdOrNull(item.getExternalHeaderId())) .externalLineId(JsonExternalIds.toExternalIdOrNull(item.getExternalLineId())) .build(); } catch (final AdempiereException e) { throw InvalidEntityException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\invoicecandidates\impl\CreateInvoiceCandidatesService.java
1
请完成以下Java代码
public void setOrderConfirmed() { this.orderStatus = OrderStatus.CONFIRMED; } public void setOrderShipped() { this.orderStatus = OrderStatus.SHIPPED; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} Order that = (Order) o; return Objects.equals(orderId, that.orderId) && Objects.equals(products, that.products) && orderStatus == that.orderStatus; } @Override public int hashCode() { return Objects.hash(orderId, products, orderStatus); } @Override public String toString() { return "Order{" + "orderId='" + orderId + '\'' + ", products=" + products + ", orderStatus=" + orderStatus + '}'; } }
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\queries\Order.java
1
请完成以下Java代码
public class ScriptException extends RuntimeException { /** * */ private static final long serialVersionUID = 5438314907624287813L; private final String _message; private final Map<String, Object> params = new LinkedHashMap<String, Object>(); public ScriptException(final String message, final Throwable cause) { super(null, cause); _message = message; } public ScriptException(final String message) { this(message, (Throwable)null); } /** * @return error message including parameters */ @Override public String getMessage() { final boolean printStackTrace = false; // of course we are no printing the stack trace in our exception message return toStringX(printStackTrace); } private final String getInnerMessage() { return _message; } public ScriptException addParameter(final String name, final Object value) { params.put(name, value); return this; } public Map<String, Object> getParameters() { return params; } public void print(final PrintStream out) { final boolean printStackTrace = true; // backward compatibility print(out, printStackTrace); } public void print(final PrintStream out, final boolean printStackTrace) { out.println("Error: " + getInnerMessage()); for (final Map.Entry<String, Object> param : getParameters().entrySet()) { final Object value = param.getValue(); if (value == null) { continue; } final String name = param.getKey(); if (value instanceof List<?>) { final List<?> list = (List<?>)value; if (list.isEmpty()) {
continue; } out.println(name + ":"); for (final Object item : list) { out.println("\t" + item); } } else { out.println(name + ": " + value); } } if (printStackTrace) { out.println("Stack trace: "); this.printStackTrace(out); } } public String toStringX() { final boolean printStackTrace = true; // backward compatibility return toStringX(printStackTrace); } public String toStringX(final boolean printStackTrace) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); print(out, printStackTrace); return baos.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\exception\ScriptException.java
1
请完成以下Java代码
public EventSubscriptionQuery eventName(String eventName) { ensureNotNull("event name", eventName); this.eventName = eventName; return this; } public EventSubscriptionQueryImpl executionId(String executionId) { ensureNotNull("execution id", executionId); this.executionId = executionId; return this; } public EventSubscriptionQuery processInstanceId(String processInstanceId) { ensureNotNull("process instance id", processInstanceId); this.processInstanceId = processInstanceId; return this; } public EventSubscriptionQueryImpl activityId(String activityId) { ensureNotNull("activity id", activityId); this.activityId = activityId; return this; } public EventSubscriptionQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public EventSubscriptionQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public EventSubscriptionQuery includeEventSubscriptionsWithoutTenantId() { this.includeEventSubscriptionsWithoutTenantId = true; return this; } public EventSubscriptionQueryImpl eventType(String eventType) { ensureNotNull("event type", eventType); this.eventType = eventType; return this; } public EventSubscriptionQuery orderByCreated() { return orderBy(EventSubscriptionQueryProperty.CREATED); } public EventSubscriptionQuery orderByTenantId() { return orderBy(EventSubscriptionQueryProperty.TENANT_ID);
} //results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getEventSubscriptionManager() .findEventSubscriptionCountByQueryCriteria(this); } @Override public List<EventSubscription> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getEventSubscriptionManager() .findEventSubscriptionsByQueryCriteria(this,page); } //getters ////////////////////////////////////////// public String getEventSubscriptionId() { return eventSubscriptionId; } public String getEventName() { return eventName; } public String getEventType() { return eventType; } public String getExecutionId() { return executionId; } public String getProcessInstanceId() { return processInstanceId; } public String getActivityId() { return activityId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\EventSubscriptionQueryImpl.java
1
请完成以下Java代码
public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getModelEntityManager().findModelCountByQueryCriteria(this); } public List<Model> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getModelEntityManager().findModelsByQueryCriteria(this, page); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; } public String getKey() { return key; } public boolean isLatest() { return latest; }
public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ModelQueryImpl.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Collections.singletonList(NAME_KEY); } public GatewayFilter apply() { return apply((NameConfig) null); } @Override public GatewayFilter apply(@Nullable NameConfig config) { String defaultClientRegistrationId = (config == null) ? null : config.getName(); return (exchange, chain) -> exchange.getPrincipal() // .log("token-relay-filter") .filter(principal -> principal instanceof Authentication) .cast(Authentication.class) .flatMap(principal -> authorizationRequest(defaultClientRegistrationId, principal)) .flatMap(this::authorizedClient) .map(OAuth2AuthorizedClient::getAccessToken) .map(token -> withBearerAuth(exchange, token)) // TODO: adjustable behavior if empty .defaultIfEmpty(exchange) .flatMap(chain::filter); } private Mono<OAuth2AuthorizeRequest> authorizationRequest(@Nullable String defaultClientRegistrationId, Authentication principal) { String clientRegistrationId = defaultClientRegistrationId;
if (clientRegistrationId == null && principal instanceof OAuth2AuthenticationToken) { clientRegistrationId = ((OAuth2AuthenticationToken) principal).getAuthorizedClientRegistrationId(); } return Mono.justOrEmpty(clientRegistrationId) .map(OAuth2AuthorizeRequest::withClientRegistrationId) .map(builder -> builder.principal(principal).build()); } private Mono<OAuth2AuthorizedClient> authorizedClient(OAuth2AuthorizeRequest request) { ReactiveOAuth2AuthorizedClientManager clientManager = clientManagerProvider.getIfAvailable(); if (clientManager == null) { return Mono.error(new IllegalStateException( "No ReactiveOAuth2AuthorizedClientManager bean was found. Did you include the " + "org.springframework.boot:spring-boot-starter-oauth2-client dependency?")); } // TODO: use Mono.defer() for request above? return clientManager.authorize(request); } private ServerWebExchange withBearerAuth(ServerWebExchange exchange, OAuth2AccessToken accessToken) { return exchange.mutate() .request(r -> r.headers(headers -> headers.setBearerAuth(accessToken.getTokenValue()))) .build(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\TokenRelayGatewayFilterFactory.java
1
请完成以下Java代码
public long findTaskCountByQueryCriteria(TaskQueryImpl taskQuery) { return taskDataManager.findTaskCountByQueryCriteria(taskQuery); } @Override public List<Task> findTasksByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) { return taskDataManager.findTasksByNativeQuery(parameterMap, firstResult, maxResults); } @Override public long findTaskCountByNativeQuery(Map<String, Object> parameterMap) { return taskDataManager.findTaskCountByNativeQuery(parameterMap); } @Override public List<Task> findTasksByParentTaskId(String parentTaskId) { return taskDataManager.findTasksByParentTaskId(parentTaskId); } @Override public void deleteTask(String taskId, String deleteReason, boolean cascade, boolean cancel) { TaskEntity task = findById(taskId); if (task != null) { if (task.getExecutionId() != null) { throw new ActivitiException("The task cannot be deleted because is part of a running process"); } deleteTask(task, deleteReason, cascade, cancel); } else if (cascade) { getHistoricTaskInstanceEntityManager().delete(taskId); } } @Override
public void deleteTask(String taskId, String deleteReason, boolean cascade) { this.deleteTask(taskId, deleteReason, cascade, false); } @Override public void updateTaskTenantIdForDeployment(String deploymentId, String newTenantId) { taskDataManager.updateTaskTenantIdForDeployment(deploymentId, newTenantId); } public TaskDataManager getTaskDataManager() { return taskDataManager; } public void setTaskDataManager(TaskDataManager taskDataManager) { this.taskDataManager = taskDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityManagerImpl.java
1
请完成以下Java代码
public I_M_HU_Item_Storage retrieveItemStorage(final I_M_HU_Item huItem, @NonNull final ProductId productId) { return Services.get(IQueryBL.class).createQueryBuilder(I_M_HU_Item_Storage.class, huItem) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID())) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_Product_ID, productId)) .create() .setOnlyActiveRecords(true) .firstOnly(I_M_HU_Item_Storage.class); } @Override public List<I_M_HU_Item_Storage> retrieveItemStorages(final I_M_HU_Item huItem) { final IQueryBuilder<I_M_HU_Item_Storage> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU_Item_Storage.class, huItem) .filter(new EqualsQueryFilter<I_M_HU_Item_Storage>(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_ID, huItem.getM_HU_Item_ID())); queryBuilder.orderBy() .addColumn(I_M_HU_Item_Storage.COLUMNNAME_M_HU_Item_Storage_ID); // predictive order final List<I_M_HU_Item_Storage> huItemStorages = queryBuilder .create() .setOnlyActiveRecords(true) .list(I_M_HU_Item_Storage.class); // Optimization: set parent link for (final I_M_HU_Item_Storage huItemStorage : huItemStorages)
{ huItemStorage.setM_HU_Item(huItem); } return huItemStorages; } @Override public void save(final I_M_HU_Item_Storage storageLine) { InterfaceWrapperHelper.save(storageLine); } @Override public void save(final I_M_HU_Item item) { InterfaceWrapperHelper.save(item); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUStorageDAO.java
1
请完成以下Java代码
public String getInstrForDbtrAgt() { return instrForDbtrAgt; } /** * Sets the value of the instrForDbtrAgt property. * * @param value * allowed object is * {@link String } * */ public void setInstrForDbtrAgt(String value) { this.instrForDbtrAgt = value; } /** * Gets the value of the purp property. * * @return * possible object is * {@link Purpose2CHCode } * */ public Purpose2CHCode getPurp() { return purp; } /** * Sets the value of the purp property. * * @param value * allowed object is * {@link Purpose2CHCode } * */ public void setPurp(Purpose2CHCode value) { this.purp = value; } /** * Gets the value of the rgltryRptg property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rgltryRptg property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRgltryRptg().add(newItem);
* </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link RegulatoryReporting3 } * * */ public List<RegulatoryReporting3> getRgltryRptg() { if (rgltryRptg == null) { rgltryRptg = new ArrayList<RegulatoryReporting3>(); } return this.rgltryRptg; } /** * Gets the value of the rmtInf property. * * @return * possible object is * {@link RemittanceInformation5CH } * */ public RemittanceInformation5CH getRmtInf() { return rmtInf; } /** * Sets the value of the rmtInf property. * * @param value * allowed object is * {@link RemittanceInformation5CH } * */ public void setRmtInf(RemittanceInformation5CH value) { this.rmtInf = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\CreditTransferTransactionInformation10CH.java
1
请完成以下Java代码
public void deleteCustomersByTenantId(TenantId tenantId) { log.trace("Executing deleteCustomersByTenantId, tenantId [{}]", tenantId); Validator.validateId(tenantId, id -> "Incorrect tenantId " + id); customersByTenantRemover.removeEntities(tenantId, tenantId); } @Override public List<Customer> findCustomersByTenantIdAndIds(TenantId tenantId, List<CustomerId> customerIds) { log.trace("Executing findCustomersByTenantIdAndIds, tenantId [{}], customerIds [{}]", tenantId, customerIds); return customerDao.findCustomersByTenantIdAndIds(tenantId.getId(), customerIds.stream().map(CustomerId::getId).collect(Collectors.toList())); } @Override public void deleteByTenantId(TenantId tenantId) { deleteCustomersByTenantId(tenantId); } private final PaginatedRemover<TenantId, Customer> customersByTenantRemover = new PaginatedRemover<>() { @Override protected PageData<Customer> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) { return customerDao.findCustomersByTenantId(id.getId(), pageLink); } @Override protected void removeEntity(TenantId tenantId, Customer entity) { deleteCustomer(tenantId, new CustomerId(entity.getUuidId()));
} }; @Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findCustomerById(tenantId, new CustomerId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(findCustomerByIdAsync(tenantId, new CustomerId(entityId.getId()))) .transform(Optional::ofNullable, directExecutor()); } @Override public long countByTenantId(TenantId tenantId) { return customerDao.countByTenantId(tenantId); } @Override public EntityType getEntityType() { return EntityType.CUSTOMER; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\customer\CustomerServiceImpl.java
1
请完成以下Java代码
public List<FormValue> getFormValues() { return formValues; } public void setFormValues(List<FormValue> formValues) { this.formValues = formValues; } public FormProperty clone() { FormProperty clone = new FormProperty(); clone.setValues(this); return clone; } public void setValues(FormProperty otherProperty) { super.setValues(otherProperty); setName(otherProperty.getName());
setExpression(otherProperty.getExpression()); setVariable(otherProperty.getVariable()); setType(otherProperty.getType()); setDefaultExpression(otherProperty.getDefaultExpression()); setDatePattern(otherProperty.getDatePattern()); setReadable(otherProperty.isReadable()); setWriteable(otherProperty.isWriteable()); setRequired(otherProperty.isRequired()); formValues = new ArrayList<FormValue>(); if (otherProperty.getFormValues() != null && !otherProperty.getFormValues().isEmpty()) { for (FormValue formValue : otherProperty.getFormValues()) { formValues.add(formValue.clone()); } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FormProperty.java
1
请完成以下Java代码
public void inactivate(final I_M_DeliveryDay deliveryDay, final String trxName) { Check.assumeNotNull(deliveryDay, "deliveryDay not null"); deliveryDay.setIsActive(false); InterfaceWrapperHelper.save(deliveryDay, trxName); } @Override public void invalidate(final I_M_DeliveryDay deliveryDay) { Check.assumeNotNull(deliveryDay, "deliveryDay not null"); // TODO: implement } /** * Sets DeliveryDateTimeMax = DeliveryDate + BufferHours. * * @param deliveryDay */ @Override public void setDeliveryDateTimeMax(final I_M_DeliveryDay deliveryDay) { final Timestamp deliveryDate = deliveryDay.getDeliveryDate(); final int bufferHours = deliveryDay.getBufferHours(); final Timestamp deliveryDateTimeMax = TimeUtil.addHours(deliveryDate, bufferHours); deliveryDay.setDeliveryDateTimeMax(deliveryDateTimeMax); } /** * The search will initially be made for the first deliveryDay of the day of the promised date. * For example, if there are 3 deliveryDay entries for a certain date and the products are * promised to be shipped in that day's evening, the first deliveryDay of that day will be chosen. * If there are no deliveryDay entries for the given date that are before the promised date/time, * select the last available deliveryDay that is before the promised date/time */ @NonNull @Override public ImmutablePair<TourId, ZonedDateTime> calculateTourAndPreparationDate( @NonNull final IContextAware context, @NonNull final SOTrx soTrx, @NonNull final ZonedDateTime calculationTime,
@NonNull final ZonedDateTime datePromised, @NonNull final BPartnerLocationId bpartnerLocationId) { LocalDate preparationDay = datePromised.toLocalDate(); // // Create Delivery Day Query Parameters final PlainDeliveryDayQueryParams deliveryDayQueryParams = new PlainDeliveryDayQueryParams(); deliveryDayQueryParams.setBPartnerLocationId(bpartnerLocationId); deliveryDayQueryParams.setDeliveryDate(datePromised); deliveryDayQueryParams.setToBeFetched(soTrx.isPurchase()); deliveryDayQueryParams.setProcessed(false); deliveryDayQueryParams.setCalculationTime(calculationTime); deliveryDayQueryParams.setPreparationDay(preparationDay); // // Find matching delivery day record final IDeliveryDayDAO deliveryDayDAO = Services.get(IDeliveryDayDAO.class); I_M_DeliveryDay dd = deliveryDayDAO.retrieveDeliveryDay(context, deliveryDayQueryParams); // No same-day deliveryDay found => chose the closest one if (dd == null) { preparationDay = null; deliveryDayQueryParams.setPreparationDay(preparationDay); dd = deliveryDayDAO.retrieveDeliveryDay(context, deliveryDayQueryParams); } // // Extract PreparationDate from DeliveryDay record final ImmutablePair<TourId, ZonedDateTime> ret; if (dd == null) { ret = ImmutablePair.of(null, null); } else { ret = ImmutablePair.of(TourId.ofRepoIdOrNull(dd.getM_Tour_ID()), TimeUtil.asZonedDateTime(dd.getDeliveryDate())); } return ret; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\DeliveryDayBL.java
1
请完成以下Java代码
private CallOrderDetailData buildCallOrderData(@NonNull final CallOrderSummaryId callOrderSummaryId, @NonNull final I_C_InvoiceLine invoiceLine) { final Quantity qtyInvoiced = invoiceLineBL.getQtyInvoicedStockUOM(InterfaceWrapperHelper.create(invoiceLine, de.metas.adempiere.model.I_C_InvoiceLine.class)); return CallOrderDetailData .builder() .summaryId(callOrderSummaryId) .invoiceId(InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID())) .invoiceAndLineId(InvoiceAndLineId.ofRepoId(invoiceLine.getC_Invoice_ID(), invoiceLine.getC_InvoiceLine_ID())) .qtyInvoiced(qtyInvoiced) .build(); } @NonNull private static CallOrderDetailData buildCallOrderData(@NonNull final CallOrderSummaryId summaryId, @NonNull final I_C_OrderLine ol) { final UomId uomId = UomId.ofRepoId(ol.getC_UOM_ID()); final Quantity qtyEntered = Quantitys.of(ol.getQtyEntered(), uomId); return CallOrderDetailData .builder() .summaryId(summaryId) .orderId(OrderId.ofRepoId(ol.getC_Order_ID()))
.orderLineId(OrderLineId.ofRepoId(ol.getC_OrderLine_ID())) .qtyEntered(qtyEntered) .build(); } @NonNull private CallOrderDetailData buildCallOrderData(@NonNull final CallOrderSummaryId summaryId, @NonNull final I_M_InOutLine shipmentLine) { return CallOrderDetailData .builder() .summaryId(summaryId) .shipmentId(InOutId.ofRepoId(shipmentLine.getM_InOut_ID())) .shipmentLineId(InOutLineId.ofRepoId(shipmentLine.getM_InOutLine_ID())) .qtyDelivered(inoutBL.getQtyEntered(shipmentLine)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\detail\CallOrderDetailService.java
1
请完成以下Java代码
public ActiveOrHistoricCurrencyAndAmount getTaxAmt() { return taxAmt; } /** * Sets the value of the taxAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTaxAmt(ActiveOrHistoricCurrencyAndAmount value) { this.taxAmt = value; } /** * Gets the value of the adjstmntAmtAndRsn property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the adjstmntAmtAndRsn property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdjstmntAmtAndRsn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentAdjustment1 } * * */ public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() { if (adjstmntAmtAndRsn == null) { adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>();
} return this.adjstmntAmtAndRsn; } /** * Gets the value of the rmtdAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() { return rmtdAmt; } /** * Sets the value of the rmtdAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) { this.rmtdAmt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceAmount1.java
1
请完成以下Java代码
public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity) { set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity); } @Override public BigDecimal getQtyItemCapacity() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOrdered (final BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOrdered_Override (final @Nullable BigDecimal QtyOrdered_Override) { set_Value (COLUMNNAME_QtyOrdered_Override, QtyOrdered_Override); } @Override public BigDecimal getQtyOrdered_Override() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered_Override); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setUPC_CU (final @Nullable java.lang.String UPC_CU) { set_Value (COLUMNNAME_UPC_CU, UPC_CU); } @Override public java.lang.String getUPC_CU() { return get_ValueAsString(COLUMNNAME_UPC_CU); } @Override public void setUPC_TU (final @Nullable java.lang.String UPC_TU) { set_Value (COLUMNNAME_UPC_TU, UPC_TU); } @Override public java.lang.String getUPC_TU() { return get_ValueAsString(COLUMNNAME_UPC_TU); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine.java
1
请完成以下Java代码
public void setStatusToolTip(final String tip) { statusLine.setToolTipText(tip); } // setStatusToolTip /** * Set Status DB Info * * @param text text * @param dse data status event */ @Override public void setStatusDB(final String text, final DataStatusEvent dse) { // log.info( "StatusBar.setStatusDB - " + text + " - " + created + "/" + createdBy); if (text == null || text.length() == 0) { statusDB.setText(""); statusDB.setVisible(false); } else { final StringBuilder sb = new StringBuilder(" "); sb.append(text).append(" "); statusDB.setText(sb.toString()); if (!statusDB.isVisible()) { statusDB.setVisible(true); } } // Save // m_text = text; m_dse = dse; } // setStatusDB /** * Set Status DB Info * * @param text text */ @Override public void setStatusDB(final String text) { setStatusDB(text, null); } // setStatusDB /** * Set Status DB Info * * @param no no
*/ public void setStatusDB(final int no) { setStatusDB(String.valueOf(no), null); } // setStatusDB /** * Set Info Line * * @param text text */ @Override public void setInfo(final String text) { infoLine.setVisible(true); infoLine.setText(text); } // setInfo /** * Show {@link RecordInfo} dialog */ private void showRecordInfo() { if (m_dse == null) { return; } final int adTableId = m_dse.getAdTableId(); final ComposedRecordId recordId = m_dse.getRecordId(); if (adTableId <= 0 || recordId == null) { return; } if (!Env.getUserRolePermissions().isShowPreference()) { return; } // final RecordInfo info = new RecordInfo(SwingUtils.getFrame(this), adTableId, recordId); AEnv.showCenterScreen(info); } public void removeBorders() { statusLine.setBorder(BorderFactory.createEmptyBorder()); statusDB.setBorder(BorderFactory.createEmptyBorder()); infoLine.setBorder(BorderFactory.createEmptyBorder()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\StatusBar.java
1
请完成以下Java代码
public void fromAnnotation(ExternalTaskSubscription config) { setAutoOpen(config.autoOpen()); String topicName = config.topicName(); setTopicName(isNull(topicName) ? null : topicName); long lockDuration = config.lockDuration(); setLockDuration(isNull(lockDuration) ? null : lockDuration); String[] variableNames = config.variableNames(); setVariableNames(isNull(variableNames) ? null : Arrays.asList(variableNames)); setLocalVariables(config.localVariables()); String businessKey = config.businessKey(); setBusinessKey(isNull(businessKey) ? null : businessKey); String processDefinitionId = config.processDefinitionId(); setProcessDefinitionId(isNull(processDefinitionId) ? null : processDefinitionId); String[] processDefinitionIdIn = config.processDefinitionIdIn(); setProcessDefinitionIdIn(isNull(processDefinitionIdIn) ? null : Arrays.asList(processDefinitionIdIn)); String processDefinitionKey = config.processDefinitionKey(); setProcessDefinitionKey(isNull(processDefinitionKey) ? null : processDefinitionKey); String[] processDefinitionKeyIn = config.processDefinitionKeyIn(); setProcessDefinitionKeyIn(isNull(processDefinitionKeyIn) ? null : Arrays.asList(processDefinitionKeyIn)); String processDefinitionVersionTag = config.processDefinitionVersionTag(); setProcessDefinitionVersionTag(isNull(processDefinitionVersionTag) ? null : processDefinitionVersionTag); ProcessVariable[] processVariables = config.processVariables(); setProcessVariables(isNull(processVariables) ? null : Arrays.stream(processVariables) .collect(Collectors.toMap(ProcessVariable::name, ProcessVariable::value))); setWithoutTenantId(config.withoutTenantId()); String[] tenantIdIn = config.tenantIdIn();
setTenantIdIn(isNull(tenantIdIn) ? null : Arrays.asList(tenantIdIn)); setIncludeExtensionProperties(config.includeExtensionProperties()); } protected static boolean isNull(String[] values) { return values.length == 1 && STRING_NULL_VALUE.equals(values[0]); } protected static boolean isNull(String value) { return STRING_NULL_VALUE.equals(value); } protected static boolean isNull(long value) { return LONG_NULL_VALUE == value; } protected static boolean isNull(ProcessVariable[] values) { return values.length == 1 && STRING_NULL_VALUE.equals(values[0].name()) && STRING_NULL_VALUE.equals(values[0].value()); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SubscriptionConfiguration.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) { int count = brandService.deleteBrand(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation(value = "批量更新显示状态") @RequestMapping(value = "/update/showStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids, @RequestParam("showStatus") Integer showStatus) { int count = brandService.updateShowStatus(ids, showStatus); if (count > 0) { return CommonResult.success(count);
} else { return CommonResult.failed(); } } @ApiOperation(value = "批量更新厂家制造商状态") @RequestMapping(value = "/update/factoryStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateFactoryStatus(@RequestParam("ids") List<Long> ids, @RequestParam("factoryStatus") Integer factoryStatus) { int count = brandService.updateFactoryStatus(ids, factoryStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsBrandController.java
2
请在Spring Boot框架中完成以下Java代码
public void updateData(RpUserBankAccount rpUserBankAccount) { rpUserBankAccountDao.update(rpUserBankAccount); } /** * 根据用户编号获取银行账户 */ @Override public RpUserBankAccount getByUserNo(String userNo){ Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("userNo", userNo); paramMap.put("status", PublicStatusEnum.ACTIVE.name()); return rpUserBankAccountDao.getBy(paramMap); } /** * 创建或更新 * @param rpUserBankAccount */ @Override public void createOrUpdate(RpUserBankAccount rpUserBankAccount){ RpUserBankAccount bankAccount = getByUserNo(rpUserBankAccount.getUserNo()); if(bankAccount == null){ bankAccount = new RpUserBankAccount(); bankAccount.setId(StringUtil.get32UUID()); bankAccount.setCreateTime(new Date()); bankAccount.setEditTime(new Date()); bankAccount.setAreas(rpUserBankAccount.getAreas()); bankAccount.setBankAccountName(rpUserBankAccount.getBankAccountName()); bankAccount.setBankAccountNo(rpUserBankAccount.getBankAccountNo()); bankAccount.setBankAccountType(rpUserBankAccount.getBankAccountType()); bankAccount.setBankCode(rpUserBankAccount.getBankCode()); bankAccount.setBankName(BankCodeEnum.getEnum(rpUserBankAccount.getBankCode()).getDesc()); bankAccount.setCardNo(rpUserBankAccount.getCardNo()); bankAccount.setCardType(rpUserBankAccount.getCardType()); bankAccount.setCity(rpUserBankAccount.getCity()); bankAccount.setIsDefault(PublicEnum.YES.name()); bankAccount.setMobileNo(rpUserBankAccount.getMobileNo()); bankAccount.setProvince(rpUserBankAccount.getProvince()); bankAccount.setRemark(rpUserBankAccount.getRemark()); bankAccount.setStatus(PublicStatusEnum.ACTIVE.name()); bankAccount.setUserNo(rpUserBankAccount.getUserNo()); bankAccount.setStreet(rpUserBankAccount.getStreet()); rpUserBankAccountDao.insert(bankAccount);
}else{ bankAccount.setEditTime(new Date()); bankAccount.setAreas(rpUserBankAccount.getAreas()); bankAccount.setBankAccountName(rpUserBankAccount.getBankAccountName()); bankAccount.setBankAccountNo(rpUserBankAccount.getBankAccountNo()); bankAccount.setBankAccountType(rpUserBankAccount.getBankAccountType()); bankAccount.setBankCode(rpUserBankAccount.getBankCode()); bankAccount.setBankName(BankCodeEnum.getEnum(rpUserBankAccount.getBankCode()).getDesc()); bankAccount.setCardNo(rpUserBankAccount.getCardNo()); bankAccount.setCardType(rpUserBankAccount.getCardType()); bankAccount.setCity(rpUserBankAccount.getCity()); bankAccount.setIsDefault(PublicEnum.YES.name()); bankAccount.setMobileNo(rpUserBankAccount.getMobileNo()); bankAccount.setProvince(rpUserBankAccount.getProvince()); bankAccount.setRemark(rpUserBankAccount.getRemark()); bankAccount.setStatus(PublicStatusEnum.ACTIVE.name()); bankAccount.setUserNo(rpUserBankAccount.getUserNo()); bankAccount.setStreet(rpUserBankAccount.getStreet()); rpUserBankAccountDao.update(bankAccount); } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpUserBankAccountServiceImpl.java
2
请完成以下Java代码
public void debugPerformOperationStep(String stepName) { logDebug( "041", "Performing deployment operation step '{}'", stepName); } public void debugSuccessfullyPerformedOperationStep(String stepName) { logDebug( "041", "Successfully performed deployment operation step '{}'", stepName); } public void exceptionWhileRollingBackOperation(Exception e) { logError( "042", "Exception while rolling back operation", e); } public ProcessEngineException exceptionWhilePerformingOperationStep(String opName, String stepName, Exception e) { return new ProcessEngineException(exceptionMessage( "043", "Exception while performing '{}' => '{}': {}", opName, stepName, e.getMessage()), e); } public void exceptionWhilePerformingOperationStep(String name, Exception e) { logError( "044", "Exception while performing '{}': {}", name, e.getMessage(), e); } public void debugRejectedExecutionException(RejectedExecutionException e) { logDebug( "045", "RejectedExecutionException while scheduling work", e); } public void foundTomcatDeploymentDescriptor(String bpmPlatformFileLocation, String fileLocation) { logInfo( "046", "Found Camunda Platform configuration in CATALINA_BASE/CATALINA_HOME conf directory [{}] at '{}'", bpmPlatformFileLocation, fileLocation); } public ProcessEngineException invalidDeploymentDescriptorLocation(String bpmPlatformFileLocation, MalformedURLException e) { throw new ProcessEngineException(exceptionMessage( "047",
"'{} is not a valid Camunda Platform configuration resource location.", bpmPlatformFileLocation), e); } public void camundaBpmPlatformSuccessfullyStarted(String serverInfo) { logInfo( "048", "Camunda Platform sucessfully started at '{}'.", serverInfo); } public void camundaBpmPlatformStopped(String serverInfo) { logInfo( "049", "Camunda Platform stopped at '{}'", serverInfo); } public void paDeployed(String name) { logInfo( "050", "Process application {} successfully deployed", name); } public void paUndeployed(String name) { logInfo( "051", "Process application {} undeployed", name); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\ContainerIntegrationLogger.java
1
请完成以下Java代码
public Set<String> getNamespaceSet() { return namespaceSet; } public ClusterServerStateVO setNamespaceSet(Set<String> namespaceSet) { this.namespaceSet = namespaceSet; return this; } public Integer getPort() { return port; } public ClusterServerStateVO setPort(Integer port) { this.port = port; return this; } public List<ConnectionGroupVO> getConnection() { return connection; } public ClusterServerStateVO setConnection(List<ConnectionGroupVO> connection) { this.connection = connection; return this; } public List<ClusterRequestLimitVO> getRequestLimitData() { return requestLimitData; } public ClusterServerStateVO setRequestLimitData(List<ClusterRequestLimitVO> requestLimitData) { this.requestLimitData = requestLimitData; return this; } public Boolean getEmbedded() { return embedded; }
public ClusterServerStateVO setEmbedded(Boolean embedded) { this.embedded = embedded; return this; } @Override public String toString() { return "ClusterServerStateVO{" + "appName='" + appName + '\'' + ", transport=" + transport + ", flow=" + flow + ", namespaceSet=" + namespaceSet + ", port=" + port + ", connection=" + connection + ", requestLimitData=" + requestLimitData + ", embedded=" + embedded + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\state\ClusterServerStateVO.java
1
请完成以下Java代码
public void run() { releaseAll(); } private void releaseAll() { IOException exceptionChain = null; exceptionChain = releaseInflators(exceptionChain); exceptionChain = releaseInputStreams(exceptionChain); exceptionChain = releaseZipContent(exceptionChain); exceptionChain = releaseZipContentForManifest(exceptionChain); if (exceptionChain != null) { throw new UncheckedIOException(exceptionChain); } } private IOException releaseInflators(IOException exceptionChain) { Deque<Inflater> inflaterCache = this.inflaterCache; if (inflaterCache != null) { try { synchronized (inflaterCache) { inflaterCache.forEach(Inflater::end); } } finally { this.inflaterCache = null; } } return exceptionChain; } private IOException releaseInputStreams(IOException exceptionChain) { synchronized (this.inputStreams) { for (InputStream inputStream : List.copyOf(this.inputStreams)) { try { inputStream.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex); } } this.inputStreams.clear(); } return exceptionChain; } private IOException releaseZipContent(IOException exceptionChain) { ZipContent zipContent = this.zipContent; if (zipContent != null) { try { zipContent.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex); } finally {
this.zipContent = null; } } return exceptionChain; } private IOException releaseZipContentForManifest(IOException exceptionChain) { ZipContent zipContentForManifest = this.zipContentForManifest; if (zipContentForManifest != null) { try { zipContentForManifest.close(); } catch (IOException ex) { exceptionChain = addToExceptionChain(exceptionChain, ex); } finally { this.zipContentForManifest = null; } } return exceptionChain; } private IOException addToExceptionChain(IOException exceptionChain, IOException ex) { if (exceptionChain != null) { exceptionChain.addSuppressed(ex); return exceptionChain; } return ex; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\jar\NestedJarFileResources.java
1
请完成以下Java代码
public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Trx_Line getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class); } @Override public void setReversalLine(final de.metas.handlingunits.model.I_M_HU_Trx_Line ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class, ReversalLine); } @Override public void setReversalLine_ID (final int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID); } @Override public int getReversalLine_ID()
{ return get_ValueAsInt(COLUMNNAME_ReversalLine_ID); } @Override public de.metas.handlingunits.model.I_M_HU_Item getVHU_Item() { return get_ValueAsPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class); } @Override public void setVHU_Item(final de.metas.handlingunits.model.I_M_HU_Item VHU_Item) { set_ValueFromPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, VHU_Item); } @Override public void setVHU_Item_ID (final int VHU_Item_ID) { if (VHU_Item_ID < 1) set_Value (COLUMNNAME_VHU_Item_ID, null); else set_Value (COLUMNNAME_VHU_Item_ID, VHU_Item_ID); } @Override public int getVHU_Item_ID() { return get_ValueAsInt(COLUMNNAME_VHU_Item_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Line.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ShippingFulfillment shippingFulfillment = (ShippingFulfillment)o; return Objects.equals(this.fulfillmentId, shippingFulfillment.fulfillmentId) && Objects.equals(this.lineItems, shippingFulfillment.lineItems) && Objects.equals(this.shipmentTrackingNumber, shippingFulfillment.shipmentTrackingNumber) && Objects.equals(this.shippedDate, shippingFulfillment.shippedDate) && Objects.equals(this.shippingCarrierCode, shippingFulfillment.shippingCarrierCode); } @Override public int hashCode() { return Objects.hash(fulfillmentId, lineItems, shipmentTrackingNumber, shippedDate, shippingCarrierCode); } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append("class ShippingFulfillment {\n"); sb.append(" fulfillmentId: ").append(toIndentedString(fulfillmentId)).append("\n"); sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n"); sb.append(" shipmentTrackingNumber: ").append(toIndentedString(shipmentTrackingNumber)).append("\n"); sb.append(" shippedDate: ").append(toIndentedString(shippedDate)).append("\n"); sb.append(" shippingCarrierCode: ").append(toIndentedString(shippingCarrierCode)).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\ShippingFulfillment.java
2
请完成以下Java代码
public static class Builder { private final PathPatternParser parser; Builder(PathPatternParser parser) { this.parser = parser; } /** * Match messages having this destination pattern. * * <p> * Path patterns always start with a slash and may contain placeholders. They can * also be followed by {@code /**} to signify all URIs under a given path. * * <p> * The following are valid patterns and their meaning * <ul> * <li>{@code /path} - match exactly and only `/path`</li> * <li>{@code /path/**} - match `/path` and any of its descendents</li> * <li>{@code /path/{value}/**} - match `/path/subdirectory` and any of its * descendents, capturing the value of the subdirectory in * {@link MessageAuthorizationContext#getVariables()}</li> * </ul> * * <p> * A more comprehensive list can be found at {@link PathPattern}. * * <p> * A dot-based message pattern is also supported when configuring a * {@link PathPatternParser} using * {@link PathPatternMessageMatcher#withPathPatternParser} * @param pattern the destination pattern to match * @return the {@link PathPatternMessageMatcher.Builder} for more configuration */ public PathPatternMessageMatcher matcher(String pattern) { return matcher(null, pattern); } /** * Match messages having this type and destination pattern. * * <p> * When the message {@code type} is null, then the matcher does not consider the * message type * * <p> * Path patterns always start with a slash and may contain placeholders. They can * also be followed by {@code /**} to signify all URIs under a given path. * * <p> * The following are valid patterns and their meaning * <ul> * <li>{@code /path} - match exactly and only `/path`</li> * <li>{@code /path/**} - match `/path` and any of its descendents</li> * <li>{@code /path/{value}/**} - match `/path/subdirectory` and any of its
* descendents, capturing the value of the subdirectory in * {@link MessageAuthorizationContext#getVariables()}</li> * </ul> * * <p> * A more comprehensive list can be found at {@link PathPattern}. * * <p> * A dot-based message pattern is also supported when configuring a * {@link PathPatternParser} using * {@link PathPatternMessageMatcher#withPathPatternParser} * @param type the message type to match * @param pattern the destination pattern to match * @return the {@link PathPatternMessageMatcher.Builder} for more configuration */ public PathPatternMessageMatcher matcher(@Nullable SimpMessageType type, String pattern) { Assert.notNull(pattern, "pattern must not be null"); PathPattern pathPattern = this.parser.parse(pattern); PathPatternMessageMatcher matcher = new PathPatternMessageMatcher(pathPattern, this.parser.getPathOptions()); if (type != null) { matcher.setMessageTypeMatcher(new SimpMessageTypeMatcher(type)); } return matcher; } } }
repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\util\matcher\PathPatternMessageMatcher.java
1
请在Spring Boot框架中完成以下Java代码
private void copyDiscountSchemaBreakWithProductId( @NonNull final PricingConditionsBreakId discountSchemaBreakId, @NonNull final PricingConditionsId toPricingConditionsId, @Nullable final ProductId toProductId) { final I_M_DiscountSchemaBreak from = getPricingConditionsBreakbyId(discountSchemaBreakId); final I_M_DiscountSchemaBreak newBreak = copy() .setSkipCalculatedColumns(true) .setFrom(from) .copyToNew(I_M_DiscountSchemaBreak.class); if (toProductId != null) { newBreak.setM_Product_ID(toProductId.getRepoId()); } newBreak.setSeqNo(retrieveNextSeqNo(toPricingConditionsId.getRepoId())); newBreak.setM_DiscountSchema_ID(toPricingConditionsId.getRepoId()); saveRecord(newBreak); } private void updateDiscountSchemaBreakRecords(@NonNull final PricingConditionsBreak fromBreak, @NonNull final PricingConditionsBreak toBreak) { final I_M_DiscountSchemaBreak to = getPricingConditionsBreakbyId(toBreak.getId()); to.setPricingSystemSurchargeAmt(fromBreak.getPricingSystemSurchargeAmt()); saveRecord(to); } private void inactivateDiscountSchemaBreakRecords(@NonNull final PricingConditionsBreak db) { final I_M_DiscountSchemaBreak record = getPricingConditionsBreakbyId(db.getId()); record.setIsActive(false); saveRecord(record); } @Override public boolean isSingleProductId(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter) { final Set<ProductId> distinctProductIds = retrieveDistinctProductIdsForSelection(selectionFilter); return distinctProductIds.size() == 1; } @Override public ProductId retrieveUniqueProductIdForSelectionOrNull(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter) {
final Set<ProductId> distinctProductsForSelection = retrieveDistinctProductIdsForSelection(selectionFilter); if (distinctProductsForSelection.isEmpty()) { return null; } if (distinctProductsForSelection.size() > 1) { throw new AdempiereException("Multiple products or none in the selected rows") .appendParametersToMessage() .setParameter("selectionFilter", selectionFilter); } final ProductId uniqueProductId = distinctProductsForSelection.iterator().next(); return uniqueProductId; } private Set<ProductId> retrieveDistinctProductIdsForSelection(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter) { final IQuery<I_M_DiscountSchemaBreak> breaksQuery = queryBL.createQueryBuilder(I_M_DiscountSchemaBreak.class) .filter(selectionFilter) .create(); final List<Integer> distinctProductRecordIds = breaksQuery.listDistinct(I_M_DiscountSchemaBreak.COLUMNNAME_M_Product_ID, Integer.class); return ProductId.ofRepoIds(distinctProductRecordIds); } public I_M_DiscountSchemaBreak getPricingConditionsBreakbyId(@NonNull PricingConditionsBreakId discountSchemaBreakId) { return load(discountSchemaBreakId.getDiscountSchemaBreakId(), I_M_DiscountSchemaBreak.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\impl\PricingConditionsRepository.java
2
请完成以下Java代码
public IAllocationResult createAllocationResult() { final List<IHUTransactionAttribute> attributeTrxs = getAndClearTransactions(); if (attributeTrxs.isEmpty()) { // no transactions, nothing to do return AllocationUtils.nullResult(); } return AllocationUtils.createQtyAllocationResult( BigDecimal.ZERO, // qtyToAllocate BigDecimal.ZERO, // qtyAllocated Collections.emptyList(), // trxs attributeTrxs // attribute transactions ); } @Override public IAllocationResult createAndProcessAllocationResult() {
final IAllocationResult result = createAllocationResult(); Services.get(IHUTrxBL.class).createTrx(huContext, result); return result; } @Override public void dispose() { // Unregister the listener/collector if (attributeStorageFactory != null && trxAttributesCollector != null) { trxAttributesCollector.dispose(); attributeStorageFactory.removeAttributeStorageListener(trxAttributesCollector); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\HUTransactionAttributeBuilder.java
1
请完成以下Java代码
public FlowableHttpClient determineHttpClient() { if (httpClient != null) { return httpClient; } else if (isApacheHttpComponentsPresent) { // Backwards compatibility, if apache HTTP Components is present then it has priority this.httpClient = new ApacheHttpComponentsFlowableHttpClient(this); return this.httpClient; } else if (isSpringWebClientPresent && isReactorHttpClientPresent) { this.httpClient = new SpringWebClientFlowableHttpClient(this); return httpClient; } else if (isApacheHttpComponents5Present) { ApacheHttpComponents5FlowableHttpClient httpClient = new ApacheHttpComponents5FlowableHttpClient(this); this.httpClient = httpClient; this.closeRunnable = httpClient::close; return this.httpClient; } else { throw new FlowableException("Failed to determine FlowableHttpClient"); }
} public boolean isDefaultParallelInSameTransaction() { return defaultParallelInSameTransaction; } public void setDefaultParallelInSameTransaction(boolean defaultParallelInSameTransaction) { this.defaultParallelInSameTransaction = defaultParallelInSameTransaction; } public void close() { if (closeRunnable != null) { closeRunnable.run(); } } }
repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\HttpClientConfig.java
1
请在Spring Boot框架中完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getVersion() { return version;
} public void setVersion(int version) { this.version = version; } public List<FormField> getFields() { return fields; } public void setFields(List<FormField> fields) { this.fields = fields; } public List<FormOutcome> getOutcomes() { return outcomes; } public void setOutcomes(List<FormOutcome> outcomes) { this.outcomes = outcomes; } public String getOutcomeVariableName() { return outcomeVariableName; } public void setOutcomeVariableName(String outcomeVariableName) { this.outcomeVariableName = outcomeVariableName; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\FormModelResponse.java
2
请完成以下Java代码
public HistoricActivityInstanceQuery orderByActivityId() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_ID); return this; } public HistoricActivityInstanceQueryImpl orderByActivityName() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_NAME); return this; } public HistoricActivityInstanceQueryImpl orderByActivityType() { orderBy(HistoricActivityInstanceQueryProperty.ACTIVITY_TYPE); return this; } public HistoricActivityInstanceQueryImpl orderByTenantId() { orderBy(HistoricActivityInstanceQueryProperty.TENANT_ID); return this; } public HistoricActivityInstanceQueryImpl activityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; return this; } // getters and setters // ////////////////////////////////////////////////////// public String getProcessInstanceId() { return processInstanceId; } public String getExecutionId() { return executionId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getActivityId() { return activityId; } public String getActivityName() { return activityName; } public String getActivityType() {
return activityType; } public String getAssignee() { return assignee; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public String getActivityInstanceId() { return activityInstanceId; } public String getDeleteReason() { return deleteReason; } public String getDeleteReasonLike() { return deleteReasonLike; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricActivityInstanceQueryImpl.java
1
请完成以下Java代码
public org.compiere.model.I_C_Period getC_Period() { return get_ValueAsPO(COLUMNNAME_C_Period_ID, org.compiere.model.I_C_Period.class); } @Override public void setC_Period(final org.compiere.model.I_C_Period C_Period) { set_ValueFromPO(COLUMNNAME_C_Period_ID, org.compiere.model.I_C_Period.class, C_Period); } @Override public void setC_Period_ID (final int C_Period_ID) { if (C_Period_ID < 1) set_Value (COLUMNNAME_C_Period_ID, null); else set_Value (COLUMNNAME_C_Period_ID, C_Period_ID); } @Override public int getC_Period_ID() { return get_ValueAsInt(COLUMNNAME_C_Period_ID); } @Override public void setDatevAcctExport_ID (final int DatevAcctExport_ID) { if (DatevAcctExport_ID < 1) set_ValueNoCheck (COLUMNNAME_DatevAcctExport_ID, null); else set_ValueNoCheck (COLUMNNAME_DatevAcctExport_ID, DatevAcctExport_ID); } @Override public int getDatevAcctExport_ID() { return get_ValueAsInt(COLUMNNAME_DatevAcctExport_ID); } @Override public void setExportBy_ID (final int ExportBy_ID) { if (ExportBy_ID < 1) set_ValueNoCheck (COLUMNNAME_ExportBy_ID, null); else set_ValueNoCheck (COLUMNNAME_ExportBy_ID, ExportBy_ID); } @Override public int getExportBy_ID() { return get_ValueAsInt(COLUMNNAME_ExportBy_ID); } @Override public void setExportDate (final @Nullable java.sql.Timestamp ExportDate) { set_ValueNoCheck (COLUMNNAME_ExportDate, ExportDate); } @Override public java.sql.Timestamp getExportDate() { return get_ValueAsTimestamp(COLUMNNAME_ExportDate); }
/** * ExportType AD_Reference_ID=541172 * Reference name: DatevExportType */ public static final int EXPORTTYPE_AD_Reference_ID=541172; /** Payment = Payment */ public static final String EXPORTTYPE_Payment = "Payment"; /** Commission Invoice = CommissionInvoice */ public static final String EXPORTTYPE_CommissionInvoice = "CommissionInvoice"; /** Sales Invoice = SalesInvoice */ public static final String EXPORTTYPE_SalesInvoice = "SalesInvoice"; /** Credit Memo = CreditMemo */ public static final String EXPORTTYPE_CreditMemo = "CreditMemo"; @Override public void setExportType (final java.lang.String ExportType) { set_Value (COLUMNNAME_ExportType, ExportType); } @Override public java.lang.String getExportType() { return get_ValueAsString(COLUMNNAME_ExportType); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExport.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_Cycle[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Currency getC_Currency() throws RuntimeException { return (I_C_Currency)MTable.get(getCtx(), I_C_Currency.Table_Name) .getPO(getC_Currency_ID(), get_TrxName()); } /** Set Currency. @param C_Currency_ID The Currency for this record */ public void setC_Currency_ID (int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID)); } /** Get Currency. @return The Currency for this record */ public int getC_Currency_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Project Cycle. @param C_Cycle_ID Identifier for this Project Reporting Cycle */ public void setC_Cycle_ID (int C_Cycle_ID) { if (C_Cycle_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, Integer.valueOf(C_Cycle_ID)); } /** Get Project Cycle. @return Identifier for this Project Reporting Cycle */ public int getC_Cycle_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record
*/ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cycle.java
1
请在Spring Boot框架中完成以下Java代码
public class SysPermission implements Serializable { @Id @GeneratedValue private Integer id; private String name; @Column(columnDefinition="enum('menu','button')") private String resourceType; // [menu|button] private String url; private String permission; // menu example:role:*,button example:role:create,role:update,role:delete,role:view private Long parentId; private String parentIds; private Boolean available = Boolean.FALSE; @ManyToMany @JoinTable(name="SysRolePermission",joinColumns={@JoinColumn(name="permissionId")},inverseJoinColumns={@JoinColumn(name="roleId")}) private List<SysRole> roles; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getResourceType() { return resourceType; } public void setResourceType(String resourceType) { this.resourceType = resourceType; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; }
public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentIds() { return parentIds; } public void setParentIds(String parentIds) { this.parentIds = parentIds; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; } }
repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysPermission.java
2
请完成以下Java代码
public class OrderOffer extends CalloutEngine { public String setOfferValidDays (final ICalloutField calloutField) { I_C_Order order = calloutField.getModel(I_C_Order.class); setOfferValidDate(order); return ""; } private static void setOfferValidDate(I_C_Order order) { if (order.isProcessed()) return; final Timestamp dateOrdered = order.getDateOrdered(); if (dateOrdered != null && isOffer(order)) { final int days = order.getOfferValidDays(); if (days < 0) throw new AdempiereException("@"+I_C_Order.COLUMNNAME_OfferValidDays+"@ < 0"); final Timestamp offerValidDate = TimeUtil.addDays(dateOrdered, days); order.setOfferValidDate(offerValidDate); } else { order.setOfferValidDays(0); order.setOfferValidDate(null); } }
private static boolean isOffer(final I_C_Order order) { DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(order.getC_DocType_ID()); if (docTypeId == null) { docTypeId = DocTypeId.ofRepoIdOrNull(order.getC_DocTypeTarget_ID()); } if (docTypeId == null) { return false; } return Services.get(IDocTypeBL.class).isSalesProposalOrQuotation(docTypeId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\OrderOffer.java
1
请完成以下Java代码
final class DataEntryRecordsMap { public static DataEntryRecordsMap of(@NonNull final Collection<DataEntryRecord> records) { if (records.isEmpty()) { return EMPTY; } return new DataEntryRecordsMap(records); } private static final DataEntryRecordsMap EMPTY = new DataEntryRecordsMap(); private final ImmutableMap<DataEntrySubTabId, DataEntryRecord> map; private DataEntryRecordsMap(@NonNull final Collection<DataEntryRecord> records) { map = Maps.uniqueIndex(records, DataEntryRecord::getDataEntrySubTabId);
} private DataEntryRecordsMap() { map = ImmutableMap.of(); } public Set<DataEntrySubTabId> getSubTabIds() { return map.keySet(); } public Optional<DataEntryRecord> getBySubTabId(final DataEntrySubTabId id) { final DataEntryRecord record = map.get(id); return Optional.ofNullable(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\DataEntryRecordsMap.java
1
请完成以下Java代码
private LookupValuesList getLookupValuesList(final Evaluatee parentEvaluatee) { return cacheByPartition.getOrLoad( createLookupDataSourceContext(parentEvaluatee), evalCtx -> fetcher.retrieveEntities(evalCtx).getValues()); } @NonNull private LookupDataSourceContext createLookupDataSourceContext(final Evaluatee parentEvaluatee) { return fetcher.newContextForFetchingList() .setParentEvaluatee(parentEvaluatee) .putFilter(LookupDataSourceContext.FILTER_Any, FIRST_ROW, Integer.MAX_VALUE) .build(); } @Override public LookupValuesPage findEntities(final Evaluatee ctx, final String filter, final int firstRow, final int pageLength) { final LookupValuesList partition = getLookupValuesList(ctx); if (partition.isEmpty()) { return LookupValuesPage.EMPTY; } final Predicate<LookupValue> filterPredicate = LookupValueFilterPredicates.of(filter); final LookupValuesList allMatchingValues; if (filterPredicate == LookupValueFilterPredicates.MATCH_ALL) { allMatchingValues = partition; } else { allMatchingValues = partition.filter(filterPredicate); } return allMatchingValues.pageByOffsetAndLimit(firstRow, pageLength); } @Override public LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength) { return findEntities(ctx, null, 0, pageLength); } @Override public LookupValue findById(final Object idObj) { final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey()); if (idNormalized == null) { return null; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getById(idNormalized); } @Override public @NonNull LookupValuesList findByIdsOrdered(@NonNull final Collection<?> ids) {
final ImmutableList<Object> idsNormalized = LookupValue.normalizeIds(ids, fetcher.isNumericKey()); if (idsNormalized.isEmpty()) { return LookupValuesList.EMPTY; } final LookupValuesList partition = getLookupValuesList(Evaluatees.empty()); return partition.getByIdsInOrder(idsNormalized); } @Override public DocumentZoomIntoInfo getDocumentZoomInto(final int id) { final String tableName = fetcher.getLookupTableName() .orElseThrow(() -> new IllegalStateException("Failed converting id=" + id + " to " + DocumentZoomIntoInfo.class + " because the fetcher returned null TableName: " + fetcher)); return DocumentZoomIntoInfo.of(tableName, id); } @Override public Optional<WindowId> getZoomIntoWindowId() { return fetcher.getZoomIntoWindowId(); } @Override public List<CCacheStats> getCacheStats() { return ImmutableList.of(cacheByPartition.stats()); } @Override public void cacheInvalidate() { cacheByPartition.reset(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\FullyCachedLookupDataSource.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> getMappingFileNames() { return mappingFileNames; } @Override public List<URL> getJarFileUrls() { return Collections.emptyList(); } @Override public URL getPersistenceUnitRootUrl() { return null; } @Override public List<String> getManagedClassNames() { return managedClassNames; } @Override public boolean excludeUnlistedClasses() { return false; } @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.UNSPECIFIED; } @Override public ValidationMode getValidationMode() { return ValidationMode.AUTO;
} public Properties getProperties() { return properties; } @Override public String getPersistenceXMLSchemaVersion() { return JPA_VERSION; } @Override public ClassLoader getClassLoader() { return Thread.currentThread().getContextClassLoader(); } @Override public void addTransformer(ClassTransformer transformer) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ClassLoader getNewTempClassLoader() { return null; } }
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\PersistenceUnitInfoImpl.java
2
请完成以下Java代码
public void addOrQuery(HistoricTaskInstanceQueryImpl orQuery) { orQuery.isOrQueryActive = true; this.queries.add(orQuery); } public void setOrQueryActive() { isOrQueryActive = true; } @Override public HistoricTaskInstanceQuery or() { if (this != queries.get(0)) { throw new ProcessEngineException("Invalid query usage: cannot set or() within 'or' query"); } HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl();
orQuery.isOrQueryActive = true; orQuery.queries = queries; queries.add(orQuery); return orQuery; } @Override public HistoricTaskInstanceQuery endOr() { if (!queries.isEmpty() && this != queries.get(queries.size()-1)) { throw new ProcessEngineException("Invalid query usage: cannot set endOr() before or()"); } return queries.get(0); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricTaskInstanceQueryImpl.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isDynamic() { return true; } public void fetchAlarmCount() { alarmCountInvocationAttempts++; log.trace("[{}] Fetching alarms: {}", cmdId, alarmCountInvocationAttempts); if (alarmCountInvocationAttempts <= maxAlarmQueriesPerRefreshInterval) { int newCount = (int) alarmService.countAlarmsByQuery(getTenantId(), getCustomerId(), query, entitiesIds); if (newCount != result) { result = newCount; sendWsMsg(new AlarmCountUpdate(cmdId, result)); } } else { log.trace("[{}] Ignore alarm count fetch due to rate limit: [{}] of maximum [{}]", cmdId, alarmCountInvocationAttempts, maxAlarmQueriesPerRefreshInterval); } } public void doFetchAlarmCount() { result = (int) alarmService.countAlarmsByQuery(getTenantId(), getCustomerId(), query, entitiesIds); sendWsMsg(new AlarmCountUpdate(cmdId, result)); } private EntityDataQuery buildEntityDataQuery() { EntityDataPageLink edpl = new EntityDataPageLink(maxEntitiesPerAlarmSubscription, 0, null, new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, ModelConstants.CREATED_TIME_PROPERTY))); return new EntityDataQuery(query.getEntityFilter(), edpl, null, null, query.getKeyFilters()); } private void resetInvocationCounter() { alarmCountInvocationAttempts = 0; } public void createAlarmSubscriptions() { for (EntityId entityId : entitiesIds) { createAlarmSubscriptionForEntity(entityId); }
} private void createAlarmSubscriptionForEntity(EntityId entityId) { int subIdx = sessionRef.getSessionSubIdSeq().incrementAndGet(); subToEntityIdMap.put(subIdx, entityId); log.trace("[{}][{}][{}] Creating alarms subscription for [{}] ", serviceId, cmdId, subIdx, entityId); TbAlarmsSubscription subscription = TbAlarmsSubscription.builder() .serviceId(serviceId) .sessionId(sessionRef.getSessionId()) .subscriptionId(subIdx) .tenantId(sessionRef.getSecurityCtx().getTenantId()) .entityId(entityId) .updateProcessor((sub, update) -> fetchAlarmCount()) .build(); localSubscriptionService.addSubscription(subscription, sessionRef); } public void clearAlarmSubscriptions() { if (subToEntityIdMap != null) { for (Integer subId : subToEntityIdMap.keySet()) { localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId); } subToEntityIdMap.clear(); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbAlarmCountSubCtx.java
2
请完成以下Java代码
public void infoJobExecutorDoesNotHandleHistoryCleanupJobs(ProcessEngineConfigurationImpl config) { logInfo("029", "JobExecutor is configured for priority range {}-{}. History cleanup jobs will not be handled, because they are outside the priority range ({}).", config.getJobExecutorPriorityRangeMin(), config.getJobExecutorPriorityRangeMax(), config.getHistoryCleanupJobPriority()); } public void infoJobExecutorDoesNotHandleBatchJobs(ProcessEngineConfigurationImpl config) { logInfo("030", "JobExecutor is configured for priority range {}-{}. Batch jobs will not be handled, because they are outside the priority range ({}).", config.getJobExecutorPriorityRangeMin(), config.getJobExecutorPriorityRangeMax(), config.getBatchJobPriority()); } public void debugFailedJobListenerSkipped(String jobId) { logDebug("031", "Failed job listener skipped for job {} because it's been already re-acquired", jobId); } public ProcessEngineException jobExecutorPriorityRangeException(String reason) { return new ProcessEngineException(exceptionMessage("031", "Invalid configuration for job executor priority range. Reason: {}", reason)); } public void failedAcquisitionLocks(String processEngine, AcquiredJobs acquiredJobs) { logDebug("033", "Jobs failed to Lock during Acquisition of jobs for the process engine '{}' : {}", processEngine, acquiredJobs.getNumberOfJobsFailedToLock()); } public void jobsToAcquire(String processEngine, int numJobsToAcquire) { logDebug("034", "Attempting to acquire {} jobs for the process engine '{}'", numJobsToAcquire, processEngine); } public void rejectedJobExecutions(String processEngine, int numJobsRejected) { logDebug("035", "Jobs execution rejections for the process engine '{}' : {}", processEngine, numJobsRejected); } public void availableJobExecutionThreads(String processEngine, int numAvailableThreads) {
logDebug("036", "Available job execution threads for the process engine '{}' : {}", processEngine, numAvailableThreads); } public void currentJobExecutions(String processEngine, int numExecutions) { logDebug("037", "Jobs currently in execution for the process engine '{}' : {}", processEngine, numExecutions); } public void numJobsInQueue(String processEngine, int numJobsInQueue, int maxQueueSize) { logDebug("038", "Jobs currently in queue to be executed for the process engine '{}' : {} (out of the max queue size : {})", processEngine, numJobsInQueue, maxQueueSize); } public void availableThreadsCalculationError() { logDebug("039", "Arithmetic exception occurred while computing remaining available thread count for logging."); } public void totalQueueCapacityCalculationError() { logDebug("040", "Arithmetic exception occurred while computing total queue capacity for logging."); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutorLogger.java
1
请完成以下Java代码
public PageDescriptor createNext() { return PageDescriptor.builder() .selectionUid(pageIdentifier.getSelectionUid()) .pageUid(UIDStringUtil.createNext()) .offset(offset + pageSize) .pageSize(pageSize) .totalSize(totalSize) .selectionTime(selectionTime) .build(); } @Builder private PageDescriptor( @NonNull final String selectionUid, @NonNull final String pageUid, final int offset, final int pageSize, final int totalSize, @NonNull final Instant selectionTime) { assumeNotEmpty(selectionUid, "Param selectionUid may not be empty"); assumeNotEmpty(pageUid, "Param selectionUid may not be empty"); this.pageIdentifier = PageIdentifier.builder() .selectionUid(selectionUid) .pageUid(pageUid) .build(); this.offset = offset; this.pageSize = pageSize; this.totalSize = totalSize; this.selectionTime = selectionTime;
} public PageDescriptor withSize(final int adjustedSize) { if (pageSize == adjustedSize) { return this; } return PageDescriptor.builder() .selectionUid(pageIdentifier.getSelectionUid()) .pageUid(pageIdentifier.getPageUid()) .offset(offset) .pageSize(adjustedSize) .totalSize(totalSize) .selectionTime(selectionTime) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\pagination\PageDescriptor.java
1
请完成以下Java代码
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final I_C_Commission_Share commissionShareRecord = getCommissionShareRecord(ic); final SOTrx soTrx = SOTrx.ofBoolean(commissionShareRecord.isSOTrx()); ic.setBill_BPartner_ID(soTrx.isSales() ? commissionShareRecord.getC_BPartner_Payer_ID() : commissionShareRecord.getC_BPartner_SalesRep_ID()); } @Override public String toString() { return "CommissionShareHandler"; } @NonNull private DocTypeId getDoctypeId(@NonNull final I_C_Commission_Share shareRecord) { final CommissionConstants.CommissionDocType commissionDocType = getCommissionDocType(shareRecord); return docTypeDAO.getDocTypeId( DocTypeQuery.builder() .docBaseType(commissionDocType.getDocBaseType()) .docSubType(DocSubType.ofCode(commissionDocType.getDocSubType())) .adClientId(shareRecord.getAD_Client_ID()) .adOrgId(shareRecord.getAD_Org_ID()) .build()); } @NonNull private CommissionConstants.CommissionDocType getCommissionDocType(@NonNull final I_C_Commission_Share shareRecord) { if (!shareRecord.isSOTrx())
{ // note that SOTrx is about the share record's settlement. // I.e. if the sales-rep receives money from the commission, then it's a purchase order trx return CommissionConstants.CommissionDocType.COMMISSION; } else if (shareRecord.getC_LicenseFeeSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.LICENSE_COMMISSION; } else if (shareRecord.getC_MediatedCommissionSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.MEDIATED_COMMISSION; } throw new AdempiereException("Unhandled commission type! ") .appendParametersToMessage() .setParameter("C_CommissionShare_ID", shareRecord.getC_Commission_Share_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\invoicecandidate\CommissionShareHandler.java
1
请完成以下Java代码
public class X_MSV3_BestellungAntwort extends org.compiere.model.PO implements I_MSV3_BestellungAntwort, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -2094677833L; /** Standard Constructor */ public X_MSV3_BestellungAntwort (Properties ctx, int MSV3_BestellungAntwort_ID, String trxName) { super (ctx, MSV3_BestellungAntwort_ID, trxName); /** if (MSV3_BestellungAntwort_ID == 0) { setMSV3_BestellungAntwort_ID (0); setMSV3_Id (null); } */ } /** Load Constructor */ public X_MSV3_BestellungAntwort (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set BestellSupportId. @param MSV3_BestellSupportId BestellSupportId */ @Override public void setMSV3_BestellSupportId (int MSV3_BestellSupportId) { set_Value (COLUMNNAME_MSV3_BestellSupportId, Integer.valueOf(MSV3_BestellSupportId)); } /** Get BestellSupportId. @return BestellSupportId */ @Override public int getMSV3_BestellSupportId () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellSupportId); if (ii == null) return 0; return ii.intValue(); } /** Set MSV3_BestellungAntwort. @param MSV3_BestellungAntwort_ID MSV3_BestellungAntwort */ @Override public void setMSV3_BestellungAntwort_ID (int MSV3_BestellungAntwort_ID) { if (MSV3_BestellungAntwort_ID < 1) set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAntwort_ID, null); else set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAntwort_ID, Integer.valueOf(MSV3_BestellungAntwort_ID)); } /** Get MSV3_BestellungAntwort. @return MSV3_BestellungAntwort */ @Override public int getMSV3_BestellungAntwort_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAntwort_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Id. @param MSV3_Id Id */ @Override public void setMSV3_Id (java.lang.String MSV3_Id) { set_Value (COLUMNNAME_MSV3_Id, MSV3_Id); } /** Get Id. @return Id */ @Override public java.lang.String getMSV3_Id () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id); } /** Set NachtBetrieb. @param MSV3_NachtBetrieb NachtBetrieb */ @Override public void setMSV3_NachtBetrieb (boolean MSV3_NachtBetrieb) { set_Value (COLUMNNAME_MSV3_NachtBetrieb, Boolean.valueOf(MSV3_NachtBetrieb)); } /** Get NachtBetrieb. @return NachtBetrieb */ @Override public boolean isMSV3_NachtBetrieb () { Object oo = get_Value(COLUMNNAME_MSV3_NachtBetrieb); 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.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAntwort.java
1
请在Spring Boot框架中完成以下Java代码
public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getZkServers() { return zkServers;
} public void setZkServers(String zkServers) { this.zkServers = zkServers; } public List<String> getDestination() { return destination; } public void setDestination(List<String> destination) { this.destination = destination; } }
repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\canal\config\CanalProperties.java
2
请完成以下Java代码
public boolean equalsByPriceRelevantFields(@NonNull final PricingConditionsBreak reference) { if (this == reference) { return true; } return Objects.equals(priceSpecification, reference.priceSpecification) && Objects.equals(coalesce(discount, Percent.ZERO), coalesce(reference.discount, Percent.ZERO)) && Objects.equals(coalesce(bpartnerFlatDiscount, Percent.ZERO), coalesce(reference.bpartnerFlatDiscount, Percent.ZERO)) && Objects.equals(paymentTermIdOrNull, reference.paymentTermIdOrNull) && Objects.equals(coalesce(paymentDiscountOverrideOrNull, Percent.ZERO), coalesce(reference.paymentDiscountOverrideOrNull, Percent.ZERO)) && Objects.equals(derivedPaymentTermIdOrNull, reference.derivedPaymentTermIdOrNull); } public boolean equalsByMatchCriteria(@NonNull final PricingConditionsBreak reference) { if (this == reference) { return true; } return Objects.equals(matchCriteria, reference.matchCriteria); } public boolean isTemporaryPricingConditionsBreak() { return hasChanges || id == null; } public PricingConditionsBreak toTemporaryPricingConditionsBreak() { if (isTemporaryPricingConditionsBreak()) { return this; } return toBuilder().id(null).build();
} public PricingConditionsBreak toTemporaryPricingConditionsBreakIfPriceRelevantFieldsChanged(@NonNull final PricingConditionsBreak reference) { if (isTemporaryPricingConditionsBreak()) { return this; } if (equalsByPriceRelevantFields(reference)) { return this; } return toTemporaryPricingConditionsBreak(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreak.java
1
请完成以下Java代码
public class HitPolicyOutputOrder extends AbstractHitPolicy implements ComposeDecisionResultBehavior { public HitPolicyOutputOrder() { super(true); } @Override public String getHitPolicyName() { return HitPolicy.OUTPUT_ORDER.getValue(); } @Override public void composeDecisionResults(final ELExecutionContext executionContext) { List<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values()); boolean outputValuesPresent = false; for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) { List<Object> outputValues = entry.getValue(); if (outputValues != null && !outputValues.isEmpty()) { outputValuesPresent = true; break; } } if (!outputValuesPresent) { String hitPolicyViolatedMessage = String.format("HitPolicy: %s violated; no output values present", getHitPolicyName()); if (CommandContextUtil.getDmnEngineConfiguration().isStrictMode()) { throw new FlowableException(hitPolicyViolatedMessage); } else { executionContext.getAuditContainer().setValidationMessage(hitPolicyViolatedMessage); } }
// sort on predefined list(s) of output values ruleResults.sort((o1, o2) -> { CompareToBuilder compareToBuilder = new CompareToBuilder(); for (Map.Entry<String, List<Object>> entry : executionContext.getOutputValues().entrySet()) { List<Object> outputValues = entry.getValue(); if (outputValues != null && !outputValues.isEmpty()) { compareToBuilder.append(o1.get(entry.getKey()), o2.get(entry.getKey()), new OutputOrderComparator<>(outputValues.toArray(new Comparable[outputValues.size()]))); compareToBuilder.toComparison(); } } return compareToBuilder.toComparison(); }); updateStackWithDecisionResults(ruleResults, executionContext); DecisionExecutionAuditContainer auditContainer = executionContext.getAuditContainer(); auditContainer.setDecisionResult(ruleResults); auditContainer.setMultipleResults(true); } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyOutputOrder.java
1
请完成以下Java代码
public class SendTaskValidator extends ExternalInvocationTaskValidator { @Override protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) { List<SendTask> sendTasks = process.findFlowElementsOfType(SendTask.class); for (SendTask sendTask : sendTasks) { // Verify implementation if ( StringUtils.isEmpty(sendTask.getType()) && !ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(sendTask.getImplementationType()) ) { addError(errors, Problems.SEND_TASK_INVALID_IMPLEMENTATION, process, sendTask); } // Verify type if (StringUtils.isNotEmpty(sendTask.getType())) { if ( !sendTask.getType().equalsIgnoreCase("mail") && !sendTask.getType().equalsIgnoreCase("mule") && !sendTask.getType().equalsIgnoreCase("camel") ) { addError(errors, Problems.SEND_TASK_INVALID_TYPE, process, sendTask); } if (sendTask.getType().equalsIgnoreCase("mail")) { validateFieldDeclarationsForEmail(process, sendTask, sendTask.getFieldExtensions(), errors); } } // Web service verifyWebservice(bpmnModel, process, sendTask, errors); } } protected void verifyWebservice( BpmnModel bpmnModel, Process process, SendTask sendTask,
List<ValidationError> errors ) { if ( ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE.equalsIgnoreCase(sendTask.getImplementationType()) && StringUtils.isNotEmpty(sendTask.getOperationRef()) ) { boolean operationFound = false; if (bpmnModel.getInterfaces() != null && !bpmnModel.getInterfaces().isEmpty()) { for (Interface bpmnInterface : bpmnModel.getInterfaces()) { if (bpmnInterface.getOperations() != null && !bpmnInterface.getOperations().isEmpty()) { for (Operation operation : bpmnInterface.getOperations()) { if (operation.getId() != null && operation.getId().equals(sendTask.getOperationRef())) { operationFound = true; } } } } } if (!operationFound) { addError(errors, Problems.SEND_TASK_WEBSERVICE_INVALID_OPERATION_REF, process, sendTask); } } } }
repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\validator\impl\SendTaskValidator.java
1
请完成以下Java代码
public boolean isMatching(@NonNull final CampaignPrice price) { if (!ProductId.equals(price.getProductId(), getProductId())) { return false; } if (price.getBpartnerId() != null && !BPartnerId.equals(price.getBpartnerId(), getBpartnerId())) { return false; } if (price.getBpGroupId() != null && !BPGroupId.equals(price.getBpGroupId(), getBpGroupId())) { return false; } if (price.getPricingSystemId() != null && !PricingSystemId.equals(price.getPricingSystemId(), getPricingSystemId())) { return false; }
if (!CountryId.equals(price.getCountryId(), getCountryId())) { return false; } if (!CurrencyId.equals(price.getCurrencyId(), getCurrencyId())) { return false; } if (!price.getValidRange().contains(getDate())) { return false; } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\CampaignPriceQuery.java
1
请完成以下Spring Boot application配置
spring.application.name=chapter74 elasticjob.reg-center.server-lists=localhost:2181 elasticjob.reg-center.namespace=${spring.application.name} elasticjob.jobs.my-simple-job.elastic-job-class=com.didispace.chapter74.MySimpleJob e
lasticjob.jobs.my-simple-job.cron=0/5 * * * * ? elasticjob.jobs.my-simple-job.sharding-total-count=1
repos\SpringBoot-Learning-master\2.x\chapter7-4\src\main\resources\application.properties
2
请完成以下Java代码
boolean isReadLockAvailable() { return readLock.tryLock(); } public static void main(String[] args) throws InterruptedException { final int threadCount = 3; final ExecutorService service = Executors.newFixedThreadPool(threadCount); SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock(); service.execute(new Thread(new Writer(object), "Writer")); service.execute(new Thread(new Reader(object), "Reader1")); service.execute(new Thread(new Reader(object), "Reader2")); service.shutdown(); } private static class Reader implements Runnable { SynchronizedHashMapWithRWLock object; Reader(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { object.get("key" + i);
} } } private static class Writer implements Runnable { SynchronizedHashMapWithRWLock object; public Writer(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { try { object.put("key" + i, "value" + i); sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SynchronizedHashMapWithRWLock.java
1
请完成以下Java代码
private DhlCustomsItem toDhlCustomsItem(@NonNull final PackageItem packageItem) { final ProductId productId = packageItem.getProductId(); final I_M_Product product = productDAO.getById(productId); final BigDecimal weightInKg = computeNominalGrossWeightInKg(packageItem).orElse(BigDecimal.ZERO); Quantity packagedQuantity; try { packagedQuantity = uomConversionBL.convertQuantityTo(packageItem.getQuantity(), productId, UomId.EACH); } catch (final NoUOMConversionException exception) { //can't convert to EACH, so we don't have an exact number. Just put 1 packagedQuantity = Quantitys.of(1, UomId.EACH); } final I_C_OrderLine orderLine = orderDAO.getOrderLineById(packageItem.getOrderLineId()); final CurrencyCode currencyCode = currencyRepository.getCurrencyCodeById(CurrencyId.ofRepoId(orderLine.getC_Currency_ID())); return DhlCustomsItem.builder() .itemDescription(product.getName())
.weightInKg(weightInKg) .packagedQuantity(packagedQuantity.intValueExact()) .itemValue(Amount.of(orderLine.getPriceEntered(), currencyCode)) .build(); } private Optional<BigDecimal> computeNominalGrossWeightInKg(final PackageItem packageItem) { final ProductId productId = packageItem.getProductId(); final Quantity quantity = packageItem.getQuantity(); return productBL.computeGrossWeight(productId, quantity) .map(weight -> uomConversionBL.convertToKilogram(weight, productId)) .map(Quantity::getAsBigDecimal); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlDeliveryOrderService.java
1
请完成以下Java代码
public static PickingJobCandidateProducts newInstance() {return new PickingJobCandidateProducts(ImmutableMap.of());} public static PickingJobCandidateProducts ofList(final List<PickingJobCandidateProduct> list) { return new PickingJobCandidateProducts(Maps.uniqueIndex(list, PickingJobCandidateProduct::getProductId)); } public static PickingJobCandidateProducts of(@NonNull final PickingJobCandidateProduct product) { return new PickingJobCandidateProducts(ImmutableMap.of(product.getProductId(), product)); } public static Collector<PickingJobCandidateProduct, ?, PickingJobCandidateProducts> collect() { return GuavaCollectors.collectUsingListAccumulator(PickingJobCandidateProducts::ofList); } public Set<ProductId> getProductIds() {return byProductId.keySet();} @Override @NonNull public Iterator<PickingJobCandidateProduct> iterator() {return byProductId.values().iterator();} public OptionalBoolean hasQtyAvailableToPick() { final QtyAvailableStatus qtyAvailableStatus = getQtyAvailableStatus().orElse(null); return qtyAvailableStatus == null ? OptionalBoolean.UNKNOWN : OptionalBoolean.ofBoolean(qtyAvailableStatus.isPartialOrFullyAvailable()); } public Optional<QtyAvailableStatus> getQtyAvailableStatus() { Optional<QtyAvailableStatus> qtyAvailableStatus = this._qtyAvailableStatus; //noinspection OptionalAssignedToNull if (qtyAvailableStatus == null) { qtyAvailableStatus = this._qtyAvailableStatus = computeQtyAvailableStatus(); } return qtyAvailableStatus; } private Optional<QtyAvailableStatus> computeQtyAvailableStatus() { return QtyAvailableStatus.computeOfLines(byProductId.values(), product -> product.getQtyAvailableStatus().orElse(null)); } public PickingJobCandidateProducts updatingEachProduct(@NonNull UnaryOperator<PickingJobCandidateProduct> updater) { if (byProductId.isEmpty()) { return this; } final ImmutableMap<ProductId, PickingJobCandidateProduct> byProductIdNew = byProductId.values() .stream()
.map(updater) .collect(ImmutableMap.toImmutableMap(PickingJobCandidateProduct::getProductId, product -> product)); return Objects.equals(this.byProductId, byProductIdNew) ? this : new PickingJobCandidateProducts(byProductIdNew); } @Nullable public ProductId getSingleProductIdOrNull() { return singleProduct != null ? singleProduct.getProductId() : null; } @Nullable public Quantity getSingleQtyToDeliverOrNull() { return singleProduct != null ? singleProduct.getQtyToDeliver() : null; } @Nullable public Quantity getSingleQtyAvailableToPickOrNull() { return singleProduct != null ? singleProduct.getQtyAvailableToPick() : null; } @Nullable public ITranslatableString getSingleProductNameOrNull() { return singleProduct != null ? singleProduct.getProductName() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobCandidateProducts.java
1
请完成以下Java代码
public Mono<Account> findById(long id) { return Mono.from(connectionFactory.create()) .flatMap(c -> Mono.from(c.createStatement("select id,iban,balance from Account where id = $1") .bind("$1", id) .execute()) .doFinally((st) -> close(c))) .map(result -> result.map((row, meta) -> new Account(row.get("id", Long.class), row.get("iban", String.class), row.get("balance", BigDecimal.class)))) .flatMap( p -> Mono.from(p)); } public Flux<Account> findAll() { return Mono.from(connectionFactory.create()) .flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account") .execute()) .doFinally((st) -> close(c))) .flatMapMany(result -> Flux.from(result.map((row, meta) -> { Account acc = new Account(); acc.setId(row.get("id", Long.class)); acc.setIban(row.get("iban", String.class)); acc.setBalance(row.get("balance", BigDecimal.class)); return acc; }))); } public Mono<Account> createAccount(Account account) { return Mono.from(connectionFactory.create()) .flatMap(c -> Mono.from(c.beginTransaction()) .then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)")
.bind("$1", account.getIban()) .bind("$2", account.getBalance()) .returnGeneratedValues("id") .execute())) .map(result -> result.map((row, meta) -> new Account(row.get("id", Long.class), account.getIban(), account.getBalance()))) .flatMap(pub -> Mono.from(pub)) .delayUntil(r -> c.commitTransaction()) .doFinally((st) -> c.close())); } private <T> Mono<T> close(Connection connection) { return Mono.from(connection.close()) .then(Mono.empty()); } }
repos\tutorials-master\persistence-modules\r2dbc\src\main\java\com\baeldung\examples\r2dbc\ReactiveAccountDao.java
1
请完成以下Java代码
public KotlinPropertyDeclaration emptyValue() { return new KotlinPropertyDeclaration(this); } /** * Sets the given value. * @param valueCode the code for the value * @return the property declaration */ public KotlinPropertyDeclaration value(CodeBlock valueCode) { this.valueCode = valueCode; return new KotlinPropertyDeclaration(this); } } /** * Builder for {@code val} properties. */ public static final class ValBuilder extends Builder<ValBuilder> { private ValBuilder(String name) { super(name, true); } @Override protected ValBuilder self() { return this; } } /** * Builder for {@code val} properties. */ public static final class VarBuilder extends Builder<VarBuilder> { private VarBuilder(String name) { super(name, false); } /** * Sets no value. * @return the property declaration */ public KotlinPropertyDeclaration empty() { return new KotlinPropertyDeclaration(this); } @Override protected VarBuilder self() { return this; } } /** * Builder for a property accessor. * * @param <T> the type of builder */ public static final class AccessorBuilder<T extends Builder<T>> { private final AnnotationContainer annotations = new AnnotationContainer(); private CodeBlock code; private final T parent; private final Consumer<Accessor> accessorFunction; private AccessorBuilder(T parent, Consumer<Accessor> accessorFunction) { this.parent = parent; this.accessorFunction = accessorFunction; } /** * Adds an annotation. * @param className the class name of the annotation * @return this for method chaining */ public AccessorBuilder<?> withAnnotation(ClassName className) { return withAnnotation(className, null); } /** * Adds an annotation. * @param className the class name of the annotation * @param annotation configurer for the annotation * @return this for method chaining */ public AccessorBuilder<?> withAnnotation(ClassName className, Consumer<Annotation.Builder> annotation) { this.annotations.addSingle(className, annotation);
return this; } /** * Sets the body. * @param code the code for the body * @return this for method chaining */ public AccessorBuilder<?> withBody(CodeBlock code) { this.code = code; return this; } /** * Builds the accessor. * @return the parent getter / setter */ public T buildAccessor() { this.accessorFunction.accept(new Accessor(this)); return this.parent; } } static final class Accessor implements Annotatable { private final AnnotationContainer annotations; private final CodeBlock code; Accessor(AccessorBuilder<?> builder) { this.annotations = builder.annotations.deepCopy(); this.code = builder.code; } CodeBlock getCode() { return this.code; } @Override public AnnotationContainer annotations() { return this.annotations; } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
public ConfigDataResource getResource() { return this.resource; } /** * Return the original location that was resolved to determine the resource. * @return the location or {@code null} if no location is available */ public @Nullable ConfigDataLocation getLocation() { return this.location; } @Override public @Nullable Origin getOrigin() { return Origin.from(this.location); } @Override public String getReferenceDescription() { return getReferenceDescription(this.resource, this.location); } /** * Create a new {@link ConfigDataResourceNotFoundException} instance with a location. * @param location the location to set * @return a new {@link ConfigDataResourceNotFoundException} instance */ ConfigDataResourceNotFoundException withLocation(ConfigDataLocation location) { return new ConfigDataResourceNotFoundException(this.resource, location, getCause()); } private static String getMessage(ConfigDataResource resource, @Nullable ConfigDataLocation location) { return String.format("Config data %s cannot be found", getReferenceDescription(resource, location)); } private static String getReferenceDescription(ConfigDataResource resource, @Nullable ConfigDataLocation location) { String description = String.format("resource '%s'", resource); if (location != null) { description += String.format(" via location '%s'", location); } return description; } /**
* Throw a {@link ConfigDataNotFoundException} if the specified {@link Path} does not * exist. * @param resource the config data resource * @param pathToCheck the path to check */ public static void throwIfDoesNotExist(ConfigDataResource resource, Path pathToCheck) { throwIfNot(resource, Files.exists(pathToCheck)); } /** * Throw a {@link ConfigDataNotFoundException} if the specified {@link File} does not * exist. * @param resource the config data resource * @param fileToCheck the file to check */ public static void throwIfDoesNotExist(ConfigDataResource resource, File fileToCheck) { throwIfNot(resource, fileToCheck.exists()); } /** * Throw a {@link ConfigDataNotFoundException} if the specified {@link Resource} does * not exist. * @param resource the config data resource * @param resourceToCheck the resource to check */ public static void throwIfDoesNotExist(ConfigDataResource resource, Resource resourceToCheck) { throwIfNot(resource, resourceToCheck.exists()); } private static void throwIfNot(ConfigDataResource resource, boolean check) { if (!check) { throw new ConfigDataResourceNotFoundException(resource); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataResourceNotFoundException.java
2
请完成以下Java代码
public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } /** * Return the script info, if present. * <p> * ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when * implementationType is 'script'. * </p> */ @Override public ScriptInfo getScriptInfo() { return scriptInfo; } /** * Sets the script info * * @see #getScriptInfo() */ @Override public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo;
} @Override public FlowableListener clone() { FlowableListener clone = new FlowableListener(); clone.setValues(this); return clone; } public void setValues(FlowableListener otherListener) { super.setValues(otherListener); setEvent(otherListener.getEvent()); setImplementation(otherListener.getImplementation()); setImplementationType(otherListener.getImplementationType()); if (otherListener.getScriptInfo() != null) { setScriptInfo(otherListener.getScriptInfo().clone()); } fieldExtensions = new ArrayList<>(); if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherListener.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } setOnTransaction(otherListener.getOnTransaction()); setCustomPropertiesResolverImplementationType(otherListener.getCustomPropertiesResolverImplementationType()); setCustomPropertiesResolverImplementation(otherListener.getCustomPropertiesResolverImplementation()); } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowableListener.java
1
请完成以下Java代码
public void deleteWithRelatedData() { delete(); } // getters //////////////////////////////////////////// @Override public String getId() { return id; } public Set<String> getIds() { return ids; } public String getDecisionDefinitionId() { return decisionDefinitionId; } public String getDeploymentId() { return deploymentId; } public String getDecisionKey() { return decisionKey; } public String getInstanceId() { return instanceId; } public String getExecutionId() { return executionId; } public String getActivityId() { return activityId; }
public String getScopeType() { return scopeType; } public boolean isWithoutScopeType() { return withoutScopeType; } public String getProcessInstanceIdWithChildren() { return processInstanceIdWithChildren; } public String getCaseInstanceIdWithChildren() { return caseInstanceIdWithChildren; } public Boolean getFailed() { return failed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\HistoricDecisionExecutionQueryImpl.java
1
请完成以下Java代码
public Object execute(CommandContext commandContext) { AttachmentEntity attachment = commandContext.getAttachmentEntityManager().findById(attachmentId); String processInstanceId = attachment.getProcessInstanceId(); String processDefinitionId = null; if (attachment.getProcessInstanceId() != null) { ExecutionEntity process = commandContext.getExecutionEntityManager().findById(processInstanceId); if (process != null) { processDefinitionId = process.getProcessDefinitionId(); } } executeInternal(commandContext, attachment, processInstanceId, processDefinitionId); return null; } protected void executeInternal( CommandContext commandContext, AttachmentEntity attachment, String processInstanceId, String processDefinitionId ) { commandContext.getAttachmentEntityManager().delete(attachment, false); if (attachment.getContentId() != null) { commandContext.getByteArrayEntityManager().deleteByteArrayById(attachment.getContentId()); } if (attachment.getTaskId() != null) { commandContext .getHistoryManager() .createAttachmentComment( attachment.getTaskId(),
attachment.getProcessInstanceId(), attachment.getName(), false ); } if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext .getProcessEngineConfiguration() .getEventDispatcher() .dispatchEvent( ActivitiEventBuilder.createEntityEvent( ActivitiEventType.ENTITY_DELETED, attachment, processInstanceId, processInstanceId, processDefinitionId ) ); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteAttachmentCmd.java
1
请完成以下Java代码
public void afterChange(final I_DD_Order_Candidate record) { final DDOrderCandidateData data = toDDOrderCandidateData(record); final UserId userId = UserId.ofRepoId(record.getUpdatedBy()); materialEventService.enqueueEventAfterNextCommit(DDOrderCandidateUpdatedEvent.of(data, userId)); } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE }) public void beforeDelete(final I_DD_Order_Candidate record) { ddOrderCandidateAllocRepository.deleteByQuery(DeleteDDOrderCandidateAllocQuery.builder() .ddOrderCandidateId(DDOrderCandidateId.ofRepoId(record.getDD_Order_Candidate_ID())) .build()); final DDOrderCandidateData data = toDDOrderCandidateData(record); final UserId userId = UserId.ofRepoId(record.getUpdatedBy());
materialEventService.enqueueEventAfterNextCommit(DDOrderCandidateDeletedEvent.of(data, userId)); } private DDOrderCandidateData toDDOrderCandidateData(final I_DD_Order_Candidate record) { final DDOrderCandidate candidate = DDOrderCandidateRepository.fromRecord(record); return candidate.toDDOrderCandidateData() .fromWarehouseMinMaxDescriptor(getFromWarehouseMinMaxDescriptor(candidate)) .build(); } private MinMaxDescriptor getFromWarehouseMinMaxDescriptor(final DDOrderCandidate candidate) { return replenishInfoRepository.getBy(ReplenishInfo.Identifier.of(candidate.getSourceWarehouseId(), candidate.getSourceLocatorId(), candidate.getProductId())).toMinMaxDescriptor(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\material_dispo\interceptor\DD_Order_Candidate.java
1
请完成以下Java代码
public POSPayment changingStatusToSuccessful() { if (paymentProcessingStatus == POSPaymentProcessingStatus.SUCCESSFUL) { return this; } return toBuilder().paymentProcessingStatus(POSPaymentProcessingStatus.SUCCESSFUL).build(); } public POSPayment changingStatusToDeleted() { if (isDeleted()) { return this; } assertAllowDelete(); return toBuilder().paymentProcessingStatus(POSPaymentProcessingStatus.DELETED).build(); } public POSPayment changingStatusFromRemote(@NonNull final POSPaymentProcessResponse response) { paymentMethod.assertCard(); // NOTE: when changing status from remote we cannot validate if the status transition is OK // we have to accept what we have on remote. return toBuilder() .paymentProcessingStatus(response.getStatus()) .cardProcessingDetails(POSPaymentCardProcessingDetails.builder() .config(response.getConfig()) .transactionId(response.getTransactionId()) .summary(response.getSummary()) .cardReader(response.getCardReader()) .build()) .build(); } public POSPayment withPaymentReceipt(@Nullable final PaymentId paymentReceiptId) { if (PaymentId.equals(this.paymentReceiptId, paymentReceiptId)) { return this; } if (paymentReceiptId != null && !paymentProcessingStatus.isSuccessful()) { throw new AdempiereException("Cannot set a payment receipt if status is not successful"); } if (this.paymentReceiptId != null && paymentReceiptId != null) { throw new AdempiereException("Changing the payment receipt is not allowed"); } return toBuilder().paymentReceiptId(paymentReceiptId).build(); }
public POSPayment withCashTenderedAmount(@NonNull final BigDecimal cashTenderedAmountBD) { paymentMethod.assertCash(); Check.assume(cashTenderedAmountBD.signum() > 0, "Cash Tendered Amount must be positive"); final Money cashTenderedAmountNew = Money.of(cashTenderedAmountBD, this.cashTenderedAmount.getCurrencyId()); if (Money.equals(this.cashTenderedAmount, cashTenderedAmountNew)) { return this; } return toBuilder().cashTenderedAmount(cashTenderedAmountNew).build(); } public POSPayment withCardPayAmount(@NonNull final BigDecimal cardPayAmountBD) { paymentMethod.assertCard(); Check.assume(cardPayAmountBD.signum() > 0, "Card Pay Amount must be positive"); final Money amountNew = Money.of(cardPayAmountBD, this.amount.getCurrencyId()); if (Money.equals(this.amount, amountNew)) { return this; } return toBuilder().amount(amountNew).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPayment.java
1
请完成以下Java代码
private static String formatDateCell(final Object value, final DateTimeFormatter dateFormatter) { if (value == null) { return null; } else if (value instanceof java.util.Date) { final java.util.Date date = (java.util.Date)value; return dateFormatter.format(TimeUtil.asLocalDate(date)); } else if (value instanceof TemporalAccessor) { TemporalAccessor temporal = (TemporalAccessor)value; return dateFormatter.format(temporal); } else
{ throw new AdempiereException("Cannot convert/format value to Date: " + value + " (" + value.getClass() + ")"); } } private static String formatNumberCell(final Object value, final ThreadLocalDecimalFormatter numberFormatter) { if (value == null) { return null; } return numberFormatter.format(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVCsvExporter.java
1