instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean has_Variable(final String variableName)
{
return params.hasParameter(variableName);
}
@SuppressWarnings("unchecked")
@Override
public <T> T get_ValueAsObject(final String variableName)
{
return (T)params.getParameterAsObject(variableName);
}
@Override
public BigDecimal get_ValueAsBigDecimal(final String variableName, final BigDecimal defaultValue)
{
final BigDecimal value = params.getParameterAsBigDecimal(variableName);
return value != null ? value : defaultValue;
}
@Override
public Boolean get_ValueAsBoolean(final String variableName, final Boolean defaultValue_IGNORED)
{
return params.getParameterAsBool(variableName);
}
@Override
public Date get_ValueAsDate(final String variableName, final Date defaultValue)
{
final Timestamp value = params.getParameterAsTimestamp(variableName);
return value != null ? value : defaultValue;
}
@Override
public Integer get_ValueAsInt(final String variableName, final Integer defaultValue)
{ | final int defaultValueInt = defaultValue != null ? defaultValue : 0;
return params.getParameterAsInt(variableName, defaultValueInt);
}
@Override
public String get_ValueAsString(final String variableName)
{
return params.getParameterAsString(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
return get_ValueAsString(variableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\Evaluatees.java | 1 |
请完成以下Java代码 | public void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
/**
* @return The ConnectionFactory that this accessor uses for obtaining RabbitMQ {@link Connection Connections}.
*/
public ConnectionFactory getConnectionFactory() {
return this.connectionFactory;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.connectionFactory, "ConnectionFactory is required");
}
/**
* Create a RabbitMQ Connection via this template's ConnectionFactory and its host and port values.
* @return the new RabbitMQ Connection
* @see ConnectionFactory#createConnection
*/
protected Connection createConnection() {
return this.connectionFactory.createConnection();
}
/**
* Fetch an appropriate Connection from the given RabbitResourceHolder.
*
* @param holder the RabbitResourceHolder
* @return an appropriate Connection fetched from the holder, or <code>null</code> if none found
*/
protected @Nullable Connection getConnection(RabbitResourceHolder holder) {
return holder.getConnection();
}
/**
* Fetch an appropriate Channel from the given RabbitResourceHolder.
*
* @param holder the RabbitResourceHolder | * @return an appropriate Channel fetched from the holder, or <code>null</code> if none found
*/
protected @Nullable Channel getChannel(RabbitResourceHolder holder) {
return holder.getChannel();
}
protected RabbitResourceHolder getTransactionalResourceHolder() {
return ConnectionFactoryUtils.getTransactionalResourceHolder(this.connectionFactory, isChannelTransacted());
}
protected RuntimeException convertRabbitAccessException(Exception ex) {
return RabbitExceptionTranslator.convertRabbitAccessException(ex);
}
protected void obtainObservationRegistry(@Nullable ApplicationContext appContext) {
if (appContext != null) {
ObjectProvider<ObservationRegistry> registry =
appContext.getBeanProvider(ObservationRegistry.class);
this.observationRegistry = registry.getIfUnique(() -> this.observationRegistry);
}
}
protected ObservationRegistry getObservationRegistry() {
return this.observationRegistry;
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitAccessor.java | 1 |
请完成以下Java代码 | public java.lang.String getDocBaseType ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocBaseType);
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
} | return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@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_C_DocLine_Sort.java | 1 |
请完成以下Java代码 | public static ROW setValue(@NonNull final GetValueRequest request, @Nullable final String newValue)
{
final COL col = extractCOL(request);
if (col == null)
{
throw new RuntimeException("Unable to find COL for request=" + request);
}
final Map<String, Integer> fieldName2Index = request.getFieldName2Index();
final Integer index = fieldName2Index.get(request.getFieldName());
final ROW rowToModify = request.getRow();
final ArrayList<COL> cols = new ArrayList<>(rowToModify.getCols());
cols.set(index, COL.of(newValue));
return rowToModify.toBuilder().clearCols().cols(cols).build(); | }
@Builder
@Getter
public static class GetValueRequest
{
@NonNull
private final ROW row;
@NonNull
private final Map<String, Integer> fieldName2Index;
@NonNull
private final String fieldName;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\FileMakerDataHelper.java | 1 |
请完成以下Java代码 | public List<Element> getAllTitles() {
try {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(this.getFile());
Element tutorials = doc.getRootElement();
List<Element> titles = tutorials.getChildren("tutorial");
return titles;
} catch (JDOMException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public Element getNodeById(String id) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(file);
String filter = "//*[@tutId='" + id + "']";
XPathFactory xFactory = XPathFactory.instance();
XPathExpression<Element> expr = xFactory.compile(filter, Filters.element());
List<Element> node = expr.evaluate(document); | return node.get(0);
} catch (JDOMException | IOException e) {
e.printStackTrace();
return null;
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\JDomParser.java | 1 |
请完成以下Java代码 | public static void propagateBpmnError(BpmnError error, ActivityExecution execution) throws Exception {
propagateError(error.getErrorCode(), error.getMessage(), null, execution);
}
public static void propagateError(String errorCode, String errorMessage, Exception origException, ActivityExecution execution) throws Exception {
ActivityExecutionHierarchyWalker walker = new ActivityExecutionHierarchyWalker(execution);
final ErrorDeclarationForProcessInstanceFinder errorDeclarationFinder = new ErrorDeclarationForProcessInstanceFinder(origException, errorCode, execution.getActivity());
ActivityExecutionMappingCollector activityExecutionMappingCollector = new ActivityExecutionMappingCollector(execution);
walker.addScopePreVisitor(errorDeclarationFinder);
walker.addExecutionPreVisitor(activityExecutionMappingCollector);
// map variables to super executions in the hierarchy of called process instances
walker.addExecutionPreVisitor(new OutputVariablesPropagator());
try {
walker.walkUntil(new ReferenceWalker.WalkCondition<ActivityExecutionTuple>() {
@Override
public boolean isFulfilled(ActivityExecutionTuple element) {
return errorDeclarationFinder.getErrorEventDefinition() != null || element == null;
}
});
} catch(Exception e) {
LOG.errorPropagationException(execution.getActivityInstanceId(), e);
// separate the exception handling to support a fail-safe error propagation
throw new ErrorPropagationException(e.getCause());
}
PvmActivity errorHandlingActivity = errorDeclarationFinder.getErrorHandlerActivity();
// process the error
if (errorHandlingActivity == null) { | if (origException == null) {
if (Context.getCommandContext().getProcessEngineConfiguration().isEnableExceptionsAfterUnhandledBpmnError()) {
throw LOG.missingBoundaryCatchEventError(execution.getActivity().getId(), errorCode, errorMessage);
} else {
LOG.missingBoundaryCatchEvent(execution.getActivity().getId(), errorCode, errorMessage);
execution.end(true);
}
} else {
// throw original exception
throw origException;
}
}
else {
ErrorEventDefinition errorDefinition = errorDeclarationFinder.getErrorEventDefinition();
PvmExecutionImpl errorHandlingExecution = activityExecutionMappingCollector.getExecutionForScope(errorHandlingActivity.getEventScope());
if(errorDefinition.getErrorCodeVariable() != null) {
errorHandlingExecution.setVariable(errorDefinition.getErrorCodeVariable(), errorCode);
}
if(errorDefinition.getErrorMessageVariable() != null) {
errorHandlingExecution.setVariable(errorDefinition.getErrorMessageVariable(), errorMessage);
}
errorHandlingExecution.executeActivity(errorHandlingActivity);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\BpmnExceptionHandler.java | 1 |
请完成以下Java代码 | public OrderItemBuilder dimension(final Dimension dimension)
{
innerBuilder.dimension(dimension);
return this;
}
public PurchaseOrderItem buildAndAddToParent()
{
final PurchaseOrderItem newItem = innerBuilder.build();
parent.purchaseOrderItems.add(newItem);
return newItem;
}
}
public OrderItemBuilder createOrderItem()
{
return new OrderItemBuilder(this);
}
/**
* Intended to be used by the persistence layer
*/
public void addLoadedPurchaseOrderItem(@NonNull final PurchaseOrderItem purchaseOrderItem)
{
final PurchaseCandidateId id = getId();
Check.assumeNotNull(id, "purchase candidate shall be saved: {}", this);
Check.assumeEquals(id, purchaseOrderItem.getPurchaseCandidateId(), | "The given purchaseOrderItem's purchaseCandidateId needs to be equal to this instance's id; purchaseOrderItem={}; this={}",
purchaseOrderItem, this);
purchaseOrderItems.add(purchaseOrderItem);
}
public Quantity getPurchasedQty()
{
return purchaseOrderItems.stream()
.map(PurchaseOrderItem::getPurchasedQty)
.reduce(Quantity::add)
.orElseGet(() -> getQtyToPurchase().toZero());
}
public List<PurchaseOrderItem> getPurchaseOrderItems()
{
return ImmutableList.copyOf(purchaseOrderItems);
}
public List<PurchaseErrorItem> getPurchaseErrorItems()
{
return ImmutableList.copyOf(purchaseErrorItems);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class CassandraAbstractAsyncDao extends CassandraAbstractDao {
protected ExecutorService readResultsProcessingExecutor;
@Value("${cassandra.query.result_processing_threads:50}")
private int threadPoolSize;
@PostConstruct
public void startExecutor() {
readResultsProcessingExecutor = ThingsBoardExecutors.newWorkStealingPool(threadPoolSize, "cassandra-callback");
}
@PreDestroy
public void stopExecutor() {
if (readResultsProcessingExecutor != null) {
readResultsProcessingExecutor.shutdownNow();
}
}
protected <T> ListenableFuture<T> getFuture(TbResultSetFuture future, java.util.function.Function<TbResultSet, T> transformer) {
return Futures.transform(future, new Function<TbResultSet, T>() {
@Nullable
@Override | public T apply(@Nullable TbResultSet input) {
return transformer.apply(input);
}
}, readResultsProcessingExecutor);
}
protected <T> ListenableFuture<T> getFutureAsync(TbResultSetFuture future, com.google.common.util.concurrent.AsyncFunction<TbResultSet, T> transformer) {
return Futures.transformAsync(future, new AsyncFunction<TbResultSet, T>() {
@Nullable
@Override
public ListenableFuture<T> apply(@Nullable TbResultSet input) {
try {
return transformer.apply(input);
} catch (Exception e) {
return Futures.immediateFailedFuture(e);
}
}
}, readResultsProcessingExecutor);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\nosql\CassandraAbstractAsyncDao.java | 2 |
请完成以下Java代码 | public java.math.BigDecimal getPrev_CurrentQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Prev_CurrentQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{ | set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_CostDetailAdjust.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceRef() {
return sourceRef;
}
public void setSourceRef(String sourceRef) {
this.sourceRef = sourceRef;
}
public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
}
public String getMessageRef() {
return messageRef;
}
public void setMessageRef(String messageRef) { | this.messageRef = messageRef;
}
public String toString() {
return sourceRef + " --> " + targetRef;
}
public MessageFlow clone() {
MessageFlow clone = new MessageFlow();
clone.setValues(this);
return clone;
}
public void setValues(MessageFlow otherFlow) {
super.setValues(otherFlow);
setName(otherFlow.getName());
setSourceRef(otherFlow.getSourceRef());
setTargetRef(otherFlow.getTargetRef());
setMessageRef(otherFlow.getMessageRef());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MessageFlow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GetCurrenciesRoute extends RouteBuilder
{
public static final String GET_CURRENCY_ROUTE_ID = "Shopware6-getCurrencies";
private final ProcessLogger processLogger;
public GetCurrenciesRoute(@NonNull final ProcessLogger processLogger)
{
this.processLogger = processLogger;
}
@Override
public void configure()
{
final CachingProvider cachingProvider = Caching.getCachingProvider();
final CacheManager cacheManager = cachingProvider.getCacheManager();
final MutableConfiguration<GetCurrenciesRequest, Object> config = new MutableConfiguration<>();
config.setTypes(GetCurrenciesRequest.class, Object.class);
config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.DAYS, 1)));
final Cache<GetCurrenciesRequest, Object> cache = cacheManager.createCache("currency", config);
final JCachePolicy jcachePolicy = new JCachePolicy();
jcachePolicy.setCache(cache);
from(direct(GET_CURRENCY_ROUTE_ID))
.id(GET_CURRENCY_ROUTE_ID)
.streamCache("true")
.policy(jcachePolicy)
.log("Route invoked. Results will be cached")
.process(this::getCurrencies);
}
private void getCurrencies(final Exchange exchange)
{
final GetCurrenciesRequest getCurrenciesRequest = exchange.getIn().getBody(GetCurrenciesRequest.class);
if (getCurrenciesRequest == null)
{
throw new RuntimeException("No getCurrenciesRequest provided!");
} | final PInstanceLogger pInstanceLogger = PInstanceLogger.of(processLogger);
final ShopwareClient shopwareClient = ShopwareClient
.of(getCurrenciesRequest.getClientId(), getCurrenciesRequest.getClientSecret(), getCurrenciesRequest.getBaseUrl(), pInstanceLogger);
final JsonCurrencies currencies = shopwareClient.getCurrencies();
if (CollectionUtils.isEmpty(currencies.getCurrencyList()))
{
throw new RuntimeException("No currencies return from Shopware!");
}
final ImmutableMap<String, String> currencyId2IsoCode = currencies.getCurrencyList().stream()
.collect(ImmutableMap.toImmutableMap(JsonCurrency::getId, JsonCurrency::getIsoCode));
final CurrencyInfoProvider currencyInfoProvider = CurrencyInfoProvider.builder()
.currencyId2IsoCode(currencyId2IsoCode)
.build();
exchange.getIn().setBody(currencyInfoProvider);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\currency\GetCurrenciesRoute.java | 2 |
请完成以下Java代码 | public int getPort() {
return randomPort;
}
public void startTomcat() throws LifecycleException {
tomcat = new Tomcat();
tomcat.setPort(randomPort);
tomcat.setHostname("localhost");
String appBase = ".";
tomcat.getHost().setAppBase(appBase);
File docBase = new File(System.getProperty("java.io.tmpdir"));
Context context = tomcat.addContext("", docBase.getAbsolutePath());
// add a servlet
Class servletClass = MyServlet.class;
Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName());
context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName());
// add a filter and filterMapping
Class filterClass = MyFilter.class;
FilterDef myFilterDef = new FilterDef();
myFilterDef.setFilterClass(filterClass.getName());
myFilterDef.setFilterName(filterClass.getSimpleName());
context.addFilterDef(myFilterDef); | FilterMap myFilterMap = new FilterMap();
myFilterMap.setFilterName(filterClass.getSimpleName());
myFilterMap.addURLPattern("/my-servlet/*");
context.addFilterMap(myFilterMap);
tomcat.start();
// uncomment for live test
// tomcat
// .getServer()
// .await();
}
public void stopTomcat() throws LifecycleException {
tomcat.stop();
tomcat.destroy();
}
} | repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\tomcat\ProgrammaticTomcat.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Map<PaymentTermId, List<I_C_PaymentTerm_Break>> retrievePaymentTermBreakRecords(@NonNull final Set<PaymentTermId> paymentTermIds)
{
if (paymentTermIds.isEmpty())
{
return ImmutableMap.of();
}
final Map<PaymentTermId, List<I_C_PaymentTerm_Break>> result = queryBL.createQueryBuilder(I_C_PaymentTerm_Break.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_C_PaymentTerm_Break.COLUMNNAME_C_PaymentTerm_ID, paymentTermIds)
.stream()
.collect(Collectors.groupingBy(PaymentTermBreakConverter::extractPaymentTermId, Collectors.toList()));
return CollectionUtils.fillMissingKeys(result, paymentTermIds, ImmutableList.of());
}
@NonNull
private List<I_C_PaySchedule> getPayScheduleRecords(@NonNull final PaymentTermId paymentTermId)
{
return CollectionUtils.getOrLoad(this.scheduleRecordsById, paymentTermId, this::retrievePayScheduleRecords);
}
@NonNull
private Map<PaymentTermId, List<I_C_PaySchedule>> retrievePayScheduleRecords(@NonNull final Set<PaymentTermId> paymentTermIds)
{
if (paymentTermIds.isEmpty())
{
return ImmutableMap.of();
}
final Map<PaymentTermId, List<I_C_PaySchedule>> result = queryBL.createQueryBuilder(I_C_PaySchedule.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_C_PaySchedule.COLUMNNAME_C_PaymentTerm_ID, paymentTermIds)
.stream()
.collect(Collectors.groupingBy(PayScheduleConverter::extractPaymentTermId, Collectors.toList()));
return CollectionUtils.fillMissingKeys(result, paymentTermIds, ImmutableList.of());
}
private PaymentTerm fromRecord(final I_C_PaymentTerm record)
{
@NonNull final PaymentTermId paymentTermId = PaymentTermConverter.extractId(record);
@NonNull final List<I_C_PaymentTerm_Break> breakRecords = getPaymentTermBreakRecords(paymentTermId);
@NonNull final List<I_C_PaySchedule> payScheduleRecords = getPayScheduleRecords(paymentTermId);
return PaymentTermConverter.fromRecord(record, breakRecords, payScheduleRecords);
}
private void saveToDB(final I_C_PaymentTerm record)
{
InterfaceWrapperHelper.saveRecord(record); | }
public void syncStateToDatabase(final Set<PaymentTermId> paymentTermIds)
{
if (paymentTermIds.isEmpty()) {return;}
trxManager.runInThreadInheritedTrx(() -> {
warmUpByIds(paymentTermIds);
for (final PaymentTermId paymentTermId : paymentTermIds)
{
final PaymentTerm paymentTerm = loadById(paymentTermId);
saveToDB(paymentTerm);
}
});
}
private void saveToDB(@NonNull final PaymentTerm paymentTerm)
{
final PaymentTermId paymentTermId = paymentTerm.getId();
final I_C_PaymentTerm record = getRecordById(paymentTermId);
PaymentTermConverter.updateRecord(record, paymentTerm);
saveToDB(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PaymentTermLoaderAndSaver.java | 2 |
请完成以下Java代码 | protected void initDao() {
if (this.createTableOnStartup) {
getTemplate().execute(CREATE_TABLE_SQL);
}
}
@Override
public void createNewToken(PersistentRememberMeToken token) {
getTemplate().update(this.insertTokenSql, token.getUsername(), token.getSeries(), token.getTokenValue(),
token.getDate());
}
@Override
public void updateToken(String series, String tokenValue, Date lastUsed) {
getTemplate().update(this.updateTokenSql, tokenValue, lastUsed, series);
}
/**
* Loads the token data for the supplied series identifier.
*
* If an error occurs, it will be reported and null will be returned (since the result
* should just be a failed persistent login).
* @param seriesId
* @return the token matching the series, or null if no match found or an exception
* occurred.
*/
@Override
public @Nullable PersistentRememberMeToken getTokenForSeries(String seriesId) {
try {
return getTemplate().queryForObject(this.tokensBySeriesSql, this::createRememberMeToken, seriesId);
}
catch (EmptyResultDataAccessException ex) {
this.logger.debug(LogMessage.format("Querying token for series '%s' returned no results.", seriesId), ex);
}
catch (IncorrectResultSizeDataAccessException ex) {
this.logger.error(LogMessage.format(
"Querying token for series '%s' returned more than one value. Series" + " should be unique",
seriesId));
} | catch (DataAccessException ex) {
this.logger.error("Failed to load token for series " + seriesId, ex);
}
return null;
}
private PersistentRememberMeToken createRememberMeToken(ResultSet rs, int rowNum) throws SQLException {
return new PersistentRememberMeToken(rs.getString(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4));
}
@Override
public void removeUserTokens(String username) {
getTemplate().update(this.removeUserTokensSql, username);
}
/**
* Intended for convenience in debugging. Will create the persistent_tokens database
* table when the class is initialized during the initDao method.
* @param createTableOnStartup set to true to execute the
*/
public void setCreateTableOnStartup(boolean createTableOnStartup) {
this.createTableOnStartup = createTableOnStartup;
}
private JdbcTemplate getTemplate() {
@Nullable JdbcTemplate result = super.getJdbcTemplate();
if (result == null) {
throw new IllegalStateException("JdbcTemplate was removed");
}
return result;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\rememberme\JdbcTokenRepositoryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JcaWorkManagerExecutorService implements Referenceable, ExecutorService {
public static int START_WORK_TIMEOUT = 1500;
private static Logger logger = Logger.getLogger(JcaWorkManagerExecutorService.class.getName());
protected final JcaExecutorServiceConnector ra;
protected WorkManager workManager;
public JcaWorkManagerExecutorService(JcaExecutorServiceConnector connector, WorkManager workManager) {
this.workManager = workManager;
this.ra = connector;
}
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunning(runnable);
} else {
return executeShortRunning(runnable);
}
}
protected boolean scheduleLongRunning(Runnable runnable) {
try {
workManager.scheduleWork(new JcaWorkRunnableAdapter(runnable));
return true;
} catch (WorkException e) {
logger.log(Level.WARNING, "Could not schedule : "+e.getMessage(), e);
return false;
}
}
protected boolean executeShortRunning(Runnable runnable) {
try {
workManager.startWork(new JcaWorkRunnableAdapter(runnable), START_WORK_TIMEOUT, null, null); | return true;
} catch (WorkRejectedException e) {
logger.log(Level.FINE, "WorkRejectedException while scheduling jobs for execution", e);
} catch (WorkException e) {
logger.log(Level.WARNING, "WorkException while scheduling jobs for execution", e);
}
return false;
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new JcaInflowExecuteJobsRunnable(jobIds, processEngine, ra);
}
// javax.resource.Referenceable /////////////////////////
protected Reference reference;
public Reference getReference() throws NamingException {
return reference;
}
public void setReference(Reference reference) {
this.reference = reference;
}
// getters / setters ////////////////////////////////////
public WorkManager getWorkManager() {
return workManager;
}
public JcaExecutorServiceConnector getPlatformJobExecutorConnector() {
return ra;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaWorkManagerExecutorService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private boolean isMatch(@Nullable String value, String requiredValue) {
if (StringUtils.hasLength(requiredValue)) {
return requiredValue.equalsIgnoreCase(value);
}
return !"false".equalsIgnoreCase(value);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("(");
result.append(this.prefix);
if (this.names.length == 1) {
result.append(this.names[0]);
} | else {
result.append("[");
result.append(StringUtils.arrayToCommaDelimitedString(this.names));
result.append("]");
}
if (StringUtils.hasLength(this.havingValue)) {
result.append("=").append(this.havingValue);
}
result.append(")");
return result.toString();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\OnPropertyCondition.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void initDbSqlSessionFactory(AbstractEngineConfiguration engineConfiguration, AbstractEngineConfiguration targetEngineConfiguration) {
DbSqlSessionFactory dbSqlSessionFactory = engineConfiguration.getDbSqlSessionFactory();
targetEngineConfiguration.setDbSqlSessionFactory(engineConfiguration.getDbSqlSessionFactory());
targetEngineConfiguration.setSqlSessionFactory(engineConfiguration.getSqlSessionFactory());
if (getEntityInsertionOrder() != null) {
// remove identity link and variable entity classes due to foreign key handling
dbSqlSessionFactory.getInsertionOrder().remove(IdentityLinkEntityImpl.class);
dbSqlSessionFactory.getInsertionOrder().remove(VariableInstanceEntityImpl.class);
dbSqlSessionFactory.getInsertionOrder().removeIf(ByteArrayEntityImpl.class::equals);
for (Class<? extends Entity> clazz : getEntityInsertionOrder()) {
dbSqlSessionFactory.getInsertionOrder().add(clazz);
}
}
if (getEntityDeletionOrder() != null) {
// remove identity link and variable entity classes due to foreign key handling
dbSqlSessionFactory.getDeletionOrder().remove(IdentityLinkEntityImpl.class);
dbSqlSessionFactory.getDeletionOrder().remove(VariableInstanceEntityImpl.class);
dbSqlSessionFactory.getDeletionOrder().removeIf(ByteArrayEntityImpl.class::equals);
for (Class<? extends Entity> clazz : getEntityDeletionOrder()) {
dbSqlSessionFactory.getDeletionOrder().add(clazz);
}
}
}
@Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
}
@Override
protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
}
@Override
protected ProcessEngine buildEngine() {
if (processEngineConfiguration == null) { | throw new FlowableException("ProcessEngineConfiguration is required");
}
return processEngineConfiguration.buildProcessEngine();
}
public ProcessEngineConfiguration getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public ProcessEngineConfigurator setProcessEngineConfiguration(ProcessEngineConfiguration processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
return this;
}
protected JobServiceConfiguration getJobServiceConfiguration(AbstractEngineConfiguration engineConfiguration) {
if (engineConfiguration.getServiceConfigurations().containsKey(EngineConfigurationConstants.KEY_JOB_SERVICE_CONFIG)) {
return (JobServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_JOB_SERVICE_CONFIG);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-configurator\src\main\java\org\flowable\engine\configurator\ProcessEngineConfigurator.java | 2 |
请完成以下Java代码 | private boolean proxyReceptorRequest(HttpServletRequest request) {
final boolean result = proxyReceptorConfigured() && this.proxyReceptorMatcher.matches(request);
this.logger.debug(LogMessage.format("proxyReceptorRequest = %s", result));
return result;
}
/**
* Determines if the {@link CasAuthenticationFilter} is configured to handle the proxy
* receptor requests.
* @return
*/
private boolean proxyReceptorConfigured() {
final boolean result = this.proxyGrantingTicketStorage != null && this.proxyReceptorMatcher != null;
this.logger.debug(LogMessage.format("proxyReceptorConfigured = %s", result));
return result;
}
/**
* A wrapper for the AuthenticationFailureHandler that will flex the
* {@link AuthenticationFailureHandler} that is used. The value
* {@link CasAuthenticationFilter#setProxyAuthenticationFailureHandler(AuthenticationFailureHandler)}
* will be used for proxy requests that fail. The value
* {@link CasAuthenticationFilter#setAuthenticationFailureHandler(AuthenticationFailureHandler)}
* will be used for service tickets that fail.
*/
private class CasAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final AuthenticationFailureHandler serviceTicketFailureHandler; | CasAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler");
this.serviceTicketFailureHandler = failureHandler;
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
if (serviceTicketRequest(request, response)) {
this.serviceTicketFailureHandler.onAuthenticationFailure(request, response, exception);
}
else {
CasAuthenticationFilter.this.proxyFailureHandler.onAuthenticationFailure(request, response, exception);
}
}
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\web\CasAuthenticationFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | BeanDefinition getCsrfAuthenticationStrategy() {
BeanDefinitionBuilder csrfAuthenticationStrategy = BeanDefinitionBuilder
.rootBeanDefinition(CsrfAuthenticationStrategy.class);
csrfAuthenticationStrategy.addConstructorArgReference(this.csrfRepositoryRef);
if (StringUtils.hasText(this.requestHandlerRef)) {
csrfAuthenticationStrategy.addPropertyReference("requestHandler", this.requestHandlerRef);
}
return csrfAuthenticationStrategy.getBeanDefinition();
}
BeanDefinition getCsrfLogoutHandler() {
BeanDefinitionBuilder csrfAuthenticationStrategy = BeanDefinitionBuilder
.rootBeanDefinition(CsrfLogoutHandler.class);
csrfAuthenticationStrategy.addConstructorArgReference(this.csrfRepositoryRef);
return csrfAuthenticationStrategy.getBeanDefinition();
}
void setIgnoreCsrfRequestMatchers(List<BeanDefinition> requestMatchers) {
if (!requestMatchers.isEmpty()) {
BeanMetadataElement requestMatcher = (!StringUtils.hasText(this.requestMatcherRef))
? new RootBeanDefinition(DefaultRequiresCsrfMatcher.class)
: new RuntimeBeanReference(this.requestMatcherRef);
BeanDefinitionBuilder and = BeanDefinitionBuilder.rootBeanDefinition(AndRequestMatcher.class);
BeanDefinitionBuilder negated = BeanDefinitionBuilder.rootBeanDefinition(NegatedRequestMatcher.class);
BeanDefinitionBuilder or = BeanDefinitionBuilder.rootBeanDefinition(OrRequestMatcher.class);
or.addConstructorArgValue(requestMatchers);
negated.addConstructorArgValue(or.getBeanDefinition());
List<BeanMetadataElement> ands = new ManagedList<>();
ands.add(requestMatcher);
ands.add(negated.getBeanDefinition());
and.addConstructorArgValue(ands);
this.csrfFilter.getPropertyValues().add("requireCsrfProtectionMatcher", and.getBeanDefinition());
} | }
void setObservationRegistry(BeanMetadataElement observationRegistry) {
this.observationRegistry = observationRegistry;
}
private static final class DefaultRequiresCsrfMatcher implements RequestMatcher {
private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
@Override
public boolean matches(HttpServletRequest request) {
return !this.allowedMethods.contains(request.getMethod());
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\CsrfBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public void setServiceFeeAmount (final @Nullable BigDecimal ServiceFeeAmount)
{
set_Value (COLUMNNAME_ServiceFeeAmount, ServiceFeeAmount);
}
@Override
public BigDecimal getServiceFeeAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ServiceFeeAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setServiceFeeAmount_Currency_ID (final int ServiceFeeAmount_Currency_ID)
{
if (ServiceFeeAmount_Currency_ID < 1)
set_Value (COLUMNNAME_ServiceFeeAmount_Currency_ID, null);
else
set_Value (COLUMNNAME_ServiceFeeAmount_Currency_ID, ServiceFeeAmount_Currency_ID);
}
@Override
public int getServiceFeeAmount_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_ServiceFeeAmount_Currency_ID);
}
@Override
public void setServiceFeeExternalInvoiceDocumentNo (final @Nullable java.lang.String ServiceFeeExternalInvoiceDocumentNo)
{
set_Value (COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo, ServiceFeeExternalInvoiceDocumentNo);
}
@Override
public java.lang.String getServiceFeeExternalInvoiceDocumentNo()
{
return get_ValueAsString(COLUMNNAME_ServiceFeeExternalInvoiceDocumentNo);
}
@Override
public void setServiceFeeInvoicedDate (final @Nullable java.sql.Timestamp ServiceFeeInvoicedDate)
{
set_Value (COLUMNNAME_ServiceFeeInvoicedDate, ServiceFeeInvoicedDate);
}
@Override
public java.sql.Timestamp getServiceFeeInvoicedDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ServiceFeeInvoicedDate);
}
@Override
public void setSource_BP_BankAccount_ID (final int Source_BP_BankAccount_ID)
{ | if (Source_BP_BankAccount_ID < 1)
set_Value (COLUMNNAME_Source_BP_BankAccount_ID, null);
else
set_Value (COLUMNNAME_Source_BP_BankAccount_ID, Source_BP_BankAccount_ID);
}
@Override
public int getSource_BP_BankAccount_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_BP_BankAccount_ID);
}
@Override
public void setSource_BPartner_ID (final int Source_BPartner_ID)
{
if (Source_BPartner_ID < 1)
set_Value (COLUMNNAME_Source_BPartner_ID, null);
else
set_Value (COLUMNNAME_Source_BPartner_ID, Source_BPartner_ID);
}
@Override
public int getSource_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RemittanceAdvice.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Reservierte Menge.
@param QtyReserved
Reservierte Menge
*/
public void setQtyReserved (BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
/** Get Reservierte Menge.
@return Reservierte Menge
*/
public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Revenue Recognition Amt.
@param RRAmt
Revenue Recognition Amount
*/
public void setRRAmt (BigDecimal RRAmt)
{
set_Value (COLUMNNAME_RRAmt, RRAmt);
}
/** Get Revenue Recognition Amt.
@return Revenue Recognition Amount
*/
public BigDecimal getRRAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RRAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Revenue Recognition Start.
@param RRStartDate
Revenue Recognition Start Date
*/
public void setRRStartDate (Timestamp RRStartDate)
{
set_Value (COLUMNNAME_RRStartDate, RRStartDate);
}
/** Get Revenue Recognition Start.
@return Revenue Recognition Start Date
*/
public Timestamp getRRStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_RRStartDate);
}
public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException
{
return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name)
.getPO(getRef_OrderLine_ID(), get_TrxName()); }
/** Set Referenced Order Line.
@param Ref_OrderLine_ID
Reference to corresponding Sales/Purchase Order
*/
public void setRef_OrderLine_ID (int Ref_OrderLine_ID) | {
if (Ref_OrderLine_ID < 1)
set_Value (COLUMNNAME_Ref_OrderLine_ID, null);
else
set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID));
}
/** Get Referenced Order Line.
@return Reference to corresponding Sales/Purchase Order
*/
public int getRef_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ressourcenzuordnung.
@param S_ResourceAssignment_ID
Ressourcenzuordnung
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_Value (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Ressourcenzuordnung.
@return Ressourcenzuordnung
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java | 1 |
请完成以下Java代码 | private void writeTradeData(MarketData data) {
try {
final int writtenBytes = MarketDataUtil.encodeAndWrite(buffer, data);
writePos.addAndGet(writtenBytes);
log.info("<writeTradeData> buffer size remaining: %{}, data: {}", 100 * buffer.remaining() / buffer.capacity(), data);
} catch (IndexOutOfBoundsException e) {
buffer.clear(); // ring buffer
writeTradeData(data);
} catch (Exception e) {
log.error("<writeTradeData> cannot write into buffer {}", buffer);
}
}
private void run(MarketDataSource source) {
writerThread.scheduleAtFixedRate(() -> { | if (source.hasNext()) {
writeTradeData(source.next());
}
}, 1, 2, TimeUnit.SECONDS);
}
public static void main(String[] args) {
MarketDataStreamServer server = new MarketDataStreamServer();
Client client1 = server.newClient("client1");
client1.read();
Client client2 = server.newClient("client2");
client2.read();
server.run(new MarketDataSource());
}
} | repos\tutorials-master\libraries-3\src\main\java\com\baeldung\sbe\MarketDataStreamServer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductActivityProvider implements IProductActivityProvider
{
private final IAcctSchemaDAO acctSchemaDAO = Services.get(IAcctSchemaDAO.class);
private final ProductAccountsRepository productAccountsRepository;
public ProductActivityProvider(
@NonNull final ProductAccountsRepository productAccountsRepository)
{
this.productAccountsRepository = productAccountsRepository;
}
@VisibleForTesting
public static ProductActivityProvider createInstanceForUnitTesting()
{
return new ProductActivityProvider(new ProductAccountsRepository());
} | @Override
@Nullable
public ActivityId retrieveActivityForAcct(final ClientId clientId, final OrgId orgId, final ProductId productId)
{
final AcctSchemaId acctSchemaId = acctSchemaDAO.getAcctSchemaIdByClientAndOrg(clientId, orgId);
if (acctSchemaId == null)
{
return null;
}
return productAccountsRepository.getAccountsIfExists(productId, acctSchemaId)
.flatMap(ProductAccounts::getActivityId)
.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\ProductActivityProvider.java | 2 |
请完成以下Java代码 | public class TaxAuthorisation1 {
@XmlElement(name = "Titl")
protected String titl;
@XmlElement(name = "Nm")
protected String nm;
/**
* Gets the value of the titl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitl() {
return titl;
}
/**
* Sets the value of the titl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitl(String value) {
this.titl = value;
} | /**
* Gets the value of the nm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
this.nm = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxAuthorisation1.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HistoricMilestoneInstanceQueryRequest extends PaginateRequest {
private String id;
private String name;
private String caseInstanceId;
private String caseDefinitionId;
private Date reachedBefore;
private Date reachedAfter;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseDefinitionId() { | return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public Date getReachedBefore() {
return reachedBefore;
}
public void setReachedBefore(Date reachedBefore) {
this.reachedBefore = reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public void setReachedAfter(Date reachedAfter) {
this.reachedAfter = reachedAfter;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\milestone\HistoricMilestoneInstanceQueryRequest.java | 2 |
请完成以下Java代码 | public void endElement(final String nameSpaceUri, final String localName, final String qName)
throws SAXException {
if (ATTRIBUTES.equals(localName)) {
this.foundAttributes = false;
this.currentAttribute = null;
} else if (this.foundAttributes) {
final Object o = this.attributes.get(this.currentAttribute);
if (o == null) {
this.attributes.put(this.currentAttribute, this.value.toString());
} else {
final List<Object> items;
if (o instanceof List) {
items = (List<Object>) o;
} else {
items = new LinkedList<Object>();
items.add(o);
this.attributes.put(this.currentAttribute, items);
}
items.add(this.value.toString());
}
}
}
public Map<String, Object> getAttributes() {
return this.attributes;
}
}
public static void main(String[] args) { | String result = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n" +
" <cas:authenticationSuccess>\r\n" +
" <cas:user>admin</cas:user>\r\n" +
" <cas:attributes>\r\n" +
" <cas:credentialType>UsernamePasswordCredential</cas:credentialType>\r\n" +
" <cas:isFromNewLogin>true</cas:isFromNewLogin>\r\n" +
" <cas:authenticationDate>2019-08-01T19:33:21.527+08:00[Asia/Shanghai]</cas:authenticationDate>\r\n" +
" <cas:authenticationMethod>RestAuthenticationHandler</cas:authenticationMethod>\r\n" +
" <cas:successfulAuthenticationHandlers>RestAuthenticationHandler</cas:successfulAuthenticationHandlers>\r\n" +
" <cas:longTermAuthenticationRequestTokenUsed>false</cas:longTermAuthenticationRequestTokenUsed>\r\n" +
" </cas:attributes>\r\n" +
" </cas:authenticationSuccess>\r\n" +
"</cas:serviceResponse>";
String errorRes = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n" +
" <cas:authenticationFailure code=\"INVALID_TICKET\">未能够识别出目标 'ST-5-1g-9cNES6KXNRwq-GuRET103sm0-DESKTOP-VKLS8B3'票根</cas:authenticationFailure>\r\n" +
"</cas:serviceResponse>";
String error = XmlUtils.getTextForElement(errorRes, "authenticationFailure");
//System.out.println("------"+error);
String error2 = XmlUtils.getTextForElement(result, "authenticationFailure");
//System.out.println("------"+error2);
String principal = XmlUtils.getTextForElement(result, "user");
//System.out.println("---principal---"+principal);
Map<String, Object> attributes = XmlUtils.extractCustomAttributes(result);
System.out.println("---attributes---"+attributes);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\XmlUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTaskScheduler(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
/**
* Set how often to run a task to check for failed consumers and idle containers.
* @param monitorInterval the interval; default 10000, but it will be adjusted down
* to the smallest of this, {@link #setIdleEventInterval(Long) idleEventInterval} / 2
* (if configured) or
* {@link #setFailedDeclarationRetryInterval(Long) failedDeclarationRetryInterval}.
*/
public void setMonitorInterval(long monitorInterval) {
this.monitorInterval = monitorInterval;
}
/**
* Each queue runs in its own consumer; set this property to create multiple
* consumers for each queue.
* If the container is already running, the number of consumers per queue will
* be adjusted up or down as necessary.
* @param consumersPerQueue the consumers per queue.
*/
public void setConsumersPerQueue(Integer consumersPerQueue) {
this.consumersPerQueue = consumersPerQueue;
}
/**
* Set the number of messages to receive before acknowledging (success).
* A failed message will short-circuit this counter.
* @param messagesPerAck the number of messages.
* @see #setAckTimeout(Long)
*/
public void setMessagesPerAck(Integer messagesPerAck) {
this.messagesPerAck = messagesPerAck;
}
/**
* An approximate timeout; when {@link #setMessagesPerAck(Integer) messagesPerAck} is
* greater than 1, and this time elapses since the last ack, the pending acks will be
* sent either when the next message arrives, or a short time later if no additional | * messages arrive. In that case, the actual time depends on the
* {@link #setMonitorInterval(long) monitorInterval}.
* @param ackTimeout the timeout in milliseconds (default 20000);
* @see #setMessagesPerAck(Integer)
*/
public void setAckTimeout(Long ackTimeout) {
this.ackTimeout = ackTimeout;
}
@Override
protected DirectMessageListenerContainer createContainerInstance() {
return new DirectMessageListenerContainer();
}
@Override
protected void initializeContainer(DirectMessageListenerContainer instance,
@Nullable RabbitListenerEndpoint endpoint) {
super.initializeContainer(instance, endpoint);
JavaUtils javaUtils = JavaUtils.INSTANCE.acceptIfNotNull(this.taskScheduler, instance::setTaskScheduler)
.acceptIfNotNull(this.monitorInterval, instance::setMonitorInterval)
.acceptIfNotNull(this.messagesPerAck, instance::setMessagesPerAck)
.acceptIfNotNull(this.ackTimeout, instance::setAckTimeout);
if (endpoint != null && endpoint.getConcurrency() != null) {
try {
instance.setConsumersPerQueue(Integer.parseInt(endpoint.getConcurrency()));
}
catch (NumberFormatException e) {
throw new IllegalStateException("Failed to parse concurrency: " + e.getMessage(), e);
}
}
else {
javaUtils.acceptIfNotNull(this.consumersPerQueue, instance::setConsumersPerQueue);
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\DirectRabbitListenerContainerFactory.java | 2 |
请完成以下Java代码 | public Object handleInvocation(ConnectorInvocation invocation) throws Exception {
request = invocation.getRequest();
target = invocation.getTarget();
if (proceed) {
return invocation.proceed();
} else {
return response;
}
}
public void setProceed(boolean proceed) {
this.proceed = proceed;
}
public boolean isProceed() {
return proceed;
}
public void setResponse(Object response) { | this.response = response;
}
@SuppressWarnings("unchecked")
public <T> T getResponse() {
return (T) response;
}
@SuppressWarnings("unchecked")
public <T extends ConnectorRequest<?>> T getRequest() {
return (T) request;
}
@SuppressWarnings("unchecked")
public <T> T getTarget() {
return (T) target;
}
} | repos\camunda-bpm-platform-master\connect\core\src\main\java\org\camunda\connect\impl\DebugRequestInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Question {
@Id
private UUID id;
private String content;
@Convert(converter = YesNoConverter.class)
private Boolean correctAnswer;
@Convert(converter = TrueFalseConverter.class)
private Boolean shouldBeAsked;
@Convert(converter = NumericBooleanConverter.class)
private Boolean isEasy;
private Boolean wasAskedBefore;
public Question() {
}
public Question(UUID id, String content, Boolean correctAnswer, Boolean shouldBeAsked, Boolean isEasy, Boolean wasAskedBefore) {
this.id = id;
this.content = content;
this.correctAnswer = correctAnswer;
this.shouldBeAsked = shouldBeAsked;
this.isEasy = isEasy;
this.wasAskedBefore = wasAskedBefore;
}
public UUID getId() {
return id;
}
public String getContent() {
return content;
}
public Boolean getCorrectAnswer() {
return correctAnswer;
}
public Boolean getShouldBeAsked() {
return shouldBeAsked; | }
public Boolean isEasy() {
return isEasy;
}
public Boolean getWasAskedBefore() {
return wasAskedBefore;
}
public void setId(UUID id) {
this.id = id;
}
public void setContent(String content) {
this.content = content;
}
public void setCorrectAnswer(Boolean correctAnswer) {
this.correctAnswer = correctAnswer;
}
public void setShouldBeAsked(Boolean shouldBeAsked) {
this.shouldBeAsked = shouldBeAsked;
}
public void setEasy(Boolean easy) {
isEasy = easy;
}
public void setWasAskedBefore(Boolean wasAskedBefore) {
this.wasAskedBefore = wasAskedBefore;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\booleanconverters\model\Question.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ModuleActivatorDescriptorsRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
public ModuleActivatorDescriptorsCollection getDescriptors()
{
final ImmutableList<ModuleActivatorDescriptor> descriptors = queryBL.createQueryBuilderOutOfTrx(I_AD_ModelValidator.class)
// .addOnlyActiveRecordsFilter() // retrieve ALL
.orderBy(I_AD_ModelValidator.COLUMNNAME_SeqNo)
.orderBy(I_AD_ModelValidator.COLUMNNAME_AD_ModelValidator_ID)
.create()
.stream()
.map(record -> toModelInterceptorDescriptorOrNull(record))
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return ModuleActivatorDescriptorsCollection.of(descriptors);
}
private static ModuleActivatorDescriptor toModelInterceptorDescriptorOrNull(@NonNull final I_AD_ModelValidator record) | {
final String modelValidationClass = record.getModelValidationClass();
if (Check.isEmpty(modelValidationClass, true))
{
return null;
}
return ModuleActivatorDescriptor.builder()
.id(record.getAD_ModelValidator_ID())
.classname(modelValidationClass.trim())
.seqNo(record.getSeqNo())
.active(record.isActive())
.entityType(record.getEntityType())
.description(record.getDescription())
.created(TimeUtil.asInstant(record.getCreated()))
.lastUpdated(TimeUtil.asInstant(record.getUpdated()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModuleActivatorDescriptorsRepository.java | 2 |
请完成以下Java代码 | public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) { | this.birthday = birthday;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
public long getIncome() {
return income;
}
public void setIncome(long income) {
this.income = income;
}
@Override
public String toString() {
return "User [name=" + name + ", email=" + email + ", gender=" + gender + ", password=" + password
+ ", profession=" + profession + ", note=" + note + ", birthday=" + birthday + ", married=" + married
+ ", income=" + income + "]";
}
} | repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringBootFormValidationJSP\src\main\java\spring\validation\model\User.java | 1 |
请完成以下Java代码 | public FinishedGoodsReceiveLine getFinishedGoodsReceiveLineById(@NonNull final FinishedGoodsReceiveLineId finishedGoodsReceiveLineId)
{
return activities.stream()
.map(ManufacturingJobActivity::getFinishedGoodsReceive)
.filter(Objects::nonNull)
.map(finishedGoodsReceive -> finishedGoodsReceive.getLineByIdOrNull(finishedGoodsReceiveLineId))
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new AdempiereException("No finished goods receive line found for " + finishedGoodsReceiveLineId));
}
public ManufacturingJob withCurrentScaleDevice(@Nullable final DeviceId currentScaleDeviceId)
{
return !DeviceId.equals(this.currentScaleDeviceId, currentScaleDeviceId)
? toBuilder().currentScaleDeviceId(currentScaleDeviceId).build()
: this;
}
@NonNull
public LocalDate getDateStartScheduleAsLocalDate()
{
return dateStartSchedule.toLocalDate();
}
@NonNull
public ManufacturingJob withChangedRawMaterialIssue(@NonNull final UnaryOperator<RawMaterialsIssue> mapper)
{
final ImmutableList<ManufacturingJobActivity> updatedActivities = activities | .stream()
.map(activity -> activity.withChangedRawMaterialsIssue(mapper))
.collect(ImmutableList.toImmutableList());
return withActivities(updatedActivities);
}
public Stream<RawMaterialsIssueLine> streamRawMaterialsIssueLines()
{
return activities.stream()
.filter(ManufacturingJobActivity::isRawMaterialsIssue)
.map(ManufacturingJobActivity::getRawMaterialsIssue)
.filter(Objects::nonNull)
.flatMap(rawMaterialsIssue -> rawMaterialsIssue.getLines().stream());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJob.java | 1 |
请完成以下Java代码 | public void createNew(
@NonNull final OrderAndLineId orderAndLineId,
@NonNull final OrgId orgId,
@NonNull final OrderLineDetailCreateRequest request)
{
final I_C_OrderLine_Detail record = InterfaceWrapperHelper.newInstance(I_C_OrderLine_Detail.class);
record.setC_Order_ID(orderAndLineId.getOrderRepoId());
record.setC_OrderLine_ID(orderAndLineId.getOrderLineRepoId());
record.setAD_Org_ID(orgId.getRepoId());
record.setM_Product_ID(request.getProductId().getRepoId());
record.setC_UOM_ID(request.getQty().getUomId().getRepoId());
record.setQty(request.getQty().toBigDecimal());
record.setPrice(request.getPrice().toBigDecimal());
record.setAmount(request.getAmount().toBigDecimal());
record.setDescription(request.getDescription());
InterfaceWrapperHelper.saveRecord(record);
}
public void deleteByOrderId(@NonNull final OrderId orderId) | {
queryBL.createQueryBuilder(I_C_OrderLine_Detail.class)
.addEqualsFilter(I_C_OrderLine_Detail.COLUMNNAME_C_Order_ID, orderId)
.create()
.deleteDirectly();
}
public void deleteByOrderLineId(@NonNull final OrderAndLineId orderAndLineId)
{
queryBL.createQueryBuilder(I_C_OrderLine_Detail.class)
.addEqualsFilter(I_C_OrderLine_Detail.COLUMNNAME_C_Order_ID, orderAndLineId.getOrderId())
.addEqualsFilter(I_C_OrderLine_Detail.COLUMNNAME_C_OrderLine_ID, orderAndLineId.getOrderLineId())
.create()
.deleteDirectly();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLineDetailRepository.java | 1 |
请完成以下Java代码 | public class OrderPOReferenceListener implements IDocumentNoListener
{
public static OrderPOReferenceListener INSTANCE = new OrderPOReferenceListener();
private OrderPOReferenceListener()
{
}
@Override
public String getTableName()
{
return I_C_Order.Table_Name;
}
/**
* If the given order has a <code>DocumentNo</code> and no <code>POReference</code> and if the order's <code>C_BPartner</code> is configured accordingly, then this method sets the given order's
* <code>POReference</code>.<br>
* Notes:
* <ul>
* <li>the order is not saved
* <li>calling this method from a model validator generally does not work well, because the (definite) documentNo itself is set when the order is changed, and the order might still have its old
* documentNo value.
* </ul>
*
* @param order
* @task http://dewiki908/mediawiki/index.php/09776_EDI_-_Customer_with_INVOIC_but_without_%28ORDERS%2C_DESADV%29_%28100584995833%29
*/
@Override
public void onDocumentNoChange(IDocumentNoAware model, String newDocumentNo)
{ | final I_C_Order order = InterfaceWrapperHelper.create(model, I_C_Order.class);
if (!Check.isEmpty(order.getPOReference(), true))
{
return; // the POReference is already set.
}
final String documentNo = order.getDocumentNo();
if(Check.isEmpty(documentNo, true))
{
return; // there is no documentNo to work with
}
final I_C_BPartner bpartner = Services.get(IOrderBL.class).getBPartner(order);
if (!bpartner.isCreateDefaultPOReference())
{
return; // the BPartner doesn't want us to set it
}
final String poReferencePattern = bpartner.getPOReferencePattern();
final String poReference = StringUtils.overlayAtEnd(poReferencePattern, documentNo);
order.setPOReference(poReference);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\document\documentNo\OrderPOReferenceListener.java | 1 |
请完成以下Java代码 | public static MobileApplicationPermissions ofCollection(final Collection<MobileApplicationPermission> collection)
{
return collection.isEmpty() ? EMPTY : new MobileApplicationPermissions(collection);
}
public static Collector<MobileApplicationPermission, ?, MobileApplicationPermissions> collect()
{
return GuavaCollectors.collectUsingListAccumulator(MobileApplicationPermissions::ofCollection);
}
public static MobileApplicationPermissions merge(
@NonNull final MobileApplicationPermissions permissions1,
@NonNull final MobileApplicationPermissions permissions2,
@NonNull final PermissionsBuilder.CollisionPolicy collisionPolicy)
{
return merge(Arrays.asList(permissions1, permissions2), collisionPolicy);
}
public static MobileApplicationPermissions merge(
@NonNull final List<MobileApplicationPermissions> permissionsList,
@NonNull final PermissionsBuilder.CollisionPolicy collisionPolicy)
{
final HashedMap<MobileApplicationRepoId, MobileApplicationPermission> resultMap = new HashedMap<>();
for (final MobileApplicationPermissions permissions : permissionsList)
{
if (permissions == null)
{
continue;
}
if (resultMap.isEmpty())
{
resultMap.putAll(permissions.byMobileApplicationId);
}
else
{
for (final MobileApplicationPermission permission : permissions.byMobileApplicationId.values())
{
final MobileApplicationRepoId mobileApplicationId = permission.getMobileApplicationId();
final MobileApplicationPermission existingPermission = resultMap.get(mobileApplicationId);
final MobileApplicationPermission newPermission = MobileApplicationPermission.merge(existingPermission, permission, collisionPolicy);
resultMap.put(mobileApplicationId, newPermission);
}
}
} | return MobileApplicationPermissions.ofCollection(resultMap.values());
}
@Override
public String toString()
{
final String permissionsName = getClass().getSimpleName();
final Collection<MobileApplicationPermission> permissionsList = byMobileApplicationId.values();
final StringBuilder sb = new StringBuilder();
sb.append(permissionsName).append(": ");
if (permissionsList.isEmpty())
{
sb.append("@NoRestrictions@");
}
else
{
sb.append(Env.NL);
}
Joiner.on(Env.NL)
.skipNulls()
.appendTo(sb, permissionsList);
return sb.toString();
}
public boolean isAllowAccess(@NonNull final MobileApplicationRepoId mobileApplicationId)
{
final MobileApplicationPermission permission = byMobileApplicationId.get(mobileApplicationId);
return permission != null && permission.isAllowAccess();
}
public boolean isAllowAction(@NonNull final MobileApplicationRepoId mobileApplicationId, @NonNull final MobileApplicationActionId actionId)
{
final MobileApplicationPermission permission = byMobileApplicationId.get(mobileApplicationId);
return permission != null && permission.isAllowAction(actionId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\mobile_application\MobileApplicationPermissions.java | 1 |
请完成以下Java代码 | public static void createStdPeriods(final I_C_Year yearRecord, Locale locale, final Timestamp startDate, String dateFormat)
{
final Properties ctx = Env.getCtx();
final int calendarId = yearRecord.getC_Calendar_ID();
final int yearId = yearRecord.getC_Year_ID();
if (locale == null)
{
final MClient client = MClient.get(ctx);
locale = client.getLocale();
}
if (locale == null && Language.getLoginLanguage() != null)
{
locale = Language.getLoginLanguage().getLocale();
}
if (locale == null)
{
locale = Env.getLanguage(ctx).getLocale();
}
//
SimpleDateFormat formatter;
if (dateFormat == null || dateFormat.equals(""))
{
dateFormat = "MMM-yy";
}
formatter = new SimpleDateFormat(dateFormat, locale);
//
int year = getYearAsInt(yearRecord.getFiscalYear());
final GregorianCalendar cal = new GregorianCalendar(locale);
if (startDate != null)
{
cal.setTime(startDate);
if (cal.get(Calendar.YEAR) != year)
{
year = cal.get(Calendar.YEAR);
}
}
else
{
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
}
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
//
for (int month = 0; month < 12; month++)
{ | final Timestamp start = new Timestamp(cal.getTimeInMillis());
final String name = formatter.format(start);
// get last day of same month
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DAY_OF_YEAR, -1);
final Timestamp end = new Timestamp(cal.getTimeInMillis());
//
MPeriod period = MPeriod.findByCalendar(ctx, start, calendarId, ITrx.TRXNAME_ThreadInherited);
if (period == null)
{
period = new MPeriod(yearRecord, month + 1, name, start, end);
}
else
{
period.setC_Year_ID(yearId);
period.setPeriodNo(month + 1);
period.setName(name);
period.setStartDate(start);
period.setEndDate(end);
}
period.saveEx(ITrx.TRXNAME_ThreadInherited); // Creates Period Control
// get first day of next month
cal.add(Calendar.DAY_OF_YEAR, 1);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MYear.java | 1 |
请完成以下Java代码 | public JSONLookupValue getLanguage()
{
final Language language = userSession.getLanguage();
return JSONLookupValue.of(language.getAD_Language(), language.getName());
}
@GetMapping("/workplace")
public JsonGetWorkplaceResponse getWorkplace(@RequestParam(name = "includeAvailable", required = false) final boolean includeAvailable)
{
userSession.assertLoggedIn();
final boolean isWorkplacesEnabled = userSession.isWorkplacesEnabled();
if (isWorkplacesEnabled)
{
final JsonGetWorkplaceResponseBuilder builder = JsonGetWorkplaceResponse.builder().workplacesEnabled(true);
userSession.getWorkplace()
.map(UserSessionRestController::toJSONLookupValue)
.ifPresent(builder::currentWorkplace);
if (includeAvailable)
{
builder.available(workplaceService.getAllActive()
.stream()
.map(UserSessionRestController::toJSONLookupValue)
.sorted(Comparator.comparing(JSONLookupValue::getCaption))
.collect(ImmutableList.toImmutableList()));
}
return builder.build();
}
else
{
return JsonGetWorkplaceResponse.NOT_ENABLED;
}
}
private static JSONLookupValue toJSONLookupValue(@NonNull Workplace workplace)
{
return JSONLookupValue.of(workplace.getId(), workplace.getName()); | }
@PutMapping("/workplace")
public void setWorkplace(@RequestBody @NonNull final JsonChangeWorkplaceRequest request)
{
userSession.assertLoggedIn();
if (!userSession.isWorkplacesEnabled())
{
throw new AdempiereException("Workplaces not enabled");
}
workplaceService.assignWorkplace(WorkplaceAssignmentCreateRequest.builder()
.workplaceId(request.getWorkplaceId())
.userId(userSession.getLoggedUserId())
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSessionRestController.java | 1 |
请完成以下Java代码 | private void fireAdditionListener(final K key, final V value)
{
logger.debug("fireAdditionListener - Item added; key={}; value={}", key, value);
if (additionListener != null)
{
additionListener.itemAdded(key, value);
}
}
/**
* Add all key/value pairs to this cache.
*
* @param map key/value pairs
*/
public void putAll(final Map<? extends K, ? extends V> map)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
cache.putAll(map);
for (final Entry<? extends K, ? extends V> entry : map.entrySet())
{
fireAdditionListener(entry.getKey(), entry.getValue());
}
}
}
/**
* @see java.util.Map#isEmpty()
*/
public boolean isEmpty()
{
return cache.size() == 0;
} // isEmpty
/**
* @see java.util.Map#keySet()
*/
public Set<K> keySet()
{
return cache.asMap().keySet();
} // keySet
/**
* @see java.util.Map#size()
*/
@Override
public long size()
{
return cache.size(); | } // size
/**
* @see java.util.Map#values()
*/
public Collection<V> values()
{
return cache.asMap().values();
} // values
@Override
protected final void finalize() throws Throwable
{
// NOTE: to avoid memory leaks we need to programatically clear our internal state
try (final IAutoCloseable ignored = CacheMDC.putCache(this))
{
logger.debug("Running finalize");
cache.invalidateAll();
}
}
public CCacheStats stats()
{
final CacheStats guavaStats = cache.stats();
return CCacheStats.builder()
.cacheId(cacheId)
.name(cacheName)
.labels(labels)
.config(config)
.debugAcquireStacktrace(debugAcquireStacktrace)
//
.size(cache.size())
.hitCount(guavaStats.hitCount())
.missCount(guavaStats.missCount())
.build();
}
private boolean isNoCache()
{
return allowDisablingCacheByThreadLocal && ThreadLocalCacheController.instance.isNoCache();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCache.java | 1 |
请完成以下Java代码 | public Builder setIncludedViewLayout(final IncludedViewLayout includedViewLayout)
{
this.includedViewLayout = includedViewLayout;
return this;
}
public Builder clearViewCloseActions()
{
allowedViewCloseActions = new LinkedHashSet<>();
return this;
}
public Builder allowViewCloseAction(@NonNull final ViewCloseAction viewCloseAction)
{
if (allowedViewCloseActions == null)
{
allowedViewCloseActions = new LinkedHashSet<>();
}
allowedViewCloseActions.add(viewCloseAction);
return this;
}
private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions()
{
return allowedViewCloseActions != null
? ImmutableSet.copyOf(allowedViewCloseActions)
: DEFAULT_allowedViewCloseActions;
}
public Builder setHasTreeSupport(final boolean hasTreeSupport)
{
this.hasTreeSupport = hasTreeSupport;
return this; | }
public Builder setTreeCollapsible(final boolean treeCollapsible)
{
this.treeCollapsible = treeCollapsible;
return this;
}
public Builder setTreeExpandedDepth(final int treeExpandedDepth)
{
this.treeExpandedDepth = treeExpandedDepth;
return this;
}
public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails)
{
this.allowOpeningRowDetails = allowOpeningRowDetails;
return this;
}
public Builder setFocusOnFieldName(final String focusOnFieldName)
{
this.focusOnFieldName = focusOnFieldName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java | 1 |
请完成以下Java代码 | public final void closeAllGroups()
{
final GroupType exceptGroup = null; // no exception
closeAllGroupsExcept(exceptGroup);
}
/**
* Close all groups, but not the last used one. Last used one is considered that group where we added last item.
*/
public final void closeAllGroupExceptLastUsed()
{
closeAllGroupsExcept(_lastGroupUsed);
}
/**
* Close all groups.
*
* @param exceptGroup optional group to except from closing
*/
private void closeAllGroupsExcept(@Nullable final GroupType exceptGroup)
{
final Iterator<GroupType> groups = _itemHashKey2group.values().iterator();
while (groups.hasNext())
{
final GroupType group = groups.next();
if (group == null)
{
continue; | }
// Skip the excepted group
if (group == exceptGroup)
{
continue;
}
closeGroupAndCollect(group);
groups.remove();
}
}
/**
* @return how many groups were created
*/
public final int getGroupsCount()
{
return _countGroups;
}
/**
* @return how many items were added
*/
public final int getItemsCount()
{
return _countItems;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MapReduceAggregator.java | 1 |
请完成以下Java代码 | public class EchoMultiServer {
private static final Logger LOG = LoggerFactory.getLogger(EchoMultiServer.class);
private ServerSocket serverSocket;
public void start(int port) {
try {
serverSocket = new ServerSocket(port);
while (true)
new EchoClientHandler(serverSocket.accept()).start();
} catch (IOException e) {
e.printStackTrace();
} finally {
stop();
}
}
public void stop() {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static class EchoClientHandler extends Thread {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public EchoClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine; | while ((inputLine = in.readLine()) != null) {
if (".".equals(inputLine)) {
out.println("bye");
break;
}
out.println(inputLine);
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
LOG.debug(e.getMessage());
}
}
}
public static void main(String[] args) {
EchoMultiServer server = new EchoMultiServer();
server.start(5555);
}
} | repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\socket\EchoMultiServer.java | 1 |
请完成以下Java代码 | public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx)
{
processor.setTrxItemProcessorCtx(processorCtx);
}
@Override
public RT getResult()
{
return processor.getResult();
}
@Override
public void process(final IT item) throws Exception
{
itemsPerBatch++;
processor.process(item);
}
@Override
public boolean isSameChunk(final IT item)
{
// If we are about to exceed the maximum number of items per batch
// => return false (we need a new chunk/batch)
if (itemsPerBatch >= maxItemsPerBatch)
{
return false;
}
//
// Ask processor is the item is on the same chunk, if this is allowed.
if (!ignoreProcessorIsSameChunkMethod)
{
return processor.isSameChunk(item);
}
// Consider this item on same chunk
return true;
} | @Override
public void newChunk(final IT item)
{
itemsPerBatch = 0;
processor.newChunk(item);
}
@Override
public void completeChunk()
{
processor.completeChunk();
}
@Override
public void cancelChunk()
{
processor.cancelChunk();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\FixedBatchTrxItemProcessor.java | 1 |
请完成以下Java代码 | public Stat exists(String path, Watcher watcher) {
try {
return zkClient.exists(path, watcher);
} catch (Exception e) {
log.error("【node exception】{},{}", path, e);
return null;
}
}
/**
* create persist node
*
* @param path
* @param data
*/
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 void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Nullable
public URI getUrl() {
return url;
}
public void setUrl(@Nullable URI url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Nullable
public String getRoom() {
return room; | }
public void setRoom(@Nullable String room) {
this.room = room;
}
@Nullable
public String getToken() {
return token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\LetsChatNotifier.java | 1 |
请完成以下Java代码 | public HistoryEvent createCaseActivityInstanceEndEvt(DelegateCaseExecution caseExecution) {
final CaseExecutionEntity caseExecutionEntity = (CaseExecutionEntity) caseExecution;
// create event instance
HistoricCaseActivityInstanceEventEntity evt = loadCaseActivityInstanceEventEntity(caseExecutionEntity);
// initialize event
initCaseActivityInstanceEvent(evt, caseExecutionEntity, HistoryEventTypes.CASE_ACTIVITY_INSTANCE_END);
// set end time
evt.setEndTime(ClockUtil.getCurrentTime());
// calculate duration
if (evt.getStartTime() != null) {
evt.setDurationInMillis(evt.getEndTime().getTime() - evt.getStartTime().getTime());
}
return evt;
}
protected HistoricCaseInstanceEventEntity newCaseInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) {
return new HistoricCaseInstanceEventEntity();
}
protected HistoricCaseInstanceEventEntity loadCaseInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) {
return newCaseInstanceEventEntity(caseExecutionEntity);
}
protected void initCaseInstanceEvent(HistoricCaseInstanceEventEntity evt, CaseExecutionEntity caseExecutionEntity, HistoryEventTypes eventType) {
evt.setId(caseExecutionEntity.getCaseInstanceId());
evt.setEventType(eventType.getEventName());
evt.setCaseDefinitionId(caseExecutionEntity.getCaseDefinitionId());
evt.setCaseInstanceId(caseExecutionEntity.getCaseInstanceId());
evt.setCaseExecutionId(caseExecutionEntity.getId());
evt.setBusinessKey(caseExecutionEntity.getBusinessKey());
evt.setState(caseExecutionEntity.getState());
evt.setTenantId(caseExecutionEntity.getTenantId());
}
protected HistoricCaseActivityInstanceEventEntity newCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) {
return new HistoricCaseActivityInstanceEventEntity();
}
protected HistoricCaseActivityInstanceEventEntity loadCaseActivityInstanceEventEntity(CaseExecutionEntity caseExecutionEntity) {
return newCaseActivityInstanceEventEntity(caseExecutionEntity); | }
protected void initCaseActivityInstanceEvent(HistoricCaseActivityInstanceEventEntity evt, CaseExecutionEntity caseExecutionEntity, HistoryEventTypes eventType) {
evt.setId(caseExecutionEntity.getId());
evt.setParentCaseActivityInstanceId(caseExecutionEntity.getParentId());
evt.setEventType(eventType.getEventName());
evt.setCaseDefinitionId(caseExecutionEntity.getCaseDefinitionId());
evt.setCaseInstanceId(caseExecutionEntity.getCaseInstanceId());
evt.setCaseExecutionId(caseExecutionEntity.getId());
evt.setCaseActivityInstanceState(caseExecutionEntity.getState());
evt.setRequired(caseExecutionEntity.isRequired());
evt.setCaseActivityId(caseExecutionEntity.getActivityId());
evt.setCaseActivityName(caseExecutionEntity.getActivityName());
evt.setCaseActivityType(caseExecutionEntity.getActivityType());
evt.setTenantId(caseExecutionEntity.getTenantId());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\DefaultCmmnHistoryEventProducer.java | 1 |
请完成以下Java代码 | private String createElasticJsonRecord(AuditLog auditLog) {
ObjectNode auditLogNode = JacksonUtil.newObjectNode();
auditLogNode.put("postDate", LocalDateTime.now().toString());
auditLogNode.put("id", auditLog.getId().getId().toString());
auditLogNode.put("entityName", auditLog.getEntityName());
auditLogNode.put("tenantId", auditLog.getTenantId().getId().toString());
if (auditLog.getCustomerId() != null) {
auditLogNode.put("customerId", auditLog.getCustomerId().getId().toString());
}
auditLogNode.put("entityId", auditLog.getEntityId().getId().toString());
auditLogNode.put("entityType", auditLog.getEntityId().getEntityType().name());
auditLogNode.put("userId", auditLog.getUserId().getId().toString());
auditLogNode.put("userName", auditLog.getUserName());
auditLogNode.put("actionType", auditLog.getActionType().name());
if (auditLog.getActionData() != null) {
auditLogNode.put("actionData", auditLog.getActionData().toString());
}
auditLogNode.put("actionStatus", auditLog.getActionStatus().name());
auditLogNode.put("actionFailureDetails", auditLog.getActionFailureDetails());
return auditLogNode.toString();
}
private ResponseListener responseListener = new ResponseListener() { | @Override
public void onSuccess(Response response) {
log.trace("Elasticsearch sink log action method succeeded. Response result [{}]!", response);
}
@Override
public void onFailure(Exception exception) {
log.warn("Elasticsearch sink log action method failed!", exception);
}
};
private String getIndexName(TenantId tenantId) {
String indexName = indexPattern;
if (indexName.contains(TENANT_PLACEHOLDER) && tenantId != null) {
indexName = indexName.replace(TENANT_PLACEHOLDER, tenantId.getId().toString());
}
if (indexName.contains(DATE_PLACEHOLDER)) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
indexName = indexName.replace(DATE_PLACEHOLDER, now.format(formatter));
}
return indexName.toLowerCase();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\audit\sink\ElasticsearchAuditLogSink.java | 1 |
请完成以下Java代码 | public String getDisplayName()
{
return inOut.getDocumentNo();
}
@Override
public List<IHUDocumentLine> getLines()
{
return lines;
}
private MInOutHUDocument reversal = null;
@Override
public MInOutHUDocument getReversal() | {
if (reversal == null)
{
reversal = new MInOutHUDocument(inOut.getReversal(), getReversalLines());
reversal.setReversal(this);
}
return reversal;
}
private void setReversal(final MInOutHUDocument reversal)
{
this.reversal = reversal;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\MInOutHUDocument.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class OnMetricsExportEnabledCondition extends SpringBootCondition {
private static final String PROPERTY_TEMPLATE = "management.%s.metrics.export.enabled";
private static final String DEFAULT_PROPERTY_NAME = "management.defaults.metrics.export.enabled";
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
AnnotationAttributes annotationAttributes = AnnotationAttributes
.fromMap(metadata.getAnnotationAttributes(ConditionalOnEnabledMetricsExport.class.getName()));
Assert.state(annotationAttributes != null, "'annotationAttributes' must not be null");
String endpointName = annotationAttributes.getString("value");
ConditionOutcome outcome = getProductOutcome(context, endpointName);
if (outcome != null) {
return outcome;
}
return getDefaultOutcome(context);
}
private @Nullable ConditionOutcome getProductOutcome(ConditionContext context, String productName) {
Environment environment = context.getEnvironment();
String enabledProperty = PROPERTY_TEMPLATE.formatted(productName);
if (environment.containsProperty(enabledProperty)) {
boolean match = environment.getProperty(enabledProperty, Boolean.class, true);
return new ConditionOutcome(match, ConditionMessage.forCondition(ConditionalOnEnabledMetricsExport.class)
.because(enabledProperty + " is " + match));
}
return null; | }
/**
* Return the default outcome that should be used if property is not set. By default
* this method will use the {@link #DEFAULT_PROPERTY_NAME} property, matching if it is
* {@code true} or if it is not configured.
* @param context the condition context
* @return the default outcome
*/
private ConditionOutcome getDefaultOutcome(ConditionContext context) {
boolean match = Boolean.parseBoolean(context.getEnvironment().getProperty(DEFAULT_PROPERTY_NAME, "true"));
return new ConditionOutcome(match, ConditionMessage.forCondition(ConditionalOnEnabledMetricsExport.class)
.because(DEFAULT_PROPERTY_NAME + " is considered " + match));
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\OnMetricsExportEnabledCondition.java | 2 |
请完成以下Java代码 | public static void ensureNotDocumentRootExpression(String expression) {
if (ROOT_EXPRESSION.equals(expression)) {
throw LOG.notAllowedXPathExpression(expression);
}
}
/**
* Ensure that the node is not null.
*
* @param node the node to ensure to be not null
* @param expression the expression was used to find the node
* @throws SpinXPathException if the node is null
*/
public static void ensureXPathNotNull(Node node, String expression) {
if (node == null) {
throw LOG.unableToFindXPathExpression(expression);
}
} | /**
* Ensure that the nodeList is either null or empty.
*
* @param nodeList the nodeList to ensure to be either null or empty
* @param expression the expression was used to fine the nodeList
* @throws SpinXPathException if the nodeList is either null or empty
*/
public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {
if (nodeList == null || nodeList.getLength() == 0) {
throw LOG.unableToFindXPathExpression(expression);
}
}
} | repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\util\DomXmlEnsure.java | 1 |
请完成以下Java代码 | public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPickupTimeFrom (final java.sql.Timestamp PickupTimeFrom)
{
set_Value (COLUMNNAME_PickupTimeFrom, PickupTimeFrom);
}
@Override
public java.sql.Timestamp getPickupTimeFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_PickupTimeFrom);
}
@Override
public void setPickupTimeTo (final java.sql.Timestamp PickupTimeTo)
{
set_Value (COLUMNNAME_PickupTimeTo, PickupTimeTo);
}
@Override
public java.sql.Timestamp getPickupTimeTo()
{
return get_ValueAsTimestamp(COLUMNNAME_PickupTimeTo);
}
/**
* ShipperGateway AD_Reference_ID=540808
* Reference name: ShipperGateway
*/
public static final int SHIPPERGATEWAY_AD_Reference_ID=540808;
/** GO = go */
public static final String SHIPPERGATEWAY_GO = "go";
/** Der Kurier = derKurier */
public static final String SHIPPERGATEWAY_DerKurier = "derKurier";
/** DHL = dhl */
public static final String SHIPPERGATEWAY_DHL = "dhl";
/** DPD = dpd */
public static final String SHIPPERGATEWAY_DPD = "dpd";
/** nShift = nshift */
public static final String SHIPPERGATEWAY_NShift = "nshift";
@Override
public void setShipperGateway (final @Nullable java.lang.String ShipperGateway)
{
set_Value (COLUMNNAME_ShipperGateway, ShipperGateway); | }
@Override
public java.lang.String getShipperGateway()
{
return get_ValueAsString(COLUMNNAME_ShipperGateway);
}
@Override
public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper.java | 1 |
请完成以下Java代码 | public void updatePartitionerInterceptorOnChange(final I_DLM_Partition_Config_Line configLine)
{
if (configLine.getDLM_Referencing_Table_ID() <= 0)
{
return;
}
final ModelValidationEngine engine = ModelValidationEngine.get();
final I_DLM_Partition_Config_Line oldConfigLine = InterfaceWrapperHelper.createOld(configLine, I_DLM_Partition_Config_Line.class);
engine.removeModelChange(oldConfigLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
engine.addModelChange(configLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void updatePartitionerInterceptorOnNew(final I_DLM_Partition_Config_Line configLine)
{
if (configLine.getDLM_Referencing_Table_ID() <= 0)
{
return; | }
final ModelValidationEngine engine = ModelValidationEngine.get();
engine.addModelChange(configLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void updatePartitionerInterceptorOnDelete(final I_DLM_Partition_Config_Line configLine)
{
if (configLine.getDLM_Referencing_Table_ID() <= 0)
{
return;
}
final ModelValidationEngine engine = ModelValidationEngine.get();
engine.removeModelChange(configLine.getDLM_Referencing_Table().getTableName(), AddToPartitionInterceptor.INSTANCE);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\model\interceptor\DLM_Partition_Config_Line.java | 1 |
请完成以下Java代码 | public int getC_ConversionType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ConversionType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{ | return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ConversionType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ArticleModel {
ArticleModelNested article;
static ArticleModel fromArticle(Article article) {
return new ArticleModel(ArticleModelNested.fromArticle(article));
}
@Value
static class ArticleModelNested {
String slug;
String title;
String description;
String body;
Set<String> tagList;
ZonedDateTime createdAt;
ZonedDateTime updatedAt;
boolean favorited;
int favoritesCount;
ProfileModelNested author; | static ArticleModelNested fromArticle(Article article) {
final var contents = article.getContents();
final var titleFromArticle = contents.getTitle();
return new ArticleModelNested(
titleFromArticle.getSlug(), titleFromArticle.getTitle(),
contents.getDescription(), contents.getBody(),
contents.getTags().stream().map(Tag::toString).collect(toSet()),
article.getCreatedAt().atZone(ZoneId.of("Asia/Seoul")),
article.getUpdatedAt().atZone(ZoneId.of("Asia/Seoul")),
article.isFavorited(), article.getFavoritedCount(),
ProfileModelNested.fromProfile(article.getAuthor().getProfile())
);
}
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\application\article\ArticleModel.java | 2 |
请完成以下Java代码 | public class FunctionalJavaMain {
public static final F<Integer, Boolean> isEven = i -> i % 2 == 0;
public static void main(String[] args) {
List<Integer> fList = List.list(3, 4, 5, 6);
List<Boolean> evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
Array<Integer> a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array<Integer> b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
Array<String> array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
Array<Integer> intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0); | System.out.println(sum);
Option<Integer> n1 = Option.some(1);
Option<Integer> n2 = Option.some(2);
F<Integer, Option<Integer>> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
Option<Integer> result1 = n1.bind(f1);
Option<Integer> result2 = n2.bind(f1);
Show.optionShow(Show.intShow).println(result1);
Show.optionShow(Show.intShow).println(result2);
}
} | repos\tutorials-master\libraries-6\src\main\java\com\baeldung\fj\FunctionalJavaMain.java | 1 |
请完成以下Java代码 | public void onBeforeInvoiceComplete(final I_C_Invoice invoice, final List<I_C_Invoice_Candidate> fromCandidates)
{
final boolean isEdiEnabled = calculateEdiEnabled(fromCandidates);
final de.metas.edi.model.I_C_Invoice ediInvoice = InterfaceWrapperHelper.create(invoice, de.metas.edi.model.I_C_Invoice.class);
// make sure the EdiEnabled flag is set based on the invoice candidates of the invoice to be completed
ediDocumentBL.setEdiEnabled(ediInvoice, isEdiEnabled);
}
private boolean calculateEdiEnabled(@NonNull final List<I_C_Invoice_Candidate> fromCandidates)
{
if (fromCandidates.isEmpty())
{
return false; | }
final boolean isEdiEnabled = InterfaceWrapperHelper.create(fromCandidates.get(0), de.metas.edi.model.I_C_Invoice_Candidate.class).isEdiEnabled();
for (int i = 0; i < fromCandidates.size(); i++)
{
final de.metas.edi.model.I_C_Invoice_Candidate candidate = InterfaceWrapperHelper.create(fromCandidates.get(i), de.metas.edi.model.I_C_Invoice_Candidate.class);
if (isEdiEnabled != candidate.isEdiEnabled())
{
throw new AdempiereException("IsEdiEnabled not consistent in candidates: " + fromCandidates);
}
}
return isEdiEnabled;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\spi\impl\EdiInvoiceCandidateListener.java | 1 |
请完成以下Java代码 | public int size()
{
return this.size;
}
public int getLinearExpandFactor()
{
return this.linearExpandFactor;
}
public void set(int index, int value)
{
this.data[index] = value;
}
public int get(int index)
{
return this.data[index];
}
public void removeLast()
{
--size;
}
public int getLast()
{
return data[size - 1];
}
public void setLast(int value)
{
data[size - 1] = value;
}
public int pop()
{
return data[--size];
}
@Override
public void save(DataOutputStream out) throws IOException
{
out.writeInt(size);
for (int i = 0; i < size; i++)
{
out.writeInt(data[i]);
}
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
@Override
public boolean load(ByteArray byteArray)
{
if (byteArray == null)
{
return false;
}
size = byteArray.nextInt();
data = new int[size];
for (int i = 0; i < size; i++)
{
data[i] = byteArray.nextInt();
} | linearExpandFactor = byteArray.nextInt();
exponentialExpanding = byteArray.nextBoolean();
exponentialExpandFactor = byteArray.nextDouble();
return true;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
loseWeight();
out.writeInt(size);
out.writeObject(data);
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
size = in.readInt();
data = (int[]) in.readObject();
linearExpandFactor = in.readInt();
exponentialExpanding = in.readBoolean();
exponentialExpandFactor = in.readDouble();
}
@Override
public String toString()
{
ArrayList<Integer> head = new ArrayList<Integer>(20);
for (int i = 0; i < Math.min(size, 20); ++i)
{
head.add(data[i]);
}
return head.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\IntArrayList.java | 1 |
请完成以下Java代码 | public int dimension()
{
return wordVectorModel.dimension();
}
/**
* 文档相似度计算
*
* @param what
* @param with
* @return
*/
public float similarity(String what, String with)
{
Vector A = query(what);
if (A == null) return -1f;
Vector B = query(with);
if (B == null) return -1f;
return A.cosineForUnitVector(B);
}
public Segment getSegment()
{
return segment;
}
public void setSegment(Segment segment)
{
this.segment = segment;
} | /**
* 是否激活了停用词过滤器
*
* @return
*/
public boolean isFilterEnabled()
{
return filter;
}
/**
* 激活/关闭停用词过滤器
*
* @param filter
*/
public void enableFilter(boolean filter)
{
this.filter = filter;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\DocVectorModel.java | 1 |
请完成以下Java代码 | public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName);
}
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setPrintServiceTray (java.lang.String PrintServiceTray)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray);
}
@Override
public java.lang.String getPrintServiceTray()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray);
}
@Override
public org.compiere.model.I_S_Resource getS_Resource()
{
return get_ValueAsPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setS_Resource(org.compiere.model.I_S_Resource S_Resource)
{
set_ValueFromPO(COLUMNNAME_S_Resource_ID, org.compiere.model.I_S_Resource.class, S_Resource);
}
@Override
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
} | @Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setWP_IsError (boolean WP_IsError)
{
set_ValueNoCheck (COLUMNNAME_WP_IsError, Boolean.valueOf(WP_IsError));
}
@Override
public boolean isWP_IsError()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsError);
}
@Override
public void setWP_IsProcessed (boolean WP_IsProcessed)
{
set_ValueNoCheck (COLUMNNAME_WP_IsProcessed, Boolean.valueOf(WP_IsProcessed));
}
@Override
public boolean isWP_IsProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_WP_IsProcessed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Order_MFGWarehouse_Report_PrintInfo_v.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static boolean hasAttribute(
@NonNull final Node node,
@NonNull final String attributeName,
@NonNull final String matchingValue)
{
final NamedNodeMap namedNodeMap = node.getAttributes();
final Node attributeNode = namedNodeMap.getNamedItem(attributeName);
if (attributeNode == null || attributeNode.getNodeValue() == null)
{
return false;
}
return matchingValue.equals(attributeNode.getNodeValue());
}
@Nullable
public static Element getElementByTag(@NonNull final Node node, @NonNull final String tagName)
{
final Element element = node instanceof Document
? ((Document)node).getDocumentElement()
: (Element)node;
final NodeList nodeList = element.getElementsByTagName(tagName);
if (nodeList.getLength() == 0)
{
return null;
}
final Node childNode = nodeList.item(0);
return (Element)childNode;
} | @NonNull
public static String addXMLDeclarationIfNeeded(@NonNull final String payload)
{
if (payload.trim().startsWith("<?xml")) {
// Payload already contains XML declaration
return payload;
}
final String xmlDeclaration = String.format(
"<?xml version=\"1.0\" encoding=\"%s\" standalone=\"%s\"?>\n",
XML_PROPERTY_FILE_ENCODING_VALUE,
XML_PROPERTY_VALUE_YES
);
return xmlDeclaration + payload;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\util\XMLUtil.java | 2 |
请完成以下Java代码 | protected void executeInternal(CommandContext commandContext, ExecutionEntity executionEntity) {
SuspensionStateUtil.setSuspensionState(executionEntity, getNewState());
commandContext.getExecutionEntityManager().update(executionEntity, false);
updateChildrenSuspensionState(commandContext);
updateTaskSuspensionState(commandContext);
suspendAllJobs(commandContext);
}
protected void suspendAllJobs(CommandContext commandContext) {
if (getNewState() == SuspensionState.ACTIVE) {
List<SuspendedJobEntity> suspendedJobs = commandContext
.getSuspendedJobEntityManager()
.findJobsByProcessInstanceId(processInstanceId);
for (SuspendedJobEntity suspendedJob : suspendedJobs) {
commandContext.getJobManager().activateSuspendedJob(suspendedJob);
}
} else {
List<TimerJobEntity> timerJobs = commandContext
.getTimerJobEntityManager()
.findJobsByProcessInstanceId(processInstanceId);
for (TimerJobEntity timerJob : timerJobs) {
commandContext.getJobManager().moveJobToSuspendedJob(timerJob);
}
List<JobEntity> jobs = commandContext.getJobEntityManager().findJobsByProcessInstanceId(processInstanceId);
for (JobEntity job : jobs) {
commandContext.getJobManager().moveJobToSuspendedJob(job);
}
} | }
protected void updateChildrenSuspensionState(CommandContext commandContext) {
Collection<ExecutionEntity> childExecutions = commandContext
.getExecutionEntityManager()
.findChildExecutionsByProcessInstanceId(processInstanceId);
for (ExecutionEntity childExecution : childExecutions) {
if (!childExecution.getId().equals(processInstanceId)) {
SuspensionStateUtil.setSuspensionState(childExecution, getNewState());
commandContext.getExecutionEntityManager().update(childExecution, false);
}
}
}
protected void updateTaskSuspensionState(CommandContext commandContext) {
List<TaskEntity> tasks = commandContext.getTaskEntityManager().findTasksByProcessInstanceId(processInstanceId);
for (TaskEntity taskEntity : tasks) {
SuspensionStateUtil.setSuspensionState(taskEntity, getNewState());
commandContext.getTaskEntityManager().update(taskEntity, false);
}
}
protected abstract SuspensionState getNewState();
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AbstractSetProcessInstanceStateCmd.java | 1 |
请完成以下Java代码 | protected boolean isMultiRelease() {
Boolean multiRelease = this.multiRelease;
if (multiRelease == null) {
synchronized (this.archiveLock) {
multiRelease = this.multiRelease;
if (multiRelease == null) {
// JarFile.isMultiRelease() is final so we must go to the manifest
Manifest manifest = getManifest();
Attributes attributes = (manifest != null) ? manifest.getMainAttributes() : null;
multiRelease = (attributes != null) && attributes.containsKey(MULTI_RELEASE);
this.multiRelease = multiRelease;
}
}
}
return multiRelease;
}
@Override
public void gc() {
synchronized (this.archiveLock) {
if (this.archive != null && this.archiveUseCount == 0) {
try {
if (!this.useCaches) {
this.archive.close();
}
}
catch (IOException ex) {
// Ignore | }
this.archive = null;
this.archiveEntries = null;
}
}
}
private JarURLConnection connect() throws IOException {
URLConnection connection = this.url.openConnection();
ResourceUtils.useCachesIfNecessary(connection);
Assert.state(connection instanceof JarURLConnection,
() -> "URL '%s' did not return a JAR connection".formatted(this.url));
connection.connect();
return (JarURLConnection) connection;
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\servlet\NestedJarResourceSet.java | 1 |
请完成以下Java代码 | public boolean isWarning() {
return isWarning;
}
public void setWarning(boolean isWarning) {
this.isWarning = isWarning;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '" + validatorSetName + "' | Problem: '" + problem + "'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (processDefinitionId != null) {
strb.append("processDefinitionId = " + processDefinitionId);
extraInfoAlreadyPresent = true;
}
if (processDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("processDefinitionName = " + processDefinitionName + " | ");
extraInfoAlreadyPresent = true;
}
if (activityId != null) { | if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("id = " + activityId + " | ");
extraInfoAlreadyPresent = true;
}
if (activityName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("activityName = " + activityName + " | ");
extraInfoAlreadyPresent = true;
}
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: " + xmlLineNumber + ", column: " + xmlColumnNumber + ")");
}
if (key != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append(" ( key: " + key + " )");
extraInfoAlreadyPresent = true;
}
if (params != null && !params.isEmpty()) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append(" ( ");
for (Map.Entry<String, String> param : params.entrySet()) {
strb.append(param.getKey() + " = " + param.getValue() + " | ");
}
strb.append(")");
extraInfoAlreadyPresent = true;
}
strb.append("]");
return strb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\ValidationError.java | 1 |
请完成以下Java代码 | public class Util {
public static Hashtable HTMLColors;
static {
HTMLColors = new Hashtable();
HTMLColors.put("red", Color.red);
HTMLColors.put("green", Color.green);
HTMLColors.put("blue", Color.blue);
HTMLColors.put("cyan", Color.cyan);
HTMLColors.put("magenta", Color.magenta);
HTMLColors.put("yellow", Color.yellow);
HTMLColors.put("black", Color.black);
HTMLColors.put("white", Color.white);
HTMLColors.put("gray", Color.gray);
HTMLColors.put("darkgray", Color.darkGray);
HTMLColors.put("lightgray", Color.lightGray);
HTMLColors.put("orange", Color.orange);
HTMLColors.put("pink", Color.pink);
}
public static Color getColorForName(String name, Color defaultColor) {
if (HTMLColors.contains(name.toLowerCase()))
return (Color)HTMLColors.get(name.toLowerCase());
return defaultColor;
}
public static Color decodeColor(String color, Color defaultColor) {
String colorVal = "";
if (color.length() > 0) {
colorVal = color.trim();
if (colorVal.startsWith("#"))
colorVal = colorVal.substring(1);
try {
colorVal = new Integer(Integer.parseInt(colorVal, 16)).toString();
return Color.decode(colorVal.toLowerCase());
}
catch (Exception ex) { | ex.printStackTrace();
}
}
else return defaultColor;
return getColorForName(color, defaultColor);
}
public static String encodeColor(Color color) {
return "#"+Integer.toHexString(color.getRGB()-0xFF000000).toUpperCase();
}
public static Color decodeColor(String color) {
return decodeColor(color, Color.white);
}
public static void setBgcolorField(JTextField field) {
Color c = Util.decodeColor(field.getText());
field.setBackground(c);
field.setForeground(new Color(~c.getRGB()));
}
public static void setColorField(JTextField field) {
Color c = Util.decodeColor(field.getText(), Color.black);
field.setForeground(c);
//field.setForeground(new Color(~c.getRGB()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\Util.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Printer[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set System Printer.
@param AD_Printer_ID System Printer */
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
/** Get System Printer.
@return System Printer */
public int getAD_Printer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Printer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** IsDirectPrint AD_Reference_ID=319 */
public static final int ISDIRECTPRINT_AD_Reference_ID=319;
/** Yes = Y */
public static final String ISDIRECTPRINT_Yes = "Y";
/** No = N */
public static final String ISDIRECTPRINT_No = "N";
/** Set Direct print.
@param IsDirectPrint
Print without dialog
*/
public void setIsDirectPrint (String IsDirectPrint)
{
set_Value (COLUMNNAME_IsDirectPrint, IsDirectPrint);
}
/** Get Direct print.
@return Print without dialog
*/
public String getIsDirectPrint ()
{
return (String)get_Value(COLUMNNAME_IsDirectPrint);
}
/** Set Drucker.
@param PrinterName
Name of the Printer
*/ | public void setPrinterName (String PrinterName)
{
set_Value (COLUMNNAME_PrinterName, PrinterName);
}
/** Get Drucker.
@return Name of the Printer
*/
public String getPrinterName ()
{
return (String)get_Value(COLUMNNAME_PrinterName);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getPrinterName());
}
/** PrinterType AD_Reference_ID=540227 */
public static final int PRINTERTYPE_AD_Reference_ID=540227;
/** General = G */
public static final String PRINTERTYPE_General = "G";
/** Fax = F */
public static final String PRINTERTYPE_Fax = "F";
/** Label = L */
public static final String PRINTERTYPE_Label = "L";
/** Set Printer Type.
@param PrinterType Printer Type */
public void setPrinterType (String PrinterType)
{
set_Value (COLUMNNAME_PrinterType, PrinterType);
}
/** Get Printer Type.
@return Printer Type */
public String getPrinterType ()
{
return (String)get_Value(COLUMNNAME_PrinterType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Printer.java | 1 |
请完成以下Java代码 | public class M_ShipmentSchedule_Set_BestBeforeDate extends JavaProcess implements IProcessPrecondition
{
@Param(mandatory = true, parameterName = "BestBeforeDate")
private LocalDate p_bestBeforeDate;
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class);
private final ILockManager lockManager = Services.get(ILockManager.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.getSelectionSize().isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx // we update each shipment sched within its own little trx, to avoid blocking on DB level
protected String doIt() throws Exception
{ | final IQueryFilter<I_M_ShipmentSchedule> queryFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final ShipmentScheduleUserChangeRequestBuilder builder = ShipmentScheduleUserChangeRequest.builder().bestBeforeDate(p_bestBeforeDate);
final IQueryFilter<I_M_ShipmentSchedule> notLockedFilter = lockManager.getNotLockedFilter(I_M_ShipmentSchedule.class);
// get the selected shipment schedule IDs
final Iterator<ShipmentScheduleId> ids = queryBL
.createQueryBuilder(I_M_ShipmentSchedule.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule.COLUMN_Processed, false)
.filter(queryFilter)
.filter(notLockedFilter)
.create()
.iterateIds(ShipmentScheduleId::ofRepoId);
// update them one by one
while (ids.hasNext())
{
final ShipmentScheduleUserChangeRequest singleRequest = builder.shipmentScheduleId(ids.next()).build();
final ShipmentScheduleUserChangeRequestsList userChanges = ShipmentScheduleUserChangeRequestsList.of(ImmutableList.of(singleRequest));
shipmentScheduleBL.applyUserChangesInTrx(userChanges);
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ShipmentSchedule_Set_BestBeforeDate.java | 1 |
请完成以下Java代码 | private boolean checkContextVariableResolved(@NonNull final ContextPath path, @NonNull final String contextVariable)
{
final ContextVariables contextVariables = getCurrentContextVariables();
final boolean isFound = contextVariables.contains(contextVariable);
missingContextVariables.recordContextVariableUsed(path, contextVariable, isFound);
return isFound || missingContextVariables.isKnownAsMissing(path, contextVariable);
}
private AdempiereException newException(final String message)
{
final AdempiereException exception = new AdempiereException(message);
fillContextInfo(exception);
return exception;
}
private AdempiereException wrapException(final Exception exception) | {
final AdempiereException wrappedException = AdempiereException.wrapIfNeeded(exception);
fillContextInfo(wrappedException);
return wrappedException;
}
private void fillContextInfo(final AdempiereException exception)
{
exception.setParameter("contextPath", getCurrentPath());
final ContextVariables contextVariables = getCurrentContextVariables();
if (contextVariables != null)
{
exception.setParameter("contextVariables", contextVariables.toSummaryString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariablesCheckCommand.java | 1 |
请完成以下Java代码 | public static Optional<LicenseFeeConfig> castOrEmpty(@NonNull final CommissionConfig commissionConfig)
{
if (isInstance(commissionConfig))
{
return Optional.of((LicenseFeeConfig)commissionConfig);
}
return Optional.empty();
}
@Override
public CommissionType getCommissionType()
{
return CommissionType.LICENSE_FEE_COMMISSION;
}
@Override | @Nullable
public CommissionContract getContractFor(@NonNull final BPartnerId contractualBPartnerId)
{
if (licenseFeeContract.getContractOwnerBPartnerId().equals(contractualBPartnerId))
{
return licenseFeeContract;
}
return null;
}
@NonNull
public LicenseFeeSettingsId getId()
{
return licenseFeeSettingsLineId.getLicenseFeeSettingsId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\licensefee\algorithm\LicenseFeeConfig.java | 1 |
请完成以下Java代码 | public class CustomInterval extends BaseAggInterval {
@NotNull
@Min(1)
private Long durationSec;
public CustomInterval(String tz, Long offsetSec, Long durationSec) {
super(tz, offsetSec);
this.durationSec = durationSec;
}
@Override
public AggIntervalType getType() {
return AggIntervalType.CUSTOM;
}
@Override
public long getCurrentIntervalDurationMillis() {
return getDurationMillis();
}
private long getDurationMillis() {
return Duration.ofSeconds(durationSec).toMillis();
} | @Override
protected ZonedDateTime alignToIntervalStart(ZonedDateTime reference) {
ZonedDateTime localMidnight = reference.toLocalDate().atStartOfDay(reference.getZone());
long secondsFromMidnight = Duration.between(localMidnight, reference).getSeconds();
long alignedSecondsFromMidnight = (secondsFromMidnight / durationSec) * durationSec;
return localMidnight.plusSeconds(alignedSecondsFromMidnight);
}
@Override
public ZonedDateTime getNextIntervalStart(ZonedDateTime currentStart) {
return currentStart.plusSeconds(durationSec);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\aggregation\single\interval\CustomInterval.java | 1 |
请完成以下Java代码 | public Execution executeActivityInAdhocSubProcess(String executionId, String activityId) {
return commandExecutor.execute(new ExecuteActivityForAdhocSubProcessCmd(executionId, activityId));
}
@Override
public void completeAdhocSubProcess(String executionId) {
commandExecutor.execute(new CompleteAdhocSubProcessCmd(executionId));
}
@Override
public ProcessInstanceBuilder createProcessInstanceBuilder() {
return new ProcessInstanceBuilderImpl(this);
}
@Override
public ProcessInstance startCreatedProcessInstance(
ProcessInstance createdProcessInstance,
Map<String, Object> variables
) {
return commandExecutor.execute(new StartCreatedProcessInstanceCmd<>(createdProcessInstance, variables));
}
public ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.hasProcessDefinitionIdOrKey()) {
return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder)); | } else if (processInstanceBuilder.getMessageName() != null) {
return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder));
} else {
throw new ActivitiIllegalArgumentException(
"No processDefinitionId, processDefinitionKey nor messageName provided"
);
}
}
public ProcessInstance createProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.hasProcessDefinitionIdOrKey()) {
return commandExecutor.execute(new CreateProcessInstanceCmd(processInstanceBuilder));
} else {
throw new ActivitiIllegalArgumentException(
"No processDefinitionId, processDefinitionKey nor messageName provided"
);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\RuntimeServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Stream<BPartnerLocationId> streamBPartnerLocationIds(
@Nullable final Set<OrgId> onlyOrgIds,
@Nullable final String glnLookupLabel)
{
return locations.stream()
.filter(location -> location.isMatching(onlyOrgIds, glnLookupLabel))
.map(GLNLocation::getBpLocationId);
}
}
@Value
@Builder
private static class GLNLocation
{
@NonNull
GlnWithLabel glnWithLabel;
@NonNull
OrgId orgId;
@NonNull
BPartnerLocationId bpLocationId;
boolean isMatching(@Nullable final Set<OrgId> onlyOrgIds,
@Nullable final String glnLookupLabel)
{
return isMatchingLookupLabel(glnLookupLabel) && isMatchingOrgId(onlyOrgIds);
}
private boolean isMatchingLookupLabel(@Nullable final String glnLookupLabel) | {
if (Check.isBlank(glnLookupLabel))
{
return true;
}
return glnLookupLabel.equals(glnWithLabel.getLabel());
}
private boolean isMatchingOrgId(@Nullable final Set<OrgId> onlyOrgIds)
{
if (onlyOrgIds == null || onlyOrgIds.isEmpty())
{
return true;
}
return onlyOrgIds.contains(orgId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\GLNLoadingCache.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BatchWindowConfiguration {
protected final static ConfigurationLogger LOG = ConfigurationLogger.CONFIG_LOGGER;
private String startTime;
private Date startTimeAsDate;
private String endTime = "00:00";
private Date endTimeAsDate;
public BatchWindowConfiguration() {
}
public BatchWindowConfiguration(String startTime, String endTime) {
this.startTime = startTime;
initStartTimeAsDate();
if (endTime != null) {
this.endTime = endTime;
}
initEndTimeAsDate();
}
private void initStartTimeAsDate() {
try {
startTimeAsDate = HistoryCleanupHelper.parseTimeConfiguration(startTime);
} catch (ParseException e) {
throw LOG.invalidPropertyValue("startTime", startTime);
}
}
private void initEndTimeAsDate() {
try {
endTimeAsDate = HistoryCleanupHelper.parseTimeConfiguration(endTime);
} catch (ParseException e) {
throw LOG.invalidPropertyValue("endTime", endTime);
}
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
initStartTimeAsDate();
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
initEndTimeAsDate(); | }
public Date getStartTimeAsDate() {
return startTimeAsDate;
}
public Date getEndTimeAsDate() {
return endTimeAsDate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BatchWindowConfiguration that = (BatchWindowConfiguration) o;
if (startTime != null ? !startTime.equals(that.startTime) : that.startTime != null)
return false;
return endTime != null ? endTime.equals(that.endTime) : that.endTime == null;
}
@Override
public int hashCode() {
int result = startTime != null ? startTime.hashCode() : 0;
result = 31 * result + (endTime != null ? endTime.hashCode() : 0);
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\BatchWindowConfiguration.java | 2 |
请完成以下Java代码 | default Map<String, Object> getClaimAsMap(String claim) {
if (!hasClaim(claim)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(Object.class));
Object claimValue = getClaims().get(claim);
Map<String, Object> convertedValue = (Map<String, Object>) ClaimConversionService.getSharedInstance()
.convert(claimValue, sourceDescriptor, targetDescriptor);
Assert.notNull(convertedValue,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to Map.");
return convertedValue;
}
/**
* Returns the claim value as a {@code List<String>} or {@code null} if the claim does
* not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if the claim does not exist
* @throws IllegalArgumentException if the claim value cannot be converted to a
* {@code List} | * @throws NullPointerException if the claim value is {@code null}
*/
@SuppressWarnings("unchecked")
default List<String> getClaimAsStringList(String claim) {
if (!hasClaim(claim)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.collection(List.class,
TypeDescriptor.valueOf(String.class));
Object claimValue = getClaims().get(claim);
List<String> convertedValue = (List<String>) ClaimConversionService.getSharedInstance()
.convert(claimValue, sourceDescriptor, targetDescriptor);
Assert.notNull(convertedValue,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to List.");
return convertedValue;
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\ClaimAccessor.java | 1 |
请完成以下Java代码 | public EventSubscriptionDto getEventSubscription() {
RuntimeService runtimeService = engine.getRuntimeService();
EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery()
.executionId(executionId).eventName(messageName).eventType(MESSAGE_EVENT_TYPE).singleResult();
if (eventSubscription == null) {
String errorMessage = String.format("Message event subscription for execution %s named %s does not exist", executionId, messageName);
throw new InvalidRequestException(Status.NOT_FOUND, errorMessage);
}
return EventSubscriptionDto.fromEventSubscription(eventSubscription);
}
@Override
public void triggerEvent(ExecutionTriggerDto triggerDto) {
RuntimeService runtimeService = engine.getRuntimeService();
try {
VariableMap variables = VariableValueDto.toMap(triggerDto.getVariables(), engine, objectMapper);
runtimeService.messageEventReceived(messageName, executionId, variables); | } catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, String.format("Cannot trigger message %s for execution %s: %s",
messageName, executionId, e.getMessage()));
} catch (RestException e) {
String errorMessage = String.format("Cannot trigger message %s for execution %s: %s", messageName, executionId, e.getMessage());
throw new InvalidRequestException(e.getStatus(), e, errorMessage);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\MessageEventSubscriptionResource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private HuId createHU(@NonNull final IHUContext huContext)
{
final I_C_UOM productStockingUOM = productBL.getStockUOM(productId);
// final I_M_InOut referenceModel = getCustomerReturns(); // using customer returns just because we need to use a referenced model
final I_AD_PInstance referencedModel = Services.get(IADPInstanceDAO.class).getById(getPinstanceId());
final IHUProducerAllocationDestination destination;
HULoader.builder()
.source(new GenericAllocationSourceDestination(
new PlainProductStorage(productId, Quantity.of(1, productStockingUOM)),
referencedModel
))
.destination(destination = HUProducerDestination.ofVirtualPI()
.setHUStatus(X_M_HU.HUSTATUS_Shipped)
.setBPartnerId(customerId)
.setLocatorId(getLocatorId()))
.load(AllocationUtils.builder()
.setHUContext(huContext)
.setProduct(productId)
.setQuantity(Quantity.of(1, productStockingUOM))
.setDate(SystemTime.asZonedDateTime())
.setForceQtyAllocation(true)
.setFromReferencedModel(referencedModel)
.create());
final I_M_HU vhu = destination.getSingleCreatedHU()
.orElseThrow(() -> new AdempiereException("No HU created"));
final IAttributeStorage vhuAttributes = huContext.getHUAttributeStorageFactory()
.getAttributeStorage(vhu);
vhuAttributes.setValue(AttributeConstants.ATTR_SerialNo, serialNo);
if (vhuAttributes.hasAttribute(AttributeConstants.WarrantyStartDate)) | {
vhuAttributes.setValue(AttributeConstants.WarrantyStartDate, warrantyStartDate);
}
vhuAttributes.saveChangesIfNeeded();
return HuId.ofRepoId(vhu.getM_HU_ID());
}
private LocatorId getLocatorId()
{
final I_M_InOut customerReturns = getCustomerReturns();
final WarehouseId warehouseId = WarehouseId.ofRepoId(customerReturns.getM_Warehouse_ID());
return warehouseBL.getOrCreateDefaultLocatorId(warehouseId);
}
private I_M_InOut getCustomerReturns()
{
I_M_InOut customerReturns = this._customerReturns;
if (customerReturns == null)
{
final HUsToReturnViewContext husToReturnViewContext = getHUsToReturnViewContext();
final InOutId customerReturnsId = husToReturnViewContext.getCustomerReturnsId();
customerReturns = this._customerReturns = inoutBL.getById(customerReturnsId);
}
return customerReturns;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\process\HUsToReturn_CreateShippedHU.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PayScheduleId implements RepoIdAware
{
int repoId;
private PayScheduleId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_PaySchedule_ID");
}
@JsonCreator
public static PayScheduleId ofRepoId(final int payScheduleId)
{
return new PayScheduleId(payScheduleId);
}
@Nullable
public static PayScheduleId ofRepoIdOrNull(@Nullable final Integer payScheduleId)
{
return payScheduleId != null && payScheduleId > 0 ? ofRepoId(payScheduleId) : null;
} | public static Optional<PayScheduleId> optionalOfRepoId(@Nullable final Integer payScheduleId)
{
return Optional.ofNullable(ofRepoIdOrNull(payScheduleId));
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final PayScheduleId payScheduleId)
{
return payScheduleId != null ? payScheduleId.getRepoId() : -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\PayScheduleId.java | 2 |
请完成以下Java代码 | public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public static HistoricDecisionInstanceDto fromHistoricDecisionInstance(HistoricDecisionInstance historicDecisionInstance) {
HistoricDecisionInstanceDto dto = new HistoricDecisionInstanceDto();
dto.id = historicDecisionInstance.getId();
dto.decisionDefinitionId = historicDecisionInstance.getDecisionDefinitionId();
dto.decisionDefinitionKey = historicDecisionInstance.getDecisionDefinitionKey();
dto.decisionDefinitionName = historicDecisionInstance.getDecisionDefinitionName();
dto.evaluationTime = historicDecisionInstance.getEvaluationTime();
dto.removalTime = historicDecisionInstance.getRemovalTime();
dto.processDefinitionId = historicDecisionInstance.getProcessDefinitionId();
dto.processDefinitionKey = historicDecisionInstance.getProcessDefinitionKey();
dto.processInstanceId = historicDecisionInstance.getProcessInstanceId();
dto.caseDefinitionId = historicDecisionInstance.getCaseDefinitionId();
dto.caseDefinitionKey = historicDecisionInstance.getCaseDefinitionKey();
dto.caseInstanceId = historicDecisionInstance.getCaseInstanceId();
dto.activityId = historicDecisionInstance.getActivityId();
dto.activityInstanceId = historicDecisionInstance.getActivityInstanceId();
dto.userId = historicDecisionInstance.getUserId();
dto.collectResultValue = historicDecisionInstance.getCollectResultValue();
dto.rootDecisionInstanceId = historicDecisionInstance.getRootDecisionInstanceId();
dto.rootProcessInstanceId = historicDecisionInstance.getRootProcessInstanceId();
dto.decisionRequirementsDefinitionId = historicDecisionInstance.getDecisionRequirementsDefinitionId();
dto.decisionRequirementsDefinitionKey = historicDecisionInstance.getDecisionRequirementsDefinitionKey();
dto.tenantId = historicDecisionInstance.getTenantId();
try {
List<HistoricDecisionInputInstanceDto> inputs = new ArrayList<HistoricDecisionInputInstanceDto>();
for (HistoricDecisionInputInstance input : historicDecisionInstance.getInputs()) {
HistoricDecisionInputInstanceDto inputDto = HistoricDecisionInputInstanceDto.fromHistoricDecisionInputInstance(input); | inputs.add(inputDto);
}
dto.inputs = inputs;
}
catch (ProcessEngineException e) {
// no inputs fetched
}
try {
List<HistoricDecisionOutputInstanceDto> outputs = new ArrayList<HistoricDecisionOutputInstanceDto>();
for (HistoricDecisionOutputInstance output : historicDecisionInstance.getOutputs()) {
HistoricDecisionOutputInstanceDto outputDto = HistoricDecisionOutputInstanceDto.fromHistoricDecisionOutputInstance(output);
outputs.add(outputDto);
}
dto.outputs = outputs;
}
catch (ProcessEngineException e) {
// no outputs fetched
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDecisionInstanceDto.java | 1 |
请完成以下Java代码 | static String buildContactName(@Nullable final String firstName, @Nullable final String lastName)
{
final StringBuilder contactName = new StringBuilder();
if (lastName != null && !Check.isBlank(lastName))
{
contactName.append(lastName.trim());
}
if (firstName != null && !Check.isBlank(firstName))
{
if (contactName.length() > 0)
{
contactName.append(", ");
}
contactName.append(firstName.trim());
}
return contactName.toString();
}
/** | * Is the email valid
*
* @return return true if email is valid (artificial check)
*/
boolean isEMailValid(I_AD_User user);
Language getUserLanguage(@NonNull UserId userId);
/**
* @return the user's language or fallbacks; never returns {@code null}.
*/
Language getUserLanguage(I_AD_User userRecord);
UserEMailConfig getEmailConfigById(UserId userId);
ExplainedOptional<EMailAddress> getEMailAddressById(@NonNull UserId userId);
void deleteUserDependency(I_AD_User userRecord);
String getUserFullNameById(@NonNull UserId userId);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\IUserBL.java | 1 |
请完成以下Java代码 | public class CompactArray implements Serializable
{
float[] array;
int offset;
public CompactArray(int offset, float[] array)
{
this.offset = offset;
this.array = array;
}
/**
* 将index处的元素设置为value
*
* @param index
* @param value
*/
public void set(int index, float value)
{
if (index < offset + array.length && index >= offset)
{
array[index - offset] += value;
}
else if (index < offset)
{ //expand from left
int gap = offset - index;
int newSize = gap + array.length;
float[] newArray = new float[newSize];
newArray[0] = value;
for (int i = 0; i < array.length; i++)
{
newArray[gap + i] = array[i];
}
this.offset = index;
this.array = newArray;
} | else
{
int gap = index - (array.length + offset - 1);
int newSize = array.length + gap;
float[] newArray = new float[newSize];
newArray[newSize - 1] = value;
for (int i = 0; i < array.length; i++)
{
newArray[i] = array[i];
}
this.array = newArray;
}
}
public float[] getArray()
{
return array;
}
public int getOffset()
{
return offset;
}
public int length()
{
return array.length;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\structures\CompactArray.java | 1 |
请完成以下Java代码 | public class X_M_DosageForm extends org.compiere.model.PO implements I_M_DosageForm, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 1350345018L;
/** Standard Constructor */
public X_M_DosageForm (Properties ctx, int M_DosageForm_ID, String trxName)
{
super (ctx, M_DosageForm_ID, trxName);
/** if (M_DosageForm_ID == 0)
{
setM_DosageForm_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_M_DosageForm (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription () | {
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Dosage Form.
@param M_DosageForm_ID Dosage Form */
@Override
public void setM_DosageForm_ID (int M_DosageForm_ID)
{
if (M_DosageForm_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DosageForm_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DosageForm_ID, Integer.valueOf(M_DosageForm_ID));
}
/** Get Dosage Form.
@return Dosage Form */
@Override
public int getM_DosageForm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DosageForm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java-gen\de\metas\vertical\pharma\model\X_M_DosageForm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MetricsRepositoryMethodInvocationListener implements RepositoryMethodInvocationListener {
private final SingletonSupplier<MeterRegistry> registrySupplier;
private final RepositoryTagsProvider tagsProvider;
private final String metricName;
private final AutoTimer autoTimer;
/**
* Create a new {@code MetricsRepositoryMethodInvocationListener}.
* @param registrySupplier a supplier for the registry to which metrics are recorded
* @param tagsProvider provider for metrics tags
* @param metricName name of the metric to record
* @param autoTimer the auto-timers to apply or {@code null} to disable auto-timing
* @since 4.0.0
*/
public MetricsRepositoryMethodInvocationListener(Supplier<MeterRegistry> registrySupplier,
RepositoryTagsProvider tagsProvider, String metricName, @Nullable AutoTimer autoTimer) {
this.registrySupplier = (registrySupplier instanceof SingletonSupplier)
? (SingletonSupplier<MeterRegistry>) registrySupplier : SingletonSupplier.of(registrySupplier);
this.tagsProvider = tagsProvider;
this.metricName = metricName;
this.autoTimer = (autoTimer != null) ? autoTimer : AutoTimer.DISABLED;
}
@Override | public void afterInvocation(RepositoryMethodInvocation invocation) {
Set<Timed> annotations = TimedAnnotations.get(invocation.getMethod(), invocation.getRepositoryInterface());
Iterable<Tag> tags = this.tagsProvider.repositoryTags(invocation);
long duration = invocation.getDuration(TimeUnit.NANOSECONDS);
AutoTimer.apply(this.autoTimer, this.metricName, annotations, (builder) -> {
MeterRegistry registry = this.registrySupplier.get();
Assert.state(registry != null, "'registry' must not be null");
builder.description("Duration of repository invocations")
.tags(tags)
.register(registry)
.record(duration, TimeUnit.NANOSECONDS);
});
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\metrics\MetricsRepositoryMethodInvocationListener.java | 2 |
请完成以下Java代码 | public class ConditionUtil {
public static boolean hasTrueCondition(SequenceFlow sequenceFlow, DelegateExecution execution) {
String conditionExpression = null;
if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
ObjectNode elementProperties = Context.getBpmnOverrideElementProperties(
sequenceFlow.getId(),
execution.getProcessDefinitionId()
);
conditionExpression = getActiveValue(
sequenceFlow.getConditionExpression(),
DynamicBpmnConstants.SEQUENCE_FLOW_CONDITION,
elementProperties
);
} else {
conditionExpression = sequenceFlow.getConditionExpression();
}
if (StringUtils.isNotEmpty(conditionExpression)) {
Expression expression = Context.getProcessEngineConfiguration()
.getExpressionManager()
.createExpression(conditionExpression);
Condition condition = new UelExpressionCondition(expression);
if (condition.evaluate(sequenceFlow.getId(), execution)) {
return true;
}
return false;
} else {
return true; | }
}
protected static String getActiveValue(String originalValue, String propertyName, ObjectNode elementProperties) {
String activeValue = originalValue;
if (elementProperties != null) {
JsonNode overrideValueNode = elementProperties.get(propertyName);
if (overrideValueNode != null) {
if (overrideValueNode.isNull()) {
activeValue = null;
} else {
activeValue = overrideValueNode.asText();
}
}
}
return activeValue;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\condition\ConditionUtil.java | 1 |
请完成以下Java代码 | int getExitCode() {
int exitCode = 0;
for (ExitCodeGenerator generator : this.generators) {
try {
int value = generator.getExitCode();
if (value != 0) {
exitCode = value;
break;
}
}
catch (Exception ex) {
exitCode = 1;
ex.printStackTrace();
}
}
return exitCode;
}
/**
* Adapts an {@link ExitCodeExceptionMapper} to an {@link ExitCodeGenerator}. | */
private static class MappedExitCodeGenerator implements ExitCodeGenerator {
private final Throwable exception;
private final ExitCodeExceptionMapper mapper;
MappedExitCodeGenerator(Throwable exception, ExitCodeExceptionMapper mapper) {
this.exception = exception;
this.mapper = mapper;
}
@Override
public int getExitCode() {
return this.mapper.getExitCode(this.exception);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ExitCodeGenerators.java | 1 |
请完成以下Java代码 | public class EngineRestExceptionDto {
protected String message;
protected String type;
protected Integer code;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) { | this.type = type;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public RestException toRestException() {
return new RestException(message, type, code);
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineRestExceptionDto.java | 1 |
请完成以下Java代码 | public <T> IQueryBuilder<T> getLockedRecordsQueryBuilder(final Class<T> modelClass, final Object contextProvider)
{
return getLockDatabase().getLockedRecordsQueryBuilder(modelClass, contextProvider);
}
@Override
public int removeAutoCleanupLocks()
{
return getLockDatabase().removeAutoCleanupLocks();
}
@Override
public <T> List<T> retrieveAndLockMultipleRecords(@NonNull final IQuery<T> query, @NonNull final Class<T> clazz)
{
return getLockDatabase().retrieveAndLockMultipleRecords(query, clazz);
}
@Override | public <T> IQuery<T> addNotLockedClause(final IQuery<T> query)
{
return getLockDatabase().addNotLockedClause(query);
}
@Override
public ExistingLockInfo getLockInfo(final TableRecordReference tableRecordReference, final LockOwner lockOwner)
{
return getLockDatabase().getLockInfo(tableRecordReference, lockOwner);
}
@Override
public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(final @NonNull TableRecordReferenceSet recordRefs)
{
return getLockDatabase().getLockInfosByRecordIds(recordRefs);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\LockManager.java | 1 |
请完成以下Java代码 | public class CompleteTaskPayload implements Payload {
private String id;
private String taskId;
private Map<String, Object> variables;
public CompleteTaskPayload() {
this.id = UUID.randomUUID().toString();
}
public CompleteTaskPayload(String taskId, Map<String, Object> variables) {
this();
this.taskId = taskId;
this.variables = variables;
}
@Override
public String getId() { | return id;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
} | repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\CompleteTaskPayload.java | 1 |
请完成以下Java代码 | public int size()
{
return getAllStrings().size();
}
@Override
public boolean isEmpty()
{
return this.equivalenceClassMDAGNodeHashMap.size() != 0;
}
@Override
public boolean contains(Object o)
{
if (o.getClass() != String.class) return false;
return contains((String) o);
}
@Override
public Iterator<String> iterator()
{
return getAllStrings().iterator();
}
@Override
public Object[] toArray()
{
return getAllStrings().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return getAllStrings().toArray(a);
}
@Override
public boolean add(String s)
{
addString(s);
return true;
}
@Override
public boolean remove(Object o)
{
if (o.getClass() == String.class)
{
removeString((String) o);
}
else
{
removeString(o.toString());
}
return true;
}
@Override
public boolean containsAll(Collection<?> c)
{
for (Object e : c)
if (!contains(e))
return false;
return true; | }
@Override
public boolean addAll(Collection<? extends String> c)
{
boolean modified = false;
for (String e : c)
if (add(e))
modified = true;
return modified;
}
@Override
public boolean retainAll(Collection<?> c)
{
boolean modified = false;
Iterator<String> it = iterator();
while (it.hasNext())
{
if (!c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c)
{
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext())
{
if (c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
}
@Override
public void clear()
{
sourceNode = new MDAGNode(false);
simplifiedSourceNode = null;
if (equivalenceClassMDAGNodeHashMap != null)
equivalenceClassMDAGNodeHashMap.clear();
mdagDataArray = null;
charTreeSet.clear();
transitionCount = 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGSet.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean productMatchesSchemaLine(final int productId, final I_M_DiscountSchemaLine schemaLine)
{
final IProductDAO productDAO = Services.get(IProductDAO.class);
final boolean sameProduct = schemaLine.getM_Product_ID() == productId;
if (sameProduct)
{
return true;
}
final boolean differentProduct = schemaLine.getM_Product_ID() > 0;
if (differentProduct)
{
return false;
}
final I_M_Product product = productDAO.getById(productId);
return product.getM_Product_Category_ID() == schemaLine.getM_Product_Category_ID();
}
private List<I_M_DiscountSchemaLine> getSchemaLines(final int discountSchemaId)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
return queryBL.createQueryBuilder(I_M_DiscountSchemaLine.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_M_DiscountSchemaLine.COLUMNNAME_M_DiscountSchema_ID, discountSchemaId)
.orderBy(I_M_DiscountSchemaLine.COLUMNNAME_SeqNo)
.orderBy(I_M_DiscountSchemaLine.COLUMNNAME_M_DiscountSchemaLine_ID)
.create()
.list(I_M_DiscountSchemaLine.class);
}
@Override
protected List<I_M_PriceList_Version> retrieveCustomPLVsToMutate(@NonNull final PriceListId basePricelistId)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQuery<I_C_BPartner> customerQuery = queryBL.createQueryBuilder(I_C_BPartner.class) | .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BPartner.COLUMNNAME_IsCustomer, true)
.addEqualsFilter(I_C_BPartner.COLUMNNAME_IsAllowPriceMutation, true)
.create();
final List<I_M_PriceList_Version> customerVersions = queryBL.createQueryBuilder(I_M_PriceList.class)
.addEqualsFilter(I_M_PriceList.COLUMN_BasePriceList_ID, basePricelistId)
.addInSubQueryFilter()
.matchingColumnNames(I_M_PriceList.COLUMNNAME_M_PricingSystem_ID, I_C_BPartner.COLUMNNAME_M_PricingSystem_ID)
.subQuery(customerQuery)
.end()
.andCollectChildren(I_M_PriceList_Version.COLUMNNAME_M_PriceList_ID, I_M_PriceList_Version.class)
.addOnlyActiveRecordsFilter()
.addNotEqualsFilter(I_M_PriceList_Version.COLUMNNAME_M_PriceList_ID, basePricelistId)
.create()
.list(I_M_PriceList_Version.class);
return customerVersions.stream()
.filter(version -> retrieveNextVersionOrNull(version, false) == null)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PlainPriceListDAO.java | 2 |
请完成以下Java代码 | public static <T> CommonPage<T> restPage(List<T> list) {
CommonPage<T> result = new CommonPage<T>();
PageInfo<T> pageInfo = new PageInfo<T>(list);
result.setTotalPage(pageInfo.getPages());
result.setPageNum(pageInfo.getPageNum());
result.setPageSize(pageInfo.getPageSize());
result.setTotal(pageInfo.getTotal());
result.setList(pageInfo.getList());
return result;
}
/**
* 将SpringData分页后的list转为分页信息
*/
public static <T> CommonPage<T> restPage(Page<T> pageInfo) {
CommonPage<T> result = new CommonPage<T>();
result.setTotalPage(pageInfo.getTotalPages());
result.setPageNum(pageInfo.getNumber());
result.setPageSize(pageInfo.getSize());
result.setTotal(pageInfo.getTotalElements());
result.setList(pageInfo.getContent());
return result;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage; | }
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
} | repos\mall-master\mall-common\src\main\java\com\macro\mall\common\api\CommonPage.java | 1 |
请完成以下Java代码 | default Timer.Builder builder(String name) {
return builder(() -> Timer.builder(name));
}
/**
* Factory method to create a new {@link Builder Timer.Builder} with auto-timer
* settings {@link #apply(Timer.Builder) applied}.
* @param supplier the builder supplier
* @return a new builder instance with auto-settings applied
*/
default Timer.Builder builder(Supplier<Timer.Builder> supplier) {
Timer.Builder builder = supplier.get();
apply(builder);
return builder;
}
/**
* Called to apply any auto-timer settings to the given {@link Builder Timer.Builder}.
* @param builder the builder to apply settings to | */
void apply(Timer.Builder builder);
static void apply(@Nullable AutoTimer autoTimer, String metricName, Set<Timed> annotations,
Consumer<Timer.Builder> action) {
if (!CollectionUtils.isEmpty(annotations)) {
for (Timed annotation : annotations) {
action.accept(Timer.builder(annotation, metricName));
}
}
else {
if (autoTimer != null && autoTimer.isEnabled()) {
action.accept(autoTimer.builder(metricName));
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\metrics\AutoTimer.java | 1 |
请完成以下Java代码 | private final void hideGlassPane()
{
final MetasfreshGlassPane glassPane = this.glassPane;
this.glassPane = null;
if (glassPane == null)
{
return;
}
glassPane.setBusyTimer(0);
glassPane.setVisible(glassPaneVisibleOld);
glassPane.setMessagePlain(glassPaneMessageOld);
}
};
}
private final RootPaneContainer findRootPaneContainer(@Nullable final Component comp)
{
final RootPaneContainer rootPaneContainer = AEnv.getParentComponent(comp, RootPaneContainer.class);
if (rootPaneContainer == null)
{
final String errmsg = "No " + RootPaneContainer.class + " found."
+ "Ignore, but please check because this could be a development error."
+ "\n Component: " + comp
+ "\n Executor: " + this;
new AdempiereException(errmsg).throwIfDeveloperModeOrLogWarningElse(logger);
}
return rootPaneContainer;
}
private final Window findWindow(@Nullable final RootPaneContainer rootPaneContainer)
{
final Component comp;
if (rootPaneContainer == null)
{
comp = null;
}
else if (rootPaneContainer instanceof Window)
{
return (Window)rootPaneContainer;
}
else if (rootPaneContainer instanceof Component) | {
comp = (Component)rootPaneContainer;
}
else
{
comp = rootPaneContainer.getRootPane();
}
final Window window = AEnv.getParentComponent(comp, Window.class);
if (window == null)
{
final String errmsg = "No " + Window.class + " found."
+ "Ignore, but please check because this could be a development error."
+ "\n RootPaneContainer: " + rootPaneContainer
+ "\n Component: " + comp
+ "\n Executor: " + this;
new AdempiereException(errmsg).throwIfDeveloperModeOrLogWarningElse(logger);
}
return window;
}
@Override
protected Runnable asInvokeLaterRunnable(final Runnable runnable)
{
return new Runnable()
{
@Override
public String toString()
{
return "InvokeLater[" + runnable + "]";
}
@Override
public void run()
{
SwingUtilities.invokeLater(runnable);
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingClientUIInvoker.java | 1 |
请完成以下Java代码 | public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
public LocalTime getLocalTime() {
return localTimeField;
}
public void setLocalTime(LocalTime localTime) {
this.localTimeField = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
} | public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\pojo\TemporalValues.java | 1 |
请完成以下Java代码 | public Builder setAD_Table_ID(final int adTableId)
{
this.adTableId = adTableId;
return this;
}
private int getAD_Table_ID()
{
Check.assumeNotNull(adTableId, "adTableId not null");
Check.assume(adTableId > 0, "adTableId > 0");
return adTableId;
}
public Builder setAD_User_ID(final int adUserId)
{
this.adUserId = adUserId;
return this;
}
public Builder setAD_User_ID_Any()
{
this.adUserId = -1;
return this;
}
private int getAD_User_ID()
{ | Check.assumeNotNull(adUserId, "Parameter adUserId is not null");
return adUserId;
}
public Builder setColumnDisplayTypeProvider(@NonNull final ColumnDisplayTypeProvider columnDisplayTypeProvider)
{
this.columnDisplayTypeProvider = columnDisplayTypeProvider;
return this;
}
public ColumnDisplayTypeProvider getColumnDisplayTypeProvider()
{
return columnDisplayTypeProvider;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\UserQueryRepository.java | 1 |
请完成以下Java代码 | public void requestFocus()
{
m_curGC.requestFocus();
}
@Override
public boolean requestFocusInWindow()
{
return m_curGC.requestFocusInWindow();
}
public GridController getCurrentGridController()
{
return this.m_curGC;
}
public final AppsAction getIgnoreAction()
{
return aIgnore;
}
public final boolean isAlignVerticalTabsWithHorizontalTabs()
{
return alignVerticalTabsWithHorizontalTabs;
}
/**
* For a given component, it removes component's key bindings (defined in ancestor's map) that this panel also have defined.
*
* The main purpose of doing this is to make sure menu/toolbar key bindings will not be intercepted by given component, so panel's key bindings will work when given component is embedded in our
* panel.
*
* @param comp component or <code>null</code>
*/
public final void removeAncestorKeyBindingsOf(final JComponent comp, final Predicate<KeyStroke> isRemoveKeyStrokePredicate)
{
// Skip null components (but tolerate that)
if (comp == null)
{
return;
}
// Get component's ancestors input map (the map which defines which key bindings will work when pressed in a component which is included inside this component).
final InputMap compInputMap = comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
// NOTE: don't check and exit if "compInputMap.size() <= 0" because it might be that this map is empty but the key bindings are defined in it's parent map.
// Iterate all key bindings for our panel and remove those which are also present in component's ancestor map. | final InputMap thisInputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
for (final KeyStroke key : thisInputMap.allKeys())
{
// Check if the component has a key binding defined for our panel key binding.
final Object compAction = compInputMap.get(key);
if (compAction == null)
{
continue;
}
if (isRemoveKeyStrokePredicate != null && !isRemoveKeyStrokePredicate.apply(key))
{
continue;
}
// NOTE: Instead of removing it, it is much more safe to bind it to "none",
// to explicitly say to not consume that key event even if is defined in some parent map of this input map.
compInputMap.put(key, "none");
if (log.isDebugEnabled())
{
log.debug("Removed " + key + "->" + compAction + " which in this component is binded to " + thisInputMap.get(key)
+ "\n\tThis panel: " + this
+ "\n\tComponent: " + comp);
}
}
}
} // APanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\APanel.java | 1 |
请完成以下Java代码 | public String toString()
{
final int requestsCount = requests.size();
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("requestsCount", requestsCount)
.add("requests", requestsCount > 0 ? requests : null)
.toString();
}
public boolean isResetAll()
{
return requests.stream().anyMatch(CacheInvalidateRequest::isAll);
}
public Set<String> getTableNamesEffective()
{
return requests.stream()
.filter(request -> !request.isAll()) | .map(CacheInvalidateRequest::getTableNameEffective)
.collect(ImmutableSet.toImmutableSet());
}
public TableRecordReferenceSet getRecordsEffective()
{
return requests.stream()
.map(CacheInvalidateRequest::getRecordEffective)
.collect(TableRecordReferenceSet.collect());
}
public TableRecordReferenceSet getRootRecords()
{
return requests.stream()
.map(CacheInvalidateRequest::getRootRecordOrNull)
.filter(Objects::nonNull)
.collect(TableRecordReferenceSet.collect());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\CacheInvalidateMultiRequest.java | 1 |
请完成以下Java代码 | protected void initMetricsCollectionTask() {
metricsCollectionTask = new MetricsCollectionTask(metricsRegistry, commandExecutor);
}
public void start() {
timer = new Timer("Camunda Metrics Reporter", true);
long reportingIntervalInMillis = reportingIntervalInSeconds * 1000;
timer.scheduleAtFixedRate(metricsCollectionTask,
reportingIntervalInMillis,
reportingIntervalInMillis);
}
public void stop() {
if(timer != null) {
// cancel the timer
timer.cancel();
timer = null;
// collect and log manually for the last time
reportNow();
}
}
public void reportNow() {
if(metricsCollectionTask != null) {
metricsCollectionTask.run();
}
}
public void reportValueAtOnce(String name, long value) {
commandExecutor.execute(new ReportDbMetricsValueCmd(name, value));
}
public long getReportingIntervalInSeconds() {
return reportingIntervalInSeconds;
}
public void setReportingIntervalInSeconds(long reportingIntervalInSeconds) {
this.reportingIntervalInSeconds = reportingIntervalInSeconds;
}
public MetricsRegistry getMetricsRegistry() {
return metricsRegistry;
}
public CommandExecutor getCommandExecutor() {
return commandExecutor; | }
public MetricsCollectionTask getMetricsCollectionTask() {
return metricsCollectionTask;
}
public void setMetricsCollectionTask(MetricsCollectionTask metricsCollectionTask) {
this.metricsCollectionTask = metricsCollectionTask;
}
public void setReporterId(String reporterId) {
this.reporterId = reporterId;
if (metricsCollectionTask != null) {
metricsCollectionTask.setReporter(reporterId);
}
}
protected class ReportDbMetricsValueCmd implements Command<Void> {
protected String name;
protected long value;
public ReportDbMetricsValueCmd(String name, long value) {
this.name = name;
this.value = value;
}
@Override
public Void execute(CommandContext commandContext) {
commandContext.getMeterLogManager().insert(new MeterLogEntity(name, reporterId, value, ClockUtil.getCurrentTime()));
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\reporter\DbMetricsReporter.java | 1 |
请完成以下Java代码 | public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, exchange);
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
}
return this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, exchange);
} | @Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal,
exchange);
}
private boolean isPrincipalAuthenticated(Authentication authentication) {
return this.authenticationTrustResolver.isAuthenticated(authentication);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\server\AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.java | 1 |
请完成以下Java代码 | protected void createValidCombinationIfNeeded(final I_C_ElementValue elementValue)
{
if (elementValue.isSummary())
{
return;
}
final AccountDimension.Builder accountDimensionTemplate = AccountDimension.builder()
//.setAcctSchemaId(acctSchema.getId())
.setC_ElementValue_ID(elementValue.getC_ElementValue_ID())
.setAD_Client_ID(elementValue.getAD_Client_ID())
.setAD_Org_ID(OrgId.ANY.getRepoId());
final ChartOfAccountsId chartOfAccountsId = ChartOfAccountsId.ofRepoId(elementValue.getC_Element_ID());
for (final AcctSchema acctSchema : acctSchemasRepo.getByChartOfAccountsId(chartOfAccountsId))
{
accountDAO.getOrCreateWithinTrx(accountDimensionTemplate.setAcctSchemaId(acctSchema.getId()).build());
}
} | public static IAutoCloseable temporaryDisableUpdateTreeNode()
{
final boolean wasDisabled = updateTreeNodeDisabled.getAndSet(true);
return () -> updateTreeNodeDisabled.set(wasDisabled);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_ElementValue.COLUMNNAME_Parent_ID, I_C_ElementValue.COLUMNNAME_SeqNo })
public void updateTreeNode(final I_C_ElementValue record)
{
if (updateTreeNodeDisabled.get())
{
return;
}
final ElementValue elementValue = ElementValueRepository.fromRecord(record);
treeNodeService.updateTreeNode(elementValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_ElementValue.java | 1 |
请完成以下Java代码 | public void setReplacementSource (final java.lang.String ReplacementSource)
{
set_Value (COLUMNNAME_ReplacementSource, ReplacementSource);
}
@Override
public java.lang.String getReplacementSource()
{
return get_ValueAsString(COLUMNNAME_ReplacementSource);
}
@Override
public void setReplaceRegExp (final @Nullable java.lang.String ReplaceRegExp)
{
set_Value (COLUMNNAME_ReplaceRegExp, ReplaceRegExp);
}
@Override
public java.lang.String getReplaceRegExp()
{
return get_ValueAsString(COLUMNNAME_ReplaceRegExp);
}
@Override
public void setTargetFieldName (final java.lang.String TargetFieldName)
{
set_Value (COLUMNNAME_TargetFieldName, TargetFieldName);
}
@Override
public java.lang.String getTargetFieldName()
{
return get_ValueAsString(COLUMNNAME_TargetFieldName);
} | /**
* TargetFieldType AD_Reference_ID=541611
* Reference name: AttributeTypeList
*/
public static final int TARGETFIELDTYPE_AD_Reference_ID=541611;
/** textArea = textArea */
public static final String TARGETFIELDTYPE_TextArea = "textArea";
/** EAN13 = EAN13 */
public static final String TARGETFIELDTYPE_EAN13 = "EAN13";
/** EAN128 = EAN128 */
public static final String TARGETFIELDTYPE_EAN128 = "EAN128";
/** numberField = numberField */
public static final String TARGETFIELDTYPE_NumberField = "numberField";
/** date = date */
public static final String TARGETFIELDTYPE_Date = "date";
/** unitChar = unitChar */
public static final String TARGETFIELDTYPE_UnitChar = "unitChar";
/** graphic = graphic */
public static final String TARGETFIELDTYPE_Graphic = "graphic";
@Override
public void setTargetFieldType (final java.lang.String TargetFieldType)
{
set_Value (COLUMNNAME_TargetFieldType, TargetFieldType);
}
@Override
public java.lang.String getTargetFieldType()
{
return get_ValueAsString(COLUMNNAME_TargetFieldType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private class ApiStatsProxyCallback<T> implements TransportServiceCallback<T> {
private final TenantId tenantId;
private final CustomerId customerId;
private final int dataPoints;
private final TransportServiceCallback<T> callback;
public ApiStatsProxyCallback(TenantId tenantId, CustomerId customerId, int dataPoints, TransportServiceCallback<T> callback) {
this.tenantId = tenantId;
this.customerId = customerId;
this.dataPoints = dataPoints;
this.callback = callback;
}
@Override
public void onSuccess(T msg) {
try {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_MSG_COUNT, 1);
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_DP_COUNT, dataPoints);
} finally {
callback.onSuccess(msg);
}
}
@Override
public void onError(Throwable e) {
callback.onError(e);
}
} | @Override
public ExecutorService getCallbackExecutor() {
return transportCallbackExecutor;
}
@Override
public boolean hasSession(TransportProtos.SessionInfoProto sessionInfo) {
return sessions.containsKey(toSessionId(sessionInfo));
}
@Override
public void createGaugeStats(String statsName, AtomicInteger number) {
statsFactory.createGauge(StatsType.TRANSPORT + "." + statsName, number);
statsMap.put(statsName, number);
}
@Scheduled(fixedDelayString = "${transport.stats.print-interval-ms:60000}")
public void printStats() {
if (statsEnabled && !statsMap.isEmpty()) {
String values = statsMap.entrySet().stream()
.map(kv -> kv.getKey() + " [" + kv.getValue() + "]").collect(Collectors.joining(", "));
log.info("Transport Stats: {}", values);
}
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportService.java | 2 |
请完成以下Java代码 | public class BatchJobDeclaration extends JobDeclaration<BatchJobContext, MessageEntity> {
public BatchJobDeclaration(String jobHandlerType) {
super(jobHandlerType);
}
@Override
protected ExecutionEntity resolveExecution(BatchJobContext context) {
return null;
}
@Override
protected MessageEntity newJobInstance(BatchJobContext context) {
return new MessageEntity();
}
@Override
protected JobHandlerConfiguration resolveJobHandlerConfiguration(BatchJobContext context) {
return new BatchJobConfiguration(context.getConfiguration().getId());
}
@Override
protected String resolveJobDefinitionId(BatchJobContext context) {
return context.getBatch().getBatchJobDefinitionId();
} | @Override
public ParameterValueProvider getJobPriorityProvider() {
long batchJobPriority = Context.getProcessEngineConfiguration()
.getBatchJobPriority();
return new ConstantValueProvider(batchJobPriority);
}
@Override
public MessageEntity reconfigure(BatchJobContext context, MessageEntity job) {
super.reconfigure(context, job);
job.setJobHandlerConfiguration(new BatchJobConfiguration(context.getConfiguration().getId()));
return job;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchJobDeclaration.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.