instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Component getTreeCellRendererComponent(JTree tree, Object object, boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
/*
* most of the rendering is delegated to the wrapped
* DefaultTreeCellRenderer, the rest depends on the TreeCheckingModel
*/
this.label.getTreeCellRendererComponent(tree, object, selected, expanded, leaf, row, hasFocus);
if (tree instanceof CheckboxTree) {
TreeCheckingModel checkingModel = ((CheckboxTree) tree).getCheckingModel();
TreePath path = tree.getPathForRow(row);
this.checkBox.setEnabled(checkingModel.isPathEnabled(path));
boolean checked = checkingModel.isPathChecked(path);
boolean greyed = checkingModel.isPathGreyed(path);
if (checked && !greyed) {
this.checkBox.setState(State.CHECKED);
}
if (!checked && greyed) {
this.checkBox.setState(State.GREY_UNCHECKED);
}
if (checked && greyed) {
this.checkBox.setState(State.GREY_CHECKED);
}
if (!checked && !greyed) {
this.checkBox.setState(State.UNCHECKED);
}
}
return this;
}
/**
* Checks if the (x,y) coordinates are on the Checkbox.
*
* @return boolean
* @param x
* @param y
*/
public boolean isOnHotspot(int x, int y) {
// TODO: alternativa (ma funge???)
//return this.checkBox.contains(x, y);
return (this.checkBox.getBounds().contains(x, y));
}
/**
* Loads an ImageIcon from the file iconFile, searching it in the
* classpath.Guarda un po'
*/
protected static ImageIcon loadIcon(String iconFile) {
try {
return new ImageIcon(DefaultCheckboxTreeCellRenderer.class.getClassLoader().getResource(iconFile)); | } catch (NullPointerException npe) { // did not find the resource
return null;
}
}
@Override
public void setBackground(Color color) {
if (color instanceof ColorUIResource) {
color = null;
}
super.setBackground(color);
}
/**
* Sets the icon used to represent non-leaf nodes that are expanded.
*/
public void setOpenIcon(Icon newIcon) {
this.label.setOpenIcon(newIcon);
}
/**
* Sets the icon used to represent non-leaf nodes that are not expanded.
*/
public void setClosedIcon(Icon newIcon) {
this.label.setClosedIcon(newIcon);
}
/**
* Sets the icon used to represent leaf nodes.
*/
public void setLeafIcon(Icon newIcon) {
this.label.setLeafIcon(newIcon);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultCheckboxTreeCellRenderer.java | 1 |
请完成以下Spring Boot application配置 | spring:
ai:
vectorstore:
redis:
uri: redis://:XXXXXXXXXXX@redis-19438.c330.asia-south1-1.gce.redns.redis-cloud.com:19438
index: faqs
prefix: "faq:"
initialize-schema: true
openai:
temperature: 0.3
api-key: ${SPRING_AI_OPENAI_API_KEY}
model: gpt-3.5-turbo
embedding-base-url: https://api.openai | .com
#embedding-api-key: ${SPRING_AI_OPENAI_API_KEY}
#embedding-model: text-embedding-ada-002
main:
allow-bean-definition-overriding: true | repos\tutorials-master\spring-ai-modules\spring-ai-2\src\main\resources\application-airag.yml | 2 |
请完成以下Java代码 | private int retrieveRecordIdByValue(@NonNull final POInfo poInfo, @NonNull final String value)
{
if (!poInfo.hasColumnName(COLUMNNAME_Value))
{
return -1;
}
final String tableName = poInfo.getTableName();
final String keyColumnName = poInfo.getKeyColumnName();
if (keyColumnName == null)
{
throw new AdempiereException("No key column found: " + tableName);
}
final String sql = "SELECT " + keyColumnName
+ " FROM " + tableName
+ " WHERE " + COLUMNNAME_Value + "=?"
+ " ORDER BY " + keyColumnName;
final int recordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, value);
return recordId;
}
@Value
private static class TableAndLookupKey
{
@NonNull | AdTableId adTableId;
@NonNull
String lookupKey;
private TableAndLookupKey(
@NonNull final AdTableId adTableId,
@NonNull final String lookupKey)
{
Check.assumeNotEmpty(lookupKey, "lookupKey is not empty");
this.adTableId = adTableId;
this.lookupKey = lookupKey.trim();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\RecordIdLookup.java | 1 |
请完成以下Java代码 | public void skipAutoDeployment() {
logInfo("020", "ProcessApplication enabled: autoDeployment via springConfiguration#deploymentResourcePattern is disabled");
}
public void autoDeployResources(Set<Resource> resources) {
// Only log the description of `Resource` objects since log libraries that serialize them and
// therefore consume the input stream make the deployment fail since the input stream has
// already been consumed.
Set<String> resourceDescriptions = resources.stream()
.filter(Objects::nonNull)
.map(Resource::getDescription)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
logInfo("021", "Auto-Deploying resources: {}", resourceDescriptions);
}
public void enterLicenseKey(String licenseKeySource) {
logInfo("030", "Setting up license key: {}", licenseKeySource);
} | public void enterLicenseKeyFailed(URL licenseKeyFile, Exception e) {
logWarn("031", "Failed setting up license key: {}", licenseKeyFile, e);
}
public void configureJobExecutorPool(Integer corePoolSize, Integer maxPoolSize) {
logInfo("040", "Setting up jobExecutor with corePoolSize={}, maxPoolSize:{}", corePoolSize, maxPoolSize);
}
public SpringBootStarterException exceptionDuringBinding(String message) {
return new SpringBootStarterException(exceptionMessage(
"050", message));
}
public void propertiesApplied(GenericProperties genericProperties) {
logDebug("051", "Properties bound to configuration: {}", genericProperties);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\SpringBootProcessEngineLogger.java | 1 |
请完成以下Java代码 | private boolean existQuarantineHUs()
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
return retrieveHUsToReceive()
.stream()
.map(handlingUnitsDAO::getById)
.anyMatch(lotNumberQuarantineService::isQuarantineHU);
}
@Override
public void onParameterChanged(String parameterName)
{
if (!WAREHOUSE_PARAM_NAME.equals(parameterName))
{
return;
}
if (warehouseIdOrNull() == null)
{
locatorRepoId = 0;
return;
}
locatorRepoId = warehouseBL.getOrCreateDefaultLocatorId(warehouseId()).getRepoId();
}
@ProcessParamLookupValuesProvider(parameterName = LOCATOR_PARAM_NAME, dependsOn = WAREHOUSE_PARAM_NAME, numericKey = true)
public LookupValuesList getLocators()
{
if (warehouseRepoId <= 0)
{
return LookupValuesList.EMPTY;
}
return warehouseDAO
.getLocators(warehouseId())
.stream() | .map(locator -> IntegerLookupValue.of(locator.getM_Locator_ID(), locator.getValue()))
.collect(LookupValuesList.collect());
}
@Override
protected void customizeParametersBuilder(@NonNull final CreateReceiptsParametersBuilder parametersBuilder)
{
final LocatorId locatorId = LocatorId.ofRepoIdOrNull(warehouseIdOrNull(), locatorRepoId);
parametersBuilder.destinationLocatorIdOrNull(locatorId);
}
private WarehouseId warehouseId()
{
return WarehouseId.ofRepoId(warehouseRepoId);
}
private WarehouseId warehouseIdOrNull()
{
return WarehouseId.ofRepoIdOrNull(warehouseRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_LocatorParams.java | 1 |
请完成以下Java代码 | 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代码 | public class ImpFormatId implements RepoIdAware
{
@JsonCreator
public static ImpFormatId ofRepoId(final int repoId)
{
return new ImpFormatId(repoId);
}
public static ImpFormatId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ImpFormatId(repoId) : null;
}
int repoId;
private ImpFormatId(final int repoId) | {
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_ImpFormat_ID");
}
@JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final ImpFormatId id)
{
return id != null ? id.getRepoId() : -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatId.java | 2 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
cloud:
# Spring Cloud Gateway 配置项,全部配置在 Nacos 中
# gateway:
# Nacos 作为注册中心的配置项
nacos:
| discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址 | repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo03-config-nacos\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public <T> Comparator<T> comparator(@NonNull final Function<T, LocalDate> bestBeforeDateExtractor)
{
return (value1, value2) -> {
final LocalDate bestBefore1 = bestBeforeDateExtractor.apply(value1);
final LocalDate bestBefore2 = bestBeforeDateExtractor.apply(value2);
return compareBestBeforeDates(bestBefore1, bestBefore2);
};
}
private int compareBestBeforeDates(@Nullable final LocalDate bestBefore1, @Nullable final LocalDate bestBefore2)
{
if (this == Expiring_First)
{
final LocalDate bestBefore1Effective = CoalesceUtil.coalesceNotNull(bestBefore1, LocalDate.MAX);
final LocalDate bestBefore2Effective = CoalesceUtil.coalesceNotNull(bestBefore2, LocalDate.MAX); | return bestBefore1Effective.compareTo(bestBefore2Effective);
}
else if (this == Newest_First)
{
final LocalDate bestBefore1Effective = CoalesceUtil.coalesceNotNull(bestBefore1, LocalDate.MIN);
final LocalDate bestBefore2Effective = CoalesceUtil.coalesceNotNull(bestBefore2, LocalDate.MIN);
return -1 * bestBefore1Effective.compareTo(bestBefore2Effective);
}
else
{
throw new AdempiereException("Unknown policy: " + this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\ShipmentAllocationBestBeforePolicy.java | 1 |
请完成以下Java代码 | public void setDecisionDefinitionName(String decisionDefinitionName) {
this.decisionDefinitionName = decisionDefinitionName;
}
public int getDecisionDefinitionVersion() {
return decisionDefinitionVersion;
}
public void setDecisionDefinitionVersion(int decisionDefinitionVersion) {
this.decisionDefinitionVersion = decisionDefinitionVersion;
}
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public void setHistoryTimeToLive(Integer historyTimeToLive) {
this.historyTimeToLive = historyTimeToLive;
}
public long getFinishedDecisionInstanceCount() {
return finishedDecisionInstanceCount;
}
public void setFinishedDecisionInstanceCount(long finishedDecisionInstanceCount) {
this.finishedDecisionInstanceCount = finishedDecisionInstanceCount;
}
public long getCleanableDecisionInstanceCount() { | return cleanableDecisionInstanceCount;
}
public void setCleanableDecisionInstanceCount(long cleanableDecisionInstanceCount) {
this.cleanableDecisionInstanceCount = cleanableDecisionInstanceCount;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String toString() {
return this.getClass().getSimpleName()
+ "[decisionDefinitionId = " + decisionDefinitionId
+ ", decisionDefinitionKey = " + decisionDefinitionKey
+ ", decisionDefinitionName = " + decisionDefinitionName
+ ", decisionDefinitionVersion = " + decisionDefinitionVersion
+ ", historyTimeToLive = " + historyTimeToLive
+ ", finishedDecisionInstanceCount = " + finishedDecisionInstanceCount
+ ", cleanableDecisionInstanceCount = " + cleanableDecisionInstanceCount
+ ", tenantId = " + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CleanableHistoricDecisionInstanceReportResultEntity.java | 1 |
请完成以下Java代码 | public Object before(JoinPoint point) {
//get params
Object[] args = point.getArgs();
//get param name
Method method = ((MethodSignature) point.getSignature()).getMethod();
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] paramNames = u.getParameterNames(method);
CheckContainer checkContainer = method.getDeclaredAnnotation(CheckContainer.class);
List<Check> value = new ArrayList<>();
if (checkContainer != null) {
value.addAll(Arrays.asList(checkContainer.value()));
} else {
Check check = method.getDeclaredAnnotation(Check.class);
value.add(check);
}
for (int i = 0; i < value.size(); i++) {
Check check = value.get(i);
String ex = check.ex();
//In the rule engine, null is represented by nil
ex = ex.replaceAll("null", "nil");
String msg = check.msg();
if (StringUtils.isEmpty(msg)) {
msg = "server exception...";
}
Map<String, Object> map = new HashMap<>(16); | for (int j = 0; j < paramNames.length; j++) {
//Prevent index out of bounds
if (j > args.length) {
continue;
}
map.put(paramNames[j], args[j]);
}
Boolean result = (Boolean) AviatorEvaluator.execute(ex, map);
if (!result) {
throw new UserFriendlyException(msg);
}
}
return null;
}
} | repos\springboot-demo-master\Aviator\src\main\java\com\et\annotation\AopConfig.java | 1 |
请完成以下Java代码 | public void setIsOwnBank (final boolean IsOwnBank)
{
set_Value (COLUMNNAME_IsOwnBank, IsOwnBank);
}
@Override
public boolean isOwnBank()
{
return get_ValueAsBoolean(COLUMNNAME_IsOwnBank);
}
@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 setRoutingNo (final java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setSwiftCode (final @Nullable java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
@Override
public java.lang.String getSwiftCode()
{
return get_ValueAsString(COLUMNNAME_SwiftCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Bank.java | 1 |
请完成以下Java代码 | public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
} | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\DepartIdModel.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-application-rabbitmq
# RabbitMQ 配置项,对应 RabbitProperties 配置类
rabbitmq:
host: 127.0.0.1 # RabbitMQ 服务的地址
port: 5672 # RabbitMQ 服务 | 的端口
username: guest # RabbitMQ 服务的账号
password: guest # RabbitMQ 服务的密码 | repos\SpringBoot-Labs-master\lab-40\lab-40-rabbitmq\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | private static class OnVerboseDisabledCondition extends NoneNestedConditions {
OnVerboseDisabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = "spring.cloud.gateway.server.webflux.actuator.verbose.enabled",
matchIfMissing = true)
static class VerboseDisabled {
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.cloud.gateway.server.webflux.enabled", matchIfMissing = true)
@ConditionalOnClass({ OAuth2AuthorizedClient.class, SecurityWebFilterChain.class, SecurityProperties.class })
@ConditionalOnEnabledFilter(TokenRelayGatewayFilterFactory.class)
protected static class TokenRelayConfiguration {
@Bean
public TokenRelayGatewayFilterFactory tokenRelayGatewayFilterFactory(
ObjectProvider<ReactiveOAuth2AuthorizedClientManager> clientManager) {
return new TokenRelayGatewayFilterFactory(clientManager);
}
}
}
class GatewayHints implements RuntimeHintsRegistrar {
@Override | public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
if (!ClassUtils.isPresent("org.springframework.cloud.gateway.route.RouteLocator", classLoader)) {
return;
}
hints.reflection()
.registerType(TypeReference.of(FilterDefinition.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(PredicateDefinition.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(AbstractNameValueGatewayFilterFactory.NameValueConfig.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference
.of("org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator$DelegatingServiceInstance"),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayAutoConfiguration.java | 2 |
请完成以下Java代码 | protected Authentication getCurrentAuthentication() {
return Context.getCommandContext().getAuthentication();
}
protected ResourceAuthorizationProvider getResourceAuthorizationProvider() {
return Context.getProcessEngineConfiguration()
.getResourceAuthorizationProvider();
}
protected void deleteAuthorizations(Resource resource, String resourceId) {
getAuthorizationManager().deleteAuthorizationsByResourceId(resource, resourceId);
}
protected void deleteAuthorizationsForUser(Resource resource, String resourceId, String userId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndUserId(resource, resourceId, userId);
}
protected void deleteAuthorizationsForGroup(Resource resource, String resourceId, String groupId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndGroupId(resource, resourceId, groupId);
}
public void saveDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) { | if(authorization.getId() == null) {
authorizationManager.insert(authorization);
} else {
authorizationManager.update(authorization);
}
}
return null;
}
});
}
}
public void deleteDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
authorizationManager.delete(authorization);
}
return null;
}
});
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public final class BPartnerCompositeCacheByLookupKey
{
private final transient CCache<OrgAndBPartnerCompositeLookupKey, BPartnerComposite> cache;
public BPartnerCompositeCacheByLookupKey(@NonNull final String identifier)
{
final CacheIndex<BPartnerId/* RK */, OrgAndBPartnerCompositeLookupKey/* CK */, BPartnerComposite/* V */> //
cacheIndex = CacheIndex.of(new BPartnerCompositeCacheIndex());
cache = CCache.<OrgAndBPartnerCompositeLookupKey, BPartnerComposite>builder()
.cacheName("BPartnerComposite_by_LookupKey" + "_" + identifier)
.additionalTableNameToResetFor(I_AD_User.Table_Name)
.additionalTableNameToResetFor(I_C_BPartner.Table_Name)
.additionalTableNameToResetFor(I_C_BPartner_Location.Table_Name)
.cacheMapType(CacheMapType.LRU)
.initialCapacity(100)
.invalidationKeysMapper(cacheIndex)
.removalListener(cacheIndex::remove)
.additionListener(cacheIndex::add)
.build();
}
public Collection<BPartnerComposite> getAllOrLoad(
@NonNull final Collection<OrgAndBPartnerCompositeLookupKey> keys,
@NonNull final Function<
Set<OrgAndBPartnerCompositeLookupKey>, | Map<OrgAndBPartnerCompositeLookupKey, BPartnerComposite>> valuesLoader)
{
return cache.getAllOrLoad(keys, valuesLoader);
}
/**
* Get all the records, assuming that there is a cache entry for each single record. If not, throw an exception.
*/
@VisibleForTesting
public Collection<BPartnerComposite> getAssertAllCached(
@NonNull final Collection<OrgAndBPartnerCompositeLookupKey> keys)
{
final ImmutableList.Builder<BPartnerComposite> result = ImmutableList.builder();
for (final OrgAndBPartnerCompositeLookupKey key : keys)
{
result.add(cache.getOrElseThrow(
key,
() -> new AdempiereException("Missing record for key=" + key)));
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\BPartnerCompositeCacheByLookupKey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Config {
@Bean
ConcurrentKafkaListenerContainerFactory<Integer, String>
kafkaListenerContainerFactory(ConsumerFactory<Integer, String> consumerFactory) {
ConcurrentKafkaListenerContainerFactory<Integer, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory);
return factory;
}
@Bean
public ConsumerFactory<Integer, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerProps());
}
private Map<String, Object> consumerProps() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "group");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// ...
return props;
}
@Bean
public Sender sender(KafkaTemplate<Integer, String> template) {
return new Sender(template);
}
@Bean
public Listener listener() {
return new Listener();
}
@Bean
public ProducerFactory<Integer, String> producerFactory() { | return new DefaultKafkaProducerFactory<>(senderProps());
}
private Map<String, Object> senderProps() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(ProducerConfig.LINGER_MS_CONFIG, 10);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
//...
return props;
}
@Bean
public KafkaTemplate<Integer, String> kafkaTemplate(ProducerFactory<Integer, String> producerFactory) {
return new KafkaTemplate<>(producerFactory);
}
}
// end::startedNoBootConfig[] | repos\spring-kafka-main\spring-kafka-docs\src\main\java\org\springframework\kafka\jdocs\started\noboot\Config.java | 2 |
请完成以下Java代码 | private static String cleanup (String title)
{
if (title != null)
{
int pos = title.indexOf('&');
if (pos != -1 && title.length() > pos) // We have a mnemonic
{
int mnemonic = title.toUpperCase().charAt(pos+1);
if (mnemonic != ' ')
{
title = title.substring(0, pos) + title.substring(pos+1);
}
}
}
return title;
} // getTitle
/**
* Set Title | * @param title title
*/
@Override
public void setTitle(String title)
{
super.setTitle(cleanup(title));
} // setTitle
public AdWindowId getAdWindowId()
{
return adWindowId;
} // getAD_Window_ID
public void setAdWindowId(@Nullable final AdWindowId adWindowId)
{
this.adWindowId = adWindowId;
}
} // CFrame | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CFrame.java | 1 |
请完成以下Java代码 | public I_M_HU_PI getM_LU_HU_PI()
{
return lutuConfig.getM_LU_HU_PI();
}
@Override
public I_M_HU_PI getM_TU_HU_PI()
{
return lutuConfig.getM_TU_HU_PI();
}
@Override
public boolean isInfiniteQtyTUsPerLU()
{
return lutuConfig.isInfiniteQtyTU();
}
@Override
public BigDecimal getQtyTUsPerLU()
{
return lutuConfig.getQtyTU();
}
@Override
public boolean isInfiniteQtyCUsPerTU()
{ | return lutuConfig.isInfiniteQtyCU();
}
@Override
public BigDecimal getQtyCUsPerTU()
{
return lutuConfig.getQtyCUsPerTU();
}
@Override
public I_C_UOM getQtyCUsPerTU_UOM()
{
return ILUTUConfigurationFactory.extractUOMOrNull(lutuConfig);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\LUTUConfigAsPackingInfo.java | 1 |
请完成以下Java代码 | public void setCode(final @NonNull String code)
{
this.code = code;
this.codeSet = true;
}
public void setName(final @NonNull String name)
{
this.name = name;
this.nameSet = true;
}
public void setType(final @NonNull Type type)
{
this.type = type;
this.typeSet = true;
}
public void setUomCode(final @NonNull String uomCode)
{
this.uomCode = uomCode;
this.uomCodeSet = true;
}
public void setEan(final String ean)
{
this.ean = ean;
this.eanSet = true;
}
public void setGtin(final String gtin)
{
this.gtin = gtin;
this.gtinSet = true;
}
public void setDescription(final String description)
{
this.description = description;
this.descriptionSet = true;
}
public void setDiscontinued(final Boolean discontinued)
{
this.discontinued = discontinued;
this.discontinuedSet = true;
}
public void setDiscontinuedFrom(final LocalDate discontinuedFrom)
{
this.discontinuedFrom = discontinuedFrom;
this.discontinuedFromSet = true;
}
public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
} | public void setStocked(final Boolean stocked)
{
this.stocked = stocked;
this.stockedSet = true;
}
public void setProductCategoryIdentifier(final String productCategoryIdentifier)
{
this.productCategoryIdentifier = productCategoryIdentifier;
this.productCategoryIdentifierSet = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
}
public void setBpartnerProductItems(final List<JsonRequestBPartnerProductUpsert> bpartnerProductItems)
{
this.bpartnerProductItems = bpartnerProductItems;
}
public void setProductTaxCategories(final List<JsonRequestProductTaxCategoryUpsert> productTaxCategories)
{
this.productTaxCategories = productTaxCategories;
}
public void setUomConversions(final List<JsonRequestUOMConversionUpsert> uomConversions)
{
this.uomConversions = uomConversions;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProduct.java | 1 |
请完成以下Java代码 | public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
// adjust xml generate directory
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// custom file name
return projectDir + "/src/main/resources/mybatis/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
// =================== strategy setting ==================
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel) // table name: underline_to_camel
.setColumnNaming(NamingStrategy.underline_to_camel) // file name: underline_to_camel
.setInclude(tableNames) // tableNames
.setCapitalMode(true) // enable CapitalMod(ORACLE )
.setTablePrefix(prefixTable) // remove table prefix
// .setFieldPrefix(pc.getModuleName() + "_") // remove fields prefix
// .setSuperEntityClass("com.maoxs.pojo") // Entity implement
// .setSuperControllerClass("com.maoxs.controller") // Controller implement
// .setSuperEntityColumns("id") // Super Columns
// .setEntityLombokModel(true) // enable lombok
.setControllerMappingHyphenStyle(true); // controller MappingHyphenStyle
// ================== custome template setting:default mybatis-plus/src/main/resources/templates ======================
//default: src/main/resources/templates directory
TemplateConfig tc = new TemplateConfig();
tc.setXml(null) // xml template
.setEntity("/templates/entity.java") // entity template
.setMapper("/templates/mapper.java") // mapper template | .setController("/templates/controller.java") // service template
.setService("/templates/service.java") // serviceImpl template
.setServiceImpl("/templates/serviceImpl.java"); // controller template
// ==================== gen setting ===================
AutoGenerator mpg = new AutoGenerator();
mpg.setCfg(cfg)
.setTemplate(tc)
.setGlobalConfig(gc)
.setDataSource(dsc)
.setPackageInfo(pc)
.setStrategy(strategy)
.setTemplateEngine(new FreemarkerTemplateEngine()); // choose freemarker engine,pay attention to pom dependency!
mpg.execute();
}
} | repos\springboot-demo-master\generator\src\main\java\com\et\generator\Generator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Optional<AdImageId> retrieveImageId(@NonNull final OrgResourceNameContext context)
{
final OrgId adOrgId = context.getOrgId();
if (adOrgId.isAny())
{
return Optional.empty();
}
if (orgLogoResourceNameMatcher.matches(context.getResourceName()))
{
return Optional.ofNullable(retrieveLogoImageId(adOrgId));
}
final String imageColumnName = OrgImageResourceNameMatcher.instance.getImageColumnName(context.getResourceName()).orElse(null);
if (imageColumnName == null)
{
return Optional.empty();
}
return orgsRepo.getOrgInfoById(adOrgId)
.getImagesMap()
.getImageId(imageColumnName);
}
@Nullable
private AdImageId retrieveLogoImageId(@NonNull final OrgId adOrgId)
{
//
// Get Logo from Organization's BPartner
// task FRESH-356: get logo also from organization's bpartner if is set
final Properties ctx = Env.getCtx();
final I_AD_Org org = orgsRepo.getById(adOrgId);
if (org != null)
{
final I_C_BPartner orgBPartner = bpartnerOrgBL.retrieveLinkedBPartner(org);
if (orgBPartner != null)
{
final AdImageId orgBPartnerLogoId = AdImageId.ofRepoIdOrNull(orgBPartner.getLogo_ID());
if (orgBPartnerLogoId != null)
{
return orgBPartnerLogoId;
}
}
}
// | // Get Org Logo
final OrgInfo orgInfo = orgsRepo.getOrgInfoById(adOrgId);
final AdImageId logoImageId = orgInfo.getImagesMap().getLogoId().orElse(null);
if (logoImageId != null)
{
return logoImageId;
}
//
// Get Tenant level Logo
final ClientId adClientId = orgInfo.getClientId();
final I_AD_ClientInfo clientInfo = clientsRepo.retrieveClientInfo(ctx, adClientId.getRepoId());
AdImageId clientLogoId = AdImageId.ofRepoIdOrNull(clientInfo.getLogoReport_ID());
if (clientLogoId == null)
{
clientLogoId = AdImageId.ofRepoIdOrNull(clientInfo.getLogo_ID());
}
return clientLogoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\images\org\OrgImageLocalFileLoader.java | 2 |
请完成以下Java代码 | public class PerfectSquareUtil {
public static boolean isPerfectSquareByUsingSqrt(long n) {
if (n <= 0)
return false;
double perfectSquare = Math.sqrt(n);
long tst = (long)(perfectSquare + 0.5);
return tst*tst == n;
}
public static boolean isPerfectSquareByUsingBinarySearch(long low, long high, long number) {
long check = (low + high) / 2L;
if (high < low)
return false;
if (number == check * check) {
return true;
} else if (number < check * check) {
high = check - 1L;
return isPerfectSquareByUsingBinarySearch(low, high, number);
} else {
low = check + 1L;
return isPerfectSquareByUsingBinarySearch(low, high, number);
}
}
public static boolean isPerfectSquareByUsingNewtonMethod(long n) {
long x1 = n;
long x2 = 1L;
while (x1 > x2) {
x1 = (x1 + x2) / 2L;
x2 = n / x1;
} | return x1 == x2 && n % x1 == 0L;
}
public static boolean isPerfectSquareWithOptimization(long n) {
if (n < 0)
return false;
switch ((int) (n & 0xF)) {
case 0: case 1: case 4: case 9:
long tst = (long) Math.sqrt(n);
return tst * tst == n;
default:
return false;
}
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-4\src\main\java\com\baeldung\perfectsquare\PerfectSquareUtil.java | 1 |
请完成以下Java代码 | class HUIdsFilterDataToSqlCaseConverter implements HUIdsFilterData.CaseConverter<FilterSql>
{
// services
private IHandlingUnitsDAO handlingUnitsDAO() {return Services.get(IHandlingUnitsDAO.class);}
@Nullable
private FilterSql.RecordsToAlwaysIncludeSql toAlwaysIncludeSql(final @NonNull Set<HuId> alwaysIncludeHUIds)
{
return !alwaysIncludeHUIds.isEmpty()
? FilterSql.RecordsToAlwaysIncludeSql.ofColumnNameAndRecordIds(I_M_HU.COLUMNNAME_M_HU_ID, alwaysIncludeHUIds)
: null;
}
private IHUQueryBuilder newHUQuery()
{
return handlingUnitsDAO()
.createHUQueryBuilder()
.setContext(PlainContextAware.newOutOfTrx())
.setOnlyActiveHUs(false) // let other enforce this rule
.setOnlyTopLevelHUs(false); // let other enforce this rule
}
private SqlAndParams toSql(@NonNull final IHUQueryBuilder huQuery)
{
final ISqlQueryFilter sqlQueryFilter = ISqlQueryFilter.cast(huQuery.createQueryFilter());
return SqlAndParams.of(
sqlQueryFilter.getSql(),
sqlQueryFilter.getSqlParams(Env.getCtx()));
}
@Override
public FilterSql acceptAll() {return FilterSql.ALLOW_ALL;}
@Override
public FilterSql acceptAllBut(@NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds)
{
final SqlAndParams whereClause = !excludeHUIds.isEmpty()
? toSql(newHUQuery().addHUIdsToExclude(excludeHUIds))
: null;
return FilterSql.builder()
.whereClause(whereClause)
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
@Override | public FilterSql acceptNone() {return FilterSql.ALLOW_NONE;}
@Override
public FilterSql acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds)
{
final SqlAndParams whereClause = fixedHUIds.isNone()
? FilterSql.ALLOW_NONE.getWhereClause()
: toSql(newHUQuery().addOnlyHUIds(fixedHUIds.toSet()));
return FilterSql.builder()
.whereClause(whereClause)
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
@Override
public FilterSql huQuery(final @NonNull IHUQueryBuilder initialHUQueryCopy, final @NonNull Set<HuId> alwaysIncludeHUIds, final @NonNull Set<HuId> excludeHUIds)
{
initialHUQueryCopy.setContext(PlainContextAware.newOutOfTrx());
initialHUQueryCopy.addHUIdsToAlwaysInclude(alwaysIncludeHUIds);
initialHUQueryCopy.addHUIdsToExclude(excludeHUIds);
return FilterSql.builder()
.whereClause(toSql(initialHUQueryCopy))
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterDataToSqlCaseConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OrderProperties orderProperties;
/**
* 测试 @ConfigurationProperties 注解的配置属性类
*/
@GetMapping("/test01")
public OrderProperties test01() {
return orderProperties;
}
@Value(value = "${order.pay-timeout-seconds}")
private Integer payTimeoutSeconds;
@Value(value = "${order.create-frequency-seconds}")
private Integer createFrequencySeconds;
/** | * 测试 @Value 注解的属性
*/
@GetMapping("/test02")
public Map<String, Object> test02() {
Map<String, Object> result = new HashMap<>();
result.put("payTimeoutSeconds", payTimeoutSeconds);
result.put("createFrequencySeconds", createFrequencySeconds);
return result;
}
@GetMapping("/logger")
public void logger() {
logger.debug("[logger][测试一下]");
}
} | repos\SpringBoot-Labs-master\labx-09-spring-cloud-apollo\labx-09-sc-apollo-demo-auto-refresh\src\main\java\cn\iocoder\springcloud\labx09\apollodemo\controller\DemoController.java | 2 |
请完成以下Java代码 | private static ICalendarIncrementor createCalendarIncrementor(final Frequency frequency)
{
if (frequency.isWeekly())
{
return CalendarIncrementors.eachNthWeek(frequency.getEveryNthWeek(), DayOfWeek.MONDAY);
}
else if (frequency.isMonthly())
{
return CalendarIncrementors.eachNthMonth(frequency.getEveryNthMonth(), 1); // every given month, 1st day
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
private static IDateSequenceExploder createDateSequenceExploder(final Frequency frequency)
{
if (frequency.isWeekly())
{ | if (frequency.isOnlySomeDaysOfTheWeek())
{
return DaysOfWeekExploder.of(frequency.getOnlyDaysOfWeek());
}
else
{
return DaysOfWeekExploder.ALL_DAYS_OF_WEEK;
}
}
else if (frequency.isMonthly())
{
return DaysOfMonthExploder.of(frequency.getOnlyDaysOfMonth());
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DateSequenceGenerator.java | 1 |
请完成以下Java代码 | static class OnPropertyEnabled {
}
@ConditionalOnPropertyExists(GatewayMvcProperties.PREFIX + ".trusted-proxies")
static class OnTrustedProxiesNotEmpty {
}
}
class XForwardedTrustedProxiesCondition extends AllNestedConditions {
public XForwardedTrustedProxiesCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = XForwardedRequestHeadersFilterProperties.PREFIX + ".enabled",
matchIfMissing = true)
static class OnPropertyEnabled {
}
@ConditionalOnPropertyExists(GatewayMvcProperties.PREFIX + ".trusted-proxies")
static class OnTrustedProxiesNotEmpty {
}
}
class OnPropertyExistsCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
String value = metadata.getAnnotations().get(ConditionalOnPropertyExists.class).getString("value"); | String property = context.getEnvironment().getProperty(value);
if (!StringUtils.hasText(property)) {
return ConditionOutcome.noMatch(value + " property is not set or is empty.");
}
return ConditionOutcome.match(value + " property is not empty.");
}
catch (NoSuchElementException e) {
return ConditionOutcome.noMatch("Missing required property 'value' of @ConditionalOnPropertyExists");
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyExistsCondition.class)
@interface ConditionalOnPropertyExists {
/**
* @return the property
*/
String value();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\TrustedProxies.java | 1 |
请完成以下Java代码 | public EventRegistryEngineConfiguration addPostDefaultELResolver(ELResolver elResolver) {
if (this.postDefaultELResolvers == null) {
this.postDefaultELResolvers = new ArrayList<>();
}
this.postDefaultELResolvers.add(elResolver);
return this;
}
public EventJsonConverter getEventJsonConverter() {
return eventJsonConverter;
}
public EventRegistryEngineConfiguration setEventJsonConverter(EventJsonConverter eventJsonConverter) {
this.eventJsonConverter = eventJsonConverter;
return this;
}
public ChannelJsonConverter getChannelJsonConverter() { | return channelJsonConverter;
}
public EventRegistryEngineConfiguration setChannelJsonConverter(ChannelJsonConverter channelJsonConverter) {
this.channelJsonConverter = channelJsonConverter;
return this;
}
public boolean isEnableEventRegistryChangeDetectionAfterEngineCreate() {
return enableEventRegistryChangeDetectionAfterEngineCreate;
}
public EventRegistryEngineConfiguration setEnableEventRegistryChangeDetectionAfterEngineCreate(boolean enableEventRegistryChangeDetectionAfterEngineCreate) {
this.enableEventRegistryChangeDetectionAfterEngineCreate = enableEventRegistryChangeDetectionAfterEngineCreate;
return this;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\EventRegistryEngineConfiguration.java | 1 |
请完成以下Java代码 | public Set<Class<? extends Throwable>> getExceptions() {
return exceptions;
}
public RetryConfig setExceptions(Set<Class<? extends Throwable>> exceptions) {
this.exceptions = exceptions;
return this;
}
public RetryConfig addExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions.addAll(Arrays.asList(exceptions));
return this;
}
public Set<HttpMethod> getMethods() {
return methods;
}
public RetryConfig setMethods(Set<HttpMethod> methods) {
this.methods = methods;
return this;
}
public RetryConfig addMethods(HttpMethod... methods) {
this.methods.addAll(Arrays.asList(methods));
return this;
}
public boolean isCacheBody() {
return cacheBody;
} | public RetryConfig setCacheBody(boolean cacheBody) {
this.cacheBody = cacheBody;
return this;
}
}
public static class RetryException extends NestedRuntimeException {
private final ServerRequest request;
private final ServerResponse response;
RetryException(ServerRequest request, ServerResponse response) {
super(null);
this.request = request;
this.response = response;
}
public ServerRequest getRequest() {
return request;
}
public ServerResponse getResponse() {
return response;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RetryFilterFunctions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ActiveMQConnectionDetails activemqConnectionDetails(ActiveMQProperties properties) {
return new PropertiesActiveMQConnectionDetails(properties);
}
/**
* Adapts {@link ActiveMQProperties} to {@link ActiveMQConnectionDetails}.
*/
static class PropertiesActiveMQConnectionDetails implements ActiveMQConnectionDetails {
private final ActiveMQProperties properties;
PropertiesActiveMQConnectionDetails(ActiveMQProperties properties) {
this.properties = properties;
}
@Override | public String getBrokerUrl() {
return this.properties.determineBrokerUrl();
}
@Override
public @Nullable String getUser() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQAutoConfiguration.java | 2 |
请完成以下Java代码 | public class InfixToPostFixExpressionConversion {
private int getPrecedenceScore(char ch) {
switch (ch) {
case '^':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
}
return -1;
}
private boolean isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
}
private char associativity(char ch) {
if (ch == '^')
return 'R';
return 'L';
}
public String infixToPostfix(String infix) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i); | if (isOperand(ch)) {
result.append(ch);
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
}
stack.pop();
} else {
while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) {
result.append(stack.pop());
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.toString();
}
private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) {
return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L';
}
} | repos\tutorials-master\core-java-modules\core-java-lang-operators-3\src\main\java\com\baeldung\infixpostfix\InfixToPostFixExpressionConversion.java | 1 |
请完成以下Java代码 | public Criteria andSpDataNotIn(List<String> values) {
addCriterion("sp_data not in", values, "spData");
return (Criteria) this;
}
public Criteria andSpDataBetween(String value1, String value2) {
addCriterion("sp_data between", value1, value2, "spData");
return (Criteria) this;
}
public Criteria andSpDataNotBetween(String value1, String value2) {
addCriterion("sp_data not between", value1, value2, "spData");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null; | this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsSkuStockExample.java | 1 |
请完成以下Java代码 | public class CollectionUtils {
private CollectionUtils() {
}
public static <T> void print(T item) {
System.out.println(item);
}
public static void swap(List<?> list, int src, int des) {
swapHelper(list, src, des);
}
private static <E> void swapHelper(List<E> list, int src, int des) {
list.set(src, list.set(des, list.get(src)));
}
public static <E> List<E> mergeTypeParameter(List<? extends E> listOne, List<? extends E> listTwo) {
return Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
}
public static <E> List<? extends E> mergeWildcard(List<? extends E> listOne, List<? extends E> listTwo) {
return Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
}
public static long sum(List<Number> numbers) {
return numbers.stream()
.mapToLong(Number::longValue)
.sum();
} | public static <T extends Number> long sumTypeParameter(List<T> numbers) {
return numbers.stream()
.mapToLong(Number::longValue)
.sum();
}
public static long sumWildcard(List<? extends Number> numbers) {
return numbers.stream()
.mapToLong(Number::longValue)
.sum();
}
public static void addNumber(List<? super Integer> list, Integer number) {
list.add(number);
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\generics\CollectionUtils.java | 1 |
请完成以下Java代码 | public static InputStream downFile(String groupName, String remoteFileName) {
try {
StorageClient storageClient = getStorageClient();
byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
InputStream ins = new ByteArrayInputStream(fileByte);
return ins;
} catch (IOException e) {
logger.error("IO Exception: Get File from Fast DFS failed", e);
} catch (Exception e) {
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
}
return null;
}
public static void deleteFile(String groupName, String remoteFileName)
throws Exception {
StorageClient storageClient = getStorageClient();
int i = storageClient.delete_file(groupName, remoteFileName);
logger.info("delete file successfully!!!" + i);
}
public static StorageServer[] getStoreStorages(String groupName)
throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerClient.getStoreStorages(trackerServer, groupName);
}
public static ServerInfo[] getFetchStorages(String groupName,
String remoteFileName) throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection(); | return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
}
public static String getTrackerUrl() throws IOException {
return "http://"+getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+"/";
}
private static StorageClient getStorageClient() throws IOException {
TrackerServer trackerServer = getTrackerServer();
StorageClient storageClient = new StorageClient(trackerServer, null);
return storageClient;
}
private static TrackerServer getTrackerServer() throws IOException {
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
return trackerServer;
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-7 课:使用 Spring Boot 上传文件到 FastDFS\spring-boot-fastDFS\src\main\java\com\neo\fastdfs\FastDFSClient.java | 1 |
请完成以下Java代码 | public void setC_OLCandAggAndOrder_ID (final int C_OLCandAggAndOrder_ID)
{
if (C_OLCandAggAndOrder_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCandAggAndOrder_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCandAggAndOrder_ID, C_OLCandAggAndOrder_ID);
}
@Override
public int getC_OLCandAggAndOrder_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCandAggAndOrder_ID);
}
@Override
public de.metas.ordercandidate.model.I_C_OLCandProcessor getC_OLCandProcessor()
{
return get_ValueAsPO(COLUMNNAME_C_OLCandProcessor_ID, de.metas.ordercandidate.model.I_C_OLCandProcessor.class);
}
@Override
public void setC_OLCandProcessor(final de.metas.ordercandidate.model.I_C_OLCandProcessor C_OLCandProcessor)
{
set_ValueFromPO(COLUMNNAME_C_OLCandProcessor_ID, de.metas.ordercandidate.model.I_C_OLCandProcessor.class, C_OLCandProcessor);
}
@Override
public void setC_OLCandProcessor_ID (final int C_OLCandProcessor_ID)
{
if (C_OLCandProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCandProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCandProcessor_ID, C_OLCandProcessor_ID);
}
@Override
public int getC_OLCandProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCandProcessor_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* Granularity AD_Reference_ID=540141
* Reference name: Granularity OLCandAggAndOrder
*/
public static final int GRANULARITY_AD_Reference_ID=540141;
/** Tag = D */ | public static final String GRANULARITY_Tag = "D";
/** Woche = W */
public static final String GRANULARITY_Woche = "W";
/** Monat = M */
public static final String GRANULARITY_Monat = "M";
@Override
public void setGranularity (final @Nullable java.lang.String Granularity)
{
set_Value (COLUMNNAME_Granularity, Granularity);
}
@Override
public java.lang.String getGranularity()
{
return get_ValueAsString(COLUMNNAME_Granularity);
}
@Override
public void setGroupBy (final boolean GroupBy)
{
set_Value (COLUMNNAME_GroupBy, GroupBy);
}
@Override
public boolean isGroupBy()
{
return get_ValueAsBoolean(COLUMNNAME_GroupBy);
}
@Override
public void setOrderBySeqNo (final int OrderBySeqNo)
{
set_Value (COLUMNNAME_OrderBySeqNo, OrderBySeqNo);
}
@Override
public int getOrderBySeqNo()
{
return get_ValueAsInt(COLUMNNAME_OrderBySeqNo);
}
@Override
public void setSplitOrder (final boolean SplitOrder)
{
set_Value (COLUMNNAME_SplitOrder, SplitOrder);
}
@Override
public boolean isSplitOrder()
{
return get_ValueAsBoolean(COLUMNNAME_SplitOrder);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCandAggAndOrder.java | 1 |
请完成以下Java代码 | public void setAD_BusinessRule(final org.compiere.model.I_AD_BusinessRule AD_BusinessRule)
{
set_ValueFromPO(COLUMNNAME_AD_BusinessRule_ID, org.compiere.model.I_AD_BusinessRule.class, AD_BusinessRule);
}
@Override
public void setAD_BusinessRule_ID (final int AD_BusinessRule_ID)
{
if (AD_BusinessRule_ID < 1)
set_Value (COLUMNNAME_AD_BusinessRule_ID, null);
else
set_Value (COLUMNNAME_AD_BusinessRule_ID, AD_BusinessRule_ID);
}
@Override
public int getAD_BusinessRule_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_ID);
}
@Override
public void setAD_BusinessRule_WarningTarget_ID (final int AD_BusinessRule_WarningTarget_ID)
{
if (AD_BusinessRule_WarningTarget_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_WarningTarget_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_BusinessRule_WarningTarget_ID, AD_BusinessRule_WarningTarget_ID);
}
@Override
public int getAD_BusinessRule_WarningTarget_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_BusinessRule_WarningTarget_ID);
}
@Override
public void setAD_Table_ID (final int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID);
} | @Override
public int getAD_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Table_ID);
}
@Override
public void setLookupSQL (final java.lang.String LookupSQL)
{
set_Value (COLUMNNAME_LookupSQL, LookupSQL);
}
@Override
public java.lang.String getLookupSQL()
{
return get_ValueAsString(COLUMNNAME_LookupSQL);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_WarningTarget.java | 1 |
请完成以下Java代码 | public void addOnlyInLocatorRepoId(final int locatorId)
{
Check.assumeGreaterThanZero(locatorId, "locatorId");
onlyInLocatorIds.add(locatorId);
}
public void addOnlyInLocatorId(@NonNull final LocatorId locatorId)
{
onlyInLocatorIds.add(locatorId.getRepoId());
}
public void addOnlyInLocatorRepoIds(final Collection<Integer> locatorIds)
{
if (locatorIds != null && !locatorIds.isEmpty())
{
locatorIds.forEach(this::addOnlyInLocatorRepoId);
}
}
public void addOnlyInLocatorIds(final Collection<LocatorId> locatorIds)
{ | if (locatorIds != null && !locatorIds.isEmpty())
{
locatorIds.forEach(this::addOnlyInLocatorId);
}
}
public void setExcludeAfterPickingLocator(final boolean excludeAfterPickingLocator)
{
this.excludeAfterPickingLocator = excludeAfterPickingLocator;
}
public void setIncludeAfterPickingLocator(final boolean includeAfterPickingLocator)
{
this.includeAfterPickingLocator = includeAfterPickingLocator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder_Locator.java | 1 |
请完成以下Java代码 | public long findDeploymentCountByQueryCriteria(DeploymentQueryImpl deploymentQuery) {
return (Long) getDbSqlSession().selectOne("selectDeploymentCountByQueryCriteria", deploymentQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<Deployment> findDeploymentsByQueryCriteria(DeploymentQueryImpl deploymentQuery, Page page) {
final String query = "selectDeploymentsByQueryCriteria";
return getDbSqlSession().selectList(query, deploymentQuery, page);
}
@Override
public List<String> getDeploymentResourceNames(String deploymentId) {
return getDbSqlSession().getSqlSession().selectList("selectResourceNamesByDeploymentId", deploymentId);
}
@Override
@SuppressWarnings("unchecked")
public List<Deployment> findDeploymentsByNativeQuery(
Map<String, Object> parameterMap, | int firstResult,
int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectDeploymentByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectDeploymentCountByNativeQuery", parameterMap);
}
@Override
public Deployment selectLatestDeployment(String deploymentName) {
return (Deployment) getDbSqlSession().selectOne("selectLatestDeployment", deploymentName);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisDeploymentDataManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Map<String, String> getLoginLinks() {
Iterable<ClientRegistration> clientRegistrations = null;
ClientRegistrationRepository clientRegistrationRepository = this.context
.getBean(ClientRegistrationRepository.class);
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
}
if (clientRegistrations == null) {
return Collections.emptyMap();
}
String authorizationRequestBaseUri = DEFAULT_AUTHORIZATION_REQUEST_BASE_URI;
Map<String, String> loginUrlToClientName = new HashMap<>();
clientRegistrations.forEach((registration) -> loginUrlToClientName.put(
authorizationRequestBaseUri + "/" + registration.getRegistrationId(),
registration.getClientName()));
return loginUrlToClientName;
}
}
@Deprecated
static class EntryPointMatcherFactoryBean implements FactoryBean<RequestMatcher> {
private final RequestMatcher entryPointMatcher;
EntryPointMatcherFactoryBean(RequestMatcher loginPageMatcher, RequestMatcher faviconMatcher) {
RequestMatcher defaultEntryPointMatcher = getAuthenticationEntryPointMatcher();
RequestMatcher defaultLoginPageMatcher = new AndRequestMatcher(
new OrRequestMatcher(loginPageMatcher, faviconMatcher), defaultEntryPointMatcher);
RequestMatcher notXRequestedWith = new NegatedRequestMatcher(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
this.entryPointMatcher = new AndRequestMatcher(notXRequestedWith, | new NegatedRequestMatcher(defaultLoginPageMatcher));
}
private RequestMatcher getAuthenticationEntryPointMatcher() {
ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
MediaTypeRequestMatcher mediaMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy,
MediaType.APPLICATION_XHTML_XML, new MediaType("image", "*"), MediaType.TEXT_HTML,
MediaType.TEXT_PLAIN);
mediaMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));
RequestMatcher notXRequestedWith = new NegatedRequestMatcher(
new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"));
return new AndRequestMatcher(Arrays.asList(notXRequestedWith, mediaMatcher));
}
@Override
public RequestMatcher getObject() {
return this.entryPointMatcher;
}
@Override
public Class<?> getObjectType() {
return RequestMatcher.class;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2LoginBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public static Session getSessionWithInterceptor(Interceptor interceptor) throws IOException {
return getSessionFactory().withOptions()
.interceptor(interceptor)
.openSession();
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.interceptors");
metadataSources.addAnnotatedClass(User.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder();
}
private static ServiceRegistry configureServiceRegistry() throws IOException { | Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate-interceptors.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\HibernateUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void validateCreate(TenantId tenantId, OtaPackage otaPackage) {
DefaultTenantProfileConfiguration profileConfiguration =
(DefaultTenantProfileConfiguration) tenantProfileCache.get(tenantId).getProfileData().getConfiguration();
long maxOtaPackagesInBytes = profileConfiguration.getMaxOtaPackagesInBytes();
validateMaxSumDataSizePerTenant(tenantId, otaPackageDao, maxOtaPackagesInBytes, otaPackage.getDataSize(), OTA_PACKAGE);
}
@Override
protected void validateDataImpl(TenantId tenantId, OtaPackage otaPackage) {
validateImpl(otaPackage);
if (!otaPackage.hasUrl()) {
if (StringUtils.isEmpty(otaPackage.getFileName())) {
throw new DataValidationException("OtaPackage file name should be specified!");
}
if (StringUtils.isEmpty(otaPackage.getContentType())) {
throw new DataValidationException("OtaPackage content type should be specified!");
}
if (otaPackage.getChecksumAlgorithm() == null) {
throw new DataValidationException("OtaPackage checksum algorithm should be specified!");
}
if (StringUtils.isEmpty(otaPackage.getChecksum())) {
throw new DataValidationException("OtaPackage checksum should be specified!");
}
String currentChecksum;
currentChecksum = otaPackageService.generateChecksum(otaPackage.getChecksumAlgorithm(), otaPackage.getData());
if (!currentChecksum.equals(otaPackage.getChecksum())) {
throw new DataValidationException("Wrong otaPackage file!");
}
} else {
if (otaPackage.getData() != null) {
throw new DataValidationException("File can't be saved if URL present!");
}
}
}
@Override | protected OtaPackage validateUpdate(TenantId tenantId, OtaPackage otaPackage) {
OtaPackage otaPackageOld = otaPackageDao.findById(tenantId, otaPackage.getUuidId());
validateUpdate(otaPackage, otaPackageOld);
if (otaPackageOld.getData() != null && !otaPackageOld.getData().equals(otaPackage.getData())) {
throw new DataValidationException("Updating otaPackage data is prohibited!");
}
if (otaPackageOld.getData() == null && otaPackage.getData() != null) {
DefaultTenantProfileConfiguration profileConfiguration =
(DefaultTenantProfileConfiguration) tenantProfileCache.get(tenantId).getProfileData().getConfiguration();
long maxOtaPackagesInBytes = profileConfiguration.getMaxOtaPackagesInBytes();
validateMaxSumDataSizePerTenant(tenantId, otaPackageDao, maxOtaPackagesInBytes, otaPackage.getDataSize(), OTA_PACKAGE);
}
return otaPackageOld;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\OtaPackageDataValidator.java | 2 |
请完成以下Java代码 | public MenuNode build()
{
return new MenuNode(this);
}
public Builder setAD_Menu_ID(final int adMenuId)
{
this.adMenuId = adMenuId;
return this;
}
public Builder setAD_Menu_ID_None()
{
// NOTE: don't set it to ZERO because ZERO is usually root node's ID.
this.adMenuId = -100;
return this;
}
private int getAD_Menu_ID()
{
Check.assumeNotNull(adMenuId, "adMenuId shall be set");
return adMenuId;
}
private String getId()
{
final int adMenuId = getAD_Menu_ID();
if (type == MenuNodeType.NewRecord)
{
return adMenuId + "-new";
}
else
{
return String.valueOf(adMenuId);
}
}
public Builder setCaption(final String caption)
{
this.caption = caption;
return this;
}
public Builder setCaptionBreadcrumb(final String captionBreadcrumb)
{
this.captionBreadcrumb = captionBreadcrumb;
return this;
}
public Builder setType(final MenuNodeType type, @Nullable final DocumentId elementId)
{
this.type = type;
this.elementId = elementId; | return this;
}
public Builder setTypeNewRecord(@NonNull final AdWindowId adWindowId)
{
return setType(MenuNodeType.NewRecord, DocumentId.of(adWindowId));
}
public void setTypeGroup()
{
setType(MenuNodeType.Group, null);
}
public void addChildToFirstsList(@NonNull final MenuNode child)
{
childrenFirst.add(child);
}
public void addChild(@NonNull final MenuNode child)
{
childrenRest.add(child);
}
public Builder setMainTableName(final String mainTableName)
{
this.mainTableName = mainTableName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuNode.java | 1 |
请完成以下Java代码 | public class JsonCsvConverter {
public static void JsonToCsv(File jsonFile, File csvFile) throws IOException {
JsonNode jsonTree = new ObjectMapper().readTree(jsonFile);
Builder csvSchemaBuilder = CsvSchema.builder();
JsonNode firstObject = jsonTree.elements().next();
firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
CsvSchema csvSchema = csvSchemaBuilder
.build()
.withHeader();
CsvMapper csvMapper = new CsvMapper();
csvMapper.writerFor(JsonNode.class)
.with(csvSchema)
.writeValue(csvFile, jsonTree);
}
public static void csvToJson(File csvFile, File jsonFile) throws IOException {
CsvSchema orderLineSchema = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<OrderLine> orderLines = csvMapper.readerFor(OrderLine.class)
.with(orderLineSchema)
.readValues(csvFile); | new ObjectMapper()
.configure(SerializationFeature.INDENT_OUTPUT, true)
.writeValue(jsonFile, orderLines.readAll());
}
public static void JsonToFormattedCsv(File jsonFile, File csvFile) throws IOException {
CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper
.schemaFor(OrderLineForCsv.class)
.withHeader();
csvMapper.addMixIn(OrderLine.class, OrderLineForCsv.class);
OrderLine[] orderLines = new ObjectMapper()
.readValue(jsonFile, OrderLine[].class);
csvMapper.writerFor(OrderLine[].class)
.with(csvSchema)
.writeValue(csvFile, orderLines);
}
} | repos\tutorials-master\jackson-modules\jackson-conversions-2\src\main\java\com\baeldung\jackson\csv\JsonCsvConverter.java | 1 |
请完成以下Java代码 | public T execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("taskId is null");
}
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
TaskEntity task = cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("Cannot find task with id " + taskId, Task.class);
}
if (task.isSuspended()) {
throw new FlowableException(getSuspendedTaskExceptionPrefix() + " a suspended " + task);
} | return execute(commandContext, task);
}
/**
* Subclasses must implement in this method their normal command logic. The provided task is ensured to be active.
*/
protected abstract T execute(CommandContext commandContext, TaskEntity task);
/**
* Subclasses can override this method to provide a customized exception message that will be thrown when the task is suspended.
*/
protected String getSuspendedTaskExceptionPrefix() {
return "Cannot execute operation for";
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\NeedsActiveTaskCmd.java | 1 |
请完成以下Java代码 | public String toAdd() {
return "user/userAdd";
}
@RequestMapping("/add")
public String add(@Valid UserParam userParam,BindingResult result, ModelMap model) {
String errorMsg="";
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
}
model.addAttribute("errorMsg",errorMsg);
return "user/userAdd";
}
User u= userRepository.findByUserName(userParam.getUserName());
if(u!=null){
model.addAttribute("errorMsg","用户已存在!");
return "user/userAdd";
}
User user=new User();
BeanUtils.copyProperties(userParam,user);
user.setRegTime(new Date());
userRepository.save(user);
return "redirect:/list";
}
@RequestMapping("/toEdit")
public String toEdit(Model model,Long id) {
User user=userRepository.findById(id);
model.addAttribute("user", user);
return "user/userEdit";
}
@RequestMapping("/edit")
public String edit(@Valid UserParam userParam, BindingResult result,ModelMap model) {
String errorMsg=""; | if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
}
model.addAttribute("errorMsg",errorMsg);
model.addAttribute("user", userParam);
return "user/userEdit";
}
User user=new User();
BeanUtils.copyProperties(userParam,user);
user.setRegTime(new Date());
userRepository.save(user);
return "redirect:/list";
}
@RequestMapping("/delete")
public String delete(Long id) {
userRepository.delete(id);
return "redirect:/list";
}
} | repos\spring-boot-leaning-master\1.x\第06课:Jpa 和 Thymeleaf 实践\spring-boot-jpa-thymeleaf\src\main\java\com\neo\web\UserController.java | 1 |
请完成以下Java代码 | public void printEvenNumber() {
synchronized (this) {
while (currentNumber < N) {
while (currentNumber % 2 == 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + " --> " + currentNumber);
currentNumber++;
notify();
}
}
}
public void printOddNumber() {
synchronized (this) {
while (currentNumber < N) { | while (currentNumber % 2 == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread()
.getName() + " --> " + currentNumber);
currentNumber++;
notify();
}
}
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-basic-2\src\main\java\com\baeldung\concurrent\threads\name\CustomThreadName.java | 1 |
请完成以下Java代码 | public String getInvolvedUser() {
return involvedUser;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public List<EventSubscriptionQueryValue> getEventSubscriptions() {
return eventSubscriptions;
}
public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) {
this.eventSubscriptions = eventSubscriptions;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getExecutionId() {
return executionId;
}
public String getDeploymentId() {
return deploymentId;
} | public List<String> getDeploymentIds() {
return deploymentIds;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isWithJobException() {
return withJobException;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<ProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
/**
* Method needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property.
*/
public String getParentId() {
return null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.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_C_DirectDebit[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Amount.
@param Amount
Amount in a defined currency
*/
public void setAmount (String Amount)
{
throw new IllegalArgumentException ("Amount is virtual column"); }
/** Get Amount.
@return Amount in a defined currency
*/
public String getAmount ()
{
return (String)get_Value(COLUMNNAME_Amount);
}
/** Set Bank statement line.
@param C_BankStatementLine_ID
Line on a statement from this Bank
*/
public void setC_BankStatementLine_ID (int C_BankStatementLine_ID)
{
if (C_BankStatementLine_ID < 1)
set_Value (COLUMNNAME_C_BankStatementLine_ID, null);
else
set_Value (COLUMNNAME_C_BankStatementLine_ID, Integer.valueOf(C_BankStatementLine_ID));
}
/** Get Bank statement line.
@return Line on a statement from this Bank
*/
public int getC_BankStatementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set C_DirectDebit_ID.
@param C_DirectDebit_ID C_DirectDebit_ID */
public void setC_DirectDebit_ID (int C_DirectDebit_ID)
{
if (C_DirectDebit_ID < 1)
throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory.");
set_ValueNoCheck (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID));
}
/** Get C_DirectDebit_ID.
@return C_DirectDebit_ID */
public int getC_DirectDebit_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Dtafile.
@param Dtafile
Copy of the *.dta stored as plain text
*/
public void setDtafile (String Dtafile) | {
set_Value (COLUMNNAME_Dtafile, Dtafile);
}
/** Get Dtafile.
@return Copy of the *.dta stored as plain text
*/
public String getDtafile ()
{
return (String)get_Value(COLUMNNAME_Dtafile);
}
/** Set IsRemittance.
@param IsRemittance IsRemittance */
public void setIsRemittance (boolean IsRemittance)
{
set_Value (COLUMNNAME_IsRemittance, Boolean.valueOf(IsRemittance));
}
/** Get IsRemittance.
@return IsRemittance */
public boolean isRemittance ()
{
Object oo = get_Value(COLUMNNAME_IsRemittance);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebit.java | 1 |
请完成以下Java代码 | public void clear() {
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return null;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Set<String> keySet() {
return null;
}
@Override
public Object put(String key, Object value) {
return null;
} | @Override
public void putAll(Map<? extends String, ? extends Object> m) {
}
@Override
public Object remove(Object key) {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Collection<Object> values() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EventRegistryEngineConfigurator extends AbstractEngineConfigurator<EventRegistryEngine> {
protected EventRegistryEngineConfiguration eventEngineConfiguration;
@Override
public int getPriority() {
return EngineConfigurationConstants.PRIORITY_ENGINE_EVENT_REGISTRY;
}
@Override
protected List<EngineDeployer> getCustomDeployers() {
List<EngineDeployer> deployers = new ArrayList<>();
deployers.add(new EventDeployer());
return deployers;
}
@Override
protected String getMybatisCfgPath() {
return EventRegistryEngineConfiguration.DEFAULT_MYBATIS_MAPPING_FILE;
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
if (eventEngineConfiguration == null) {
eventEngineConfiguration = new StandaloneEventRegistryEngineConfiguration();
}
initialiseEventRegistryEngineConfiguration(eventEngineConfiguration);
initialiseCommonProperties(engineConfiguration, eventEngineConfiguration);
initEngine();
initServiceConfigurations(engineConfiguration, eventEngineConfiguration);
}
protected void initialiseEventRegistryEngineConfiguration(EventRegistryEngineConfiguration eventRegistryEngineConfiguration) {
// meant to be overridden
}
@Override
protected List<Class<? extends Entity>> getEntityInsertionOrder() {
return EntityDependencyOrder.INSERT_ORDER;
}
@Override
protected List<Class<? extends Entity>> getEntityDeletionOrder() {
return EntityDependencyOrder.DELETE_ORDER;
}
@Override
protected EventRegistryEngine buildEngine() {
if (eventEngineConfiguration == null) {
throw new FlowableException("EventRegistryEngineConfiguration is required"); | }
return eventEngineConfiguration.buildEventRegistryEngine();
}
public EventRegistryEngineConfiguration getEventEngineConfiguration() {
return eventEngineConfiguration;
}
public EventRegistryEngineConfigurator setEventEngineConfiguration(EventRegistryEngineConfiguration eventEngineConfiguration) {
this.eventEngineConfiguration = eventEngineConfiguration;
return this;
}
public EventRegistryEngine getEventRegistryEngine() {
return buildEngine;
}
public void setEventRegistryEngine(EventRegistryEngine eventRegistryEngine) {
this.buildEngine = eventRegistryEngine;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-configurator\src\main\java\org\flowable\eventregistry\impl\configurator\EventRegistryEngineConfigurator.java | 2 |
请完成以下Java代码 | public WebuiLetter getLetter(final String letterId)
{
return getLetterEntry(letterId).getLetter();
}
public WebuiLetterChangeResult changeLetter(final String letterId, @NonNull final UnaryOperator<WebuiLetter> letterModifier)
{
return getLetterEntry(letterId).compute(letterModifier);
}
public void removeLetterById(final String letterId)
{
lettersById.invalidate(letterId);
}
public void createC_Letter(@NonNull final WebuiLetter letter)
{
final I_C_Letter persistentLetter = InterfaceWrapperHelper.newInstance(I_C_Letter.class);
persistentLetter.setLetterSubject(letter.getSubject());
persistentLetter.setLetterBody(Strings.nullToEmpty(letter.getContent()));
persistentLetter.setLetterBodyParsed(letter.getContent());
persistentLetter.setAD_BoilerPlate_ID(letter.getTextTemplateId());
persistentLetter.setC_BPartner_ID(letter.getBpartnerId());
persistentLetter.setC_BPartner_Location_ID(letter.getBpartnerLocationId());
persistentLetter.setC_BP_Contact_ID(letter.getBpartnerContactId());
persistentLetter.setBPartnerAddress(Strings.nullToEmpty(letter.getBpartnerAddress()));
InterfaceWrapperHelper.save(persistentLetter);
}
@ToString
private static final class WebuiLetterEntry
{
private WebuiLetter letter;
public WebuiLetterEntry(@NonNull final WebuiLetter letter)
{
this.letter = letter; | }
public synchronized WebuiLetter getLetter()
{
return letter;
}
public synchronized WebuiLetterChangeResult compute(final UnaryOperator<WebuiLetter> modifier)
{
final WebuiLetter letterOld = letter;
final WebuiLetter letterNew = modifier.apply(letterOld);
if (letterNew == null)
{
throw new NullPointerException("letter");
}
letter = letterNew;
return WebuiLetterChangeResult.builder().letter(letterNew).originalLetter(letterOld).build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\letter\WebuiLetterRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
/**
* 用户认证 Manager
*/
@Autowired
private AuthenticationManager authenticationManager;
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("nainai_zui_shuai"); // JWT 秘钥
return converter;
}
@Bean
public JwtTokenStore jwtTokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.tokenStore(jwtTokenStore())
.accessTokenConverter(jwtAccessTokenConverter());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.checkTokenAccess("isAuthenticated()");
// oauthServer.tokenKeyAccess("isAuthenticated()")
// .checkTokenAccess("isAuthenticated()"); | // oauthServer.tokenKeyAccess("permitAll()")
// .checkTokenAccess("permitAll()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientapp").secret("112233") // Client 账号、密码。
.authorizedGrantTypes("password", "refresh_token") // 密码模式
.scopes("read_userinfo", "read_contacts") // 可授权的 Scope
// .and().withClient() // 可以继续配置新的 Client
;
}
} | repos\SpringBoot-Labs-master\lab-68-spring-security-oauth\lab-68-demo11-authorization-server-by-jwt-store\src\main\java\cn\iocoder\springboot\lab68\authorizationserverdemo\config\OAuth2AuthorizationServerConfig.java | 2 |
请完成以下Java代码 | public String getFoosOrBarsByPath() {
return "Advanced - Get some Foos or Bars";
}
@RequestMapping(value = "*")
@ResponseBody
public String getFallback() {
return "Fallback for GET Requests";
}
@RequestMapping(value = "*", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String allFallback() {
return "Fallback for All Requests";
}
@RequestMapping(value = "/foos/multiple", method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
return "Advanced - PUT and POST within single method";
}
// --- Ambiguous Mapping | @GetMapping(value = "foos/duplicate" )
public ResponseEntity<String> duplicate() {
return new ResponseEntity<>("Duplicate", HttpStatus.OK);
}
// uncomment for exception of type java.lang.IllegalStateException: Ambiguous mapping
// @GetMapping(value = "foos/duplicate" )
// public String duplicateEx() {
// return "Duplicate";
// }
@GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<String> duplicateXml() {
return new ResponseEntity<>("<message>Duplicate</message>", HttpStatus.OK);
}
@GetMapping(value = "foos/duplicate", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> duplicateJson() {
return new ResponseEntity<>("{\"message\":\"Duplicate\"}", HttpStatus.OK);
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\requestmapping\FooMappingExamplesController.java | 1 |
请完成以下Java代码 | public boolean hasJobAcquisitionLockFailureOccurred() {
for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) {
if (acquiredJobs.getNumberOfJobsFailedToLock() > 0) {
return true;
}
}
return false;
}
// getters and setters
public void setAcquisitionTime(long acquisitionTime) {
this.acquisitionTime = acquisitionTime;
}
public long getAcquisitionTime() {
return acquisitionTime;
}
/**
* Jobs that were acquired in the current acquisition cycle.
* @return
*/
public Map<String, AcquiredJobs> getAcquiredJobsByEngine() {
return acquiredJobsByEngine;
}
/**
* Jobs that were rejected from execution in the acquisition cycle
* due to lacking execution resources.
* With an execution thread pool, these jobs could not be submitted due to
* saturation of the underlying job queue.
*/
public Map<String, List<List<String>>> getRejectedJobsByEngine() {
return rejectedJobBatchesByEngine;
} | /**
* Jobs that have been acquired in previous cycles and are supposed to
* be re-submitted for execution
*/
public Map<String, List<List<String>>> getAdditionalJobsByEngine() {
return additionalJobBatchesByEngine;
}
public void setAcquisitionException(Exception e) {
this.acquisitionException = e;
}
public Exception getAcquisitionException() {
return acquisitionException;
}
public void setJobAdded(boolean isJobAdded) {
this.isJobAdded = isJobAdded;
}
public boolean isJobAdded() {
return isJobAdded;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobAcquisitionContext.java | 1 |
请完成以下Java代码 | public Future<String> doTaskOne() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务一完成");
}
@Async
public Future<String> doTaskTwo() throws Exception {
System.out.println("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis(); | System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务二完成");
}
@Async
public Future<String> doTaskThree() throws Exception {
System.out.println("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务三完成");
}
} | repos\SpringBoot-Learning-master\1.x\Chapter4-1-2\src\main\java\com\didispace\async\Task.java | 1 |
请完成以下Java代码 | public Integer getBeginLine() {
return beginLine;
}
public void setBeginLine(Integer beginLine) {
this.beginLine = beginLine;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCurrentPage() {
return currentPage;
} | public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getEndLine() {
return endLine;
}
public void setEndLine(Integer endLine) {
this.endLine = endLine;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
} | repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\param\PageParam.java | 1 |
请完成以下Java代码 | public void collectRowChanged(@NonNull final ViewId viewId, final DocumentId rowId)
{
viewChanges(viewId).addChangedRowId(rowId);
autoflushIfEnabled();
}
public void collectHeaderPropertiesChanged(@NonNull final IView view)
{
viewChanges(view).setHeaderPropertiesChanged();
autoflushIfEnabled();
}
public void collectHeaderPropertiesChanged(@NonNull final ViewId viewId)
{
viewChanges(viewId).setHeaderPropertiesChanged();
autoflushIfEnabled();
}
private void collectFromChanges(@NonNull final ViewChanges changes)
{
viewChanges(changes.getViewId()).collectFrom(changes);
autoflushIfEnabled();
}
@Nullable
private ViewChangesCollector getParentOrNull()
{
final ViewChangesCollector threadLocalCollector = getCurrentOrNull();
if (threadLocalCollector != null && threadLocalCollector != this)
{
return threadLocalCollector;
}
return null;
}
void flush()
{
final ImmutableList<ViewChanges> changesList = getAndClean();
if (changesList.isEmpty())
{
return;
}
//
// Try flushing to parent collector if any
final ViewChangesCollector parentCollector = getParentOrNull();
if (parentCollector != null)
{
logger.trace("Flushing {} to parent collector: {}", this, parentCollector);
changesList.forEach(parentCollector::collectFromChanges);
}
//
// Fallback: flush to websocket
else
{
logger.trace("Flushing {} to websocket", this);
final ImmutableList<JSONViewChanges> jsonChangeEvents = changesList.stream()
.filter(ViewChanges::hasChanges)
.map(JSONViewChanges::of)
.collect(ImmutableList.toImmutableList());
sendToWebsocket(jsonChangeEvents);
}
}
private void autoflushIfEnabled()
{
if (!autoflush)
{
return;
} | flush();
}
private ImmutableList<ViewChanges> getAndClean()
{
if (viewChangesMap.isEmpty())
{
return ImmutableList.of();
}
final ImmutableList<ViewChanges> changesList = ImmutableList.copyOf(viewChangesMap.values());
viewChangesMap.clear();
return changesList;
}
private void sendToWebsocket(@NonNull final List<JSONViewChanges> jsonChangeEvents)
{
if (jsonChangeEvents.isEmpty())
{
return;
}
WebsocketSender websocketSender = _websocketSender;
if (websocketSender == null)
{
websocketSender = this._websocketSender = SpringContextHolder.instance.getBean(WebsocketSender.class);
}
try
{
websocketSender.convertAndSend(jsonChangeEvents);
logger.debug("Sent to websocket: {}", jsonChangeEvents);
}
catch (final Exception ex)
{
logger.warn("Failed sending to websocket {}: {}", jsonChangeEvents, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChangesCollector.java | 1 |
请完成以下Java代码 | public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
public List<DataAssociation> getDataInputAssociations() {
return dataInputAssociations;
}
public void setDataInputAssociations(List<DataAssociation> dataInputAssociations) {
this.dataInputAssociations = dataInputAssociations;
}
public List<DataAssociation> getDataOutputAssociations() {
return dataOutputAssociations;
}
public void setDataOutputAssociations(List<DataAssociation> dataOutputAssociations) {
this.dataOutputAssociations = dataOutputAssociations;
}
public List<MapExceptionEntry> getMapExceptions() {
return mapExceptions;
}
public void setMapExceptions(List<MapExceptionEntry> mapExceptions) {
this.mapExceptions = mapExceptions;
}
public void setValues(Activity otherActivity) {
super.setValues(otherActivity);
setFailedJobRetryTimeCycleValue(otherActivity.getFailedJobRetryTimeCycleValue());
setDefaultFlow(otherActivity.getDefaultFlow());
setForCompensation(otherActivity.isForCompensation());
if (otherActivity.getLoopCharacteristics() != null) {
setLoopCharacteristics(otherActivity.getLoopCharacteristics().clone()); | }
if (otherActivity.getIoSpecification() != null) {
setIoSpecification(otherActivity.getIoSpecification().clone());
}
dataInputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataInputAssociations() != null && !otherActivity.getDataInputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataInputAssociations()) {
dataInputAssociations.add(association.clone());
}
}
dataOutputAssociations = new ArrayList<DataAssociation>();
if (otherActivity.getDataOutputAssociations() != null && !otherActivity.getDataOutputAssociations().isEmpty()) {
for (DataAssociation association : otherActivity.getDataOutputAssociations()) {
dataOutputAssociations.add(association.clone());
}
}
boundaryEvents.clear();
for (BoundaryEvent event : otherActivity.getBoundaryEvents()) {
boundaryEvents.add(event);
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Activity.java | 1 |
请完成以下Java代码 | public void setMaxFacetsToFetch (final int MaxFacetsToFetch)
{
set_Value (COLUMNNAME_MaxFacetsToFetch, MaxFacetsToFetch);
}
@Override
public int getMaxFacetsToFetch()
{
return get_ValueAsInt(COLUMNNAME_MaxFacetsToFetch);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* ObscureType AD_Reference_ID=291
* Reference name: AD_Field ObscureType
*/
public static final int OBSCURETYPE_AD_Reference_ID=291;
/** Obscure Digits but last 4 = 904 */
public static final String OBSCURETYPE_ObscureDigitsButLast4 = "904";
/** Obscure Digits but first/last 4 = 944 */
public static final String OBSCURETYPE_ObscureDigitsButFirstLast4 = "944";
/** Obscure AlphaNumeric but first/last 4 = A44 */
public static final String OBSCURETYPE_ObscureAlphaNumericButFirstLast4 = "A44";
/** Obscure AlphaNumeric but last 4 = A04 */
public static final String OBSCURETYPE_ObscureAlphaNumericButLast4 = "A04";
@Override
public void setObscureType (final @Nullable java.lang.String ObscureType)
{
set_Value (COLUMNNAME_ObscureType, ObscureType);
}
@Override
public java.lang.String getObscureType()
{
return get_ValueAsString(COLUMNNAME_ObscureType);
}
@Override
public void setSelectionColumnSeqNo (final @Nullable BigDecimal SelectionColumnSeqNo)
{
set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo);
}
@Override
public BigDecimal getSelectionColumnSeqNo()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SelectionColumnSeqNo);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNoGrid (final int SeqNoGrid)
{
set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid);
}
@Override
public int getSeqNoGrid()
{
return get_ValueAsInt(COLUMNNAME_SeqNoGrid); | }
@Override
public void setSortNo (final @Nullable BigDecimal SortNo)
{
set_Value (COLUMNNAME_SortNo, SortNo);
}
@Override
public BigDecimal getSortNo()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSpanX (final int SpanX)
{
set_Value (COLUMNNAME_SpanX, SpanX);
}
@Override
public int getSpanX()
{
return get_ValueAsInt(COLUMNNAME_SpanX);
}
@Override
public void setSpanY (final int SpanY)
{
set_Value (COLUMNNAME_SpanY, SpanY);
}
@Override
public int getSpanY()
{
return get_ValueAsInt(COLUMNNAME_SpanY);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java | 1 |
请完成以下Java代码 | public boolean isAuthenticated() {
return authentication != null && authentication != Authentication.ANONYMOUS;
}
public String getApplication() {
return application;
}
////// static helpers //////////////////////////////
public static Authorization granted(Authentication authentication) {
return new Authorization(authentication, true);
}
public static Authorization denied(Authentication authentication) {
return new Authorization(authentication, false);
}
public static Authorization grantedUnlessNull(Authentication authentication) {
return authentication != null ? granted(authentication) : denied(authentication); | }
private static String join(String delimiter, Collection<?> collection) {
StringBuilder builder = new StringBuilder();
for (Object o: collection) {
if (builder.length() > 0) {
builder.append(delimiter);
}
builder.append(o);
}
return builder.toString();
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\Authorization.java | 1 |
请完成以下Java代码 | public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public String getCaseDefinitionName() {
return caseDefinitionName;
}
public void setCaseDefinitionName(String caseDefinitionName) {
this.caseDefinitionName = caseDefinitionName;
}
public int getXmlLineNumber() {
return xmlLineNumber;
}
public void setXmlLineNumber(int xmlLineNumber) {
this.xmlLineNumber = xmlLineNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getDefaultDescription() {
return defaultDescription;
}
public void setDefaultDescription(String defaultDescription) {
this.defaultDescription = defaultDescription;
}
public String getItemId() {
return itemId;
} | public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '").append(validatorSetName).append("' | Problem: '").append(problem).append("'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (caseDefinitionId != null) {
strb.append("caseDefinitionId = ").append(caseDefinitionId);
extraInfoAlreadyPresent = true;
}
if (caseDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("caseDefinitionName = ").append(caseDefinitionName).append(" | ");
extraInfoAlreadyPresent = true;
}
if (itemId != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("id = ").append(itemId).append(" | ");
extraInfoAlreadyPresent = true;
}
if (itemName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("name = ").append(itemName).append(" | ");
extraInfoAlreadyPresent = true;
}
strb.append("]");
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: ").append(xmlLineNumber).append(", column: ").append(xmlColumnNumber).append(")");
}
return strb.toString();
}
} | repos\flowable-engine-main\modules\flowable-case-validation\src\main\java\org\flowable\cmmn\validation\validator\ValidationEntry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getIdPrefix() {
// id prefix is empty because sequence is used instead of id prefix
return "";
}
@Override
public void setLogNumber(long logNumber) {
this.logNumber = logNumber;
}
@Override
public long getLogNumber() {
return logNumber;
}
@Override
public String getType() {
return type;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
} | @Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")";
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java | 2 |
请完成以下Java代码 | public void setVersion()
{
final String versionStr = createVersionWithOptionalSuffix(newVersion, additionalMetaDataSuffix);
logger.info("Setting AD_System.DBVersion to {}", versionStr);
final String updateSql = "UPDATE public.AD_System SET DBVersion='" + versionStr + "'";
try (final Connection connection = db.getConnection();
final Statement stmt = connection.createStatement())
{
stmt.executeUpdate(updateSql);
}
catch (final SQLException e)
{
throw new RuntimeException("Could not set version; updateSql=" + updateSql, e);
}
}
@VisibleForTesting
static String createVersionWithOptionalSuffix(
@NonNull final String versionStr,
final String suffix)
{ | final Version version;
if (suffix == null || "".equals(suffix) || versionStr.endsWith(suffix))
{
// there is no suffix, or the same suffix was already added earlier when a migration was not completed
version = Version.valueOf(versionStr);
}
else
{
final Version tmp = Version.valueOf(versionStr);
version = tmp.setBuildMetadata(tmp.getBuildMetadata() + "x" + suffix);
}
return version.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBVersionSetter.java | 1 |
请完成以下Java代码 | public class UserWithIgnoreType {
public int id;
public Name name;
public UserWithIgnoreType() {
}
public UserWithIgnoreType(final int id, final Name name) {
this.id = id;
this.name = name;
}
@JsonIgnoreType | public static class Name {
public String firstName;
public String lastName;
public Name() {
}
public Name(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
} | repos\tutorials-master\jackson-simple\src\main\java\com\baeldung\jackson\annotation\UserWithIgnoreType.java | 1 |
请完成以下Java代码 | public void setM_CostType(final org.compiere.model.I_M_CostType M_CostType)
{
set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType);
}
@Override
public void setM_CostType_ID (final int M_CostType_ID)
{
if (M_CostType_ID < 1)
set_Value (COLUMNNAME_M_CostType_ID, null);
else
set_Value (COLUMNNAME_M_CostType_ID, M_CostType_ID);
}
@Override
public int getM_CostType_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostType_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 setPeriod_OpenFuture (final int Period_OpenFuture)
{
set_Value (COLUMNNAME_Period_OpenFuture, Period_OpenFuture);
}
@Override
public int getPeriod_OpenFuture()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenFuture);
}
@Override
public void setPeriod_OpenHistory (final int Period_OpenHistory)
{
set_Value (COLUMNNAME_Period_OpenHistory, Period_OpenHistory);
}
@Override
public int getPeriod_OpenHistory()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenHistory);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
} | @Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
/**
* TaxCorrectionType AD_Reference_ID=392
* Reference name: C_AcctSchema TaxCorrectionType
*/
public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392;
/** None = N */
public static final String TAXCORRECTIONTYPE_None = "N";
/** Write_OffOnly = W */
public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */
public static final String TAXCORRECTIONTYPE_DiscountOnly = "D";
/** Write_OffAndDiscount = B */
public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B";
@Override
public void setTaxCorrectionType (final java.lang.String TaxCorrectionType)
{
set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType);
}
@Override
public java.lang.String getTaxCorrectionType()
{
return get_ValueAsString(COLUMNNAME_TaxCorrectionType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java | 1 |
请完成以下Java代码 | static String getBaseDirectory (final String... entries)
{
final StringBuilder sb = new StringBuilder (DIR_BASE);
for (final String entry : entries)
{
if (Check.isEmpty(entry, true))
{
continue;
}
if (sb.length() > 0 && !entry.startsWith("/"))
{
sb.append("/");
}
sb.append(entry);
}
return sb.toString();
} // getBaseDirectory
/**
* Get Logo Path. | *
* @param width optional image width
* @return url to logo
*/
public static String getLogoURL(final int width)
{
String logoURL = getBaseDirectory(DIR_IMAGE, LOGO);
return logoURL + "?" + IMAGE_PARAM_Width + "=" + width;
} // getLogoPath
/**
* Get Stylesheet Path.
* <p>
* /adempiere/standard.css
* @return url of Stylesheet
*/
public static String getStylesheetURL()
{
return getBaseDirectory(STYLE_STD);
} // getStylesheetURL
} // WEnv | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebEnv.java | 1 |
请完成以下Java代码 | public Builder putProperty(final String name, final boolean value)
{
properties.put(name, value);
return this;
}
public Builder putPropertyIfTrue(final String name, final boolean value)
{
if (value)
{
properties.put(name, value);
}
return this;
}
public Builder putProperty(final String name, final String value)
{
properties.put(name, value);
return this;
}
public Builder putProperty(final String name, final Date value)
{
properties.put(name, value);
return this;
}
public Builder putProperty(final String name, final BigDecimal value)
{
properties.put(name, value);
return this;
}
public Builder putProperty(final String name, final ITableRecordReference value)
{
properties.put(name, value);
return this;
}
public Builder putProperty(final String name, final List<?> value)
{
properties.put(name, value);
return this;
}
/**
* @see #putProperty(String, ITableRecordReference)
* @see Event#PROPERTY_Record
*/
public Builder setRecord(final ITableRecordReference record)
{
putProperty(Event.PROPERTY_Record, record);
return this;
}
public Builder putPropertyFromObject(final String name, @Nullable final Object value)
{
if (value == null)
{
properties.remove(name);
return this;
}
else if (value instanceof Integer)
{
return putProperty(name, value);
}
else if (value instanceof Long)
{
return putProperty(name, value);
}
else if (value instanceof Double)
{
final double doubleValue = (Double)value;
final int intValue = (int)doubleValue;
if (doubleValue == intValue)
{
return putProperty(name, intValue);
}
else
{
return putProperty(name, BigDecimal.valueOf(doubleValue));
}
}
else if (value instanceof String)
{
return putProperty(name, (String)value);
}
else if (value instanceof Date)
{
return putProperty(name, (Date)value);
}
else if (value instanceof Boolean) | {
return putProperty(name, value);
}
else if (value instanceof ITableRecordReference)
{
return putProperty(name, (ITableRecordReference)value);
}
else if (value instanceof BigDecimal)
{
return putProperty(name, (BigDecimal)value);
}
else if (value instanceof List)
{
return putProperty(name, (List<?>)value);
}
else
{
throw new AdempiereException("Unknown value type " + name + " = " + value + " (type " + value.getClass() + ")");
}
}
public Builder setSuggestedWindowId(final int suggestedWindowId)
{
putProperty(PROPERTY_SuggestedWindowId, suggestedWindowId);
return this;
}
public Builder wasLogged()
{
this.loggingStatus = LoggingStatus.WAS_LOGGED;
return this;
}
public Builder shallBeLogged()
{
this.loggingStatus = LoggingStatus.SHALL_BE_LOGGED;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\Event.java | 1 |
请完成以下Java代码 | private static AdUISectionId extractUISectionId(final I_AD_UI_Section from) {return AdUISectionId.ofRepoId(from.getAD_UI_Section_ID());}
private ImmutableSet<AdUIColumnId> extractUIColumnIds(final Collection<I_AD_UI_Column> uiColumns)
{
return uiColumns.stream().map(DAOWindowUIElementsProvider::extractUIColumnId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIColumnId extractUIColumnId(final I_AD_UI_Column from) {return AdUIColumnId.ofRepoId(from.getAD_UI_Column_ID());}
private static AdUISectionId extractUISectionId(final I_AD_UI_Column from) {return AdUISectionId.ofRepoId(from.getAD_UI_Section_ID());}
private static AdUIColumnId extractUIColumnId(final I_AD_UI_ElementGroup from) {return AdUIColumnId.ofRepoId(from.getAD_UI_Column_ID());}
private ImmutableSet<AdUIElementGroupId> extractUIElementGroupIds(final Collection<I_AD_UI_ElementGroup> froms)
{
return froms.stream().map(DAOWindowUIElementsProvider::extractUIElementGroupId).distinct().collect(ImmutableSet.toImmutableSet()); | }
private static AdUIElementGroupId extractUIElementGroupId(final I_AD_UI_ElementGroup from) {return AdUIElementGroupId.ofRepoId(from.getAD_UI_ElementGroup_ID());}
private static AdUIElementGroupId extractUIElementGroupId(final I_AD_UI_Element from) {return AdUIElementGroupId.ofRepoId(from.getAD_UI_ElementGroup_ID());}
private static AdTabId extractTabId(final I_AD_UI_Element from) {return AdTabId.ofRepoId(from.getAD_Tab_ID());}
private ImmutableSet<AdUIElementId> extractUIElementIds(final Collection<I_AD_UI_Element> froms)
{
return froms.stream().map(DAOWindowUIElementsProvider::extractUIElementId).distinct().collect(ImmutableSet.toImmutableSet());
}
private static AdUIElementId extractUIElementId(final I_AD_UI_Element from) {return AdUIElementId.ofRepoId(from.getAD_UI_Element_ID());}
private static AdUIElementId extractUIElementId(final I_AD_UI_ElementField from) {return AdUIElementId.ofRepoId(from.getAD_UI_Element_ID());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\DAOWindowUIElementsProvider.java | 1 |
请完成以下Java代码 | public void setSortBy(String sortBy) {
if (!isValidSortByValue(sortBy)) {
throw new InvalidRequestException(Status.BAD_REQUEST, "sortBy parameter has invalid value: " + sortBy);
}
this.sortBy = sortBy;
}
@CamundaQueryParam("sortOrder")
public void setSortOrder(String sortOrder) {
if (!VALID_SORT_ORDER_VALUES.contains(sortOrder)) {
throw new InvalidRequestException(Status.BAD_REQUEST, "sortOrder parameter has invalid value: " + sortOrder);
}
this.sortOrder = sortOrder;
}
public void setSorting(List<SortingDto> sorting) {
this.sortings = sorting;
}
public List<SortingDto> getSorting() {
return sortings;
}
protected abstract boolean isValidSortByValue(String value);
protected boolean sortOptionsValid() {
return (sortBy != null && sortOrder != null) || (sortBy == null && sortOrder == null);
}
public T toQuery(ProcessEngine engine) {
T query = createNewQuery(engine);
applyFilters(query);
if (!sortOptionsValid()) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Only a single sorting parameter specified. sortBy and sortOrder required");
}
applySortingOptions(query, engine);
return query;
}
protected abstract T createNewQuery(ProcessEngine engine);
protected abstract void applyFilters(T query);
protected void applySortingOptions(T query, ProcessEngine engine) {
if (sortBy != null) {
applySortBy(query, sortBy, null, engine);
}
if (sortOrder != null) {
applySortOrder(query, sortOrder);
}
if (sortings != null) {
for (SortingDto sorting : sortings) {
String sortingOrder = sorting.getSortOrder();
String sortingBy = sorting.getSortBy(); | if (sortingBy != null) {
applySortBy(query, sortingBy, sorting.getParameters(), engine);
}
if (sortingOrder != null) {
applySortOrder(query, sortingOrder);
}
}
}
}
protected abstract void applySortBy(T query, String sortBy, Map<String, Object> parameters, ProcessEngine engine);
protected void applySortOrder(T query, String sortOrder) {
if (sortOrder != null) {
if (sortOrder.equals(SORT_ORDER_ASC_VALUE)) {
query.asc();
} else if (sortOrder.equals(SORT_ORDER_DESC_VALUE)) {
query.desc();
}
}
}
public static String sortOrderValueForDirection(Direction direction) {
if (Direction.ASCENDING.equals(direction)) {
return SORT_ORDER_ASC_VALUE;
}
else if (Direction.DESCENDING.equals(direction)) {
return SORT_ORDER_DESC_VALUE;
}
else {
throw new RestException("Unknown query sorting direction " + direction);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AbstractQueryDto.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Column getSource_Column()
{
return get_ValueAsPO(COLUMNNAME_Source_Column_ID, org.compiere.model.I_AD_Column.class);
}
@Override
public void setSource_Column(org.compiere.model.I_AD_Column Source_Column)
{
set_ValueFromPO(COLUMNNAME_Source_Column_ID, org.compiere.model.I_AD_Column.class, Source_Column);
}
/** Set Source Column.
@param Source_Column_ID Source Column */
@Override
public void setSource_Column_ID (int Source_Column_ID)
{
if (Source_Column_ID < 1)
set_Value (COLUMNNAME_Source_Column_ID, null);
else
set_Value (COLUMNNAME_Source_Column_ID, Integer.valueOf(Source_Column_ID));
}
/** Get Source Column.
@return Source Column */
@Override
public int getSource_Column_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Source_Column_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Source Table.
@param Source_Table_ID Source Table */
@Override
public void setSource_Table_ID (int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null);
else
set_Value (COLUMNNAME_Source_Table_ID, Integer.valueOf(Source_Table_ID));
}
/** Get Source Table.
@return Source Table */
@Override
public int getSource_Table_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_Source_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SQL to get Target Record IDs by Source Record IDs.
@param SQL_GetTargetRecordIdBySourceRecordId SQL to get Target Record IDs by Source Record IDs */
@Override
public void setSQL_GetTargetRecordIdBySourceRecordId (java.lang.String SQL_GetTargetRecordIdBySourceRecordId)
{
set_Value (COLUMNNAME_SQL_GetTargetRecordIdBySourceRecordId, SQL_GetTargetRecordIdBySourceRecordId);
}
/** Get SQL to get Target Record IDs by Source Record IDs.
@return SQL to get Target Record IDs by Source Record IDs */
@Override
public java.lang.String getSQL_GetTargetRecordIdBySourceRecordId ()
{
return (java.lang.String)get_Value(COLUMNNAME_SQL_GetTargetRecordIdBySourceRecordId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SQLColumn_SourceTableColumn.java | 1 |
请完成以下Java代码 | static Builder<?> builder(RestClient client) {
return builder(client.mutate());
}
/**
* Variant of {@link #builder()} with a pre-configured {@code RestClient}
* to mutate and customize further through the returned builder.
* @param builder the {@code RestClient} builder to use for HTTP requests
*/
static Builder<?> builder(RestClient.Builder builder) {
return new DefaultSyncHttpGraphQlClientBuilder(builder);
}
/**
* Builder for the GraphQL over HTTP client with a blocking execution chain.
* @param <B> the type of builder
*/
interface Builder<B extends Builder<B>> extends GraphQlClient.SyncBuilder<B> {
/**
* Set the GraphQL endpoint URL as a String.
* @param url the url to send HTTP requests to
*/
B url(String url);
/**
* Set the GraphQL endpoint URL.
* @param url the url to send HTTP requests to
*/
B url(URI url);
/**
* Add the given header to HTTP requests.
* @param name the header name
* @param values the header values
*/
B header(String name, String... values);
/**
* Variant of {@link #header(String, String...)} that provides access
* to the underlying headers to inspect or modify directly.
* @param headersConsumer a function that consumes the {@code HttpHeaders}
*/ | B headers(Consumer<HttpHeaders> headersConsumer);
/**
* Configure message converters for JSON for use in the
* {@link org.springframework.graphql.GraphQlResponse} to convert response
* data to higher level objects.
* @param configurer the configurer to apply
* @return this builder
* @deprecated since 2.0 in favor of {@link #configureMessageConverters(Consumer)}.
*/
@Deprecated(since = "2.0.0", forRemoval = true)
B messageConverters(Consumer<List<HttpMessageConverter<?>>> configurer);
/**
* Configure message converters for JSON for use in the
* {@link org.springframework.graphql.GraphQlResponse} to convert response
* data to higher level objects.
* @param configurer the configurer to apply
* @return this builder
*/
B configureMessageConverters(Consumer<HttpMessageConverters.ClientBuilder> configurer);
/**
* Customize the underlying {@code RestClient}.
* <p>Note that some properties of {@code RestClient.Builder} like the base URL,
* headers, and message converters can be customized through this builder.
* @param builderConsumer a consumer that customizes the {@code RestClient}.
* @see #url(String)
* @see #header(String, String...)
* @see #configureMessageConverters(Consumer)
*/
B restClient(Consumer<RestClient.Builder> builderConsumer);
/**
* Build the {@code HttpSyncGraphQlClient} instance.
*/
@Override
HttpSyncGraphQlClient build();
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\HttpSyncGraphQlClient.java | 1 |
请完成以下Java代码 | private IWeightable getWeightableIfApplies(final IHUContext huContext, final I_M_HU_Trx_Line trxLine)
{
//
// If there is no VHU involved on this transaction, then it does not apply
final I_M_HU_Item vhuItem = trxLine.getVHU_Item();
if (vhuItem == null || vhuItem.getM_HU_Item_ID() <= 0)
{
return null;
}
//
// Make sure we are NOT transfering between HUs.
// In that case we relly on de.metas.handlingunits.attribute.strategy.impl.RedistributeQtyHUAttributeTransferStrategy.
// Also we assume the weight attributes have UseInASI=false
final I_M_HU_Trx_Line trxLineCounterpart = Services.get(IHUTrxDAO.class).retrieveCounterpartTrxLine(trxLine);
if (trxLineCounterpart.getVHU_Item_ID() > 0)
{
return null; | }
//
// Get the IWeightable from VHU
final I_M_HU vhu = vhuItem.getM_HU();
final IAttributeStorage attributeStoarge = huContext.getHUAttributeStorageFactory().getAttributeStorage(vhu);
final IWeightable weightable = Weightables.wrap(attributeStoarge);
//
// If there is no WeightNet attribute, there is no point to update it
if (!weightable.hasWeightNet())
{
return null;
}
return weightable;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightGenerateHUTrxListener.java | 1 |
请完成以下Java代码 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String token = resolveToken(httpServletRequest);
// 对于 Token 为空的不需要去查 Redis
if(StrUtil.isNotBlank(token)){
// 获取用户Token的Key
String loginKey = tokenProvider.loginKey(token);
OnlineUserDto onlineUserDto = onlineUserService.getOne(loginKey);
// 判断用户在线信息是否为空
if (onlineUserDto != null) {
// Token 续期判断
tokenProvider.checkRenewal(token);
// 获取认证信息,设置上下文
Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(servletRequest, servletResponse); | }
/**
* 初步检测Token
*
* @param request /
* @return /
*/
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(properties.getHeader());
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
// 去掉令牌前缀
return bearerToken.replace(properties.getTokenStartWith(), "");
} else {
log.debug("非法Token:{}", bearerToken);
}
return null;
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\security\TokenFilter.java | 1 |
请完成以下Java代码 | public boolean isReservedOnlyFor(@Nullable final HUReservationDocRef reservationDocRef)
{
return this.reservationDocRef != null
&& HUReservationDocRef.equals(this.reservationDocRef, reservationDocRef);
}
private void assertSameProductId(final AllocablePackageable allocable)
{
if (!ProductId.equals(productId, allocable.getProductId()))
{
throw new AdempiereException("ProductId not matching")
.appendParametersToMessage()
.setParameter("allocable", allocable)
.setParameter("storage", this);
}
}
private static Quantity computeEffectiveQtyToAllocate(
@NonNull final Quantity requestedQtyToAllocate, | @NonNull final Quantity qtyFreeToAllocate)
{
if (requestedQtyToAllocate.signum() <= 0)
{
return requestedQtyToAllocate.toZero();
}
else if (qtyFreeToAllocate.signum() <= 0)
{
return requestedQtyToAllocate.toZero();
}
else
{
return requestedQtyToAllocate.min(qtyFreeToAllocate);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\allocableHUStorages\VHUAllocableStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EventConsumerImpl implements EventConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(EventConsumerImpl.class);
private final Map<String, TxContext> processing;
@Autowired
public EventConsumerImpl() {
this.processing = new ConcurrentHashMap<>();
}
@KafkaListener(topics = "sync-prod-con-responses")
public void consume(EventWrapper<? extends AsyncEvent> message) throws IOException {
LOGGER.info("#### Consumed message -> {}", message.getType());
if (message.getType().equals(TxMessageAsyncEvent.class)) {
EventWrapper<TxMessageAsyncEvent> wrapper = (EventWrapper<TxMessageAsyncEvent>)message;
TxMessageAsyncEvent txMessageAsyncEvent = wrapper.getEvent();
TxContext txContext = processing.get(txMessageAsyncEvent.getTxId()); | if (txContext != null) {
Float duration = (System.nanoTime() - txContext.getStarted())/1_000_000F;
MessageReply reply = new MessageReply(txMessageAsyncEvent.getId(), txMessageAsyncEvent.getMessage(), duration);
txContext.getCompletableFuture().complete(reply);
}
} else {
LOGGER.error("ERROR: unsupported message type {}", message.getType());
}
}
@Override
public void setTransaction(String txId, CompletableFuture<MessageReply> completableFuture) {
processing.put(txId, new TxContext(System.nanoTime(), completableFuture));
}
} | repos\spring-examples-java-17\spring-kafka\kafka-sync-producer\src\main\java\itx\examples\spring\kafka\service\EventConsumerImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BusinessRuleWarningTarget
{
public static final BusinessRuleWarningTarget ROOT_TARGET_RECORD = _builder().type(BusinessRuleWarningTargetType.ROOT_TARGET_RECORD).build();
@NonNull BusinessRuleWarningTargetType type;
@Nullable SqlLookup sqlLookup;
public static BusinessRuleWarningTarget sqlLookup(@NonNull AdTableId adTableId, @NonNull String lookupSQL)
{
return _builder()
.type(BusinessRuleWarningTargetType.SQL_LOOKUP)
.sqlLookup(SqlLookup.builder()
.adTableId(adTableId)
.sql(lookupSQL)
.build())
.build();
}
public SqlLookup getSqlLookupNotNull() | {
return Check.assumeNotNull(sqlLookup, "Target {} has sqlLookup set", this);
}
//
//
//
@Value
@Builder
public static class SqlLookup
{
@NonNull AdTableId adTableId;
@NonNull String sql;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\model\BusinessRuleWarningTarget.java | 2 |
请完成以下Java代码 | private static void errorIfQueryValueNotNull(
@NonNull final String field,
final Object value,
@NonNull final HUTraceEventQuery query)
{
if (value != null)
{
final String message = StringUtils.formatMessage("The given HUTraceEventQuery already has {}={}", field, value);
throw new AdempiereException(message).setParameter("HUTraceEventQuery", query);
}
}
private static void errorfIfNotEqualsOperator(@NonNull final DocumentFilterParam parameter)
{
if (!Operator.EQUAL.equals(parameter.getOperator()))
{
final String message = StringUtils.formatMessage("The given DocumentFilterParam needs to have an EQUAL operator, but has {}", parameter.getOperator());
throw new AdempiereException(message).setParameter("DocumentFilterParam", parameter);
}
}
private static HuId extractHuId(@NonNull final DocumentFilterParam parameter)
{
return HuId.ofRepoIdOrNull(extractInt(parameter));
}
private static ImmutableSet<HuId> extractHuIds(@NonNull final DocumentFilterParam parameter)
{
final HuId huId = extractHuId(parameter);
return huId != null ? ImmutableSet.of(huId) : ImmutableSet.of();
}
private static int extractInt(@NonNull final DocumentFilterParam parameter)
{
final Object value = Check.assumeNotNull(parameter.getValue(), "Given paramter may not have a null value; parameter={}", parameter);
if (value instanceof LookupValue)
{
final LookupValue lookupValue = (LookupValue)value;
return lookupValue.getIdAsInt();
}
else if (value instanceof Integer)
{
return (Integer)value;
}
else
{
throw new AdempiereException("Unable to extract an integer ID from parameter=" + parameter);
}
} | private static String extractString(@NonNull final DocumentFilterParam parameter)
{
final Object value = Check.assumeNotNull(parameter.getValue(), "Given paramter may not have a null value; parameter={}", parameter);
if (value instanceof LookupValue)
{
final LookupValue lookupValue = (LookupValue)value;
return lookupValue.getIdAsString();
}
else if (value instanceof String)
{
return (String)value;
}
throw Check.fail("Unable to extract a String from parameter={}", parameter);
}
private static Boolean extractBoolean(@NonNull final DocumentFilterParam parameter)
{
final Object value = Check.assumeNotNull(parameter.getValue(), "Given parameter may not have a null value; parameter={}", parameter);
if (value instanceof Boolean)
{
return (Boolean)value;
}
throw Check.fail("Unable to extract a Boolean from parameter={}", parameter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\trace\HuTraceQueryCreator.java | 1 |
请完成以下Java代码 | public void setSMTPHost (final @Nullable java.lang.String SMTPHost)
{
set_Value (COLUMNNAME_SMTPHost, SMTPHost);
}
@Override
public java.lang.String getSMTPHost()
{
return get_ValueAsString(COLUMNNAME_SMTPHost);
}
@Override
public void setSMTPPort (final int SMTPPort)
{
set_Value (COLUMNNAME_SMTPPort, SMTPPort);
}
@Override
public int getSMTPPort()
{
return get_ValueAsInt(COLUMNNAME_SMTPPort);
}
/**
* Type AD_Reference_ID=541904
* Reference name: AD_MailBox_Type
*/
public static final int TYPE_AD_Reference_ID=541904;
/** SMTP = smtp */
public static final String TYPE_SMTP = "smtp";
/** MSGraph = msgraph */
public static final String TYPE_MSGraph = "msgraph";
@Override | public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java | 1 |
请完成以下Java代码 | public class MustacheSection implements Section {
private final MustacheTemplateRenderer templateRenderer;
private final String templateName;
private final Map<String, Object> model;
/**
* Create a new instance.
* @param templateRenderer the {@link MustacheTemplateRenderer template renderer} to
* use
* @param templateName the name of the template
* @param model the initial model
*/
public MustacheSection(MustacheTemplateRenderer templateRenderer, String templateName, Map<String, Object> model) {
this.templateRenderer = templateRenderer;
this.templateName = templateName;
this.model = model;
} | @Override
public void write(PrintWriter writer) {
writer.println(this.templateRenderer.render(this.templateName, resolveModel(this.model)));
}
/**
* Resolve the {@code model} prior to render the section.
* @param model the current model
* @return the model to use to render this section (never null)
*/
protected Map<String, Object> resolveModel(Map<String, Object> model) {
return model;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\text\MustacheSection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Neo4jMappingContext neo4jMappingContext(Neo4jManagedTypes managedTypes, Neo4jConversions neo4jConversions) {
Neo4jMappingContext context = new Neo4jMappingContext(neo4jConversions);
context.setManagedTypes(managedTypes);
return context;
}
@Bean
@ConditionalOnMissingBean
DatabaseSelectionProvider databaseSelectionProvider(DataNeo4jProperties properties) {
String database = properties.getDatabase();
return (database != null) ? DatabaseSelectionProvider.createStaticDatabaseSelectionProvider(database)
: DatabaseSelectionProvider.getDefaultSelectionProvider();
}
@Bean(Neo4jRepositoryConfigurationExtension.DEFAULT_NEO4J_CLIENT_BEAN_NAME)
@ConditionalOnMissingBean
Neo4jClient neo4jClient(Driver driver, DatabaseSelectionProvider databaseNameProvider) {
return Neo4jClient.create(driver, databaseNameProvider); | }
@Bean(Neo4jRepositoryConfigurationExtension.DEFAULT_NEO4J_TEMPLATE_BEAN_NAME)
@ConditionalOnMissingBean(Neo4jOperations.class)
Neo4jTemplate neo4jTemplate(Neo4jClient neo4jClient, Neo4jMappingContext neo4jMappingContext) {
return new Neo4jTemplate(neo4jClient, neo4jMappingContext);
}
@Bean(Neo4jRepositoryConfigurationExtension.DEFAULT_TRANSACTION_MANAGER_BEAN_NAME)
@ConditionalOnMissingBean(TransactionManager.class)
Neo4jTransactionManager transactionManager(Driver driver, DatabaseSelectionProvider databaseNameProvider,
ObjectProvider<TransactionManagerCustomizers> optionalCustomizers) {
Neo4jTransactionManager transactionManager = new Neo4jTransactionManager(driver, databaseNameProvider);
optionalCustomizers.ifAvailable((customizer) -> customizer.customize(transactionManager));
return transactionManager;
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-neo4j\src\main\java\org\springframework\boot\data\neo4j\autoconfigure\DataNeo4jAutoConfiguration.java | 2 |
请完成以下Java代码 | public void close()
{
// Restore previous entry collector
// or clear the current one
if (previousEntryCollector != null)
{
threadLocalCollector.set(previousEntryCollector);
}
else
{
threadLocalCollector.remove();
}
// Avoid throwing exception because EventLogService is not available in unit tests
if (Adempiere.isUnitTestMode()) | {
return;
}
try
{
final EventLogService eventStoreService = SpringContextHolder.instance.getBean(EventLogService.class);
eventStoreService.saveEventLogEntries(eventLogEntries);
}
catch (final Exception ex)
{
logger.warn("Failed saving {}. Ignored", eventLogEntries, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogEntryCollector.java | 1 |
请完成以下Java代码 | public class QuartzSessionValidationJob implements Job {
/**
* Key used to store the session manager in the job data map for this job.
*/
public static final String SESSION_MANAGER_KEY = "sessionManager";
/**--------------------------------------------
| I N S T A N C E V A R I A B L E S |
============================================*/
private static final Logger log = LoggerFactory.getLogger(QuartzSessionValidationJob.class);
/*--------------------------------------------
| C O N S T R U C T O R S |
============================================*/
/*--------------------------------------------
| A C C E S S O R S / M O D I F I E R S |
============================================*/
/*--------------------------------------------
| M E T H O D S |
============================================*/
/**
* Called when the job is executed by quartz. This method delegates to the <tt>validateSessions()</tt> method on the | * associated session manager.
*
* @param context the Quartz job execution context for this execution.
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getMergedJobDataMap();
ValidatingSessionManager sessionManager = (ValidatingSessionManager) jobDataMap.get(SESSION_MANAGER_KEY);
if (log.isDebugEnabled()) {
log.debug("Executing session validation Quartz job...");
}
sessionManager.validateSessions();
if (log.isDebugEnabled()) {
log.debug("Session validation Quartz job complete.");
}
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ext\QuartzSessionValidationJob.java | 1 |
请完成以下Java代码 | private String getExternalId(@NonNull final I_M_ReceiptSchedule receiptSchedule)
{
final ReceiptScheduleId receiptScheduleId = ReceiptScheduleId.ofRepoId(receiptSchedule.getM_ReceiptSchedule_ID());
final ReceiptScheduleExternalInfo externalInfo = externalInfoByReceiptScheduleId.get(receiptScheduleId);
return Optional.ofNullable(externalInfo)
.map(ReceiptScheduleExternalInfo::getExternalId)
.map(StringUtils::trimBlankToNull)
.orElseGet(receiptSchedule::getExternalHeaderId);
}
@Nullable
private String getExternalResourceURL(@NonNull final I_M_ReceiptSchedule receiptSchedule)
{
return StringUtils.trimBlankToNull(receiptSchedule.getExternalResourceURL());
}
private Timestamp getMovementDate(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final Properties context)
{
return movementDateRule.map(new ReceiptMovementDateRule.CaseMapper<Timestamp>()
{
@Override
public Timestamp orderDatePromised() {return getPromisedDate(receiptSchedule, context);}
@Override
public Timestamp externalDateIfAvailable() {return getExternalMovementDate(receiptSchedule, context);}
// Use Login Date as movement date because some roles will rely on the fact that they can override it (08247)
@Override
public Timestamp currentDate() {return Env.getDate(context);}
@Override
public Timestamp fixedDate(@NonNull final Instant fixedDate) {return Timestamp.from(fixedDate);}
});
}
private Timestamp getDateAcct(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final Properties context) | {
return movementDateRule.map(new ReceiptMovementDateRule.CaseMapper<Timestamp>()
{
@Override
public Timestamp orderDatePromised() {return getPromisedDate(receiptSchedule, context);}
@Override
public Timestamp externalDateIfAvailable() {return getExternalDateAcct(receiptSchedule, context);}
// Use Login Date as movement date because some roles will rely on the fact that they can override it (08247)
@Override
public Timestamp currentDate() {return Env.getDate(context);}
@Override
public Timestamp fixedDate(@NonNull final Instant fixedDate) {return Timestamp.from(fixedDate);}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\InOutProducer.java | 1 |
请完成以下Java代码 | public List<HazardSymbol> getByIds(@NonNull final Collection<HazardSymbolId> ids)
{
return getAll().getByIds(ids);
}
private HazardSymbolMap getAll()
{
return cache.getOrLoad(0, this::retrieveAll);
}
private HazardSymbolMap retrieveAll()
{
final ImmutableList<HazardSymbol> list = queryBL.createQueryBuilder(I_M_HazardSymbol.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(HazardSymbolRepository::fromRecord)
.collect(ImmutableList.toImmutableList()); | return new HazardSymbolMap(list);
}
private static HazardSymbol fromRecord(final I_M_HazardSymbol record)
{
final IModelTranslationMap trl = InterfaceWrapperHelper.getModelTranslationMap(record);
return HazardSymbol.builder()
.id(HazardSymbolId.ofRepoId(record.getM_HazardSymbol_ID()))
.value(record.getValue())
.name(trl.getColumnTrl(I_M_HazardSymbol.COLUMNNAME_Name, record.getName()))
.imageId(AdImageId.ofRepoIdOrNull(record.getAD_Image_ID()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\hazard_symbol\HazardSymbolRepository.java | 1 |
请完成以下Java代码 | public static BufferedImage toBufferedImage(final Image image)
{
if (image instanceof BufferedImage)
{
return (BufferedImage)image;
}
// Create a buffered image with transparency
final BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
final Graphics2D bGr = bufferedImage.createGraphics();
bGr.drawImage(image, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bufferedImage;
}
private static byte[] toPngData(final BufferedImage image, final int width)
{
if (image == null)
{
return null;
}
BufferedImage imageScaled;
final int widthOrig = image.getWidth();
final int heightOrig = image.getHeight();
if (width > 0 && widthOrig > 0)
{
final double scale = (double)width / (double)widthOrig;
final int height = (int)(heightOrig * scale);
imageScaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final AffineTransform at = new AffineTransform();
at.scale(scale, scale);
final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
imageScaled = scaleOp.filter(image, imageScaled); | }
else
{
imageScaled = image;
}
final ByteArrayOutputStream pngBuf = new ByteArrayOutputStream();
try
{
ImageIO.write(imageScaled, "png", pngBuf);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
return pngBuf.toByteArray();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ImagesServlet.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String delete(Model model, DwzAjax dwz, @RequestParam("productCode") String productCode) {
rpPayProductService.deletePayProduct(productCode);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 : 查找带回
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/lookupList", method ={RequestMethod.POST, RequestMethod.GET})
public String lookupList(RpPayProduct rpPayProduct, PageParam pageParam, Model model) {
//查询已生效数据
rpPayProduct.setAuditStatus(PublicEnum.YES.name());
PageBean pageBean = rpPayProductService.listPage(pageParam, rpPayProduct);
model.addAttribute("pageBean", pageBean);
model.addAttribute("pageParam", pageParam);
model.addAttribute("rpPayProduct", rpPayProduct);
return "pay/product/lookupList";
} | /**
* 函数功能说明 : 审核
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("pay:product:add")
@RequestMapping(value = "/audit", method ={RequestMethod.POST, RequestMethod.GET})
public String audit(Model model, DwzAjax dwz, @RequestParam("productCode") String productCode
, @RequestParam("auditStatus") String auditStatus) {
rpPayProductService.audit(productCode, auditStatus);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\PayProductController.java | 2 |
请完成以下Java代码 | public static class DetailsBuilder {
private String name;
private String lockOwner;
private int lockTimeInMillis;
private int maxJobsPerAcquisition;
private int waitTimeInMillis;
private Set<String> processEngineNames;
DetailsBuilder() {}
public DetailsBuilder name(String name) {
this.name = name;
return this;
}
public DetailsBuilder lockOwner(String lockOwner) {
this.lockOwner = lockOwner;
return this;
}
public DetailsBuilder lockTimeInMillis(int lockTimeInMillis) {
this.lockTimeInMillis = lockTimeInMillis;
return this;
}
public DetailsBuilder maxJobsPerAcquisition(int maxJobsPerAcquisition) {
this.maxJobsPerAcquisition = maxJobsPerAcquisition;
return this;
}
public DetailsBuilder waitTimeInMillis(int waitTimeInMillis) {
this.waitTimeInMillis = waitTimeInMillis;
return this;
}
public DetailsBuilder processEngineName(String processEngineName) {
if (this.processEngineNames == null) {
this.processEngineNames = new HashSet<String>();
}
this.processEngineNames.add(processEngineName);
return this;
}
public DetailsBuilder processEngineNames(Set<? extends String> processEngineNames) {
if (this.processEngineNames == null) {
this.processEngineNames = new HashSet<String>();
}
this.processEngineNames.addAll(processEngineNames);
return this;
}
public DetailsBuilder clearProcessEngineNames(Set<? extends String> processEngineNames) {
if (this.processEngineNames != null) {
this.processEngineNames.clear();
}
return this;
} | public Details build() {
return new Details(this);
}
}
public String getName() {
return name;
}
public String getLockOwner() {
return lockOwner;
}
public int getLockTimeInMillis() {
return lockTimeInMillis;
}
public int getMaxJobsPerAcquisition() {
return maxJobsPerAcquisition;
}
public int getWaitTimeInMillis() {
return waitTimeInMillis;
}
public Set<String> getProcessEngineNames() {
return processEngineNames;
}
@Override
public String toString() {
return "Details [name=" + name + ", lockOwner=" + lockOwner + ", lockTimeInMillis="
+ lockTimeInMillis + ", maxJobsPerAcquisition=" + maxJobsPerAcquisition
+ ", waitTimeInMillis=" + waitTimeInMillis + ", processEngineNames=" + processEngineNames
+ "]";
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\actuator\JobExecutorHealthIndicator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class SourcePropertyDescriptor extends PropertyDescriptor {
private final PropertyDescriptor delegate;
private final ItemMetadata sourceItemMetadata;
private final ItemHint sourceItemHint;
SourcePropertyDescriptor(PropertyDescriptor delegate, ItemMetadata sourceItemMetadata,
ItemHint sourceItemHint) {
super(delegate.getName(), delegate.getType(), delegate.getDeclaringElement(), delegate.getGetter());
this.delegate = delegate;
this.sourceItemMetadata = sourceItemMetadata;
this.sourceItemHint = sourceItemHint;
}
@Override
protected ItemHint resolveItemHint(String prefix, MetadataGenerationEnvironment environment) {
return (this.sourceItemHint != null) ? this.sourceItemHint.applyPrefix(prefix)
: super.resolveItemHint(prefix, environment);
}
@Override
protected boolean isMarkedAsNested(MetadataGenerationEnvironment environment) {
return this.delegate.isMarkedAsNested(environment);
}
@Override
protected String resolveDescription(MetadataGenerationEnvironment environment) {
String description = this.delegate.resolveDescription(environment);
return (description != null) ? description : this.sourceItemMetadata.getDescription();
}
@Override
protected Object resolveDefaultValue(MetadataGenerationEnvironment environment) { | Object defaultValue = this.delegate.resolveDefaultValue(environment);
return (defaultValue != null) ? defaultValue : this.sourceItemMetadata.getDefaultValue();
}
@Override
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
ItemDeprecation itemDeprecation = this.delegate.resolveItemDeprecation(environment);
return (itemDeprecation != null) ? itemDeprecation : this.sourceItemMetadata.getDeprecation();
}
@Override
boolean isProperty(MetadataGenerationEnvironment environment) {
return this.delegate.isProperty(environment);
}
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ConfigurationPropertiesSourceResolver.java | 2 |
请完成以下Java代码 | public CommonResult missingServletRequestParameterExceptionHandler(HttpServletRequest req, MissingServletRequestParameterException ex) {
logger.debug("[missingServletRequestParameterExceptionHandler]", ex);
// 包装 CommonResult 结果
return CommonResult.error(ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getCode(),
ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getMessage());
}
@ResponseBody
@ExceptionHandler(value = ConstraintViolationException.class)
public CommonResult constraintViolationExceptionHandler(HttpServletRequest req, ConstraintViolationException ex) {
logger.debug("[constraintViolationExceptionHandler]", ex);
// 拼接错误
StringBuilder detailMessage = new StringBuilder();
for (ConstraintViolation<?> constraintViolation : ex.getConstraintViolations()) {
// 使用 ; 分隔多个错误
if (detailMessage.length() > 0) {
detailMessage.append(";");
}
// 拼接内容到其中
detailMessage.append(constraintViolation.getMessage());
}
// 包装 CommonResult 结果
return CommonResult.error(ServiceExceptionEnum.INVALID_REQUEST_PARAM_ERROR.getCode(),
ServiceExceptionEnum.INVALID_REQUEST_PARAM_ERROR.getMessage() + ":" + detailMessage.toString());
}
@ResponseBody
@ExceptionHandler(value = BindException.class)
public CommonResult bindExceptionHandler(HttpServletRequest req, BindException ex) {
logger.debug("[bindExceptionHandler]", ex); | // 拼接错误
StringBuilder detailMessage = new StringBuilder();
for (ObjectError objectError : ex.getAllErrors()) {
// 使用 ; 分隔多个错误
if (detailMessage.length() > 0) {
detailMessage.append(";");
}
// 拼接内容到其中
detailMessage.append(objectError.getDefaultMessage());
}
// 包装 CommonResult 结果
return CommonResult.error(ServiceExceptionEnum.INVALID_REQUEST_PARAM_ERROR.getCode(),
ServiceExceptionEnum.INVALID_REQUEST_PARAM_ERROR.getMessage() + ":" + detailMessage.toString());
}
/**
* 处理其它 Exception 异常
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(HttpServletRequest req, Exception e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 返回 ERROR CommonResult
return CommonResult.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
ServiceExceptionEnum.SYS_ERROR.getMessage());
}
} | repos\SpringBoot-Labs-master\lab-22\lab-22-validation-01\src\main\java\cn\iocoder\springboot\lab22\validation\core\web\GlobalExceptionHandler.java | 1 |
请完成以下Java代码 | public void setC_Print_Job_Instructions_ID (int C_Print_Job_Instructions_ID)
{
if (C_Print_Job_Instructions_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Instructions_ID, Integer.valueOf(C_Print_Job_Instructions_ID));
}
@Override
public int getC_Print_Job_Instructions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Instructions_ID);
}
@Override
public de.metas.printing.model.I_C_Print_Package getC_Print_Package()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class);
}
@Override
public void setC_Print_Package(de.metas.printing.model.I_C_Print_Package C_Print_Package)
{
set_ValueFromPO(COLUMNNAME_C_Print_Package_ID, de.metas.printing.model.I_C_Print_Package.class, C_Print_Package);
}
@Override
public void setC_Print_Package_ID (int C_Print_Package_ID)
{
if (C_Print_Package_ID < 1)
set_Value (COLUMNNAME_C_Print_Package_ID, null);
else
set_Value (COLUMNNAME_C_Print_Package_ID, Integer.valueOf(C_Print_Package_ID));
}
@Override
public int getC_Print_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Package_ID);
}
@Override
public void setM_Warehouse_ID (int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID));
}
@Override
public int getM_Warehouse_ID()
{ | return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@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_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions_v.java | 1 |
请完成以下Java代码 | public class MigrationValidator implements ModelValidator
{
private int adClientId = -1;
@Override
public void initialize(ModelValidationEngine engine, MClient client)
{
if (client != null)
{
adClientId = client.getAD_Client_ID();
}
engine.addModelValidator(new AD_Migration(), client);
engine.addModelValidator(new AD_MigrationStep(), client);
}
@Override
public int getAD_Client_ID()
{
return adClientId;
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{ | return null;
}
@Override
public String modelChange(PO po, int type) throws Exception
{
return null;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\MigrationValidator.java | 1 |
请完成以下Java代码 | public void deleteChildEntity(CommandContext commandContext, DelegatePlanItemInstance delegatePlanItemInstance, boolean cascade) {
if (ReferenceTypes.PLAN_ITEM_CHILD_CASE.equals(delegatePlanItemInstance.getReferenceType())) {
CaseInstanceEntityManager caseInstanceEntityManager = CommandContextUtil.getCaseInstanceEntityManager(commandContext);
CaseInstanceEntity caseInstance = caseInstanceEntityManager.findById(delegatePlanItemInstance.getReferenceId());
if (caseInstance != null && !caseInstance.isDeleted()) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
cmmnEngineConfiguration.getCmmnHistoryManager().recordCaseInstanceEnd(
caseInstance, CaseInstanceState.TERMINATED, cmmnEngineConfiguration.getClock().getCurrentTime());
caseInstanceEntityManager.delete(caseInstance.getId(), cascade, null);
}
} else {
throw new FlowableException("Can only delete a child entity for a plan item with reference type " + ReferenceTypes.PLAN_ITEM_CHILD_CASE + " for " + delegatePlanItemInstance);
}
}
protected void handleOutParameters(CommandContext commandContext, PlanItemInstanceEntity planItemInstance) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
handleOutParameters(planItemInstance, cmmnEngineConfiguration); | }
protected void handleOutParameters(DelegatePlanItemInstance planItemInstance, CmmnEngineConfiguration cmmnEngineConfiguration) {
if (outParameters == null) {
return;
}
CaseInstanceEntityManager caseInstanceEntityManager = cmmnEngineConfiguration.getCaseInstanceEntityManager();
CaseInstanceEntity referenceCase = caseInstanceEntityManager.findById(planItemInstance.getReferenceId());
IOParameterUtil.processOutParameters(outParameters, referenceCase, planItemInstance, cmmnEngineConfiguration.getExpressionManager());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\CaseTaskActivityBehavior.java | 1 |
请完成以下Java代码 | public DocumentLineType1 getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link DocumentLineType1 }
*
*/
public void setTp(DocumentLineType1 value) {
this.tp = value;
}
/**
* Gets the value of the nb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNb() {
return nb;
}
/**
* Sets the value of the nb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNb(String value) {
this.nb = value;
} | /**
* Gets the value of the rltdDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getRltdDt() {
return rltdDt;
}
/**
* Sets the value of the rltdDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setRltdDt(XMLGregorianCalendar value) {
this.rltdDt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\DocumentLineIdentification1.java | 1 |
请完成以下Java代码 | public DomElement createElement(String namespaceUri, String localName) {
synchronized(document) {
XmlQName xmlQName = new XmlQName(this, namespaceUri, localName);
Element element = document.createElementNS(xmlQName.getNamespaceUri(), xmlQName.getPrefixedName());
return new DomElementImpl(element);
}
}
public DomElement getElementById(String id) {
synchronized(document) {
Element element = document.getElementById(id);
if (element != null) {
return new DomElementImpl(element);
}
else {
return null;
}
}
}
public List<DomElement> getElementsByNameNs(String namespaceUri, String localName) {
synchronized(document) {
NodeList elementsByTagNameNS = document.getElementsByTagNameNS(namespaceUri, localName);
return DomUtil.filterNodeListByName(elementsByTagNameNS, namespaceUri, localName);
}
}
public DOMSource getDomSource() {
return new DOMSource(document);
}
public String registerNamespace(String namespaceUri) {
synchronized(document) {
DomElement rootElement = getRootElement();
if (rootElement != null) {
return rootElement.registerNamespace(namespaceUri);
}
else {
throw new ModelException("Unable to define a new namespace without a root document element");
}
}
}
public void registerNamespace(String prefix, String namespaceUri) {
synchronized(document) {
DomElement rootElement = getRootElement();
if (rootElement != null) {
rootElement.registerNamespace(prefix, namespaceUri);
}
else { | throw new ModelException("Unable to define a new namespace without a root document element");
}
}
}
protected String getUnusedGenericNsPrefix() {
synchronized(document) {
Element documentElement = document.getDocumentElement();
if (documentElement == null) {
return GENERIC_NS_PREFIX + "0";
}
else {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (!documentElement.hasAttributeNS(XMLNS_ATTRIBUTE_NS_URI, GENERIC_NS_PREFIX + i)) {
return GENERIC_NS_PREFIX + i;
}
}
throw new ModelException("Unable to find an unused namespace prefix");
}
}
}
public DomDocument clone() {
synchronized(document) {
return new DomDocumentImpl((Document) document.cloneNode(true));
}
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DomDocumentImpl that = (DomDocumentImpl) o;
return document.equals(that.document);
}
public int hashCode() {
return document.hashCode();
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\instance\DomDocumentImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Characteristic {
@Id
private Long id;
private String type;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private Item item;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() { | return type;
}
public void setType(String type) {
this.type = type;
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-2\src\main\java\com\baeldung\entitygraph\model\Characteristic.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BPartnerLocationId getCurrentLocation(final BPartnerLocationId locationId)
{
int currentLocationId = locationId.getRepoId();
int previousLocationId = currentLocationId;
while (currentLocationId > 0)
{
currentLocationId = queryBL.createQueryBuilder(I_C_BPartner_Location.class)
.addEqualsFilter(I_C_BPartner_Location.COLUMNNAME_Previous_ID, currentLocationId)
.create()
.firstIdOnly();
if (currentLocationId > 0)
{
previousLocationId = currentLocationId;
}
}
return BPartnerLocationId.ofRepoId(locationId.getBpartnerId(), previousLocationId);
}
@Override
public List<I_C_BPartner> retrieveVendors(@NonNull final QueryLimit limit)
{
return queryBL.createQueryBuilder(I_C_BPartner.class)
.addInArrayFilter(I_C_BPartner.COLUMNNAME_IsVendor, true)
.addOnlyActiveRecordsFilter()
.orderBy(I_C_BPartner.COLUMNNAME_Name)
.orderBy(I_C_BPartner.COLUMNNAME_C_BPartner_ID)
.setLimit(limit)
.create()
.listImmutable(I_C_BPartner.class);
} | @Override
public Optional<SalesRegionId> getSalesRegionIdByBPLocationId(@NonNull final BPartnerLocationId bpartnerLocationId)
{
final I_C_BPartner_Location bpLocation = getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
return bpLocation != null ? SalesRegionId.optionalOfRepoId(bpLocation.getC_SalesRegion_ID()) : Optional.empty();
}
@Override
@NonNull
public List<String> getOtherLocationNamesOfBPartner(@NonNull final BPartnerId bPartnerId, @Nullable final BPartnerLocationId bPartnerLocationId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_Location.class)
.addEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, bPartnerId)
.addNotEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_Location_ID, bPartnerLocationId)
.create()
.listDistinct(I_C_BPartner_Location.COLUMNNAME_Name, String.class);
}
@Override
public Optional<ShipperId> getShipperIdByBPLocationId(@NonNull final BPartnerLocationId bpartnerLocationId)
{
final I_C_BPartner_Location bpLocation = getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
return bpLocation != null ? ShipperId.optionalOfRepoId(bpLocation.getM_Shipper_ID()) : Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerDAO.java | 2 |
请完成以下Java代码 | public static EngineInfo getCmmnEngineInfo(String cmmnEngineName) {
return cmmnEngineInfosByName.get(cmmnEngineName);
}
public static CmmnEngine getDefaultCmmnEngine() {
return getCmmnEngine(NAME_DEFAULT);
}
/**
* Obtain a cmmn engine by name.
*
* @param cmmnEngineName
* is the name of the cmmn engine or null for the default cmmn engine.
*/
public static CmmnEngine getCmmnEngine(String cmmnEngineName) {
if (!isInitialized()) {
init();
}
return cmmnEngines.get(cmmnEngineName);
}
/**
* retries to initialize a cmmn engine that previously failed.
*/
public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initCmmnEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to cmmn engine to application clients in a managed server environment.
*/
public static Map<String, CmmnEngine> getCmmnEngines() {
return cmmnEngines;
}
/**
* closes all cmmn engines. This method should be called when the server shuts down. | */
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines);
cmmnEngines = new HashMap<>();
for (String cmmnEngineName : engines.keySet()) {
CmmnEngine cmmnEngine = engines.get(cmmnEngineName);
try {
cmmnEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e);
}
}
cmmnEngineInfosByName.clear();
cmmnEngineInfosByResourceUrl.clear();
cmmnEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
CmmnEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java | 1 |
请完成以下Java代码 | public Optional<AuthResolution> getAuthResolution(@NonNull final HttpServletRequest httpRequest)
{
if (matchers.isEmpty())
{
return Optional.empty();
}
final String path = httpRequest.getServletPath();
if (path == null)
{
return Optional.empty();
}
return matchers.stream()
.filter(matcher -> matcher.isMatching(path)) | .map(PathMatcher::getResolution)
.findFirst();
}
@Value
@Builder
private static class PathMatcher
{
@NonNull String containing;
@NonNull AuthResolution resolution;
public boolean isMatching(final String path) {return path.contains(containing);}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenFilterConfiguration.java | 1 |
请完成以下Java代码 | public TbQueueConsumer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsEventsToBackupConsumer() {
throw new UnsupportedOperationException();
}
@Override
public TbQueueConsumer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsStateConsumer() {
throw new UnsupportedOperationException();
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsStateProducer() {
throw new UnsupportedOperationException();
}
@Override
public PartitionedQueueResponseTemplate<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> createEdqsResponseTemplate(TbQueueHandler<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> handler) {
TbQueueProducer<TbProtoQueueMsg<FromEdqsMsg>> responseProducer = new InMemoryTbQueueProducer<>(storage, edqsConfig.getResponsesTopic());
return PartitionedQueueResponseTemplate.<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>>builder()
.key("edqs")
.handler(handler)
.requestsTopic(edqsConfig.getRequestsTopic())
.consumerCreator(tpi -> new InMemoryTbQueueConsumer<>(storage, edqsConfig.getRequestsTopic()))
.responseProducer(responseProducer) | .pollInterval(edqsConfig.getPollInterval())
.requestTimeout(edqsConfig.getMaxRequestTimeout())
.maxPendingRequests(edqsConfig.getMaxPendingRequests())
.consumerExecutor(edqsExecutors.getConsumersExecutor())
.callbackExecutor(edqsExecutors.getRequestExecutor())
.consumerTaskExecutor(edqsExecutors.getConsumerTaskExecutor())
.stats(statsFactory.createMessagesStats(StatsType.EDQS.getName()))
.build();
}
@Override
public TbQueueAdmin getEdqsQueueAdmin() {
return queueAdmin;
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\edqs\InMemoryEdqsQueueFactory.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.