instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public int getCountTotalToRecompute()
{
return countTotalToRecompute;
}
public Set<String> getCurrencySymbols()
{
return currencySymbols;
}
@Override
public String toString()
{
return getSummaryMessage();
}
/**
* Keep in sync with {@link de.metas.ui.web.view.OrderCandidateViewHeaderPropertiesProvider#toViewHeaderProperties(de.metas.invoicecandidate.api.impl.InvoiceCandidatesAmtSelectionSummary)}
*/
public String getSummaryMessage()
{
final StringBuilder message = new StringBuilder();
message.append("@Netto@ (@ApprovalForInvoicing@): ");
final BigDecimal totalNetAmtApproved = getTotalNetAmtApproved();
message.append(getAmountFormatted(totalNetAmtApproved));
final BigDecimal huNetAmtApproved = getHUNetAmtApproved();
message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtApproved));
final BigDecimal cuNetAmtApproved = getCUNetAmtApproved();
message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtApproved));
message.append(" | @Netto@ (@NotApprovedForInvoicing@): ");
final BigDecimal totalNetAmtNotApproved = getTotalNetAmtNotApproved();
message.append(getAmountFormatted(totalNetAmtNotApproved));
final BigDecimal huNetAmtNotApproved = getHUNetAmtNotApproved();
message.append(" - ").append("Gebinde ").append(getAmountFormatted(huNetAmtNotApproved));
final BigDecimal cuNetAmtNotApproved = getCUNetAmtNotApproved();
message.append(" - ").append("Ware ").append(getAmountFormatted(cuNetAmtNotApproved)); | if (countTotalToRecompute > 0)
{
message.append(", @IsToRecompute@: ");
message.append(countTotalToRecompute);
}
return message.toString();
}
private String getAmountFormatted(final BigDecimal amt)
{
final DecimalFormat amountFormat = DisplayType.getNumberFormat(DisplayType.Amount);
final StringBuilder amountFormatted = new StringBuilder();
amountFormatted.append(amountFormat.format(amt));
final boolean isSameCurrency = currencySymbols.size() == 1;
String curSymbol = null;
if (isSameCurrency)
{
curSymbol = currencySymbols.iterator().next();
amountFormatted.append(curSymbol);
}
return amountFormatted.toString();
}
@Override
public String getSummaryMessageTranslated(final Properties ctx)
{
final String message = getSummaryMessage();
final String messageTrl = Services.get(IMsgBL.class).parseTranslation(ctx, message);
return messageTrl;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\invoicecandidate\ui\spi\impl\HUInvoiceCandidatesSelectionSummaryInfo.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set 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);
}
/** TokenType AD_Reference_ID=397 */
public static final int TOKENTYPE_AD_Reference_ID=397;
/** SQL Command = Q */
public static final String TOKENTYPE_SQLCommand = "Q";
/** Internal Link = I */
public static final String TOKENTYPE_InternalLink = "I";
/** External Link = E */
public static final String TOKENTYPE_ExternalLink = "E";
/** Style = S */
public static final String TOKENTYPE_Style = "S";
/** Set TokenType.
@param TokenType
Wiki Token Type
*/
public void setTokenType (String TokenType)
{ | set_Value (COLUMNNAME_TokenType, TokenType);
}
/** Get TokenType.
@return Wiki Token Type
*/
public String getTokenType ()
{
return (String)get_Value(COLUMNNAME_TokenType);
}
/** 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_CM_WikiToken.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Server start() {
if (!isStarted) {
server.bind(config.getPort());
isStarted = true;
}
return this;
}
public void awaitShutdown() {
if (isStarted) server.awaitShutdown();
}
public void shutdown() {
if (isStarted) server.shutdown();
}
private void configurePlugins(Configuration config, RestExpress server) {
configureMetrics(config, server);
new SwaggerPlugin()
.flag(Flags.Auth.PUBLIC_ROUTE)
.register(server);
new CacheControlPlugin()
.register(server);
new HyperExpressPlugin(Linkable.class)
.register(server);
new CorsHeaderPlugin("*")
.flag(PUBLIC_ROUTE)
.allowHeaders(CONTENT_TYPE, ACCEPT, AUTHORIZATION, REFERER, LOCATION)
.exposeHeaders(LOCATION)
.register(server);
}
private void configureMetrics(Configuration config, RestExpress server) {
MetricsConfig mc = config.getMetricsConfig();
if (mc.isEnabled()) {
MetricRegistry registry = new MetricRegistry();
new MetricsPlugin(registry)
.register(server);
if (mc.isGraphiteEnabled()) { | final Graphite graphite = new Graphite(new InetSocketAddress(mc.getGraphiteHost(), mc.getGraphitePort()));
final GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
.prefixedWith(mc.getPrefix())
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.build(graphite);
reporter.start(mc.getPublishSeconds(), TimeUnit.SECONDS);
} else {
LOG.warn("*** Graphite Metrics Publishing is Disabled ***");
}
} else {
LOG.warn("*** Metrics Generation is Disabled ***");
}
}
private void mapExceptions(RestExpress server) {
server
.mapException(ItemNotFoundException.class, NotFoundException.class)
.mapException(DuplicateItemException.class, ConflictException.class)
.mapException(ValidationException.class, BadRequestException.class)
.mapException(InvalidObjectIdException.class, BadRequestException.class);
}
} | repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\Server.java | 2 |
请完成以下Java代码 | public void setServerName(String serverName) {
this.serverName = serverName;
}
public void setPort(int port) {
this.port = port;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public void setServletPath(String servletPath) {
this.servletPath = servletPath;
}
public void setPathInfo(String pathInfo) {
this.pathInfo = pathInfo;
}
public void setQuery(String query) {
this.query = query;
}
public String getUrl() {
StringBuilder sb = new StringBuilder();
Assert.notNull(this.scheme, "scheme cannot be null");
Assert.notNull(this.serverName, "serverName cannot be null");
sb.append(this.scheme).append("://").append(this.serverName);
// Append the port number if it's not standard for the scheme
if (this.port != (this.scheme.equals("http") ? 80 : 443)) {
sb.append(":").append(this.port); | }
if (this.contextPath != null) {
sb.append(this.contextPath);
}
if (this.servletPath != null) {
sb.append(this.servletPath);
}
if (this.pathInfo != null) {
sb.append(this.pathInfo);
}
if (this.query != null) {
sb.append("?").append(this.query);
}
return sb.toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\RedirectUrlBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static void assertAuthorizedClientProviderIsNull(
OAuth2AuthorizedClientProvider authorizedClientProvider) {
if (authorizedClientProvider != null) {
// @formatter:off
throw new BeanInitializationException(String.format(
"Unable to create an %s bean. Expected one bean of type %s, but found multiple. " +
"Please consider defining only a single bean of this type, or define an %s bean yourself.",
OAuth2AuthorizedClientManager.class.getName(),
authorizedClientProvider.getClass().getName(),
OAuth2AuthorizedClientManager.class.getName()));
// @formatter:on
}
}
private <T> String[] getBeanNamesForType(Class<T> beanClass) { | return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, beanClass, true, true);
}
private <T> T getBeanOfType(ResolvableType resolvableType) {
ObjectProvider<T> objectProvider = this.beanFactory.getBeanProvider(resolvableType, true);
return objectProvider.getIfAvailable();
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\OAuth2ClientConfiguration.java | 2 |
请完成以下Java代码 | public class IOSpecification extends BaseElement {
protected List<DataSpec> dataInputs = new ArrayList<DataSpec>();
protected List<DataSpec> dataOutputs = new ArrayList<DataSpec>();
protected List<String> dataInputRefs = new ArrayList<String>();
protected List<String> dataOutputRefs = new ArrayList<String>();
public List<DataSpec> getDataInputs() {
return dataInputs;
}
public void setDataInputs(List<DataSpec> dataInputs) {
this.dataInputs = dataInputs;
}
public List<DataSpec> getDataOutputs() {
return dataOutputs;
}
public void setDataOutputs(List<DataSpec> dataOutputs) {
this.dataOutputs = dataOutputs;
}
public List<String> getDataInputRefs() {
return dataInputRefs;
}
public void setDataInputRefs(List<String> dataInputRefs) {
this.dataInputRefs = dataInputRefs;
}
public List<String> getDataOutputRefs() {
return dataOutputRefs;
} | public void setDataOutputRefs(List<String> dataOutputRefs) {
this.dataOutputRefs = dataOutputRefs;
}
public IOSpecification clone() {
IOSpecification clone = new IOSpecification();
clone.setValues(this);
return clone;
}
public void setValues(IOSpecification otherSpec) {
dataInputs = new ArrayList<DataSpec>();
if (otherSpec.getDataInputs() != null && !otherSpec.getDataInputs().isEmpty()) {
for (DataSpec dataSpec : otherSpec.getDataInputs()) {
dataInputs.add(dataSpec.clone());
}
}
dataOutputs = new ArrayList<DataSpec>();
if (otherSpec.getDataOutputs() != null && !otherSpec.getDataOutputs().isEmpty()) {
for (DataSpec dataSpec : otherSpec.getDataOutputs()) {
dataOutputs.add(dataSpec.clone());
}
}
dataInputRefs = new ArrayList<String>(otherSpec.getDataInputRefs());
dataOutputRefs = new ArrayList<String>(otherSpec.getDataOutputRefs());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\IOSpecification.java | 1 |
请完成以下Spring Boot application配置 | # 2.4之前的配置
#spring:
# profiles:
# active: "dev"
#
#---
#spring.profiles: "dev"
#spring.profiles.include: "dev-db,dev-mq"
#
#---
#spring.profiles: "dev-db"
#
#db: dev-db.didispace.com
#
#---
#spring.profiles: "dev-mq"
#
#mq: dev-mq.didispace.com
#
#---
#2.4之后的配置
# 默认激活dev配置
spring:
profiles:
active: "dev"
group:
"dev": "dev-db,dev-mq"
"prod": "prod-db,prod-mq"
---
spring:
config:
activate:
on-profile: "dev-db"
db: dev-db.didispace.com
---
spring:
config:
activate:
on-p | rofile: "dev-mq"
mq: dev-mq.didispace.com
---
spring:
config:
activate:
on-profile: "prod-db"
db: prod-db.didispace.com
---
spring:
config:
activate:
on-profile: "prod-mq"
mq: prod-mq.didispace.com | repos\SpringBoot-Learning-master\2.x\chapter1-3\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean) | return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceBatch.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getComment() {
return comment;
}
/**
* Sets the value of the comment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment(String value) {
this.comment = value;
}
/**
* The type of surcharge or reduction. May be used to aggregate surcharges and reductions into different categories.Gets the value of the classification property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the classification property.
* | * <p>
* For example, to add a new item, do as follows:
* <pre>
* getClassification().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ClassificationType }
*
*
*/
public List<ClassificationType> getClassification() {
if (classification == null) {
classification = new ArrayList<ClassificationType>();
}
return this.classification;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ReductionAndSurchargeBaseType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CacheManagerCustomizer<ConcurrentMapCacheManager> activitiSpringSimpleCacheManagerCustomizer(
ActivitiSpringCacheManagerProperties properties
) {
return cacheManager -> {
List<String> cacheNames = new ArrayList<>();
var cacheProperties = properties.getSimple();
cacheManager.setAllowNullValues(cacheProperties.isAllowNullValues());
properties
.getCaches()
.entrySet()
.stream()
.filter(it -> it.getValue().isEnabled())
.map(Map.Entry::getKey)
.forEach(cacheNames::add);
cacheManager.setCacheNames(cacheNames);
};
}
@Bean
@ConditionalOnClass(CaffeineCacheManager.class)
@ConditionalOnProperty(value = "activiti.spring.cache-manager.provider", havingValue = "caffeine")
public CacheManagerCustomizer<CaffeineCacheManager> activitiSpringCaffeineCacheManagerCustomizer(
ActivitiSpringCacheManagerProperties properties,
ObjectProvider<ActivitiSpringCaffeineCacheConfigurer> cacheConfigurers
) {
return cacheManager -> {
var caffeineCacheProperties = properties.getCaffeine();
cacheManager.setCaffeineSpec(CaffeineSpec.parse(caffeineCacheProperties.getDefaultSpec())); | cacheManager.setAllowNullValues(caffeineCacheProperties.isAllowNullValues());
properties
.getCaches()
.entrySet()
.stream()
.filter(it -> it.getValue().isEnabled())
.forEach(cacheEntry -> {
Optional.ofNullable(cacheEntry.getValue())
.map(ActivitiSpringCacheManagerProperties.ActivitiCacheProperties::getCaffeine)
.map(CacheProperties.Caffeine::getSpec)
.or(() -> Optional.ofNullable(properties.getCaffeine().getDefaultSpec()))
.map(CaffeineSpec::parse)
.map(Caffeine::from)
.ifPresent(caffeine -> {
if (caffeineCacheProperties.isUseSystemScheduler()) {
caffeine.scheduler(Scheduler.systemScheduler());
}
var cache = cacheConfigurers
.orderedStream()
.filter(configurer -> configurer.test(cacheEntry.getKey()))
.findFirst()
.map(configurer -> configurer.apply(caffeine))
.orElseGet(caffeine::build);
cacheManager.registerCustomCache(cacheEntry.getKey(), cache);
});
});
};
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-cache-manager\src\main\java\org\activiti\spring\cache\config\ActivitiSpringCacheManagerAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private Predicate<AbstractUserDashboardInfo> filterById(UUID id) {
return d -> id.equals(d.getId());
}
private UserDashboardsInfo refreshDashboardTitles(TenantId tenantId, UserDashboardsInfo stored) {
if (stored == null) {
return UserDashboardsInfo.EMPTY;
}
stored.getLast().forEach(i -> i.setTitle(null));
stored.getStarred().forEach(i -> i.setTitle(null));
Set<UUID> uniqueIds = new HashSet<>();
stored.getLast().stream().map(AbstractUserDashboardInfo::getId).forEach(uniqueIds::add);
stored.getStarred().stream().map(AbstractUserDashboardInfo::getId).forEach(uniqueIds::add);
Map<UUID, String> dashboardTitles = new HashMap<>(); | uniqueIds.forEach(id -> {
var title = dashboardService.findDashboardTitleById(tenantId, new DashboardId(id));
if (StringUtils.isNotEmpty(title)) {
dashboardTitles.put(id, title);
}
}
);
stored.getLast().forEach(i -> i.setTitle(dashboardTitles.get(i.getId())));
stored.getLast().removeIf(EMPTY_TITLE);
stored.getStarred().forEach(i -> i.setTitle(dashboardTitles.get(i.getId())));
stored.getStarred().removeIf(EMPTY_TITLE);
return stored;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\user\DefaultTbUserSettingsService.java | 2 |
请完成以下Java代码 | private String getSearchStringSQL(final String searchInput, final int caretPosition)
{
final String search;
if (caretPosition > 0 && caretPosition < searchInput.length())
{
search = new StringBuilder(searchInput).insert(caretPosition, "%").toString();
}
else
{
search = searchInput;
}
// Note: as we use the query builder to make the SQL there is no need to prepend and append the '%'
return search;
}
/**
* Creates and returns a {@link KeyNamePair} with the given ResultSet's C_ValidCombination_ID and the result of
* {@link MAccountLookup#getDisplay(org.adempiere.ad.validationRule.IValidationContext, Object)}.
*/
@Override
protected Object fetchUserObject(final ResultSet rs) throws SQLException
{
final int id = rs.getInt(I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID);
final KeyNamePair item = KeyNamePair.of(id, accountLookup.getDisplay(null, id));
return item; | }
/**
* Calls {@link FieldAutoCompleter#setUserObject(Object)}, then calls {@link VAccount#setValue(Object)} for set the given <code>userObject</code> into our <code>VEditor</code>.
*/
@Override
public void setUserObject(final Object userObject)
{
super.setUserObject(userObject);
if (userObject != null)
{
final KeyNamePair keyNamePair = (KeyNamePair)userObject; // it's always a KeyNamePair, see fetchUserObject
editor.setValue(keyNamePair.getID());
}
else
{
editor.setValue(null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VAccountAutoCompleter.java | 1 |
请完成以下Java代码 | public boolean isEmpty()
{
return orderBys.isEmpty();
}
public DocumentQueryOrderByList toDocumentQueryOrderByList()
{
return orderBys;
}
public ViewRowsOrderBy withOrderBys(final DocumentQueryOrderByList orderBys)
{
if (DocumentQueryOrderByList.equals(this.orderBys, orderBys))
{
return this;
} | else
{
return new ViewRowsOrderBy(orderBys, jsonOpts);
}
}
public <T extends IViewRow> Comparator<T> toComparator()
{
return orderBys.toComparator(IViewRow::getFieldValueAsComparable, jsonOpts);
}
public <T extends IViewRow> Comparator<T> toComparatorOrNull()
{
return !orderBys.isEmpty() ? toComparator() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowsOrderBy.java | 1 |
请完成以下Java代码 | public class UpdateEmployee {
protected int arg0;
protected String arg1;
/**
* Gets the value of the arg0 property.
*
*/
public int getArg0() {
return arg0;
}
/**
* Sets the value of the arg0 property.
*
*/
public void setArg0(int value) {
this.arg0 = value;
}
/**
* Gets the value of the arg1 property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getArg1() {
return arg1;
}
/**
* Sets the value of the arg1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArg1(String value) {
this.arg1 = value;
}
} | repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\UpdateEmployee.java | 1 |
请完成以下Java代码 | private DDOrderCandidateProcessRequest getProcessRequest(@NonNull final UserId userId)
{
final DDOrderCandidateEnqueueRequest enqueueRequest = DDOrderCandidateEnqueueService.extractRequest(getParameters());
final PInstanceId selectionId = enqueueRequest.getSelectionId();
final List<DDOrderCandidate> candidates = ddOrderCandidateService.getBySelectionId(selectionId);
logCandidatesToProcess(candidates, selectionId);
return DDOrderCandidateProcessRequest.builder()
.userId(userId)
.candidates(candidates)
.build();
}
/** | * There is a weird problem when running this remotely via a cucumber-test..
*/
private static void logCandidatesToProcess(@NonNull final List<DDOrderCandidate> candidates, @NonNull final PInstanceId selectionId)
{
final List<String> ids = new ArrayList<>();
for (int i = 0; i < candidates.size() && i < 10; i++)
{
ids.add(Integer.toString(candidates.get(i).getIdNotNull().getRepoId()));
}
Loggables.withLogger(logger, Level.INFO)
.addLog("Retrieved {} DDOrderCandidates for SelectionId={}; The first (max 10) selection IDs are: {}",
candidates.size(), selectionId, String.join(",", ids));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\async\GenerateDDOrderFromDDOrderCandidate.java | 1 |
请完成以下Java代码 | public class RelatedInvoicesForOrdersProvider implements RelatedRecordsProvider
{
@Override
public SourceRecordsKey getSourceRecordsKey()
{
return SourceRecordsKey.of(I_C_Order.Table_Name);
}
@Override
public IPair<SourceRecordsKey, List<ITableRecordReference>> provideRelatedRecords(
@NonNull final List<ITableRecordReference> records)
{
final ImmutableList<OrderId> orderIds = records
.stream()
.map(ref -> OrderId.ofRepoId(ref.getRecord_ID()))
.collect(ImmutableList.toImmutableList());
final ImmutableList<ITableRecordReference> invoiceReferences = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_C_OrderLine.COLUMN_C_Order_ID, orderIds)
.andCollectChildren(I_C_InvoiceLine.COLUMN_C_OrderLine_ID)
.addOnlyActiveRecordsFilter() | .andCollect(I_C_InvoiceLine.COLUMN_C_Invoice_ID)
.addOnlyActiveRecordsFilter()
.create()
.listIds()
.stream()
.distinct()
.map(invoiceRepoId -> TableRecordReference.of(I_C_Invoice.Table_Name, invoiceRepoId))
.collect(ImmutableList.toImmutableList());
final SourceRecordsKey sourceRecordsKey = SourceRecordsKey.of(I_C_Invoice.Table_Name);
final IPair<SourceRecordsKey, List<ITableRecordReference>> result = ImmutablePair.of(sourceRecordsKey, invoiceReferences);
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\order\restart\RelatedInvoicesForOrdersProvider.java | 1 |
请完成以下Java代码 | public class InventoryLineAggregatorFactory
{
public static InventoryLineAggregator getForDocBaseAndSubType(@NonNull final DocBaseAndSubType docBaseAndSubType)
{
final AggregationType aggregationMode = AggregationType.getByDocTypeOrNull(docBaseAndSubType);
Check.assumeNotNull(aggregationMode, "Unexpected docBaseAndSubType={} with no registered aggregationMode", docBaseAndSubType);
try
{
return getForAggregationMode(aggregationMode);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("docBaseAndSubType", docBaseAndSubType)
.appendParametersToMessage();
}
} | public static InventoryLineAggregator getForAggregationMode(@NonNull final AggregationType aggregationMode)
{
switch (aggregationMode)
{
case SINGLE_HU:
return SingleHUInventoryLineAggregator.INSTANCE;
case MULTIPLE_HUS:
return MultipleHUInventoryLineAggregator.INSTANCE;
default:
throw new AdempiereException("Unexpected aggregationMode: " + aggregationMode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\aggregator\InventoryLineAggregatorFactory.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Interest Area.
@param R_InterestArea_ID
Interest Area or Topic
*/
public void setR_InterestArea_ID (int R_InterestArea_ID)
{
if (R_InterestArea_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID));
}
/** Get Interest Area.
@return Interest Area or Topic
*/
public int getR_InterestArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID);
if (ii == null) | return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_InterestArea.java | 1 |
请完成以下Java代码 | public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public boolean equals(Object obj) { | if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootNamedEntityGraphBasicAttrs\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public final class SimpleDateFormatThreadLocal implements Serializable
{
private final String pattern;
private final transient ThreadLocal<SimpleDateFormat> dateFormatHolder = new ThreadLocal<>();
/**
*
* @param pattern {@link SimpleDateFormat}'s pattern
*/
public SimpleDateFormatThreadLocal(final String pattern)
{
Check.assumeNotEmpty(pattern, "pattern not empty");
this.pattern = pattern;
// we are calling this method just to eagerly validate the pattern
getDateFormatInternal();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("pattern", pattern)
.toString();
}
public SimpleDateFormat getDateFormat()
{
return (SimpleDateFormat)getDateFormatInternal().clone();
}
private SimpleDateFormat getDateFormatInternal()
{
SimpleDateFormat dateFormat = dateFormatHolder.get();
if(dateFormat == null)
{
dateFormat = new SimpleDateFormat(pattern);
dateFormatHolder.set(dateFormat);
}
return dateFormat;
}
/** | * @see SimpleDateFormat#format(Date)
*/
public String format(final Date date)
{
return getDateFormatInternal().format(date);
}
/**
* @see SimpleDateFormat#format(Object)
*/
public Object format(final Object value)
{
return getDateFormatInternal().format(value);
}
/**
* @see SimpleDateFormat#parse(String)
*/
public Date parse(final String source) throws ParseException
{
return getDateFormatInternal().parse(source);
}
/**
* @see SimpleDateFormat#parseObject(String)
*/
public Object parseObject(final String source) throws ParseException
{
return getDateFormatInternal().parseObject(source);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\SimpleDateFormatThreadLocal.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Project_Label_ID (final int C_Project_Label_ID)
{
if (C_Project_Label_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Project_Label_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Project_Label_ID, C_Project_Label_ID);
}
@Override
public int getC_Project_Label_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_Label_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | @Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Label.java | 1 |
请完成以下Java代码 | public class NonGreedyAlgorithm {
int currentLevel = 0;
final int maxLevel = 3;
SocialConnector tc;
public NonGreedyAlgorithm(SocialConnector tc, int level) {
super();
this.tc = tc;
this.currentLevel = level;
}
public long findMostFollowersPath(String account) {
List<SocialUser> followers = tc.getFollowers(account);
long total = currentLevel > 0 ? followers.size() : 0;
if (currentLevel < maxLevel ) {
currentLevel++;
long[] count = new long[followers.size()];
int i = 0;
for (SocialUser el : followers) { | NonGreedyAlgorithm sub = new NonGreedyAlgorithm(tc, currentLevel);
count[i] = sub.findMostFollowersPath(el.getUsername());
i++;
}
long max = 0;
for (; i > 0; i--) {
if (count[i-1] > max )
max = count[i-1];
}
return total + max;
}
return total;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\greedy\NonGreedyAlgorithm.java | 1 |
请完成以下Java代码 | public void stringBasedSolution(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void logarithmicApproach(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void repeatedMultiplication(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS) | public void shiftOperators(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void dividingWithPowersOf2(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void divideAndConquer(ExecutionPlan plan) {
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
}
} | repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\numberofdigits\Benchmarking.java | 1 |
请完成以下Java代码 | public int getC_Print_Job_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_ID);
}
@Override
public void setc_print_job_name (java.lang.String c_print_job_name)
{
set_Value (COLUMNNAME_c_print_job_name, c_print_job_name);
}
@Override
public java.lang.String getc_print_job_name()
{
return (java.lang.String)get_Value(COLUMNNAME_c_print_job_name);
}
@Override
public void setdocument (java.lang.String document)
{
set_Value (COLUMNNAME_document, document);
}
@Override
public java.lang.String getdocument()
{
return (java.lang.String)get_Value(COLUMNNAME_document);
}
@Override
public void setDocumentNo (java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return (java.lang.String)get_Value(COLUMNNAME_DocumentNo);
}
@Override
public void setFirstname (java.lang.String Firstname)
{
set_Value (COLUMNNAME_Firstname, Firstname);
}
@Override
public java.lang.String getFirstname()
{
return (java.lang.String)get_Value(COLUMNNAME_Firstname); | }
@Override
public void setGrandTotal (java.math.BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
@Override
public java.math.BigDecimal getGrandTotal()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_GrandTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setLastname (java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return (java.lang.String)get_Value(COLUMNNAME_Lastname);
}
@Override
public void setprintjob (java.lang.String printjob)
{
set_Value (COLUMNNAME_printjob, printjob);
}
@Override
public java.lang.String getprintjob()
{
return (java.lang.String)get_Value(COLUMNNAME_printjob);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_RV_Printing_Bericht_List_Per_Print_Job.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Persons updateUser(@PathVariable Long id, @RequestBody Persons data) {
/*
* @api {PUT} /api/persons/detail/:id update person info
* @apiName PutPersonDetails
* @apiGroup Info Manage
* @apiVersion 1.0.0
*
* @apiParam {String} phone
* @apiParam {String} zone
*
* @apiSuccess {String} create_datetime
* @apiSuccess {String} email
* @apiSuccess {String} id
* @apiSuccess {String} phone | * @apiSuccess {String} sex
* @apiSuccess {String} username
* @apiSuccess {String} zone
*/
Persons user = personsRepository.findById(id);
user.setPhone(data.getPhone());
user.setZone(data.getZone());
return personsRepository.save(user);
}
} | repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\controller\MainController.java | 2 |
请完成以下Java代码 | public class VariableResponseProvider {
public Response getResponseForTypedVariable(TypedValue typedVariableValue, String id) {
if (typedVariableValue instanceof BytesValue || ValueType.BYTES.equals(typedVariableValue.getType())) {
return responseForByteVariable(typedVariableValue);
} else if (ValueType.FILE.equals(typedVariableValue.getType())) {
return responseForFileVariable((FileValue) typedVariableValue);
} else {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, String.format("Value of variable with id %s is not a binary value.", id));
}
}
/**
* Creates a response for a variable of type {@link ValueType#FILE}.
*/
protected Response responseForFileVariable(FileValue fileValue) {
String type = fileValue.getMimeType() != null ? fileValue.getMimeType() : MediaType.APPLICATION_OCTET_STREAM;
if (fileValue.getEncoding() != null) {
type += "; charset=" + fileValue.getEncoding();
} | Object value = fileValue.getValue() == null ? "" : fileValue.getValue();
return Response.ok(value, type).header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileValue.getFilename())).build();
}
/**
* Creates a response for a variable of type {@link ValueType#BYTES}.
*/
protected Response responseForByteVariable(TypedValue variableInstance) {
byte[] valueBytes = (byte[]) variableInstance.getValue();
if (valueBytes == null) {
valueBytes = new byte[0];
}
return Response.ok(new ByteArrayInputStream(valueBytes), MediaType.APPLICATION_OCTET_STREAM).build();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\impl\VariableResponseProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static Saml2X509Credential getSaml2SigningCredential(String privateKeyLocation,
String certificateLocation) {
return getSaml2Credential(privateKeyLocation, certificateLocation,
Saml2X509Credential.Saml2X509CredentialType.SIGNING);
}
private static Saml2X509Credential getSaml2DecryptionCredential(String privateKeyLocation,
String certificateLocation) {
return getSaml2Credential(privateKeyLocation, certificateLocation,
Saml2X509Credential.Saml2X509CredentialType.DECRYPTION);
}
private static Saml2X509Credential getSaml2Credential(String privateKeyLocation, String certificateLocation,
Saml2X509Credential.Saml2X509CredentialType credentialType) {
RSAPrivateKey privateKey = readPrivateKey(privateKeyLocation);
X509Certificate certificate = readCertificate(certificateLocation);
return new Saml2X509Credential(privateKey, certificate, credentialType);
}
private static Saml2X509Credential getSaml2Credential(String certificateLocation,
Saml2X509Credential.Saml2X509CredentialType credentialType) {
X509Certificate certificate = readCertificate(certificateLocation);
return new Saml2X509Credential(certificate, credentialType);
}
private static RSAPrivateKey readPrivateKey(String privateKeyLocation) { | Resource privateKey = resourceLoader.getResource(privateKeyLocation);
try (InputStream inputStream = privateKey.getInputStream()) {
return RsaKeyConverters.pkcs8().convert(inputStream);
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private static X509Certificate readCertificate(String certificateLocation) {
Resource certificate = resourceLoader.getResource(certificateLocation);
try (InputStream inputStream = certificate.getInputStream()) {
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inputStream);
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private static String resolveAttribute(ParserContext pc, String value) {
return pc.getReaderContext().getEnvironment().resolvePlaceholders(value);
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\saml2\RelyingPartyRegistrationsBeanDefinitionParser.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void process(final Exchange exchange) throws Exception
{
final ImportProductsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_PRODUCTS_CONTEXT, ImportProductsRouteContext.class);
final JsonProduct productParent = context.getParentJsonProduct();
final JsonProduct product = context.getJsonProduct();
if (productParent == null)
{
exchange.getIn().setBody(null);
return;
}
// merge missing details to variant.
final JsonProduct mergedProduct = new JsonProduct(
product.getId(),
product.getParentId(),
Optional.ofNullable(product.getName()).orElse(productParent.getName()),
product.getProductNumber(),
Optional.ofNullable(product.getEan()).orElse(productParent.getEan()),
Optional.ofNullable(product.getUnitId()).orElse(productParent.getUnitId()),
Optional.ofNullable(product.getJsonTax()).orElse(productParent.getJsonTax()),
product.getCreatedAt(),
product.getUpdatedAt(),
Optional.ofNullable(product.getPrices()).orElse(productParent.getPrices())
);
context.setJsonProduct(mergedProduct); | //currently, this code is duplicated -> refactor, if solution is permanent or replace with variant specific upsert.
final ProductUpsertRequestProducer productUpsertRequestProducer = ProductUpsertRequestProducer.builder()
.product(mergedProduct)
.routeContext(context)
.processLogger(processLogger)
.build();
final JsonRequestProductUpsert productRequestProducerResult = productUpsertRequestProducer.run();
if (productRequestProducerResult.getRequestItems().isEmpty())
{
exchange.getIn().setBody(null);
return;
}
final ProductUpsertCamelRequest productUpsertCamelRequest = ProductUpsertCamelRequest.builder()
.jsonRequestProductUpsert(productRequestProducerResult)
.orgCode(context.getOrgCode())
.build();
exchange.getIn().setBody(productUpsertCamelRequest);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\processor\ProductVariantUpsertProcessor.java | 2 |
请完成以下Java代码 | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLoginTime() {
return loginTime; | }
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", icon=").append(icon);
sb.append(", email=").append(email);
sb.append(", nickName=").append(nickName);
sb.append(", note=").append(note);
sb.append(", createTime=").append(createTime);
sb.append(", loginTime=").append(loginTime);
sb.append(", status=").append(status);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdmin.java | 1 |
请完成以下Java代码 | public void setQtyToMove (final @Nullable BigDecimal QtyToMove)
{
set_ValueNoCheck (COLUMNNAME_QtyToMove, QtyToMove);
}
@Override
public BigDecimal getQtyToMove()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToMove);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToProduce (final @Nullable BigDecimal QtyToProduce)
{
set_ValueNoCheck (COLUMNNAME_QtyToProduce, QtyToProduce);
}
@Override
public BigDecimal getQtyToProduce()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToProduce); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyUnconfirmedBySupplier (final @Nullable BigDecimal QtyUnconfirmedBySupplier)
{
set_ValueNoCheck (COLUMNNAME_QtyUnconfirmedBySupplier, QtyUnconfirmedBySupplier);
}
@Override
public BigDecimal getQtyUnconfirmedBySupplier()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUnconfirmedBySupplier);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_QtyDemand_QtySupply_V.java | 1 |
请完成以下Java代码 | public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set DocumentLinesNumber.
@param DocumentLinesNumber DocumentLinesNumber */
@Override
public void setDocumentLinesNumber (int DocumentLinesNumber)
{
set_Value (COLUMNNAME_DocumentLinesNumber, Integer.valueOf(DocumentLinesNumber));
}
/** Get DocumentLinesNumber.
@return DocumentLinesNumber */
@Override
public int getDocumentLinesNumber ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DocumentLinesNumber);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Abgabemeldung Konfiguration.
@param M_Shipment_Declaration_Config_ID Abgabemeldung Konfiguration */
@Override
public void setM_Shipment_Declaration_Config_ID (int M_Shipment_Declaration_Config_ID)
{
if (M_Shipment_Declaration_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, Integer.valueOf(M_Shipment_Declaration_Config_ID));
} | /** Get Abgabemeldung Konfiguration.
@return Abgabemeldung Konfiguration */
@Override
public int getM_Shipment_Declaration_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void deleteUser(String login) {
userRepository.findOneByLogin(login).ifPresent(user -> {
userRepository.delete(user);
log.debug("Deleted User: {}", user);
});
}
public void changePassword(String currentClearTextPassword, String newPassword) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities(Long id) {
return userRepository.findOneWithAuthoritiesById(id);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p> | * This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
});
}
/**
* @return a list of all the authorities
*/
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\UserService.java | 2 |
请完成以下Spring Boot application配置 | # --------------------------------------------------------------------------------
# HTTP server (tomcat)
# --------------------------------------------------------------------------------
server.port=8082
# --------------------------------------------------------------------------------
# Datasource
# --------------------------------------------------------------------------------
#spring.datasource.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE
#spring.datasource.username=sa
#spring.datasource.password=
spring.datasource.url=jdbc:postgresql://localhost/mfprocurement
spring.datasource.username=metasfresh
spring.datasource.password=metasfresh
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# --------------------------------------------------------------------------------
# RabbitMQ
# --------------------------------------------------------------------------------
# The settings for the broker to which this application connects in order to sync with metasfresh
spring.rabbitmq.host=localhost
# spring.rabbitmq.host=192.168.99.100 # note: 192.168.99.100 is probably the correct IP if it runs in minikube on your local virtualbox
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
# --------------------------------------------------------------------------------
# Email
# --------------------------------------------------------------------------------
spring.mail.host=localhost
spring.mail.port=25
mfprocurement.mail.from=recovery@metasfresh.com
mfprocurement.passwordResetUrl=http://localhost/resetPassword
#mfprocurement.sync.mocked=true
# --------------------------------------------------------------------------------
# Logging
# --------------------------------------------------------------------------------
# Location of the log file. For instance `/var/log`
# logging.path=./log/
# Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.config=classpath:logback-spring.xml
# - Debug transactions
#logging.level.org.springframework.transaction=TRACE
#logging.level.org.springframework.orm.jpa=DEBUG
#logging.level.org.springframework.jdbc=TRACE
# All application loggers
logging.level.de.metas.procurement.webui=DEBUG
#
# - Others
# ....
# --------------------------------------------------------------------------------
# Logo
# ------------------------------------------------------------------------------- | -
# Path to logo file (optional)
#mfprocurement.logo.file=
# PoweredBy Logo URL (optional). If not specified, the default powered-by logo will be used (FRESH-79)
#mfprocurement.poweredby.url=
# PoweredBy Logo link URL (optional). If specified, the image will be clickable and will open a new browser window pointing to this url.
# mfprocurement.poweredby.link.url=https://metasfresh.com/?utm_content=procurementLogin&utm_medium=app&utm_source=insert_webui_hostname_here&utm_campaign=procurement
# --------------------------------------------------------------------------------
# "/metasfreshSync" password
# --------------------------------------------------------------------------------
mfprocurement.metasfreshSync.apiKey=m3t4s
# --------------------------------------------------------------------------------
# REST ERROR handling
# --------------------------------------------------------------------------------
server.error.include-message=always
server.error.include-exception=true
server.error.include-stacktrace=always
server.error.include-binding-errors=always | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public String getBICOrBEI() {
return bicOrBEI;
}
/**
* Sets the value of the bicOrBEI property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBICOrBEI(String value) {
this.bicOrBEI = value;
}
/**
* Gets the value of the othr property.
*
* @return
* possible object is
* {@link GenericOrganisationIdentification1 }
*
*/ | public GenericOrganisationIdentification1 getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link GenericOrganisationIdentification1 }
*
*/
public void setOthr(GenericOrganisationIdentification1 value) {
this.othr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\OrganisationIdentification4CH.java | 1 |
请完成以下Java代码 | public static Result editOne(String desformCode, JSONObject formData, String token) {
return addOrEditOne(desformCode, formData, token, HttpMethod.PUT);
}
private static Result addOrEditOne(String desformCode, JSONObject formData, String token, HttpMethod method) {
String url = getBaseUrl(desformCode).toString();
HttpHeaders headers = getHeaders(token);
ResponseEntity<JSONObject> result = RestUtil.request(url, method, headers, null, formData, JSONObject.class);
return packageReturn(result);
}
/**
* 删除数据
*
* @param desformCode
* @param dataId
* @param token
* @return
*/
public static Result removeOne(String desformCode, String dataId, String token) {
String url = getBaseUrl(desformCode, dataId).toString();
HttpHeaders headers = getHeaders(token);
ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.DELETE, headers, null, null, JSONObject.class);
return packageReturn(result);
}
private static Result packageReturn(ResponseEntity<JSONObject> result) {
if (result.getBody() != null) {
return result.getBody().toJavaObject(Result.class);
}
return Result.error("操作失败");
} | private static StringBuilder getBaseUrl() {
StringBuilder builder = new StringBuilder(domain).append(path);
builder.append("/desform/api");
return builder;
}
private static StringBuilder getBaseUrl(String desformCode, String dataId) {
StringBuilder builder = getBaseUrl();
builder.append("/").append(desformCode);
if (dataId != null) {
builder.append("/").append(dataId);
}
return builder;
}
private static StringBuilder getBaseUrl(String desformCode) {
return getBaseUrl(desformCode, null);
}
private static HttpHeaders getHeaders(String token) {
HttpHeaders headers = new HttpHeaders();
String mediaType = MediaType.APPLICATION_JSON_UTF8_VALUE;
headers.setContentType(MediaType.parseMediaType(mediaType));
headers.set("Accept", mediaType);
headers.set("X-Access-Token", token);
return headers;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\RestDesformUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private PricingInfo getPricingInfo(
@NonNull final BPartnerLocationAndCaptureId bpartnerAndLocationId,
@NonNull final ZonedDateTime customerReturnDate)
{
final PricingSystemId pricingSystemId = bpartnerDAO.retrievePricingSystemIdOrNull(bpartnerAndLocationId.getBpartnerId(), SOTrx.SALES);
if (pricingSystemId == null)
{
throw new AdempiereException("@NotFound@ @M_PricingSystem_ID@")
.setParameter("C_BPartner_ID", bpartnerDAO.getBPartnerNameById(bpartnerAndLocationId.getBpartnerId()))
.setParameter("SOTrx", SOTrx.SALES);
}
final PriceListId priceListId = priceListDAO.retrievePriceListIdByPricingSyst(pricingSystemId, bpartnerAndLocationId, SOTrx.SALES);
if (priceListId == null)
{
throw new PriceListNotFoundException(
priceListDAO.getPricingSystemName(pricingSystemId), | SOTrx.SALES);
}
final I_M_PriceList_Version priceListVersion = priceListDAO.retrievePriceListVersionOrNull(priceListId, customerReturnDate, null);
if (priceListVersion == null)
{
throw new PriceListVersionNotFoundException(priceListId, customerReturnDate);
}
return PricingInfo.builder()
.priceListVersionId(PriceListVersionId.ofRepoId(priceListVersion.getM_PriceList_Version_ID()))
.currencyId(priceListDAO.getCurrencyId(priceListId))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\CreateServiceRepairProjectCommand.java | 2 |
请完成以下Java代码 | public I_M_Product getM_Product()
{
return Services.get(IProductDAO.class).getById(productId);
}
@Override
public int getM_Product_ID()
{
return ProductId.toRepoId(productId);
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return Services.get(IAttributeSetInstanceBL.class).getById(attributeSetInstanceId);
}
@Override
public int getM_AttributeSetInstance_ID()
{ | return attributeSetInstanceId.getRepoId();
}
@Override
public void setM_AttributeSetInstance(I_M_AttributeSetInstance asi)
{
throw new UnsupportedOperationException("Changing the M_AttributeSetInstance is not supported for " + PlainAttributeSetInstanceAware.class.getName());
}
@Override
public void setM_AttributeSetInstance_ID(int M_AttributeSetInstance_ID)
{
throw new UnsupportedOperationException("Changing the M_AttributeSetInstance_ID is not supported for " + PlainAttributeSetInstanceAware.class.getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\asi_aware\PlainAttributeSetInstanceAware.java | 1 |
请完成以下Java代码 | public static ExternalSystemScriptedExportConversionConfig fromRecord(@NonNull final I_ExternalSystem_Config_ScriptedExportConversion config,
@NonNull final ExternalSystemParentConfigId parentConfigId)
{
return ExternalSystemScriptedExportConversionConfig.builder()
.id(ExternalSystemScriptedExportConversionConfigId.ofRepoId(config.getExternalSystem_Config_ScriptedExportConversion_ID()))
.parentId(parentConfigId)
.externalSystemOutboundEndpointId(ExternalSystemOutboundEndpointId.ofRepoId(config.getExternalSystem_Outbound_Endpoint_ID()))
.value(config.getExternalSystemValue())
.description(config.getDescription())
.outboundDataProcessId(AdProcessId.ofRepoIdOrNull(config.getAD_Process_OutboundData_ID()))
.scriptIdentifier(config.getScriptIdentifier())
.adTableId(AdTableId.ofRepoId(config.getAD_Table_ID()))
.docBaseType(DocBaseType.ofNullableCode(config.getDocBaseType()))
.whereClause(config.getWhereClause())
.seqNo(SeqNo.ofInt(config.getSeqNo()))
.active(config.isActive())
.clientId(ClientId.ofRepoId(config.getAD_Client_ID()))
.build();
} | @NonNull
private static ExternalSystemScriptedExportConversionConfig fromRecord(@NonNull final I_ExternalSystem_Config_ScriptedExportConversion config)
{
return fromRecord(config, ExternalSystemParentConfigId.ofRepoId(config.getExternalSystem_Config_ID()));
}
@NonNull
private IQueryBuilder<I_ExternalSystem_Config_ScriptedExportConversion> getOrderedQueryBuilder(@NonNull final AdTableAndClientId tableAndClientId)
{
return queryBL.createQueryBuilder(I_ExternalSystem_Config_ScriptedExportConversion.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_ExternalSystem_Config_ScriptedExportConversion.COLUMNNAME_AD_Table_ID, tableAndClientId.getTableId())
.addEqualsFilter(I_ExternalSystem_Config_ScriptedExportConversion.COLUMNNAME_AD_Client_ID, tableAndClientId.getClientId())
.orderBy(I_ExternalSystem_Config_ScriptedExportConversion.COLUMN_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\ExternalSystemScriptedExportConversionRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void initEntityManagers() {
if (entityLinkEntityManager == null) {
entityLinkEntityManager = new EntityLinkEntityManagerImpl(this, entityLinkDataManager);
}
if (historicEntityLinkEntityManager == null) {
historicEntityLinkEntityManager = new HistoricEntityLinkEntityManagerImpl(this, historicEntityLinkDataManager);
}
}
// getters and setters
// //////////////////////////////////////////////////////
public EntityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return this;
}
public EntityLinkService getEntityLinkService() {
return entityLinkService;
}
public EntityLinkServiceConfiguration setEntityLinkService(EntityLinkService entityLinkService) {
this.entityLinkService = entityLinkService;
return this;
}
public HistoricEntityLinkService getHistoricEntityLinkService() {
return historicEntityLinkService;
}
public EntityLinkServiceConfiguration setHistoricEntityLinkService(HistoricEntityLinkService historicEntityLinkService) {
this.historicEntityLinkService = historicEntityLinkService;
return this;
}
public EntityLinkDataManager getEntityLinkDataManager() {
return entityLinkDataManager;
}
public EntityLinkServiceConfiguration setEntityLinkDataManager(EntityLinkDataManager entityLinkDataManager) {
this.entityLinkDataManager = entityLinkDataManager;
return this;
}
public HistoricEntityLinkDataManager getHistoricEntityLinkDataManager() {
return historicEntityLinkDataManager;
}
public EntityLinkServiceConfiguration setHistoricEntityLinkDataManager(HistoricEntityLinkDataManager historicEntityLinkDataManager) {
this.historicEntityLinkDataManager = historicEntityLinkDataManager;
return this;
}
public EntityLinkEntityManager getEntityLinkEntityManager() {
return entityLinkEntityManager; | }
public EntityLinkServiceConfiguration setEntityLinkEntityManager(EntityLinkEntityManager entityLinkEntityManager) {
this.entityLinkEntityManager = entityLinkEntityManager;
return this;
}
public HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() {
return historicEntityLinkEntityManager;
}
public EntityLinkServiceConfiguration setHistoricEntityLinkEntityManager(HistoricEntityLinkEntityManager historicEntityLinkEntityManager) {
this.historicEntityLinkEntityManager = historicEntityLinkEntityManager;
return this;
}
@Override
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public EntityLinkServiceConfiguration setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\EntityLinkServiceConfiguration.java | 2 |
请完成以下Java代码 | public void addMouseListener(MouseListener l)
{
m_text.addMouseListener(l);
}
/**
* Data Binding to MTable (via GridController) - Enter pressed
* @param e event
*/
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == m_button)
{
action_button();
return;
}
// Data Binding
try
{
fireVetoableChange(m_columnName, m_oldText, getText());
}
catch (PropertyVetoException pve)
{
}
} // actionPerformed
/**
* Preliminary check if this current URL is valid.
*
* NOTE: This method is used to check if we shall enable the "browse/action button", so for performance purposes we are not actually validate if the URL is really valid.
*
* @return true if value
*/
private final boolean isValidURL()
{
final String urlString = m_text.getText();
if (Check.isEmpty(urlString, true))
{
return false;
}
return true;
}
/**
* Action button pressed - show URL
*/
private void action_button()
{
String urlString = m_text.getText();
if (!Check.isEmpty(urlString, true))
{
urlString = urlString.trim();
try
{
// validate the URL
new URL(urlString);
Env.startBrowser(urlString);
return;
}
catch (Exception e)
{
final String message = e.getLocalizedMessage();
ADialog.warn(0, this, "URLnotValid", message);
}
}
} // action button
/**
* Set Field/WindowNo for ValuePreference
* @param mField field
*/
@Override
public void setField (GridField mField)
{
this.m_mField = mField; | EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
/**
* Set Text
* @param text text
*/
public void setText (String text)
{
m_text.setText (text);
validateOnTextChanged();
} // setText
/**
* Get Text (clear)
* @return text
*/
public String getText ()
{
String text = m_text.getText();
return text;
} // getText
/**
* Focus Gained.
* Enabled with Obscure
* @param e event
*/
public void focusGained (FocusEvent e)
{
m_infocus = true;
setText(getText()); // clear
} // focusGained
/**
* Focus Lost
* Enabled with Obscure
* @param e event
*/
public void focusLost (FocusEvent e)
{
m_infocus = false;
setText(getText()); // obscure
} // focus Lost
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VURL | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VURL.java | 1 |
请完成以下Java代码 | public void setAttribute(String attributeName, Object attributeValue) {
if (attributeValue == null) {
removeAttribute(attributeName);
}
else {
this.sessionAttrs.put(attributeName, attributeValue);
}
}
@Override
public void removeAttribute(String attributeName) {
this.sessionAttrs.remove(attributeName);
}
/**
* Sets the time that this {@link Session} was created. The default is when the
* {@link Session} was instantiated.
* @param creationTime the time that this {@link Session} was created.
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = creationTime;
}
/**
* Sets the identifier for this {@link Session}. The id should be a secure random
* generated value to prevent malicious users from guessing this value. The default is
* a secure random generated identifier.
* @param id the identifier for this session.
*/
public void setId(String id) { | this.id = id;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Session && this.id.equals(((Session) obj).getId());
}
@Override
public int hashCode() {
return this.id.hashCode();
}
private static String generateId() {
return UUID.randomUUID().toString();
}
/**
* Sets the {@link SessionIdGenerator} to use when generating a new session id.
* @param sessionIdGenerator the {@link SessionIdGenerator} to use.
* @since 3.2
*/
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
private static final long serialVersionUID = 7160779239673823561L;
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSession.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FormDefinitionResponse {
protected String id;
protected String url;
protected String category;
protected String name;
protected String key;
protected String description;
protected int version;
protected String resourceName;
protected String deploymentId;
protected String tenantId;
public FormDefinitionResponse(FormDefinition formDefinition) {
setId(formDefinition.getId());
setCategory(formDefinition.getCategory());
setName(formDefinition.getName());
setKey(formDefinition.getKey());
setDescription(formDefinition.getDescription());
setVersion(formDefinition.getVersion());
setResourceName(formDefinition.getResourceName());
setDeploymentId(formDefinition.getDeploymentId());
setTenantId(formDefinition.getTenantId());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getDescription() {
return description;
} | public void setDescription(String description) {
this.description = description;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getResourceName() {
return resourceName;
}
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\FormDefinitionResponse.java | 2 |
请完成以下Java代码 | public CountResultDto queryJobsCount(JobQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
JobQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
@Override
public BatchDto setRetries(SetJobRetriesDto setJobRetriesDto) {
try {
EnsureUtil.ensureNotNull("setJobRetriesDto", setJobRetriesDto);
EnsureUtil.ensureNotNull("retries", setJobRetriesDto.getRetries());
} catch (NullValueException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
JobQuery jobQuery = null;
if (setJobRetriesDto.getJobQuery() != null) {
JobQueryDto jobQueryDto = setJobRetriesDto.getJobQuery();
jobQueryDto.setObjectMapper(getObjectMapper());
jobQuery = jobQueryDto.toQuery(getProcessEngine());
} | try {
SetJobRetriesByJobsAsyncBuilder builder = getProcessEngine().getManagementService()
.setJobRetriesByJobsAsync(setJobRetriesDto.getRetries().intValue())
.jobIds(setJobRetriesDto.getJobIds())
.jobQuery(jobQuery);
if(setJobRetriesDto.isDueDateSet()) {
builder.dueDate(setJobRetriesDto.getDueDate());
}
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public void updateSuspensionState(JobSuspensionStateDto dto) {
if (dto.getJobId() != null) {
String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state.";
throw new InvalidRequestException(Status.BAD_REQUEST, message);
}
dto.updateSuspensionState(getProcessEngine());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\JobRestServiceImpl.java | 1 |
请完成以下Java代码 | public final ClearanceStatusInfo getHUClearanceStatusInfo()
{
return _huClearanceStatusInfo;
}
private void destroyCurrentHU(final HUListCursor currentHUCursor, final IHUContext huContext)
{
final I_M_HU hu = currentHUCursor.current();
if (hu == null)
{
return; // shall not happen
}
currentHUCursor.closeCurrent(); // close the current position of this cursor
// since _createdNonAggregateHUs is just a subset of _createdHUs, we don't know if 'hu' was in there to start with. All we care is that it's not in _createdNonAggregateHUs after this method.
_createdNonAggregateHUs.remove(hu);
final boolean removedFromCreatedHUs = _createdHUs.remove(hu);
Check.assume(removedFromCreatedHUs, "Cannot destroy {} because it wasn't created by us", hu); | // Delete only those HUs which were internally created by THIS producer
if (DYNATTR_Producer.getValue(hu) == this)
{
final Supplier<IAutoCloseable> getDontDestroyParentLUClosable = () -> {
final I_M_HU lu = handlingUnitsBL.getLoadingUnitHU(hu);
return lu != null
? huContext.temporarilyDontDestroyHU(HuId.ofRepoId(lu.getM_HU_ID()))
: () -> {
};
};
try (final IAutoCloseable ignored = getDontDestroyParentLUClosable.get())
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, hu);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractProducerDestination.java | 1 |
请完成以下Java代码 | public static BankToCustomerDebitCreditNotificationV02 loadXML(@NonNull final MultiVersionStreamReaderDelegate xsr)
{
final Document document;
try
{
// https://stackoverflow.com/questions/20410202/jaxb-unmarshalling-not-working-expected-elements-are-none
// use ObjectFactory for creating the context because otherwise unmarshalling will not work
final JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
@SuppressWarnings("unchecked") final JAXBElement<Document> e = (JAXBElement<Document>)unmarshaller.unmarshal(xsr);
document = e.getValue();
}
catch (final JAXBException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
return document.getBkToCstmrDbtCdtNtfctn();
}
private String getErrorMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... params)
{
return msgBL.getTranslatableMsgText(adMessage, params).translate(adLanguage);
}
/**
* Marshals the given {@code} into an XML string and return that as the "key".
* mkTrxKey for version 2 <code>BankToCustomerDebitCreditNotificationV02</code>
*/
private static String mkTrxKey(@NonNull final EntryTransaction2 txDtl)
{
final ByteArrayOutputStream transactionKey = new ByteArrayOutputStream();
JAXB.marshal(txDtl, transactionKey);
try | {
return transactionKey.toString("UTF-8");
}
catch (UnsupportedEncodingException e)
{
// won't happen because UTF-8 is supported
throw AdempiereException.wrapIfNeeded(e);
}
}
/**
* asTimestamp for version 6 <code>BankToCustomerDebitCreditNotificationV06</code>
*/
private static Timestamp asTimestamp(@NonNull final DateAndDateTimeChoice valDt)
{
return new Timestamp(valDt.getDt().toGregorianCalendar().getTimeInMillis());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\impl\camt54\ESRDataImporterCamt54v02.java | 1 |
请完成以下Java代码 | public boolean createNode(String path, String data) {
try {
zkClient.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
return true;
} catch (Exception e) {
log.error("【create persist node exception】{},{},{}", path, data, e);
return false;
}
}
/**
* update persist node
*
* @param path
* @param data
*/
public boolean updateNode(String path, String data) {
try {
//The data version of zk starts counting from 0. If the client passes -1, it means that the zk server needs to be updated based on the latest data. If there is no atomicity requirement for the update operation of zk's data node, you can use -1.
//The version parameter specifies the version of the data to be updated. If the version is different from the real version, the update operation will fail. Specify version as -1 to ignore the version check.
zkClient.setData(path, data.getBytes(), -1);
return true;
} catch (Exception e) {
log.error("【update persist node exception】{},{},{}", path, data, e);
return false;
}
}
/**
* delete persist node
*
* @param path
*/
public boolean deleteNode(String path) {
try {
//The version parameter specifies the version of the data to be updated. If the version is different from the real version, the update operation will fail. Specify version as -1 to ignore the version check.
zkClient.delete(path, -1);
return true; | } catch (Exception e) {
log.error("【delete persist node exception】{},{}", path, e);
return false;
}
}
/**
* Get the child nodes of the current node (excluding grandchild nodes)
*
* @param path
*/
public List<String> getChildren(String path) throws KeeperException, InterruptedException {
List<String> list = zkClient.getChildren(path, false);
return list;
}
/**
* Get the value of the specified node
*
* @param path
* @return
*/
public String getData(String path, Watcher watcher) {
try {
Stat stat = new Stat();
byte[] bytes = zkClient.getData(path, watcher, stat);
return new String(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
} | repos\springboot-demo-master\zookeeper\src\main\java\com\et\zookeeper\api\ZkApi.java | 1 |
请完成以下Java代码 | public final int getResultSetHoldability() throws SQLException
{
return delegate.getResultSetHoldability();
}
@Override
public final boolean isClosed() throws SQLException
{
return delegate.isClosed();
}
@Override
public final void setPoolable(final boolean poolable) throws SQLException
{
delegate.setPoolable(poolable);
}
@Override
public final boolean isPoolable() throws SQLException
{ | return delegate.isPoolable();
}
@Override
public final void closeOnCompletion() throws SQLException
{
delegate.closeOnCompletion();
}
@Override
public final boolean isCloseOnCompletion() throws SQLException
{
return delegate.isCloseOnCompletion();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingStatement.java | 1 |
请完成以下Java代码 | public IdentityOperationResult deleteTenantGroupMembership(String tenantId, String groupId) {
checkAuthorization(Permissions.DELETE, Resources.TENANT_MEMBERSHIP, tenantId);
if (existsTenantMembership(tenantId, null, groupId)) {
deleteAuthorizations(Resources.TENANT_MEMBERSHIP, groupId);
deleteAuthorizationsForGroup(Resources.TENANT, tenantId, groupId);
Map<String, Object> parameters = new HashMap<>();
parameters.put("tenantId", tenantId);
parameters.put("groupId", groupId);
getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembership", parameters);
return new IdentityOperationResult(null, IdentityOperationResult.OPERATION_DELETE);
}
return new IdentityOperationResult(null, IdentityOperationResult.OPERATION_NONE);
}
protected void deleteTenantMembershipsOfUser(String userId) {
getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfUser", userId);
}
protected void deleteTenantMembershipsOfGroup(String groupId) {
getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfGroup", groupId);
}
protected void deleteTenantMembershipsOfTenant(String tenant) {
getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfTenant", tenant);
}
// authorizations ////////////////////////////////////////////////////////////
protected void createDefaultAuthorizations(UserEntity userEntity) {
if(Context.getProcessEngineConfiguration().isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newUser(userEntity));
}
} | protected void createDefaultAuthorizations(Group group) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newGroup(group));
}
}
protected void createDefaultAuthorizations(Tenant tenant) {
if (isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newTenant(tenant));
}
}
protected void createDefaultMembershipAuthorizations(String userId, String groupId) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().groupMembershipCreated(groupId, userId));
}
}
protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, User user) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, user));
}
}
protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, Group group) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, group));
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbIdentityServiceProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserProfileService {
@Autowired
AmazonS3 amazonS3Client;
@Value("${aws.s3.bucket}")
private String bucketName;
private String subFolder = "";
@Autowired
UserProfileDataAccessService userProfileDataAccessService;
List<UserProfile> getUserProfiles(){
return userProfileDataAccessService.getUserProfile();
}
@Async
void uploadUserProfileImage(String userProfileId, MultipartFile multipartFile) throws Exception {
final File file = convertMultiPartFileToFile(multipartFile);
String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
uploadFileToS3Bucket(bucketName, file, extension);
file.delete(); | }
private void uploadFileToS3Bucket(final String bucketName, final File file, String filename) {
final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, file);
amazonS3Client.putObject(putObjectRequest);
}
private File convertMultiPartFileToFile(final MultipartFile multipartFile) throws Exception{
final File file = new File(multipartFile.getOriginalFilename());
try (final FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(multipartFile.getBytes());
} catch (final IOException ex) {
}
return file;
}
} | repos\Spring-Boot-Advanced-Projects-main\Project-4.SpringBoot-AWS-S3\backend\src\main\java\com\urunov\profile\UserProfileService.java | 2 |
请完成以下Java代码 | public class MultiInputs {
public void UsingSpaceDelimiter(){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2);
}
public void UsingREDelimiter(){
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("[\\s,]+");
System.out.print("Enter two numbers separated by a space or a comma: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2); | }
public void UsingCustomDelimiter(){
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(";");
System.out.print("Enter two numbers separated by a semicolon: ");
try { int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
System.out.println("You entered " + num1 + " and " + num2); }
catch (InputMismatchException e)
{ System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
}
} | repos\tutorials-master\core-java-modules\core-java-io-apis\src\main\java\com\baeldung\multinput\MultiInputs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
public boolean isShowInOverview() {
return showInOverview;
}
public void setShowInOverview(boolean showInOverview) {
this.showInOverview = showInOverview;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-planitem-instances/5")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4")
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) { | this.caseDefinitionUrl = caseDefinitionUrl;
}
public String getDerivedCaseDefinitionUrl() {
return derivedCaseDefinitionUrl;
}
public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) {
this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl;
}
public String getStageInstanceUrl() {
return stageInstanceUrl;
}
public void setStageInstanceUrl(String stageInstanceUrl) {
this.stageInstanceUrl = stageInstanceUrl;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public AnonymousConfigurer<H> authorities(List<GrantedAuthority> authorities) {
this.authorities = authorities;
return this;
}
/**
* Sets the {@link org.springframework.security.core.Authentication#getAuthorities()}
* for anonymous users
* @param authorities Sets the
* {@link org.springframework.security.core.Authentication#getAuthorities()} for
* anonymous users (i.e. "ROLE_ANONYMOUS")
* @return the {@link AnonymousConfigurer} for further customization of anonymous
* authentication
*/
public AnonymousConfigurer<H> authorities(String... authorities) {
return authorities(AuthorityUtils.createAuthorityList(authorities));
}
/**
* Sets the {@link AuthenticationProvider} used to validate an anonymous user. If this
* is set, no attributes on the {@link AnonymousConfigurer} will be set on the
* {@link AuthenticationProvider}.
* @param authenticationProvider the {@link AuthenticationProvider} used to validate
* an anonymous user. Default is {@link AnonymousAuthenticationProvider}
* @return the {@link AnonymousConfigurer} for further customization of anonymous
* authentication
*/
public AnonymousConfigurer<H> authenticationProvider(AuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
return this;
}
/**
* Sets the {@link AnonymousAuthenticationFilter} used to populate an anonymous user.
* If this is set, no attributes on the {@link AnonymousConfigurer} will be set on the
* {@link AnonymousAuthenticationFilter}.
* @param authenticationFilter the {@link AnonymousAuthenticationFilter} used to
* populate an anonymous user.
* @return the {@link AnonymousConfigurer} for further customization of anonymous
* authentication
*/
public AnonymousConfigurer<H> authenticationFilter(AnonymousAuthenticationFilter authenticationFilter) {
this.authenticationFilter = authenticationFilter;
return this;
}
@Override
public void init(H http) {
if (this.authenticationProvider == null) {
this.authenticationProvider = new AnonymousAuthenticationProvider(getKey());
}
this.authenticationProvider = postProcess(this.authenticationProvider); | http.authenticationProvider(this.authenticationProvider);
}
@Override
public void configure(H http) {
if (this.authenticationFilter == null) {
this.authenticationFilter = new AnonymousAuthenticationFilter(getKey(), this.principal, this.authorities);
}
this.authenticationFilter.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
this.authenticationFilter.afterPropertiesSet();
http.addFilter(this.authenticationFilter);
}
private String getKey() {
if (this.computedKey != null) {
return this.computedKey;
}
if (this.key == null) {
this.computedKey = UUID.randomUUID().toString();
}
else {
this.computedKey = this.key;
}
return this.computedKey;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AnonymousConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
DisputeSummaryResponse disputeSummaryResponse = (DisputeSummaryResponse)o;
return Objects.equals(this.href, disputeSummaryResponse.href) &&
Objects.equals(this.limit, disputeSummaryResponse.limit) &&
Objects.equals(this.next, disputeSummaryResponse.next) &&
Objects.equals(this.offset, disputeSummaryResponse.offset) &&
Objects.equals(this.paymentDisputeSummaries, disputeSummaryResponse.paymentDisputeSummaries) &&
Objects.equals(this.prev, disputeSummaryResponse.prev) &&
Objects.equals(this.total, disputeSummaryResponse.total);
}
@Override
public int hashCode()
{
return Objects.hash(href, limit, next, offset, paymentDisputeSummaries, prev, total);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class DisputeSummaryResponse {\n");
sb.append(" href: ").append(toIndentedString(href)).append("\n"); | sb.append(" limit: ").append(toIndentedString(limit)).append("\n");
sb.append(" next: ").append(toIndentedString(next)).append("\n");
sb.append(" offset: ").append(toIndentedString(offset)).append("\n");
sb.append(" paymentDisputeSummaries: ").append(toIndentedString(paymentDisputeSummaries)).append("\n");
sb.append(" prev: ").append(toIndentedString(prev)).append("\n");
sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\DisputeSummaryResponse.java | 2 |
请完成以下Java代码 | protected boolean canReachActivity(ActivityExecution execution, PvmActivity activity) {
PvmTransition pvmTransition = execution.getTransition();
if (pvmTransition != null) {
return isReachable(pvmTransition.getDestination(), activity, new HashSet<PvmActivity>());
} else {
return isReachable(execution.getActivity(), activity, new HashSet<PvmActivity>());
}
}
protected boolean isReachable(PvmActivity srcActivity, PvmActivity targetActivity, Set<PvmActivity> visitedActivities) {
if (srcActivity.equals(targetActivity)) {
return true;
}
if (visitedActivities.contains(srcActivity)) {
return false;
}
// To avoid infinite looping, we must capture every node we visit and
// check before going further in the graph if we have already visited the node.
visitedActivities.add(srcActivity);
List<PvmTransition> outgoingTransitions = srcActivity.getOutgoingTransitions();
if (outgoingTransitions.isEmpty()) {
if (srcActivity.getActivityBehavior() instanceof EventBasedGatewayActivityBehavior) {
ActivityImpl eventBasedGateway = (ActivityImpl) srcActivity;
Set<ActivityImpl> eventActivities = eventBasedGateway.getEventActivities();
for (ActivityImpl eventActivity : eventActivities) {
boolean isReachable = isReachable(eventActivity, targetActivity, visitedActivities);
if (isReachable) {
return true;
}
} | }
else {
ScopeImpl flowScope = srcActivity.getFlowScope();
if (flowScope != null && flowScope instanceof PvmActivity) {
return isReachable((PvmActivity) flowScope, targetActivity, visitedActivities);
}
}
return false;
}
else {
for (PvmTransition pvmTransition : outgoingTransitions) {
PvmActivity destinationActivity = pvmTransition.getDestination();
if (destinationActivity != null && !visitedActivities.contains(destinationActivity)) {
boolean reachable = isReachable(destinationActivity, targetActivity, visitedActivities);
// If false, we should investigate other paths, and not yet return the result
if (reachable) {
return true;
}
}
}
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\InclusiveGatewayActivityBehavior.java | 1 |
请完成以下Java代码 | public static Tags empty() {
return EMPTY;
}
public static Tags from(Map<String, ?> map) {
return from(map, null);
}
@SuppressWarnings("unchecked")
public static Tags from(Map<String, ?> map, @Nullable String prefix) {
if (map.isEmpty()) {
return empty();
}
if (StringUtils.hasText(prefix)) {
Object nestedTags = map.get(prefix);
if (nestedTags instanceof Map) {
return from((Map<String, Object>) nestedTags);
}
String flatPrefix = prefix + ".";
return from(map.entrySet()
.stream()
.filter((e) -> e.getKey() != null) | .filter((e) -> e.getKey().toLowerCase().startsWith(flatPrefix))
.collect(toLinkedHashMap((e) -> e.getKey().substring(flatPrefix.length()), Map.Entry::getValue)));
}
return new Tags(map.entrySet()
.stream()
.filter((e) -> e.getKey() != null)
.collect(toLinkedHashMap(Map.Entry::getKey, (e) -> Objects.toString(e.getValue()))));
}
private static <T, K, U> Collector<T, ?, LinkedHashMap<K, U>> toLinkedHashMap(
Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
}, LinkedHashMap::new);
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\values\Tags.java | 1 |
请完成以下Java代码 | private class GuavaEventListenerAdapter
{
@NonNull
private final IEventListener eventListener;
@Subscribe
public void onEvent(@NonNull final Event event)
{
micrometerEventBusStatsCollector.incrementEventsDequeued();
micrometerEventBusStatsCollector
.getEventProcessingTimer()
.record(() ->
{
try (final MDCCloseable ignored = EventMDC.putEvent(event))
{
logger.debug("GuavaEventListenerAdapter.onEvent - eventListener to invoke={}", eventListener);
invokeEventListener(this.eventListener, event);
}
});
}
}
private void invokeEventListener(
@NonNull final IEventListener eventListener,
@NonNull final Event event)
{
if (event.isWasLogged())
{
invokeEventListenerWithLogging(eventListener, event);
}
else
{
eventListener.onEvent(this, event);
}
}
private void invokeEventListenerWithLogging(
@NonNull final IEventListener eventListener,
@NonNull final Event event)
{
try (final EventLogEntryCollector ignored = EventLogEntryCollector.createThreadLocalForEvent(event))
{
try | {
eventListener.onEvent(this, event);
}
catch (final RuntimeException ex)
{
if (!Adempiere.isUnitTestMode())
{
final EventLogUserService eventLogUserService = SpringContextHolder.instance.getBean(EventLogUserService.class);
eventLogUserService
.newErrorLogEntry(eventListener.getClass(), ex)
.createAndStore();
}
else
{
logger.warn("Got exception while invoking eventListener={} with event={}", eventListener, event, ex);
}
}
}
}
@Override
public EventBusStats getStats()
{
return micrometerEventBusStatsCollector.snapshot();
}
private void enqueueEvent0(final Event event)
{
if (Type.LOCAL == topic.getType())
{
eventEnqueuer.enqueueLocalEvent(event, topic);
}
else
{
eventEnqueuer.enqueueDistributedEvent(event, topic);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBus.java | 1 |
请完成以下Java代码 | public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Over/Under Payment.
@param OverUnderAmt
Over-Payment (unallocated) or Under-Payment (partial payment) Amount
*/
@Override
public void setOverUnderAmt (java.math.BigDecimal OverUnderAmt)
{
set_Value (COLUMNNAME_OverUnderAmt, OverUnderAmt);
}
/** Get Over/Under Payment.
@return Over-Payment (unallocated) or Under-Payment (partial payment) Amount
*/
@Override
public java.math.BigDecimal getOverUnderAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OverUnderAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Abschreibung Betrag.
@param PaymentWriteOffAmt
Abschreibung Betrag
*/
@Override
public void setPaymentWriteOffAmt (java.math.BigDecimal PaymentWriteOffAmt)
{
set_Value (COLUMNNAME_PaymentWriteOffAmt, PaymentWriteOffAmt);
}
/** Get Abschreibung Betrag.
@return Abschreibung Betrag
*/
@Override
public java.math.BigDecimal getPaymentWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PaymentWriteOffAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
@Override
public org.compiere.model.I_C_AllocationLine getReversalLine()
{ | return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class);
}
@Override
public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine);
}
/** Set Storno-Zeile.
@param ReversalLine_ID Storno-Zeile */
@Override
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Storno-Zeile.
@return Storno-Zeile */
@Override
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Abschreiben.
@param WriteOffAmt
Amount to write-off
*/
@Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{
set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Abschreiben.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java | 1 |
请完成以下Java代码 | public static void writeValue_C_Country_ID(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
final IntegerLookupValue country = fromField.getValueAs(IntegerLookupValue.class);
if (country == null)
{
toLocationRecord.setC_Country_ID(-1);
}
else if (country.getIdAsInt() <= 0)
{
toLocationRecord.setC_Country_ID(-1);
}
else
{
toLocationRecord.setC_Country_ID(country.getIdAsInt());
}
}
private static void writeValue_C_Postal_ID(final I_C_Location toLocationRecord, final IDocumentFieldView fromField)
{
final IntegerLookupValue postalLookupValue = fromField.getValueAs(IntegerLookupValue.class);
final int postalId = postalLookupValue != null ? postalLookupValue.getIdAsInt() : -1;
if (postalId <= 0)
{
toLocationRecord.setC_Postal_ID(-1);
toLocationRecord.setPostal(null); | toLocationRecord.setCity(null);
toLocationRecord.setC_City_ID(-1);
}
else
{
final I_C_Postal postalRecord = InterfaceWrapperHelper.load(postalId, I_C_Postal.class);
toLocationRecord.setC_Postal_ID(postalRecord.getC_Postal_ID());
toLocationRecord.setPostal(postalRecord.getPostal());
toLocationRecord.setPostal_Add(postalRecord.getPostal_Add());
toLocationRecord.setC_City_ID(postalRecord.getC_City_ID());
toLocationRecord.setCity(postalRecord.getCity());
toLocationRecord.setC_Country_ID(postalRecord.getC_Country_ID());
toLocationRecord.setC_Region_ID(postalRecord.getC_Region_ID());
toLocationRecord.setRegionName(postalRecord.getRegionName());
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressDescriptorFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Phone implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private boolean deleted;
private String number;
public Phone() {
}
public Phone(String number) {
this.number = number;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
} | public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\pojo\Phone.java | 2 |
请完成以下Java代码 | public UIComponent getUIComponent(
final @NonNull WFProcess wfProcess,
final @NonNull WFActivity wfActivity,
final @NonNull JsonOpts jsonOpts)
{
final JsonQRCode pickFromHU = getPickingJob(wfProcess)
.getPickFromHU()
.map(SetPickFromHUWFActivityHandler::toJsonQRCode)
.orElse(null);
return SetScannedBarcodeSupportHelper.uiComponent()
.currentValue(pickFromHU)
.alwaysAvailableToUser(wfActivity.getAlwaysAvailableToUser())
.build();
}
public static JsonQRCode toJsonQRCode(final HUInfo pickFromHU)
{
final HUQRCode qrCode = pickFromHU.getQrCode();
return JsonQRCode.builder()
.qrCode(qrCode.toGlobalQRCodeString())
.caption(qrCode.toDisplayableQRCode())
.build();
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
final PickingJob pickingJob = getPickingJob(wfProcess);
return computeActivityState(pickingJob);
}
public static WFActivityStatus computeActivityState(final PickingJob pickingJob)
{
return pickingJob.getPickFromHU().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED;
} | @Override
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request)
{
final HUQRCode qrCode = parseHUQRCode(request.getScannedBarcode());
final HuId huId = huQRCodesService.getHuIdByQRCode(qrCode);
final HUInfo pickFromHU = HUInfo.builder()
.id(huId)
.qrCode(qrCode)
.build();
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJob -> pickingJobRestService.setPickFromHU(pickingJob, pickFromHU)
);
}
private HUQRCode parseHUQRCode(final String scannedCode)
{
final IHUQRCode huQRCode = huQRCodesService.parse(scannedCode);
if (huQRCode instanceof HUQRCode)
{
return (HUQRCode)huQRCode;
}
else
{
throw new AdempiereException("Invalid HU QR code: " + scannedCode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickFromHUWFActivityHandler.java | 1 |
请完成以下Java代码 | public static final class PublicKeyCredentialBuilder<R extends AuthenticatorResponse> {
@SuppressWarnings("NullAway.Init")
private String id;
private @Nullable PublicKeyCredentialType type;
@SuppressWarnings("NullAway.Init")
private Bytes rawId;
@SuppressWarnings("NullAway.Init")
private R response;
private @Nullable AuthenticatorAttachment authenticatorAttachment;
private @Nullable AuthenticationExtensionsClientOutputs clientExtensionResults;
private PublicKeyCredentialBuilder() {
}
/**
* Sets the {@link #getId()} property
* @param id the id
* @return the PublicKeyCredentialBuilder
*/
public PublicKeyCredentialBuilder id(String id) {
this.id = id;
return this;
}
/**
* Sets the {@link #getType()} property.
* @param type the type
* @return the PublicKeyCredentialBuilder
*/
public PublicKeyCredentialBuilder type(PublicKeyCredentialType type) {
this.type = type;
return this;
}
/**
* Sets the {@link #getRawId()} property.
* @param rawId the raw id
* @return the PublicKeyCredentialBuilder
*/
public PublicKeyCredentialBuilder rawId(Bytes rawId) {
this.rawId = rawId;
return this;
}
/**
* Sets the {@link #getResponse()} property.
* @param response the response
* @return the PublicKeyCredentialBuilder | */
public PublicKeyCredentialBuilder response(R response) {
this.response = response;
return this;
}
/**
* Sets the {@link #getAuthenticatorAttachment()} property.
* @param authenticatorAttachment the authenticator attachement
* @return the PublicKeyCredentialBuilder
*/
public PublicKeyCredentialBuilder authenticatorAttachment(AuthenticatorAttachment authenticatorAttachment) {
this.authenticatorAttachment = authenticatorAttachment;
return this;
}
/**
* Sets the {@link #getClientExtensionResults()} property.
* @param clientExtensionResults the client extension results
* @return the PublicKeyCredentialBuilder
*/
public PublicKeyCredentialBuilder clientExtensionResults(
AuthenticationExtensionsClientOutputs clientExtensionResults) {
this.clientExtensionResults = clientExtensionResults;
return this;
}
/**
* Creates a new {@link PublicKeyCredential}
* @return a new {@link PublicKeyCredential}
*/
public PublicKeyCredential<R> build() {
Assert.notNull(this.id, "id cannot be null");
Assert.notNull(this.rawId, "rawId cannot be null");
Assert.notNull(this.response, "response cannot be null");
return new PublicKeyCredential(this.id, this.type, this.rawId, this.response, this.authenticatorAttachment,
this.clientExtensionResults);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredential.java | 1 |
请完成以下Java代码 | public static Builder field(String name) {
return new Builder(name);
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
/**
* Return the modifiers.
* @return the modifiers
*/
public int getModifiers() {
return this.modifiers;
}
/**
* Return the name.
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Return the return type.
* @return the return type
*/
public String getReturnType() {
return this.returnType;
}
/**
* Return the value.
* @return the value
*/
public Object getValue() {
return this.value;
}
/**
* Whether the field declaration is initialized.
* @return whether the field declaration is initialized
*/
public boolean isInitialized() {
return this.initialized;
}
/**
* Builder for {@link GroovyFieldDeclaration}.
*/
public static final class Builder {
private final String name;
private String returnType;
private int modifiers;
private Object value; | private boolean initialized;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
}
/**
* Sets the value.
* @param value the value
* @return this for method chaining
*/
public Builder value(Object value) {
this.value = value;
this.initialized = true;
return this;
}
/**
* Sets the return type.
* @param returnType the return type
* @return the field
*/
public GroovyFieldDeclaration returning(String returnType) {
this.returnType = returnType;
return new GroovyFieldDeclaration(this);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyFieldDeclaration.java | 1 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getIncidentType() {
return incidentType;
}
public void setIncidentType(String incidentType) {
this.incidentType = incidentType;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getCauseIncidentId() {
return causeIncidentId;
}
public void setCauseIncidentId(String causeIncidentId) {
this.causeIncidentId = causeIncidentId;
}
public String getRootCauseIncidentId() {
return rootCauseIncidentId;
}
public void setRootCauseIncidentId(String rootCauseIncidentId) {
this.rootCauseIncidentId = rootCauseIncidentId;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public void setHistoryConfiguration(String historyConfiguration) {
this.historyConfiguration = historyConfiguration;
}
public String getIncidentMessage() {
return incidentMessage;
}
public void setIncidentMessage(String incidentMessage) {
this.incidentMessage = incidentMessage;
}
public void setIncidentState(int incidentState) {
this.incidentState = incidentState;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public boolean isOpen() {
return IncidentState.DEFAULT.getStateCode() == incidentState;
}
public boolean isDeleted() {
return IncidentState.DELETED.getStateCode() == incidentState;
}
public boolean isResolved() {
return IncidentState.RESOLVED.getStateCode() == incidentState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java | 1 |
请完成以下Java代码 | private static TooltipType getTooltipType(final @NotNull LookupDataSourceContext evalCtx)
{
final String tableName = evalCtx.getTableName();
return tableName != null
? TableIdsCache.instance.getTooltipType(tableName)
: TooltipType.DEFAULT;
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return prepareNewContext()
.requiresParameters(dependsOnContextVariables)
.requiresFilterAndLimit();
}
private LookupDataSourceContext.Builder prepareNewContext()
{
return LookupDataSourceContext.builder(CONTEXT_LookupTableName);
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int limit = evalCtx.getLimit(Integer.MAX_VALUE);
final int offset = evalCtx.getOffset(0);
return attributeValuesProvider.getAvailableValues(evalCtx)
.stream()
.map(namePair -> StringLookupValue.of(
namePair.getID(),
TranslatableStrings.constant(namePair.getName()),
TranslatableStrings.constant(namePair.getDescription())))
.filter(filter)
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
@Override | public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression()
{
if (attributeValuesProvider instanceof DefaultAttributeValuesProvider)
{
final DefaultAttributeValuesProvider defaultAttributeValuesProvider = (DefaultAttributeValuesProvider)attributeValuesProvider;
final AttributeId attributeId = defaultAttributeValuesProvider.getAttributeId();
return SqlForFetchingLookupById.builder()
.keyColumnNameFQ(ColumnNameFQ.ofTableAndColumnName(I_M_AttributeValue.Table_Name, I_M_AttributeValue.COLUMNNAME_Value))
.numericKey(false)
.displayColumn(ConstantStringExpression.of(I_M_AttributeValue.COLUMNNAME_Name))
.descriptionColumn(ConstantStringExpression.of(I_M_AttributeValue.COLUMNNAME_Description))
.activeColumn(ColumnNameFQ.ofTableAndColumnName(I_M_AttributeValue.Table_Name, I_M_AttributeValue.COLUMNNAME_IsActive))
.sqlFrom(ConstantStringExpression.of(I_M_AttributeValue.Table_Name))
.additionalWhereClause(I_M_AttributeValue.Table_Name + "." + I_M_AttributeValue.COLUMNNAME_M_Attribute_ID + "=" + attributeId.getRepoId())
.build();
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILookupDescriptor.java | 1 |
请完成以下Java代码 | public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText)
{
final int defaultRadius = Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_DefaultRadius, 0, Env.getAD_Client_ID(Env.getCtx()));
//
fieldCityZip = new CTextField();
fieldCityZip.setPreferredSize(new Dimension(200, (int)fieldCityZip.getPreferredSize().getHeight()));
fieldCityZipAutocompleter = new GeodbAutoCompleter(fieldCityZip);
fieldCityZipAutocompleter.setUserObject(null);
//
fieldRadius = new VNumber("RadiusKM", false, false, true, DisplayType.Integer, "");
fieldRadius.setValue(defaultRadius);
fieldRadius.setRange(0.0, 999999.0);
}
@Override
public Object getParameterComponent(int index)
{
if (index == 0)
return fieldCityZip;
else if (index == 1)
return fieldRadius;
else
return null;
}
@Override
public String[] getWhereClauses(List<Object> params)
{
final GeodbObject go = getGeodbObject();
final String searchText = getText();
if (go == null && !Check.isEmpty(searchText, true))
return new String[]{"1=2"};
if (go == null)
return new String[]{"1=1"};
final int radius = getRadius();
//
final String whereClause = "EXISTS (SELECT 1 FROM geodb_coordinates co WHERE "
+ " co.zip=" + locationTableAlias + ".Postal" // join to C_Location.Postal
+ " AND co.c_country_id=" + locationTableAlias + ".C_Country_ID"
+ " AND " + getSQLDistanceFormula("co", go.getLat(), go.getLon()) + " <= " + radius
+ ")";
return new String[]{whereClause};
}
private static String getSQLDistanceFormula(String tableAlias, double lat, double lon)
{
return "DEGREES(" | + " (ACOS("
+ " SIN(RADIANS(" + lat + ")) * SIN(RADIANS(" + tableAlias + ".lat)) "
+ " + COS(RADIANS(" + lat + "))*COS(RADIANS(" + tableAlias + ".lat))*COS(RADIANS(" + tableAlias + ".lon) - RADIANS(" + lon + "))"
+ ") * 60 * 1.1515 " // miles
+ " * 1.609344" // KM factor
+ " )"
+ " )";
}
private GeodbObject getGeodbObject()
{
return (GeodbObject)fieldCityZipAutocompleter.getUserOject();
}
@Override
public String getText()
{
return fieldCityZipAutocompleter.getText();
}
private int getRadius()
{
if (fieldRadius == null)
return 0;
Object o = fieldRadius.getValue();
if (o instanceof Number)
return ((Number)o).intValue();
return 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoQueryCriteriaBPRadius.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractDaoAuthenticationConfigurer<B extends ProviderManagerBuilder<B>, C extends AbstractDaoAuthenticationConfigurer<B, C, U>, U extends UserDetailsService>
extends UserDetailsAwareConfigurer<B, U> {
private DaoAuthenticationProvider provider;
private final U userDetailsService;
/**
* Creates a new instance
* @param userDetailsService
*/
AbstractDaoAuthenticationConfigurer(U userDetailsService) {
this.userDetailsService = userDetailsService;
this.provider = new DaoAuthenticationProvider(userDetailsService);
if (userDetailsService instanceof UserDetailsPasswordService) {
this.provider.setUserDetailsPasswordService((UserDetailsPasswordService) userDetailsService);
}
}
/**
* Adds an {@link ObjectPostProcessor} for this class.
* @param objectPostProcessor
* @return the {@link AbstractDaoAuthenticationConfigurer} for further customizations
*/
@SuppressWarnings("unchecked")
public C withObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
addObjectPostProcessor(objectPostProcessor);
return (C) this;
}
/**
* Allows specifying the {@link PasswordEncoder} to use with the
* {@link DaoAuthenticationProvider}. The default is to use plain text.
* @param passwordEncoder The {@link PasswordEncoder} to use. | * @return the {@link AbstractDaoAuthenticationConfigurer} for further customizations
*/
@SuppressWarnings("unchecked")
public C passwordEncoder(PasswordEncoder passwordEncoder) {
this.provider.setPasswordEncoder(passwordEncoder);
return (C) this;
}
public C userDetailsPasswordManager(UserDetailsPasswordService passwordManager) {
this.provider.setUserDetailsPasswordService(passwordManager);
return (C) this;
}
@Override
public void configure(B builder) {
this.provider = postProcess(this.provider);
builder.authenticationProvider(this.provider);
}
/**
* Gets the {@link UserDetailsService} that is used with the
* {@link DaoAuthenticationProvider}
* @return the {@link UserDetailsService} that is used with the
* {@link DaoAuthenticationProvider}
*/
@Override
public U getUserDetailsService() {
return this.userDetailsService;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\authentication\configurers\userdetails\AbstractDaoAuthenticationConfigurer.java | 2 |
请完成以下Java代码 | public void setM_TU_HU_ID (final int M_TU_HU_ID)
{
if (M_TU_HU_ID < 1)
set_Value (COLUMNNAME_M_TU_HU_ID, null);
else
set_Value (COLUMNNAME_M_TU_HU_ID, M_TU_HU_ID);
}
@Override
public int getM_TU_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_TU_HU_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyDeliveredCatch (final @Nullable BigDecimal QtyDeliveredCatch)
{
set_Value (COLUMNNAME_QtyDeliveredCatch, QtyDeliveredCatch);
}
@Override
public BigDecimal getQtyDeliveredCatch()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredCatch);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO; | }
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_Value (COLUMNNAME_VHU_ID, null);
else
set_Value (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_QtyPicked.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<RpPayProduct> listAll(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpPayProductDao.listBy(paramMap);
}
/**
* 审核
* @param productCode
* @param auditStatus
*/
@Override
public void audit(String productCode, String auditStatus) throws PayBizException{
RpPayProduct rpPayProduct = getByProductCode(productCode, null);
if(rpPayProduct == null){
throw new PayBizException(PayBizException.PAY_PRODUCT_IS_NOT_EXIST,"支付产品不存在!");
}
if(auditStatus.equals(PublicEnum.YES.name())){
//检查是否已设置支付方式
List<RpPayWay> payWayList = rpPayWayService.listByProductCode(productCode); | if(payWayList.isEmpty()){
throw new PayBizException(PayBizException.PAY_TYPE_IS_NOT_EXIST,"支付方式未设置,无法操作!");
}
}else if(auditStatus.equals(PublicEnum.NO.name())){
//检查是否已有支付配置
List<RpUserPayConfig> payConfigList = rpUserPayConfigService.listByProductCode(productCode);
if(!payConfigList.isEmpty()){
throw new PayBizException(PayBizException.USER_PAY_CONFIG_IS_EXIST,"支付产品已关联用户支付配置,无法操作!");
}
}
rpPayProduct.setAuditStatus(auditStatus);
rpPayProduct.setEditTime(new Date());
updateData(rpPayProduct);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpPayProductServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EventBusRestController
{
// FIXME: move MetasfreshRestAPIConstants to de.metas.util
public static final String ENDPOINT_API = "/api";
public static final String ENDPOINT = ENDPOINT_API + "/eventBus";
private final IEventBusFactory eventBusFactory;
public EventBusRestController(final IEventBusFactory eventBusFactory)
{
this.eventBusFactory = eventBusFactory;
}
@GetMapping
public JSONEventBusAggregatedStats getSummary(
@RequestParam(name = "topicName", required = false) final String topicName)
{
final List<IEventBus> eventBusInstances = getEventBusInstances(topicName);
return JSONEventBusAggregatedStats.builder()
.eventBusInstancesCount(eventBusInstances.size())
.eventBusInstances(toJSONEventBusStats(eventBusInstances))
.build();
}
private List<IEventBus> getEventBusInstances(@Nullable final String topicName)
{
if (!Check.isBlank(topicName))
{
final ArrayList<IEventBus> eventBusInstances = new ArrayList<>();
{
final IEventBus remoteEventBus = eventBusFactory.getEventBusIfExists(Topic.distributed(topicName));
if (remoteEventBus != null)
{
eventBusInstances.add(remoteEventBus);
}
}
{
final IEventBus localEventBus = eventBusFactory.getEventBusIfExists(Topic.local(topicName));
if (localEventBus != null) | {
eventBusInstances.add(localEventBus);
}
}
return eventBusInstances;
}
else
{
return eventBusFactory.getAllEventBusInstances();
}
}
private static ImmutableList<JSONEventBusStats> toJSONEventBusStats(final List<IEventBus> eventBusInstances)
{
return eventBusInstances.stream()
.map(eventBus -> toJSONEventBusStats(eventBus))
.collect(ImmutableList.toImmutableList());
}
private static JSONEventBusStats toJSONEventBusStats(final IEventBus eventBus)
{
final EventBusStats stats = eventBus.getStats();
final Topic eventBusTopic = eventBus.getTopic();
return JSONEventBusStats.builder()
.topicName(eventBusTopic.getName())
.type(eventBusTopic.getType())
.async(eventBus.isAsync())
.destroyed(eventBus.isDestroyed())
//
.eventsEnqueued(stats.getEventsEnqueued())
.eventsDequeued(stats.getEventsDequeued())
.eventsToDequeue(stats.getEventsToDequeue())
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\rest\EventBusRestController.java | 2 |
请完成以下Java代码 | private OAuth2AccessTokenResponse getTokenResponse(ClientRegistration clientRegistration,
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
try {
return this.accessTokenResponseClient.getTokenResponse(clientCredentialsGrantRequest);
}
catch (OAuth2AuthorizationException ex) {
throw new ClientAuthorizationException(ex.getError(), clientRegistration.getRegistrationId(), ex);
}
}
private boolean hasTokenExpired(OAuth2Token token) {
return this.clock.instant().isAfter(token.getExpiresAt().minus(this.clockSkew));
}
/**
* Sets the client used when requesting an access token credential at the Token
* Endpoint for the {@code client_credentials} grant.
* @param accessTokenResponseClient the client used when requesting an access token
* credential at the Token Endpoint for the {@code client_credentials} grant
*/
public void setAccessTokenResponseClient(
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
/**
* Sets the maximum acceptable clock skew, which is used when checking the | * {@link OAuth2AuthorizedClient#getAccessToken() access token} expiry. The default is
* 60 seconds.
*
* <p>
* An access token is considered expired if
* {@code OAuth2AccessToken#getExpiresAt() - clockSkew} is before the current time
* {@code clock#instant()}.
* @param clockSkew the maximum acceptable clock skew
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when checking the access
* token expiry.
* @param clock the clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\ClientCredentialsOAuth2AuthorizedClientProvider.java | 1 |
请完成以下Java代码 | default Collection<String> prefixes() {
return Collections.singleton(prefix());
}
/**
* The name of the method when used in an expression, like the second part of ${prefix:method()}.
* Will be used to match the text of the expression to the actual {@link FlowableFunctionDelegate} instance.
*/
String localName();
/**
* All the names of the method when used in an expression, like the second part of ${prefix:method()}.
* It allows one method to cover multiple local names.
* e.g. {@code ${prefix:method()}} or {@code ${prefix:alternativeMethod()}}.
* Will be used to match the text of the expression to the actual {@link FlowableFunctionDelegate} instance. | */
default Collection<String> localNames() {
return Collections.singleton(localName());
}
/**
* Returns the method that is invoked by JUEL.
*/
Method functionMethod() throws NoSuchMethodException;
default Method functionMethod(String prefix, String localName) throws NoSuchMethodException{
return functionMethod();
}
} | repos\flowable-engine-main\modules\flowable-engine-common-api\src\main\java\org\flowable\common\engine\api\delegate\FlowableFunctionDelegate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getSize() {
return this.size;
}
public void setSize(int size) {
this.size = size;
}
}
public static class Simple {
/**
* Set the maximum number of parallel accesses allowed. -1 indicates no
* concurrency limit at all.
*/
private @Nullable Integer concurrencyLimit;
public @Nullable Integer getConcurrencyLimit() {
return this.concurrencyLimit;
}
public void setConcurrencyLimit(@Nullable Integer concurrencyLimit) {
this.concurrencyLimit = concurrencyLimit;
}
}
public static class Shutdown {
/**
* Whether the executor should wait for scheduled tasks to complete on shutdown.
*/
private boolean awaitTermination;
/**
* Maximum time the executor should wait for remaining tasks to complete.
*/ | private @Nullable Duration awaitTerminationPeriod;
public boolean isAwaitTermination() {
return this.awaitTermination;
}
public void setAwaitTermination(boolean awaitTermination) {
this.awaitTermination = awaitTermination;
}
public @Nullable Duration getAwaitTerminationPeriod() {
return this.awaitTerminationPeriod;
}
public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) {
this.awaitTerminationPeriod = awaitTerminationPeriod;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingProperties.java | 2 |
请完成以下Java代码 | public String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
@Override
public void setVATCode (final @Nullable String VATCode)
{
set_Value (COLUMNNAME_VATCode, VATCode);
}
@Override
public String getVATCode()
{
return get_ValueAsString(COLUMNNAME_VATCode);
}
@Override
public org.compiere.model.I_C_CostClassification_Category getC_CostClassification_Category()
{
return get_ValueAsPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class);
}
@Override
public void setC_CostClassification_Category(final org.compiere.model.I_C_CostClassification_Category C_CostClassification_Category)
{
set_ValueFromPO(COLUMNNAME_C_CostClassification_Category_ID, org.compiere.model.I_C_CostClassification_Category.class, C_CostClassification_Category);
}
@Override
public void setC_CostClassification_Category_ID (final int C_CostClassification_Category_ID)
{
if (C_CostClassification_Category_ID < 1)
set_Value (COLUMNNAME_C_CostClassification_Category_ID, null);
else
set_Value (COLUMNNAME_C_CostClassification_Category_ID, C_CostClassification_Category_ID);
}
@Override
public int getC_CostClassification_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_Category_ID);
} | @Override
public org.compiere.model.I_C_CostClassification getC_CostClassification()
{
return get_ValueAsPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class);
}
@Override
public void setC_CostClassification(final org.compiere.model.I_C_CostClassification C_CostClassification)
{
set_ValueFromPO(COLUMNNAME_C_CostClassification_ID, org.compiere.model.I_C_CostClassification.class, C_CostClassification);
}
@Override
public void setC_CostClassification_ID (final int C_CostClassification_ID)
{
if (C_CostClassification_ID < 1)
set_Value (COLUMNNAME_C_CostClassification_ID, null);
else
set_Value (COLUMNNAME_C_CostClassification_ID, C_CostClassification_ID);
}
@Override
public int getC_CostClassification_ID()
{
return get_ValueAsInt(COLUMNNAME_C_CostClassification_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Fact_Acct_Transactions_View.java | 1 |
请完成以下Java代码 | public boolean createRating(Rating persisted) {
try {
valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted));
setOps.add("book-" + persisted.getBookId(), "rating-" + persisted.getId());
return true;
} catch (JsonProcessingException ex) {
return false;
}
}
public boolean updateRating(Rating persisted) {
try {
valueOps.set("rating-" + persisted.getId(), jsonMapper.writeValueAsString(persisted));
return true;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return false;
}
public boolean deleteRating(Long ratingId) {
Rating toDel;
try { | toDel = jsonMapper.readValue(valueOps.get("rating-" + ratingId), Rating.class);
setOps.remove("book-" + toDel.getBookId(), "rating-" + ratingId);
redisTemplate.delete("rating-" + ratingId);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
public void afterPropertiesSet() throws Exception {
this.redisTemplate = new StringRedisTemplate(cacheConnectionFactory);
this.valueOps = redisTemplate.opsForValue();
this.setOps = redisTemplate.opsForSet();
jsonMapper = new ObjectMapper();
jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\zipkin-log-svc-rating\src\main\java\com\baeldung\spring\cloud\bootstrap\svcrating\rating\RatingCacheRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Set<String> getPermissionsByOperatorId(Long operatorId) {
// 根据操作员Id查询出关联的所有角色id
String roleIds = pmsOperatorRoleService.getRoleIdsByOperatorId(operatorId);
String permissionIds = getActionIdsByRoleIds(roleIds);
Set<String> permissionSet = new HashSet<String>();
// 根据角色ID字符串得到该用户的所有权限拼成的字符串
if (!StringUtils.isEmpty(permissionIds)) {
List<PmsPermission> permissions = pmsPermissionDao.findByIds(permissionIds);
for (PmsPermission permission : permissions) {
permissionSet.add(permission.getPermission());
}
}
return permissionSet;
}
/**
* 根据角色ID集得到所有权限ID集
*
* @param roleIds
* @return actionIds
*/
private String getActionIdsByRoleIds(String roleIds) {
// 得到角色-权限表中roleiId在ids中的所有关联对象
List<PmsRolePermission> listRolePermission = pmsRolePermissionDao.listByRoleIds(roleIds); // 构建StringBuffer
StringBuffer actionIdsBuf = new StringBuffer("");
// 拼接字符串
for (PmsRolePermission pmsRolePermission : listRolePermission) {
actionIdsBuf.append(pmsRolePermission.getPermissionId()).append(",");
}
String actionIds = actionIdsBuf.toString();
// 截取字符串
if (StringUtils.isEmpty(actionIds) && actionIds.length() > 0) {
actionIds = actionIds.substring(0, actionIds.length() - 1); // 去掉最后一个逗号
}
return actionIds;
}
// /////////////////////////////下面:基本操作方法///////////////////////////////////////////////
/**
* 创建pmsOperator
*/
public void saveData(PmsRolePermission pmsRolePermission) {
pmsRolePermissionDao.insert(pmsRolePermission);
}
/**
* 修改pmsOperator
*/
public void updateData(PmsRolePermission pmsRolePermission) {
pmsRolePermissionDao.update(pmsRolePermission);
}
/**
* 根据id获取数据pmsOperator
*
* @param id
* @return
*/
public PmsRolePermission getDataById(Long id) {
return pmsRolePermissionDao.getById(id); | }
/**
* 分页查询pmsOperator
*
* @param pageParam
* @param ActivityVo
* PmsOperator
* @return
*/
public PageBean listPage(PageParam pageParam, PmsRolePermission pmsRolePermission) {
Map<String, Object> paramMap = new HashMap<String, Object>();
return pmsRolePermissionDao.listPage(pageParam, paramMap);
}
/**
* 保存角色和权限之间的关联关系
*/
@Transactional(rollbackFor = Exception.class)
public void saveRolePermission(Long roleId, String rolePermissionStr){
// 删除原来的角色与权限关联
pmsRolePermissionDao.deleteByRoleId(roleId);
if (!StringUtils.isEmpty(rolePermissionStr)) {
// 创建新的关联
String[] permissionIds = rolePermissionStr.split(",");
for (int i = 0; i < permissionIds.length; i++) {
Long permissionId = Long.valueOf(permissionIds[i]);
PmsRolePermission item = new PmsRolePermission();
item.setPermissionId(permissionId);
item.setRoleId(roleId);
pmsRolePermissionDao.insert(item);
}
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsRolePermissionServiceImpl.java | 2 |
请完成以下Java代码 | public class JMXQueueProcessor implements JMXQueueProcessorMBean
{
private final IQueueProcessor processor;
private final int queueProcessorId;
public JMXQueueProcessor(final IQueueProcessor processor, final int queueProcessorId)
{
this.processor = processor;
this.queueProcessorId = queueProcessorId;
}
@Override
public String getName()
{
return processor.getName();
}
@Override
public int getQueueProcessorId()
{
return queueProcessorId;
}
@Override
public long getCountAll()
{
return processor.getStatisticsSnapshot().getCountAll();
}
@Override
public long getCountProcessed() | {
return processor.getStatisticsSnapshot().getCountProcessed();
}
@Override
public long getCountErrors()
{
return processor.getStatisticsSnapshot().getCountErrors();
}
@Override
public long getCountSkipped()
{
return processor.getStatisticsSnapshot().getCountSkipped();
}
@Override
public String getQueueInfo()
{
return processor.getQueue().toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\jmx\JMXQueueProcessor.java | 1 |
请完成以下Java代码 | public class SubmitStartFormCmd implements Command<ProcessInstance>, Serializable {
private static final long serialVersionUID = 1L;
protected final String processDefinitionId;
protected final String businessKey;
protected VariableMap variables;
public SubmitStartFormCmd(String processDefinitionId, String businessKey, Map<String, Object> properties) {
this.processDefinitionId = processDefinitionId;
this.businessKey = businessKey;
this.variables = Variables.fromMap(properties);
}
@Override
public ProcessInstance execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache();
ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
ensureNotNull("No process definition found for id = '" + processDefinitionId + "'", "processDefinition", processDefinition);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkCreateProcessInstance(processDefinition);
} | ExecutionEntity processInstance = null;
if (businessKey != null) {
processInstance = processDefinition.createProcessInstance(businessKey);
} else {
processInstance = processDefinition.createProcessInstance();
}
processInstance.startWithFormProperties(variables);
commandContext.getOperationLogManager().logProcessInstanceOperation(
UserOperationLogEntry.OPERATION_TYPE_CREATE,
processInstance.getId(),
processInstance.getProcessDefinitionId(),
processInstance.getProcessDefinition().getKey(),
Collections.singletonList(PropertyChange.EMPTY_CHANGE));
return processInstance;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SubmitStartFormCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static Integer getIntegerFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Integer.valueOf(s);
}
return null;
}
public static Double getDoubleFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Double.valueOf(s);
}
return null;
}
public static Long getLongFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Long.valueOf(s);
} | return null;
}
public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName, Boolean defaultValue) {
Boolean value = getBooleanFromJson(objectNode, fieldName);
return value != null ? value : defaultValue;
}
public static Boolean getBooleanFromJson(ObjectNode objectNode, String fieldName) {
String s = getStringFromJson(objectNode, fieldName);
if (StringUtils.isNotEmpty(s)) {
return Boolean.valueOf(s);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\history\async\util\AsyncHistoryJsonUtil.java | 2 |
请完成以下Java代码 | public Object getValue() {
TypedValue typedValue = getTypedValue();
if (typedValue != null) {
return typedValue.getValue();
} else {
return null;
}
}
public T getTypedValue() {
return getTypedValue(true);
}
public T getTypedValue(boolean deserializeValue) {
if (cachedValue != null && cachedValue instanceof SerializableValue) {
SerializableValue serializableValue = (SerializableValue) cachedValue;
if(deserializeValue && !serializableValue.isDeserialized()) {
cachedValue = null;
}
}
if (cachedValue == null) {
cachedValue = getSerializer().readValue(typedValueField, deserializeValue);
if (cachedValue instanceof DeferredFileValueImpl) {
DeferredFileValueImpl fileValue = (DeferredFileValueImpl) cachedValue;
fileValue.setExecutionId(executionId);
fileValue.setVariableName(variableName);
}
}
return cachedValue;
}
@SuppressWarnings("unchecked")
public ValueMapper<T> getSerializer() { | if (serializer == null) {
serializer = mappers.findMapperForTypedValueField(typedValueField);
}
return serializer;
}
@Override
public String toString() {
return "VariableValue ["
+ "cachedValue=" + cachedValue + ", "
+ "executionId=" + executionId + ", "
+ "variableName=" + variableName + ", "
+ "typedValueField=" + typedValueField + "]";
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\VariableValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserDaoService {
// JPA/Hibernate > Database
// UserDaoService > Static List
private static List<User> users = new ArrayList<>();
private static int usersCount = 0;
static {
users.add(new User(++usersCount,"Adam",LocalDate.now().minusYears(30)));
users.add(new User(++usersCount,"Eve",LocalDate.now().minusYears(25)));
users.add(new User(++usersCount,"Jim",LocalDate.now().minusYears(20)));
}
public List<User> findAll() {
return users;
}
public User save(User user) {
user.setId(++usersCount); | users.add(user);
return user;
}
public User findOne(int id) {
Predicate<? super User> predicate = user -> user.getId().equals(id);
return users.stream().filter(predicate).findFirst().orElse(null);
}
public void deleteById(int id) {
Predicate<? super User> predicate = user -> user.getId().equals(id);
users.removeIf(predicate);
}
} | repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\user\UserDaoService.java | 2 |
请完成以下Java代码 | void swap(int i, int j) {
if (this.enabled != null) {
boolean temp = this.enabled.get(i);
this.enabled.set(i, this.enabled.get(j));
this.enabled.set(j, temp);
}
}
int get(int index) {
return isEnabled(index) ? this.offset : 0;
}
int enable(int index, boolean enable) {
if (this.enabled != null) {
this.enabled.set(index, enable);
}
return (!enable) ? 0 : this.offset; | }
boolean isEnabled(int index) {
return (this.enabled != null && this.enabled.get(index));
}
boolean hasAnyEnabled() {
return this.enabled != null && this.enabled.cardinality() > 0;
}
NameOffsetLookups emptyCopy() {
return new NameOffsetLookups(this.offset, this.enabled.size());
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\NameOffsetLookups.java | 1 |
请完成以下Java代码 | public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
} | public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
@Override
public String toString() {
return "Survey [id=" + id + ", title=" + title + ", description="
+ description + ", questions=" + questions + "]";
}
} | repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\java\com\in28minutes\springboot\model\Survey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@ApiModelProperty(value = "Can be any arbitrary value. When a valid formatted media-type (e.g. application/xml, text/plain) is included, the binary content HTTP response content-type will be set the given value.")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTaskUrl() {
return taskUrl;
} | public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public String getProcessInstanceUrl() {
return processInstanceUrl;
}
public void setProcessInstanceUrl(String processInstanceUrl) {
this.processInstanceUrl = processInstanceUrl;
}
@ApiModelProperty(value = "contentUrl:In case the attachment is a link to an external resource, the externalUrl contains the URL to the external content. If the attachment content is present in the Flowable engine, the contentUrl will contain an URL where the binary content can be streamed from.")
public String getExternalUrl() {
return externalUrl;
}
public void setExternalUrl(String externalUrl) {
this.externalUrl = externalUrl;
}
public String getContentUrl() {
return contentUrl;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\AttachmentResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DynamicTableAspect {
/**
* 定义切面拦截切入点
*/
@Pointcut("@annotation(org.jeecg.common.aspect.annotation.DynamicTable)")
public void dynamicTable() {
}
@Around("dynamicTable()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DynamicTable dynamicTable = method.getAnnotation(DynamicTable.class); | HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
//获取前端传递的版本标记
String version = request.getHeader(CommonConstant.VERSION);
//存储版本号到本地线程变量
ThreadLocalDataHelper.put(CommonConstant.VERSION, version);
//存储表名到本地线程变量
ThreadLocalDataHelper.put(CommonConstant.DYNAMIC_TABLE_NAME, dynamicTable.value());
//执行方法
Object result = point.proceed();
//清空本地变量
ThreadLocalDataHelper.clear();
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\mybatis\aspect\DynamicTableAspect.java | 2 |
请完成以下Java代码 | public PageData<ComponentDescriptor> findByTypeAndPageLink(TenantId tenantId, ComponentType type, PageLink pageLink) {
Validator.validatePageLink(pageLink);
return componentDescriptorDao.findByTypeAndPageLink(tenantId, type, pageLink);
}
@Override
public PageData<ComponentDescriptor> findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, PageLink pageLink) {
Validator.validatePageLink(pageLink);
return componentDescriptorDao.findByScopeAndTypeAndPageLink(tenantId, scope, type, pageLink);
}
@Override
public void deleteByClazz(TenantId tenantId, String clazz) {
Validator.validateString(clazz, "Incorrect clazz for delete request.");
componentDescriptorDao.deleteByClazz(tenantId, clazz);
}
@Override | public boolean validate(TenantId tenantId, ComponentDescriptor component, JsonNode configuration) {
try {
if (!component.getConfigurationDescriptor().has("schema")) {
throw new DataValidationException("Configuration descriptor doesn't contain schema property!");
}
JsonNode configurationSchema = component.getConfigurationDescriptor().get("schema");
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema schema = factory.getSchema(configurationSchema);
Set<ValidationMessage> validationMessages = schema.validate(configuration);
return validationMessages.isEmpty();
} catch (Exception e) {
throw new IncorrectParameterException(e.getMessage(), e);
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\component\BaseComponentDescriptorService.java | 1 |
请完成以下Java代码 | private I_C_Flatrate_Term createTermInOwnTrx()
{
final TrxCallable<I_C_Flatrate_Term> callable = () -> {
final I_C_Flatrate_Term term = PMMContractBuilder.newBuilder()
.setCtx(getCtx())
.setFailIfNotCreated(true)
.setComplete(true)
.setC_Flatrate_Conditions(p_C_Flatrate_Conditions)
.setC_BPartner(p_C_BPartner)
.setStartDate(p_StartDate)
.setEndDate(p_EndDate)
.setPMM_Product(p_PMM_Product)
.setC_UOM(p_C_UOM)
.setAD_User_InCharge(p_AD_User_Incharge)
.setCurrencyId(p_CurrencyId)
.setComplete(p_isComplete) // complete if flag on true, do not complete otherwise
.build();
return term;
};
// the default config is fine for us
final ITrxRunConfig config = trxManager.newTrxRunConfigBuilder().build();
return trxManager.call(ITrx.TRXNAME_None, config, callable);
}
/**
* If the given <code>parameterName</code> is {@value #PARAM_NAME_AD_USER_IN_CHARGE_ID},<br>
* then the method returns the user from {@link IPMMContractsBL#getDefaultContractUserInCharge_ID(Properties)}.
*/ | @Override
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final String parameterName = parameter.getColumnName();
if (!PARAM_NAME_AD_USER_IN_CHARGE_ID.equals(parameterName))
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
final int adUserInChargeId = pmmContractsBL.getDefaultContractUserInCharge_ID(getCtx());
if (adUserInChargeId < 0)
{
return DEFAULT_VALUE_NOTAVAILABLE;
}
return adUserInChargeId; // we need to return the ID, not the actual record. Otherwise then lookup logic will be confused.
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\process\C_Flatrate_Term_Create_ProcurementContract.java | 1 |
请完成以下Java代码 | public void addAttributeStorageFactoryClasses(final List<Class<? extends IAttributeStorageFactory>> factoryClasses)
{
if (factoryClasses == null || factoryClasses.isEmpty())
{
return;
}
for (final Class<? extends IAttributeStorageFactory> factoryClass : factoryClasses)
{
addAttributeStorageFactory(factoryClass);
}
}
@Override
public boolean isHandled(final Object model)
{
for (final IAttributeStorageFactory factory : factories)
{
if (factory.isHandled(model))
{
return true;
}
}
return false;
}
@Override
public IAttributeStorage getAttributeStorage(@NonNull final Object model)
{
final IAttributeStorage storage = getAttributeStorageIfHandled(model);
if (storage == null)
{
throw new AdempiereException("None of the registered factories can handle the given model")
.appendParametersToMessage()
.setParameter("model", model)
.setParameter("this instance", this);
}
return storage;
}
@Override
public IAttributeStorage getAttributeStorageIfHandled(final Object model)
{
for (final IAttributeStorageFactory factory : factories)
{
final IAttributeStorage storage = factory.getAttributeStorageIfHandled(model);
if (storage != null)
{
return storage;
}
}
return null;
}
@Override
public final IHUAttributesDAO getHUAttributesDAO() | {
Check.assumeNotNull(huAttributesDAO, "huAttributesDAO not null");
return huAttributesDAO;
}
@Override
public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
{
this.huAttributesDAO = huAttributesDAO;
for (final IAttributeStorageFactory factory : factories)
{
factory.setHUAttributesDAO(huAttributesDAO);
}
}
@Override
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
return huStorageFactory;
}
@Override
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
for (final IAttributeStorageFactory factory : factories)
{
factory.setHUStorageFactory(huStorageFactory);
}
}
@Override
public void flush()
{
for (final IAttributeStorageFactory factory : factories)
{
factory.flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static CredentialRecord toCredentialRecord(PasskeyCredential credential, Bytes userId) {
log.info("toCredentialRecord: credentialId={}, userId={}", credential.getCredentialId(), userId);
return ImmutableCredentialRecord.builder()
.userEntityUserId(userId)
.label(credential.getLabel())
.credentialType(PublicKeyCredentialType.valueOf(credential.getCredentialType()))
.credentialId(Bytes.fromBase64(credential.getCredentialId()))
.publicKey(ImmutablePublicKeyCose.fromBase64(credential.getPublicKeyCose()))
.signatureCount(credential.getSignatureCount())
.uvInitialized(credential.getUvInitialized())
.transports(asTransportSet(credential.getTransports()))
.backupEligible(credential.getBackupEligible())
.backupState(credential.getBackupState())
.attestationObject(Bytes.fromBase64(credential.getAttestationObject()))
.lastUsed(credential.getLastUsed())
.created(credential.getCreated())
.build();
}
private static Set<AuthenticatorTransport> asTransportSet(String transports) {
if ( transports == null || transports.isEmpty() ) {
return Set.of();
}
return Set.of(transports.split(","))
.stream()
.map(AuthenticatorTransport::valueOf) | .collect(Collectors.toSet());
}
private static PasskeyCredential toPasskeyCredential(PasskeyCredential credential, CredentialRecord credentialRecord, PasskeyUser user) {
credential.setUser(AggregateReference.to(user.getId()));
credential.setLabel(credentialRecord.getLabel());
credential.setCredentialType(credentialRecord.getCredentialType().getValue());
credential.setCredentialId(credentialRecord.getCredentialId().toBase64UrlString());
credential.setPublicKeyCose(Base64.getUrlEncoder().encodeToString(credentialRecord.getPublicKey().getBytes()));
credential.setSignatureCount(credentialRecord.getSignatureCount());
credential.setUvInitialized(credentialRecord.isUvInitialized());
credential.setTransports(credentialRecord.getTransports().stream().map(AuthenticatorTransport::getValue).collect(Collectors.joining(",")));
credential.setBackupEligible(credentialRecord.isBackupEligible());
credential.setBackupState(credentialRecord.isBackupState());
credential.setAttestationObject(credentialRecord.getAttestationObject().toBase64UrlString());
credential.setLastUsed(credentialRecord.getLastUsed());
credential.setCreated(credentialRecord.getCreated());
return credential;
}
private static PasskeyCredential toPasskeyCredential(CredentialRecord credentialRecord, PasskeyUser user) {
return toPasskeyCredential(new PasskeyCredential(),credentialRecord,user);
}
} | repos\tutorials-master\spring-security-modules\spring-security-passkey\src\main\java\com\baeldung\tutorials\passkey\repository\DbUserCredentialRepository.java | 2 |
请完成以下Java代码 | public List<String> getMimeTypes() {
return mimeTypes;
}
public List<String> getNames() {
return names;
}
public String getOutputStatement(String toDisplay) {
// We will use out:print function to output statements
StringBuilder stringBuffer = new StringBuilder();
stringBuffer.append("out:print(\"");
int length = toDisplay.length();
for (int i = 0; i < length; i++) {
char c = toDisplay.charAt(i);
switch (c) {
case '"':
stringBuffer.append("\\\"");
break;
case '\\':
stringBuffer.append("\\\\");
break;
default:
stringBuffer.append(c);
break;
}
}
stringBuffer.append("\")");
return stringBuffer.toString();
}
public String getParameter(String key) {
if (key.equals(ScriptEngine.NAME)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.ENGINE)) {
return getEngineName();
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return getEngineVersion();
} else if (key.equals(ScriptEngine.LANGUAGE)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return getLanguageVersion(); | } else if (key.equals("THREADING")) {
return "MULTITHREADED";
} else {
return null;
}
}
public String getProgram(String... statements) {
// Each statement is wrapped in '${}' to comply with EL
StringBuilder buf = new StringBuilder();
if (statements.length != 0) {
for (int i = 0; i < statements.length; i++) {
buf.append("${");
buf.append(statements[i]);
buf.append("} ");
}
}
return buf.toString();
}
public ScriptEngine getScriptEngine() {
return new JuelScriptEngine(this);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngineFactory.java | 1 |
请完成以下Java代码 | public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, Const.SECRET )
.compact();
}
public Boolean canTokenBeRefreshed(String token) {
return !isTokenExpired(token);
}
public String refreshToken(String token) {
String refreshedToken;
try {
final Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims); | } catch (Exception e) {
refreshedToken = null;
}
return refreshedToken;
}
public Boolean validateToken(String token, UserDetails userDetails) {
User user = (User) userDetails;
final String username = getUsernameFromToken(token);
return (
username.equals(user.getUsername())
&& !isTokenExpired(token)
);
}
} | repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\util\JwtTokenUtil.java | 1 |
请完成以下Java代码 | public int getSeqNo()
{
if (m_seqNo == -1)
getRegistrationAttribute();
return m_seqNo;
} // getSeqNo
/**
* Compare To
* @param o the Object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
public int compareTo (Object o)
{
if (o == null)
return 0;
MRegistrationValue oo = (MRegistrationValue)o; | int compare = getSeqNo() - oo.getSeqNo();
return compare;
} // compareTo
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append(getSeqNo()).append(": ")
.append(getRegistrationAttribute()).append("=").append(getName());
return sb.toString();
} // toString
} // MRegistrationValue | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistrationValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<Object> getUserById(@PathVariable Integer id) {
return new ResponseEntity<>(userService.getUserById(Long.valueOf(id)), HttpStatus.OK);
}
/**
* 通过spring data jpa 调用方法
* api :localhost:8099/users/byname?username=xxx
* 通过用户名查找用户
* @param request
* @return
*/
@RequestMapping(value = "/byname", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParam(paramType = "query",name= "username" ,value = "用户名",dataType = "string")
@ApiOperation(value = "通过用户名获取用户信息", notes="返回用户信息")
public ResponseEntity<Object> getUserByUserName(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
String username = (String) map.get("username");
return new ResponseEntity<>(userService.getUserByUserName(username), HttpStatus.OK);
}
/**
* 通过spring data jpa 调用方法
* api :localhost:8099/users/byUserNameContain?username=xxx
* 通过用户名模糊查询
* @param request
* @return
*/
@RequestMapping(value = "/byUserNameContain", method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParam(paramType = "query",name= "username" ,value = "用户名",dataType = "string")
@ApiOperation(value = "通过用户名模糊搜索用户信息", notes="返回用户信息")
public ResponseEntity<Object> getUsers(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
String username = (String) map.get("username");
return new ResponseEntity<>(userService.getByUsernameContaining(username), HttpStatus.OK);
}
/**
* 添加用户啊
* api :localhost:8099/users
*
* @param user
* @return | */
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiModelProperty(value="user",notes = "用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> saveUser(@RequestBody User user) {
return new ResponseEntity<>(userService.saveUser(user), HttpStatus.OK);
}
/**
* 修改用户信息
* api :localhost:8099/users
* @param user
* @return
*/
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
@ApiModelProperty(value="user",notes = "修改后用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> updateUser(@RequestBody User user) {
return new ResponseEntity<>(userService.updateUser(user), HttpStatus.OK);
}
/**
* 通过ID删除用户
* api :localhost:8099/users/2
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(value = "通过id删除用户信息", notes="返回删除状态1 成功 0 失败")
public ResponseEntity<Object> deleteUser(@PathVariable Integer id) {
return new ResponseEntity<>(userService.removeUser(id.longValue()), HttpStatus.OK);
}
} | repos\springBoot-master\springboot-swagger-ui\src\main\java\com\abel\example\controller\UserController.java | 2 |
请完成以下Java代码 | public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public org.compiere.model.I_S_Resource getPP_Plant()
{
return get_ValueAsPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setPP_Plant(final org.compiere.model.I_S_Resource PP_Plant)
{
set_ValueFromPO(COLUMNNAME_PP_Plant_ID, org.compiere.model.I_S_Resource.class, PP_Plant);
}
@Override
public void setPP_Plant_ID (final int PP_Plant_ID)
{
if (PP_Plant_ID < 1)
set_Value (COLUMNNAME_PP_Plant_ID, null);
else
set_Value (COLUMNNAME_PP_Plant_ID, PP_Plant_ID);
}
@Override
public int getPP_Plant_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Plant_ID);
}
@Override
public void setProductGroup (final @Nullable java.lang.String ProductGroup)
{
throw new IllegalArgumentException ("ProductGroup is virtual column"); }
@Override
public java.lang.String getProductGroup()
{
return get_ValueAsString(COLUMNNAME_ProductGroup); | }
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
throw new IllegalArgumentException ("ProductName is virtual column"); }
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setQtyCount (final BigDecimal QtyCount)
{
set_Value (COLUMNNAME_QtyCount, QtyCount);
}
@Override
public BigDecimal getQtyCount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_Fresh_QtyOnHand_Line.java | 1 |
请完成以下Java代码 | public byte[] getResourceData(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataById(resourceId.getId());
}
@Override
public byte[] getResourcePreview(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getPreviewById(resourceId.getId());
}
@Override
public long getResourceSize(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataSizeById(resourceId.getId());
}
@Override
public TbResourceDataInfo getResourceDataInfo(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataInfoById(resourceId.getId());
}
@Override
public Long sumDataSizeByTenantId(TenantId tenantId) {
return resourceRepository.sumDataSizeByTenantId(tenantId.getId());
}
@Override
public TbResource findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(resourceRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public PageData<TbResource> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink);
}
@Override | public PageData<TbResourceId> findIdsByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.pageToPageData(resourceRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink))
.map(TbResourceId::new));
}
@Override
public TbResourceId getExternalIdByInternal(TbResourceId internalId) {
return DaoUtil.toEntityId(resourceRepository.getExternalIdByInternal(internalId.getId()), TbResourceId::new);
}
@Override
public EntityType getEntityType() {
return EntityType.TB_RESOURCE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\resource\JpaTbResourceDao.java | 1 |
请完成以下Java代码 | public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Reversal Line.
@return Use to keep the reversal line ID for reversing costing purpose
*/
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
Durch QA verworfene Menge
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_ValueNoCheck (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return Durch QA verworfene Menge
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zielmenge. | @param TargetQty
Zielmenge der Warenbewegung
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
@return Zielmenge der Warenbewegung
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_M_InOutLine_Overview.java | 1 |
请完成以下Java代码 | public I_A_Registration getA_Registration() throws RuntimeException
{
return (I_A_Registration)MTable.get(getCtx(), I_A_Registration.Table_Name)
.getPO(getA_Registration_ID(), get_TrxName()); }
/** Set Registration.
@param A_Registration_ID
User Asset Registration
*/
public void setA_Registration_ID (int A_Registration_ID)
{
if (A_Registration_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Registration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Registration_ID, Integer.valueOf(A_Registration_ID));
}
/** Get Registration.
@return User Asset Registration
*/
public int getA_Registration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Registration_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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_RegistrationValue.java | 1 |
请完成以下Java代码 | public class User implements Serializable {
private static final long serialVersionUID = -2731598327208972274L;
private String username;
private String password;
private Set<String> role;
private Set<String> permission;
public User(String username, String password, Set<String> role, Set<String> permission) {
this.username = username;
this.password = password;
this.role = role;
this.permission = permission;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
} | public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<String> getRole() {
return role;
}
public void setRole(Set<String> role) {
this.role = role;
}
public Set<String> getPermission() {
return permission;
}
public void setPermission(Set<String> permission) {
this.permission = permission;
}
} | repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\domain\User.java | 1 |
请完成以下Java代码 | public class PmsMemberPrice implements Serializable {
private Long id;
private Long productId;
private Long memberLevelId;
@ApiModelProperty(value = "会员价格")
private BigDecimal memberPrice;
private String memberLevelName;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public Long getMemberLevelId() {
return memberLevelId;
}
public void setMemberLevelId(Long memberLevelId) {
this.memberLevelId = memberLevelId;
}
public BigDecimal getMemberPrice() {
return memberPrice;
} | public void setMemberPrice(BigDecimal memberPrice) {
this.memberPrice = memberPrice;
}
public String getMemberLevelName() {
return memberLevelName;
}
public void setMemberLevelName(String memberLevelName) {
this.memberLevelName = memberLevelName;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", memberLevelId=").append(memberLevelId);
sb.append(", memberPrice=").append(memberPrice);
sb.append(", memberLevelName=").append(memberLevelName);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsMemberPrice.java | 1 |
请完成以下Spring Boot application配置 | github.client.clientId=[CLIENT_ID]
github.client.clientSecret=[CLIENT_SECRET]
github.client.userAuthorizationUri=https://github.com/login/oauth/authorize
github.client.accessTokenUri=https://github.com/login/oauth/access_token
github.client.clientAuthenticationScheme=form
gi | thub.resource.userInfoUri=https://api.github.com/user
spring.thymeleaf.prefix=classpath:/templates/oauth2resttemplate/ | repos\tutorials-master\spring-security-modules\spring-security-oauth2\src\main\resources\application-oauth2-rest-template.properties | 2 |
请完成以下Java代码 | public void updateAllExecutionRelatedEntityCountFlags(boolean newValue) {
getDbSqlSession().directUpdate("updateExecutionRelatedEntityCountEnabled", newValue);
}
@Override
public void clearProcessInstanceLockTime(String processInstanceId) {
HashMap<String, Object> params = new HashMap<>();
params.put("id", processInstanceId);
getDbSqlSession().directUpdate("clearProcessInstanceLockTime", params);
}
@Override
public void clearAllProcessInstanceLockTimes(String lockOwner) {
HashMap<String, Object> params = new HashMap<>();
params.put("lockOwner", lockOwner);
getDbSqlSession().directUpdate("clearAllProcessInstanceLockTimes", params);
}
protected void setSafeInValueLists(ExecutionQueryImpl executionQuery) {
if (executionQuery.getInvolvedGroups() != null) {
executionQuery.setSafeInvolvedGroups(createSafeInValuesList(executionQuery.getInvolvedGroups()));
}
if (executionQuery.getProcessInstanceIds() != null) {
executionQuery.setSafeProcessInstanceIds(createSafeInValuesList(executionQuery.getProcessInstanceIds()));
}
if (executionQuery.getOrQueryObjects() != null && !executionQuery.getOrQueryObjects().isEmpty()) {
for (ExecutionQueryImpl orExecutionQuery : executionQuery.getOrQueryObjects()) {
setSafeInValueLists(orExecutionQuery);
} | }
}
protected void setSafeInValueLists(ProcessInstanceQueryImpl processInstanceQuery) {
if (processInstanceQuery.getProcessInstanceIds() != null) {
processInstanceQuery.setSafeProcessInstanceIds(createSafeInValuesList(processInstanceQuery.getProcessInstanceIds()));
}
if (processInstanceQuery.getInvolvedGroups() != null) {
processInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(processInstanceQuery.getInvolvedGroups()));
}
if (processInstanceQuery.getOrQueryObjects() != null && !processInstanceQuery.getOrQueryObjects().isEmpty()) {
for (ProcessInstanceQueryImpl orProcessInstanceQuery : processInstanceQuery.getOrQueryObjects()) {
setSafeInValueLists(orProcessInstanceQuery);
}
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisExecutionDataManager.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.