instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public abstract class TbSubscription<T> {
/** Cache the hash code */
private transient int hash; // Default to 0. The hash code calculated for this object likely never be zero
private final String serviceId;
private final String sessionId;
private final int subscriptionId;
private final TenantId tenantId;
private final EntityId entityId;
private final TbSubscriptionType type;
private final BiConsumer<TbSubscription<T>, T> updateProcessor;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; | TbSubscription that = (TbSubscription) o;
return subscriptionId == that.subscriptionId &&
sessionId.equals(that.sessionId) &&
tenantId.equals(that.tenantId) &&
entityId.equals(that.entityId) &&
type == that.type;
}
@Override
public int hashCode() {
if (hash == 0) {
hash = Objects.hash(sessionId, subscriptionId, tenantId, entityId, type);
}
return hash;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbSubscription.java | 1 |
请完成以下Java代码 | class ForwardedTrustedProxiesCondition extends AllNestedConditions {
public ForwardedTrustedProxiesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = GatewayProperties.PREFIX + ".forwarded.enabled", matchIfMissing = true)
static class OnPropertyEnabled {
}
@ConditionalOnPropertyExists
static class OnTrustedProxiesNotEmpty {
}
}
class XForwardedTrustedProxiesCondition extends AllNestedConditions {
public XForwardedTrustedProxiesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = GatewayProperties.PREFIX + ".x-forwarded.enabled", matchIfMissing = true)
static class OnPropertyEnabled {
}
@ConditionalOnPropertyExists
static class OnTrustedProxiesNotEmpty {
}
}
class OnPropertyExistsCondition extends SpringBootCondition { | @Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
String property = context.getEnvironment().getProperty(PROPERTY);
if (!StringUtils.hasText(property)) {
return ConditionOutcome.noMatch(PROPERTY + " property is not set or is empty.");
}
return ConditionOutcome.match(PROPERTY + " property is not empty.");
}
catch (NoSuchElementException e) {
return ConditionOutcome.noMatch("Missing required property 'value' of @ConditionalOnPropertyExists");
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyExistsCondition.class)
@interface ConditionalOnPropertyExists {
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\TrustedProxies.java | 1 |
请完成以下Java代码 | public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues;
}
public boolean isDoNotUpdateToLatestVersionAutomatically() {
return doNotUpdateToLatestVersionAutomatically;
}
public String getTenantId() {
return tenantId;
}
@Override
public EventSubscription subscribe() {
checkValidInformation(); | return cmmnRuntimeService.registerCaseInstanceStartEventSubscription(this);
}
protected void checkValidInformation() {
if (StringUtils.isEmpty(caseDefinitionKey)) {
throw new FlowableIllegalArgumentException("The case definition must be provided using the key for the subscription to be registered.");
}
if (correlationParameterValues.isEmpty()) {
throw new FlowableIllegalArgumentException(
"At least one correlation parameter value must be provided for a dynamic case start event subscription, "
+ "otherwise the case would get started on all events, regardless their correlation parameter values.");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionBuilderImpl.java | 1 |
请完成以下Java代码 | public class SampleUtilsTest {
/**
* 2个线程运行。
* 准备时间:1000ms
* 运行时间: 2000ms
* @throws InterruptedException if any
*/
@JunitPerfConfig(duration = 2000)
public void junitPerfConfigTest() throws InterruptedException {
System.out.println("junitPerfConfigTest");
Thread.sleep(200);
}
@JunitPerfConfig(warmUp = 1000, duration = 5000, reporter = {HtmlReporter.class})
public void print1Test() {
Long sum = 0L; | for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
@JunitPerfConfig(duration = 5000)
public void print2Test() {
long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
System.out.println(sum);
}
} | repos\spring-boot-quick-master\quick-method-evaluate\src\main\java\com\method\evaluate\SampleUtilsTest.java | 1 |
请完成以下Java代码 | public void assertNotExcludedFromTransaction(@NonNull final SOTrx soTrx, @NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
if (soTrx.isSales())
{
assertNotExcludedFromSaleToCustomer(productId, partnerId);
}
else
{
assertNotExcludedFromPurchaseFromVendor(productId, partnerId);
}
}
private void assertNotExcludedFromSaleToCustomer(@NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
bpProductDAO.getExcludedFromSaleToCustomer(productId, partnerId)
.ifPresent(productExclude -> this.throwException(productExclude, AdMessageKey.of(MSG_ProductSalesExclusionError)));
}
private void assertNotExcludedFromPurchaseFromVendor(@NonNull final ProductId productId, @NonNull final BPartnerId partnerId)
{
bpProductDAO.getExcludedFromPurchaseFromVendor(productId, partnerId)
.ifPresent(productExclude -> this.throwException(productExclude, AdMessageKey.of(MSG_ProductPurchaseExclusionError)));
}
private void throwException(@NonNull final ProductExclude productExclude, @NonNull final AdMessageKey adMessage)
{
final String partnerName = bpartnerDAO.getBPartnerNameById(productExclude.getBpartnerId());
final String msg = msgBL.getMsg(adMessage,
ImmutableList.of(partnerName, productExclude.getReason()));
throw new AdempiereException(msg);
}
@Override
public void setProductCodeFieldsFromGTIN(@NonNull final I_C_BPartner_Product record, @Nullable final GTIN gtin)
{
final EAN13 ean13 = gtin != null ? gtin.toEAN13().orElse(null) : null; | record.setGTIN(gtin != null ? gtin.getAsString() : null);
record.setEAN_CU(ean13 != null ? ean13.getAsString() : null);
record.setUPC(gtin != null ? gtin.getAsString() : null);
if (gtin != null)
{
record.setEAN13_ProductCode(null);
}
}
@Override
public void setProductCodeFieldsFromEAN13ProductCode(@NonNull final I_C_BPartner_Product record, @Nullable final EAN13ProductCode ean13ProductCode)
{
record.setEAN13_ProductCode(ean13ProductCode != null ? ean13ProductCode.getAsString() : null);
if (ean13ProductCode != null)
{
record.setGTIN(null);
record.setEAN_CU(null);
record.setUPC(null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner_product\impl\BPartnerProductBL.java | 1 |
请完成以下Java代码 | public String getDescription()
{
return "*" + fileExtensionSuggestion;
}
@Override
public boolean accept(final File f)
{
if (f.isDirectory())
{
return true;
}
return f.getName().toLowerCase().endsWith(fileExtensionSuggestionLC);
}
});
}
if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
{
fileToUse = fc.getSelectedFile();
}
else
{
fileToUse = null;
}
}
return fileToUse;
}
@Override
public String getClientInfo()
{
final String javaVersion = System.getProperty("java.version");
return new StringBuilder("Swing, java.version=").append(javaVersion).toString();
}
@Override
public void showWindow(final Object model)
{
Check.assumeNotNull(model, "model not null");
final int adTableId = InterfaceWrapperHelper.getModelTableId(model);
final int recordId = InterfaceWrapperHelper.getId(model);
AEnv.zoom(adTableId, recordId);
} | @Override
public IClientUIInvoker invoke()
{
return new SwingClientUIInvoker(this);
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
return new SwingClientUIAsyncInvoker();
}
@Override
public void showURL(final String url)
{
try
{
final URI uri = new URI(url);
Desktop.getDesktop().browse(uri);
}
catch (Exception e)
{
logger.warn("Failed opening " + url, e.getLocalizedMessage());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingClientUIInstance.java | 1 |
请完成以下Java代码 | public Map<String, Map<String, GraphicInfo>> getLabelLocationByDiagramIdMap() {
return labelLocationByDiagramIdMap;
}
public Map<String, GraphicInfo> getLabelLocationByDiagramId(String diagramId) {
return labelLocationByDiagramIdMap.get(diagramId);
}
public void addLabelGraphicInfo(String key, GraphicInfo graphicInfo) {
labelLocationMap.put(key, graphicInfo);
}
public void addLabelGraphicInfoByDiagramId(String diagramId, String key, GraphicInfo graphicInfo) {
labelLocationByDiagramIdMap.computeIfAbsent(diagramId, k -> new LinkedHashMap<>());
labelLocationByDiagramIdMap.get(diagramId).put(key, graphicInfo);
labelLocationMap.put(key, graphicInfo);
}
public void removeLabelGraphicInfo(String key) {
flowLocationMap.remove(key);
}
public Map<String, Map<String, List<GraphicInfo>>> getDecisionServiceDividerLocationByDiagramIdMap() {
return decisionServiceDividerLocationByDiagramIdMap;
}
public Map<String, List<GraphicInfo>> getDecisionServiceDividerLocationMapByDiagramId(String diagramId) {
return decisionServiceDividerLocationByDiagramIdMap.get(diagramId);
}
public Map<String, List<GraphicInfo>> getDecisionServiceDividerLocationMap() {
return decisionServiceDividerLocationMap;
}
public List<GraphicInfo> getDecisionServiceDividerGraphicInfo(String key) {
return decisionServiceDividerLocationMap.get(key);
}
public void addDecisionServiceDividerGraphicInfoList(String key, List<GraphicInfo> graphicInfoList) {
decisionServiceDividerLocationMap.put(key, graphicInfoList);
}
public void addDecisionServiceDividerGraphicInfoListByDiagramId(String diagramId, String key, List<GraphicInfo> graphicInfoList) {
decisionServiceDividerLocationByDiagramIdMap.computeIfAbsent(diagramId, k -> new LinkedHashMap<>()); | decisionServiceDividerLocationByDiagramIdMap.get(diagramId).put(key, graphicInfoList);
decisionServiceDividerLocationMap.put(key, graphicInfoList);
}
public String getExporter() {
return exporter;
}
public void setExporter(String exporter) {
this.exporter = exporter;
}
public String getExporterVersion() {
return exporterVersion;
}
public void setExporterVersion(String exporterVersion) {
this.exporterVersion = exporterVersion;
}
public Map<String, String> getNamespaces() {
return namespaceMap;
}
public void addNamespace(String prefix, String uri) {
namespaceMap.put(prefix, uri);
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnDefinition.java | 1 |
请完成以下Java代码 | public void setCurrentVendor(final Boolean currentVendor)
{
this.currentVendor = currentVendor;
currentVendorSet = true;
}
public void setExcludedFromSales(final Boolean excludedFromSales)
{
this.excludedFromSales = excludedFromSales;
excludedFromSalesSet = true;
}
public void setExclusionFromSalesReason(final String exclusionFromSalesReason)
{
this.exclusionFromSalesReason = exclusionFromSalesReason;
exclusionFromSalesReasonSet = true;
}
public void setDropShip(final Boolean dropShip)
{
this.dropShip = dropShip;
dropShipSet = true;
} | public void setUsedForVendor(final Boolean usedForVendor)
{
this.usedForVendor = usedForVendor;
usedForVendorSet = true;
}
public void setExcludedFromPurchase(final Boolean excludedFromPurchase)
{
this.excludedFromPurchase = excludedFromPurchase;
excludedFromPurchaseSet = true;
}
public void setExclusionFromPurchaseReason(final String exclusionFromPurchaseReason)
{
this.exclusionFromPurchaseReason = exclusionFromPurchaseReason;
exclusionFromPurchaseReasonSet = true;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestBPartnerProductUpsert.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MaterialEventConfiguration
{
public static final String BEAN_NAME = "metasfreshEventBusService";
@Bean(name = BEAN_NAME)
@Profile(Profiles.PROFILE_Test)
public MetasfreshEventBusService createLocalMaterialEventService(
@NonNull final MaterialEventConverter materialEventConverter,
@NonNull final IEventBusFactory eventBusFactory,
@NonNull final MaterialEventObserver materialEventObserver)
{
final MetasfreshEventBusService materialEventService = MetasfreshEventBusService
.createLocalServiceThatIsReadyToUse(materialEventConverter, eventBusFactory, materialEventObserver);
return materialEventService;
} | @Bean(name = BEAN_NAME)
@DependsOn(Adempiere.BEAN_NAME)
@Profile(Profiles.PROFILE_NotTest)
public MetasfreshEventBusService createDistributedMaterialEventService(
@NonNull final MaterialEventConverter materialEventConverter,
@NonNull final IEventBusFactory eventBusFactory,
@NonNull final MaterialEventObserver materialEventObserver)
{
final MetasfreshEventBusService materialEventService = MetasfreshEventBusService
.createDistributedServiceThatNeedsToSubscribe(materialEventConverter, eventBusFactory, materialEventObserver);
return materialEventService;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\MaterialEventConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void validateEvent(@NonNull final PurchaseCandidateUpdatedEvent event)
{
// nothing to do; the event was already validated on construction time
}
@Override
public void handleEvent(@NonNull final PurchaseCandidateUpdatedEvent event)
{
handlePurchaseCandidateEvent(event);
}
@Override
protected CandidatesQuery createCandidatesQuery(@NonNull final PurchaseCandidateEvent event)
{
final PurchaseDetailsQuery purchaseDetailsQuery = PurchaseDetailsQuery.builder()
.purchaseCandidateRepoId(event.getPurchaseCandidateRepoId())
.build(); | return CandidatesQuery.builder()
.businessCase(CandidateBusinessCase.PURCHASE)
.type(CandidateType.SUPPLY)
.purchaseDetailsQuery(purchaseDetailsQuery)
.build();
}
@Override
protected CandidateBuilder updateBuilderFromEvent(
@NonNull final CandidateBuilder candidateBuilder,
@NonNull final PurchaseCandidateEvent event)
{
return candidateBuilder; // nothing to update
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateUpdatedHandler.java | 2 |
请完成以下Java代码 | public Iterator getPrefixes(String namespaceURI) {
ensureNotNull("Namespace URI", namespaceURI);
List<String> list = new ArrayList<String>();
if(namespaceURI.equals(XMLConstants.XML_NS_URI)) {
list.add(XMLConstants.XML_NS_PREFIX);
return Collections.unmodifiableList(list).iterator();
}
if(namespaceURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
list.add(XMLConstants.XMLNS_ATTRIBUTE);
return Collections.unmodifiableList(list).iterator();
}
// default namespace
if(namespaceURI.equals(element.namespace())) {
list.add(XMLConstants.DEFAULT_NS_PREFIX);
}
if(namespaces.containsValue(namespaceURI)) {
// all other namespaces
for (Map.Entry<String, String> entry : namespaces.entrySet()) {
if (namespaceURI.equals(entry.getValue())) {
list.add(entry.getKey());
}
}
}
return Collections.unmodifiableList(list).iterator();
}
/**
* Maps a single prefix, uri pair as namespace.
*
* @param prefix the prefix to use
* @param namespaceURI the URI to use
* @throws IllegalArgumentException if prefix or namespaceURI is null
*/ | public void setNamespace(String prefix, String namespaceURI) {
ensureNotNull("Prefix", prefix);
ensureNotNull("Namespace URI", namespaceURI);
namespaces.put(prefix, namespaceURI);
}
/**
* Maps a map of prefix, uri pairs as namespaces.
*
* @param namespaces the map of namespaces
* @throws IllegalArgumentException if namespaces is null
*/
public void setNamespaces(Map<String, String> namespaces) {
ensureNotNull("Namespaces", namespaces);
this.namespaces = namespaces;
}
} | repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\query\DomXPathNamespaceResolver.java | 1 |
请完成以下Java代码 | public boolean isShowColumnNamesForCaption()
{
return getData().isShowColumnNamesForCaption();
}
public void setShowColumnNamesForCaption(final boolean showColumnNamesForCaption)
{
final InternalUserSessionData data = getData();
final boolean showColumnNamesForCaptionOld = data.isShowColumnNamesForCaption();
data.setShowColumnNamesForCaption(showColumnNamesForCaption);
logSettingChanged("ShowColumnNamesForCaption", showColumnNamesForCaption, showColumnNamesForCaptionOld);
}
public void setHttpCacheMaxAge(final int httpCacheMaxAge)
{
final InternalUserSessionData data = getData();
final int httpCacheMaxAgeOld = data.getHttpCacheMaxAge();
data.setHttpCacheMaxAge(httpCacheMaxAge);
logSettingChanged("HttpCacheMaxAge", httpCacheMaxAge, httpCacheMaxAgeOld);
}
public int getHttpCacheMaxAge()
{
return getData().getHttpCacheMaxAge();
}
private static final String SYSCONFIG_DefaultLookupSearchStartDelayMillis = "de.metas.ui.web.window.descriptor.LookupDescriptor.DefaultLookupSearchStartDelayMillis";
public Supplier<Duration> getDefaultLookupSearchStartDelay()
{
return () -> {
final int defaultLookupSearchStartDelayMillis = sysConfigBL.getIntValue(SYSCONFIG_DefaultLookupSearchStartDelayMillis, 0);
return defaultLookupSearchStartDelayMillis > 0 ? Duration.ofMillis(defaultLookupSearchStartDelayMillis) : Duration.ZERO;
};
}
/*
This configuration is used for a webui option.
*/
private static final String SYSCONFIG_isAlwaysDisplayNewBPartner = "de.metas.ui.web.session.UserSession.IsAlwaysDisplayNewBPartner";
public boolean isAlwaysShowNewBPartner()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_isAlwaysDisplayNewBPartner, false, getClientId().getRepoId(), getOrgId().getRepoId());
}
@NonNull
public ZoneId getTimeZone()
{
final OrgId orgId = getOrgId();
final OrgInfo orgInfo = orgDAO.getOrgInfoById(orgId);
if (orgInfo.getTimeZone() != null)
{
return orgInfo.getTimeZone();
}
return de.metas.common.util.time.SystemTime.zoneId();
} | /**
* @deprecated avoid using this method; usually it's workaround-ish / quick and dirty fix
*/
@Deprecated
public static ZoneId getTimeZoneOrSystemDefault()
{
final UserSession userSession = getCurrentOrNull();
return userSession != null ? userSession.getTimeZone() : SystemTime.zoneId();
}
public boolean isWorkplacesEnabled()
{
return workplaceService.isAnyWorkplaceActive();
}
public @NonNull Optional<Workplace> getWorkplace()
{
if (!isWorkplacesEnabled())
{
return Optional.empty();
}
return getLoggedUserIdIfExists().flatMap(workplaceService::getWorkplaceByUserId);
}
/**
* Event fired when the user language was changed.
* Usually it is user triggered.
*
* @author metas-dev <dev@metasfresh.com>
*/
@lombok.Value
public static class LanguagedChangedEvent
{
@NonNull String adLanguage;
UserId adUserId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSession.java | 1 |
请完成以下Java代码 | public List<Object> retrieveDownstreamNodes(final I_M_HU_Item node)
{
final String itemType = handlingUnitsBL.getItemType(node);
if (X_M_HU_Item.ITEMTYPE_HandlingUnit.equals(itemType))
{
final List<I_M_HU> includedHUs = handlingUnitsDAO.retrieveIncludedHUs(node);
return new ArrayList<>(includedHUs);
}
else if (X_M_HU_Item.ITEMTYPE_Material.equals(itemType)
|| X_M_HU_Item.ITEMTYPE_HUAggregate.equals(itemType)) // gh #1099: this is the actual fix. Also load VHUs that are below HA items.
{
if (handlingUnitsBL.isVirtual(node))
{
final IHUItemStorage itemStorage = getStorageFactoryToUse().getStorage(node);
return Collections.singletonList((Object)itemStorage);
}
else
{
// Navigate included Virtual HUs
final List<I_M_HU> vhus = handlingUnitsDAO.retrieveVirtualHUs(node);
return new ArrayList<>(vhus);
}
}
else
{
return Collections.emptyList();
}
}
}
protected class HUItemStorageNodeIterator extends AbstractNodeIterator<IHUItemStorage>
{
@Override
public final ArrayKey getKey(final IHUItemStorage node)
{
return Util.mkKey(IHUItemStorage.class, node.getM_HU_Item().getM_HU_Item_ID());
}
@Override
public final void setCurrentNode(final IHUItemStorage node)
{
currentHUItemStorage = node;
}
@Override
public final Result beforeIterate(final IMutable<IHUItemStorage> node)
{
return getActiveListener().beforeHUItemStorage(node); | }
@Override
public final Result afterIterate(final IHUItemStorage node)
{
return getActiveListener().afterHUItemStorage(node);
}
@Override
public AbstractNodeIterator<?> getDownstreamNodeIterator(final IHUItemStorage node)
{
return null;
}
@Override
public List<Object> retrieveDownstreamNodes(final IHUItemStorage node)
{
throw new IllegalStateException("Shall not be called because we don't have a downstream node iterator");
}
}
@Override
public void setDepthMax(final int depthMax)
{
this.depthMax = depthMax;
}
@Override
public int getDepthMax()
{
return depthMax;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\AbstractHUIterator.java | 1 |
请完成以下Java代码 | private void createPickingCandidatesIfNeeded(final PackageableRow row)
{
final boolean existsPickingCandidates = pickingCandidateService.existsPickingCandidates(row.getShipmentScheduleIds());
if (!existsPickingCandidates)
{
// run in a different transaction so that the report can access it
trxManager.runInNewTrx(new TrxRunnable2()
{
@Override
public void run(final String localTrxName) throws Exception
{
productsToPickRowsService.createPickingCandidates(row);
}
// Throw an explicit error in order to make sure that the user sees that something went wrong
// mainly we might got some line that should not be in picking terminal
@Override
public boolean doCatch(final Throwable e) throws Throwable
{
throw AdempiereException.wrapIfNeeded(e)
.markUserNotified();
}
@Override
public void doFinally()
{
// nothing
}
});
}
}
private ReportResult printPicklist(@NonNull final PackageableRow row)
{
final PInstanceRequest pinstanceRequest = createPInstanceRequest(row);
final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder()
.setCtx(getCtx())
.setAD_Process_ID(PickListPdf_AD_Process_ID) | .setAD_PInstance(adPInstanceDAO.getById(pinstanceId))
.setReportLanguage(getProcessInfo().getReportLanguage())
.setJRDesiredOutputType(OutputType.PDF)
.build();
final ReportsClient reportsClient = ReportsClient.get();
return reportsClient.report(jasperProcessInfo);
}
private PInstanceRequest createPInstanceRequest(@NonNull final PackageableRow row)
{
final String orderNo = row.getOrderDocumentNo();
final List<ProcessInfoParameter> piParams = ImmutableList.of(ProcessInfoParameter.of(I_M_Packageable_V.COLUMNNAME_OrderDocumentNo, orderNo));
final PInstanceRequest pinstanceRequest = PInstanceRequest.builder()
.processId(PickListPdf_AD_Process_ID)
.processParams(piParams)
.build();
return pinstanceRequest;
}
private String buildFilename(@NonNull final PackageableRow row)
{
final String customer = row.getCustomer().getDisplayName();
final String docuemntNo = row.getOrderDocumentNo();
return Joiner.on("_")
.skipNulls()
.join(docuemntNo, customer)
+ ".pdf";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesView_PrintPicklist.java | 1 |
请完成以下Java代码 | public static Date toDate(LocalDate localDate) {
return toDate(localDate.atTime(LocalTime.now(ZoneId.systemDefault())));
}
/**
* Date转 LocalDateTime
* Jdk8 后 不推荐使用 {@link Date} Date
*
* @param date /
* @return /
*/
public static LocalDateTime toLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
/**
* 日期 格式化
*
* @param localDateTime /
* @param patten /
* @return /
*/
public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(patten);
return df.format(localDateTime);
}
/**
* 日期 格式化
*
* @param localDateTime /
* @param df /
* @return /
*/
public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) {
return df.format(localDateTime);
}
/**
* 日期格式化 yyyy-MM-dd HH:mm:ss
*
* @param localDateTime /
* @return /
*/
public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) {
return DFY_MD_HMS.format(localDateTime);
}
/**
* 日期格式化 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public String localDateTimeFormatyMd(LocalDateTime localDateTime) {
return DFY_MD.format(localDateTime);
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
* | * @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) {
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss
*
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) {
return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime));
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\DateUtil.java | 1 |
请完成以下Java代码 | public String toString()
{
final StringBuilder sb = new StringBuilder("GenericPO[")
.append("TableName=").append(get_TableName())
.append(",ID=").append(get_ID())
.append("]");
return sb.toString();
}
public static final String COLUMNNAME_AD_OrgTrx_ID = "AD_OrgTrx_ID";
public static final int AD_ORGTRX_ID_AD_Reference_ID = 130;
/**
* Set Trx Organization. Performing or initiating organization
*/
public void setAD_OrgTrx_ID(int AD_OrgTrx_ID)
{
if (AD_OrgTrx_ID == 0)
set_Value(COLUMNNAME_AD_OrgTrx_ID, null);
else
set_Value(COLUMNNAME_AD_OrgTrx_ID, new Integer(AD_OrgTrx_ID));
}
/**
* Get Trx Organization. Performing or initiating organization
*/
public int getAD_OrgTrx_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgTrx_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
protected final GenericPO newInstance()
{
return new GenericPO(tableName, getCtx(), ID_NewInstanceNoInit); | }
@Override
public final PO copy()
{
final GenericPO po = (GenericPO)super.copy();
po.tableName = this.tableName;
po.tableID = this.tableID;
return po;
}
} // GenericPO
/**
* Wrapper class to workaround the limit of PO constructor that doesn't take a tableName or
* tableID parameter. Note that in the generated class scenario ( X_ ), tableName and tableId
* is generated as a static field.
*
* @author Low Heng Sin
*
*/
final class PropertiesWrapper extends Properties
{
/**
*
*/
private static final long serialVersionUID = 8887531951501323594L;
protected Properties source;
protected String tableName;
PropertiesWrapper(Properties source, String tableName)
{
this.source = source;
this.tableName = tableName;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GenericPO.java | 1 |
请完成以下Java代码 | public class TokenExchangeGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private static final String ACCESS_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:access_token";
private static final String JWT_TOKEN_TYPE_VALUE = "urn:ietf:params:oauth:token-type:jwt";
private final OAuth2Token subjectToken;
private final OAuth2Token actorToken;
/**
* Constructs a {@code TokenExchangeGrantRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param subjectToken the subject token
* @param actorToken the actor token
*/
public TokenExchangeGrantRequest(ClientRegistration clientRegistration, OAuth2Token subjectToken,
OAuth2Token actorToken) {
super(AuthorizationGrantType.TOKEN_EXCHANGE, clientRegistration);
Assert.isTrue(AuthorizationGrantType.TOKEN_EXCHANGE.equals(clientRegistration.getAuthorizationGrantType()),
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.TOKEN_EXCHANGE");
Assert.notNull(subjectToken, "subjectToken cannot be null");
this.subjectToken = subjectToken;
this.actorToken = actorToken;
}
/**
* Returns the {@link OAuth2Token subject token}.
* @return the {@link OAuth2Token subject token}
*/
public OAuth2Token getSubjectToken() {
return this.subjectToken;
}
/**
* Returns the {@link OAuth2Token actor token}. | * @return the {@link OAuth2Token actor token}
*/
public OAuth2Token getActorToken() {
return this.actorToken;
}
/**
* Populate default parameters for the Token Exchange Grant.
* @param grantRequest the authorization grant request
* @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access
* Token Request body
*/
static MultiValueMap<String, String> defaultParameters(TokenExchangeGrantRequest grantRequest) {
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
parameters.set(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
}
parameters.set(OAuth2ParameterNames.REQUESTED_TOKEN_TYPE, ACCESS_TOKEN_TYPE_VALUE);
OAuth2Token subjectToken = grantRequest.getSubjectToken();
parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN, subjectToken.getTokenValue());
parameters.set(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, tokenType(subjectToken));
OAuth2Token actorToken = grantRequest.getActorToken();
if (actorToken != null) {
parameters.set(OAuth2ParameterNames.ACTOR_TOKEN, actorToken.getTokenValue());
parameters.set(OAuth2ParameterNames.ACTOR_TOKEN_TYPE, tokenType(actorToken));
}
return parameters;
}
private static String tokenType(OAuth2Token token) {
return (token instanceof Jwt) ? JWT_TOKEN_TYPE_VALUE : ACCESS_TOKEN_TYPE_VALUE;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\TokenExchangeGrantRequest.java | 1 |
请完成以下Java代码 | public static class InboundEventPayloadExtractorBuilderImpl implements InboundEventPayloadExtractorBuilder {
protected InboundEventProcessingPipelineBuilderImpl inboundEventProcessingPipelineBuilder;
public InboundEventPayloadExtractorBuilderImpl(InboundEventProcessingPipelineBuilderImpl inboundEventProcessingPipelineBuilder) {
this.inboundEventProcessingPipelineBuilder = inboundEventProcessingPipelineBuilder;
}
@Override
public InboundEventTransformerBuilder payloadExtractor(String delegateExpression) {
inboundEventProcessingPipelineBuilder.channelModel.setPayloadExtractorDelegateExpression(delegateExpression);
return new InboundEventTransformerBuilderImpl(inboundEventProcessingPipelineBuilder);
}
}
public static class InboundEventTransformerBuilderImpl implements InboundEventTransformerBuilder {
protected InboundEventProcessingPipelineBuilderImpl inboundEventProcessingPipelineBuilder; | public InboundEventTransformerBuilderImpl(InboundEventProcessingPipelineBuilderImpl inboundEventProcessingPipelineBuilder) {
this.inboundEventProcessingPipelineBuilder = inboundEventProcessingPipelineBuilder;
}
@Override
public InboundChannelModelBuilder transformer(String delegateExpression) {
this.inboundEventProcessingPipelineBuilder.channelModel.setEventTransformerDelegateExpression(delegateExpression);
return this.inboundEventProcessingPipelineBuilder.channelDefinitionBuilder;
}
@Override
public EventDeployment deploy() {
return this.inboundEventProcessingPipelineBuilder.channelDefinitionBuilder.deploy();
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\model\InboundChannelDefinitionBuilderImpl.java | 1 |
请完成以下Java代码 | public void setCurrentWindow(@NonNull final AdWindowId windowId, @Nullable final String windowName)
{
this.currentWindowId = windowId;
this._currentWindowName = windowName;
}
public void clearCurrentWindow()
{
this.currentWindowId = null;
this._currentWindowName = null;
}
@Nullable
public String getCurrentWindowName()
{
if (this._currentWindowName == null && this.currentWindowId != null)
{
this._currentWindowName = adWindowDAO.retrieveWindowName(currentWindowId).translate(adLanguage);
}
return this._currentWindowName;
} | public void collectError(@NonNull final String errorMessage)
{
errors.add(JsonWindowsHealthCheckResponse.Entry.builder()
.windowId(WindowId.of(currentWindowId))
.windowName(getCurrentWindowName())
.errorMessage(errorMessage)
.build());
}
public void collectError(@NonNull final Throwable exception)
{
errors.add(JsonWindowsHealthCheckResponse.Entry.builder()
.windowId(WindowId.of(currentWindowId))
.windowName(getCurrentWindowName())
.error(JsonErrors.ofThrowable(exception, adLanguage))
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ErrorsCollector.java | 1 |
请完成以下Java代码 | public void setPostal (final @Nullable java.lang.String Postal)
{
set_ValueNoCheck (COLUMNNAME_Postal, Postal);
}
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
public void setPostal_Add (final @Nullable java.lang.String Postal_Add)
{
set_ValueNoCheck (COLUMNNAME_Postal_Add, Postal_Add);
}
@Override
public java.lang.String getPostal_Add()
{
return get_ValueAsString(COLUMNNAME_Postal_Add);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{
set_ValueNoCheck (COLUMNNAME_RegionName, RegionName);
} | @Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setStreet (final @Nullable java.lang.String Street)
{
set_Value (COLUMNNAME_Street, Street);
}
@Override
public java.lang.String getStreet()
{
return get_ValueAsString(COLUMNNAME_Street);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Location.java | 1 |
请完成以下Java代码 | public class Book {
private long id;
@NotBlank
@Size(min = 0, max = 20)
private String title;
@NotBlank
@Size(min = 0, max = 30)
private String author;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id; | }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc\src\main\java\com\baeldung\springdoc\model\Book.java | 1 |
请完成以下Java代码 | public static UomId getCommonUomIdOfAll(@Nullable final CostAmountAndQty... values)
{
return UomId.getCommonUomIdOfAll(CostAmountAndQty::getUomId, "quantity", values);
}
public CurrencyId getCurrencyId() {return amt.getCurrencyId();}
public UomId getUomId() {return qty.getUomId();}
public boolean isZero() {return amt.isZero() && qty.isZero();}
public CostAmountAndQty toZero() {return isZero() ? this : of(amt.toZero(), qty.toZero());}
public CostAmountAndQty negate() {return isZero() ? this : of(amt.negate(), qty.negate());}
public CostAmountAndQty mapQty(@NonNull final UnaryOperator<Quantity> qtyMapper)
{
if (qty.isZero())
{
return this;
}
final Quantity newQty = qtyMapper.apply(qty);
if (Objects.equals(qty, newQty))
{
return this;
}
return of(amt, newQty); | }
public CostAmountAndQty add(@NonNull final CostAmountAndQty other)
{
if (other.isZero())
{
return this;
}
else if (this.isZero())
{
return other;
}
else
{
return of(this.amt.add(other.amt), this.qty.add(other.qty));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmountAndQty.java | 1 |
请完成以下Java代码 | private static Set<AvailabilityRequest> createAvailabilityRequests(@NonNull final Map<TrackingId, PurchaseCandidatesGroup> purchaseCandidatesGroupsByTrackingId)
{
final ListMultimap<BPartnerId, AvailabilityRequestItem> requestItemsByVendorId = purchaseCandidatesGroupsByTrackingId
.entrySet()
.stream()
.map(entry -> toVendorAndRequestItem(entry))
.collect(GuavaCollectors.toImmutableListMultimap());
final Set<BPartnerId> vendorIds = requestItemsByVendorId.keySet();
return vendorIds.stream()
.map(vendorId -> createAvailabilityRequestOrNull(vendorId, requestItemsByVendorId.get(vendorId)))
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
private static Map.Entry<BPartnerId, AvailabilityRequestItem> toVendorAndRequestItem(final Map.Entry<TrackingId, PurchaseCandidatesGroup> entry)
{
final TrackingId trackingId = entry.getKey();
final PurchaseCandidatesGroup purchaseCandidatesGroup = entry.getValue();
final BPartnerId vendorId = purchaseCandidatesGroup.getVendorId();
final AvailabilityRequestItem requestItem = createAvailabilityRequestItem(trackingId, purchaseCandidatesGroup);
return GuavaCollectors.entry(vendorId, requestItem);
}
private static AvailabilityRequestItem createAvailabilityRequestItem(final TrackingId trackingId, final PurchaseCandidatesGroup purchaseCandidatesGroup)
{
final Quantity qtyToPurchase = purchaseCandidatesGroup.getQtyToPurchase();
final ProductAndQuantity productAndQuantity = ProductAndQuantity.of(
purchaseCandidatesGroup.getVendorProductNo(),
qtyToPurchase.toBigDecimal().max(ONE), // check availability for at least one, even if qtyToPurchase is still zero
qtyToPurchase.getUOMId()); | return AvailabilityRequestItem.builder()
.trackingId(trackingId)
.productAndQuantity(productAndQuantity)
.purchaseCandidateId(PurchaseCandidateId.getRepoIdOr(purchaseCandidatesGroup.getSinglePurchaseCandidateIdOrNull(), -1))
.salesOrderLineId(OrderAndLineId.getOrderLineRepoIdOr(purchaseCandidatesGroup.getSingleSalesOrderAndLineIdOrNull(), -1))
.build();
}
private static AvailabilityRequest createAvailabilityRequestOrNull(final BPartnerId vendorId, final Collection<AvailabilityRequestItem> requestItems)
{
if (requestItems.isEmpty())
{
return null;
}
return AvailabilityRequest.builder()
.vendorId(vendorId.getRepoId())
.availabilityRequestItems(requestItems)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\availability\AvailabilityCheckService.java | 1 |
请完成以下Java代码 | protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
// nothing to do
}
@Override
protected BaseElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
MessageFlow flow = new MessageFlow();
String sourceRef = BpmnJsonConverterUtil.lookForSourceRef(
elementNode.get(EDITOR_SHAPE_ID).asText(),
modelNode.get(EDITOR_CHILD_SHAPES) | );
if (sourceRef != null) {
flow.setSourceRef(sourceRef);
JsonNode targetNode = elementNode.get("target");
if (targetNode != null && !targetNode.isNull()) {
String targetId = targetNode.get(EDITOR_SHAPE_ID).asText();
if (shapeMap.get(targetId) != null) {
flow.setTargetRef(BpmnJsonConverterUtil.getElementId(shapeMap.get(targetId)));
}
}
}
return flow;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\MessageFlowJsonConverter.java | 1 |
请完成以下Java代码 | public class ParallelGatewayActivityBehavior extends GatewayActivityBehavior {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(ParallelGatewayActivityBehavior.class);
@Override
public void execute(DelegateExecution execution) {
ActivityExecution activityExecution = (ActivityExecution) execution;
// Join
PvmActivity activity = activityExecution.getActivity();
List<PvmTransition> outgoingTransitions = activityExecution.getActivity().getOutgoingTransitions();
execution.inactivate();
lockConcurrentRoot(activityExecution);
List<ActivityExecution> joinedExecutions = activityExecution.findInactiveConcurrentExecutions(activity);
int nbrOfExecutionsToJoin = activityExecution.getActivity().getIncomingTransitions().size();
int nbrOfExecutionsJoined = joinedExecutions.size(); | Context.getCommandContext().getHistoryManager().recordActivityEnd((ExecutionEntity) execution);
if (nbrOfExecutionsJoined == nbrOfExecutionsToJoin) {
// Fork
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("parallel gateway '{}' activates: {} of {} joined", activity.getId(), nbrOfExecutionsJoined, nbrOfExecutionsToJoin);
}
activityExecution.takeAll(outgoingTransitions, joinedExecutions);
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("parallel gateway '{}' does not activate: {} of {} joined", activity.getId(), nbrOfExecutionsJoined, nbrOfExecutionsToJoin);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\ParallelGatewayActivityBehavior.java | 1 |
请完成以下Java代码 | private Mono<Health> validate(Health.Builder builder) {
builder.withDetail("database", this.connectionFactory.getMetadata().getName());
return (StringUtils.hasText(this.validationQuery)) ? validateWithQuery(builder)
: validateWithConnectionValidation(builder);
}
private Mono<Health> validateWithQuery(Health.Builder builder) {
Assert.state(this.validationQuery != null, "'validationQuery' must not be null");
builder.withDetail("validationQuery", this.validationQuery);
Mono<Object> connectionValidation = Mono.usingWhen(this.connectionFactory.create(),
(conn) -> Flux.from(conn.createStatement(this.validationQuery).execute())
.flatMap((it) -> it.map(this::extractResult))
.next(),
Connection::close, (o, throwable) -> o.close(), Connection::close);
return connectionValidation.map((result) -> builder.up().withDetail("result", result).build()); | }
private Mono<Health> validateWithConnectionValidation(Health.Builder builder) {
builder.withDetail("validationQuery", "validate(REMOTE)");
Mono<Boolean> connectionValidation = Mono.usingWhen(this.connectionFactory.create(),
(connection) -> Mono.from(connection.validate(ValidationDepth.REMOTE)), Connection::close,
(connection, ex) -> connection.close(), Connection::close);
return connectionValidation.map((valid) -> builder.status((valid) ? Status.UP : Status.DOWN).build());
}
private @Nullable Object extractResult(Row row, RowMetadata metadata) {
return row.get(metadata.getColumnMetadatas().iterator().next().getName());
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\health\ConnectionFactoryHealthIndicator.java | 1 |
请完成以下Java代码 | public static String encodeMD5String(String str) {
return encode(str, "MD5");
}
/**
* 用SHA算法进行加密
*
* @param str
* 需要加密的字符串
* @return SHA加密后的结果
*/
public static String encodeSHAString(String str) {
return encode(str, "SHA");
}
/**
* 用base64算法进行加密
*
* @param str
* 需要加密的字符串
* @return base64加密后的结果
*/
public static String encodeBase64String(String str) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(str.getBytes());
}
/**
* 用base64算法进行解密
*
* @param str
* 需要解密的字符串
* @return base64解密后的结果
* @throws IOException
*/
public static String decodeBase64String(String str) throws IOException {
BASE64Decoder encoder = new BASE64Decoder();
return new String(encoder.decodeBuffer(str));
} | private static String encode(String str, String method) {
MessageDigest mdInst = null;
// 把密文转换成十六进制的字符串形式
// 单线程用StringBuilder,速度快 多线程用stringbuffer,安全
StringBuilder dstr = new StringBuilder();
try {
// 获得MD5摘要算法的 MessageDigest对象
mdInst = MessageDigest.getInstance(method);
// 使用指定的字节更新摘要
mdInst.update(str.getBytes());
// 获得密文
byte[] md = mdInst.digest();
for (int i = 0; i < md.length; i++) {
int tmp = md[i];
if (tmp < 0) {
tmp += 256;
}
if (tmp < 16) {
dstr.append("0");
}
dstr.append(Integer.toHexString(tmp));
}
} catch (NoSuchAlgorithmException e) {
LOG.error(e);
}
return dstr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\EncryptUtil.java | 1 |
请完成以下Java代码 | public class ModelApiResponse {
public static final String JSON_PROPERTY_CODE = "code";
private Integer code;
public static final String JSON_PROPERTY_TYPE = "type";
private String type;
public static final String JSON_PROPERTY_MESSAGE = "message";
private String message;
public ModelApiResponse code(Integer code) {
this.code = code;
return this;
}
/**
* Get code
* @return code
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_CODE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public ModelApiResponse type(String type) {
this.type = type;
return this;
}
/**
* Get type
* @return type
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_TYPE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ModelApiResponse message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_MESSAGE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
} | if (o == null || getClass() != o.getClass()) {
return false;
}
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message);
}
@Override
public int hashCode() {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java | 1 |
请完成以下Java代码 | public void dispose()
{
log.debug("");
super.dispose();
} // dispose
/**
* Return data as sorted Array - not implemented
* @param mandatory mandatory
* @param onlyValidated only validated
* @param onlyActive only active
* @param temporary force load for temporary display
* @return null
*/
@Override
public ArrayList<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary)
{
log.error("Not implemented");
return null;
} // getArray
@Override
public String getTableName() | {
return I_M_AttributeSetInstance.Table_Name;
}
/**
* Get underlying fully qualified Table.Column Name.
* Used for VLookup.actionButton (Zoom)
* @return column name
*/
@Override
public String getColumnName()
{
return I_M_AttributeSetInstance.Table_Name
+ "."
+ I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID;
}
} // MPAttribute | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPAttributeLookup.java | 1 |
请完成以下Java代码 | public Optional<GeographicalCoordinates> findBestCoordinates(final GeoCoordinatesRequest request)
{
final List<GeographicalCoordinates> coords = findAllCoordinates(request);
if (coords.isEmpty())
{
return Optional.empty();
}
return Optional.of(coords.get(0));
}
@NonNull
private ImmutableList<GeographicalCoordinates> findAllCoordinates(final @NonNull GeoCoordinatesRequest request)
{
final ImmutableList<GeographicalCoordinates> response = coordinatesCache.get(request);
if (response != null)
{
return response;
}
return coordinatesCache.getOrLoad(request, this::queryAllCoordinates);
}
@NonNull
private ImmutableList<GeographicalCoordinates> queryAllCoordinates(@NonNull final GeoCoordinatesRequest request)
{
final String formattedAddress = String.format("%s, %s %s, %s",
CoalesceUtil.coalesce(request.getAddress(), ""),
CoalesceUtil.coalesce(request.getPostal(), ""),
CoalesceUtil.coalesce(request.getCity(), ""),
CoalesceUtil.coalesce(request.getCountryCode2(), ""));
logger.trace("Formatted address: {}", formattedAddress);
final GeocodingResult[] results = GeocodingApi
.geocode(context, formattedAddress)
.awaitIgnoreError(); | //noinspection ConfusingArgumentToVarargsMethod
logger.trace("Geocoding response from google: {}", results);
if (results == null)
{
return ImmutableList.of();
}
return Arrays.stream(results)
.map(GoogleMapsGeocodingProviderImpl::toGeographicalCoordinates)
.collect(GuavaCollectors.toImmutableList());
}
private static GeographicalCoordinates toGeographicalCoordinates(@NonNull final GeocodingResult result)
{
final LatLng ll = result.geometry.location;
return GeographicalCoordinates.builder()
.latitude(BigDecimal.valueOf(ll.lat))
.longitude(BigDecimal.valueOf(ll.lng))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\googlemaps\GoogleMapsGeocodingProviderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String list(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "6") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(page, size, sort);
Page<UserEntity> users=userRepository.findAll(pageable);
model.addAttribute("users", users);
logger.info("user list "+ users.getContent());
return "user/list";
}
@RequestMapping("/toAdd")
public String toAdd() {
return "user/userAdd";
}
@RequestMapping("/add")
public String add(@Valid UserParam userParam,BindingResult result, ModelMap model) {
String errorMsg="";
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
}
model.addAttribute("errorMsg",errorMsg);
return "user/userAdd";
}
UserEntity u= userRepository.findByUserNameOrEmail(userParam.getUserName(),userParam.getEmail());
if(u!=null){
model.addAttribute("errorMsg","用户已存在!");
return "user/userAdd";
}
UserEntity user=new UserEntity();
BeanUtils.copyProperties(userParam,user);
user.setRegTime(new Date());
user.setUserType("user");
userRepository.save(user);
return "redirect:/list";
}
@RequestMapping("/toEdit")
public String toEdit(Model model,String id) {
UserEntity user=userRepository.findById(id); | model.addAttribute("user", user);
return "user/userEdit";
}
@RequestMapping("/edit")
public String edit(@Valid UserParam userParam, BindingResult result,ModelMap model) {
String errorMsg="";
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
}
model.addAttribute("errorMsg",errorMsg);
model.addAttribute("user", userParam);
return "user/userEdit";
}
UserEntity user=userRepository.findById(userParam.getId());
BeanUtils.copyProperties(userParam,user);
user.setRegTime(new Date());
userRepository.save(user);
return "redirect:/list";
}
@RequestMapping("/delete")
public String delete(String id) {
userRepository.delete(id);
return "redirect:/list";
}
} | repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\web\UserController.java | 2 |
请完成以下Java代码 | public String generateReferenceNo(@NonNull final Object sourceModel)
{
return generator.generateReferenceNo(sourceModel);
}
@Override
public I_C_ReferenceNo_Type getType()
{
return type;
}
@Override
public IReferenceNoGenerator getGenerator()
{
return generator;
} | @Override
public List<Integer> getAssignedTableIds()
{
return assignedTableIds;
}
@Override
public String toString()
{
return "ReferenceNoGeneratorInstance ["
+ "type=" + (type == null ? null : type.getName())
+ ", assignedTableIds=" + assignedTableIds
+ ", generator=" + generator
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\ReferenceNoGeneratorInstance.java | 1 |
请完成以下Java代码 | public abstract class FormDataImpl implements FormData, Serializable {
private static final long serialVersionUID = 1L;
protected String formKey;
protected String deploymentId;
protected List<FormProperty> formProperties = new ArrayList<>();
// getters and setters
// //////////////////////////////////////////////////////
@Override
public String getFormKey() {
return formKey;
}
@Override
public String getDeploymentId() {
return deploymentId;
} | @Override
public List<FormProperty> getFormProperties() {
return formProperties;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public void setFormProperties(List<FormProperty> formProperties) {
this.formProperties = formProperties;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormDataImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TBRedisClusterConfiguration extends TBRedisCacheConfiguration {
@Value("${redis.cluster.nodes:}")
private String clusterNodes;
@Value("${redis.cluster.max-redirects:12}")
private Integer maxRedirects;
@Value("${redis.cluster.useDefaultPoolConfig:true}")
private boolean useDefaultPoolConfig;
@Value("${redis.username:}")
private String username;
@Value("${redis.password:}")
private String password;
@Value("${redis.ssl.enabled:false}")
private boolean useSsl;
public JedisConnectionFactory loadFactory() {
RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
clusterConfiguration.setClusterNodes(getNodes(clusterNodes));
clusterConfiguration.setMaxRedirects(maxRedirects);
clusterConfiguration.setUsername(username); | clusterConfiguration.setPassword(password);
return new JedisConnectionFactory(clusterConfiguration, buildClientConfig());
}
private JedisClientConfiguration buildClientConfig() {
JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfigurationBuilder = JedisClientConfiguration.builder();
if (!useDefaultPoolConfig) {
jedisClientConfigurationBuilder
.usePooling()
.poolConfig(buildPoolConfig());
}
if (useSsl) {
jedisClientConfigurationBuilder
.useSsl()
.sslSocketFactory(createSslSocketFactory());
}
return jedisClientConfigurationBuilder.build();
}
} | repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\TBRedisClusterConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void onSuccess(@Nullable Void tmp) {
result.set(new ReclaimResult(unassignedCustomer));
}
@Override
public void onFailure(Throwable t) {
result.setException(t);
}
})
.build());
return result;
}
cacheEviction(device.getId());
return Futures.immediateFuture(new ReclaimResult(null));
}
private List<Object> constructCacheKey(DeviceId deviceId) {
return List.of(deviceId);
}
private void persistInCache(String secretKey, long durationMs, Cache cache, List<Object> key) {
ClaimData claimData = new ClaimData(secretKey,
System.currentTimeMillis() + validateDurationMs(durationMs));
cache.putIfAbsent(key, claimData);
}
private long validateDurationMs(long durationMs) {
if (durationMs > 0L) {
return durationMs;
}
return systemDurationMs;
}
private ListenableFuture<Void> removeClaimingSavedData(Cache cache, ClaimDataInfo data, Device device) {
if (data.isFromCache()) {
cache.evict(data.getKey()); | }
SettableFuture<Void> result = SettableFuture.create();
telemetryService.deleteAttributes(AttributesDeleteRequest.builder()
.tenantId(device.getTenantId())
.entityId(device.getId())
.scope(AttributeScope.SERVER_SCOPE)
.keys(Arrays.asList(CLAIM_ATTRIBUTE_NAME, CLAIM_DATA_ATTRIBUTE_NAME))
.future(result)
.build());
return result;
}
private void cacheEviction(DeviceId deviceId) {
Cache cache = cacheManager.getCache(CLAIM_DEVICES_CACHE);
cache.evict(constructCacheKey(deviceId));
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\device\ClaimDevicesServiceImpl.java | 2 |
请完成以下Java代码 | public void updatePaymentTermIdFromPaymentDiscount(@NonNull final I_C_OrderLine orderLineRecord, @NonNull final ICalloutField field)
{
updatePaymentTermId(orderLineRecord);
}
private void updatePaymentTermId(@NonNull final I_C_OrderLine orderLineRecord)
{
final PaymentTermId basePaymentTermId = Services.get(IOrderLineBL.class).getPaymentTermId(orderLineRecord);
final Percent paymentDiscount = Percent.of(orderLineRecord.getPaymentDiscount());
final PaymentTermId derivedPaymentTermId = paymentTermService.getOrCreateDerivedPaymentTerm(basePaymentTermId, paymentDiscount);
orderLineRecord.setC_PaymentTerm_Override_ID(PaymentTermId.toRepoId(derivedPaymentTermId));
}
@CalloutMethod(skipIfCopying = true, columnNames = { I_C_OrderLine.COLUMNNAME_C_PaymentTerm_Override_ID, I_C_OrderLine.COLUMNNAME_PaymentDiscount })
public void setManualPaymentTermFlag(@NonNull final I_C_OrderLine orderLineRecord, @NonNull final ICalloutField field)
{
orderLineRecord.setIsManualPaymentTerm(true);
}
@CalloutMethod(skipIfCopying = true, columnNames = { I_C_OrderLine.COLUMNNAME_C_PaymentTerm_Override_ID })
public void resetPaymentDiscount(@NonNull final I_C_OrderLine orderLineRecord, @NonNull final ICalloutField field)
{
final PaymentTermId paymentTermId = PaymentTermId.ofRepoIdOrNull(orderLineRecord.getC_PaymentTerm_Override_ID());
if (paymentTermId == null)
{
orderLineRecord.setPaymentDiscount(null);
return;
} | final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId);
final Percent paymentDiscount = paymentTerm.getDiscount();
orderLineRecord.setPaymentDiscount(paymentDiscount.toBigDecimal());
}
@CalloutMethod(skipIfCopying = true, columnNames = I_C_OrderLine.COLUMNNAME_IsManualPaymentTerm)
public void resetPrices(@NonNull final I_C_OrderLine orderLineRecord, @NonNull final ICalloutField field)
{
if (orderLineRecord.isManualPaymentTerm())
{
return;
}
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updatePrices(OrderLinePriceUpdateRequest.ofOrderLine(orderLineRecord));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\interceptor\C_OrderLine.java | 1 |
请完成以下Java代码 | public String getExternalTaskErrorDetails(String externalTaskId) {
return commandExecutor.execute(new GetExternalTaskErrorDetailsCmd(externalTaskId));
}
@Override
public void setRetries(String externalTaskId, int retries) {
setRetries(externalTaskId, retries, true);
}
@Override
public void setRetries(List<String> externalTaskIds, int retries) {
updateRetries()
.externalTaskIds(externalTaskIds)
.set(retries);
}
@Override | public Batch setRetriesAsync(List<String> externalTaskIds, ExternalTaskQuery externalTaskQuery, int retries) {
return updateRetries()
.externalTaskIds(externalTaskIds)
.externalTaskQuery(externalTaskQuery)
.setAsync(retries);
}
@Override
public UpdateExternalTaskRetriesSelectBuilder updateRetries() {
return new UpdateExternalTaskRetriesBuilderImpl(commandExecutor);
}
@Override
public void extendLock(String externalTaskId, String workerId, long lockDuration) {
commandExecutor.execute(new ExtendLockOnExternalTaskCmd(externalTaskId, workerId, lockDuration));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskServiceImpl.java | 1 |
请完成以下Java代码 | public String getBusinessKey(VariableScope variableScope) {
if (businessKeyValueProvider == null) {
return null;
}
Object result = businessKeyValueProvider.getValue(variableScope);
if (result != null && !(result instanceof String)) {
throw new ClassCastException("Cannot cast '"+result+"' to String");
}
return (String) result;
}
public ParameterValueProvider getBusinessKeyValueProvider() {
return businessKeyValueProvider;
}
public void setBusinessKeyValueProvider(ParameterValueProvider businessKeyValueProvider) {
this.businessKeyValueProvider = businessKeyValueProvider;
}
// inputs //////////////////////////////////////////////////////////////////////
public List<CallableElementParameter> getInputs() {
return inputs;
}
public void addInput(CallableElementParameter input) {
inputs.add(input);
}
public void addInputs(List<CallableElementParameter> inputs) {
this.inputs.addAll(inputs);
}
public VariableMap getInputVariables(VariableScope variableScope) {
List<CallableElementParameter> inputs = getInputs();
return getVariables(inputs, variableScope);
}
// outputs /////////////////////////////////////////////////////////////////////
public List<CallableElementParameter> getOutputs() {
return outputs;
} | public List<CallableElementParameter> getOutputsLocal() {
return outputsLocal;
}
public void addOutput(CallableElementParameter output) {
outputs.add(output);
}
public void addOutputLocal(CallableElementParameter output) {
outputsLocal.add(output);
}
public void addOutputs(List<CallableElementParameter> outputs) {
this.outputs.addAll(outputs);
}
public VariableMap getOutputVariables(VariableScope calledElementScope) {
List<CallableElementParameter> outputs = getOutputs();
return getVariables(outputs, calledElementScope);
}
public VariableMap getOutputVariablesLocal(VariableScope calledElementScope) {
List<CallableElementParameter> outputs = getOutputsLocal();
return getVariables(outputs, calledElementScope);
}
// variables //////////////////////////////////////////////////////////////////
protected VariableMap getVariables(List<CallableElementParameter> params, VariableScope variableScope) {
VariableMap result = Variables.createVariables();
for (CallableElementParameter param : params) {
param.applyTo(variableScope, result);
}
return result;
}
// deployment id //////////////////////////////////////////////////////////////
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\CallableElement.java | 1 |
请完成以下Java代码 | public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg msg) {
log.trace("[{}] Received attributes update notification to device", sessionId);
responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg).toString(), HttpStatus.OK));
}
@Override
public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) {
log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage());
responseWriter.setResult(new ResponseEntity<>(HttpStatus.REQUEST_TIMEOUT));
}
@Override
public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg msg) {
log.trace("[{}] Received RPC command to device", sessionId);
responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg, true).toString(), HttpStatus.OK));
transportService.process(sessionInfo, msg, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY);
}
@Override
public void onToServerRpcResponse(ToServerRpcResponseMsg msg) {
responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg).toString(), HttpStatus.OK));
}
@Override
public void onDeviceDeleted(DeviceId deviceId) {
UUID sessionId = new UUID(sessionInfo.getSessionIdMSB(), sessionInfo.getSessionIdLSB()); | log.trace("[{}] Received device deleted notification for device with id: {}",sessionId, deviceId);
responseWriter.setResult(new ResponseEntity<>("Device was deleted!", HttpStatus.FORBIDDEN));
}
}
private static MediaType parseMediaType(String contentType) {
try {
return MediaType.parseMediaType(contentType);
} catch (Exception e) {
return MediaType.APPLICATION_OCTET_STREAM;
}
}
@Override
public String getName() {
return DataConstants.HTTP_TRANSPORT_NAME;
}
} | repos\thingsboard-master\common\transport\http\src\main\java\org\thingsboard\server\transport\http\DeviceApiController.java | 1 |
请完成以下Java代码 | public V put(K key, V value) {
V oldValue = super.put(key, value);
if (oldValue == null) {
int number = this.size() - 1;
numberToKey.put(number, key);
keyToNumber.put(key, number);
}
return oldValue;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public V remove(Object key) {
V removedValue = super.remove(key);
if (removedValue != null) {
removeFromTrackingMaps(key);
}
return removedValue;
}
@Override
public boolean remove(Object key, Object value) {
boolean removed = super.remove(key, value);
if (removed) {
removeFromTrackingMaps(key);
}
return removed;
}
@Override
public void clear() {
super.clear();
numberToKey.clear();
keyToNumber.clear(); | }
public V getRandomValue() {
if (this.isEmpty()) {
return null;
}
int randomNumber = ThreadLocalRandom.current().nextInt(this.size());
K randomKey = numberToKey.get(randomNumber);
return this.get(randomKey);
}
private void removeFromTrackingMaps(Object key) {
@SuppressWarnings("unchecked")
K keyToRemove = (K) key;
Integer numberToRemove = keyToNumber.get(keyToRemove);
if (numberToRemove == null) {
return;
}
int mapSize = this.size();
int lastIndex = mapSize;
if (numberToRemove == lastIndex) {
numberToKey.remove(numberToRemove);
keyToNumber.remove(keyToRemove);
} else {
K lastKey = numberToKey.get(lastIndex);
if (lastKey == null) {
numberToKey.remove(numberToRemove);
keyToNumber.remove(keyToRemove);
return;
}
numberToKey.put(numberToRemove, lastKey);
keyToNumber.put(lastKey, numberToRemove);
numberToKey.remove(lastIndex);
keyToNumber.remove(keyToRemove);
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-9\src\main\java\com\baeldung\map\randommapkey\RandomizedMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AllocationAmounts subtract(@NonNull final AllocationAmounts other)
{
return toBuilder()
.payAmt(this.payAmt.subtract(other.payAmt))
.discountAmt(this.discountAmt.subtract(other.discountAmt))
.writeOffAmt(this.writeOffAmt.subtract(other.writeOffAmt))
.invoiceProcessingFee(this.invoiceProcessingFee.subtract(other.invoiceProcessingFee))
.build();
}
public AllocationAmounts convertToRealAmounts(@NonNull final InvoiceAmtMultiplier invoiceAmtMultiplier)
{
return negateIf(invoiceAmtMultiplier.isNegateToConvertToRealValue());
}
private AllocationAmounts negateIf(final boolean condition)
{
return condition ? negate() : this;
}
public AllocationAmounts negate()
{
if (isZero())
{
return this;
}
return toBuilder()
.payAmt(this.payAmt.negate())
.discountAmt(this.discountAmt.negate())
.writeOffAmt(this.writeOffAmt.negate())
.invoiceProcessingFee(this.invoiceProcessingFee) // never negate the processing fee because it will be paid to the service provider no matter what kind of invoice it is applied to.
.build(); | }
public Money getTotalAmt()
{
return payAmt.add(discountAmt).add(writeOffAmt).add(invoiceProcessingFee);
}
public boolean isZero()
{
return payAmt.signum() == 0
&& discountAmt.signum() == 0
&& writeOffAmt.signum() == 0
&& invoiceProcessingFee.signum() == 0;
}
public AllocationAmounts toZero()
{
return isZero() ? this : AllocationAmounts.zero(getCurrencyId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\AllocationAmounts.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Ssl getSsl() {
return this.ssl;
}
public static class Ssl {
/**
* Whether to enable SSL support. If enabled, 'mail.(protocol).ssl.enable'
* property is set to 'true'.
*/
private boolean enabled;
/**
* SSL bundle name. If set, 'mail.(protocol).ssl.socketFactory' property is set to
* an SSLSocketFactory obtained from the corresponding SSL bundle.
* <p>
* Note that the STARTTLS command can use the corresponding SSLSocketFactory, even
* if the 'mail.(protocol).ssl.enable' property is not set.
*/
private @Nullable String bundle; | public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CurrencyId getCurrencyId()
{
return getAmountsToAllocate().getCurrencyId();
}
public void addAllocatedAmounts(@NonNull final AllocationAmounts amounts)
{
amountsAllocated = amountsAllocated.add(amounts);
amountsToAllocate = amountsToAllocate.subtract(amounts);
}
public void moveRemainingOpenAmtToDiscount()
{
amountsToAllocate = amountsToAllocate.movePayAmtToDiscount();
}
public void moveRemainingOpenAmtToWriteOff()
{
amountsToAllocate = amountsToAllocate.movePayAmtToWriteOff();
}
public Money computeProjectedOverUnderAmt(@NonNull final AllocationAmounts amountsToAllocate)
{
return computeOpenAmtRemainingToAllocate().subtract(amountsToAllocate.getTotalAmt());
}
@NonNull
private Money computeOpenAmtRemainingToAllocate()
{
return openAmtInitial.subtract(amountsAllocated.getTotalAmt());
}
@NonNull
public Money getTotalAllocatedAmount()
{ | return amountsAllocated.getTotalAmt();
}
public boolean isFullyAllocated()
{
return amountsToAllocate.getTotalAmt().isZero();
}
public boolean isARC()
{
return isCreditMemo() && getSoTrx().isSales();
}
public boolean isAPI()
{
return !isCreditMemo() && getSoTrx().isPurchase();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PayableDocument.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_AD_Workflow getAD_Workflow() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class);
}
@Override
public void setAD_Workflow(org.compiere.model.I_AD_Workflow AD_Workflow)
{
set_ValueFromPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class, AD_Workflow);
}
/** Set Workflow.
@param AD_Workflow_ID
Workflow or combination of tasks
*/
@Override
public void setAD_Workflow_ID (int AD_Workflow_ID)
{
if (AD_Workflow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, Integer.valueOf(AD_Workflow_ID));
}
/** Get Workflow.
@return Workflow or combination of tasks
*/
@Override
public int getAD_Workflow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
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_AD_Workflow_Access.java | 1 |
请完成以下Java代码 | public class ShipmentSchedulesMDC
{
public MDCCloseable putShipmentScheduleId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return TableRecordMDC.putTableRecordReference(I_M_ShipmentSchedule.Table_Name, shipmentScheduleId);
}
public MDCCloseable putShipmentSchedule(@NonNull final I_M_ShipmentSchedule shipmentSchedule)
{
return putShipmentScheduleId(ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID()));
}
public MDCCloseable putShipmentScheduleUpdateRunNo(final int runNo)
{
return MDC.putCloseable("ShipmentScheduleUpdater-Run#", Integer.toString(runNo));
} | public MDCCloseable putRevalidationId(@NonNull final PInstanceId selectionId)
{
return MDC.putCloseable("RevalidationId", Integer.toString(selectionId.getRepoId()));
}
/**
* Remove shipment schedule ID from MDC just to add it back when the closable is closed.
*/
public IAutoCloseable removeCurrentShipmentScheduleId()
{
final String value = MDC.get(I_M_ShipmentSchedule.Table_Name);
MDC.remove(I_M_ShipmentSchedule.Table_Name);
return () -> MDC.put(I_M_ShipmentSchedule.Table_Name, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\ShipmentSchedulesMDC.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PayModeEnum getPayModeEnum() {
return payModeEnum;
}
public void setPayModeEnum(PayModeEnum payModeEnum) {
this.payModeEnum = payModeEnum;
}
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public ReceiptEntity getReceiptEntity() {
return receiptEntity;
}
public void setReceiptEntity(ReceiptEntity receiptEntity) {
this.receiptEntity = receiptEntity;
}
public LocationEntity getLocationEntity() {
return locationEntity;
}
public void setLocationEntity(LocationEntity locationEntity) {
this.locationEntity = locationEntity;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getExpressNo() {
return expressNo;
} | public void setExpressNo(String expressNo) {
this.expressNo = expressNo;
}
public UserEntity getBuyer() {
return buyer;
}
public void setBuyer(UserEntity buyer) {
this.buyer = buyer;
}
@Override
public String toString() {
return "OrdersEntity{" +
"id='" + id + '\'' +
", buyer=" + buyer +
", company=" + company +
", productOrderList=" + productOrderList +
", orderStateEnum=" + orderStateEnum +
", orderStateTimeList=" + orderStateTimeList +
", payModeEnum=" + payModeEnum +
", totalPrice='" + totalPrice + '\'' +
", receiptEntity=" + receiptEntity +
", locationEntity=" + locationEntity +
", remark='" + remark + '\'' +
", expressNo='" + expressNo + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
List<JsonDocument> docs = new ArrayList<>();
for (String key : keys) {
JsonDocument doc = bucket.get(key);
if (doc != null) {
docs.add(doc);
}
}
return docs;
}
@Override
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
} | });
final List<JsonDocument> docs = new ArrayList<>();
try {
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
docs.add(doc);
}
});
} catch (Exception e) {
logger.error("Error during bulk get", e);
}
return docs;
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\spring\service\ClusterServiceImpl.java | 2 |
请完成以下Java代码 | public void updateASI()
{
final Object sourceModel = getSourceModel();
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(sourceModel);
if (asiAware == null)
{
return;
}
if (asiAware.getM_Product_ID() <= 0)
{
return;
}
final AttributeId lotNoAttributeId = Services.get(ILotNumberDateAttributeDAO.class).getLotNumberAttributeId();
if (lotNoAttributeId == null)
{
return;
}
final ProductId productId = ProductId.ofRepoId(asiAware.getM_Product_ID());
final I_M_Attribute attribute = attributesBL.getAttributeOrNull(productId, lotNoAttributeId);
if (attribute == null)
{
return;
}
attributeSetInstanceBL.getCreateASI(asiAware);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoId(asiAware.getM_AttributeSetInstance_ID());
final I_M_AttributeInstance ai = attributeSetInstanceBL.getAttributeInstance(asiId, lotNoAttributeId); | if (ai != null)
{
// If it was set, just leave it as it is
return;
}
attributeSetInstanceBL.getCreateAttributeInstance(asiId, lotNoAttributeId);
}
public LotNumberAttributeUpdater setSourceModel(final Object sourceModel)
{
this.sourceModel = sourceModel;
return this;
}
private Object getSourceModel()
{
Check.assumeNotNull(sourceModel, "sourceModel not null");
return sourceModel;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\LotNumberAttributeUpdater.java | 1 |
请完成以下Java代码 | public int getCarrier_ShipmentOrder_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_ID);
}
@Override
public void setCarrier_ShipmentOrder_Log_ID (final int Carrier_ShipmentOrder_Log_ID)
{
if (Carrier_ShipmentOrder_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_ShipmentOrder_Log_ID, Carrier_ShipmentOrder_Log_ID);
}
@Override
public int getCarrier_ShipmentOrder_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Log_ID);
}
@Override
public void setDurationMillis (final int DurationMillis)
{
set_Value (COLUMNNAME_DurationMillis, DurationMillis);
}
@Override
public int getDurationMillis()
{
return get_ValueAsInt(COLUMNNAME_DurationMillis);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setRequestID (final java.lang.String RequestID)
{
set_Value (COLUMNNAME_RequestID, RequestID);
}
@Override
public java.lang.String getRequestID()
{ | return get_ValueAsString(COLUMNNAME_RequestID);
}
@Override
public void setRequestMessage (final @Nullable java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
@Override
public java.lang.String getRequestMessage()
{
return get_ValueAsString(COLUMNNAME_RequestMessage);
}
@Override
public void setResponseMessage (final @Nullable java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
@Override
public java.lang.String getResponseMessage()
{
return get_ValueAsString(COLUMNNAME_ResponseMessage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Log.java | 1 |
请完成以下Java代码 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getSession(false) != null) {
response.sendRedirect(request.getContextPath() + "/user-check/home");
return;
}
String referer = (String) request.getAttribute("origin");
request.setAttribute("origin", referer);
UserCheckFilter.forward(request, response, "/login.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = request.getParameter("name");
String pass = request.getParameter("password");
User user = User.DB.get(key);
if (user == null || !user.getPassword()
.equals(pass)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
request.setAttribute("origin", request.getParameter("origin")); | request.setAttribute("error", "invalid login");
UserCheckFilter.forward(request, response, "/login.jsp");
return;
}
user.getLogins()
.add(new Date());
HttpSession session = request.getSession();
session.setAttribute("user", user);
String origin = request.getParameter("origin");
if (origin == null || origin.contains("login"))
origin = "./";
response.sendRedirect(origin);
}
} | repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\user\check\UserCheckLoginServlet.java | 1 |
请完成以下Java代码 | protected ViewLayout createViewLayout(final ViewLayoutKey key)
{
final ITranslatableString caption = getProcessCaption(WEBUI_BPartner_ProductsProposal_Launcher.class)
.orElse(null);
return ViewLayout.builder()
.setWindowId(key.getWindowId())
.setCaption(caption)
.addElementsFromViewRowClass(ProductsProposalRow.class, key.getViewDataType())
.removeElementByFieldName(ProductsProposalRow.FIELD_Qty)
.allowViewCloseAction(ViewCloseAction.DONE)
.setAllowOpeningRowDetails(false)
.build();
}
@Override
protected ProductsProposalRowsLoader createRowsLoaderFromRecord(final TableRecordReference recordRef)
{
final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
recordRef.assertTableName(I_C_BPartner.Table_Name);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(recordRef.getRecord_ID());
final Set<CountryId> countryIds = bpartnersRepo.retrieveBPartnerLocationCountryIds(bpartnerId);
if (countryIds.isEmpty())
{
throw new AdempiereException("@NotFound@ @C_BPartner_Location_ID@");
}
final I_C_BPartner bpartnerRecord = bpartnersRepo.getById(bpartnerId);
PricingSystemId pricingSystemId = null;
SOTrx soTrx = null;
if (bpartnerRecord.isCustomer())
{
pricingSystemId = PricingSystemId.ofRepoIdOrNull(bpartnerRecord.getM_PricingSystem_ID());
soTrx = SOTrx.SALES;
}
if (pricingSystemId == null && bpartnerRecord.isVendor())
{
pricingSystemId = PricingSystemId.ofRepoIdOrNull(bpartnerRecord.getPO_PricingSystem_ID());
soTrx = SOTrx.PURCHASE; | }
if (pricingSystemId == null)
{
throw new AdempiereException("@NotFound@ @M_PricingSystem_ID@");
}
final ZonedDateTime today = SystemTime.asZonedDateTime();
final Set<PriceListVersionId> priceListVersionIds = priceListsRepo.retrievePriceListsCollectionByPricingSystemId(pricingSystemId)
.filterAndStreamIds(countryIds)
.map(priceListId -> priceListsRepo.retrievePriceListVersionId(priceListId, today))
.collect(ImmutableSet.toImmutableSet());
return ProductsProposalRowsLoader.builder()
.lookupDataSourceFactory(lookupDataSourceFactory)
.bpartnerProductStatsService(bpartnerProductStatsService)
.orderProductProposalsService(orderProductProposalsService)
.priceListVersionIds(priceListVersionIds)
.bpartnerId(bpartnerId)
.soTrx(soTrx)
.build();
}
@Override
protected List<RelatedProcessDescriptor> getRelatedProcessDescriptors()
{
return ImmutableList.of(
createProcessDescriptor(WEBUI_ProductsProposal_SaveProductPriceToCurrentPriceListVersion.class),
createProcessDescriptor(WEBUI_ProductsProposal_ShowProductsToAddFromBasePriceList.class));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\BPartnerProductsProposalViewFactory.java | 1 |
请完成以下Java代码 | public EnqueueDesadvResult enqueue(@NonNull final EnqueueDesadvRequest enqueueDesadvRequest)
{
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(enqueueDesadvRequest.getCtx(), EDIWorkpackageProcessor.class);
final ImmutableList.Builder<I_EDI_Desadv> skippedDesadvCollector = ImmutableList.builder();
trxItemProcessorExecutorService
.<I_EDI_Desadv, Void>createExecutor()
.setContext(enqueueDesadvRequest.getCtx(), ITrx.TRXNAME_None)
.setExceptionHandler(FailTrxItemExceptionHandler.instance)
.setProcessor(new TrxItemProcessorAdapter<I_EDI_Desadv, Void>()
{
@Override
public void process(final I_EDI_Desadv desadv)
{
// make sure the desadvs that don't meet the sum percentage requirement won't get enqueued
final BigDecimal currentSumPercentage = desadv.getFulfillmentPercent();
if (currentSumPercentage.compareTo(desadv.getFulfillmentPercentMin()) < 0)
{
skippedDesadvCollector.add(desadv);
}
else
{
// note: in here, the desadv has the item processor's trxName (as of this task)
enqueueDesadv(enqueueDesadvRequest.getPInstanceId(), queue, desadv);
}
}
})
.process(enqueueDesadvRequest.getDesadvIterator());
return EnqueueDesadvResult.builder()
.skippedDesadvList(skippedDesadvCollector.build())
.build();
}
private void enqueueDesadv( | @Nullable final PInstanceId pInstanceId,
@NonNull final IWorkPackageQueue queue,
@NonNull final I_EDI_Desadv desadv)
{
final String trxName = InterfaceWrapperHelper.getTrxName(desadv);
queue
.newWorkPackage()
.setAD_PInstance_ID(pInstanceId)
.bindToTrxName(trxName)
.addElement(desadv)
.buildAndEnqueue();
desadv.setEDI_ExportStatus(X_EDI_Desadv.EDI_EXPORTSTATUS_Enqueued);
InterfaceWrapperHelper.save(desadv);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\enqueue\DesadvEnqueuer.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-application # 应用名
management:
endpoints:
# Actuator HTTP 配置项,对应 WebEndpointProperties 配置类
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点 | 。通过设置 * ,可以开放所有端点。
metrics:
tags: # 通用标签
application: ${spring.application.name} | repos\SpringBoot-Labs-master\lab-36\lab-36-prometheus-demo\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | private final void onClose()
{
if (isDisposed())
{
return;
}
if (callback == null)
{
return;
}
callback.notificationClosed(item);
}
public void dispose()
{
setVisible(false);
disposed = true;
} | private boolean isDisposed()
{
return disposed;
}
/**
* Fade away and dispose this notification item.
*/
public void fadeAwayAndDispose()
{
// NOTE: atm we are just disposing it. Maybe in future we will really implement a nice fade away behaviour.
dispose();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\NotificationItemPanel.java | 1 |
请完成以下Java代码 | public void setC_Currency_ID (int C_Currency_ID)
{
if (C_Currency_ID < 1)
set_Value (COLUMNNAME_C_Currency_ID, null);
else
set_Value (COLUMNNAME_C_Currency_ID, Integer.valueOf(C_Currency_ID));
}
/** Get Currency.
@return The Currency for this record
*/
public int getC_Currency_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Currency_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Project Cycle.
@param C_Cycle_ID
Identifier for this Project Reporting Cycle
*/
public void setC_Cycle_ID (int C_Cycle_ID)
{
if (C_Cycle_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, Integer.valueOf(C_Cycle_ID));
}
/** Get Project Cycle.
@return Identifier for this Project Reporting Cycle
*/
public int getC_Cycle_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description) | {
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cycle.java | 1 |
请完成以下Java代码 | public boolean isValidDPD()
{
return get_ValueAsBoolean(COLUMNNAME_IsValidDPD);
}
@Override
public void setNonStdAddress (final boolean NonStdAddress)
{
set_Value (COLUMNNAME_NonStdAddress, NonStdAddress);
}
@Override
public boolean isNonStdAddress()
{
return get_ValueAsBoolean(COLUMNNAME_NonStdAddress);
}
@Override
public void setPostal (final @Nullable java.lang.String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
public void setPostal_Add (final @Nullable java.lang.String Postal_Add)
{
set_Value (COLUMNNAME_Postal_Add, Postal_Add);
}
@Override
public java.lang.String getPostal_Add()
{ | return get_ValueAsString(COLUMNNAME_Postal_Add);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
@Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setTownship (final @Nullable java.lang.String Township)
{
set_Value (COLUMNNAME_Township, Township);
}
@Override
public java.lang.String getTownship()
{
return get_ValueAsString(COLUMNNAME_Township);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Postal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JwtUserDto getUserCache(String userName) {
// 转小写
userName = StringUtils.lowerCase(userName);
if (StringUtils.isNotEmpty(userName)) {
// 获取数据
return redisUtils.get(LoginProperties.cacheKey + userName, JwtUserDto.class);
}
return null;
}
/**
* 添加缓存到Redis
* @param userName 用户名
*/
@Async
public void addUserCache(String userName, JwtUserDto user) {
// 转小写
userName = StringUtils.lowerCase(userName);
if (StringUtils.isNotEmpty(userName)) {
// 添加数据, 避免数据同时过期 | long time = idleTime + RandomUtil.randomInt(900, 1800);
redisUtils.set(LoginProperties.cacheKey + userName, user, time);
}
}
/**
* 清理用户缓存信息
* 用户信息变更时
* @param userName 用户名
*/
@Async
public void cleanUserCache(String userName) {
// 转小写
userName = StringUtils.lowerCase(userName);
if (StringUtils.isNotEmpty(userName)) {
// 清除数据
redisUtils.del(LoginProperties.cacheKey + userName);
}
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\service\UserCacheManager.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected final String getLoginPage() {
return this.loginPage;
}
/**
* Gets the Authentication Entry Point
* @return the Authentication Entry Point
*/
protected final AuthenticationEntryPoint getAuthenticationEntryPoint() {
return this.authenticationEntryPoint;
}
/**
* Gets the URL to submit an authentication request to (i.e. where username/password
* must be submitted)
* @return the URL to submit an authentication request to
*/
protected final String getLoginProcessingUrl() {
return this.loginProcessingUrl;
}
/**
* Gets the URL to send users to if authentication fails
* @return the URL to send users if authentication fails (e.g. "/login?error").
*/
protected final String getFailureUrl() {
return this.failureUrl;
}
/**
* Updates the default values for authentication.
*/
protected final void updateAuthenticationDefaults() {
if (this.loginProcessingUrl == null) {
loginProcessingUrl(this.loginPage);
}
if (this.failureHandler == null) {
failureUrl(this.loginPage + "?error");
}
LogoutConfigurer<B> logoutConfigurer = getBuilder().getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null && !logoutConfigurer.isCustomLogoutSuccess()) {
logoutConfigurer.logoutSuccessUrl(this.loginPage + "?logout");
}
}
/**
* Updates the default values for access.
*/
protected final void updateAccessDefaults(B http) { | if (this.permitAll) {
PermitAllSupport.permitAll(http, this.loginPage, this.loginProcessingUrl, this.failureUrl);
}
}
/**
* Sets the loginPage and updates the {@link AuthenticationEntryPoint}.
* @param loginPage
*/
private void setLoginPage(String loginPage) {
this.loginPage = loginPage;
this.authenticationEntryPoint = new LoginUrlAuthenticationEntryPoint(loginPage);
}
private <C> C getBeanOrNull(B http, Class<C> clazz) {
ApplicationContext context = http.getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
return context.getBeanProvider(clazz).getIfUnique();
}
@SuppressWarnings("unchecked")
private T getSelf() {
return (T) this;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AbstractAuthenticationFilterConfigurer.java | 2 |
请完成以下Java代码 | public int getColtIntList() {
return coltList.get(getValue);
}
@Benchmark
public int getFastUtilIntList() {
return fastUtilList.getInt(getValue);
}
@Benchmark
public boolean containsArrayList() {
return arrayList.contains(getValue);
}
@Benchmark
public boolean containsTroveIntList() {
return tList.contains(getValue);
}
@Benchmark
public boolean containsColtIntList() {
return coltList.contains(getValue); | }
@Benchmark
public boolean containsFastUtilIntList() {
return fastUtilList.contains(getValue);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(PrimitivesListPerformance.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\primitive\PrimitivesListPerformance.java | 1 |
请完成以下Java代码 | private PPOrderId createPickingOrderIfNeeded(@NonNull final I_C_OrderLine salesOrderLine)
{
final OrgId orgId = OrgId.ofRepoId(salesOrderLine.getAD_Org_ID());
final WarehouseId warehouseId = getWarehouseId(salesOrderLine);
final ProductId productId = ProductId.ofRepoId(salesOrderLine.getM_Product_ID());
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(salesOrderLine.getM_AttributeSetInstance_ID());
final PickingOrderConfig config = pickingBOMService.getPickingOrderConfig(orgId, warehouseId, productId, asiId).orElse(null);
if (config == null)
{
return null;
}
final I_C_UOM stockUOM = productBL.getStockUOM(productId);
final Quantity qtyOrdered = Quantity.of(salesOrderLine.getQtyOrdered(), stockUOM);
final I_PP_Order ppOrder = ppOrderBL.createOrder(PPOrderCreateRequest.builder()
.clientAndOrgId(ClientAndOrgId.ofClientAndOrg(salesOrderLine.getAD_Client_ID(), salesOrderLine.getAD_Org_ID()))
.productPlanningId(config.getProductPlanningId())
// .materialDispoGroupId(null)
//
.plantId(config.getPlantId())
.warehouseId(warehouseId)
.plannerId(config.getPlannerId())
//
.bomId(config.getBomId())
.productId(productId)
.attributeSetInstanceId(asiId)
.qtyRequired(qtyOrdered) | //
.dateOrdered(SystemTime.asInstant())
.datePromised(TimeUtil.asInstant(salesOrderLine.getDatePromised()))
.dateStartSchedule(SystemTime.asInstant())
//
.salesOrderLineId(OrderLineId.ofRepoId(salesOrderLine.getC_OrderLine_ID()))
.customerId(BPartnerId.ofRepoId(salesOrderLine.getC_BPartner_ID()))
//
.completeDocument(true)
//
.build());
return PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\inoutcandidate\OrderLineShipmentScheduleHandler.java | 1 |
请完成以下Java代码 | public String getBPartnerAddress()
{
return delegate.getBPartnerAddress();
}
@Override
public void setBPartnerAddress(final String address)
{
delegate.setBPartnerAddress(address);
}
}
@ToString
private class ReceiptScheduleEffectiveDocumentLocation implements IDocumentLocationAdapter
{
private final I_M_ReceiptSchedule delegate;
private ReceiptScheduleEffectiveDocumentLocation(@NonNull final I_M_ReceiptSchedule delegate)
{
this.delegate = delegate;
}
@Override
public int getC_BPartner_ID()
{
return BPartnerId.toRepoId(getBPartnerEffectiveId(delegate));
}
@Override
public void setC_BPartner_ID(final int C_BPartner_ID)
{
}
@Override
public int getC_BPartner_Location_ID()
{
return getC_BPartner_Location_Effective_ID(delegate);
}
@Override
@Deprecated
public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID)
{
}
@Override
public int getC_BPartner_Location_Value_ID()
{
return -1;
}
@Override
public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID)
{ | }
@Override
public int getAD_User_ID()
{
return BPartnerContactId.toRepoId(getBPartnerContactID(delegate));
}
@Override
public void setAD_User_ID(final int AD_User_ID)
{
}
@Override
public String getBPartnerAddress()
{
return delegate.getBPartnerAddress_Override();
}
@Override
public void setBPartnerAddress(final String address)
{
delegate.setBPartnerAddress_Override(address);
}
}
@Override
public int updateDatePromisedOverrideAndPOReference(@NonNull final PInstanceId pinstanceId, @Nullable final LocalDate datePromisedOverride, @Nullable final String poReference)
{
if (datePromisedOverride == null && Check.isBlank(poReference))
{
throw new AdempiereException(MSG_DATEPROMISEDOVERRIDE_POREFERENCE_VALIDATION_ERROR)
.markAsUserValidationError();
}
final ICompositeQueryUpdater<I_M_ReceiptSchedule> updater = queryBL
.createCompositeQueryUpdater(I_M_ReceiptSchedule.class);
if (datePromisedOverride != null)
{
updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_DatePromised_Override, datePromisedOverride);
}
if (!Check.isBlank(poReference))
{
updater.addSetColumnValue(I_M_ReceiptSchedule.COLUMNNAME_POReference, poReference);
}
return queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.setOnlySelection(pinstanceId)
.create()
.update(updater);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ReceiptScheduleBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CalculatedFieldType getType() {
return CalculatedFieldType.ALARM;
}
@Override
public Output getOutput() {
return null;
}
@JsonIgnore
@Override
public boolean requiresScheduledReevaluation() {
return getAllRules().anyMatch(entry -> entry.getValue().requiresScheduledReevaluation());
}
@JsonIgnore
public Stream<Pair<AlarmSeverity, AlarmRule>> getAllRules() {
Stream<Pair<AlarmSeverity, AlarmRule>> rules = createRules.entrySet().stream()
.map(entry -> Pair.of(entry.getKey(), entry.getValue()));
if (clearRule != null) {
rules = Stream.concat(rules, Stream.of(Pair.of(null, clearRule)));
}
return rules.sorted(comparingByKey(Comparator.nullsLast(Comparator.naturalOrder())));
} | public boolean rulesEqual(AlarmCalculatedFieldConfiguration other, BiPredicate<AlarmRule, AlarmRule> equalityCheck) {
List<Pair<AlarmSeverity, AlarmRule>> thisRules = this.getAllRules().toList();
List<Pair<AlarmSeverity, AlarmRule>> otherRules = other.getAllRules().toList();
return CollectionsUtil.elementsEqual(thisRules, otherRules, (thisRule, otherRule) -> {
if (!Objects.equals(thisRule.getKey(), otherRule.getKey())) {
return false;
}
return equalityCheck.test(thisRule.getValue(), otherRule.getValue());
});
}
public boolean propagationSettingsEqual(AlarmCalculatedFieldConfiguration other) {
return this.propagate == other.propagate &&
this.propagateToOwner == other.propagateToOwner &&
this.propagateToTenant == other.propagateToTenant &&
Objects.equals(this.propagateRelationTypes, other.propagateRelationTypes);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\AlarmCalculatedFieldConfiguration.java | 2 |
请完成以下Java代码 | public void onError(String params, Exception e) {
try {
if (e instanceof TimeoutException) {
return;
}
processRemove.run();
} finally {
callback.onError(params, e);
}
}
};
}
@Override
public void persistUpdates(String endpoint) {
LwM2MModelConfig modelConfig = currentModelConfigs.get(endpoint);
if (modelConfig != null && !modelConfig.isEmpty()) {
modelStore.put(modelConfig);
} | }
@Override
public void removeUpdates(String endpoint) {
currentModelConfigs.remove(endpoint);
modelStore.remove(endpoint);
}
@PreDestroy
private void destroy() {
currentModelConfigs.values().forEach(model -> {
if (model != null && !model.isEmpty()) {
modelStore.put(model);
}
});
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\model\LwM2MModelConfigServiceImpl.java | 1 |
请完成以下Java代码 | public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
}
/**
* Information about the Java Runtime Environment the application is running in.
*/
public static class JavaRuntimeEnvironmentInfo {
private final String name;
private final String version;
public JavaRuntimeEnvironmentInfo() {
this.name = System.getProperty("java.runtime.name");
this.version = System.getProperty("java.runtime.version");
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
} | /**
* Information about the Java Virtual Machine the application is running in.
*/
public static class JavaVirtualMachineInfo {
private final String name;
private final String vendor;
private final String version;
public JavaVirtualMachineInfo() {
this.name = System.getProperty("java.vm.name");
this.vendor = System.getProperty("java.vm.vendor");
this.version = System.getProperty("java.vm.version");
}
public String getName() {
return this.name;
}
public String getVendor() {
return this.vendor;
}
public String getVersion() {
return this.version;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\JavaInfo.java | 1 |
请完成以下Java代码 | public BigDecimal getTaxAmt()
{
return isAccountSignDR() ? glJournalLine.getDR_TaxAmt() : glJournalLine.getCR_TaxAmt();
}
@Override
public void setTaxAmt(final BigDecimal taxAmt)
{
if (isAccountSignDR())
{
glJournalLine.setDR_TaxAmt(taxAmt);
}
else
{
glJournalLine.setCR_TaxAmt(taxAmt);
}
}
@Override
public BigDecimal getTaxBaseAmt()
{
return isAccountSignDR() ? glJournalLine.getDR_TaxBaseAmt() : glJournalLine.getCR_TaxBaseAmt();
}
@Override
public void setTaxBaseAmt(final BigDecimal taxBaseAmt)
{
if (isAccountSignDR())
{
glJournalLine.setDR_TaxBaseAmt(taxBaseAmt);
}
else
{
glJournalLine.setCR_TaxBaseAmt(taxBaseAmt);
}
}
@Override
public BigDecimal getTaxTotalAmt()
{
return isAccountSignDR() ? glJournalLine.getDR_TaxTotalAmt() : glJournalLine.getCR_TaxTotalAmt();
}
@Override
public void setTaxTotalAmt(final BigDecimal totalAmt)
{
if (isAccountSignDR()) | {
glJournalLine.setDR_TaxTotalAmt(totalAmt);
}
else
{
glJournalLine.setCR_TaxTotalAmt(totalAmt);
}
//
// Update AmtSourceDr/Cr
// NOTE: we are updating both sides because they shall be the SAME
glJournalLine.setAmtSourceDr(totalAmt);
glJournalLine.setAmtSourceCr(totalAmt);
}
@Override
public I_C_ValidCombination getTaxBase_Acct()
{
return isAccountSignDR() ? glJournalLine.getAccount_DR() : glJournalLine.getAccount_CR();
}
@Override
public I_C_ValidCombination getTaxTotal_Acct()
{
return isAccountSignDR() ? glJournalLine.getAccount_CR() : glJournalLine.getAccount_DR();
}
@Override
public CurrencyPrecision getPrecision()
{
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournalLine.getC_Currency_ID());
return currencyId != null
? Services.get(ICurrencyDAO.class).getStdPrecision(currencyId)
: CurrencyPrecision.TWO;
}
@Override
public AcctSchemaId getAcctSchemaId()
{
return AcctSchemaId.ofRepoId(glJournalLine.getGL_Journal().getC_AcctSchema_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\impl\GLJournalLineTaxAccountable.java | 1 |
请完成以下Java代码 | public void extractKeyParts(final CacheKeyBuilder keyBuilder, final Object targetObject, final Object[] params)
{
final Object modelObj = params[parameterIndex];
int id = -1;
Exception errorException = null;
if (modelObj != null)
{
try
{
id = InterfaceWrapperHelper.getId(modelObj);
}
catch (final Exception ex)
{
id = -1;
errorException = ex;
}
}
if (id < 0 || errorException != null)
{
keyBuilder.setSkipCaching(); | final CacheGetException ex = new CacheGetException("Invalid parameter type.")
.addSuppressIfNotNull(errorException)
.setTargetObject(targetObject)
.setMethodArguments(params)
.setInvalidParameter(parameterIndex, modelObj)
.setAnnotation(CacheTrx.class);
logger.warn("Invalid parameter. Skip caching", ex);
return;
}
keyBuilder.add(id);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheModelIdParamDescriptor.java | 1 |
请完成以下Java代码 | protected boolean isEligible(final IDunningContext dunningContext, final IDunnableDoc dunnableDoc)
{
if (dunnableDoc.getOpenAmt().signum() == 0)
{
logger.info("Skip " + dunnableDoc + " because OpenAmt is ZERO");
return false;
}
if (dunnableDoc.isInDispute())
{
logger.info("Skip " + dunnableDoc + " because is in dispute");
return false;
}
final I_C_DunningLevel level = dunningContext.getC_DunningLevel();
final boolean isDue = dunnableDoc.getDaysDue() >= 0;
if (isDue)
{
if (level.isShowAllDue())
{
// Document is due, and we are asked to show all due, so there is no point to check if the days after due is valid
return true;
}
}
else | {
// Document is not due yet => not eligible for dunning
return false;
}
final int daysAfterDue = level.getDaysAfterDue().intValue();
if (dunnableDoc.getDaysDue() < daysAfterDue)
{
logger.info("Skip " + dunnableDoc + " because is not already due (DaysAfterDue:" + daysAfterDue + ")");
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\spi\impl\AbstractDunnableSource.java | 1 |
请完成以下Java代码 | public Boolean isStrictMode() {
return strictMode;
}
public void setStrictMode(Boolean strictMode) {
this.strictMode = strictMode;
}
public Map<String, String> getInputVariableTypes() {
return inputVariableTypes;
}
public void setInputVariableTypes(Map<String, String> inputVariableTypes) {
this.inputVariableTypes = inputVariableTypes;
}
public Map<String, String> getDecisionResultTypes() {
return decisionResultTypes;
}
public void addDecisionResultType(String decisionResultId, String decisionResultType) {
this.decisionResultTypes.put(decisionResultId, decisionResultType);
}
protected static boolean isBoolean(Object obj) {
return obj instanceof Boolean;
}
protected static boolean isDate(Object obj) {
return (obj instanceof Date || obj instanceof DateTime || obj instanceof LocalDate || obj instanceof java.time.LocalDate || obj instanceof LocalDateTime
|| obj instanceof Instant);
}
protected static boolean isNumber(Object obj) {
return obj instanceof Number;
}
protected Map<String, Object> createDefensiveCopyInputVariables(Map<String, Object> inputVariables) {
Map<String, Object> defensiveCopyMap = new HashMap<>();
if (inputVariables != null) { | for (Map.Entry<String, Object> entry : inputVariables.entrySet()) {
Object newValue = null;
if (entry.getValue() == null) {
// do nothing
} else if (entry.getValue() instanceof Long) {
newValue = Long.valueOf(((Long) entry.getValue()).longValue());
} else if (entry.getValue() instanceof Double) {
newValue = Double.valueOf(((Double) entry.getValue()).doubleValue());
} else if (entry.getValue() instanceof Integer) {
newValue = Integer.valueOf(((Integer) entry.getValue()).intValue());
} else if (entry.getValue() instanceof Date) {
newValue = new Date(((Date) entry.getValue()).getTime());
} else if (entry.getValue() instanceof Boolean) {
newValue = Boolean.valueOf(((Boolean) entry.getValue()).booleanValue());
} else {
newValue = new String(entry.getValue().toString());
}
defensiveCopyMap.put(entry.getKey(), newValue);
}
}
return defensiveCopyMap;
}
} | repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DecisionExecutionAuditContainer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LLMConfiguration {
@Bean
public VectorStore vectorStore(EmbeddingModel embeddingModel) {
return SimpleVectorStore
.builder(embeddingModel)
.build();
}
@Bean
public ChatClient contentGenerator(ChatModel chatModel, VectorStore vectorStore) {
return ChatClient.builder(chatModel)
.defaultAdvisors(new QuestionAnswerAdvisor(vectorStore))
.build();
}
@Bean
public ChatClient contentEvaluator(
OllamaApi olamaApi,
@Value("${com.baeldung.evaluation.model}") String evaluationModel) {
ChatModel chatModel = OllamaChatModel.builder()
.ollamaApi(olamaApi) | .defaultOptions(OllamaOptions.builder()
.model(evaluationModel)
.build())
.modelManagementOptions(ModelManagementOptions.builder()
.pullModelStrategy(PullModelStrategy.WHEN_MISSING)
.build())
.build();
return ChatClient.builder(chatModel)
.build();
}
@Bean
public FactCheckingEvaluator factCheckingEvaluator(@Qualifier("contentEvaluator") ChatClient chatClient) {
return new FactCheckingEvaluator(chatClient.mutate());
}
@Bean
public RelevancyEvaluator relevancyEvaluator(@Qualifier("contentEvaluator") ChatClient chatClient) {
return new RelevancyEvaluator(chatClient.mutate());
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\java\com\baeldung\springai\evaluator\LLMConfiguration.java | 2 |
请完成以下Java代码 | public String getOrgColumn ()
{
return (String)get_Value(COLUMNNAME_OrgColumn);
}
/** Set Measure Calculation.
@param PA_MeasureCalc_ID
Calculation method for measuring performance
*/
public void setPA_MeasureCalc_ID (int PA_MeasureCalc_ID)
{
if (PA_MeasureCalc_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, Integer.valueOf(PA_MeasureCalc_ID));
}
/** Get Measure Calculation.
@return Calculation method for measuring performance
*/
public int getPA_MeasureCalc_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_MeasureCalc_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Product Column.
@param ProductColumn
Fully qualified Product column (M_Product_ID)
*/
public void setProductColumn (String ProductColumn)
{
set_Value (COLUMNNAME_ProductColumn, ProductColumn);
}
/** Get Product Column.
@return Fully qualified Product column (M_Product_ID)
*/
public String getProductColumn ()
{ | return (String)get_Value(COLUMNNAME_ProductColumn);
}
/** Set Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_MeasureCalc.java | 1 |
请完成以下Java代码 | public double[] categorize(Document document) throws IllegalArgumentException, IllegalStateException
{
Integer category;
Integer feature;
Integer occurrences;
Double logprob;
double[] predictionScores = new double[model.catalog.length];
for (Map.Entry<Integer, Double> entry1 : model.logPriors.entrySet())
{
category = entry1.getKey();
logprob = entry1.getValue(); //用类目的对数似然初始化概率
//对文档中的每个特征
for (Map.Entry<Integer, int[]> entry2 : document.tfMap.entrySet())
{
feature = entry2.getKey();
if (!model.logLikelihoods.containsKey(feature))
{
continue; //如果在模型中找不到就跳过了
}
occurrences = entry2.getValue()[0]; //获取其在文档中的频次
logprob += occurrences * model.logLikelihoods.get(feature).get(category); //将对数似然乘上频次
}
predictionScores[category] = logprob;
}
if (configProbabilityEnabled) MathUtility.normalizeExp(predictionScores);
return predictionScores;
}
/**
* 统计特征并且执行特征选择,返回一个FeatureStats对象,用于计算模型中的概率
*
* @param dataSet
* @return
*/
protected BaseFeatureData selectFeatures(IDataSet dataSet)
{
ChiSquareFeatureExtractor chiSquareFeatureExtractor = new ChiSquareFeatureExtractor();
ConsoleLogger.logger.start("使用卡方检测选择特征中...");
//FeatureStats对象包含文档中所有特征及其统计信息
BaseFeatureData featureData = chiSquareFeatureExtractor.extractBasicFeatureData(dataSet); //执行统计 | //我们传入这些统计信息到特征选择算法中,得到特征与其分值
Map<Integer, Double> selectedFeatures = chiSquareFeatureExtractor.chi_square(featureData);
//从统计数据中删掉无用的特征并重建特征映射表
int[][] featureCategoryJointCount = new int[selectedFeatures.size()][];
featureData.wordIdTrie = new BinTrie<Integer>();
String[] wordIdArray = dataSet.getLexicon().getWordIdArray();
int p = -1;
for (Integer feature : selectedFeatures.keySet())
{
featureCategoryJointCount[++p] = featureData.featureCategoryJointCount[feature];
featureData.wordIdTrie.put(wordIdArray[feature], p);
}
ConsoleLogger.logger.finish(",选中特征数:%d / %d = %.2f%%\n", featureCategoryJointCount.length,
featureData.featureCategoryJointCount.length,
featureCategoryJointCount.length / (double)featureData.featureCategoryJointCount.length * 100.);
featureData.featureCategoryJointCount = featureCategoryJointCount;
return featureData;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\classifiers\NaiveBayesClassifier.java | 1 |
请完成以下Java代码 | public int size() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".size() is not supported.");
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".isEmpty() is not supported.");
}
@Override
public boolean containsKey(Object key) {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsKey() is not supported.");
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsValue() is not supported.");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException("ProcessVariableMap.remove is unsupported. Use ProcessVariableMap.put(key, null)");
}
@Override
public void clear() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".clear() is not supported.");
} | @Override
public Set<String> keySet() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".keySet() is not supported.");
}
@Override
public Collection<Object> values() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".values() is not supported.");
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".entrySet() is not supported.");
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\ProcessVariableMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPRODUCTDESCCODE(String value) {
this.productdesccode = value;
}
/**
* Gets the value of the productdesctext property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRODUCTDESCTEXT() {
return productdesctext;
}
/**
* Sets the value of the productdesctext property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRODUCTDESCTEXT(String value) {
this.productdesctext = value;
}
/**
* Gets the value of the productdesctype property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRODUCTDESCTYPE() {
return productdesctype;
}
/**
* Sets the value of the productdesctype property. | *
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRODUCTDESCTYPE(String value) {
this.productdesctype = value;
}
/**
* Gets the value of the productdesclang property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRODUCTDESCLANG() {
return productdesclang;
}
/**
* Sets the value of the productdesclang property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRODUCTDESCLANG(String value) {
this.productdesclang = 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\DPRDE1.java | 2 |
请完成以下Java代码 | public GetProcessDefinitionsPayload restrictProcessDefQuery(SecurityPolicyAccess securityPolicyAccess) {
return restrictQuery(processDefinitionRestrictionApplier, securityPolicyAccess);
}
private Set<String> definitionKeysAllowedForApplicationPolicy(SecurityPolicyAccess securityPolicyAccess) {
Map<String, Set<String>> restrictions = getAllowedKeys(securityPolicyAccess);
Set<String> keys = new HashSet<>();
for (String appName : restrictions.keySet()) {
//only take policies for this app
//or if we don't know our own appName (just being defensive) then include everything
//ignore hyphens and case due to values getting set via env vars
if (appName != null && appName.replace("-", "").equalsIgnoreCase(applicationName.replace("-", ""))) {
keys.addAll(restrictions.get(appName));
}
}
return keys;
}
public GetProcessInstancesPayload restrictProcessInstQuery(SecurityPolicyAccess securityPolicyAccess) {
return restrictQuery(processInstanceRestrictionApplier, securityPolicyAccess);
}
private <T> T restrictQuery(
SecurityPoliciesRestrictionApplier<T> restrictionApplier,
SecurityPolicyAccess securityPolicyAccess
) {
if (!arePoliciesDefined()) {
return restrictionApplier.allowAll();
}
Set<String> keys = definitionKeysAllowedForApplicationPolicy(securityPolicyAccess);
if (keys != null && !keys.isEmpty()) {
if (keys.contains(getSecurityPoliciesProperties().getWildcard())) {
return restrictionApplier.allowAll();
}
return restrictionApplier.restrictToKeys(keys);
}
//policies are in place but if we've got here then none for this user
if (!getSecurityPoliciesProperties().getPolicies().isEmpty()) {
return restrictionApplier.denyAll(); | }
return restrictionApplier.allowAll();
}
public boolean canWrite(String processDefinitionKey) {
return hasPermission(processDefinitionKey, SecurityPolicyAccess.WRITE, applicationName);
}
public boolean canRead(String processDefinitionKey) {
return (
hasPermission(processDefinitionKey, SecurityPolicyAccess.READ, applicationName) ||
hasPermission(processDefinitionKey, SecurityPolicyAccess.WRITE, applicationName)
);
}
protected boolean anEntryInSetStartsKey(Set<String> keys, String processDefinitionKey) {
for (String key : keys) {
//override the base class with exact matching as startsWith is only preferable for audit where id might be used that would start with key
if (processDefinitionKey.equalsIgnoreCase(key)) {
return true;
}
}
return false;
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-security-policies\src\main\java\org\activiti\core\common\spring\security\policies\ProcessSecurityPoliciesManagerImpl.java | 1 |
请完成以下Java代码 | protected String getModuleName(DeploymentUnit deploymentUnit) {
try {
// Try to get MODULE_IDENTIFIER first (for JBoss EAP 8 versions)
Field moduleIdentifierField = Attachments.class.getDeclaredField(MODULE_IDENTIFIER);
ModuleIdentifier identifier = deploymentUnit.getAttachment((AttachmentKey<ModuleIdentifier>) moduleIdentifierField.get(null));
return identifier.toString();
} catch (NoSuchFieldException | IllegalAccessException e) {
// Fallback to MODULE_NAME for newer WildFly versions
return deploymentUnit.getAttachment(Attachments.MODULE_NAME);
}
}
private void addSystemDependencies(ModuleLoader moduleLoader, final ModuleSpecification moduleSpecification) {
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_PROCESS_ENGINE);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_XML_MODEL);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_BPMN_MODEL);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_CMMN_MODEL);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_DMN_MODEL);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_SPIN); | addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_CONNECT);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_ENGINE_DMN);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_GRAAL_JS, true);
addSystemDependency(moduleLoader, moduleSpecification, MODULE_IDENTIFIER_JUEL, true);
}
private void addSystemDependency(ModuleLoader moduleLoader, final ModuleSpecification moduleSpecification, String identifier) {
addSystemDependency(moduleLoader, moduleSpecification, identifier, false);
}
private void addSystemDependency(ModuleLoader moduleLoader, final ModuleSpecification moduleSpecification, String identifier, boolean importServices) {
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, identifier, false, false, importServices, false));
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\deployment\processor\ModuleDependencyProcessor.java | 1 |
请完成以下Java代码 | public String[][] getEdgeArray()
{
String[][] edge = new String[word.length + 1][word.length + 1];
for (CoNLLWord coNLLWord : word)
{
edge[coNLLWord.ID][coNLLWord.HEAD.ID] = coNLLWord.DEPREL;
}
return edge;
}
/**
* 获取包含根节点在内的单词数组
* @return
*/
public CoNLLWord[] getWordArrayWithRoot()
{
CoNLLWord[] wordArray = new CoNLLWord[word.length + 1];
wordArray[0] = CoNLLWord.ROOT;
System.arraycopy(word, 0, wordArray, 1, word.length);
return wordArray;
}
public CoNLLWord[] getWordArray()
{
return word;
}
@Override
public Iterator<CoNLLWord> iterator()
{
return new Iterator<CoNLLWord>()
{
int index;
@Override
public boolean hasNext()
{
return index < word.length;
}
@Override
public CoNLLWord next()
{
return word[index++];
}
@Override
public void remove()
{
throw new UnsupportedOperationException("CoNLLSentence是只读对象,不允许删除");
} | };
}
/**
* 找出所有子节点
* @param word
* @return
*/
public List<CoNLLWord> findChildren(CoNLLWord word)
{
List<CoNLLWord> result = new LinkedList<CoNLLWord>();
for (CoNLLWord other : this)
{
if (other.HEAD == word)
result.add(other);
}
return result;
}
/**
* 找出特定依存关系的子节点
* @param word
* @param relation
* @return
*/
public List<CoNLLWord> findChildren(CoNLLWord word, String relation)
{
List<CoNLLWord> result = new LinkedList<CoNLLWord>();
for (CoNLLWord other : this)
{
if (other.HEAD == word && other.DEPREL.equals(relation))
result.add(other);
}
return result;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\CoNLLSentence.java | 1 |
请完成以下Java代码 | public void setRecord_ID(final int Record_ID)
{
if (Record_ID < 0)
{
set_Value(COLUMNNAME_Record_ID, null);
}
else
{
set_Value(COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
}
/**
* Get Datensatz-ID.
*
* @return Direct internal record ID
*/
@Override
public int getRecord_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/** | * Set Name der DB-Tabelle.
*
* @param TableName Name der DB-Tabelle
*/
@Override
public void setTableName(final java.lang.String TableName)
{
throw new IllegalArgumentException("TableName is virtual column");
}
/**
* Get Name der DB-Tabelle.
*
* @return Name der DB-Tabelle
*/
@Override
public java.lang.String getTableName()
{
return (java.lang.String)get_Value(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Workqueue.java | 1 |
请完成以下Java代码 | public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setQtyOnHandStock (final @Nullable BigDecimal QtyOnHandStock)
{
set_Value (COLUMNNAME_QtyOnHandStock, QtyOnHandStock);
}
@Override
public BigDecimal getQtyOnHandStock()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandStock);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped)
{
set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped);
}
@Override
public BigDecimal getQtyToBeShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setQueryNo (final int QueryNo)
{
set_Value (COLUMNNAME_QueryNo, QueryNo);
}
@Override
public int getQueryNo()
{
return get_ValueAsInt(COLUMNNAME_QueryNo);
}
@Override
public void setStorageAttributesKey (final @Nullable String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public String getStorageAttributesKey()
{
return get_ValueAsString(COLUMNNAME_StorageAttributesKey);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Available_For_Sales_QueryResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(@PathVariable Integer id) {
log.info("单个参数用 ApiImplicitParam");
}
@PostMapping
@ApiOperation(value = "添加用户(DONE)")
public User post(@RequestBody User user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PostMapping("/multipar")
@ApiOperation(value = "添加用户(DONE)")
public List<User> multipar(@RequestBody List<User> user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam");
return user;
}
@PostMapping("/array")
@ApiOperation(value = "添加用户(DONE)")
public User[] array(@RequestBody User[] user) {
log.info("如果是 POST PUT 这种带 @RequestBody 的可以不用写 @ApiImplicitParam"); | return user;
}
@PutMapping("/{id}")
@ApiOperation(value = "修改用户(DONE)")
public void put(@PathVariable Long id, @RequestBody User user) {
log.info("如果你不想写 @ApiImplicitParam 那么 swagger 也会使用默认的参数名作为描述信息 ");
}
@PostMapping("/{id}/file")
@ApiOperation(value = "文件上传(DONE)")
public String file(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
log.info(file.getContentType());
log.info(file.getName());
log.info(file.getOriginalFilename());
return file.getOriginalFilename();
}
} | repos\spring-boot-demo-master\demo-swagger\src\main\java\com\xkcoding\swagger\controller\UserController.java | 2 |
请完成以下Java代码 | public ArrayList<Node<T>> getUpStream()
{
Node<T> currentNode = this;
final ArrayList<Node<T>> upStream = new ArrayList<>();
upStream.add(currentNode);
while (currentNode.parent != null)
{
upStream.add(currentNode.parent);
currentNode = currentNode.parent;
}
return upStream;
}
/**
* Tries to found a node among the ones found below {@code this} on the same branch
* in the tree with {@code value} equal to the given one.
*
* e.g given the following tree:
* ----1----
* ---/-\---
* --2---3--
* --|---|--
* --4---5--
* /-|-\----
* 6-7-8----
*
* if {@code getNode(4)} it's called for node 1,
* it will return: Optional.of(Node(4)).
*/
@NonNull
public Optional<Node<T>> getNode(final T value)
{
return Optional.ofNullable(getNode_rec(this, value));
}
@NonNull
public String toString()
{
return this.getValue().toString();
}
@Nullable
private Node<T> getNode_rec(final Node<T> currentNode, final T value)
{
if (currentNode.value.equals(value))
{ | return currentNode;
}
else
{
final Iterator<Node<T>> iterator = currentNode.getChildren().iterator();
Node<T> requestedNode = null;
while (requestedNode == null && iterator.hasNext())
{
requestedNode = getNode_rec(iterator.next(), value);
}
return requestedNode;
}
}
private void listAllNodesBelow_rec(final Node<T> currentNode, final List<Node<T>> nodeList)
{
nodeList.add(currentNode);
if (!currentNode.isLeaf())
{
currentNode.getChildren().forEach(child -> listAllNodesBelow_rec(child, nodeList));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Node.java | 1 |
请完成以下Java代码 | public class WEBUI_M_HU_ReturnToVendor extends HUEditorProcessTemplate implements IProcessPrecondition
{
private final ReturnsServiceFacade returnsServiceFacade = SpringContextHolder.instance.getBean(ReturnsServiceFacade.class);
private List<I_M_HU> husToReturn = null;
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if(!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
if (!streamSelectedHUIds(Select.ONLY_TOPLEVEL).findAny().isPresent())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU));
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
husToReturn = streamSelectedHUs(Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList()); | if (husToReturn.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final Timestamp movementDate = Env.getDate(getCtx());
returnsServiceFacade.createVendorReturnInOutForHUs(husToReturn, movementDate);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (husToReturn != null && !husToReturn.isEmpty())
{
getView().removeHUsAndInvalidate(husToReturn);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnToVendor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMpsExpectedSendingTime() {
return mpsExpectedSendingTime;
}
/**
* Sets the value of the mpsExpectedSendingTime property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMpsExpectedSendingTime(String value) {
this.mpsExpectedSendingTime = value;
}
/**
* Gets the value of the sender property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getSender() {
return sender;
}
/**
* Sets the value of the sender property.
*
* @param value | * allowed object is
* {@link Address }
*
*/
public void setSender(Address value) {
this.sender = value;
}
/**
* Gets the value of the recipient property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getRecipient() {
return recipient;
}
/**
* Sets the value of the recipient property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setRecipient(Address value) {
this.recipient = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\GeneralShipmentData.java | 2 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_PP_WF_Node_Asset[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_A_Asset getA_Asset() throws RuntimeException
{
return (I_A_Asset)MTable.get(getCtx(), I_A_Asset.Table_Name)
.getPO(getA_Asset_ID(), get_TrxName()); }
/** Set Asset.
@param A_Asset_ID
Asset used internally or by customers
*/
public void setA_Asset_ID (int A_Asset_ID)
{
if (A_Asset_ID < 1)
set_Value (COLUMNNAME_A_Asset_ID, null);
else
set_Value (COLUMNNAME_A_Asset_ID, Integer.valueOf(A_Asset_ID));
}
/** Get Asset.
@return Asset used internally or by customers
*/
public int getA_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_WF_Node getAD_WF_Node() throws RuntimeException
{
return (I_AD_WF_Node)MTable.get(getCtx(), I_AD_WF_Node.Table_Name)
.getPO(getAD_WF_Node_ID(), get_TrxName()); }
/** Set Node.
@param AD_WF_Node_ID
Workflow Node (activity), step or process
*/
public void setAD_WF_Node_ID (int AD_WF_Node_ID)
{
if (AD_WF_Node_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Node_ID, Integer.valueOf(AD_WF_Node_ID));
}
/** Get Node.
@return Workflow Node (activity), step or process
*/
public int getAD_WF_Node_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Node_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workflow Node Asset.
@param PP_WF_Node_Asset_ID Workflow Node Asset */
public void setPP_WF_Node_Asset_ID (int PP_WF_Node_Asset_ID)
{
if (PP_WF_Node_Asset_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_WF_Node_Asset_ID, Integer.valueOf(PP_WF_Node_Asset_ID));
}
/** Get Workflow Node Asset.
@return Workflow Node Asset */
public int getPP_WF_Node_Asset_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_WF_Node_Asset_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_WF_Node_Asset.java | 1 |
请完成以下Java代码 | private static final int toID(final Object idObj)
{
if (idObj == null)
{
return -1;
}
else if (idObj instanceof Number)
{
return ((Number)idObj).intValue();
}
else
{
return -1;
}
}
private void doConvert(final String reason)
{
// Reset
setDescription(null);
setQtyConv(null);
final I_C_UOM uomFrom = getC_UOM();
final I_C_UOM uomTo = getC_UOM_To();
if (uomFrom == null || uomTo == null)
{
return;
}
final I_M_Product product = getM_Product();
final BigDecimal qty = getQty();
try
{
final BigDecimal qtyConv;
if (product != null)
{ | final UOMConversionContext conversionCtx = UOMConversionContext.of(product);
qtyConv = uomConversionBL.convertQty(conversionCtx, qty, uomFrom, uomTo);
}
else
{
qtyConv = uomConversionBL.convert(uomFrom, uomTo, qty).orElse(null);
}
setQtyConv(qtyConv);
setDescription("Converted "
+ NumberUtils.stripTrailingDecimalZeros(qty) + " " + uomFrom.getUOMSymbol()
+ " to "
+ NumberUtils.stripTrailingDecimalZeros(qtyConv) + " " + uomTo.getUOMSymbol()
+ "<br>Product: " + (product == null ? "-" : product.getName())
+ "<br>Reason: " + reason);
}
catch (final Exception e)
{
setDescription(e.getLocalizedMessage());
// because this is a test form, printing the exception directly to console it's totally fine.
// More, if we would log it as WARNING/SEVERE, an AD_Issue would be created, but we don't want that.
e.printStackTrace();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\uom\form\UOMConversionCheckFormPanel.java | 1 |
请完成以下Java代码 | public String getDescription() {
return (String) getProperty("documentation");
}
/**
* @return all lane-sets defined on this process-instance. Returns an empty list if none are defined.
*/
public List<LaneSet> getLaneSets() {
if(laneSets == null) {
laneSets = new ArrayList<LaneSet>();
}
return laneSets;
}
public void setParticipantProcess(ParticipantProcess participantProcess) {
this.participantProcess = participantProcess;
}
public ParticipantProcess getParticipantProcess() {
return participantProcess;
} | public boolean isScope() {
return true;
}
public PvmScope getEventScope() {
return null;
}
public ScopeImpl getFlowScope() {
return null;
}
public PvmScope getLevelOfSubprocessScope() {
return null;
}
@Override
public boolean isSubProcessScope() {
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ProcessDefinitionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object visitPrimitiveAsBoolean(PrimitiveType type, String value) {
return Boolean.parseBoolean(value);
}
@Override
public Object visitPrimitiveAsByte(PrimitiveType type, String value) {
return parseNumber(value, Byte::parseByte, type);
}
@Override
public Object visitPrimitiveAsShort(PrimitiveType type, String value) {
return parseNumber(value, Short::parseShort, type);
}
@Override
public Object visitPrimitiveAsInt(PrimitiveType type, String value) {
return parseNumber(value, Integer::parseInt, type);
}
@Override
public Object visitPrimitiveAsLong(PrimitiveType type, String value) {
return parseNumber(value, Long::parseLong, type);
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, String value) {
if (value.length() > 1) {
throw new IllegalArgumentException(String.format("Invalid character representation '%s'", value)); | }
return value;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, String value) {
return parseNumber(value, Float::parseFloat, type);
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, String value) {
return parseNumber(value, Double::parseDouble, type);
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ParameterPropertyDescriptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DictDto dictDTO : dictDtos) {
if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){
for (DictDetailDto dictDetail : dictDTO.getDictDetails()) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", dictDetail.getLabel());
map.put("字典值", dictDetail.getValue());
map.put("创建日期", dictDetail.getCreateTime());
list.add(map);
}
} else {
Map<String,Object> map = new LinkedHashMap<>(); | map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", null);
map.put("字典值", null);
map.put("创建日期", dictDTO.getCreateTime());
list.add(map);
}
}
FileUtil.downloadExcel(list, response);
}
public void delCaches(Dict dict){
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictServiceImpl.java | 2 |
请完成以下Java代码 | public static void addLoggingData(String type, ObjectNode data, String engineType) {
data.put(ID, idGenerator.getNextId());
data.put(TIMESTAMP, formatDate(new Date()));
data.put("type", type);
LoggingSession loggingSession = Context.getCommandContext().getSession(LoggingSession.class);
loggingSession.addLoggingData(type, data, engineType);
}
public static ObjectNode fillLoggingData(String message, String scopeId, String subScopeId, String scopeType,
String scopeDefinitionId, String elementId, String elementName, String elementType, String elementSubType, ObjectMapper objectMapper) {
ObjectNode loggingNode = fillLoggingData(message, scopeId, subScopeId, scopeType, objectMapper);
loggingNode.put("scopeDefinitionId", scopeDefinitionId);
if (StringUtils.isNotEmpty(elementId)) {
loggingNode.put("elementId", elementId);
}
if (StringUtils.isNotEmpty(elementName)) {
loggingNode.put("elementName", elementName);
}
if (StringUtils.isNotEmpty(elementType)) {
loggingNode.put("elementType", elementType);
}
if (StringUtils.isNotEmpty(elementSubType)) {
loggingNode.put("elementSubType", elementSubType);
}
return loggingNode;
}
public static ObjectNode fillLoggingData(String message, String scopeId, String subScopeId, String scopeType, ObjectMapper objectMapper) {
ObjectNode loggingNode = objectMapper.createObjectNode();
loggingNode.put("message", message);
loggingNode.put("scopeId", scopeId); | if (StringUtils.isNotEmpty(subScopeId)) {
loggingNode.put("subScopeId", subScopeId);
}
loggingNode.put("scopeType", scopeType);
return loggingNode;
}
public static String formatDate(Date date) {
if (date != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
dateFormat.setTimeZone(utcTimeZone);
return dateFormat.format(date);
}
return null;
}
public static String formatDate(DateTime date) {
if (date != null) {
return date.toString("yyyy-MM-dd'T'hh:mm:ss.sss'Z'");
}
return null;
}
public static String formatDate(LocalDate date) {
if (date != null) {
return date.toString("yyyy-MM-dd");
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSessionUtil.java | 1 |
请完成以下Spring Boot application配置 | spring:
ai:
anthropic:
api-key: ${ANTHROPIC_API_KEY}
chat:
options:
model: ${SECONDARY_LLM}
tertiary-model: ${TERTIARY_LLM}
open-ai:
api-key: ${OPENAI_API | _KEY}
chat:
options:
model: ${PRIMARY_LLM}
temperature: 1 | repos\tutorials-master\spring-ai-modules\spring-ai-multiple-llms\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public DOMSource getDomSource() {
return new DOMSource(document);
}
public String registerNamespace(String namespaceUri) {
synchronized(document) {
DomElement rootElement = getRootElement();
if (rootElement != null) {
return rootElement.registerNamespace(namespaceUri);
}
else {
throw new ModelException("Unable to define a new namespace without a root document element");
}
}
}
public void registerNamespace(String prefix, String namespaceUri) {
synchronized(document) {
DomElement rootElement = getRootElement();
if (rootElement != null) {
rootElement.registerNamespace(prefix, namespaceUri);
}
else {
throw new ModelException("Unable to define a new namespace without a root document element");
}
}
}
protected String getUnusedGenericNsPrefix() {
synchronized(document) {
Element documentElement = document.getDocumentElement();
if (documentElement == null) {
return GENERIC_NS_PREFIX + "0";
}
else {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (!documentElement.hasAttributeNS(XMLNS_ATTRIBUTE_NS_URI, GENERIC_NS_PREFIX + i)) {
return GENERIC_NS_PREFIX + i;
}
}
throw new ModelException("Unable to find an unused namespace prefix");
}
} | }
public DomDocument clone() {
synchronized(document) {
return new DomDocumentImpl((Document) document.cloneNode(true));
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DomDocumentImpl that = (DomDocumentImpl) o;
return document.equals(that.document);
}
public int hashCode() {
return document.hashCode();
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomDocumentImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("test-secret");
return converter;
}
/**
* 设置token 由Jwt产生,不使用默认的透明令牌
*/
@Bean
public JwtTokenStore jwtTokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenStore(jwtTokenStore())
.accessTokenConverter(accessTokenConverter()); | }
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientapp")
.secret("123")
.scopes("read")
//设置支持[密码模式、授权码模式、token刷新]
.authorizedGrantTypes(
"password",
"authorization_code",
"refresh_token");
}
} | repos\SpringBootLearning-master (1)\springboot-security-oauth2-jwt\jwt-authserver\src\main\java\com\gf\config\OAuth2AuthorizationServer.java | 2 |
请完成以下Java代码 | protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("X-Auth-Token", token);
headers.add("X-User-Id", userId);
return Mono.fromRunnable(() -> restTemplate.exchange(getUri(), HttpMethod.POST,
new HttpEntity<>(createMessage(event, instance), headers), Void.class));
}
private URI getUri() {
if (url == null) {
throw new IllegalStateException("'url' must not be null.");
}
return URI.create(String.format("%s/api/v1/chat.sendMessage", url));
}
protected Object createMessage(InstanceEvent event, Instance instance) {
Map<String, String> messageJsonData = new HashMap<>();
messageJsonData.put("rid", roomId);
messageJsonData.put("msg", createContent(event, instance));
Map<String, Object> messageJson = new HashMap<>();
messageJson.put("message", messageJsonData);
return messageJson;
}
@Override
protected Map<String, Object> buildContentModel(InstanceEvent event, Instance instance) {
var content = super.buildContentModel(event, instance);
content.put("roomId", roomId);
return content;
}
@Override
protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Nullable
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Nullable
public String getRoomId() {
return roomId;
} | public void setRoomId(String roomId) {
this.roomId = roomId;
}
@Nullable
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Nullable
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\RocketChatNotifier.java | 1 |
请完成以下Java代码 | public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
} | public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\CreateUserTaskBeforeContext.java | 1 |
请完成以下Java代码 | public class PrimitiveCollections {
public static void main(String[] args) {
int[] primitives = new int[] {5, 10, 0, 2, -8};
guavaPrimitives(primitives);
intStream(primitives);
TIntArrayList tList = new TIntArrayList(primitives);
cern.colt.list.IntArrayList coltList = new cern.colt.list.IntArrayList(primitives);
IntArrayList fastUtilList = new IntArrayList(primitives);
System.out.println(tList);
System.out.println(coltList);
System.out.println(fastUtilList);
}
private static void intStream(int[] primitives) { | IntStream stream = IntStream.of(5, 10, 0, 2, -8);
IntStream newStream = IntStream.of(primitives);
OptionalDouble average = stream.filter(i -> i > 0).average();
}
private static void guavaPrimitives(int[] primitives) {
ImmutableIntArray immutableIntArray = ImmutableIntArray.builder().addAll(primitives).build();
System.out.println(immutableIntArray);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-3\src\main\java\com\baeldung\list\primitive\PrimitiveCollections.java | 1 |
请完成以下Java代码 | public static class Result {
private final HandlerFunction<ServerResponse> handlerFunction;
private final List<HandlerFilterFunction<ServerResponse, ServerResponse>> lowerPrecedenceFilters;
private final List<HandlerFilterFunction<ServerResponse, ServerResponse>> higherPrecedenceFilters;
public Result(HandlerFunction<ServerResponse> handlerFunction,
List<HandlerFilterFunction<ServerResponse, ServerResponse>> lowerPrecedenceFilters,
List<HandlerFilterFunction<ServerResponse, ServerResponse>> higherPrecedenceFilters) {
this.handlerFunction = handlerFunction;
this.lowerPrecedenceFilters = Objects.requireNonNullElse(lowerPrecedenceFilters, Collections.emptyList());
this.higherPrecedenceFilters = Objects.requireNonNullElse(higherPrecedenceFilters, Collections.emptyList());
} | public HandlerFunction<ServerResponse> getHandlerFunction() {
return handlerFunction;
}
public List<HandlerFilterFunction<ServerResponse, ServerResponse>> getLowerPrecedenceFilters() {
return lowerPrecedenceFilters;
}
public List<HandlerFilterFunction<ServerResponse, ServerResponse>> getHigherPrecedenceFilters() {
return higherPrecedenceFilters;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\HandlerDiscoverer.java | 1 |
请完成以下Java代码 | public void setIsDefaultContact (final boolean IsDefaultContact)
{
set_Value (COLUMNNAME_IsDefaultContact, IsDefaultContact);
}
@Override
public boolean isDefaultContact()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefaultContact);
}
/**
* IsInvoiceEmailEnabled AD_Reference_ID=319
* Reference name: _YesNo
*/
public static final int ISINVOICEEMAILENABLED_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISINVOICEEMAILENABLED_Yes = "Y";
/** No = N */
public static final String ISINVOICEEMAILENABLED_No = "N";
@Override
public void setIsInvoiceEmailEnabled (final @Nullable java.lang.String IsInvoiceEmailEnabled)
{
set_Value (COLUMNNAME_IsInvoiceEmailEnabled, IsInvoiceEmailEnabled);
}
@Override
public java.lang.String getIsInvoiceEmailEnabled()
{
return get_ValueAsString(COLUMNNAME_IsInvoiceEmailEnabled);
}
@Override
public void setIsMembershipContact (final boolean IsMembershipContact)
{
set_Value (COLUMNNAME_IsMembershipContact, IsMembershipContact);
}
@Override
public boolean isMembershipContact()
{
return get_ValueAsBoolean(COLUMNNAME_IsMembershipContact);
}
@Override
public void setIsNewsletter (final boolean IsNewsletter)
{
set_Value (COLUMNNAME_IsNewsletter, IsNewsletter);
}
@Override
public boolean isNewsletter()
{
return get_ValueAsBoolean(COLUMNNAME_IsNewsletter);
}
@Override
public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override | public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java | 1 |
请完成以下Java代码 | private Map<String, String> resolveStatusCheckerNamesMapFromDubboHealthIndicatorProperties() {
DubboHealthIndicatorProperties.Status status =
dubboHealthIndicatorProperties.getStatus();
Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>();
for (String statusName : status.getDefaults()) {
statusCheckerNamesMap.put(statusName, DubboHealthIndicatorProperties.PREFIX + ".status.defaults");
}
for (String statusName : status.getExtras()) {
statusCheckerNamesMap.put(statusName, DubboHealthIndicatorProperties.PREFIX + ".status.extras");
}
return statusCheckerNamesMap;
}
private Map<String, String> resolveStatusCheckerNamesMapFromProtocolConfigs() {
Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>();
for (Map.Entry<String, ProtocolConfig> entry : protocolConfigs.entrySet()) {
String beanName = entry.getKey();
ProtocolConfig protocolConfig = entry.getValue();
Set<String> statusCheckerNames = getStatusCheckerNames(protocolConfig);
for (String statusCheckerName : statusCheckerNames) {
String source = buildSource(beanName, protocolConfig);
statusCheckerNamesMap.put(statusCheckerName, source);
}
}
return statusCheckerNamesMap;
}
private Map<String, String> resolveStatusCheckerNamesMapFromProviderConfig() { | Map<String, String> statusCheckerNamesMap = new LinkedHashMap<>();
for (Map.Entry<String, ProviderConfig> entry : providerConfigs.entrySet()) {
String beanName = entry.getKey();
ProviderConfig providerConfig = entry.getValue();
Set<String> statusCheckerNames = getStatusCheckerNames(providerConfig);
for (String statusCheckerName : statusCheckerNames) {
String source = buildSource(beanName, providerConfig);
statusCheckerNamesMap.put(statusCheckerName, source);
}
}
return statusCheckerNamesMap;
}
private Set<String> getStatusCheckerNames(ProtocolConfig protocolConfig) {
String status = protocolConfig.getStatus();
return StringUtils.commaDelimitedListToSet(status);
}
private Set<String> getStatusCheckerNames(ProviderConfig providerConfig) {
String status = providerConfig.getStatus();
return StringUtils.commaDelimitedListToSet(status);
}
private String buildSource(String beanName, Object bean) {
return beanName + "@" + bean.getClass().getSimpleName() + ".getStatus()";
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\health\DubboHealthIndicator.java | 1 |
请完成以下Java代码 | public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Column(name = "emailId", nullable = false)
public String getEmailId() { | return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public Employee(){}
public Employee(String firstName, String lastName, String emailId){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringRestDB\src\main\java\spring\restdb\model\Employee.java | 1 |
请完成以下Java代码 | public class MReference extends X_AD_Reference {
/**
*
*/
private static final long serialVersionUID = 3298182955450711914L;
public MReference(Properties ctx, int AD_Reference_ID, String trxName) {
super(ctx, AD_Reference_ID, trxName);
}
public MReference(Properties ctx, ResultSet rs, String trxName) {
super(ctx, rs, trxName);
}
/**
* @param ctx | * @param referenceId
* @param trxName
* @return MRefTable
* @deprecated Please consider using {@link ILookupDAO#retrieveTableRefInfo(int)}
*/
@Deprecated
public static I_AD_Ref_Table retrieveRefTable(final Properties ctx, final int referenceId, final String trxName)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Ref_Table.class, ctx, trxName)
.addEqualsFilter(I_AD_Ref_Table.COLUMNNAME_AD_Reference_ID, referenceId)
.create()
.firstOnly(I_AD_Ref_Table.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MReference.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Config {
private @Nullable String fromHeader;
private @Nullable String toHeader;
public @Nullable String getFromHeader() {
return this.fromHeader;
}
public Config setFromHeader(String fromHeader) {
this.fromHeader = fromHeader;
return this;
}
public @Nullable String getToHeader() {
return this.toHeader;
} | public Config setToHeader(String toHeader) {
this.toHeader = toHeader;
return this;
}
@Override
public String toString() {
// @formatter:off
return new ToStringCreator(this)
.append("fromHeader", fromHeader)
.append("toHeader", toHeader)
.toString();
// @formatter:on
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\MapRequestHeaderGatewayFilterFactory.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.