instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public void save() { } public static String constantField() { return constantField; } public void saveFirstName(String firstName) { this.firstName = firstName; } public Long multiplyValue(LambdaExpression expr) { Long theResult = (Long) expr.invoke(FacesContext.getCurrentInstance() .getELContext(), pageCounter); return theResult; } public void saveByELEvaluation() { firstName = (String) evaluateEL("#{firstName.value}", String.class); FacesContext ctx = FacesContext.getCurrentInstance(); FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName); theMessage.setSeverity(FacesMessage.SEVERITY_INFO); ctx.addMessage(null, theMessage); } private Object evaluateEL(String elExpression, Class<?> clazz) { Object toReturn = null; FacesContext ctx = FacesContext.getCurrentInstance(); Application app = ctx.getApplication(); toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz); return toReturn; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; }
/** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the pageDescription */ public String getPageDescription() { return pageDescription; } /** * @param pageDescription the pageDescription to set */ public void setPageDescription(String pageDescription) { this.pageDescription = pageDescription; } /** * @return the pageCounter */ public int getPageCounter() { return pageCounter; } /** * @param pageCounter the pageCounter to set */ public void setPageCounter(int pageCounter) { this.pageCounter = pageCounter; } }
repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\ELSampleBean.java
2
请在Spring Boot框架中完成以下Java代码
public void setDOCUMENTID(String value) { this.documentid = value; } /** * Gets the value of the linenumber property. * * @return * possible object is * {@link String } * */ public String getLINENUMBER() { return linenumber; } /** * Sets the value of the linenumber property. * * @param value * allowed object is * {@link String } * */ public void setLINENUMBER(String value) { this.linenumber = value; } /** * Gets the value of the amountqual property. * * @return * possible object is * {@link String } * */ public String getAMOUNTQUAL() { return amountqual; } /** * Sets the value of the amountqual property. * * @param value * allowed object is * {@link String } * */ public void setAMOUNTQUAL(String value) { this.amountqual = value; } /** * Gets the value of the amount property. * * @return * possible object is * {@link String }
* */ public String getAMOUNT() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link String } * */ public void setAMOUNT(String value) { this.amount = value; } /** * Gets the value of the currency property. * * @return * possible object is * {@link String } * */ public String getCURRENCY() { return currency; } /** * Sets the value of the currency property. * * @param value * allowed object is * {@link String } * */ public void setCURRENCY(String value) { this.currency = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DAMOU1.java
2
请完成以下Java代码
public class DeleteHistoricDecisionInstanceBatchConfigurationJsonConverter extends AbstractBatchConfigurationObjectConverter<BatchConfiguration> { public static final DeleteHistoricDecisionInstanceBatchConfigurationJsonConverter INSTANCE = new DeleteHistoricDecisionInstanceBatchConfigurationJsonConverter(); public static final String HISTORIC_DECISION_INSTANCE_IDS = "historicDecisionInstanceIds"; public static final String HISTORIC_DECISION_INSTANCE_ID_MAPPINGS = "historicDecisionInstanceIdMappingss"; @Override public JsonObject writeConfiguration(BatchConfiguration configuration) { JsonObject json = JsonUtil.createObject(); JsonUtil.addListField(json, HISTORIC_DECISION_INSTANCE_IDS, configuration.getIds()); JsonUtil.addListField(json, HISTORIC_DECISION_INSTANCE_ID_MAPPINGS, DeploymentMappingJsonConverter.INSTANCE, configuration.getIdMappings()); return json; }
@Override public BatchConfiguration readConfiguration(JsonObject json) { BatchConfiguration configuration = new BatchConfiguration(readDecisionInstanceIds(json), readMappings(json)); return configuration; } protected List<String> readDecisionInstanceIds(JsonObject jsonNode) { return JsonUtil.asStringList(JsonUtil.getArray(jsonNode, HISTORIC_DECISION_INSTANCE_IDS)); } protected DeploymentMappings readMappings(JsonObject jsonNode) { return JsonUtil.asList(JsonUtil.getArray(jsonNode, HISTORIC_DECISION_INSTANCE_ID_MAPPINGS), DeploymentMappingJsonConverter.INSTANCE, DeploymentMappings::new); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\batch\DeleteHistoricDecisionInstanceBatchConfigurationJsonConverter.java
1
请完成以下Java代码
protected void prepareContext(Host host, TomcatHttpHandlerAdapter servlet) { File docBase = createTempDir("tomcat-docbase"); TomcatEmbeddedContext context = new TomcatEmbeddedContext(); WebResourceRoot resourceRoot = new StandardRoot(context); ignoringNoSuchMethodError(() -> resourceRoot.setReadOnly(true)); context.setResources(resourceRoot); context.setPath(""); context.setDocBase(docBase.getAbsolutePath()); context.addLifecycleListener(new Tomcat.FixContextListener()); ClassLoader parentClassLoader = ClassUtils.getDefaultClassLoader(); context.setParentClassLoader(parentClassLoader); skipAllTldScanning(context); WebappLoader loader = new WebappLoader(); loader.setLoaderInstance(new TomcatEmbeddedWebappClassLoader(parentClassLoader)); loader.setDelegate(true); context.setLoader(loader); Tomcat.addServlet(context, "httpHandlerServlet", servlet).setAsyncSupported(true); context.addServletMappingDecoded("/", "httpHandlerServlet"); host.addChild(context); configureContext(context); } private void ignoringNoSuchMethodError(Runnable method) { try { method.run(); } catch (NoSuchMethodError ex) { } } private void skipAllTldScanning(TomcatEmbeddedContext context) { StandardJarScanFilter filter = new StandardJarScanFilter(); filter.setTldSkip("*.jar"); context.getJarScanner().setJarScanFilter(filter); } /** * Configure the Tomcat {@link Context}. * @param context the Tomcat context */
protected void configureContext(Context context) { this.getContextLifecycleListeners().forEach(context::addLifecycleListener); new DisableReferenceClearingContextCustomizer().customize(context); this.getContextCustomizers().forEach((customizer) -> customizer.customize(context)); } /** * Factory method called to create the {@link TomcatWebServer}. Subclasses can * override this method to return a different {@link TomcatWebServer} or apply * additional processing to the Tomcat server. * @param tomcat the Tomcat server. * @return a new {@link TomcatWebServer} instance */ protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown()); } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\reactive\TomcatReactiveWebServerFactory.java
1
请完成以下Java代码
public void setParent_ID (final int Parent_ID) { if (Parent_ID < 1) set_ValueNoCheck (COLUMNNAME_Parent_ID, null); else set_ValueNoCheck (COLUMNNAME_Parent_ID, Parent_ID); } @Override public int getParent_ID() { return get_ValueAsInt(COLUMNNAME_Parent_ID); } @Override public void setPostActual (final boolean PostActual) { set_Value (COLUMNNAME_PostActual, PostActual); } @Override public boolean isPostActual() { return get_ValueAsBoolean(COLUMNNAME_PostActual); } @Override public void setPostBudget (final boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, PostBudget); } @Override public boolean isPostBudget() { return get_ValueAsBoolean(COLUMNNAME_PostBudget); } @Override public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() { return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance); } @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical); } @Override public void setSeqNo (final int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } @Override
public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ElementValue.java
1
请在Spring Boot框架中完成以下Java代码
private List<JsonRequestProductUpsertItem> getProductItems() { return mapProductToProductRequestItem() .map(ImmutableList::of) .orElseGet(ImmutableList::of); } @NonNull private Optional<JsonRequestProductUpsertItem> mapProductToProductRequestItem() { if (product.getName() == null) { return Optional.empty(); } routeContext.setNextImportStartingTimestamp(product.getUpdatedAtNonNull().toInstant()); final String productIdentifier = formatExternalId(product.getId()); final JsonRequestProduct jsonRequestProduct = new JsonRequestProduct(); jsonRequestProduct.setCode(product.getProductNumber()); jsonRequestProduct.setEan(product.getEan()); jsonRequestProduct.setName(product.getName()); jsonRequestProduct.setType(JsonRequestProduct.Type.ITEM); jsonRequestProduct.setUomCode(getUOMCode(product.getUnitId())); return Optional.of(JsonRequestProductUpsertItem.builder() .productIdentifier(productIdentifier) .requestProduct(jsonRequestProduct) .externalSystemConfigId(routeContext.getExternalSystemRequest().getExternalSystemConfigId()) .build()); } @NonNull private String getUOMCode(@Nullable final String unitId) { if (unitId == null) { processLogger.logMessage("Shopware unit id is null, fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId());
return DEFAULT_PRODUCT_UOM; } if (routeContext.getUomMappings().isEmpty()) { processLogger.logMessage("No UOM mappings found in the route context, fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } final String externalCode = routeContext.getShopwareUomInfoProvider().getCode(unitId); if (externalCode == null) { processLogger.logMessage("No externalCode found for unit id: " + unitId + ", fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } final JsonUOM jsonUOM = routeContext.getUomMappings().get(externalCode); if (jsonUOM == null) { processLogger.logMessage("No UOM mapping found for externalCode: " + externalCode + " ! fallback to default UOM: PCE ! ProductId: " + product.getId(), routeContext.getPInstanceId()); return DEFAULT_PRODUCT_UOM; } return jsonUOM.getCode(); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\ProductUpsertRequestProducer.java
2
请完成以下Java代码
public ChildElementBuilder<T> required() { super.required(); return this; } public ChildElementBuilder<T> minOccurs(int i) { super.minOccurs(i); return this; } public ChildElementBuilder<T> maxOccurs(int i) { super.maxOccurs(i); return this; } public ChildElement<T> build() { return (ChildElement<T>) super.build(); } public <V extends ModelElementInstance> ElementReferenceBuilder<V, T> qNameElementReference(Class<V> referenceTargetType) { ChildElementImpl<T> child = (ChildElementImpl<T>) build(); QNameElementReferenceBuilderImpl<V,T> builder = new QNameElementReferenceBuilderImpl<V, T>(childElementType, referenceTargetType, child); setReferenceBuilder(builder); return builder; }
public <V extends ModelElementInstance> ElementReferenceBuilder<V, T> idElementReference(Class<V> referenceTargetType) { ChildElementImpl<T> child = (ChildElementImpl<T>) build(); ElementReferenceBuilderImpl<V, T> builder = new ElementReferenceBuilderImpl<V, T>(childElementType, referenceTargetType, child); setReferenceBuilder(builder); return builder; } public <V extends ModelElementInstance> ElementReferenceBuilder<V, T> uriElementReference(Class<V> referenceTargetType) { ChildElementImpl<T> child = (ChildElementImpl<T>) build(); ElementReferenceBuilderImpl<V, T> builder = new UriElementReferenceBuilderImpl<V, T>(childElementType, referenceTargetType, child); setReferenceBuilder(builder); return builder; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\child\ChildElementBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { // 创建线程安全的Map,模拟users信息的存储 static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>()); @GetMapping("/") @ApiOperation(value = "获取用户列表") public List<User> getUserList() { List<User> r = new ArrayList<>(users.values()); return r; } @PostMapping("/") @ApiOperation(value = "创建用户", notes = "根据User对象创建用户") public String postUser(@RequestBody User user) { users.put(user.getId(), user); return "success"; } @GetMapping("/{id}") @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息") public User getUser(@PathVariable Long id) { return users.get(id); } @PutMapping("/{id}") @ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用户编号", required = true, example = "1") @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息") public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @DeleteMapping("/{id}") @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象") public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; } }
repos\SpringBoot-Learning-master\2.x\chapter2-2\src\main\java\com\didispace\chapter22\UserController.java
2
请在Spring Boot框架中完成以下Java代码
public class BPartnerAttributesRepository { private final BPAttributes1RecordAdapter attributes1RecordAdapter = new BPAttributes1RecordAdapter(); private final BPAttributes2RecordAdapter attributes2RecordAdapter = new BPAttributes2RecordAdapter(); private final BPAttributes3RecordAdapter attributes3RecordAdapter = new BPAttributes3RecordAdapter(); private final BPAttributes4RecordAdapter attributes4RecordAdapter = new BPAttributes4RecordAdapter(); private final BPAttributes5RecordAdapter attributes5RecordAdapter = new BPAttributes5RecordAdapter(); public BPartnerAttributes getByBPartnerId(@NonNull final BPartnerId bpartnerId) { return BPartnerAttributes.builder() .attributesSet1(attributes1RecordAdapter.getAttributes(bpartnerId)) .attributesSet2(attributes2RecordAdapter.getAttributes(bpartnerId)) .attributesSet3(attributes3RecordAdapter.getAttributes(bpartnerId)) .attributesSet4(attributes4RecordAdapter.getAttributes(bpartnerId))
.attributesSet5(attributes5RecordAdapter.getAttributes(bpartnerId)) .build(); } public void saveAttributes( @NonNull final BPartnerAttributes bpartnerAttributes, @NonNull final BPartnerId bpartnerId) { attributes1RecordAdapter.saveAttributes(bpartnerAttributes.getAttributesSet1(), bpartnerId); attributes2RecordAdapter.saveAttributes(bpartnerAttributes.getAttributesSet2(), bpartnerId); attributes3RecordAdapter.saveAttributes(bpartnerAttributes.getAttributesSet3(), bpartnerId); attributes4RecordAdapter.saveAttributes(bpartnerAttributes.getAttributesSet4(), bpartnerId); attributes5RecordAdapter.saveAttributes(bpartnerAttributes.getAttributesSet5(), bpartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\attributes\service\BPartnerAttributesRepository.java
2
请完成以下Java代码
public static PackToSpec ofTUPackingInstructionsId(@NonNull final HUPIItemProductId tuPackingInstructionsId) { if (tuPackingInstructionsId.isVirtualHU()) { return VIRTUAL; } else { return new PackToSpec(null, tuPackingInstructionsId); } } public static PackToSpec ofGenericPackingInstructionsId(@NonNull final HuPackingInstructionsId genericPackingInstructionsId) { if (genericPackingInstructionsId.isVirtual()) { return VIRTUAL; } else { return new PackToSpec(genericPackingInstructionsId, null); } } private PackToSpec( @Nullable final HuPackingInstructionsId genericPackingInstructionsId, @Nullable final HUPIItemProductId tuPackingInstructionsId) { if (CoalesceUtil.countNotNulls(genericPackingInstructionsId, tuPackingInstructionsId) != 1) { throw new AdempiereException("Only one of packingInstructionsId or huPIItemProductId shall be specified"); } this.genericPackingInstructionsId = genericPackingInstructionsId; this.tuPackingInstructionsId = tuPackingInstructionsId; } public boolean isVirtual() { if (tuPackingInstructionsId != null) { return tuPackingInstructionsId.isVirtualHU(); } else { return genericPackingInstructionsId != null && genericPackingInstructionsId.isVirtual(); } } public interface CaseMapper<T>
{ T packToVirtualHU(); T packToTU(HUPIItemProductId tuPackingInstructionsId); T packToGenericHU(HuPackingInstructionsId genericPackingInstructionsId); } public <T> T map(@NonNull final CaseMapper<T> mapper) { if (isVirtual()) { return mapper.packToVirtualHU(); } else if (tuPackingInstructionsId != null) { return mapper.packToTU(tuPackingInstructionsId); } else { return mapper.packToGenericHU(Objects.requireNonNull(genericPackingInstructionsId)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PackToSpec.java
1
请完成以下Java代码
public void setRequestControls(List<Control> listControls) { try { initialContext.setRequestControls(listControls.toArray(new Control[0])); } catch (NamingException e) { throw new IdentityProviderException("LDAP server failed to set request controls.", e); } } public Control[] getResponseControls() { try { return initialContext.getResponseControls(); } catch (NamingException e) { throw new IdentityProviderException("Error occurred while getting the response controls from the LDAP server.", e); } } public static void addPaginationControl(List<Control> listControls, byte[] cookie, Integer pageSize) { try { listControls.add(new PagedResultsControl(pageSize, cookie, Control.NONCRITICAL)); } catch (IOException e) { throw new IdentityProviderException("Pagination couldn't be enabled.", e); } } public static void addSortKey(SortKey sortKey, List<Control> controls) { try { controls.add(new SortControl(new SortKey[] { sortKey }, Control.CRITICAL)); } catch (IOException e) { throw new IdentityProviderException("Sorting couldn't be enabled.", e); } } protected static String getValue(String attrName, Attributes attributes) { Attribute attribute = attributes.get(attrName); if (attribute != null) {
try { return (String) attribute.get(); } catch (NamingException e) { throw new IdentityProviderException("Error occurred while retrieving the value.", e); } } else { return null; } } @SuppressWarnings("unchecked") public static NamingEnumeration<String> getAllMembers(String attributeId, LdapSearchResults searchResults) { SearchResult result = searchResults.nextElement(); Attributes attributes = result.getAttributes(); if (attributes != null) { Attribute memberAttribute = attributes.get(attributeId); if (memberAttribute != null) { try { return (NamingEnumeration<String>) memberAttribute.getAll(); } catch (NamingException e) { throw new IdentityProviderException("Value couldn't be retrieved.", e); } } } return null; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapClient.java
1
请完成以下Java代码
public LocalDateTime trancateTo(LocalDateTime time) { switch (this) { case DAYS: return time.truncatedTo(ChronoUnit.DAYS); case MONTHS: return time.truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1); case YEARS: return time.truncatedTo(ChronoUnit.DAYS).withDayOfYear(1); case INDEFINITE: return EPOCH_START; default: throw new RuntimeException("Failed to parse partitioning property!"); } } public LocalDateTime plusTo(LocalDateTime time) { switch (this) { case DAYS: return time.plusDays(1); case MONTHS: return time.plusMonths(1); case YEARS: return time.plusYears(1);
default: throw new RuntimeException("Failed to parse partitioning property!"); } } public static Optional<SqlTsPartitionDate> parse(String name) { SqlTsPartitionDate partition = null; if (name != null) { for (SqlTsPartitionDate partitionDate : SqlTsPartitionDate.values()) { if (partitionDate.name().equalsIgnoreCase(name)) { partition = partitionDate; break; } } } return Optional.ofNullable(partition); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\SqlTsPartitionDate.java
1
请完成以下Java代码
protected ProductsProposalRowsLoader createRowsLoaderFromRecord(final TableRecordReference recordRef) { throw new UnsupportedOperationException(); } public final ProductsProposalView createView(@NonNull final ProductsProposalView parentView) { final PriceListVersionId basePriceListVersionId = parentView.getBasePriceListVersionIdOrFail(); final ProductsProposalRowsData rowsData = ProductsProposalRowsLoader.builder() .bpartnerProductStatsService(bpartnerProductStatsService) .orderProductProposalsService(orderProductProposalsService) .lookupDataSourceFactory(lookupDataSourceFactory) // .priceListVersionId(basePriceListVersionId) .productIdsToExclude(parentView.getProductIds()) .bpartnerId(parentView.getBpartnerId().orElse(null)) .currencyId(parentView.getCurrencyId()) .soTrx(parentView.getSoTrx()) // .build().load(); logger.debug("loaded ProductsProposalRowsData with size={} for basePriceListVersionId={}", basePriceListVersionId, rowsData.size()); final ProductsProposalView view = ProductsProposalView.builder() .windowId(getWindowId()) .rowsData(rowsData) .processes(getRelatedProcessDescriptors()) .initialViewId(parentView.getInitialViewId()) .build(); put(view); return view; } @Override protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors() { return ImmutableList.of(
createProcessDescriptor(WEBUI_ProductsProposal_AddProductFromBasePriceList.class)); } @Override public ProductsProposalView filterView( final IView view, final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo) { final ProductsProposalView productsProposalView = ProductsProposalView.cast(view); final ProductsProposalViewFilter filter = ProductsProposalViewFilters.extractPackageableViewFilterVO(filterViewRequest); productsProposalView.filter(filter); return productsProposalView; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\BasePLVProductsProposalViewFactory.java
1
请在Spring Boot框架中完成以下Java代码
public class LocalToRemoteSyncResult implements SyncResult { /** We don't know (and for performance reasons didn't check) if the record was existing remotely. But at any rate, now it's there. */ public static LocalToRemoteSyncResult upserted(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.UPSERTED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult inserted(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.INSERTED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult updated(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.UPDATED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult deleted(@NonNull final DataRecord datarecord) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.DELETED_ON_REMOTE) .build(); } public static LocalToRemoteSyncResult error( @NonNull final DataRecord datarecord, @NonNull final String errorMessage) { return LocalToRemoteSyncResult.builder() .synchedDataRecord(datarecord) .localToRemoteStatus(LocalToRemoteStatus.ERROR) .errorMessage(errorMessage) .build();
} public enum LocalToRemoteStatus { INSERTED_ON_REMOTE, UPDATED_ON_REMOTE, UPSERTED_ON_REMOTE, DELETED_ON_REMOTE, UNCHANGED, ERROR; } LocalToRemoteStatus localToRemoteStatus; String errorMessage; DataRecord synchedDataRecord; @Builder private LocalToRemoteSyncResult( @NonNull final DataRecord synchedDataRecord, @Nullable final LocalToRemoteStatus localToRemoteStatus, @Nullable final String errorMessage) { this.synchedDataRecord = synchedDataRecord; this.localToRemoteStatus = localToRemoteStatus; this.errorMessage = errorMessage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\LocalToRemoteSyncResult.java
2
请完成以下Java代码
public abstract class SpinValueTypeImpl extends AbstractValueTypeImpl implements SpinValueType { private static final long serialVersionUID = 1L; public SpinValueTypeImpl(String name) { super(name); } public TypedValue createValue(Object value, Map<String, Object> valueInfo) { SpinValueBuilder<?> builder = createValue((SpinValue) value); applyValueInfo(builder, valueInfo); return builder.create(); } public SerializableValue createValueFromSerialized(String serializedValue, Map<String, Object> valueInfo) { SpinValueBuilder<?> builder = createValueFromSerialized(serializedValue); applyValueInfo(builder, valueInfo); return builder.create(); } public boolean isPrimitiveValueType() { return false; } public Map<String, Object> getValueInfo(TypedValue typedValue) { if(!(typedValue instanceof SpinValue)) { throw new IllegalArgumentException("Value not of type Spin Value."); }
SpinValue spinValue = (SpinValue) typedValue; Map<String, Object> valueInfo = new HashMap<String, Object>(); if (spinValue.isTransient()) { valueInfo.put(VALUE_INFO_TRANSIENT, spinValue.isTransient()); } return valueInfo; } protected void applyValueInfo(SpinValueBuilder<?> builder, Map<String, Object> valueInfo) { if(valueInfo != null) { builder.setTransient(isTransient(valueInfo)); } } protected abstract SpinValueBuilder<?> createValue(SpinValue value); protected abstract SpinValueBuilder<?> createValueFromSerialized(String value); }
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\variable\type\impl\SpinValueTypeImpl.java
1
请完成以下Java代码
public MqttClientSettings getMqttClientSettings() { return mainCtx.getMqttClientSettings(); } private TbMsgMetaData getActionMetaData(RuleNodeId ruleNodeId) { TbMsgMetaData metaData = new TbMsgMetaData(); metaData.putValue("ruleNodeId", ruleNodeId.toString()); return metaData; } @Override public void schedule(Runnable runnable, long delay, TimeUnit timeUnit) { mainCtx.getScheduler().schedule(runnable, delay, timeUnit); } @Override public void checkTenantEntity(EntityId entityId) throws TbNodeException { TenantId actualTenantId = TenantIdLoader.findTenantId(this, entityId); if (!getTenantId().equals(actualTenantId)) { throw new TbNodeException("Entity with id: '" + entityId + "' specified in the configuration doesn't belong to the current tenant.", true); } } @Override public <E extends HasId<I> & HasTenantId, I extends EntityId> void checkTenantOrSystemEntity(E entity) throws TbNodeException { TenantId actualTenantId = entity.getTenantId(); if (!getTenantId().equals(actualTenantId) && !actualTenantId.isSysTenantId()) { throw new TbNodeException("Entity with id: '" + entity.getId() + "' specified in the configuration doesn't belong to the current or system tenant.", true); } } private static String getFailureMessage(Throwable th) { String failureMessage; if (th != null) { if (!StringUtils.isEmpty(th.getMessage())) { failureMessage = th.getMessage(); } else { failureMessage = th.getClass().getSimpleName(); } } else { failureMessage = null; } return failureMessage; }
private void persistDebugOutput(TbMsg msg, String relationType) { persistDebugOutput(msg, Set.of(relationType)); } private void persistDebugOutput(TbMsg msg, Set<String> relationTypes) { persistDebugOutput(msg, relationTypes, null, null); } private void persistDebugOutput(TbMsg msg, Set<String> relationTypes, Throwable error, String failureMessage) { RuleNode ruleNode = nodeCtx.getSelf(); if (DebugModeUtil.isDebugAllAvailable(ruleNode)) { relationTypes.forEach(relationType -> mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, relationType, error, failureMessage)); } else if (DebugModeUtil.isDebugFailuresAvailable(ruleNode, relationTypes)) { mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, TbNodeConnectionType.FAILURE, error, failureMessage); } } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\DefaultTbContext.java
1
请完成以下Java代码
public class JmsHealthIndicator extends AbstractHealthIndicator { private final Log logger = LogFactory.getLog(JmsHealthIndicator.class); private final ConnectionFactory connectionFactory; public JmsHealthIndicator(ConnectionFactory connectionFactory) { super("JMS health check failed"); this.connectionFactory = connectionFactory; } @Override protected void doHealthCheck(Health.Builder builder) throws Exception { try (Connection connection = this.connectionFactory.createConnection()) { new MonitoredConnection(connection).start(); builder.up().withDetail("provider", connection.getMetaData().getJMSProviderName()); } } private final class MonitoredConnection { private final CountDownLatch latch = new CountDownLatch(1); private final Connection connection; MonitoredConnection(Connection connection) { this.connection = connection; } void start() throws JMSException { new Thread(() -> { try { if (!this.latch.await(5, TimeUnit.SECONDS)) { JmsHealthIndicator.this.logger .warn("Connection failed to start within 5 seconds and will be closed."); closeConnection(); } } catch (InterruptedException ex) {
Thread.currentThread().interrupt(); } }, "jms-health-indicator").start(); this.connection.start(); this.latch.countDown(); } private void closeConnection() { try { this.connection.close(); } catch (Exception ex) { // Continue } } } }
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\health\JmsHealthIndicator.java
1
请完成以下Java代码
public class M_ReceiptSchedule_ChangeExportStatus extends JavaProcess implements IProcessPrecondition { private final IReceiptScheduleDAO receiptScheduleDAO = Services.get(IReceiptScheduleDAO.class); private final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class); private static final AdMessageKey MSG_NO_UNPROCESSED_LINES = AdMessageKey.of("receiptschedule.noUnprocessedLines"); private static final String PARAM_ExportStatus = "ExportStatus"; @Param(parameterName = PARAM_ExportStatus, mandatory = true) private String exportStatus; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context) { if (context.isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected void prepare() { final IQueryFilter<I_M_ReceiptSchedule> userSelectionFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBuilder<de.metas.inoutcandidate.model.I_M_ReceiptSchedule> queryBuilderForShipmentSchedulesSelection = receiptScheduleDAO.createQueryForReceiptScheduleSelection(getCtx(), userSelectionFilter); // Create selection and return how many items were added final int selectionCount = queryBuilderForShipmentSchedulesSelection .create() .createSelection(getPinstanceId()); if (selectionCount <= 0)
{ throw new AdempiereException(MSG_NO_UNPROCESSED_LINES) .markAsUserValidationError(); } } @Override protected String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); receiptScheduleBL.updateExportStatus(APIExportStatus.ofCode(exportStatus), pinstanceId); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_ChangeExportStatus.java
1
请完成以下Java代码
public void add( @NonNull PrintingData printingData, @NonNull PrintingSegment segment) { Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer); segments.add(PrintingDataAndSegment.of(printingData, segment)); } public FrontendPrinterDataItem toFrontendPrinterData() { return FrontendPrinterDataItem.builder() .printer(printer) .filename(suggestFilename()) .data(toByteArray()) .build(); } private byte[] toByteArray() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos)) { for (PrintingDataAndSegment printingDataAndSegment : segments) { pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment()); }
} return baos.toByteArray(); } private String suggestFilename() { final ImmutableSet<String> filenames = segments.stream() .map(PrintingDataAndSegment::getDocumentFileName) .collect(ImmutableSet.toImmutableSet()); return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf"; } } @Value(staticConstructor = "of") private static class PrintingDataAndSegment { @NonNull PrintingData printingData; @NonNull PrintingSegment segment; public String getDocumentFileName() { return printingData.getDocumentFileName(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
1
请完成以下Java代码
Banner print(Environment environment, @Nullable Class<?> sourceClass, Log logger) { Banner banner = getBanner(environment); try { logger.info(createStringFromBanner(banner, environment, sourceClass)); } catch (UnsupportedEncodingException ex) { logger.warn("Failed to create String for banner", ex); } return new PrintedBanner(banner, sourceClass); } Banner print(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) { Banner banner = getBanner(environment); banner.printBanner(environment, sourceClass, out); return new PrintedBanner(banner, sourceClass); } private Banner getBanner(Environment environment) { Banner textBanner = getTextBanner(environment); if (textBanner != null) { return textBanner; } if (this.fallbackBanner != null) { return this.fallbackBanner; } return DEFAULT_BANNER; } private @Nullable Banner getTextBanner(Environment environment) { String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION); Resource resource = this.resourceLoader.getResource(location); try { if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) { return new ResourceBanner(resource); } } catch (IOException ex) { // Ignore } return null; } private String createStringFromBanner(Banner banner, Environment environment, @Nullable Class<?> mainApplicationClass) throws UnsupportedEncodingException { String charset = environment.getProperty("spring.banner.charset", StandardCharsets.UTF_8.name()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream out = new PrintStream(byteArrayOutputStream, false, charset)) { banner.printBanner(environment, mainApplicationClass, out); } return byteArrayOutputStream.toString(charset); } /** * Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class. */ private static class PrintedBanner implements Banner { private final Banner banner; private final @Nullable Class<?> sourceClass; PrintedBanner(Banner banner, @Nullable Class<?> sourceClass) { this.banner = banner; this.sourceClass = sourceClass; } @Override public void printBanner(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) { sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass; this.banner.printBanner(environment, sourceClass, out); } } static class SpringApplicationBannerPrinterRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern(DEFAULT_BANNER_LOCATION); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationBannerPrinter.java
1
请在Spring Boot框架中完成以下Java代码
public T findOne(final long id) { return getDao().findOne(id); } @Override public List<T> findAll() { return getDao().findAll(); } @Override public void create(final T entity) { getDao().create(entity); } @Override public T update(final T entity) {
return getDao().update(entity); } @Override public void delete(final T entity) { getDao().delete(entity); } @Override public void deleteById(final long entityId) { getDao().deleteById(entityId); } protected abstract IOperations<T> getDao(); }
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\service\common\AbstractService.java
2
请完成以下Java代码
public int getM_HU_PI_Item_Product_ID() { final IHUInOutBL huInOutBL = Services.get(IHUInOutBL.class); final org.compiere.model.I_M_InOut inOut = inoutLine.getM_InOut(); // Applied only to customer return inout lines. final boolean isCustomerReturnInOutLine = huInOutBL.isCustomerReturn(inOut); if (inoutLine.isManualPackingMaterial() || isCustomerReturnInOutLine) { return inoutLine.getM_HU_PI_Item_Product_ID(); } final I_C_OrderLine orderline = InterfaceWrapperHelper.create(inoutLine.getC_OrderLine(), I_C_OrderLine.class); return orderline == null ? -1 : orderline.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return inoutLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { inoutLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return inoutLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { inoutLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return inoutLine.getQtyEnteredTU(); } @Override
public void setQtyTU(final BigDecimal qtyPacks) { inoutLine.setQtyEnteredTU(qtyPacks); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public boolean isInDispute() { return inoutLine.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { inoutLine.setIsInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InOutLineHUPackingAware.java
1
请完成以下Spring Boot application配置
spring.application.name=api-gateway server.port=5555 # routes to serviceId zuul.routes.api-a.path=/api-a/** zuul.routes.api-a.serviceId=service-A zuul.routes.api-b.path=/api-b/** zuul.routes.api-b.serviceId=service-B # routes to url zuul.routes.api-a-url.path=/api-a-url/*
* zuul.routes.api-a-url.url=http://localhost:2222/ eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
repos\SpringBoot-Learning-master\1.x\Chapter9-1-5\api-gateway\src\main\resources\application.properties
2
请完成以下Java代码
public class Supplier { private String name; private String phoneNumber; public Supplier() { } public Supplier(String name, String phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Supplier supplier = (Supplier) o; if (name != null ? !name.equals(supplier.name) : supplier.name != null) return false; return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); return result; } }
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\libraries\smooks\model\Supplier.java
1
请完成以下Java代码
public class ArgumentMethodArgumentResolver implements HandlerMethodArgumentResolver { private final GraphQlArgumentBinder argumentBinder; public ArgumentMethodArgumentResolver(GraphQlArgumentBinder argumentBinder) { Assert.notNull(argumentBinder, "GraphQlArgumentBinder is required"); this.argumentBinder = argumentBinder; } /** * Return the configured {@link GraphQlArgumentBinder}. * @since 1.3.0 */ public GraphQlArgumentBinder getArgumentBinder() { return this.argumentBinder; } @Override public boolean supportsParameter(MethodParameter parameter) { return (parameter.getParameterAnnotation(Argument.class) != null || parameter.getParameterType() == ArgumentValue.class); } @Override public @Nullable Object resolveArgument(MethodParameter parameter, DataFetchingEnvironment environment) throws Exception { String name = getArgumentName(parameter); ResolvableType targetType = ResolvableType.forMethodParameter(parameter); return doBind(environment, name, targetType); } /** * Perform the binding with the configured {@link #getArgumentBinder() binder}. * @param environment for access to the arguments * @param name the name of an argument, or {@code null} to use the full map * @param targetType the type of Object to create * @since 1.3.0
*/ protected @Nullable Object doBind( DataFetchingEnvironment environment, String name, ResolvableType targetType) throws BindException { return this.argumentBinder.bind(environment, name, targetType); } static String getArgumentName(MethodParameter parameter) { Argument argument = parameter.getParameterAnnotation(Argument.class); if (argument != null) { if (StringUtils.hasText(argument.name())) { return argument.name(); } } else if (parameter.getParameterType() != ArgumentValue.class) { throw new IllegalStateException( "Expected either @Argument or a method parameter of type ArgumentValue"); } String parameterName = parameter.getParameterName(); if (parameterName != null) { return parameterName; } throw new IllegalArgumentException( "Name for argument of type [" + parameter.getNestedParameterType().getName() + "] not specified, and parameter name information not found in class file either."); } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\data\method\annotation\support\ArgumentMethodArgumentResolver.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable DataSize getFragmentSize() { return this.fragmentSize; } public void setFragmentSize(@Nullable DataSize fragmentSize) { this.fragmentSize = fragmentSize; } public @Nullable Ssl getSsl() { return this.ssl; } public void setSsl(@Nullable Ssl ssl) { this.ssl = ssl; } public Spec getSpec() { return this.spec; } public static class Spec { /** * Sub-protocols to use in websocket handshake signature. */ private @Nullable String protocols; /** * Maximum allowable frame payload length. */ private DataSize maxFramePayloadLength = DataSize.ofBytes(65536); /** * Whether to proxy websocket ping frames or respond to them. */ private boolean handlePing; /** * Whether the websocket compression extension is enabled. */ private boolean compress; public @Nullable String getProtocols() { return this.protocols; } public void setProtocols(@Nullable String protocols) {
this.protocols = protocols; } public DataSize getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(DataSize maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isHandlePing() { return this.handlePing; } public void setHandlePing(boolean handlePing) { this.handlePing = handlePing; } public boolean isCompress() { return this.compress; } public void setCompress(boolean compress) { this.compress = compress; } } } }
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketProperties.java
2
请完成以下Java代码
public static SessionFactory getSessionFactory() { if (sessionFactory == null) { sessionFactory = buildSessionFactory(); } return sessionFactory; } private static SessionFactory buildSessionFactory() { try { ServiceRegistry serviceRegistry = configureServiceRegistry(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(Student.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder().build(); } catch (IOException ex) { throw new ExceptionInInitializerError(ex); }
} private static ServiceRegistry configureServiceRegistry() throws IOException { Properties properties = getProperties(); return new StandardServiceRegistryBuilder().applySettings(properties).build(); } private static Properties getProperties() throws IOException { Properties properties = new Properties(); URL propertiesURL = Thread.currentThread() .getContextClassLoader() .getResource("hibernate.properties"); try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) { properties.load(inputStream); } return properties; } }
repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteriaquery\HibernateUtil.java
1
请在Spring Boot框架中完成以下Java代码
public void setPOSPaymentMethod (final java.lang.String POSPaymentMethod) { set_Value (COLUMNNAME_POSPaymentMethod, POSPaymentMethod); } @Override public java.lang.String getPOSPaymentMethod() { return get_ValueAsString(COLUMNNAME_POSPaymentMethod); } /** * POSPaymentProcessingStatus AD_Reference_ID=541897 * Reference name: POSPaymentProcessingStatus */ public static final int POSPAYMENTPROCESSINGSTATUS_AD_Reference_ID=541897; /** SUCCESSFUL = SUCCESSFUL */ public static final String POSPAYMENTPROCESSINGSTATUS_SUCCESSFUL = "SUCCESSFUL"; /** CANCELLED = CANCELLED */ public static final String POSPAYMENTPROCESSINGSTATUS_CANCELLED = "CANCELLED"; /** FAILED = FAILED */ public static final String POSPAYMENTPROCESSINGSTATUS_FAILED = "FAILED"; /** PENDING = PENDING */ public static final String POSPAYMENTPROCESSINGSTATUS_PENDING = "PENDING"; /** NEW = NEW */ public static final String POSPAYMENTPROCESSINGSTATUS_NEW = "NEW"; /** DELETED = DELETED */ public static final String POSPAYMENTPROCESSINGSTATUS_DELETED = "DELETED"; @Override public void setPOSPaymentProcessingStatus (final java.lang.String POSPaymentProcessingStatus) { set_Value (COLUMNNAME_POSPaymentProcessingStatus, POSPaymentProcessingStatus); } @Override public java.lang.String getPOSPaymentProcessingStatus() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessingStatus); } @Override public void setPOSPaymentProcessingSummary (final @Nullable java.lang.String POSPaymentProcessingSummary) { set_Value (COLUMNNAME_POSPaymentProcessingSummary, POSPaymentProcessingSummary); } @Override public java.lang.String getPOSPaymentProcessingSummary() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessingSummary); } @Override public void setPOSPaymentProcessing_TrxId (final @Nullable java.lang.String POSPaymentProcessing_TrxId) { set_Value (COLUMNNAME_POSPaymentProcessing_TrxId, POSPaymentProcessing_TrxId); } @Override public java.lang.String getPOSPaymentProcessing_TrxId()
{ return get_ValueAsString(COLUMNNAME_POSPaymentProcessing_TrxId); } /** * POSPaymentProcessor AD_Reference_ID=541896 * Reference name: POSPaymentProcessor */ public static final int POSPAYMENTPROCESSOR_AD_Reference_ID=541896; /** SumUp = sumup */ public static final String POSPAYMENTPROCESSOR_SumUp = "sumup"; @Override public void setPOSPaymentProcessor (final @Nullable java.lang.String POSPaymentProcessor) { set_Value (COLUMNNAME_POSPaymentProcessor, POSPaymentProcessor); } @Override public java.lang.String getPOSPaymentProcessor() { return get_ValueAsString(COLUMNNAME_POSPaymentProcessor); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_Value (COLUMNNAME_SUMUP_Config_ID, null); else set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Payment.java
2
请完成以下Java代码
public void setM_Picking_Config_ID (final int M_Picking_Config_ID) { if (M_Picking_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, M_Picking_Config_ID); } @Override public int getM_Picking_Config_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Config_ID); } /** * WEBUI_PickingTerminal_ViewProfile AD_Reference_ID=540772 * Reference name: WEBUI_PickingTerminal_ViewProfile */ public static final int WEBUI_PICKINGTERMINAL_VIEWPROFILE_AD_Reference_ID=540772;
/** groupByProduct = groupByProduct */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByProduct = "groupByProduct"; /** Group by Order = groupByOrder */ public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByOrder = "groupByOrder"; @Override public void setWEBUI_PickingTerminal_ViewProfile (final java.lang.String WEBUI_PickingTerminal_ViewProfile) { set_Value (COLUMNNAME_WEBUI_PickingTerminal_ViewProfile, WEBUI_PickingTerminal_ViewProfile); } @Override public java.lang.String getWEBUI_PickingTerminal_ViewProfile() { return get_ValueAsString(COLUMNNAME_WEBUI_PickingTerminal_ViewProfile); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config.java
1
请完成以下Java代码
public List<DependsOnType> getDependsOn() { if (dependsOn == null) { dependsOn = new ArrayList<DependsOnType>(); } return this.dependsOn; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the copyright property. * * @return * possible object is * {@link String } * */ public String getCopyright() { return copyright; } /** * Sets the value of the copyright property. * * @param value * allowed object is * {@link String } * */ public void setCopyright(String value) { this.copyright = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link Long } * */ public Long getVersion() { return version; }
/** * Sets the value of the version property. * * @param value * allowed object is * {@link Long } * */ public void setVersion(Long value) { this.version = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public long getId() { if (id == null) { return 0L; } else { return id; } } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\SoftwareType.java
1
请在Spring Boot框架中完成以下Java代码
private void onTimeSeriesDelete(TenantId tenantId, EntityId entityId, List<String> keys, List<TsKvLatestRemovingResult> ts) { forwardToSubscriptionManagerService(tenantId, entityId, subscriptionManagerService -> { List<TsKvEntry> updated = new ArrayList<>(); List<String> deleted = new ArrayList<>(); ts.stream().filter(Objects::nonNull).forEach(res -> { if (res.isRemoved()) { if (res.getData() != null) { updated.add(res.getData()); } else { deleted.add(res.getKey()); } } }); subscriptionManagerService.onTimeSeriesUpdate(tenantId, entityId, updated, TbCallback.EMPTY); subscriptionManagerService.onTimeSeriesDelete(tenantId, entityId, deleted, TbCallback.EMPTY); }, () -> TbSubscriptionUtils.toTimeseriesDeleteProto(tenantId, entityId, keys)); } private <S> void addMainCallback(ListenableFuture<S> saveFuture, final FutureCallback<Void> callback) { if (callback == null) return; addMainCallback(saveFuture, result -> callback.onSuccess(null), callback::onFailure); } private <S> void addMainCallback(ListenableFuture<S> saveFuture, Consumer<S> onSuccess) { addMainCallback(saveFuture, onSuccess, null); } private <S> void addMainCallback(ListenableFuture<S> saveFuture, Consumer<S> onSuccess, Consumer<Throwable> onFailure) { DonAsynchron.withCallback(saveFuture, onSuccess, onFailure, tsCallBackExecutor); } private void checkInternalEntity(EntityId entityId) { if (EntityType.API_USAGE_STATE.equals(entityId.getEntityType())) { throw new RuntimeException("Can't update API Usage State!"); } } private FutureCallback<TimeseriesSaveResult> getApiUsageCallback(TenantId tenantId, CustomerId customerId, boolean sysTenant) { return new FutureCallback<>() { @Override public void onSuccess(TimeseriesSaveResult result) {
Integer dataPoints = result.getDataPoints(); if (!sysTenant && dataPoints != null && dataPoints > 0) { apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.STORAGE_DP_COUNT, dataPoints); } } @Override public void onFailure(Throwable t) {} }; } private FutureCallback<Void> getCalculatedFieldCallback(FutureCallback<List<String>> originalCallback, List<String> keys) { return new FutureCallback<>() { @Override public void onSuccess(Void unused) { originalCallback.onSuccess(keys); } @Override public void onFailure(Throwable t) { originalCallback.onFailure(t); } }; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultTelemetrySubscriptionService.java
2
请完成以下Java代码
public final class ModelChangeUtil { private ModelChangeUtil() { } public static boolean isJustActivated(@NonNull final Object model) { final IIsActiveAware activeAware = InterfaceWrapperHelper.create(model, IIsActiveAware.class); if (!activeAware.isActive()) { return false; } final IIsActiveAware oldActiveAware = InterfaceWrapperHelper.createOld(activeAware, IIsActiveAware.class); return !oldActiveAware.isActive(); } public static boolean isJustDeactivated(@NonNull final Object model) { final IIsActiveAware activeAware = InterfaceWrapperHelper.create(model, IIsActiveAware.class); if (activeAware.isActive()) { return false; } final IIsActiveAware oldActiveAware = InterfaceWrapperHelper.createOld(activeAware, IIsActiveAware.class); return oldActiveAware.isActive(); } public static boolean isJustDeactivatedOrUnProcessed(@NonNull final Object model) { final IActiveAndProcessedAware newAware = InterfaceWrapperHelper.create(model, IActiveAndProcessedAware.class); final IActiveAndProcessedAware oldAware = InterfaceWrapperHelper.createOld(newAware, IActiveAndProcessedAware.class); final boolean deactivated = oldAware.isActive() && !newAware.isActive();
final boolean unprocessed = oldAware.isProcessed() && !newAware.isProcessed(); return deactivated || unprocessed; } public static boolean isJustActivatedOrProcessed(@NonNull final Object model) { final IActiveAndProcessedAware newAware = InterfaceWrapperHelper.create(model, IActiveAndProcessedAware.class); final IActiveAndProcessedAware oldAware = InterfaceWrapperHelper.createOld(newAware, IActiveAndProcessedAware.class); final boolean activated = !oldAware.isActive() && newAware.isActive(); final boolean processed = !oldAware.isProcessed() && newAware.isProcessed(); return activated || processed; } public static interface IIsActiveAware { boolean isActive(); } public static interface IActiveAndProcessedAware { boolean isActive(); boolean isProcessed(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelChangeUtil.java
1
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } /** * Gender AD_Reference_ID=541317 * Reference name: Gender_List */ public static final int GENDER_AD_Reference_ID=541317; /** Unbekannt = 0 */ public static final String GENDER_Unbekannt = "0"; /** Weiblich = 1 */ public static final String GENDER_Weiblich = "1"; /** Männlich = 2 */ public static final String GENDER_Maennlich = "2"; /** Divers = 3 */ public static final String GENDER_Divers = "3"; @Override public void setGender (final @Nullable java.lang.String Gender) { set_Value (COLUMNNAME_Gender, Gender); } @Override public java.lang.String getGender() { return get_ValueAsString(COLUMNNAME_Gender); } @Override public void setTimestamp (final @Nullable java.sql.Timestamp Timestamp) { set_Value (COLUMNNAME_Timestamp, Timestamp); } @Override public java.sql.Timestamp getTimestamp() { return get_ValueAsTimestamp(COLUMNNAME_Timestamp); } /** * Title AD_Reference_ID=541318 * Reference name: Title_List */ public static final int TITLE_AD_Reference_ID=541318; /** Unbekannt = 0 */ public static final String TITLE_Unbekannt = "0"; /** Dr. = 1 */ public static final String TITLE_Dr = "1"; /** Prof. Dr. = 2 */ public static final String TITLE_ProfDr = "2"; /** Dipl. Ing. = 3 */ public static final String TITLE_DiplIng = "3"; /** Dipl. Med. = 4 */
public static final String TITLE_DiplMed = "4"; /** Dipl. Psych. = 5 */ public static final String TITLE_DiplPsych = "5"; /** Dr. Dr. = 6 */ public static final String TITLE_DrDr = "6"; /** Dr. med. = 7 */ public static final String TITLE_DrMed = "7"; /** Prof. Dr. Dr. = 8 */ public static final String TITLE_ProfDrDr = "8"; /** Prof. = 9 */ public static final String TITLE_Prof = "9"; /** Prof. Dr. med. = 10 */ public static final String TITLE_ProfDrMed = "10"; /** Rechtsanwalt = 11 */ public static final String TITLE_Rechtsanwalt = "11"; /** Rechtsanwältin = 12 */ public static final String TITLE_Rechtsanwaeltin = "12"; /** Schwester (Orden) = 13 */ public static final String TITLE_SchwesterOrden = "13"; @Override public void setTitle (final @Nullable java.lang.String Title) { set_Value (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_AD_User_Alberta.java
1
请完成以下Java代码
private UOMPrecision getUOMPrecision() { return UOMPrecision.ofInt(uom.getStdPrecision()); } public Quantity setScale(@NonNull final UOMPrecision newScale) { return setScale(newScale, newScale.getRoundingMode()); } public Quantity setScale(final UOMPrecision newScale, @NonNull final RoundingMode roundingMode) { final BigDecimal newQty = qty.setScale(newScale.toInt(), roundingMode); return new Quantity( newQty, uom, sourceQty != null ? sourceQty.setScale(newScale.toInt(), roundingMode) : newQty, sourceUom != null ? sourceUom : uom); } public int intValueExact() { return toBigDecimal().intValueExact(); } public boolean isWeightable() { return UOMType.ofNullableCodeOrOther(uom.getUOMType()).isWeight(); } public Percent percentageOf(@NonNull final Quantity whole) { assertSameUOM(this, whole); return Percent.of(toBigDecimal(), whole.toBigDecimal()); } private void assertUOMOrSourceUOM(@NonNull final UomId uomId) { if (!getUomId().equals(uomId) && !getSourceUomId().equals(uomId)) { throw new QuantitiesUOMNotMatchingExpection("UOMs are not compatible") .appendParametersToMessage() .setParameter("Qty.UOM", getUomId()) .setParameter("assertUOM", uomId); } } @NonNull
public BigDecimal toBigDecimalAssumingUOM(@NonNull final UomId uomId) { assertUOMOrSourceUOM(uomId); return getUomId().equals(uomId) ? toBigDecimal() : getSourceQty(); } public List<Quantity> spreadEqually(final int count) { if (count <= 0) { throw new AdempiereException("count shall be greater than zero, but it was " + count); } else if (count == 1) { return ImmutableList.of(this); } else // count > 1 { final ImmutableList.Builder<Quantity> result = ImmutableList.builder(); final Quantity qtyPerPart = divide(count); Quantity qtyRemainingToSpread = this; for (int i = 1; i <= count; i++) { final boolean isLast = i == count; if (isLast) { result.add(qtyRemainingToSpread); } else { result.add(qtyPerPart); qtyRemainingToSpread = qtyRemainingToSpread.subtract(qtyPerPart); } } return result.build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\Quantity.java
1
请完成以下Java代码
public void focusLost(FocusEvent e) { if (e.isTemporary()) { return; } if (m_button == null // guarding against NPE (i.e. component was disposed in meantime) || !m_button.isEnabled()) // set by actionButton { return; } if (m_mAccount == null) { return; } // metas: begin: 02029: nerviges verhalten wenn man eine Maskeneingabe abbrechen will (2011082210000084) // Check if toolbar Ignore button was pressed if (e.getOppositeComponent() instanceof AbstractButton) { final AbstractButton b = (AbstractButton)e.getOppositeComponent(); if (APanel.CMD_Ignore.equals(b.getActionCommand())) { return; } } // metas: end if (m_text == null) return; // arhipac: teo_sarca: already disposed // Test Case: Open a window, click on account field that is mandatory but not filled, close the window and you will get an NPE // TODO: integrate to trunk // New text String newText = m_text.getText(); if (newText == null)
newText = ""; // Actual text String actualText = m_mAccount.getDisplay(m_value); if (actualText == null) actualText = ""; // If text was modified, try to resolve the valid combination if (!newText.equals(actualText)) { cmd_text(); } } @Override public boolean isAutoCommit() { return true; } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); } } // VAccount
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAccount.java
1
请完成以下Java代码
public static CConnectionAttributes of(@NonNull final String attributesStr) { // NOTE: keep in sync with toString() final String dbPortString = attributesStr.substring(attributesStr.indexOf("DBport=") + 7, attributesStr.indexOf(",DBname=")); return CConnectionAttributes.builder() .dbHost(attributesStr.substring(attributesStr.indexOf("DBhost=") + 7, attributesStr.indexOf(",DBport="))) .dbPort(parseDbPort(dbPortString)) .dbName(getSubString(attributesStr, "DBname=", ",")) .dbUid(attributesStr.substring(attributesStr.indexOf("UID=") + 4, attributesStr.indexOf(",PWD="))) .dbPwd(attributesStr.substring(attributesStr.indexOf("PWD=") + 4, attributesStr.indexOf("]"))) .build(); } @Nullable private static String getSubString(@NonNull final String attributesStr, @NonNull final String before, @NonNull final String after) { final int indexOfAppsPasswordStart = attributesStr.indexOf(before); final int indexOfAppsPasswordEnd = attributesStr.indexOf(after, indexOfAppsPasswordStart); if (indexOfAppsPasswordStart >= 0 && indexOfAppsPasswordEnd >= 0) { return attributesStr.substring(indexOfAppsPasswordStart + before.length(), indexOfAppsPasswordEnd); } return null; } private static final transient Logger logger = LogManager.getLogger(CConnectionAttributes.class); @Builder.Default private String dbHost = "localhost"; @Builder.Default private int dbPort = 5432; @Builder.Default private String dbName = "metasfresh"; private String dbUid; private String dbPwd; /** * Builds connection attributes string representation. * * This string can be parsed back by using {@link #of(String)}. * * @return connection attributes string representation */ @Override public String toString() { // NOTE: keep in sync with the parser!!!
final StringBuilder sb = new StringBuilder("CConnection["); sb .append("DBhost=").append(dbHost) .append(",DBport=").append(dbPort) .append(",DBname=").append(dbName) .append(",UID=").append(dbUid) .append(",PWD=").append(dbPwd); sb.append("]"); return sb.toString(); } // toStringLong private static int parseDbPort(final String dbPortString) { try { if (Check.isBlank(dbPortString)) { return -1; } else { return Integer.parseInt(dbPortString); } } catch (final Exception e) { logger.error("Error parsing db port: " + dbPortString, e); return -1; } } // setDbPort }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\db\CConnectionAttributes.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Password. @param Password Password of any length (case sensitive) */ public void setPassword (String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Password. @return Password of any length (case sensitive) */ public String getPassword () { return (String)get_Value(COLUMNNAME_Password); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); }
/** Set Registered EMail. @param UserName Email of the responsible for the System */ public void setUserName (String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ public String getUserName () { return (String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
1
请完成以下Java代码
public Path load(String filename) { return rootLocation.resolve(filename); } @Override public Resource loadAsResource(String filename) { try { Path file = load(filename); Resource resource = new UrlResource(file.toUri()); if(resource.exists() || resource.isReadable()) { return resource; } else { throw new StorageFileNotFoundException("Could not read file: " + filename); } } catch (MalformedURLException e) { throw new StorageFileNotFoundException("Could not read file: " + filename, e);
} } @Override public void deleteAll() { FileSystemUtils.deleteRecursively(rootLocation.toFile()); } @Override public void init() { try { Files.createDirectory(rootLocation); } catch (IOException e) { throw new StorageException("Could not initialize storage", e); } } }
repos\SpringBootLearning-master\springboot-upload-file\src\main\java\com\forezp\storage\FileSystemStorageService.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setAmount(BigDecimal value) { this.amount = value; } /** * The tax amount in the domestic currency. The domestic currency != invoice currency. * * @return * possible object is * {@link DomesticAmountType } * */ public DomesticAmountType getDomesticAmount() { return domesticAmount; } /** * Sets the value of the domesticAmount property. * * @param value
* allowed object is * {@link DomesticAmountType } * */ public void setDomesticAmount(DomesticAmountType value) { this.domesticAmount = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ItemType.java
2
请在Spring Boot框架中完成以下Java代码
public class QuoteServiceImpl implements QuoteService { private final Logger log = LoggerFactory.getLogger(QuoteServiceImpl.class); private final QuoteRepository quoteRepository; private final QuoteMapper quoteMapper; public QuoteServiceImpl(QuoteRepository quoteRepository, QuoteMapper quoteMapper) { this.quoteRepository = quoteRepository; this.quoteMapper = quoteMapper; } /** * Save a quote. * * @param quoteDTO the entity to save * @return the persisted entity */ @Override public QuoteDTO save(QuoteDTO quoteDTO) { log.debug("Request to save Quote : {}", quoteDTO); Quote quote = quoteMapper.toEntity(quoteDTO); quote = quoteRepository.save(quote); return quoteMapper.toDto(quote); } /** * Get all the quotes. * * @param pageable the pagination information * @return the list of entities */ @Override
@Transactional(readOnly = true) public Page<QuoteDTO> findAll(Pageable pageable) { log.debug("Request to get all Quotes"); return quoteRepository.findAll(pageable) .map(quoteMapper::toDto); } /** * Get one quote by id. * * @param id the id of the entity * @return the entity */ @Override @Transactional(readOnly = true) public Optional<QuoteDTO> findOne(Long id) { log.debug("Request to get Quote : {}", id); return quoteRepository.findById(id) .map(quoteMapper::toDto); } /** * Delete the quote by id. * * @param id the id of the entity */ @Override public void delete(Long id) { log.debug("Request to delete Quote : {}", id); quoteRepository.deleteById(id); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\impl\QuoteServiceImpl.java
2
请完成以下Java代码
public final class SwingFieldsUtil { private static Logger log = LogManager.getLogger(SwingFieldsUtil.class); public static void setSelectAllOnFocus(final JComponent c) { if (c instanceof JTextComponent) { setSelectAllOnFocus((JTextComponent)c); } else { for (Component cc : c.getComponents()) { if (cc instanceof JTextComponent) { setSelectAllOnFocus((JTextComponent)cc); break; } } } } public static void setSelectAllOnFocus(final JTextComponent c) { c.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { c.selectAll(); } }); } public static boolean isEmpty(Object editor) { if (editor == null) { return false; } if (editor instanceof CComboBox) { final CComboBox c = (CComboBox)editor; return c.isSelectionNone(); } else if (editor instanceof VDate) { VDate c = (VDate)editor; return c.getTimestamp() == null; } else if (editor instanceof VLookup) { VLookup c = (VLookup)editor; return c.getValue() == null; } else if (editor instanceof JTextComponent) { JTextComponent c = (JTextComponent)editor; return Check.isEmpty(c.getText(), true);
} // log.warn("Component type not supported - "+editor.getClass()); return false; } public static boolean isEditable(Component c) { if (c == null) return false; if (!c.isEnabled()) return false; if (c instanceof CEditor) return ((CEditor)c).isReadWrite(); if (c instanceof JTextComponent) return ((JTextComponent)c).isEditable(); // log.warn("Unknown component type - "+c.getClass()); return false; } public static void focusNextNotEmpty(Component component, Collection<Component> editors) { boolean found = false; Component last = null; for (Component c : editors) { last = c; if (found) { if (isEditable(c) && isEmpty(c)) { c.requestFocus(); return; } } else if (c == component) { found = true; } } // if (!found) log.warn("Component not found - "+component); if (found && last != null) last.requestFocus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\SwingFieldsUtil.java
1
请完成以下Java代码
public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){ return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK); } @Log("修改邮箱") @ApiOperation("修改邮箱") @PostMapping(value = "/updateEmail/{code}") public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception { String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword()); UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername()); if(!passwordEncoder.matches(password, userDto.getPassword())){ throw new BadRequestException("密码错误"); } verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code); userService.updateEmail(userDto.getUsername(),user.getEmail());
return new ResponseEntity<>(HttpStatus.OK); } /** * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误 * @param resources / */ private void checkLevel(User resources) { Integer currentLevel = Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList())); Integer optLevel = roleService.findByRoles(resources.getRoles()); if (currentLevel > optLevel) { throw new BadRequestException("角色权限不足"); } } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\UserController.java
1
请在Spring Boot框架中完成以下Java代码
private void getUnits(final Exchange exchange) { final GetUnitsRequest getUnitsRequest = exchange.getIn().getBody(GetUnitsRequest.class); if (getUnitsRequest == null) { throw new RuntimeException("No getUnitsRequest provided!"); } final ShopwareClient shopwareClient = ShopwareClient .of(getUnitsRequest.getClientId(), getUnitsRequest.getClientSecret(), getUnitsRequest.getBaseUrl(), PInstanceLogger.of(processLogger)); final JsonUnits units = shopwareClient.getUnits(); if (CollectionUtils.isEmpty(units.getUnitList()))
{ throw new RuntimeException("No units return from Shopware!"); } final ImmutableMap<String, String> unitId2Code = units.getUnitList() .stream() .collect(ImmutableMap.toImmutableMap(JsonUOM::getId, JsonUOM::getShortCode)); final UOMInfoProvider uomInfoProvider = UOMInfoProvider.builder() .unitId2Code(unitId2Code) .build(); exchange.getIn().setBody(uomInfoProvider); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\unit\GetUnitsRouteBuilder.java
2
请完成以下Java代码
public List<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) { List<XSLFShape> placeholders = new ArrayList<>(); for (XSLFShape shape : slide.getShapes()) { if (shape instanceof XSLFAutoShape) { placeholders.add(shape); } } return placeholders; } /** * Create a table * * @param slide * Slide */ private void createTable(XSLFSlide slide) { XSLFTable tbl = slide.createTable(); tbl.setAnchor(new Rectangle(50, 50, 450, 300)); int numColumns = 3; int numRows = 5; // header XSLFTableRow headerRow = tbl.addRow(); headerRow.setHeight(50); for (int i = 0; i < numColumns; i++) { XSLFTableCell th = headerRow.addCell(); XSLFTextParagraph p = th.addNewTextParagraph(); p.setTextAlign(TextParagraph.TextAlign.CENTER); XSLFTextRun r = p.addNewTextRun(); r.setText("Header " + (i + 1)); r.setBold(true); r.setFontColor(Color.white); th.setFillColor(new Color(79, 129, 189));
th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0); th.setBorderColor(TableCell.BorderEdge.bottom, Color.white); // all columns are equally sized tbl.setColumnWidth(i, 150); } // data for (int rownum = 0; rownum < numRows; rownum++) { XSLFTableRow tr = tbl.addRow(); tr.setHeight(50); for (int i = 0; i < numColumns; i++) { XSLFTableCell cell = tr.addCell(); XSLFTextParagraph p = cell.addNewTextParagraph(); XSLFTextRun r = p.addNewTextRun(); r.setText("Cell " + (i * rownum + 1)); if (rownum % 2 == 0) { cell.setFillColor(new Color(208, 216, 232)); } else { cell.setFillColor(new Color(233, 247, 244)); } } } } }
repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\powerpoint\PowerPointHelper.java
1
请完成以下Java代码
public ProcessInstance update(UpdateProcessPayload updateProcessPayload) { if (updateProcessPayload.getBusinessKey() != null) { runtimeService.updateBusinessKey( updateProcessPayload.getProcessInstanceId(), updateProcessPayload.getBusinessKey() ); } if (updateProcessPayload.getName() != null) { runtimeService.setProcessInstanceName( updateProcessPayload.getProcessInstanceId(), updateProcessPayload.getName() ); } return processInstanceConverter.from( runtimeService .createProcessInstanceQuery() .processInstanceId(updateProcessPayload.getProcessInstanceId()) .singleResult() ); } @Override public void setVariables(SetProcessVariablesPayload setProcessVariablesPayload) { ProcessInstanceImpl processInstance = (ProcessInstanceImpl) processInstance( setProcessVariablesPayload.getProcessInstanceId() ); processVariablesValidator.checkPayloadVariables( setProcessVariablesPayload, processInstance.getProcessDefinitionId() ); runtimeService.setVariables( setProcessVariablesPayload.getProcessInstanceId(), setProcessVariablesPayload.getVariables() ); } @Override public List<VariableInstance> variables(GetVariablesPayload getVariablesPayload) { processInstance(getVariablesPayload.getProcessInstanceId()); Map<String, org.activiti.engine.impl.persistence.entity.VariableInstance> variables; variables = runtimeService.getVariableInstances(getVariablesPayload.getProcessInstanceId()); return variableInstanceConverter.from(variables.values()); }
@Override public void removeVariables(RemoveProcessVariablesPayload removeProcessVariablesPayload) { runtimeService.removeVariables( removeProcessVariablesPayload.getProcessInstanceId(), removeProcessVariablesPayload.getVariableNames() ); } @Override @Transactional public void receive(ReceiveMessagePayload messagePayload) { processVariablesValidator.checkReceiveMessagePayloadVariables(messagePayload, null); eventPublisher.publishEvent(messagePayload); } @Override public ProcessInstance start(StartMessagePayload messagePayload) { String messageName = messagePayload.getName(); String businessKey = messagePayload.getBusinessKey(); Map<String, Object> variables = messagePayload.getVariables(); processVariablesValidator.checkStartMessagePayloadVariables(messagePayload, null); ProcessInstance processInstance = processInstanceConverter.from( runtimeService.startProcessInstanceByMessage(messageName, businessKey, variables) ); return processInstance; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\impl\ProcessAdminRuntimeImpl.java
1
请完成以下Java代码
private Flow<String, Integer, NotUsed> parseContent() { return Flow.of(String.class).mapConcat(this::parseLine); } private Flow<Integer, Double, NotUsed> computeAverage() { return Flow.of(Integer.class).grouped(2).mapAsyncUnordered(8, integers -> CompletableFuture.supplyAsync(() -> integers .stream() .mapToDouble(v -> v) .average() .orElse(-1.0))); } Flow<String, Double, NotUsed> calculateAverage() { return Flow.of(String.class) .via(parseContent()) .via(computeAverage()); } private Sink<Double, CompletionStage<Done>> storeAverages() { return Flow.of(Double.class) .mapAsyncUnordered(4, averageRepository::save) .toMat(Sink.ignore(), Keep.right()); }
CompletionStage<Done> calculateAverageForContent(String content) { return Source.single(content) .via(calculateAverage()) .runWith(storeAverages(), ActorMaterializer.create(actorSystem)) .whenComplete((d, e) -> { if (d != null) { System.out.println("Import finished "); } else { e.printStackTrace(); } }); } }
repos\tutorials-master\akka-modules\akka-streams\src\main\java\com\baeldung\akkastreams\DataImporter.java
1
请在Spring Boot框架中完成以下Java代码
public String getEntryType() { return entryType; } public void setEntryType(String entryType) { this.entryType = entryType; } /** * * @return the UUID of the entry this sync confirm record is about. */ public String getEntryUuid() { return entryUuid; } public void setEntryUuid(String entry_uuid) { this.entryUuid = entry_uuid; } public String getServerEventId() { return serverEventId; } public void setServerEventId(String serverEventId) { this.serverEventId = serverEventId; } /** * * @return the date when this record was created, which is also the date when the sync request was submitted towards the remote endpoint. */ @Override public Date getDateCreated() { return super.getDateCreated(); }
/** * * @return the date when the remote endpoint actually confirmed the data receipt. */ public Date getDateConfirmed() { return dateConfirmed; } public void setDateConfirmed(Date dateConfirmed) { this.dateConfirmed = dateConfirmed; } /** * * @return the date when our local endpoint received the remote endpoint's confirmation. */ public Date getDateConfirmReceived() { return dateConfirmReceived; } public void setDateConfirmReceived(Date dateConfirmReceived) { this.dateConfirmReceived = dateConfirmReceived; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\SyncConfirm.java
2
请完成以下Java代码
public String getMemberNickName() { return memberNickName; } public void setMemberNickName(String memberNickName) { this.memberNickName = memberNickName; } public Long getTopicId() { return topicId; } public void setTopicId(Long topicId) { this.topicId = topicId; } public String getMemberIcon() { return memberIcon; } public void setMemberIcon(String memberIcon) { this.memberIcon = memberIcon; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) {
this.createTime = createTime; } public Integer getShowStatus() { return showStatus; } public void setShowStatus(Integer showStatus) { this.showStatus = showStatus; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberNickName=").append(memberNickName); sb.append(", topicId=").append(topicId); sb.append(", memberIcon=").append(memberIcon); sb.append(", content=").append(content); sb.append(", createTime=").append(createTime); sb.append(", showStatus=").append(showStatus); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopicComment.java
1
请完成以下Java代码
public Permission getPermission() { return permission; } public void setPermission(Permission permission) { this.permission = permission; if (permission != null) { perms = permission.getValue(); } } public int getPerms() { return perms; } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; if (resource != null) { resourceType = resource.resourceType(); } } public int getResourceType() { return resourceType; }
public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getResourceIdQueryParam() { return resourceIdQueryParam; } public void setResourceIdQueryParam(String resourceIdQueryParam) { this.resourceIdQueryParam = resourceIdQueryParam; } public Long getAuthorizationNotFoundReturnValue() { return authorizationNotFoundReturnValue; } public void setAuthorizationNotFoundReturnValue(Long authorizationNotFoundReturnValue) { this.authorizationNotFoundReturnValue = authorizationNotFoundReturnValue; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\PermissionCheck.java
1
请完成以下Java代码
public void saveChanges(final PPOrderIssueSchedule issueSchedule) { final I_PP_Order_IssueSchedule record = InterfaceWrapperHelper.load(issueSchedule.getId(), I_PP_Order_IssueSchedule.class); final PPOrderIssueSchedule.Issued issued = issueSchedule.getIssued(); final boolean processed = issued != null; final Quantity qtyIssued = issued != null ? issued.getQtyIssued() : null; final QtyRejectedWithReason qtyRejected = issued != null ? issued.getQtyRejected() : null; record.setSeqNo(issueSchedule.getSeqNo().toInt()); record.setProcessed(processed); record.setQtyIssued(qtyIssued != null ? qtyIssued.toBigDecimal() : BigDecimal.ZERO); record.setQtyReject(qtyRejected != null ? qtyRejected.toBigDecimal() : BigDecimal.ZERO); record.setRejectReason(qtyRejected != null ? qtyRejected.getReasonCode().getCode() : null); record.setQtyToIssue(issueSchedule.getQtyToIssue().toBigDecimal()); record.setC_UOM_ID(issueSchedule.getQtyToIssue().getUomId().getRepoId()); InterfaceWrapperHelper.save(record); } public void deleteNotProcessedByOrderId(@NonNull final PPOrderId ppOrderId) { queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class) .addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_ID, ppOrderId) .addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_Processed, false) .create() .delete(); } public void deleteNotProcessedById(@NonNull final PPOrderIssueScheduleId issueScheduleId) { queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class)
.addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_IssueSchedule_ID, issueScheduleId) .addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_Processed, false) .create() .delete(); } public boolean matchesByOrderId(@NonNull final PPOrderId ppOrderId) { return queryBL.createQueryBuilder(I_PP_Order_IssueSchedule.class) .addEqualsFilter(I_PP_Order_IssueSchedule.COLUMNNAME_PP_Order_ID, ppOrderId) .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\issue_schedule\PPOrderIssueScheduleRepository.java
1
请完成以下Java代码
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord) { this.assignment = assignmentRecord; return updateFromRecord(assignmentRecord); } private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord) { setTopLevelHU(assignmentRecord.getM_HU()); setM_LU_HU(assignmentRecord.getM_LU_HU()); setM_TU_HU(assignmentRecord.getM_TU_HU()); setVHU(assignmentRecord.getVHU()); setQty(assignmentRecord.getQty()); setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials()); setIsActive(assignmentRecord.isActive()); return this; } @Override public I_M_HU_Assignment build() { Check.assumeNotNull(model, "model not null"); Check.assumeNotNull(topLevelHU, "topLevelHU not null"); Check.assumeNotNull(assignment, "assignment not null"); TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU); assignment.setM_LU_HU(luHU); assignment.setM_TU_HU(tuHU); assignment.setVHU(vhu); assignment.setQty(qty); assignment.setIsTransferPackingMaterials(isTransferPackingMaterials); assignment.setIsActive(isActive); InterfaceWrapperHelper.save(assignment); return assignment; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java
1
请完成以下Java代码
private ExplainedOptional<Plan> creatPlan() { return createPlan(getPaymentRowsSelectedForAllocation()); } private static ITranslatableString computeCaption(final Amount writeOffAmt) { return TranslatableStrings.builder() .appendADElement("PaymentWriteOffAmt").append(": ").append(writeOffAmt) .build(); } @Override protected String doIt() { final Plan plan = creatPlan().orElseThrow(); final PaymentAmtMultiplier amtMultiplier = plan.getAmtMultiplier(); final Amount amountToWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToWriteOff()); paymentBL.paymentWriteOff( plan.getPaymentId(), amountToWriteOff.toMoney(moneyService::getCurrencyIdByCurrencyCode), p_DateTrx.atStartOfDay(SystemTime.zoneId()).toInstant(), null); return MSG_OK; } // // // private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<PaymentRow> paymentRows) { if (paymentRows.size() != 1)
{ return ExplainedOptional.emptyBecause("Only one payment row can be selected for write-off"); } final PaymentRow paymentRow = CollectionUtils.singleElement(paymentRows); final Amount openAmt = paymentRow.getOpenAmt(); if (openAmt.signum() == 0) { return ExplainedOptional.emptyBecause("Zero open amount. Nothing to write-off"); } return ExplainedOptional.of( Plan.builder() .paymentId(paymentRow.getPaymentId()) .amtMultiplier(paymentRow.getPaymentAmtMultiplier()) .amountToWriteOff(openAmt) .build()); } @Value @Builder private static class Plan { @NonNull PaymentId paymentId; @NonNull PaymentAmtMultiplier amtMultiplier; @NonNull Amount amountToWriteOff; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_PaymentWriteOff.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, String> getMaximumExpectedValue() { return this.maximumExpectedValue; } public Map<String, Duration> getExpiry() { return this.expiry; } public Map<String, Integer> getBufferLength() { return this.bufferLength; } } public static class Observations {
/** * Meters that should be ignored when recoding observations. */ private Set<IgnoredMeters> ignoredMeters = new LinkedHashSet<>(); public Set<IgnoredMeters> getIgnoredMeters() { return this.ignoredMeters; } public void setIgnoredMeters(Set<IgnoredMeters> ignoredMeters) { this.ignoredMeters = ignoredMeters; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\MetricsProperties.java
2
请完成以下Java代码
public static String messageToxml(BaseMessage message) { XStream xstream = new XStream(); xstream.alias("xml", message.getClass()); return xstream.toXML(message); } /** * 封装发送消息对象,封装时,需要将调换发送者和接收者的关系 * * @param FromUserName * @param ToUserName */ public static String subscribeMessage(String FromUserName, String ToUserName) { String message = "Hi!我的小伙伴~欢迎关注人事情报科!\n" + "\n" + "快速搜索查看2000万人才简历,点击<a href=\"http://wx.rchezi.com\">【搜索】</a>\n" + "\n" + "与HR和猎头加好友交换简历~~点击 <a href=\"http://www.rchezi.com/?from=WeChatGZH\">【交换简历】</a>\n" + "\n" + "体验产品,领新手红包,点击<a href=\"http://channel.rchezi.com/download?c=WeChatGZH\">【下载App】</a>\n" + "\n" + "更多人事资讯请时刻关注我们哦,定期免费课程大放送~"; return reversalMessage(FromUserName, ToUserName, message); } /** * 封装发送消息对象,封装时,需要将调换发送者和接收者的关系 * * @param fromUserName * @param toUserName * @param Content */ public static String reversalMessage(String fromUserName, String toUserName, String Content) { TextMessage text = new TextMessage(); text.setToUserName(fromUserName); text.setFromUserName(toUserName); text.setContent(Content); text.setCreateTime(new Date().getTime()); text.setMsgType(ReqType.TEXT); return messageToxml(text); } /** * 封装voice消息对象 * * @param fromUserName * @param toUserName * @param mediaId
* @return */ public static String reversalVoiceMessage(String fromUserName, String toUserName, String mediaId) { VoiceMessage voiceMessage = new VoiceMessage(); voiceMessage.setToUserName(fromUserName); voiceMessage.setFromUserName(toUserName); voiceMessage.setVoice(new Voice(mediaId)); voiceMessage.setCreateTime(new Date().getTime()); voiceMessage.setMsgType(ReqType.VOICE); return messageToxml(voiceMessage); } /** * 判断是否是QQ表情 * * @param content * @return */ public static boolean isQqFace(String content) { boolean result = false; // 判断QQ表情的正则表达式 Matcher m = p.matcher(content); if (m.matches()) { result = true; } return result; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\utils\MessageUtil.java
1
请完成以下Java代码
public class ArticleLink { @From private Article article; @To private Author author; public ArticleLink() { } public ArticleLink(Article article, Author author) { this.article = article; this.author = author; }
public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } }
repos\tutorials-master\persistence-modules\spring-data-arangodb\src\main\java\com\baeldung\arangodb\model\ArticleLink.java
1
请完成以下Java代码
public void configurePolymorphicTypeValidator(BasicPolymorphicTypeValidator.Builder builder) { builder.allowIfSubType(OAuth2AuthenticationException.class) .allowIfSubType(DefaultOidcUser.class) .allowIfSubType(OAuth2AuthorizationRequest.class) .allowIfSubType(OAuth2Error.class) .allowIfSubType(OAuth2AuthorizedClient.class) .allowIfSubType(OidcIdToken.class) .allowIfSubType(OidcUserInfo.class) .allowIfSubType(DefaultOAuth2User.class) .allowIfSubType(ClientRegistration.class) .allowIfSubType(OAuth2AccessToken.class) .allowIfSubType(OAuth2RefreshToken.class) .allowIfSubType(OAuth2AuthenticationToken.class) .allowIfSubType(OidcUserAuthority.class) .allowIfSubType(OAuth2UserAuthority.class); } @Override public void setupModule(SetupContext context) {
context.setMixIn(OAuth2AuthorizationRequest.class, OAuth2AuthorizationRequestMixin.class); context.setMixIn(ClientRegistration.class, ClientRegistrationMixin.class); context.setMixIn(OAuth2AccessToken.class, OAuth2AccessTokenMixin.class); context.setMixIn(OAuth2RefreshToken.class, OAuth2RefreshTokenMixin.class); context.setMixIn(OAuth2AuthorizedClient.class, OAuth2AuthorizedClientMixin.class); context.setMixIn(OAuth2UserAuthority.class, OAuth2UserAuthorityMixin.class); context.setMixIn(DefaultOAuth2User.class, DefaultOAuth2UserMixin.class); context.setMixIn(OidcIdToken.class, OidcIdTokenMixin.class); context.setMixIn(OidcUserInfo.class, OidcUserInfoMixin.class); context.setMixIn(OidcUserAuthority.class, OidcUserAuthorityMixin.class); context.setMixIn(DefaultOidcUser.class, DefaultOidcUserMixin.class); context.setMixIn(OAuth2AuthenticationToken.class, OAuth2AuthenticationTokenMixin.class); context.setMixIn(OAuth2AuthenticationException.class, OAuth2AuthenticationExceptionMixin.class); context.setMixIn(OAuth2Error.class, OAuth2ErrorMixin.class); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\jackson\OAuth2ClientJacksonModule.java
1
请完成以下Java代码
public static JSONLookupValuesPage of( @Nullable final LookupValuesPage page, @NonNull final String adLanguage) { return of(page, adLanguage, false); } public static JSONLookupValuesPage of( @Nullable final LookupValuesPage page, @NonNull final String adLanguage, @Nullable final Boolean isAlwaysDisplayNewBPartner) { if (page == null || page.isEmpty()) { return EMPTY;
} else { return builder() .values(JSONLookupValuesList.toListOfJSONLookupValues(page.getValues(), adLanguage, false)) .hasMoreResults(page.getHasMoreResults().toBooleanOrNull()) .isAlwaysDisplayNewBPartner(isAlwaysDisplayNewBPartner) .build(); } } public static JSONLookupValuesPage error(@NonNull final JsonErrorItem error) { return builder().error(error).values(ImmutableList.of()).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONLookupValuesPage.java
1
请完成以下Java代码
public boolean isMandatoryWithholding () { Object oo = get_Value(COLUMNNAME_IsMandatoryWithholding); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Temporary exempt. @param IsTemporaryExempt Temporarily do not withhold taxes */ public void setIsTemporaryExempt (boolean IsTemporaryExempt) {
set_Value (COLUMNNAME_IsTemporaryExempt, Boolean.valueOf(IsTemporaryExempt)); } /** Get Temporary exempt. @return Temporarily do not withhold taxes */ public boolean isTemporaryExempt () { Object oo = get_Value(COLUMNNAME_IsTemporaryExempt); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Withholding.java
1
请在Spring Boot框架中完成以下Java代码
public String getDeploymentUrl() { return deploymentUrl; } public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testCase.cmmn", value = "Contains the actual deployed CMMN 1.1 xml.") public String getResource() { return resource; } @ApiModelProperty(example = "This is a case for testing purposes") public String getDescription() { return description; } public void setDescription(String description) {
this.description = description; } public void setDiagramResource(String diagramResource) { this.diagramResource = diagramResource; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the case, null when no diagram is available.") public String getDiagramResource() { return diagramResource; } public void setGraphicalNotationDefined(boolean graphicalNotationDefined) { this.graphicalNotationDefined = graphicalNotationDefined; } @ApiModelProperty(value = "Indicates the case definition contains graphical information (CMMN DI).") public boolean isGraphicalNotationDefined() { return graphicalNotationDefined; } public void setStartFormDefined(boolean startFormDefined) { this.startFormDefined = startFormDefined; } public boolean isStartFormDefined() { return startFormDefined; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionResponse.java
2
请完成以下Java代码
public class CamundaPotentialStarterImpl extends BpmnModelElementInstanceImpl implements CamundaPotentialStarter { protected static ChildElement<ResourceAssignmentExpression> resourceAssignmentExpressionChild; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CamundaPotentialStarter.class, CAMUNDA_ELEMENT_POTENTIAL_STARTER) .namespaceUri(CAMUNDA_NS) .instanceProvider(new ModelTypeInstanceProvider<CamundaPotentialStarter>() { public CamundaPotentialStarter newInstance(ModelTypeInstanceContext instanceContext) { return new CamundaPotentialStarterImpl(instanceContext); } }); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); resourceAssignmentExpressionChild = sequenceBuilder.element(ResourceAssignmentExpression.class) .build();
typeBuilder.build(); } public CamundaPotentialStarterImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public ResourceAssignmentExpression getResourceAssignmentExpression() { return resourceAssignmentExpressionChild.getChild(this); } public void setResourceAssignmentExpression(ResourceAssignmentExpression resourceAssignmentExpression) { resourceAssignmentExpressionChild.setChild(this, resourceAssignmentExpression); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaPotentialStarterImpl.java
1
请完成以下Java代码
public JobQuery tenantIdIn(String... tenantIds) { ensureNotNull("tenantIds", (Object[]) tenantIds); this.tenantIds = tenantIds; isTenantIdSet = true; return this; } public JobQuery withoutTenantId() { isTenantIdSet = true; this.tenantIds = null; return this; } public JobQuery includeJobsWithoutTenantId() { this.includeJobsWithoutTenantId = true; return this; } //sorting ////////////////////////////////////////// public JobQuery orderByJobDuedate() { return orderBy(JobQueryProperty.DUEDATE); } public JobQuery orderByExecutionId() { return orderBy(JobQueryProperty.EXECUTION_ID); } public JobQuery orderByJobId() { return orderBy(JobQueryProperty.JOB_ID); } public JobQuery orderByProcessInstanceId() { return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID); } public JobQuery orderByProcessDefinitionId() { return orderBy(JobQueryProperty.PROCESS_DEFINITION_ID); } public JobQuery orderByProcessDefinitionKey() { return orderBy(JobQueryProperty.PROCESS_DEFINITION_KEY); } public JobQuery orderByJobRetries() { return orderBy(JobQueryProperty.RETRIES); } public JobQuery orderByJobPriority() { return orderBy(JobQueryProperty.PRIORITY); } public JobQuery orderByTenantId() { return orderBy(JobQueryProperty.TENANT_ID); } //results ////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobManager() .findJobCountByQueryCriteria(this); } @Override public List<Job> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getJobManager() .findJobsByQueryCriteria(this, page); } @Override public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) { checkQueryOk(); return commandContext .getJobManager() .findDeploymentIdMappingsByQueryCriteria(this); }
//getters ////////////////////////////////////////// public Set<String> getIds() { return ids; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getProcessInstanceId() { return processInstanceId; } public Set<String> getProcessInstanceIds() { return processInstanceIds; } public String getExecutionId() { return executionId; } public boolean getRetriesLeft() { return retriesLeft; } public boolean getExecutable() { return executable; } public Date getNow() { return ClockUtil.getCurrentTime(); } public boolean isWithException() { return withException; } public String getExceptionMessage() { return exceptionMessage; } public boolean getAcquired() { return acquired; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobQueryImpl.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public org.compiere.model.I_AD_Tree getAD_Tree() { return get_ValueAsPO(COLUMNNAME_AD_Tree_ID, org.compiere.model.I_AD_Tree.class); } @Override public void setAD_Tree(final org.compiere.model.I_AD_Tree AD_Tree) { set_ValueFromPO(COLUMNNAME_AD_Tree_ID, org.compiere.model.I_AD_Tree.class, AD_Tree); } @Override public void setAD_Tree_ID (final int AD_Tree_ID) { if (AD_Tree_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, AD_Tree_ID); } @Override public int getAD_Tree_ID() { return get_ValueAsInt(COLUMNNAME_AD_Tree_ID); } @Override public void setC_Element_ID (final int C_Element_ID) { if (C_Element_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Element_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Element_ID, C_Element_ID); } @Override public int getC_Element_ID() { return get_ValueAsInt(COLUMNNAME_C_Element_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * ElementType AD_Reference_ID=116 * Reference name: C_Element Type */ public static final int ELEMENTTYPE_AD_Reference_ID=116; /** Account = A */ public static final String ELEMENTTYPE_Account = "A"; /** UserDefined = U */ public static final String ELEMENTTYPE_UserDefined = "U"; @Override public void setElementType (final java.lang.String ElementType)
{ set_ValueNoCheck (COLUMNNAME_ElementType, ElementType); } @Override public java.lang.String getElementType() { return get_ValueAsString(COLUMNNAME_ElementType); } @Override public void setIsBalancing (final boolean IsBalancing) { set_Value (COLUMNNAME_IsBalancing, IsBalancing); } @Override public boolean isBalancing() { return get_ValueAsBoolean(COLUMNNAME_IsBalancing); } @Override public void setIsNaturalAccount (final boolean IsNaturalAccount) { set_Value (COLUMNNAME_IsNaturalAccount, IsNaturalAccount); } @Override public boolean isNaturalAccount() { return get_ValueAsBoolean(COLUMNNAME_IsNaturalAccount); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setVFormat (final @Nullable java.lang.String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } @Override public java.lang.String getVFormat() { return get_ValueAsString(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Element.java
1
请在Spring Boot框架中完成以下Java代码
public String getCaseDefinitionDescription() { return caseDefinitionDescription; } public void setCaseDefinitionDescription(String caseDefinitionDescription) { this.caseDefinitionDescription = caseDefinitionDescription; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @ApiModelProperty(example = "kermit") public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } @ApiModelProperty(example = "kermit") public String getEndUserId() { return endUserId; } public void setEndUserId(String endUserId) { this.endUserId = endUserId; } @ApiModelProperty(example = "3") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) {
variables.add(variable); } @ApiModelProperty(example = "null") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } @ApiModelProperty(example = "active") public String getState() { return state; } public void setState(String state) { this.state = state; } @ApiModelProperty(example = "123") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请完成以下Java代码
public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile"); } // create path and map variables final Map<String, Object> uriVariables = new HashMap<String, Object>(); uriVariables.put("petId", petId); String path = UriComponentsBuilder.fromPath("/pet/{petId}/uploadImage").buildAndExpand(uriVariables).toUriString(); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); if (additionalMetadata != null) formParams.add("additionalMetadata", additionalMetadata);
if (file != null) formParams.add("file", new FileSystemResource(file)); final String[] accepts = { "application/json" }; final List<MediaType> accept = apiClient.selectHeaderAccept(accepts); final String[] contentTypes = { "multipart/form-data" }; final MediaType contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {}; return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\api\PetApi.java
1
请完成以下Java代码
public List<DataEntryRecord> list(@NonNull final DataEntryRecordQuery query) { return stream(query).collect(ImmutableList.toImmutableList()); } public Stream<DataEntryRecord> stream(@NonNull final DataEntryRecordQuery query) { return query(query) .stream() .map(this::toDataEntryRecord); } public DataEntryRecord getById(@NonNull final DataEntryRecordId dataEntryRecordId) { final I_DataEntry_Record record = getRecordById(dataEntryRecordId); return toDataEntryRecord(record); } private I_DataEntry_Record getRecordById(final DataEntryRecordId dataEntryRecordId) { return load(dataEntryRecordId, I_DataEntry_Record.class); } private DataEntryRecord toDataEntryRecord(@NonNull final I_DataEntry_Record record) { final String jsonString = record.getDataEntry_RecordData(); final List<DataEntryRecordField<?>> fields = jsonDataEntryRecordMapper.deserialize(jsonString); return DataEntryRecord.builder() .id(DataEntryRecordId.ofRepoId(record.getDataEntry_Record_ID())) .dataEntrySubTabId(DataEntrySubTabId.ofRepoId(record.getDataEntry_SubTab_ID())) .mainRecord(TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID())) .fields(fields) .build(); } public DataEntryRecordId save(@NonNull final DataEntryRecord dataEntryRecord) { final I_DataEntry_Record dataRecord; final DataEntryRecordId existingId = dataEntryRecord.getId().orElse(null); if (existingId == null) { dataRecord = newInstance(I_DataEntry_Record.class); } else { dataRecord = getRecordById(existingId); } dataRecord.setAD_Table_ID(dataEntryRecord.getMainRecord().getAD_Table_ID()); dataRecord.setRecord_ID(dataEntryRecord.getMainRecord().getRecord_ID()); dataRecord.setDataEntry_SubTab_ID(dataEntryRecord.getDataEntrySubTabId().getRepoId()); dataRecord.setIsActive(true); final String jsonString = jsonDataEntryRecordMapper.serialize(dataEntryRecord.getFields()); dataRecord.setDataEntry_RecordData(jsonString); saveRecord(dataRecord);
final DataEntryRecordId dataEntryRecordId = DataEntryRecordId.ofRepoId(dataRecord.getDataEntry_Record_ID()); dataEntryRecord.setId(dataEntryRecordId); return dataEntryRecordId; } public void deleteBy(@NonNull final DataEntryRecordQuery query) { query(query).delete(); } private IQuery<I_DataEntry_Record> query(@NonNull final DataEntryRecordQuery query) { final ImmutableSet<DataEntrySubTabId> dataEntrySubTabIds = query.getDataEntrySubTabIds(); final int recordId = query.getRecordId(); return Services.get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Record.class) .addOnlyActiveRecordsFilter() // we have a UC on those columns .addInArrayFilter(I_DataEntry_Record.COLUMN_DataEntry_SubTab_ID, dataEntrySubTabIds) .addEqualsFilter(I_DataEntry_Record.COLUMN_Record_ID, recordId) .orderBy(I_DataEntry_Record.COLUMNNAME_DataEntry_SubTab_ID) .create(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecordRepository.java
1
请完成以下Java代码
public static GlobalQRCodeParseResult parse(@NonNull final String string) { String remainingString = string; // // Extract type final GlobalQRCodeType type; { int idx = remainingString.indexOf(SEPARATOR); if (idx <= 0) { return GlobalQRCodeParseResult.error("Invalid global QR code(1): " + string); } type = GlobalQRCodeType.ofString(remainingString.substring(0, idx)); remainingString = remainingString.substring(idx + 1); } // // Extract version final GlobalQRCodeVersion version; { int idx = remainingString.indexOf(SEPARATOR); if (idx <= 0) { return GlobalQRCodeParseResult.error("Invalid global QR code(2): " + string); } version = GlobalQRCodeVersion.ofString(remainingString.substring(0, idx)); remainingString = remainingString.substring(idx + 1); } // // Payload final String payloadAsJson = remainingString; // return GlobalQRCodeParseResult.ok(builder() .type(type) .version(version) .payloadAsJson(payloadAsJson) .build()); } public <T> T getPayloadAs(@NonNull final Class<T> type) { try { return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(payloadAsJson, type); } catch (JsonProcessingException e) {
throw Check.mkEx("Failed converting payload to `" + type + "`: " + payloadAsJson, e); } } @Override @Deprecated public String toString() { return getAsString(); } @JsonValue public String getAsString() { return type.toJson() + SEPARATOR + version + SEPARATOR + payloadAsJson; } public static boolean equals(@Nullable GlobalQRCode o1, @Nullable GlobalQRCode o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.api\src\main\java\de\metas\global_qrcodes\GlobalQRCode.java
1
请完成以下Java代码
public void init(@NonNull final ClientId clientId) { if (endpoint == null) { final String endpointClassname = Services.get(ISysConfigBL.class).getValue( RemoteArchiveStorage.SYSCONFIG_ArchiveEndpoint, RemoteArchiveStorage.DEFAULT_ArchiveEndpoint, clientId.getRepoId() ); endpoint = Util.getInstance(IArchiveEndpoint.class, endpointClassname); } } public IArchiveEndpoint getEndpoint() { return endpoint; } private final void checkContext() { Check.assume(Ini.isSwingClient(), "RemoveArchive requires client mode"); Check.assumeNotNull(endpoint, "endpoint is configured"); } @Override public byte[] getBinaryData(final I_AD_Archive archive) { checkContext(); Check.assumeNotNull(archive, "archive not null"); final int archiveId = archive.getAD_Archive_ID(); if (archiveId <= 0) { // FIXME: handle the case when adArchiveId <= 0 throw new IllegalStateException("Retrieving data from a not saved archived is not supported: " + archive); } final ArchiveGetDataRequest request = new ArchiveGetDataRequest(); request.setAdArchiveId(archiveId); final ArchiveGetDataResponse response = endpoint.getArchiveData(request); return response.getData(); } @Override public void setBinaryData(final I_AD_Archive archive, final byte[] data) { checkContext(); Check.assumeNotNull(archive, "archive not null"); final int archiveId = archive.getAD_Archive_ID(); final ArchiveSetDataRequest request = new ArchiveSetDataRequest(); request.setAdArchiveId(archiveId);
request.setData(data); final ArchiveSetDataResponse response = endpoint.setArchiveData(request); final int tempArchiveId = response.getAdArchiveId(); transferData(archive, tempArchiveId); } private void transferData(final I_AD_Archive archive, final int fromTempArchiveId) { Check.assume(fromTempArchiveId > 0, "fromTempArchiveId > 0"); final Properties ctx = InterfaceWrapperHelper.getCtx(archive); final String trxName = InterfaceWrapperHelper.getTrxName(archive); final I_AD_Archive tempArchive = InterfaceWrapperHelper.create(ctx, fromTempArchiveId, I_AD_Archive.class, trxName); Check.assumeNotNull(tempArchive, "Temporary archive not found for AD_Archive_ID={}", fromTempArchiveId); transferData(archive, tempArchive); InterfaceWrapperHelper.delete(tempArchive); } private void transferData(final I_AD_Archive archive, final I_AD_Archive fromTempArchive) { Check.assume(fromTempArchive.isFileSystem(), "Temporary archive {} shall be saved in filesystem", fromTempArchive); archive.setIsFileSystem(fromTempArchive.isFileSystem()); archive.setBinaryData(fromTempArchive.getBinaryData()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\spi\impl\RemoteArchiveStorage.java
1
请完成以下Java代码
public boolean load(ByteArray byteArray) { boolean result = super.load(byteArray); if (result) { initTagSet(); } return result; } @Override protected void onLoadTxtFinished() { super.onLoadTxtFinished(); initTagSet(); } @Override public void tag(Table table) { int size = table.size(); if (size == 1) { table.setLast(0, "S"); return; } double[][] net = new double[size][4]; for (int i = 0; i < size; ++i) { LinkedList<double[]> scoreList = computeScoreList(table, i); for (int tag = 0; tag < 4; ++tag) { net[i][tag] = computeScore(scoreList, tag); } } net[0][idM] = -1000.0; // 第一个字不可能是M或E net[0][idE] = -1000.0; int[][] from = new int[size][4];
double[][] maxScoreAt = new double[2][4]; // 滚动数组 System.arraycopy(net[0], 0, maxScoreAt[0], 0, 4); // 初始preI=0, maxScoreAt[preI][pre] = net[0][pre] int curI = 0; for (int i = 1; i < size; ++i) { curI = i & 1; int preI = 1 - curI; for (int now = 0; now < 4; ++now) { double maxScore = -1e10; for (int pre = 0; pre < 4; ++pre) { double score = maxScoreAt[preI][pre] + matrix[pre][now] + net[i][now]; if (score > maxScore) { maxScore = score; from[i][now] = pre; maxScoreAt[curI][now] = maxScore; } } net[i][now] = maxScore; } } // 反向回溯最佳路径 int maxTag = maxScoreAt[curI][idS] > maxScoreAt[curI][idE] ? idS : idE; table.setLast(size - 1, id2tag[maxTag]); maxTag = from[size - 1][maxTag]; for (int i = size - 2; i > 0; --i) { table.setLast(i, id2tag[maxTag]); maxTag = from[i][maxTag]; } table.setLast(0, id2tag[maxTag]); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\CRFSegmentModel.java
1
请在Spring Boot框架中完成以下Java代码
public Converter<List<SystemRuleEntity>, String> systemRuleRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<SystemRuleEntity>> systemRuleRuleEntityDecoder() { return s -> JSON.parseArray(s, SystemRuleEntity.class); } /** * 授权规则 * @return */ @Bean public Converter<List<AuthorityRuleCorrectEntity>, String> authorityRuleRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<AuthorityRuleCorrectEntity>> authorityRuleRuleEntityDecoder() { return s -> JSON.parseArray(s, AuthorityRuleCorrectEntity.class); } /** * 网关API * * @return * @throws Exception */ @Bean public Converter<List<ApiDefinitionEntity>, String> apiDefinitionEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<ApiDefinitionEntity>> apiDefinitionEntityDecoder() { return s -> JSON.parseArray(s, ApiDefinitionEntity.class); } /** * 网关flowRule * * @return * @throws Exception */ @Bean public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() { return JSON::toJSONString; }
@Bean public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() { return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class); } @Bean public ConfigService nacosConfigService() throws Exception { Properties properties=new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR,nacosConfigProperties.getServerAddr()); if(StringUtils.isNotBlank(nacosConfigProperties.getUsername())){ properties.put(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername()); } if(StringUtils.isNotBlank(nacosConfigProperties.getPassword())){ properties.put(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword()); } if(StringUtils.isNotBlank(nacosConfigProperties.getNamespace())){ properties.put(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace()); } return ConfigFactory.createConfigService(properties); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\SentinelConfig.java
2
请完成以下Java代码
public int getM_Product_ID() { return ddOrderLine.getM_Product_ID(); } @Override public void setM_Product_ID(final int productId) { ddOrderLine.setM_Product_ID(productId); values.setM_Product_ID(productId); } @Override public void setQty(final BigDecimal qty) { ddOrderLine.setQtyEntered(qty); final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID()); final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID()); final BigDecimal qtyOrdered = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty); ddOrderLine.setQtyOrdered(qtyOrdered); values.setQty(qty); } @Override public BigDecimal getQty() { return ddOrderLine.getQtyEntered(); } @Override public int getM_HU_PI_Item_Product_ID() { return ddOrderLine.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { ddOrderLine.setM_HU_PI_Item_Product_ID(huPiItemProductId); values.setM_HU_PI_Item_Product_ID(huPiItemProductId); } @Override public int getM_AttributeSetInstance_ID() { return ddOrderLine.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { ddOrderLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
} @Override public int getC_UOM_ID() { return ddOrderLine.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { values.setC_UOM_ID(uomId); // NOTE: uom is mandatory // we assume orderLine's UOM is correct if (uomId > 0) { ddOrderLine.setC_UOM_ID(uomId); } } @Override public BigDecimal getQtyTU() { return ddOrderLine.getQtyEnteredTU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { ddOrderLine.setQtyEnteredTU(qtyPacks); values.setQtyTU(qtyPacks); } @Override public boolean isInDispute() { // order line has no IsInDispute flag return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } @Override public void setC_BPartner_ID(final int partnerId) { // nothing } @Override public int getC_BPartner_ID() { return ddOrderLine.getDD_Order().getC_BPartner_ID(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\lowlevel\model\DDOrderLineHUPackingAware.java
1
请完成以下Java代码
private static IPricingResult invokePricingEngine(@NonNull final IPricingContext subscriptionPricingCtx) { final IPricingBL pricingBL = Services.get(IPricingBL.class); return pricingBL.calculatePrice(subscriptionPricingCtx); } /** * Copy the results of our internal call into 'result' */ private static void copySubscriptionResultIntoResult( @NonNull final IPricingResult subscriptionPricingResult, @NonNull final IPricingResult result) { if (Util.same(subscriptionPricingResult, result)) { return; // no need to copy anything } result.setCurrencyId(subscriptionPricingResult.getCurrencyId()); result.setPriceUomId(subscriptionPricingResult.getPriceUomId()); result.setCalculated(subscriptionPricingResult.isCalculated()); result.setDisallowDiscount(subscriptionPricingResult.isDisallowDiscount()); result.setUsesDiscountSchema(subscriptionPricingResult.isUsesDiscountSchema()); result.setPricingConditions(subscriptionPricingResult.getPricingConditions()); result.setEnforcePriceLimit(subscriptionPricingResult.getEnforcePriceLimit()); result.setPricingSystemId(subscriptionPricingResult.getPricingSystemId()); result.setPriceListVersionId(subscriptionPricingResult.getPriceListVersionId()); result.setProductCategoryId(subscriptionPricingResult.getProductCategoryId()); result.setPrecision(subscriptionPricingResult.getPrecision()); result.setPriceLimit(subscriptionPricingResult.getPriceLimit());
result.setPriceList(subscriptionPricingResult.getPriceList()); result.setPriceStd(subscriptionPricingResult.getPriceStd()); result.setTaxIncluded(subscriptionPricingResult.isTaxIncluded()); result.setTaxCategoryId(subscriptionPricingResult.getTaxCategoryId()); result.setPriceEditable(subscriptionPricingResult.isPriceEditable()); } private static void copyDiscountIntoResultIfAllowedByPricingContext( @NonNull final IPricingResult subscriptionPricingResult, @NonNull final IPricingResult result, @NonNull final IPricingContext pricingCtx) { if (!pricingCtx.isDisallowDiscount()) { if (result.isDiscountEditable()) { result.setDiscount(subscriptionPricingResult.getDiscount()); result.setDiscountEditable(subscriptionPricingResult.isDiscountEditable()); result.setDontOverrideDiscountAdvice(subscriptionPricingResult.isDontOverrideDiscountAdvice()); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\SubscriptionPricingRule.java
1
请在Spring Boot框架中完成以下Java代码
public void initBinder(WebDataBinder binder) { // Date - dd/MM/yyyy SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); } //@RequestMapping(value = "/list-todos", method = RequestMethod.GET) @GetMapping(value = "/list-todos") public String showTodos(ModelMap model) { String name = getLoggedInUserName(model); model.put("todos", todoService.getTodosByUser(name)); // model.put("todos", service.retrieveTodos(name)); return "list-todos"; } private String getLoggedInUserName(ModelMap model) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } return principal.toString(); } @RequestMapping(value = "/add-todo", method = RequestMethod.GET) public String showAddTodoPage(ModelMap model) { model.addAttribute("todo", new Todo()); return "todo"; } @RequestMapping(value = "/delete-todo", method = RequestMethod.GET) public String deleteTodo(@RequestParam long id) { todoService.deleteTodo(id); // service.deleteTodo(id); return "redirect:/list-todos"; } @RequestMapping(value = "/update-todo", method = RequestMethod.GET) public String showUpdateTodoPage(@RequestParam long id, ModelMap model) { Todo todo = todoService.getTodoById(id).get();
model.put("todo", todo); return "todo"; } @RequestMapping(value = "/update-todo", method = RequestMethod.POST) public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUserName(getLoggedInUserName(model)); todoService.updateTodo(todo); return "redirect:/list-todos"; } @RequestMapping(value = "/add-todo", method = RequestMethod.POST) public String addTodo(ModelMap model, @Valid Todo todo, BindingResult result) { if (result.hasErrors()) { return "todo"; } todo.setUserName(getLoggedInUserName(model)); todoService.saveTodo(todo); return "redirect:/list-todos"; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDB\src\main\java\spring\hibernate\controller\TodoController.java
2
请完成以下Java代码
public List<String> getY_() { return y_; } public void setY_(List<String> y_) { this.y_ = y_; } public List<List<Path>> getPathList_() { return pathList_; }
public void setPathList_(List<List<Path>> pathList_) { this.pathList_ = pathList_; } public List<List<Node>> getNodeList_() { return nodeList_; } public void setNodeList_(List<List<Node>> nodeList_) { this.nodeList_ = nodeList_; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java
1
请完成以下Java代码
public boolean apply(IAllocableDocRow row) { return row.isSelected(); } }; /** * Predicate: Only those which are NOT taboo * * @see #isTaboo() */ Predicate<IAllocableDocRow> PREDICATE_NoTaboo = new Predicate<IAllocableDocRow>() { @Override public boolean apply(IAllocableDocRow row) { return !row.isTaboo(); } }; Ordering<IAllocableDocRow> ORDERING_DocumentDate_DocumentNo = new Ordering<IAllocableDocRow>() { @Override public int compare(IAllocableDocRow row1, IAllocableDocRow row2) { return ComparisonChain.start() .compare(row1.getDocumentDate(), row2.getDocumentDate()) .compare(row1.getDocumentNo(), row2.getDocumentNo()) .result(); } }; //@formatter:off String PROPERTY_Selected = "Selected"; boolean isSelected(); void setSelected(boolean selected); //@formatter:on String getDocumentNo(); //@formatter:off BigDecimal getOpenAmtConv(); BigDecimal getOpenAmtConv_APAdjusted(); //@formatter:on //@formatter:off String PROPERTY_AppliedAmt = "AppliedAmt"; BigDecimal getAppliedAmt(); BigDecimal getAppliedAmt_APAdjusted(); void setAppliedAmt(BigDecimal appliedAmt); /** Sets applied amount and update the other write-off amounts, if needed. */ void setAppliedAmtAndUpdate(PaymentAllocationContext context, BigDecimal appliedAmt); //@formatter:on
/** @return true if automatic calculations and updating are allowed on this row; false if user manually set the amounts and we don't want to change them for him/her */ boolean isTaboo(); /** * @param taboo <ul> * <li>true if automatic calculations shall be disallowed on this row * <li>false if automatic calculations are allowed on this row * </ul> */ void setTaboo(boolean taboo); /** @return document's date */ Date getDocumentDate(); // task 09643: separate the accounting date from the transaction date Date getDateAcct(); int getC_BPartner_ID(); /** @return AP Multiplier, i.e. Vendor=-1, Customer=+1 */ BigDecimal getMultiplierAP(); boolean isVendorDocument(); boolean isCustomerDocument(); boolean isCreditMemo(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\IAllocableDocRow.java
1
请完成以下Java代码
public String getBaseUrl() { return urlResolver.getBaseUrl(); } protected String getWorkerId() { return workerId; } protected List<ClientRequestInterceptor> getInterceptors() { return interceptors; } protected int getMaxTasks() { return maxTasks; } protected Long getAsyncResponseTimeout() { return asyncResponseTimeout; } protected long getLockDuration() { return lockDuration; } protected boolean isAutoFetchingEnabled() { return isAutoFetchingEnabled; } protected BackoffStrategy getBackoffStrategy() { return backoffStrategy; } public String getDefaultSerializationFormat() {
return defaultSerializationFormat; } public String getDateFormat() { return dateFormat; } public ObjectMapper getObjectMapper() { return objectMapper; } public ValueMappers getValueMappers() { return valueMappers; } public TypedValues getTypedValues() { return typedValues; } public EngineClient getEngineClient() { return engineClient; } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\ExternalTaskClientBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
public String getCsvDir() { return csvDir; } public void setCsvDir(String csvDir) { this.csvDir = csvDir; } public String getCsvExeOffice() { return csvExeOffice; } public void setCsvExeOffice(String csvExeOffice) { this.csvExeOffice = csvExeOffice; } public String getCsvVtoll() { return csvVtoll; } public void setCsvVtoll(String csvVtoll) { this.csvVtoll = csvVtoll; } public String getCsvApp() { return csvApp; } public void setCsvApp(String csvApp) { this.csvApp = csvApp; } public String getCsvLog() {
return csvLog; } public void setCsvLog(String csvLog) { this.csvLog = csvLog; } public String getCsvCanton() { return csvCanton; } public void setCsvCanton(String csvCanton) { this.csvCanton = csvCanton; } public Integer getLocation() { return location; } public void setLocation(Integer location) { this.location = location; } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\config\properties\CommonProperties.java
2
请完成以下Java代码
public abstract class AbstractSetVariableAsyncCmd { protected void addVariable(boolean isLocal, String scopeId, String subScopeId, String varName, Object varValue, String tenantId, VariableService variableService) { VariableInstanceEntity variableInstance = variableService.createVariableInstance(varName); variableInstance.setScopeId(scopeId); variableInstance.setSubScopeId(subScopeId); variableInstance.setScopeType(ScopeTypes.CMMN_ASYNC_VARIABLES); variableInstance.setMetaInfo(String.valueOf(isLocal)); variableService.insertVariableInstanceWithValue(variableInstance, varValue, tenantId); } protected void createSetAsyncVariablesJob(CaseInstanceEntity caseInstanceEntity, CmmnEngineConfiguration cmmnEngineConfiguration) { JobServiceConfiguration jobServiceConfiguration = cmmnEngineConfiguration.getJobServiceConfiguration(); JobService jobService = jobServiceConfiguration.getJobService(); JobEntity job = jobService.createJob(); job.setScopeId(caseInstanceEntity.getId()); job.setScopeDefinitionId(caseInstanceEntity.getCaseDefinitionId()); job.setScopeType(ScopeTypes.CMMN); job.setJobHandlerType(SetAsyncVariablesJobHandler.TYPE); // Inherit tenant id (if applicable) if (caseInstanceEntity.getTenantId() != null) { job.setTenantId(caseInstanceEntity.getTenantId()); }
jobService.createAsyncJob(job, true); jobService.scheduleAsyncJob(job); } protected void createSetAsyncVariablesJob(PlanItemInstanceEntity planItemInstanceEntity, CmmnEngineConfiguration cmmnEngineConfiguration) { JobServiceConfiguration jobServiceConfiguration = cmmnEngineConfiguration.getJobServiceConfiguration(); JobService jobService = jobServiceConfiguration.getJobService(); JobEntity job = jobService.createJob(); job.setScopeId(planItemInstanceEntity.getCaseInstanceId()); job.setSubScopeId(planItemInstanceEntity.getId()); job.setScopeDefinitionId(planItemInstanceEntity.getCaseDefinitionId()); job.setScopeType(ScopeTypes.CMMN); job.setJobHandlerType(SetAsyncVariablesJobHandler.TYPE); // Inherit tenant id (if applicable) if (planItemInstanceEntity.getTenantId() != null) { job.setTenantId(planItemInstanceEntity.getTenantId()); } jobService.createAsyncJob(job, true); jobService.scheduleAsyncJob(job); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AbstractSetVariableAsyncCmd.java
1
请完成以下Java代码
public class ResponseProvider { /** * 成功 * * @param message 信息 * @return */ public static Map<String, Object> success(String message) { return response(200, message); } /** * 失败 * * @param message 信息 * @return */ public static Map<String, Object> fail(String message) { return response(400, message); } /** * 未授权 * * @param message 信息 * @return */ public static Map<String, Object> unAuth(String message) { return response(401, message); } /** * 服务器异常 * * @param message 信息 * @return
*/ public static Map<String, Object> error(String message) { return response(500, message); } /** * 构建返回的JSON数据格式 * * @param status 状态码 * @param message 信息 * @return */ public static Map<String, Object> response(int status, String message) { Map<String, Object> map = new HashMap<>(16); map.put("code", status); map.put("msg", message); map.put("data", null); return map; } }
repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\provider\ResponseProvider.java
1
请完成以下Java代码
int numOnes() { return _numOnes; } /** * 大小 * @return */ int size() { return _size; } /** * 在末尾追加 */ void append() { if ((_size % UNIT_SIZE) == 0) { _units.add(0); } ++_size; } /** * 构建 */ void build() { _ranks = new int[_units.size()]; _numOnes = 0; for (int i = 0; i < _units.size(); ++i) { _ranks[i] = _numOnes; _numOnes += popCount(_units.get(i)); } } /** * 清空 */ void clear() { _units.clear(); _ranks = null; } /** * 整型大小 */ private static final int UNIT_SIZE = 32; // sizeof(int) * 8 /** * 1的数量 * @param unit
* @return */ private static int popCount(int unit) { unit = ((unit & 0xAAAAAAAA) >>> 1) + (unit & 0x55555555); unit = ((unit & 0xCCCCCCCC) >>> 2) + (unit & 0x33333333); unit = ((unit >>> 4) + unit) & 0x0F0F0F0F; unit += unit >>> 8; unit += unit >>> 16; return unit & 0xFF; } /** * 储存空间 */ private AutoIntPool _units = new AutoIntPool(); /** * 是每个元素的1的个数的累加 */ private int[] _ranks; /** * 1的数量 */ private int _numOnes; /** * 大小 */ private int _size; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\BitVector.java
1
请完成以下Java代码
public void setSupportExpDate (java.sql.Timestamp SupportExpDate) { set_ValueNoCheck (COLUMNNAME_SupportExpDate, SupportExpDate); } /** Get Support Expires. @return Date when the Adempiere support expires */ @Override public java.sql.Timestamp getSupportExpDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_SupportExpDate); } /** Set Internal Users. @param SupportUnits Number of Internal Users for Adempiere Support */ @Override public void setSupportUnits (int SupportUnits) { set_ValueNoCheck (COLUMNNAME_SupportUnits, Integer.valueOf(SupportUnits)); } /** Get Internal Users. @return Number of Internal Users for Adempiere Support */ @Override public int getSupportUnits () { Integer ii = (Integer)get_Value(COLUMNNAME_SupportUnits); if (ii == null) return 0; return ii.intValue(); } /** * SystemStatus AD_Reference_ID=374 * Reference name: AD_System Status */ public static final int SYSTEMSTATUS_AD_Reference_ID=374; /** Evaluation = E */ public static final String SYSTEMSTATUS_Evaluation = "E"; /** Implementation = I */ public static final String SYSTEMSTATUS_Implementation = "I"; /** Production = P */ public static final String SYSTEMSTATUS_Production = "P"; /** Set System Status. @param SystemStatus Status of the system - Support priority depends on system status */ @Override public void setSystemStatus (java.lang.String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } /** Get System Status. @return Status of the system - Support priority depends on system status */ @Override
public java.lang.String getSystemStatus () { return (java.lang.String)get_Value(COLUMNNAME_SystemStatus); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ @Override public void setUserName (java.lang.String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ @Override public java.lang.String getUserName () { return (java.lang.String)get_Value(COLUMNNAME_UserName); } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_ValueNoCheck (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } /** Set ZK WebUI URL. @param WebUI_URL ZK WebUI root URL */ @Override public void setWebUI_URL (java.lang.String WebUI_URL) { set_Value (COLUMNNAME_WebUI_URL, WebUI_URL); } /** Get ZK WebUI URL. @return ZK WebUI root URL */ @Override public java.lang.String getWebUI_URL () { return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java
1
请完成以下Java代码
public String getLoopDataOutputRef() { return loopDataOutputRef; } public boolean hasLoopDataOutputRef() { return loopDataOutputRef != null && !loopDataOutputRef.trim().isEmpty(); } public void setLoopDataOutputRef(String loopDataOutputRef) { this.loopDataOutputRef = loopDataOutputRef; } public String getOutputDataItem() { return outputDataItem; } public boolean hasOutputDataItem() { return outputDataItem != null && !outputDataItem.trim().isEmpty(); } public void setOutputDataItem(String outputDataItem) { this.outputDataItem = outputDataItem; } protected void updateResultCollection(DelegateExecution childExecution, DelegateExecution miRootExecution) { if (miRootExecution != null && hasLoopDataOutputRef()) { Object loopDataOutputReference = miRootExecution.getVariableLocal(getLoopDataOutputRef()); List<Object> resultCollection; if (loopDataOutputReference instanceof List) { resultCollection = (List<Object>) loopDataOutputReference; } else { resultCollection = new ArrayList<>(); } resultCollection.add(getResultElementItem(childExecution)); setLoopVariable(miRootExecution, getLoopDataOutputRef(), resultCollection); } } protected Object getResultElementItem(DelegateExecution childExecution) { return getResultElementItem(childExecution.getVariablesLocal()); } protected CommandContext getCommandContext() { return Context.getCommandContext(); } protected Object getResultElementItem(Map<String, Object> availableVariables) { if (hasOutputDataItem()) { return availableVariables.get(getOutputDataItem());
} else { //exclude from the result all the built-in multi-instances variables //and loopDataOutputRef itself that may exist in the context depending // on the variable propagation List<String> resultItemExclusions = Arrays.asList( getLoopDataOutputRef(), getCollectionElementIndexVariable(), NUMBER_OF_INSTANCES, NUMBER_OF_COMPLETED_INSTANCES, NUMBER_OF_ACTIVE_INSTANCES ); HashMap<String, Object> resultItem = new HashMap<>(availableVariables); resultItemExclusions.forEach(resultItem.keySet()::remove); return resultItem; } } protected void propagateLoopDataOutputRefToProcessInstance(ExecutionEntity miRootExecution) { if (hasLoopDataOutputRef()) { miRootExecution .getProcessInstance() .setVariable(getLoopDataOutputRef(), miRootExecution.getVariable(getLoopDataOutputRef())); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\MultiInstanceActivityBehavior.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_AD_User getSupervisor() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getSupervisor_ID(), get_TrxName()); } /** Set Supervisor. @param Supervisor_ID Supervisor for this user/organization - used for escalation and approval */
public void setSupervisor_ID (int Supervisor_ID) { if (Supervisor_ID < 1) set_Value (COLUMNNAME_Supervisor_ID, null); else set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID)); } /** Get Supervisor. @return Supervisor for this user/organization - used for escalation and approval */ public int getSupervisor_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_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_AD_AlertProcessor.java
1
请在Spring Boot框架中完成以下Java代码
private PickingJob execute(@NonNull final PickingJob initialPickingJob) { //noinspection OptionalGetWithoutIsPresent return Stream.of(initialPickingJob) .sequential() .map(this::releasePickingSlotAndSave) // NOTE: abort is not "reversing", so we don't have to reverse (unpick) what we picked. // Even more, imagine that those picked things are already phisically splitted out. //.map(this::unpickAllStepsAndSave) .peek(huService::releaseAllReservations) .peek(pickingJobLockService::unlockSchedules) .map(this::markAsVoidedAndSave) .findFirst() .get(); } private PickingJob markAsVoidedAndSave(PickingJob pickingJob) { pickingJob = pickingJob.withDocStatus(PickingJobDocStatus.Voided); pickingJobRepository.save(pickingJob); return pickingJob; } // private PickingJob unpickAllStepsAndSave(final PickingJob pickingJob) // { // return PickingJobUnPickCommand.builder() // .pickingJobRepository(pickingJobRepository) // .pickingCandidateService(pickingCandidateService) // .pickingJob(pickingJob) // .build()
// .execute(); // } private PickingJob releasePickingSlotAndSave(PickingJob pickingJob) { final PickingJobId pickingJobId = pickingJob.getId(); final PickingSlotId pickingSlotId = pickingJob.getPickingSlotId().orElse(null); if (pickingSlotId != null) { pickingJob = pickingJob.withPickingSlot(null); pickingJobRepository.save(pickingJob); pickingSlotService.release(pickingSlotId, pickingJobId); } return pickingJob; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobAbortCommand.java
2
请完成以下Java代码
public java.lang.String getIsShowFilterInline() { return get_ValueAsString(COLUMNNAME_IsShowFilterInline); } @Override public void setMaxFacetsToFetch (final int MaxFacetsToFetch) { set_Value (COLUMNNAME_MaxFacetsToFetch, MaxFacetsToFetch); } @Override public int getMaxFacetsToFetch() { return get_ValueAsInt(COLUMNNAME_MaxFacetsToFetch); } @Override public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * ObscureType AD_Reference_ID=291 * Reference name: AD_Field ObscureType */ public static final int OBSCURETYPE_AD_Reference_ID=291; /** Obscure Digits but last 4 = 904 */ public static final String OBSCURETYPE_ObscureDigitsButLast4 = "904"; /** Obscure Digits but first/last 4 = 944 */ public static final String OBSCURETYPE_ObscureDigitsButFirstLast4 = "944"; /** Obscure AlphaNumeric but first/last 4 = A44 */ public static final String OBSCURETYPE_ObscureAlphaNumericButFirstLast4 = "A44"; /** Obscure AlphaNumeric but last 4 = A04 */ public static final String OBSCURETYPE_ObscureAlphaNumericButLast4 = "A04"; @Override public void setObscureType (final @Nullable java.lang.String ObscureType) { set_Value (COLUMNNAME_ObscureType, ObscureType); } @Override public java.lang.String getObscureType() { return get_ValueAsString(COLUMNNAME_ObscureType); } @Override public void setSelectionColumnSeqNo (final @Nullable BigDecimal SelectionColumnSeqNo) { set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo); } @Override public BigDecimal getSelectionColumnSeqNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SelectionColumnSeqNo); return bd != null ? bd : BigDecimal.ZERO; }
@Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNoGrid (final int SeqNoGrid) { set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid); } @Override public int getSeqNoGrid() { return get_ValueAsInt(COLUMNNAME_SeqNoGrid); } @Override public void setSortNo (final @Nullable BigDecimal SortNo) { set_Value (COLUMNNAME_SortNo, SortNo); } @Override public BigDecimal getSortNo() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setSpanX (final int SpanX) { set_Value (COLUMNNAME_SpanX, SpanX); } @Override public int getSpanX() { return get_ValueAsInt(COLUMNNAME_SpanX); } @Override public void setSpanY (final int SpanY) { set_Value (COLUMNNAME_SpanY, SpanY); } @Override public int getSpanY() { return get_ValueAsInt(COLUMNNAME_SpanY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java
1
请完成以下Java代码
public boolean hasId() { return fieldSetFlags()[0]; } /** * Clears the value of the 'id' field. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder clearId() { fieldSetFlags()[0] = false; return this; } /** * Gets the value of the 'departmentName' field. * @return The value. */ public java.lang.CharSequence getDepartmentName() { return departmentName; } /** * Sets the value of the 'departmentName' field. * @param value The value of 'departmentName'. * @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder setDepartmentName(java.lang.CharSequence value) { validate(fields()[1], value); this.departmentName = value; fieldSetFlags()[1] = true; return this; } /** * Checks whether the 'departmentName' field has been set. * @return True if the 'departmentName' field has been set, false otherwise. */ public boolean hasDepartmentName() { return fieldSetFlags()[1]; } /** * Clears the value of the 'departmentName' field.
* @return This builder. */ public com.baeldung.schema.EmployeeKey.Builder clearDepartmentName() { departmentName = null; fieldSetFlags()[1] = false; return this; } @Override @SuppressWarnings("unchecked") public EmployeeKey build() { try { EmployeeKey record = new EmployeeKey(); record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]); record.departmentName = fieldSetFlags()[1] ? this.departmentName : (java.lang.CharSequence) defaultValue(fields()[1]); return record; } catch (java.lang.Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumWriter<EmployeeKey> WRITER$ = (org.apache.avro.io.DatumWriter<EmployeeKey>)MODEL$.createDatumWriter(SCHEMA$); @Override public void writeExternal(java.io.ObjectOutput out) throws java.io.IOException { WRITER$.write(this, SpecificData.getEncoder(out)); } @SuppressWarnings("unchecked") private static final org.apache.avro.io.DatumReader<EmployeeKey> READER$ = (org.apache.avro.io.DatumReader<EmployeeKey>)MODEL$.createDatumReader(SCHEMA$); @Override public void readExternal(java.io.ObjectInput in) throws java.io.IOException { READER$.read(this, SpecificData.getDecoder(in)); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\EmployeeKey.java
1
请完成以下Java代码
public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public ReviewStatus getStatus() { return status; } public void setStatus(ReviewStatus status) { this.status = status; } @Override public boolean equals(Object obj) {
if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof BookReview)) { return false; } return id != null && id.equals(((BookReview) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\entity\BookReview.java
1
请完成以下Java代码
String getUri(ServerWebExchange exchange, Config config) { String template = Objects.requireNonNull(config.getTemplate(), "template must not be null"); if (template.indexOf('{') == -1) { return template; } Map<String, String> variables = getUriTemplateVariables(exchange); return UriComponentsBuilder.fromUriString(template).build().expand(variables).toUriString(); } @Override protected Optional<URI> determineRequestUri(ServerWebExchange exchange, Config config) { try { String url = getUri(exchange, config); URI uri = URI.create(url); if (!uri.isAbsolute()) { log.info("Request url is invalid: url={}, error=URI is not absolute", url); return Optional.ofNullable(null); } return Optional.of(uri); } catch (IllegalArgumentException e) { log.info("Request url is invalid : url={}, error={}", config.getTemplate(), e.getMessage()); return Optional.ofNullable(null);
} } public static class Config { private @Nullable String template; public @Nullable String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetRequestUriGatewayFilterFactory.java
1
请完成以下Java代码
private static final class MappingDescriptionVisitor implements Visitor { private final List<DispatcherHandlerMappingDescription> descriptions = new ArrayList<>(); @Override public void startNested(RequestPredicate predicate) { } @Override public void endNested(RequestPredicate predicate) { } @Override public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) { DispatcherHandlerMappingDetails details = new DispatcherHandlerMappingDetails(); details.setHandlerFunction(new HandlerFunctionDescription(handlerFunction)); this.descriptions.add( new DispatcherHandlerMappingDescription(predicate.toString(), handlerFunction.toString(), details)); } @Override public void resources(Function<ServerRequest, Mono<Resource>> lookupFunction) { } @Override public void attributes(Map<String, Object> attributes) {
} @Override public void unknown(RouterFunction<?> routerFunction) { } } static class DispatcherHandlersMappingDescriptionProviderRuntimeHints implements RuntimeHintsRegistrar { private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar(); @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { this.bindingRegistrar.registerReflectionHints(hints.reflection(), DispatcherHandlerMappingDescription.class); } } }
repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\mappings\DispatcherHandlersMappingDescriptionProvider.java
1
请完成以下Java代码
public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } @XmlJavaTypeAdapter(LocalDateTimeAdapter.class) public LocalDateTime getTransactionDate() { return transactionDate; } public void setTransactionDate(LocalDateTime transactionDate) { this.transactionDate = transactionDate; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }
public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } @Override public String toString() { return "Transaction [username=" + username + ", userId=" + userId + ", age=" + age + ", postCode=" + postCode + ", transactionDate=" + transactionDate + ", amount=" + amount + "]"; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\model\Transaction.java
1
请在Spring Boot框架中完成以下Java代码
DirectRabbitListenerContainerFactory directRabbitListenerContainerFactory( DirectRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory, ObjectProvider<ContainerCustomizer<DirectMessageListenerContainer>> directContainerCustomizer) { DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory(); configurer.configure(factory, connectionFactory); directContainerCustomizer.ifUnique(factory::setContainerCustomizer); return factory; } private SimpleRabbitListenerContainerFactoryConfigurer simpleListenerConfigurer() { SimpleRabbitListenerContainerFactoryConfigurer configurer = new SimpleRabbitListenerContainerFactoryConfigurer( this.properties); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique()); configurer.setRetrySettingsCustomizers(this.retrySettingsCustomizers.orderedStream().toList()); return configurer; }
private DirectRabbitListenerContainerFactoryConfigurer directListenerConfigurer() { DirectRabbitListenerContainerFactoryConfigurer configurer = new DirectRabbitListenerContainerFactoryConfigurer( this.properties); configurer.setMessageConverter(this.messageConverter.getIfUnique()); configurer.setMessageRecoverer(this.messageRecoverer.getIfUnique()); configurer.setRetrySettingsCustomizers(this.retrySettingsCustomizers.orderedStream().toList()); return configurer; } @Configuration(proxyBeanMethods = false) @EnableRabbit @ConditionalOnMissingBean(name = RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) static class EnableRabbitConfiguration { } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitAnnotationDrivenConfiguration.java
2
请完成以下Java代码
public class AsyncCallbackTemplate { public static <T> void withCallbackAndTimeout(ListenableFuture<T> future, Consumer<T> onSuccess, Consumer<Throwable> onFailure, long timeoutInMs, ScheduledExecutorService timeoutExecutor, Executor callbackExecutor) { future = Futures.withTimeout(future, timeoutInMs, TimeUnit.MILLISECONDS, timeoutExecutor); withCallback(future, onSuccess, onFailure, callbackExecutor); } public static <T> void withCallback(ListenableFuture<T> future, Consumer<T> onSuccess, Consumer<Throwable> onFailure, Executor executor) { FutureCallback<T> callback = new FutureCallback<T>() { @Override public void onSuccess(T result) { try { onSuccess.accept(result); } catch (Throwable th) { onFailure(th);
} } @Override public void onFailure(Throwable t) { onFailure.accept(t); } }; if (executor != null) { Futures.addCallback(future, callback, executor); } else { Futures.addCallback(future, callback, MoreExecutors.directExecutor()); } } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\AsyncCallbackTemplate.java
1
请完成以下Java代码
public void connect() throws IOException { connected = true; System.out.println("Connection established to: " + url); } @Override public InputStream getInputStream() throws IOException { if (!connected) { connect(); } return new ByteArrayInputStream(simulatedData.getBytes()); } @Override public OutputStream getOutputStream() throws IOException { ByteArrayOutputStream simulatedOutput = new ByteArrayOutputStream(); return simulatedOutput; }
@Override public int getContentLength() { return simulatedData.length(); } @Override public String getHeaderField(String name) { if ("SimulatedHeader".equalsIgnoreCase(name)) { // Example header name return headerValue; } else { return null; // Header not found } } }
repos\tutorials-master\core-java-modules\core-java-networking-4\src\main\java\com\baeldung\customurlconnection\CustomURLConnection.java
1
请在Spring Boot框架中完成以下Java代码
public static class ResponseParam { private int code; private String msg; private ResponseParam(int code, String msg) { this.code = code; this.msg = msg; } public static ResponseParam buildParam(int code, String msg) { return new ResponseParam(code, msg); } public int getCode() { return code;
} public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } }
repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\config\BaseResult.java
2
请完成以下Java代码
public void setAD_RelationType_ID (final java.lang.String AD_RelationType_ID) { set_Value (COLUMNNAME_AD_RelationType_ID, AD_RelationType_ID); } @Override public java.lang.String getAD_RelationType_ID() { return get_ValueAsString(COLUMNNAME_AD_RelationType_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setM_Product_Relationship_ID (final int M_Product_Relationship_ID) { if (M_Product_Relationship_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, M_Product_Relationship_ID); } @Override public int getM_Product_Relationship_ID()
{ return get_ValueAsInt(COLUMNNAME_M_Product_Relationship_ID); } @Override public void setRelatedProduct_ID (final int RelatedProduct_ID) { if (RelatedProduct_ID < 1) set_Value (COLUMNNAME_RelatedProduct_ID, null); else set_Value (COLUMNNAME_RelatedProduct_ID, RelatedProduct_ID); } @Override public int getRelatedProduct_ID() { return get_ValueAsInt(COLUMNNAME_RelatedProduct_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Relationship.java
1
请完成以下Java代码
public List<Person> findPersonsByFirstnameQueryDSL(final String firstname) { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).where(person.firstname.eq(firstname)).fetch(); } @Override public List<Person> findPersonsByFirstnameAndSurnameQueryDSL(final String firstname, final String surname) { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).where(person.firstname.eq(firstname).and(person.surname.eq(surname))).fetch(); } @Override public List<Person> findPersonsByFirstnameInDescendingOrderQueryDSL(final String firstname) { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).where(person.firstname.eq(firstname)).orderBy(person.surname.desc()).fetch();
} @Override public int findMaxAge() { final JPAQuery<Person> query = new JPAQuery<>(em); final QPerson person = QPerson.person; return query.from(person).select(person.age.max()).fetchFirst(); } @Override public Map<String, Integer> findMaxAgeByName() { final JPAQueryFactory query = new JPAQueryFactory(JPQLTemplates.DEFAULT, em); final QPerson person = QPerson.person; return query.from(person).transform(GroupBy.groupBy(person.firstname).as(GroupBy.max(person.age))); } }
repos\tutorials-master\persistence-modules\querydsl\src\main\java\com\baeldung\dao\PersonDaoImpl.java
1
请完成以下Java代码
public boolean canAdd(@NonNull final HUReceiptLinePartCandidate receiptLinePart) { // Cannot add to it self if (equals(receiptLinePart)) { return false; } // // Shall be precisely the same attributes (i.e. M_HU_ID) if (!Objects.equals(getAttributes().getId(), receiptLinePart.getAttributes().getId())) { return false; } return true; } /** * @return collected {@link I_M_ReceiptSchedule_Alloc}s */ public List<I_M_ReceiptSchedule_Alloc> getReceiptScheduleAllocs() { return receiptScheduleAllocsRO; } private final void updateIfStale() { if (!_stale) { return; } final HUReceiptLinePartAttributes attributes = getAttributes(); // // Qty & Quality final Percent qualityDiscountPercent = Percent.of(attributes.getQualityDiscountPercent()); final ReceiptQty qtyAndQuality; final Optional<Quantity> weight = attributes.getWeight(); if (weight.isPresent()) { qtyAndQuality = ReceiptQty.newWithCatchWeight(productId, weight.get().getUomId()); final StockQtyAndUOMQty stockAndCatchQty = StockQtyAndUOMQtys.createConvert(_qty, productId, weight.get()); qtyAndQuality.addQtyAndQualityDiscountPercent(stockAndCatchQty, qualityDiscountPercent); } else { qtyAndQuality = ReceiptQty.newWithoutCatchWeight(productId); qtyAndQuality.addQtyAndQualityDiscountPercent(_qty, qualityDiscountPercent); } I_M_QualityNote qualityNote = null; // // Quality Notice (only if we have a discount percentage) if (qualityDiscountPercent.signum() != 0) { qualityNote = attributes.getQualityNote(); final String qualityNoticeDisplayName = attributes.getQualityNoticeDisplayName(); qtyAndQuality.addQualityNotices(QualityNoticesCollection.valueOfQualityNote(qualityNoticeDisplayName)); } // // Update values if (_qualityNote == null) { // set the quality note only if it was not set before. Only the first one is needed _qualityNote = qualityNote; } _qtyAndQuality = qtyAndQuality; _subProducerBPartnerId = attributes.getSubProducer_BPartner_ID(); _attributeStorageAggregationKey = attributes.getAttributeStorageAggregationKey(); _stale = false; // not stale anymore }
/** * @return part attributes; never return null */ // package level access for testing purposes HUReceiptLinePartAttributes getAttributes() { return _attributes; } /** * @return qty & quality; never returns null */ public final ReceiptQty getQtyAndQuality() { updateIfStale(); return _qtyAndQuality; } public int getSubProducer_BPartner_ID() { updateIfStale(); return _subProducerBPartnerId; } public Object getAttributeStorageAggregationKey() { updateIfStale(); return _attributeStorageAggregationKey; } /** * Get the quality note linked with the part candidate * * @return */ public I_M_QualityNote getQualityNote() { return _qualityNote; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLinePartCandidate.java
1
请完成以下Java代码
public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } /** Set Timeout in Days. @param TimeoutDays Timeout in Days to change Status automatically */ public void setTimeoutDays (int TimeoutDays) { set_Value (COLUMNNAME_TimeoutDays, Integer.valueOf(TimeoutDays)); } /** Get Timeout in Days. @return Timeout in Days to change Status automatically */ public int getTimeoutDays () { Integer ii = (Integer)get_Value(COLUMNNAME_TimeoutDays); if (ii == null) return 0; return ii.intValue(); } public I_R_Status getUpdate_Status() throws RuntimeException { return (I_R_Status)MTable.get(getCtx(), I_R_Status.Table_Name) .getPO(getUpdate_Status_ID(), get_TrxName()); }
/** Set Update Status. @param Update_Status_ID Automatically change the status after entry from web */ public void setUpdate_Status_ID (int Update_Status_ID) { if (Update_Status_ID < 1) set_Value (COLUMNNAME_Update_Status_ID, null); else set_Value (COLUMNNAME_Update_Status_ID, Integer.valueOf(Update_Status_ID)); } /** Get Update Status. @return Automatically change the status after entry from web */ public int getUpdate_Status_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Update_Status_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Status.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } CorrelationKey other = (CorrelationKey) obj; if (!Arrays.equals(this.correlationId, other.correlationId)) { return false; } return true; } private static String bytesToHex(byte[] bytes) { boolean uuid = bytes.length == 16; char[] hexChars = new char[bytes.length * 2 + (uuid ? 4 : 0)]; int i = 0; for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF; hexChars[i++] = HEX_ARRAY[v >>> 4]; hexChars[i++] = HEX_ARRAY[v & 0x0F]; if (uuid && (j == 3 || j == 5 || j == 7 || j == 9)) { hexChars[i++] = '-'; } } return new String(hexChars); } @Override public String toString() { if (this.asString == null) { this.asString = bytesToHex(this.correlationId); } return this.asString; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\CorrelationKey.java
1
请在Spring Boot框架中完成以下Java代码
public Employee createEmployee( @ApiParam(value = "Employee object store in database table", required = true) @Valid @RequestBody Employee employee) { return employeeRepository.save(employee); } @ApiOperation(value = "Update an employee") @PutMapping("/employees/{id}") public ResponseEntity<Employee> updateEmployee( @ApiParam(value = "Employee Id to update employee object", required = true) @PathVariable(value = "id") Long employeeId, @ApiParam(value = "Update employee object", required = true) @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employee.setEmailId(employeeDetails.getEmailId()); employee.setLastName(employeeDetails.getLastName()); employee.setFirstName(employeeDetails.getFirstName()); final Employee updatedEmployee = employeeRepository.save(employee); return ResponseEntity.ok(updatedEmployee); }
@ApiOperation(value = "Delete an employee") @DeleteMapping("/employees/{id}") public Map<String, Boolean> deleteEmployee( @ApiParam(value = "Employee Id from which employee object will delete from database table", required = true) @PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employeeRepository.delete(employee); Map<String, Boolean> response = new HashMap<>(); response.put("deleted", Boolean.TRUE); return response; } }
repos\Spring-Boot-Advanced-Projects-main\springboot2-jpa-swagger2\src\main\java\net\alanbinu\springboot2\springboot2swagger2\controller\EmployeeController.java
2
请完成以下Java代码
public class TreeMaintenance extends JavaProcess { /** Tree */ private int m_AD_Tree_ID; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.error("prepare - Unknown Parameter: " + name); } m_AD_Tree_ID = getRecord_ID(); // from Window } // prepare
/** * Perform process. * @return Message (clear text) * @throws Exception if not successful */ protected String doIt() throws Exception { log.info("AD_Tree_ID=" + m_AD_Tree_ID); if (m_AD_Tree_ID == 0) throw new IllegalArgumentException("Tree_ID = 0"); MTree tree = new MTree (getCtx(), m_AD_Tree_ID, get_TrxName()); if (tree == null || tree.getAD_Tree_ID() == 0) throw new IllegalArgumentException("No Tree -" + tree); // if (MTree.TREETYPE_BoM.equals(tree.getTreeType())) return "BOM Trees not implemented"; tree.verifyTree(); return "Ok"; } // doIt } // TreeMaintenence
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\TreeMaintenance.java
1