instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public DownlinkMsg convertEdgeEventToDownlink(EdgeEvent edgeEvent, EdgeVersion edgeVersion) {
UpdateMsgType msgType = getUpdateMsgType(edgeEvent.getAction());
switch (edgeEvent.getAction()) {
case ADDED_COMMENT:
case UPDATED_COMMENT:
case DELETED_COMMENT:
AlarmComment alarmComment = JacksonUtil.convertValue(edgeEvent.getBody(), AlarmComment.class);
if (alarmComment != null) {
return DownlinkMsg.newBuilder()
.setDownlinkMsgId(EdgeUtils.nextPositiveInt())
.addAlarmCommentUpdateMsg(EdgeMsgConstructorUtils.constructAlarmCommentUpdatedMsg(msgType, alarmComment))
.build();
}
default:
return null;
}
}
@Override
public ListenableFuture<Void> processEntityNotification(TenantId tenantId, TransportProtos.EdgeNotificationMsgProto edgeNotificationMsg) {
EdgeEventActionType actionType = EdgeEventActionType.valueOf(edgeNotificationMsg.getAction());
AlarmId alarmId = new AlarmId(new UUID(edgeNotificationMsg.getEntityIdMSB(), edgeNotificationMsg.getEntityIdLSB())); | EdgeId originatorEdgeId = safeGetEdgeId(edgeNotificationMsg.getOriginatorEdgeIdMSB(), edgeNotificationMsg.getOriginatorEdgeIdLSB());
AlarmComment alarmComment = JacksonUtil.fromString(edgeNotificationMsg.getBody(), AlarmComment.class);
if (alarmComment == null) {
return Futures.immediateFuture(null);
}
Alarm alarmById = edgeCtx.getAlarmService().findAlarmById(tenantId, new AlarmId(alarmComment.getAlarmId().getId()));
List<ListenableFuture<Void>> delFutures = pushEventToAllRelatedEdges(tenantId, alarmById.getOriginator(),
alarmId, actionType, JacksonUtil.valueToTree(alarmComment), originatorEdgeId, EdgeEventType.ALARM_COMMENT);
return Futures.transform(Futures.allAsList(delFutures), voids -> null, dbCallbackExecutorService);
}
@Override
public EdgeEventType getEdgeEventType() {
return EdgeEventType.ALARM_COMMENT;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\alarm\comment\AlarmCommentEdgeProcessor.java | 2 |
请完成以下Java代码 | public class EdgeConnectionTrigger implements NotificationRuleTrigger {
@Serial
private static final long serialVersionUID = -261939829962721957L;
private final TenantId tenantId;
private final CustomerId customerId;
private final EdgeId edgeId;
private final boolean connected;
private final String edgeName;
@Override
public DeduplicationStrategy getDeduplicationStrategy() {
return DeduplicationStrategy.ALL;
}
@Override
public String getDeduplicationKey() {
return String.join(":", NotificationRuleTrigger.super.getDeduplicationKey(), String.valueOf(connected));
} | @Override
public long getDefaultDeduplicationDuration() {
return TimeUnit.MINUTES.toMillis(1);
}
@Override
public NotificationRuleTriggerType getType() {
return NotificationRuleTriggerType.EDGE_CONNECTION;
}
@Override
public EntityId getOriginatorEntityId() {
return edgeId;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\rule\trigger\EdgeConnectionTrigger.java | 1 |
请完成以下Java代码 | public String getIpAddress() {
return ipAddress;
}
@Override
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
@Override
public String getUserAgent() {
return userAgent;
}
@Override
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
@Override
public String getUserId() {
return userId;
}
@Override
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String getTokenData() {
return tokenData;
}
@Override
public void setTokenData(String tokenData) {
this.tokenData = tokenData;
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>(); | persistentState.put("tokenValue", tokenValue);
persistentState.put("tokenDate", tokenDate);
persistentState.put("ipAddress", ipAddress);
persistentState.put("userAgent", userAgent);
persistentState.put("userId", userId);
persistentState.put("tokenData", tokenData);
return persistentState;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "TokenEntity[tokenValue=" + tokenValue + ", userId=" + userId + "]";
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\TokenEntityImpl.java | 1 |
请完成以下Java代码 | public boolean matches(HttpServletRequest request) {
if (this.httpMethod != null && request.getMethod() != null
&& this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
return false;
}
String url = request.getServletPath();
String pathInfo = request.getPathInfo();
String query = request.getQueryString();
if (pathInfo != null || query != null) {
StringBuilder sb = new StringBuilder(url);
if (pathInfo != null) {
sb.append(pathInfo);
}
if (query != null) {
sb.append('?').append(query);
}
url = sb.toString();
} | logger.debug(LogMessage.format("Checking match of request : '%s'; against '%s'", url, this.pattern));
return this.pattern.matcher(url).matches();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Regex [pattern='").append(this.pattern).append("'");
if (this.httpMethod != null) {
sb.append(", ").append(this.httpMethod);
}
sb.append("]");
return sb.toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\RegexRequestMatcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public FilterChainProxy samlFilter(SAMLProcessingFilter samlProcessingFilter) throws Exception {
List<SecurityFilterChain> chains = new ArrayList<>();
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
samlProcessingFilter));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
samlDiscovery()));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
samlEntryPoint));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
samlLogoutFilter));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
samlLogoutProcessingFilter));
return new FilterChainProxy(chains);
}
@Bean
public MetadataGeneratorFilter metadataGeneratorFilter() {
return new MetadataGeneratorFilter(metadataGenerator());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, SAMLProcessingFilter samlProcessingFilter) throws Exception {
http
.csrf()
.disable();
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint); | http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
.addFilterAfter(samlProcessingFilter, BasicAuthenticationFilter.class)
.addFilterBefore(samlProcessingFilter, CsrfFilter.class);
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated();
http
.logout()
.addLogoutHandler((request, response, authentication) -> {
try {
response.sendRedirect("/saml/logout");
} catch (IOException e) {
e.printStackTrace();
}
});
http.authenticationProvider(samlAuthenticationProvider);
return http.build();
}
} | repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\WebSecurityConfig.java | 2 |
请完成以下Java代码 | private BPartnerId getBPartnerId()
{
return jsonRetrieverService.resolveBPartnerExternalIdentifier(bpartnerIdentifier, orgId)
.orElseThrow(() -> new InvalidIdentifierException("No BPartner found for identifier")
.appendParametersToMessage()
.setParameter("ExternalIdentifier", bpartnerIdentifier));
}
@NonNull
private ProductId getProductId()
{
return externalIdentifierResolver.resolveProductExternalIdentifier(productIdentifier, orgId)
.orElseThrow(() -> new InvalidIdentifierException("Fail to resolve product external identifier")
.appendParametersToMessage()
.setParameter("ExternalIdentifier", productIdentifier));
}
@NonNull
private ZonedDateTime getTargetDateAndTime()
{
final ZonedDateTime zonedDateTime = TimeUtil.asZonedDateTime(targetDate, orgDAO.getTimeZone(orgId));
Check.assumeNotNull(zonedDateTime, "zonedDateTime is not null!");
return zonedDateTime;
}
@NonNull
private List<JsonResponsePrice> getJsonResponsePrices( | @NonNull final ProductId productId,
@NonNull final String productValue,
@NonNull final PriceListVersionId priceListVersionId)
{
return bpartnerPriceListServicesFacade.getProductPricesByPLVAndProduct(priceListVersionId, productId)
.stream()
.map(productPrice -> JsonResponsePrice.builder()
.productId(JsonMetasfreshId.of(productId.getRepoId()))
.productCode(productValue)
.taxCategoryId(JsonMetasfreshId.of(productPrice.getC_TaxCategory_ID()))
.price(productPrice.getPriceStd())
.build())
.collect(ImmutableList.toImmutableList());
}
@NonNull
private String getCurrencyCode(@NonNull final I_M_PriceList priceList)
{
return bpartnerPriceListServicesFacade
.getCurrencyCodeById(CurrencyId.ofRepoId(priceList.getC_Currency_ID()))
.toThreeLetterCode();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\pricing\command\SearchProductPricesCommand.java | 1 |
请完成以下Java代码 | public static void mergeSort(int[] a, int n) {
if (n < 2)
return;
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0; | while (i < left && j < right) {
if (l[i] <= r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];
}
while (i < left)
a[k++] = l[i++];
while (j < right)
a[k++] = r[j++];
}
} | repos\tutorials-master\algorithms-modules\algorithms-sorting\src\main\java\com\baeldung\algorithms\mergesort\MergeSort.java | 1 |
请完成以下Java代码 | public int getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public Duration getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(Duration keepAlive) {
this.keepAlive = keepAlive;
}
public int getQueueSize() {
return queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
public boolean isAllowCoreThreadTimeout() {
return allowCoreThreadTimeout;
}
public void setAllowCoreThreadTimeout(boolean allowCoreThreadTimeout) { | this.allowCoreThreadTimeout = allowCoreThreadTimeout;
}
public Duration getAwaitTerminationPeriod() {
return awaitTerminationPeriod;
}
public void setAwaitTerminationPeriod(Duration awaitTerminationPeriod) {
this.awaitTerminationPeriod = awaitTerminationPeriod;
}
public String getThreadPoolNamingPattern() {
return threadPoolNamingPattern;
}
public void setThreadPoolNamingPattern(String threadPoolNamingPattern) {
this.threadPoolNamingPattern = threadPoolNamingPattern;
}
public void setThreadNamePrefix(String prefix) {
if (prefix == null) {
this.threadPoolNamingPattern = "%d";
} else {
this.threadPoolNamingPattern = prefix + "%d";
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\async\AsyncTaskExecutorConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public NoPaymentType getNoPayment() {
return noPayment;
}
/**
* Sets the value of the noPayment property.
*
* @param value
* allowed object is
* {@link NoPaymentType }
*
*/
public void setNoPayment(NoPaymentType value) {
this.noPayment = value;
}
/**
* Indicates that a direct debit will take place as a result of this invoice.
*
* @return
* possible object is
* {@link DirectDebitType }
*
*/
public DirectDebitType getDirectDebit() {
return directDebit;
}
/**
* Sets the value of the directDebit property.
*
* @param value
* allowed object is
* {@link DirectDebitType }
*
*/
public void setDirectDebit(DirectDebitType value) {
this.directDebit = value;
}
/**
* Used to denote details about a SEPA direct debit, via which this invoice has to be paid.
*
* @return | * possible object is
* {@link SEPADirectDebitType }
*
*/
public SEPADirectDebitType getSEPADirectDebit() {
return sepaDirectDebit;
}
/**
* Sets the value of the sepaDirectDebit property.
*
* @param value
* allowed object is
* {@link SEPADirectDebitType }
*
*/
public void setSEPADirectDebit(SEPADirectDebitType value) {
this.sepaDirectDebit = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PaymentMethodType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class HttpExchangesProperties {
private final Recording recording = new Recording();
public Recording getRecording() {
return this.recording;
}
/**
* Recording properties.
*
* @since 3.0.0
*/
public static class Recording {
/** | * Items to be included in the exchange recording. Defaults to request headers
* (excluding Authorization and Cookie), response headers (excluding Set-Cookie),
* and time taken.
*/
private Set<Include> include = new HashSet<>(Include.defaultIncludes());
public Set<Include> getInclude() {
return this.include;
}
public void setInclude(Set<Include> include) {
this.include = include;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\web\exchanges\HttpExchangesProperties.java | 2 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Table_MView[")
.append(get_ID()).append("]");
return sb.toString();
}
public org.compiere.model.I_AD_Table getAD_Table() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set DB-Tabelle.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Staled.
@param IsStaled Staled */
public void setIsStaled (boolean IsStaled)
{
set_Value (COLUMNNAME_IsStaled, Boolean.valueOf(IsStaled));
}
/** Get Staled.
@return Staled */
public boolean isStaled ()
{
Object oo = get_Value(COLUMNNAME_IsStaled);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo); | }
return false;
}
/** Set Gueltig.
@param IsValid
Element ist gueltig
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Gueltig.
@return Element ist gueltig
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Last Refresh Date.
@param LastRefreshDate Last Refresh Date */
public void setLastRefreshDate (Timestamp LastRefreshDate)
{
set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate);
}
/** Get Last Refresh Date.
@return Last Refresh Date */
public Timestamp getLastRefreshDate ()
{
return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate);
}
/** Set Staled Since.
@param StaledSinceDate Staled Since */
public void setStaledSinceDate (Timestamp StaledSinceDate)
{
set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate);
}
/** Get Staled Since.
@return Staled Since */
public Timestamp getStaledSinceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public ZonedDateTime getLastTrade() {
return lastTrade;
}
public void setLastTrade(ZonedDateTime lastTrade) {
this.lastTrade = lastTrade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QuoteDTO quoteDTO = (QuoteDTO) o; | if (quoteDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), quoteDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "QuoteDTO{" +
"id=" + getId() +
", symbol='" + getSymbol() + "'" +
", price=" + getPrice() +
", lastTrade='" + getLastTrade() + "'" +
"}";
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteDTO.java | 2 |
请完成以下Java代码 | public class MybatisUserDataManager extends AbstractIdmDataManager<UserEntity> implements UserDataManager {
public MybatisUserDataManager(IdmEngineConfiguration idmEngineConfiguration) {
super(idmEngineConfiguration);
}
@Override
public Class<? extends UserEntity> getManagedEntityClass() {
return UserEntityImpl.class;
}
@Override
public UserEntity create() {
return new UserEntityImpl();
}
@SuppressWarnings("unchecked")
@Override
public List<User> findUserByQueryCriteria(UserQueryImpl query) {
return getDbSqlSession().selectList("selectUserByQueryCriteria", query, getManagedEntityClass());
} | @Override
public long findUserCountByQueryCriteria(UserQueryImpl query) {
return (Long) getDbSqlSession().selectOne("selectUserCountByQueryCriteria", query);
}
@Override
@SuppressWarnings("unchecked")
public List<User> findUsersByPrivilegeId(String privilegeId) {
return getDbSqlSession().selectList("selectUsersWithPrivilegeId", privilegeId);
}
@SuppressWarnings("unchecked")
@Override
public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectUserByNativeQuery", parameterMap);
}
@Override
public long findUserCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectUserCountByNativeQuery", parameterMap);
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\data\impl\MybatisUserDataManager.java | 1 |
请完成以下Java代码 | public String asString() {
return "spring.rabbit.listener.id";
}
},
/**
* The queue the listener is plugged to.
*
* @since 3.2
*/
DESTINATION_NAME {
@Override
public String asString() {
return "messaging.destination.name";
}
}
}
/**
* High cardinality tags.
*
* @since 3.2.1
*/
public enum ListenerHighCardinalityTags implements KeyName {
/**
* The delivery tag.
*/
DELIVERY_TAG {
@Override
public String asString() {
return "messaging.rabbitmq.message.delivery_tag";
}
}
}
/**
* Default {@link RabbitListenerObservationConvention} for Rabbit listener key values.
*/
public static class DefaultRabbitListenerObservationConvention implements RabbitListenerObservationConvention { | /**
* A singleton instance of the convention.
*/
public static final DefaultRabbitListenerObservationConvention INSTANCE =
new DefaultRabbitListenerObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(RabbitMessageReceiverContext context) {
MessageProperties messageProperties = context.getCarrier().getMessageProperties();
String consumerQueue = Objects.requireNonNullElse(messageProperties.getConsumerQueue(), "");
return KeyValues.of(
RabbitListenerObservation.ListenerLowCardinalityTags.LISTENER_ID.asString(),
context.getListenerId(),
RabbitListenerObservation.ListenerLowCardinalityTags.DESTINATION_NAME.asString(),
consumerQueue);
}
@Override
public KeyValues getHighCardinalityKeyValues(RabbitMessageReceiverContext context) {
return KeyValues.of(RabbitListenerObservation.ListenerHighCardinalityTags.DELIVERY_TAG.asString(),
String.valueOf(context.getCarrier().getMessageProperties().getDeliveryTag()));
}
@Override
public String getContextualName(RabbitMessageReceiverContext context) {
return context.getSource() + " receive";
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\support\micrometer\RabbitListenerObservation.java | 1 |
请完成以下Java代码 | public ArrayTree<E> deserialize(byte[] data) throws IOException {
try {
if ((data == null) || (data.length == 0)) {
throw new IOException("Null or empty data array is invalid.");
}
if ((data.length == 1) && (data[0] == 0)) {
E[] array = (E[]) new Object[] {};
ArrayTree<E> tree = new ArrayTree<E>(this.comparator, array);
return tree;
}
ByteArrayInputStream bin = new ByteArrayInputStream(data);
DataInputStream din = new DataInputStream(bin);
byte startByte = din.readByte();
if (startByte != 0) {
throw new IOException("wrong array serialized data format");
}
int size = din.readInt();
E[] nodes = (E[]) new Object[size];
for (int i = 0; i < size; i++) {
// Read the object's size
int dataSize = din.readInt();
if (dataSize != 0) {
byte[] bytes = new byte[dataSize];
din.read(bytes);
E key = this.keyMarshaller.deserialize(bytes); | nodes[i] = key;
}
}
ArrayTree<E> arrayTree = new ArrayTree<E>(this.comparator, nodes);
return arrayTree;
}
catch (NullPointerException npe) {
System.out.println("Bad tree : [" + StringTools.dumpBytes(data) + "]");
throw npe;
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\org\apache\directory\server\core\avltree\ArrayMarshaller.java | 1 |
请完成以下Java代码 | public class RequestSizeGatewayFilterFactory
extends AbstractGatewayFilterFactory<RequestSizeGatewayFilterFactory.RequestSizeConfig> {
private static String PREFIX = "kMGTPE";
private static String ERROR = "Request size is larger than permissible limit."
+ " Request size is %s where permissible limit is %s";
public RequestSizeGatewayFilterFactory() {
super(RequestSizeGatewayFilterFactory.RequestSizeConfig.class);
}
private static String getErrorMessage(Long currentRequestSize, Long maxSize) {
return String.format(ERROR, getReadableByteCount(currentRequestSize), getReadableByteCount(maxSize));
}
private static String getReadableByteCount(long bytes) {
int unit = 1000;
if (bytes < unit) {
return bytes + " B";
}
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = Character.toString(PREFIX.charAt(exp - 1));
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
@Override
public GatewayFilter apply(RequestSizeGatewayFilterFactory.RequestSizeConfig requestSizeConfig) {
requestSizeConfig.validate();
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String contentLength = request.getHeaders().getFirst("content-length");
if (!ObjectUtils.isEmpty(contentLength)) {
Long currentRequestSize = Long.valueOf(contentLength);
if (currentRequestSize > requestSizeConfig.getMaxSize().toBytes()) {
exchange.getResponse().setStatusCode(HttpStatus.CONTENT_TOO_LARGE);
if (!exchange.getResponse().isCommitted()) {
exchange.getResponse()
.getHeaders()
.add("errorMessage",
getErrorMessage(currentRequestSize, requestSizeConfig.getMaxSize().toBytes()));
} | return exchange.getResponse().setComplete();
}
}
return chain.filter(exchange);
}
@Override
public String toString() {
return filterToStringCreator(RequestSizeGatewayFilterFactory.this)
.append("max", requestSizeConfig.getMaxSize())
.toString();
}
};
}
public static class RequestSizeConfig {
// TODO: use boot data size type
private DataSize maxSize = DataSize.ofBytes(5000000L);
public DataSize getMaxSize() {
return maxSize;
}
public RequestSizeGatewayFilterFactory.RequestSizeConfig setMaxSize(DataSize maxSize) {
this.maxSize = maxSize;
return this;
}
// TODO: use validator annotation
public void validate() {
Objects.requireNonNull(this.maxSize, "maxSize may not be null");
Assert.isTrue(this.maxSize.toBytes() > 0, "maxSize must be greater than 0");
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestSizeGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public void setMatchIfTermEndsWithCalendarYear (final boolean MatchIfTermEndsWithCalendarYear)
{
set_Value (COLUMNNAME_MatchIfTermEndsWithCalendarYear, MatchIfTermEndsWithCalendarYear);
}
@Override
public boolean isMatchIfTermEndsWithCalendarYear()
{
return get_ValueAsBoolean(COLUMNNAME_MatchIfTermEndsWithCalendarYear);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override | public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStartDay (final int StartDay)
{
set_Value (COLUMNNAME_StartDay, StartDay);
}
@Override
public int getStartDay()
{
return get_ValueAsInt(COLUMNNAME_StartDay);
}
@Override
public void setStartMonth (final int StartMonth)
{
set_Value (COLUMNNAME_StartMonth, StartMonth);
}
@Override
public int getStartMonth()
{
return get_ValueAsInt(COLUMNNAME_StartMonth);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_SubscrDiscount_Line.java | 1 |
请完成以下Java代码 | int findAvailablePort(int minPort, int maxPort) {
Assert.isTrue(minPort > 0, "'minPort' must be greater than 0");
Assert.isTrue(maxPort >= minPort, "'maxPort' must be greater than or equal to 'minPort'");
Assert.isTrue(maxPort <= PORT_RANGE_MAX, "'maxPort' must be less than or equal to " + PORT_RANGE_MAX);
int portRange = maxPort - minPort;
int candidatePort;
int searchCounter = 0;
do {
if (searchCounter > portRange) {
throw new IllegalStateException(String.format(
"Could not find an available %s port in the range [%d, %d] after %d attempts",
name(), minPort, maxPort, searchCounter));
}
candidatePort = findRandomPort(minPort, maxPort);
searchCounter++;
} while (!isPortAvailable(candidatePort));
return candidatePort;
}
/**
* Find the requested number of available ports for this {@code SocketType}, each randomly selected from the
* range [{@code minPort}, {@code maxPort}].
*
* @param numRequested the number of available ports to find
* @param minPort the minimum port number
* @param maxPort the maximum port number
* @return a sorted set of available port numbers for this socket type
* @throws IllegalStateException if the requested number of available ports could not be found
*/
SortedSet<Integer> findAvailablePorts(int numRequested, int minPort, int maxPort) {
Assert.isTrue(minPort > 0, "'minPort' must be greater than 0"); | Assert.isTrue(maxPort > minPort, "'maxPort' must be greater than 'minPort'");
Assert.isTrue(maxPort <= PORT_RANGE_MAX, "'maxPort' must be less than or equal to " + PORT_RANGE_MAX);
Assert.isTrue(numRequested > 0, "'numRequested' must be greater than 0");
Assert.isTrue((maxPort - minPort) >= numRequested,
"'numRequested' must not be greater than 'maxPort' - 'minPort'");
SortedSet<Integer> availablePorts = new TreeSet<>();
int attemptCount = 0;
while ((++attemptCount <= numRequested + 100) && availablePorts.size() < numRequested) {
availablePorts.add(findAvailablePort(minPort, maxPort));
}
if (availablePorts.size() != numRequested) {
throw new IllegalStateException(String.format(
"Could not find %d available %s ports in the range [%d, %d]",
numRequested, name(), minPort, maxPort));
}
return availablePorts;
}
}
} | repos\grpc-spring-master\grpc-common-spring-boot\src\main\java\net\devh\boot\grpc\common\util\SocketUtils.java | 1 |
请完成以下Java代码 | public static SqlViewRowFieldBinding createViewFieldBinding(
@NonNull final SqlDocumentFieldDataBindingDescriptor documentField,
@NonNull final Collection<String> availableDisplayColumnNames)
{
final String fieldName = documentField.getFieldName();
final boolean isDisplayColumnAvailable = documentField.getSqlSelectDisplayValue() != null && availableDisplayColumnNames.contains(fieldName);
return SqlViewRowFieldBinding.builder()
.fieldName(fieldName)
.columnName(documentField.getColumnName())
.keyColumn(documentField.isKeyColumn())
.widgetType(documentField.getWidgetType())
.virtualColumn(documentField.isVirtualColumn())
.mandatory(documentField.isMandatory())
.hideGridColumnIfEmpty(documentField.isHideGridColumnIfEmpty())
//
.sqlValueClass(documentField.getSqlValueClass())
.sqlSelectValue(documentField.getSqlSelectValue())
.sqlSelectDisplayValue(isDisplayColumnAvailable ? documentField.getSqlSelectDisplayValue() : null)
//
.sqlOrderBy(documentField.getSqlOrderBy())
//
.fieldLoader(createSqlViewRowFieldLoader(documentField, isDisplayColumnAvailable))
//
.build();
}
private static SqlViewRowFieldLoader createSqlViewRowFieldLoader(
@NonNull final SqlDocumentFieldDataBindingDescriptor documentField,
final boolean isDisplayColumnAvailable)
{
return new DocumentFieldValueLoaderAsSqlViewRowFieldLoader(
documentField.getDocumentFieldValueLoader(),
documentField.getLookupDescriptor(),
isDisplayColumnAvailable);
}
private IViewInvalidationAdvisor getViewInvalidationAdvisor(final WindowId windowId)
{
return viewInvalidationAdvisorsByWindowId.getOrDefault(windowId, DefaultViewInvalidationAdvisor.instance);
} | @Value
private static class DocumentFieldValueLoaderAsSqlViewRowFieldLoader implements SqlViewRowFieldLoader
{
@NonNull DocumentFieldValueLoader fieldValueLoader;
@Nullable LookupDescriptor lookupDescriptor;
boolean isDisplayColumnAvailable;
@Override
@Nullable
public Object retrieveValue(@NonNull final ResultSet rs, final String adLanguage) throws SQLException
{
return fieldValueLoader.retrieveFieldValue(
rs,
isDisplayColumnAvailable,
adLanguage,
lookupDescriptor);
}
}
@Value
private static class SqlViewBindingKey
{
@NonNull WindowId windowId;
@Nullable Characteristic requiredFieldCharacteristic;
@Nullable ViewProfileId profileId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlViewBindingFactory.java | 1 |
请完成以下Java代码 | public abstract class BaseAggInterval implements AggInterval {
@NotBlank
protected String tz;
protected Long offsetSec; // delay seconds since start of interval
@Override
public ZoneId getZoneId() {
return ZoneId.of(tz);
}
protected long getOffsetSafe() {
return offsetSec != null ? offsetSec : 0L;
}
@Override
public long getCurrentIntervalDurationMillis() {
return getCurrentIntervalEndTs() - getCurrentIntervalStartTs();
}
@Override
public long getCurrentIntervalStartTs() {
ZoneId zoneId = getZoneId();
ZonedDateTime now = ZonedDateTime.now(zoneId);
return getDateTimeIntervalStartTs(now);
}
@Override
public long getDateTimeIntervalStartTs(ZonedDateTime dateTime) {
long offset = getOffsetSafe();
ZonedDateTime shiftedNow = dateTime.minusSeconds(offset);
ZonedDateTime alignedStart = getAlignedBoundary(shiftedNow, false);
ZonedDateTime actualStart = alignedStart.plusSeconds(offset);
return actualStart.toInstant().toEpochMilli();
}
@Override
public long getCurrentIntervalEndTs() {
ZoneId zoneId = getZoneId();
ZonedDateTime now = ZonedDateTime.now(zoneId);
return getDateTimeIntervalEndTs(now);
}
@Override
public long getDateTimeIntervalEndTs(ZonedDateTime dateTime) {
long offset = getOffsetSafe();
ZonedDateTime shiftedNow = dateTime.minusSeconds(offset); | ZonedDateTime alignedEnd = getAlignedBoundary(shiftedNow, true);
ZonedDateTime actualEnd = alignedEnd.plusSeconds(offset);
return actualEnd.toInstant().toEpochMilli();
}
protected abstract ZonedDateTime alignToIntervalStart(ZonedDateTime reference);
protected ZonedDateTime getAlignedBoundary(ZonedDateTime reference, boolean next) {
ZonedDateTime base = alignToIntervalStart(reference);
return next ? getNextIntervalStart(base) : base;
}
@Override
public void validate() {
try {
getZoneId();
} catch (Exception ex) {
throw new IllegalArgumentException("Invalid timezone in interval: " + ex.getMessage());
}
if (offsetSec != null) {
if (offsetSec < 0) {
throw new IllegalArgumentException("Offset cannot be negative.");
}
if (TimeUnit.SECONDS.toMillis(offsetSec) >= getCurrentIntervalDurationMillis()) {
throw new IllegalArgumentException("Offset must be greater than interval duration.");
}
}
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\aggregation\single\interval\BaseAggInterval.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Optional<FailedTimeBooking> getOptionalByExternalIdAndSystem(@NonNull final ExternalSystem externalSystem,
@NonNull final String externalId)
{
return queryBL.createQueryBuilder(I_S_FailedTimeBooking.class)
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalSystem_ID, externalSystem.getId() )
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalId, externalId)
.create()
.firstOnlyOptional(I_S_FailedTimeBooking.class)
.map(this::buildFailedTimeBooking);
}
public ImmutableList<FailedTimeBooking> listBySystem(@NonNull final ExternalSystem externalSystem)
{
return queryBL.createQueryBuilder(I_S_FailedTimeBooking.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_S_FailedTimeBooking.COLUMNNAME_ExternalSystem_ID, externalSystem.getId() )
.create()
.list()
.stream()
.map(this::buildFailedTimeBooking)
.collect(ImmutableList.toImmutableList()); | }
private FailedTimeBooking buildFailedTimeBooking(@NonNull final I_S_FailedTimeBooking record)
{
final ExternalSystem externalSystem = externalSystemRepository.getById(ExternalSystemId.ofRepoId(record.getExternalSystem_ID()));
return FailedTimeBooking.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.failedTimeBookingId(FailedTimeBookingId.ofRepoId(record.getS_FailedTimeBooking_ID()))
.externalId(record.getExternalId())
.externalSystem(externalSystem)
.jsonValue(record.getJSONValue())
.errorMsg(record.getImportErrorMsg())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\importer\failed\FailedTimeBookingRepository.java | 2 |
请完成以下Java代码 | public void setExistingHUs(final IHUAllocations existingHUs)
{
assertConfigurable();
this.existingHUs = existingHUs;
}
@Override
public LUTUResult getResult()
{
final LUTUResult.LUTUResultBuilder result = LUTUResult.builder()
.topLevelTUs(LUTUResult.TUsList.ofSingleTUsList(_createdTUsForRemainingQty));
for (final I_M_HU lu : _createdLUs)
{
final TUProducerDestination tuProducer = getTUProducerOrNull(lu);
final List<LUTUResult.TU> tus = tuProducer != null ? tuProducer.getResult() : ImmutableList.of(); | result.lu(LUTUResult.LU.of(lu, tus));
}
if (_existingLU != null)
{
final TUProducerDestination tuProducer = getTUProducerOrNull(_existingLU);
final List<LUTUResult.TU> tus = tuProducer != null ? tuProducer.getResult() : ImmutableList.of();
result.lu(LUTUResult.LU.of(_existingLU, tus).markedAsPreExistingLU());
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\LUTUProducerDestination.java | 1 |
请完成以下Java代码 | public PublicKey getPublicKey(String resourceLocation, KeyFormat format) {
return getPublicKey(resourceLoader.getResource(resourceLocation), format);
}
/**
* <p>getPublicKey.</p>
*
* @param resource a {@link org.springframework.core.io.Resource} object
* @param format a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
* @return a {@link java.security.PublicKey} object
*/
@SneakyThrows
public PublicKey getPublicKey(Resource resource, KeyFormat format) {
byte[] keyBytes = getResourceBytes(resource);
if (format == KeyFormat.PEM) {
keyBytes = decodePem(keyBytes, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER);
}
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
/**
* <p>encrypt.</p>
*
* @param msg an array of {@link byte} objects
* @param key a {@link java.security.PublicKey} object
* @return an array of {@link byte} objects
*/
@SneakyThrows
public byte[] encrypt(byte[] msg, PublicKey key) {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(msg);
}
/**
* <p>decrypt.</p> | *
* @param msg an array of {@link byte} objects
* @param key a {@link java.security.PrivateKey} object
* @return an array of {@link byte} objects
*/
@SneakyThrows
public byte[] decrypt(byte[] msg, PrivateKey key) {
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(msg);
}
public enum KeyFormat {
DER,
PEM;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\AsymmetricCryptography.java | 1 |
请完成以下Java代码 | public int getMobileUI_UserProfile_Picking_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID);
}
@Override
public org.compiere.model.I_MobileUI_UserProfile_Picking_Job getMobileUI_UserProfile_Picking_Job()
{
return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, org.compiere.model.I_MobileUI_UserProfile_Picking_Job.class);
}
@Override
public void setMobileUI_UserProfile_Picking_Job(final org.compiere.model.I_MobileUI_UserProfile_Picking_Job MobileUI_UserProfile_Picking_Job)
{
set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, org.compiere.model.I_MobileUI_UserProfile_Picking_Job.class, MobileUI_UserProfile_Picking_Job);
} | @Override
public void setMobileUI_UserProfile_Picking_Job_ID (final int MobileUI_UserProfile_Picking_Job_ID)
{
if (MobileUI_UserProfile_Picking_Job_ID < 1)
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, null);
else
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID, MobileUI_UserProfile_Picking_Job_ID);
}
@Override
public int getMobileUI_UserProfile_Picking_Job_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_Job_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking_BPartner.java | 1 |
请完成以下Java代码 | public Collection<ObjectModel> getObjectModels() {
LwM2mClient lwM2mClient = lwM2mClientContext.getClientByEndpoint(registration.getEndpoint());
Map<Integer, LwM2m.Version> supportedObjects = lwM2mClient.getSupportedClientObjects();
Collection<ObjectModel> result = new ArrayList<>(supportedObjects.size());
for (Map.Entry<Integer, LwM2m.Version> supportedObject : supportedObjects.entrySet()) {
ObjectModel objectModel = this.getObjectModelDynamic(supportedObject.getKey(), String.valueOf(supportedObject.getValue()));
if (objectModel != null) {
result.add(objectModel);
}
}
return result;
}
private ObjectModel getObjectModelDynamic(Integer objectId, String version) {
String key = getKeyIdVer(objectId, version);
ObjectModel objectModel = tenantId != null ? models.get(tenantId).get(key) : null;
if (tenantId != null && objectModel == null) {
modelsLock.lock();
try {
objectModel = models.get(tenantId).get(key);
if (objectModel == null) { | objectModel = getObjectModel(key);
}
if (objectModel != null) {
models.get(tenantId).put(key, objectModel);
} else {
log.error("Tenant hasn't such the resource: Object model with id [{}] version [{}].", objectId, version);
}
} finally {
modelsLock.unlock();
}
}
return objectModel;
}
private ObjectModel getObjectModel(String key) {
Optional<TbResource> tbResource = context.getTransportResourceCache().get(this.tenantId, LWM2M_MODEL, key);
return tbResource.map(resource -> helper.parseFromXmlToObjectModel(resource.getData(),
key + ".xml")).orElse(null);
}
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\LwM2mVersionedModelProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ShiroConfig {
/**
* 创建shiroFilterFactoryBean
*/
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/**","authc");
// filterMap.put("/update","authc");
//使用通配的方式设置某一个目录的访问级别
/* filterMap.put("/templates","authc");*/
//修改访问被拦截过后的跳转页面
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean;
}
/**
* 创建defaultWebSecurityManageer
*/
@Bean(value = "defaultWebSecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联我们创建的realm
securityManager.setRealm(userRealm); | return securityManager;
}
/**
* 创建realm
*/
@Bean(value = "userRealm")
public UserRealm getRealm(){
return new UserRealm();
}
} | repos\spring-boot-quick-master\quick-app\src\main\java\com\app\controller\ShiroConfig.java | 2 |
请完成以下Java代码 | public void actualImportError(@NonNull final ActualImportRecordsResult.Error error)
{
actualImportErrors.add(error);
}
}
@EqualsAndHashCode
private static final class Counter
{
private boolean unknownValue;
private int value = 0;
@Override
public String toString()
{
return unknownValue ? "N/A" : String.valueOf(value);
}
public void set(final int value)
{
if (value < 0)
{
throw new AdempiereException("value shall NOT be negative: " + value); | }
this.value = value;
this.unknownValue = false;
}
public void add(final int valueToAdd)
{
Check.assumeGreaterOrEqualToZero(valueToAdd, "valueToAdd");
set(this.value + valueToAdd);
}
public OptionalInt toOptionalInt() {return unknownValue ? OptionalInt.empty() : OptionalInt.of(value);}
public int toIntOr(final int defaultValue) {return unknownValue ? defaultValue : value;}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\ImportProcessResult.java | 1 |
请完成以下Java代码 | public boolean add(final E item)
{
final boolean added = list.add(item);
fireIntervalAdded(this, list.size() - 1, list.size() - 1);
selectFirstItemIfOnlyOneItemAndNotSelected();
return added;
}
public boolean addAll(Collection<? extends E> c)
{
if(c == null || c.isEmpty())
{
return false;
}
final int sizeBeforeAdd = list.size();
final boolean added = list.addAll(c);
final int sizeAfterAdd = list.size();
// Fire interval added if any
final int index0 = sizeBeforeAdd;
final int index1 = sizeAfterAdd - 1;
if (index0 <= index1)
{
fireIntervalAdded(this, index0, index1);
}
selectFirstItemIfOnlyOneItemAndNotSelected();
return added;
}
/**
* @param item
* @return <tt>true</tt> if the element was added
*/
public boolean addIfAbsent(final E item)
{
if (list.contains(item))
{
return false;
}
return add(item);
}
public int size()
{ | return list.size();
}
public E get(final int index)
{
return list.get(index);
}
public void clear()
{
if (list.isEmpty())
{
return;
}
final int sizeBeforeClear = list.size();
list.clear();
fireIntervalRemoved(this, 0, sizeBeforeClear - 1);
}
public void set(final Collection<E> items)
{
clear();
addAll(items);
}
public void set(final E[] items)
{
final List<E> itemsAsList;
if (items == null || items.length == 0)
{
itemsAsList = Collections.emptyList();
}
else
{
itemsAsList = Arrays.asList(items);
}
set(itemsAsList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\ListComboBoxModel.java | 1 |
请完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof DocumentKey))
{
return false;
}
final DocumentKey other = (DocumentKey)obj;
return Objects.equals(documentType, other.documentType)
&& Objects.equals(documentTypeId, other.documentTypeId)
&& Objects.equals(documentId, other.documentId);
}
public WindowId getWindowId() | {
Check.assume(documentType == DocumentType.Window, "documentType shall be {} but it was {}", DocumentType.Window, documentType);
return WindowId.of(documentTypeId);
}
public DocumentId getDocumentId()
{
return documentId;
}
public DocumentPath getDocumentPath()
{
return DocumentPath.rootDocumentPath(documentType, documentTypeId, documentId);
}
} // DocumentKey
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentCollection.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() { | return id;
}
public void setId(int id) {
this.id = id;
}
public void addProduct(Product product) {
product.setStore(this);
this.products.add(product);
}
public List<Product> getProducts() {
return this.products;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\domain\Store.java | 1 |
请完成以下Java代码 | public class Address {
private String line;
private String city;
private String state;
private Integer zip;
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city; | }
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getZip() {
return zip;
}
public void setZip(Integer zip) {
this.zip = zip;
}
} | repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\snakeyaml\Address.java | 1 |
请完成以下Java代码 | public Map<String, Object> shutdown() throws Exception {
Map<String, Object> shutdownCountData = new LinkedHashMap<>();
// registries
int registriesCount = getRegistries().size();
// protocols
int protocolsCount = getProtocolConfigsBeanMap().size();
shutdownCountData.put("registries", registriesCount);
shutdownCountData.put("protocols", protocolsCount);
// Service Beans
Map<String, ServiceBean> serviceBeansMap = getServiceBeansMap();
if (!serviceBeansMap.isEmpty()) {
for (ServiceBean serviceBean : serviceBeansMap.values()) {
serviceBean.destroy();
}
}
shutdownCountData.put("services", serviceBeansMap.size());
// Reference Beans
ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor(); | int referencesCount = beanPostProcessor.getReferenceBeans().size();
beanPostProcessor.destroy();
shutdownCountData.put("references", referencesCount);
// Set Result to complete
Map<String, Object> shutdownData = new TreeMap<>();
shutdownData.put("shutdown.count", shutdownCountData);
return shutdownData;
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\DubboShutdownMetadata.java | 1 |
请完成以下Java代码 | public static String toJson(@Nullable final DetailId detailId)
{
return detailId == null ? null : (detailId.idPrefix + PARTS_SEPARATOR + detailId.idInt);
}
public static Set<String> toJson(@Nullable final Collection<DetailId> detailIds)
{
if (detailIds == null || detailIds.isEmpty())
{
return ImmutableSet.of();
}
return detailIds.stream().map(detailId -> detailId.toJson()).collect(GuavaCollectors.toImmutableSet());
}
@Getter
private final String idPrefix;
@Getter
private final int idInt;
private transient String _tableAlias = null; // lazy
private DetailId(@NonNull final String idPrefix, final int idInt)
{
assumeNotEmpty(idPrefix, "idPrefix");
Check.assume(!idPrefix.contains(PARTS_SEPARATOR), "The given prefix may not contain the the parts-separator={}; prefix={}", PARTS_SEPARATOR, idPrefix);
this.idPrefix = idPrefix;
this.idInt = idInt;
}
@Override
public String toString()
{
return toJson(this);
}
@JsonValue
public String toJson()
{
return toJson(this);
}
public String getTableAlias()
{
String tableAlias = this._tableAlias;
if (tableAlias == null)
{
tableAlias = this._tableAlias = "d" + idInt;
} | return tableAlias;
}
@Nullable
public AdTabId toAdTabId()
{
if (PREFIX_AD_TAB_ID.equals(idPrefix))
{
return AdTabId.ofRepoId(idInt);
}
return null;
}
@Override
public int compareTo(@Nullable final DetailId o)
{
if (o == null)
{
return 1;
}
return Objects.compare(toJson(), o.toJson(), Comparator.naturalOrder());
}
public static boolean equals(@Nullable final DetailId o1, @Nullable final DetailId o2)
{
return Objects.equals(o1, o2);
}
public int getIdIntAssumingPrefix(@NonNull final String expectedPrefix)
{
assertIdPrefix(expectedPrefix);
return getIdInt();
}
private void assertIdPrefix(@NonNull final String expectedPrefix)
{
if (!expectedPrefix.equals(idPrefix))
{
throw new AdempiereException("Expected id prefix `" + expectedPrefix + "` for " + this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DetailId.java | 1 |
请完成以下Java代码 | private void cmd_file()
{
// Show File Open Dialog
final JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(false);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.showOpenDialog(this);
// Get File Name
final File imageFile = jfc.getSelectedFile();
if (imageFile == null || imageFile.isDirectory() || !imageFile.exists())
{
return;
}
final String fileName = imageFile.getAbsolutePath();
//
// See if we can load & display it
final byte[] data;
final ImageIcon image;
try
{
data = Util.readBytes(imageFile);
image = new ImageIcon(data, fileName);
}
catch (final Exception e)
{
clientUI.error(getWindowNo(), e);
return;
}
//
// Update UI
fileButton.setText(imageFile.getAbsolutePath());
imagePreviewLabel.setIcon(image);
confirmPanel.getOKButton().setEnabled(true);
pack();
// Save info
m_mImage.setName(fileName); | m_mImage.setImageURL(fileName);
m_mImage.setBinaryData(data);
} // cmd_file
/**
* Get Image ID
*
* @return ID or -1
*/
public int getAD_Image_ID()
{
if (m_mImage != null && m_mImage.getAD_Image_ID() > 0)
{
return m_mImage.getAD_Image_ID();
}
return -1;
}
/**
* @return true if the window was canceled and the caller shall ignore the result
*/
public boolean isCanceled()
{
return canceled;
}
} // VImageDialog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VImageDialog.java | 1 |
请完成以下Java代码 | public List<LoggerConfiguration> getLoggerConfigurations() {
List<LoggerConfiguration> result = new ArrayList<>();
Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
while (names.hasMoreElements()) {
result.add(getLoggerConfiguration(names.nextElement()));
}
result.sort(CONFIGURATION_COMPARATOR);
return Collections.unmodifiableList(result);
}
@Override
public @Nullable LoggerConfiguration getLoggerConfiguration(String loggerName) {
Logger logger = Logger.getLogger(loggerName);
if (logger == null) {
return null;
}
LogLevel level = LEVELS.convertNativeToSystem(logger.getLevel());
LogLevel effectiveLevel = LEVELS.convertNativeToSystem(getEffectiveLevel(logger));
String name = (StringUtils.hasLength(logger.getName()) ? logger.getName() : ROOT_LOGGER_NAME);
Assert.state(effectiveLevel != null, "effectiveLevel must not be null");
return new LoggerConfiguration(name, level, effectiveLevel);
}
private Level getEffectiveLevel(Logger root) {
Logger logger = root;
while (logger.getLevel() == null) {
logger = logger.getParent();
}
return logger.getLevel();
}
@Override
public Runnable getShutdownHandler() {
return () -> LogManager.getLogManager().reset();
} | @Override
public void cleanUp() {
this.configuredLoggers.clear();
}
/**
* {@link LoggingSystemFactory} that returns {@link JavaLoggingSystem} if possible.
*/
@Order(Ordered.LOWEST_PRECEDENCE - 1024)
public static class Factory implements LoggingSystemFactory {
private static final boolean PRESENT = ClassUtils.isPresent("java.util.logging.LogManager",
Factory.class.getClassLoader());
@Override
public @Nullable LoggingSystem getLoggingSystem(ClassLoader classLoader) {
if (PRESENT) {
return new JavaLoggingSystem(classLoader);
}
return null;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\java\JavaLoggingSystem.java | 1 |
请完成以下Java代码 | public static ResponseEntity ok() {
ResponseEntity ResponseEntity = new ResponseEntity();
return ResponseEntity;
}
public static ResponseEntity error(int code, String msg) {
ResponseEntity ResponseEntity = new ResponseEntity();
ResponseEntity.setStatus(code);
ResponseEntity.setMessage(msg);
return ResponseEntity;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
} | public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data == null ? new HashMap() : data;
}
public void setData(Object data) {
this.data = data;
}
} | repos\springBoot-master\abel-util\src\main\java\cn\abel\response\ResponseEntity.java | 1 |
请完成以下Java代码 | public String moderate(String text) {
ModerationPrompt moderationRequest = new ModerationPrompt(text);
ModerationResponse response = openAiModerationModel.call(moderationRequest);
Moderation output = response.getResult().getOutput();
return output.getResults().stream()
.map(this::buildModerationResult)
.collect(Collectors.joining("\n"));
}
private String buildModerationResult(ModerationResult moderationResult) {
Categories categories = moderationResult.getCategories();
String violations = Stream.of(
Map.entry("Sexual", categories.isSexual()),
Map.entry("Hate", categories.isHate()),
Map.entry("Harassment", categories.isHarassment()), | Map.entry("Self-Harm", categories.isSelfHarm()),
Map.entry("Sexual/Minors", categories.isSexualMinors()),
Map.entry("Hate/Threatening", categories.isHateThreatening()),
Map.entry("Violence/Graphic", categories.isViolenceGraphic()),
Map.entry("Self-Harm/Intent", categories.isSelfHarmIntent()),
Map.entry("Self-Harm/Instructions", categories.isSelfHarmInstructions()),
Map.entry("Harassment/Threatening", categories.isHarassmentThreatening()),
Map.entry("Violence", categories.isViolence()))
.filter(entry -> Boolean.TRUE.equals(entry.getValue()))
.map(Map.Entry::getKey)
.collect(Collectors.joining(", "));
return violations.isEmpty()
? "No category violations detected."
: "Violated categories: " + violations;
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-4\src\main\java\com\baeldung\springai\moderation\TextModerationService.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
} | public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", make='" + make + '\'' +
", model='" + model + '\'' +
'}';
}
} | repos\tutorials-master\persistence-modules\spring-persistence\src\main\java\com\baeldung\spring\transactional\Car.java | 1 |
请完成以下Java代码 | public void ensureOrderLineHasShipper(final I_C_OrderLine orderLine)
{
if (orderLine.getM_Shipper_ID() <= 0)
{
logger.debug("Making sure {} has a M_Shipper_ID", orderLine);
orderLineBL.setShipper(orderLine);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID })
public void updateProductDescriptionFromProductBOMIfConfigured(final I_C_OrderLine orderLine)
{
orderLineBL.updateProductDescriptionFromProductBOMIfConfigured(orderLine);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID })
public void updateProductDocumentNote(final I_C_OrderLine orderLine)
{
orderLineBL.updateProductDocumentNote(orderLine);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsGroupCompensationLine, I_C_OrderLine.COLUMNNAME_C_Order_CompensationGroup_ID })
public void renumberLinesIfCompensationGroupChanged(@NonNull final I_C_OrderLine orderLine)
{
if (!OrderGroupCompensationUtils.isInGroup(orderLine))
{
return;
}
groupChangesHandler.renumberOrderLinesForOrderId(OrderId.ofRepoId(orderLine.getC_Order_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID, I_C_OrderLine.COLUMNNAME_QtyOrdered })
public void updateWeight(@NonNull final I_C_OrderLine orderLine)
{
final I_C_Order order = orderBL.getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
orderBL.setWeightFromLines(order);
saveRecord(order);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge, I_C_OrderLine.COLUMNNAME_PriceActual, I_C_OrderLine.COLUMNNAME_PriceEntered }) | public void updatePriceToZero(final I_C_OrderLine orderLine)
{
if (orderLine.isWithoutCharge())
{
orderLine.setPriceActual(BigDecimal.ZERO);
orderLine.setPriceEntered(BigDecimal.ZERO);
orderLine.setIsManualPrice(true);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge})
public void updatePriceToStd(final I_C_OrderLine orderLine)
{
if (!orderLine.isWithoutCharge())
{
orderLine.setPriceActual(orderLine.getPriceStd());
orderLine.setPriceEntered(orderLine.getPriceStd());
orderLine.setIsManualPrice(false);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_OrderLine.java | 1 |
请完成以下Java代码 | protected void prepare()
{
int migrationId = -1;
boolean isMergeTo = false;
for (ProcessInfoParameter p : getParametersAsArray())
{
String para = p.getParameterName();
if (para == null)
continue;
else if (para.equals("AD_Migration_ID"))
migrationId = p.getParameterAsInt();
else if (para.equals("IsMergeTo"))
isMergeTo = p.getParameterAsBoolean();
else if (para.equals("DeleteOld"))
isDeleteFrom = true;
}
int recordId = -1;
if (I_AD_Migration.Table_Name.equals(getTableName()) && getRecord_ID() > 0)
{
recordId = getRecord_ID();
}
final int fromId;
final int toId;
if (isMergeTo)
{
fromId = recordId;
toId = migrationId;
}
else
{
fromId = migrationId;
toId = recordId;
}
migrationTo = InterfaceWrapperHelper.create(getCtx(), toId, I_AD_Migration.class, get_TrxName());
migrationFrom = InterfaceWrapperHelper.create(getCtx(), fromId, I_AD_Migration.class, get_TrxName());
} | @Override
protected String doIt() throws Exception
{
if (migrationFrom == null || migrationFrom.getAD_Migration_ID() <= 0
|| migrationTo == null || migrationTo.getAD_Migration_ID() <= 0
|| migrationFrom.getAD_Migration_ID() == migrationTo.getAD_Migration_ID())
{
throw new AdempiereException("Two different existing migrations required for merge");
}
Services.get(IMigrationBL.class).mergeMigration(migrationTo, migrationFrom);
addLog("Merged " + migrationFrom + " to " + migrationTo);
if (isDeleteFrom)
{
InterfaceWrapperHelper.delete(migrationFrom);
addLog("Deleted " + migrationFrom);
}
return "@OK@";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\ad\migration\process\MigrationMergeToFrom.java | 1 |
请完成以下Java代码 | public void addAttribute(DmnExtensionAttribute attribute) {
if (attribute != null && attribute.getName() != null && !attribute.getName().trim().isEmpty()) {
List<DmnExtensionAttribute> attributeList = null;
if (!this.attributes.containsKey(attribute.getName())) {
attributeList = new ArrayList<>();
this.attributes.put(attribute.getName(), attributeList);
}
this.attributes.get(attribute.getName()).add(attribute);
}
}
public void setValues(DmnElement otherElement) {
setId(otherElement.getId());
extensionElements = new LinkedHashMap<>();
if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) {
for (String key : otherElement.getExtensionElements().keySet()) {
List<DmnExtensionElement> otherElementList = otherElement.getExtensionElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<DmnExtensionElement> elementList = new ArrayList<>();
for (DmnExtensionElement extensionElement : otherElementList) {
elementList.add(extensionElement.clone());
}
extensionElements.put(key, elementList);
}
}
} | attributes = new LinkedHashMap<>();
if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) {
for (String key : otherElement.getAttributes().keySet()) {
List<DmnExtensionAttribute> otherAttributeList = otherElement.getAttributes().get(key);
if (otherAttributeList != null && !otherAttributeList.isEmpty()) {
List<DmnExtensionAttribute> attributeList = new ArrayList<>();
for (DmnExtensionAttribute extensionAttribute : otherAttributeList) {
attributeList.add(extensionAttribute.clone());
}
attributes.put(key, attributeList);
}
}
}
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnElement.java | 1 |
请完成以下Java代码 | public static OrgId ofRepoIdOrAny(final int repoId)
{
final OrgId orgId = ofRepoIdOrNull(repoId);
return orgId != null ? orgId : ANY;
}
public static Optional<OrgId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : -1;
}
public static int toRepoIdOrAny(@Nullable final OrgId orgId)
{
return orgId != null ? orgId.getRepoId() : ANY.repoId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public boolean isAny()
{
return repoId == Env.CTXVALUE_AD_Org_ID_Any;
}
/**
* @return {@code true} if the org in question is not {@code *} (i.e. "ANY"), but a specific organisation's ID
*/
public boolean isRegular() | {
return !isAny();
}
public void ifRegular(@NonNull final Consumer<OrgId> consumer)
{
if (isRegular())
{
consumer.accept(this);
}
}
@Nullable
public OrgId asRegularOrNull() {return isRegular() ? this : null;}
public static boolean equals(@Nullable final OrgId id1, @Nullable final OrgId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgId.java | 1 |
请完成以下Java代码 | public @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) {
Assert.notNull(name, "'name' must not be null");
ConfigurationProperty result = getSource().getConfigurationProperty(name);
if (result == null) {
ConfigurationPropertyName aliasedName = getAliases().getNameForAlias(name);
result = (aliasedName != null) ? getSource().getConfigurationProperty(aliasedName) : null;
}
return result;
}
@Override
public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) {
Assert.notNull(name, "'name' must not be null");
ConfigurationPropertyState result = this.source.containsDescendantOf(name);
if (result != ConfigurationPropertyState.ABSENT) {
return result;
}
for (ConfigurationPropertyName alias : getAliases().getAliases(name)) {
ConfigurationPropertyState aliasResult = this.source.containsDescendantOf(alias);
if (aliasResult != ConfigurationPropertyState.ABSENT) {
return aliasResult;
}
}
for (ConfigurationPropertyName from : getAliases()) { | for (ConfigurationPropertyName alias : getAliases().getAliases(from)) {
if (name.isAncestorOf(alias)) {
if (this.source.getConfigurationProperty(from) != null) {
return ConfigurationPropertyState.PRESENT;
}
}
}
}
return ConfigurationPropertyState.ABSENT;
}
@Override
public @Nullable Object getUnderlyingSource() {
return this.source.getUnderlyingSource();
}
protected ConfigurationPropertySource getSource() {
return this.source;
}
protected ConfigurationPropertyNameAliases getAliases() {
return this.aliases;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\AliasedConfigurationPropertySource.java | 1 |
请完成以下Java代码 | public void setAuthenticated(boolean isAuthenticated) {
this.isAuthenticated = isAuthenticated;
}
public List<String> getGroups() {
return groups;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
public List<String> getTenants() {
return tenants;
} | public void setTenants(List<String> tenants) {
this.tenants = tenants;
}
public static AuthenticationResult successful(String userId) {
return new AuthenticationResult(userId, true);
}
public static AuthenticationResult unsuccessful() {
return new AuthenticationResult(null, false);
}
public static AuthenticationResult unsuccessful(String userId) {
return new AuthenticationResult(userId, false);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\security\auth\AuthenticationResult.java | 1 |
请完成以下Java代码 | protected final void invalidatePickingSlotsView()
{
final PickingSlotView pickingSlotsView = getPickingSlotViewOrNull();
if (pickingSlotsView == null)
{
return;
}
invalidateView(pickingSlotsView.getViewId());
}
protected final void invalidatePackablesView()
{
final PickingSlotView pickingSlotsView = getPickingSlotViewOrNull();
if (pickingSlotsView == null)
{
return;
}
final ViewId packablesViewId = pickingSlotsView.getParentViewId();
if (packablesViewId == null) | {
return;
}
invalidateView(packablesViewId);
}
protected final void addHUIdToCurrentPickingSlot(@NonNull final HuId huId)
{
final PickingSlotView pickingSlotsView = getPickingSlotView();
final PickingSlotRow pickingSlotRow = getPickingSlotRow();
final PickingSlotId pickingSlotId = pickingSlotRow.getPickingSlotId();
final ShipmentScheduleId shipmentScheduleId = pickingSlotsView.getCurrentShipmentScheduleId();
pickingCandidateService.pickHU(PickRequest.builder()
.shipmentScheduleId(shipmentScheduleId)
.pickFrom(PickFrom.ofHuId(huId))
.pickingSlotId(pickingSlotId)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\husToPick\process\HUsToPickViewBasedProcess.java | 1 |
请完成以下Java代码 | public final Timestamp getDatePromised() {
return datePromised;
}
public final void setDatePromised(Timestamp datePromised) {
this.datePromised = datePromised;
}
public final boolean isIncludeWhenIncompleteInOutExists() {
return isIncludeWhenIncompleteInOutExists;
}
public final void setIncludeWhenIncompleteInOutExists(boolean isUnconfirmedInOut) {
this.isIncludeWhenIncompleteInOutExists = isUnconfirmedInOut;
}
public final boolean isConsolidateDocument() {
return consolidateDocument;
}
public final void setConsolidateDocument(boolean consolidateDocument) {
this.consolidateDocument = consolidateDocument;
}
public final Timestamp getMovementDate() {
return movementDate;
}
public final void setMovementDate(Timestamp dateShipped) {
this.movementDate = dateShipped;
}
public final boolean isPreferBPartner() {
return preferBPartner;
} | public final void setPreferBPartner(boolean preferBPartner) {
this.preferBPartner = preferBPartner;
}
public final boolean isIgnorePostageFreeamount() {
return ignorePostageFreeamount;
}
public final void setIgnorePostageFreeamount(boolean ignorePostageFreeamount) {
this.ignorePostageFreeamount = ignorePostageFreeamount;
}
public Set<Integer> getSelectedOrderLineIds() {
return selectedOrderLineIds;
}
public void setSelectedOrderLineIds(Set<Integer> selectedOrderLineIds) {
this.selectedOrderLineIds = selectedOrderLineIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\shipment\ShipmentParams.java | 1 |
请完成以下Java代码 | public CarrierGoodsType getOrCreateGoodsType(@NonNull final ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final CarrierGoodsType cachedGoodsTypeByExternalId = getCachedGoodsTypeByShipperExternalId(shipperId, externalId);
if (cachedGoodsTypeByExternalId != null)
{
return cachedGoodsTypeByExternalId;
}
return createGoodsType(shipperId, externalId, name);
}
private CarrierGoodsType createGoodsType(final @NonNull ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final I_Carrier_Goods_Type po = InterfaceWrapperHelper.newInstance(I_Carrier_Goods_Type.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(externalId);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromRecord(po);
}
@Nullable
private CarrierGoodsType getCachedGoodsTypeByShipperExternalId(@NonNull final ShipperId shipperId, @Nullable final String externalId)
{
if (externalId == null)
{
return null;
}
return carrierGoodsTypesByExternalId.getOrLoad(shipperId + externalId, () ->
queryBL.createQueryBuilder(I_Carrier_Goods_Type.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_ExternalId, externalId)
.firstOptional() | .map(CarrierGoodsTypeRepository::fromRecord)
.orElse(null));
}
@Nullable
public CarrierGoodsType getCachedGoodsTypeById(@Nullable final CarrierGoodsTypeId goodsTypeId)
{
if (goodsTypeId == null)
{
return null;
}
return carrierGoodsTypesById.getOrLoad(goodsTypeId.toString(), () ->
queryBL.createQueryBuilder(I_Carrier_Goods_Type.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_Carrier_Goods_Type_ID, goodsTypeId)
.firstOptional()
.map(CarrierGoodsTypeRepository::fromRecord)
.orElse(null));
}
private static CarrierGoodsType fromRecord(@NotNull final I_Carrier_Goods_Type goodsType)
{
return CarrierGoodsType.builder()
.id(CarrierGoodsTypeId.ofRepoId(goodsType.getCarrier_Goods_Type_ID()))
.externalId(goodsType.getExternalId())
.name(goodsType.getName())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierGoodsTypeRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public I_C_BPartner_Location extractShipToLocation(@NonNull final org.compiere.model.I_C_BPartner bp)
{
I_C_BPartner_Location bPartnerLocation = null;
final List<I_C_BPartner_Location> locations = bpartnersRepo.retrieveBPartnerLocations(bp);
// Set Locations
final List<I_C_BPartner_Location> shipLocations = new ArrayList<>();
boolean foundLoc = false;
for (final I_C_BPartner_Location loc : locations)
{
if (loc.isShipTo() && loc.isActive())
{
shipLocations.add(loc);
}
final org.compiere.model.I_C_BPartner_Location bpLoc = InterfaceWrapperHelper.create(loc, org.compiere.model.I_C_BPartner_Location.class);
if (bpLoc.isShipToDefault())
{
bPartnerLocation = bpLoc;
foundLoc = true;
}
}
// set first ship location if is not set
if (!foundLoc)
{
if (!shipLocations.isEmpty())
{
bPartnerLocation = shipLocations.get(0);
}
//No longer setting any location when no shipping location exists for the bpartner
}
if (!foundLoc)
{
logger.error("MOrder.setBPartner - Has no Ship To Address: {}", bp);
}
return bPartnerLocation;
}
@NonNull
@Override
public Optional<UserId> getDefaultDunningContact(@NonNull final BPartnerId bPartnerId)
{
return userRepository.getDefaultDunningContact(bPartnerId);
}
@NonNull
@Override
public Optional<VATIdentifier> getVATTaxId(@NonNull final BPartnerLocationId bpartnerLocationId)
{
final I_C_BPartner_Location bpartnerLocation = bpartnersRepo.getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
if (bpartnerLocation != null && Check.isNotBlank(bpartnerLocation.getVATaxID()))
{
return Optional.of(VATIdentifier.of(bpartnerLocation.getVATaxID()));
}
// if is set on Y, we will not use the vatid from partner
final boolean ignorePartnerVATID = sysConfigBL.getBooleanValue(SYS_CONFIG_IgnorePartnerVATID, false);
if (ignorePartnerVATID)
{
return Optional.empty();
} | else
{
final I_C_BPartner bPartner = getById(bpartnerLocationId.getBpartnerId());
if (bPartner != null && Check.isNotBlank(bPartner.getVATaxID()))
{
return Optional.of(VATIdentifier.of(bPartner.getVATaxID()));
}
}
return Optional.empty();
}
@Override
public boolean isInvoiceEmailCcToMember(@NonNull final BPartnerId bpartnerId)
{
final I_C_BPartner bpartner = getById(bpartnerId);
return bpartner.isInvoiceEmailCcToMember();
}
@Override
public I_C_BPartner_Location getBPartnerLocationByIdEvenInactive(@NonNull final BPartnerLocationId bpartnerLocationId)
{
return bpartnersRepo.getBPartnerLocationByIdEvenInactive(bpartnerLocationId);
}
@Override
public List<I_C_BPartner_Location> getBPartnerLocationsByIds(final Set<BPartnerLocationId> bpartnerLocationIds)
{
return bpartnersRepo.retrieveBPartnerLocationsByIds(bpartnerLocationIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPartnerBL.java | 2 |
请完成以下Java代码 | private Mailbox findMailboxOrNull(@NonNull final DocOutboundLogMailRecipientRequest request)
{
try
{
return mailService.findMailbox(MailboxQuery.builder()
.clientId(request.getClientId())
.orgId(request.getOrgId())
.docBaseAndSubType(extractDocBaseAndSubType(request))
.build());
}
catch (final MailboxNotFoundException e)
{
Loggables.addLog("findMailboxOrNull. DefaultDocOutboundLogMailRecipientProvider - Unable to find a mailbox for record (system-user) => return null; exception message: {}; request={}", e.getMessage(), request);
return null;
} | }
@Nullable
private DocBaseAndSubType extractDocBaseAndSubType(final DocOutboundLogMailRecipientRequest request)
{
final DocTypeId docTypeId = request.getDocTypeId();
if (docTypeId == null)
{
return null;
}
final I_C_DocType docType = docTypesRepo.getById(docTypeId);
return DocBaseAndSubType.of(docType.getDocBaseType(), docType.getDocSubType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\mailrecipient\impl\DefaultDocOutboundLogMailRecipientProvider.java | 1 |
请完成以下Java代码 | public <T> List<T> getDeployedArtifacts(Class<T> clazz) {
for (Class<?> deployedArtifactsClass : deployedArtifacts.keySet()) {
if (clazz.isAssignableFrom(deployedArtifactsClass)) {
return (List<T>) deployedArtifacts.get(deployedArtifactsClass);
}
}
return null;
}
@Override
public void addCaseDefinitionCacheEntry(String caseDefinitionId, CaseDefinitionCacheEntry caseDefinitionCacheEntry) {
caseDefinitionCache.put(caseDefinitionId, caseDefinitionCacheEntry);
}
@Override
public CaseDefinitionCacheEntry getCaseDefinitionCacheEntry(String caseDefinitionId) {
return caseDefinitionCache.get(caseDefinitionId);
}
// getters and setters ////////////////////////////////////////////////////////
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getParentDeploymentId() {
return parentDeploymentId;
}
@Override
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
} | @Override
public void setResources(Map<String, EngineResource> resources) {
this.resources = resources;
}
@Override
public Date getDeploymentTime() {
return deploymentTime;
}
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public String getDerivedFrom() {
return null;
}
@Override
public String getDerivedFromRoot() {
return null;
}
@Override
public String getEngineVersion() {
return null;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "CmmnDeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityImpl.java | 1 |
请完成以下Java代码 | public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return this.artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public List<String> getRepositories() {
return this.repositories;
}
public List<String> getAdditionalBoms() {
return this.additionalBoms;
}
public VersionRange getRange() {
return this.range;
} | public void setRepositories(List<String> repositories) {
this.repositories = repositories;
}
public void setAdditionalBoms(List<String> additionalBoms) {
this.additionalBoms = additionalBoms;
}
public void setRange(VersionRange range) {
this.range = range;
}
@Override
public String toString() {
return "Mapping ["
+ ((this.compatibilityRange != null) ? "compatibilityRange=" + this.compatibilityRange + ", " : "")
+ ((this.groupId != null) ? "groupId=" + this.groupId + ", " : "")
+ ((this.artifactId != null) ? "artifactId=" + this.artifactId + ", " : "")
+ ((this.version != null) ? "version=" + this.version + ", " : "")
+ ((this.repositories != null) ? "repositories=" + this.repositories + ", " : "")
+ ((this.additionalBoms != null) ? "additionalBoms=" + this.additionalBoms + ", " : "")
+ ((this.range != null) ? "range=" + this.range : "") + "]";
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\BillOfMaterials.java | 1 |
请完成以下Java代码 | public CostAmount divide(
@NonNull final Quantity divisor,
@NonNull final CurrencyPrecision precision)
{
return divide(divisor.toBigDecimal(), precision);
}
public Optional<CostAmount> divideIfNotZero(
@NonNull final Quantity divisor,
@NonNull final CurrencyPrecision precision)
{
return divisor.isZero() ? Optional.empty() : Optional.of(divide(divisor, precision));
}
public CostAmount round(@NonNull final Function<CurrencyId, CurrencyPrecision> precisionProvider)
{
final Money valueNew = value.round(precisionProvider);
final Money sourceValueNew = sourceValue != null ? sourceValue.round(precisionProvider) : null;
if (Money.equals(value, valueNew)
&& Money.equals(sourceValue, sourceValueNew))
{
return this;
}
else
{
return new CostAmount(valueNew, sourceValueNew);
}
}
public CostAmount roundToPrecisionIfNeeded(final CurrencyPrecision precision)
{
final Money valueRounded = value.roundIfNeeded(precision);
if (Money.equals(value, valueRounded))
{
return this;
}
else
{
return new CostAmount(valueRounded, sourceValue);
}
}
public CostAmount roundToCostingPrecisionIfNeeded(final AcctSchema acctSchema)
{
final AcctSchemaCosting acctSchemaCosting = acctSchema.getCosting();
final CurrencyPrecision precision = acctSchemaCosting.getCostingPrecision();
return roundToPrecisionIfNeeded(precision);
}
@NonNull
public CostAmount subtract(@NonNull final CostAmount amtToSubtract)
{
assertCurrencyMatching(amtToSubtract);
if (amtToSubtract.isZero())
{
return this;
}
return add(amtToSubtract.negate());
}
public CostAmount toZero()
{
if (isZero())
{
return this;
} | else
{
return new CostAmount(value.toZero(), sourceValue != null ? sourceValue.toZero() : null);
}
}
public Money toMoney()
{
return value;
}
@Nullable
public Money toSourceMoney()
{
return sourceValue;
}
public BigDecimal toBigDecimal() {return value.toBigDecimal();}
public boolean compareToEquals(@NonNull final CostAmount other)
{
return this.value.compareTo(other.value) == 0;
}
public static CurrencyId getCommonCurrencyIdOfAll(@Nullable final CostAmount... costAmounts)
{
return CurrencyId.getCommonCurrencyIdOfAll(CostAmount::getCurrencyId, "Amount", costAmounts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostAmount.java | 1 |
请完成以下Java代码 | private LookupValuesPage getShipmentScheduleValues(final LookupDataSourceContext context)
{
return createNewDefaultParametersFiller().getShipmentScheduleValues(context);
}
@Nullable
private OrderLineId getSalesOrderLineId()
{
if (getView() != null)
{
return getView().getSalesOrderLineId();
}
return null;
}
@ProcessParamLookupValuesProvider(//
parameterName = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_PickingSlot_ID, //
dependsOn = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_ShipmentSchedule_ID, //
numericKey = true, //
lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup)
private LookupValuesList getPickingSlotValues(final LookupDataSourceContext context)
{
final WEBUI_M_HU_Pick_ParametersFiller filler = WEBUI_M_HU_Pick_ParametersFiller
.pickingSlotFillerBuilder()
.shipmentScheduleId(shipmentScheduleId) | .build();
return filler.getPickingSlotValues(context);
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
invalidateView();
}
private WEBUI_M_HU_Pick_ParametersFiller createNewDefaultParametersFiller()
{
final HURow row = WEBUI_PP_Order_ProcessHelper.getHURowsFromIncludedRows(getView()).get(0);
return WEBUI_M_HU_Pick_ParametersFiller.defaultFillerBuilder()
.huId(row.getHuId())
.salesOrderLineId(getSalesOrderLineId())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Pick_ReceivedHUs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUQRCodeGenerateRequest
{
int count;
@NonNull HuPackingInstructionsId huPackingInstructionsId;
@Nullable ProductId productId;
@NonNull ImmutableList<Attribute> attributes;
@Builder
private HUQRCodeGenerateRequest(
final int count,
@Nullable final HuPackingInstructionsId huPackingInstructionsId,
@Nullable final ProductId productId,
@NonNull @Singular("_attribute") final List<Attribute> attributes)
{
Check.assumeGreaterThanZero(count, "count");
this.count = count;
this.huPackingInstructionsId = CoalesceUtil.coalesceNotNull(huPackingInstructionsId, HuPackingInstructionsId.VIRTUAL);
this.productId = productId;
this.attributes = ImmutableList.copyOf(attributes);
}
//
//
//
@SuppressWarnings("unused")
public static class HUQRCodeGenerateRequestBuilder
{
public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable String valueString)
{
return _attribute(Attribute.builder().attributeId(attributeId).valueString(valueString).build());
}
public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable BigDecimal valueNumber)
{
return _attribute(Attribute.builder().attributeId(attributeId).valueNumber(valueNumber).build());
} | public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable LocalDate valueDate)
{
return _attribute(Attribute.builder().attributeId(attributeId).valueDate(valueDate).build());
}
public HUQRCodeGenerateRequestBuilder attribute(@NonNull AttributeId attributeId, @Nullable AttributeValueId valueListId)
{
return _attribute(Attribute.builder().attributeId(attributeId).valueListId(valueListId).build());
}
public HUQRCodeGenerateRequestBuilder lotNo(@Nullable final String lotNo, @NonNull final Function<AttributeCode, AttributeId> getAttributeIdByCode)
{
final AttributeId attributeId = getAttributeIdByCode.apply(AttributeConstants.ATTR_LotNumber);
return attribute(attributeId, StringUtils.trimBlankToNull(lotNo));
}
}
//
//
//
@Value
@Builder
public static class Attribute
{
@Nullable AttributeId attributeId;
@Nullable AttributeCode code;
@Nullable String valueString;
@Nullable BigDecimal valueNumber;
@Nullable LocalDate valueDate;
@Nullable AttributeValueId valueListId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodeGenerateRequest.java | 2 |
请完成以下Java代码 | public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) { | this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", pid=").append(pid);
sb.append(", name=").append(name);
sb.append(", value=").append(value);
sb.append(", icon=").append(icon);
sb.append(", type=").append(type);
sb.append(", uri=").append(uri);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsPermission.java | 1 |
请完成以下Java代码 | public void setDateAcct (Timestamp DateAcct)
{
set_Value (COLUMNNAME_DateAcct, DateAcct);
}
/** Get Account Date.
@return Accounting Date
*/
public Timestamp getDateAcct ()
{
return (Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed) | {
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Split.java | 1 |
请完成以下Java代码 | public class PermissionAspect {
@Autowired
TokenService tokenService;
@Before("@annotation(com.heeexy.example.config.annotation.RequiresPermissions)")
public void before(JoinPoint joinPoint) {
log.debug("开始校验[操作权限]");
SessionUserInfo userInfo = tokenService.getUserInfo();
Set<String> myCodes = userInfo.getPermissionList();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
RequiresPermissions a = methodSignature.getMethod().getAnnotation(RequiresPermissions.class);
String[] perms = a.value();
log.debug("校验权限code: {}", Arrays.toString(perms));
log.debug("用户已有权限: {}", myCodes);
//5.对比[要求]的code和[用户实际拥有]的code
if (a.logical() == Logical.AND) {
//必须包含要求的每个权限
for (String perm : perms) {
if (!myCodes.contains(perm)) {
log.warn("用户缺少权限 code : {}", perm);
throw new UnauthorizedException();//抛出[权限不足]的异常
} | }
} else {
//多个权限只需包含其中一种即可
boolean flag = false;
for (String perm : perms) {
if (myCodes.contains(perm)) {
flag = true;
break;
}
}
if (!flag) {
log.warn("用户缺少权限 code= : {} (任意有一种即可)", Arrays.toString(perms));
throw new UnauthorizedException();//抛出[权限不足]的异常
}
}
}
} | repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\config\filter\PermissionAspect.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserAlbertaId implements RepoIdAware
{
@JsonCreator
public static UserAlbertaId ofRepoId(final int repoId)
{
return new UserAlbertaId(repoId);
}
@Nullable
public static UserAlbertaId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new UserAlbertaId(repoId) : null;
}
public static int toRepoId(@Nullable final UserAlbertaId userAlbertaId)
{
return userAlbertaId != null ? userAlbertaId.getRepoId() : -1;
} | int repoId;
private UserAlbertaId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_User_Alberta_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\bpartner\user\UserAlbertaId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SpringBootAdminConsulApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminConsulApplication.class, args);
}
@Profile("insecure")
@Configuration(proxyBeanMethods = false)
public static class SecurityPermitAllConfig {
private final String adminContextPath;
public SecurityPermitAllConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults()
.matcher(POST, this.adminContextPath + "/instances"),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminContextPath + "/instances/*"),
PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**")));
return http.build();
}
}
@Profile("secure")
@Configuration(proxyBeanMethods = false)
public static class SecuritySecureConfig {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
} | @Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminContextPath + "/");
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/assets/**"))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/login"))
.permitAll()
.anyRequest()
.authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login")
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout"))
.httpBasic(Customizer.withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults()
.matcher(POST, this.adminContextPath + "/instances"),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminContextPath + "/instances/*"),
PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**")));
return http.build();
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-consul\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminConsulApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ReactiveHttpClientsProperties {
/**
* Default connector used for a client HTTP request.
*/
private @Nullable Connector connector;
public @Nullable Connector getConnector() {
return this.connector;
}
public void setConnector(@Nullable Connector connector) {
this.connector = connector;
}
/**
* Supported factory types.
*/
public enum Connector {
/**
* Reactor-Netty.
*/
REACTOR(ClientHttpConnectorBuilder::reactor),
/**
* Jetty's HttpClient.
*/
JETTY(ClientHttpConnectorBuilder::jetty),
/**
* Apache HttpComponents HttpClient.
*/
HTTP_COMPONENTS(ClientHttpConnectorBuilder::httpComponents), | /**
* Java's HttpClient.
*/
JDK(ClientHttpConnectorBuilder::jdk);
private final Supplier<ClientHttpConnectorBuilder<?>> builderSupplier;
Connector(Supplier<ClientHttpConnectorBuilder<?>> builderSupplier) {
this.builderSupplier = builderSupplier;
}
ClientHttpConnectorBuilder<?> builder() {
return this.builderSupplier.get();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\reactive\ReactiveHttpClientsProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected EntityLinkServiceConfiguration getEntityLinkServiceConfiguration() {
return entityLinkServiceConfiguration;
}
protected Clock getClock() { | return getEntityLinkServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getEntityLinkServiceConfiguration().getEventDispatcher();
}
protected EntityLinkEntityManager getEntityLinkEntityManager() {
return getEntityLinkServiceConfiguration().getEntityLinkEntityManager();
}
protected HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() {
return getEntityLinkServiceConfiguration().getHistoricEntityLinkEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\AbstractManager.java | 2 |
请完成以下Java代码 | public String getName() {
return name;
}
}
@Override
public Map<String, String> initParams() {
Arrays.asList(Parameters.values()).forEach(parameter -> {
initParams.put(parameter.getName(), null);
});
return initParams;
}
@Override
public void parseParams() {
String disabled = getParameterValue(DISABLED);
if (ServletFilterUtil.isEmpty(disabled)) {
setDisabled(true);
} else {
setDisabled(Boolean.parseBoolean(disabled));
}
if (!isDisabled()) {
boolean isAnyParameterDefined =
checkAnyParameterDefined(MAX_AGE, INCLUDE_SUBDOMAINS_DISABLED);
String value = getParameterValue(VALUE);
boolean isValueParameterDefined = !ServletFilterUtil.isEmpty(value);
if (isValueParameterDefined && isAnyParameterDefined) {
String className = this.getClass().getSimpleName();
throw exceptionParametersCannotBeSet(className);
} else if (isValueParameterDefined) {
setValue(value);
} else if (isAnyParameterDefined) {
StringBuilder headerValueStringBuilder = new StringBuilder();
headerValueStringBuilder.append(VALUE_PART_MAX_AGE);
String maxAge = getParameterValue(MAX_AGE);
if (ServletFilterUtil.isEmpty(maxAge)) {
headerValueStringBuilder.append(MAX_AGE_DEFAULT_VALUE);
} else {
int maxAgeParsed = Integer.parseInt(maxAge);
headerValueStringBuilder.append(maxAgeParsed);
}
String includeSubdomainsDisabled = getParameterValue(INCLUDE_SUBDOMAINS_DISABLED);
if (!ServletFilterUtil.isEmpty(includeSubdomainsDisabled) && !Boolean.parseBoolean(includeSubdomainsDisabled)) {
headerValueStringBuilder.append(VALUE_PART_INCLUDE_SUBDOMAINS); | }
setValue(headerValueStringBuilder.toString());
} else {
setValue(VALUE_PART_MAX_AGE + MAX_AGE_DEFAULT_VALUE);
}
}
}
protected ProcessEngineException exceptionParametersCannotBeSet(String className) {
return new ProcessEngineException(className + ": cannot set " + VALUE.getName() +
" in conjunction with " + MAX_AGE.getName() + " or " +
INCLUDE_SUBDOMAINS_DISABLED.getName() + ".");
}
protected String getParameterValue(Parameters parameter) {
String parameterName = parameter.getName();
return initParams.get(parameterName);
}
protected boolean checkAnyParameterDefined(Parameters... parameters) {
for (Parameters parameter : parameters) {
String parameterValue = getParameterValue(parameter);
if (!ServletFilterUtil.isEmpty(parameterValue)) {
return true;
}
}
return false;
}
@Override
public String getHeaderName() {
return HEADER_NAME;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\StrictTransportSecurityProvider.java | 1 |
请完成以下Java代码 | public final void setDeleted()
{
deleted = Boolean.TRUE;
}
@JsonAnyGetter
private Map<String, Object> getOtherProperties()
{
return otherProperties;
}
@JsonAnySetter
private void putOtherProperty(final String name, final Object jsonValue)
{
otherProperties.put(name, jsonValue);
}
protected final JSONDocumentBase putDebugProperty(final String name, final Object jsonValue)
{
otherProperties.put("debug-" + name, jsonValue);
return this;
}
public final void setFields(final Collection<JSONDocumentField> fields)
{ | setFields(fields == null ? null : Maps.uniqueIndex(fields, JSONDocumentField::getField));
}
@JsonIgnore
protected final void setFields(final Map<String, JSONDocumentField> fieldsByName)
{
this.fieldsByName = fieldsByName;
if (unboxPasswordFields && fieldsByName != null && !fieldsByName.isEmpty())
{
fieldsByName.forEach((fieldName, field) -> field.unboxPasswordField());
}
}
@JsonIgnore
protected final int getFieldsCount()
{
return fieldsByName == null ? 0 : fieldsByName.size();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentBase.java | 1 |
请完成以下Java代码 | public class WEBUI_Picking_HUEditor_Launcher extends PickingSlotViewBasedProcess
{
private final IViewsRepository viewsRepo = SpringContextHolder.instance.getBean(IViewsRepository.class);
private final HUsToPickViewFactory husToPickViewFactory = SpringContextHolder.instance.getBean(HUsToPickViewFactory.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final IView husToPickView = createHUsToPickView();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(husToPickView.getViewId().getViewId())
.profileId("husToPick")
.target(ViewOpenTarget.IncludedView)
.build()); | return MSG_OK;
}
private IView createHUsToPickView()
{
final PickingSlotView pickingSlotsView = getPickingSlotView();
final PickingSlotRowId pickingSlotRowId = getSingleSelectedPickingSlotRow().getPickingSlotRowId();
return viewsRepo.createView(husToPickViewFactory.createViewRequest(
pickingSlotsView.getViewId(),
pickingSlotRowId,
pickingSlotsView.getCurrentShipmentScheduleId(),
getBarcodeFilterData().orElse(null)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_HUEditor_Launcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void saveData(RpMicroSubmitRecord rpMicroSubmitRecord) {
rpMicroSubmitRecord.setEditTime(new Date());
if (StringUtil.isEmpty(rpMicroSubmitRecord.getStatus())) {
rpMicroSubmitRecord.setStatus(PublicEnum.YES.name());
}
rpMicroSubmitRecordDao.insert(rpMicroSubmitRecord);
}
@Override
public Map<String, Object> microSubmit(RpMicroSubmitRecord rpMicroSubmitRecord) {
rpMicroSubmitRecord.setBusinessCode(StringUtil.get32UUID());
rpMicroSubmitRecord.setIdCardValidTime("[\"" + rpMicroSubmitRecord.getIdCardValidTimeBegin() + "\",\"" + rpMicroSubmitRecord.getIdCardValidTimeEnd() + "\"]");
Map<String, Object> returnMap = WeiXinMicroUtils.microSubmit(rpMicroSubmitRecord);
rpMicroSubmitRecord.setStoreStreet(WxCityNo.getCityNameByNo(rpMicroSubmitRecord.getStoreAddressCode()) + ":" + rpMicroSubmitRecord.getStoreStreet());
if ("SUCCESS".equals(returnMap.get("result_code"))) {
saveData(rpMicroSubmitRecord);
}
return returnMap;
} | @Override
public Map<String, Object> microQuery(String businessCode) {
Map<String, Object> returnMap = WeiXinMicroUtils.microQuery(businessCode);
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("businessCode", businessCode);
RpMicroSubmitRecord rpMicroSubmitRecord = rpMicroSubmitRecordDao.getBy(paramMap);
if (StringUtil.isNotNull(returnMap.get("sub_mch_id")) && StringUtil.isEmpty(rpMicroSubmitRecord.getSubMchId())) {
rpMicroSubmitRecord.setSubMchId(String.valueOf(returnMap.get("sub_mch_id")));
rpMicroSubmitRecordDao.update(rpMicroSubmitRecord);
}
return returnMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\service\impl\RpMicroSubmitRecordServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) { | this.scopeDefinitionId = scopeDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryResponse.java | 2 |
请完成以下Java代码 | public int getM_Demand_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Demand Line.
@param M_DemandLine_ID
Material Demand Line
*/
public void setM_DemandLine_ID (int M_DemandLine_ID)
{
if (M_DemandLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DemandLine_ID, Integer.valueOf(M_DemandLine_ID));
}
/** Get Demand Line.
@return Material Demand Line
*/
public int getM_DemandLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DemandLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Calculated Quantity.
@param QtyCalculated
Calculated Quantity
*/
public void setQtyCalculated (BigDecimal QtyCalculated)
{
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated);
}
/** Get Calculated Quantity.
@return Calculated Quantity
*/
public BigDecimal getQtyCalculated ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyCalculated);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DemandLine.java | 1 |
请完成以下Java代码 | public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
} | public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
} | repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\quarkus-project\src\main\java\com\baeldung\quarkus_project\ZipCode.java | 1 |
请完成以下Java代码 | public String[] getTenantIds() {
return tenantIds;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public HistoricBatchQuery withoutTenantId() {
this.tenantIds = null;
isTenantIdSet = true;
return this;
}
public String getType() {
return type;
}
public HistoricBatchQuery orderById() {
return orderBy(HistoricBatchQueryProperty.ID);
}
public HistoricBatchQuery orderByStartTime() {
return orderBy(HistoricBatchQueryProperty.START_TIME);
}
public HistoricBatchQuery orderByEndTime() {
return orderBy(HistoricBatchQueryProperty.END_TIME);
}
@Override
public HistoricBatchQuery orderByTenantId() { | return orderBy(HistoricBatchQueryProperty.TENANT_ID);
}
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getHistoricBatchManager()
.findBatchCountByQueryCriteria(this);
}
@Override
public List<HistoricBatch> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getHistoricBatchManager()
.findBatchesByQueryCriteria(this, page);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\history\HistoricBatchQueryImpl.java | 1 |
请完成以下Java代码 | public String getOperateNote() {
return operateNote;
}
public void setOperateNote(String operateNote) {
this.operateNote = operateNote;
}
public Integer getSourceType() {
return sourceType;
}
public void setSourceType(Integer sourceType) {
this.sourceType = sourceType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", createTime=").append(createTime);
sb.append(", changeType=").append(changeType);
sb.append(", changeCount=").append(changeCount);
sb.append(", operateMan=").append(operateMan);
sb.append(", operateNote=").append(operateNote);
sb.append(", sourceType=").append(sourceType);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsGrowthChangeHistory.java | 1 |
请完成以下Java代码 | public class Doc_Order extends Doc<DocLine_Order>
{
public Doc_Order(final AcctDocContext ctx)
{
super(ctx);
}
@Override
protected void loadDocumentDetails()
{
}
@Override
public BigDecimal getBalance()
{
return BigDecimal.ZERO;
}
@Override
protected void checkConvertible(final AcctSchema acctSchema)
{
// since we are creating no acct facts there is no point to check
// if the document's currency can be converted to accounting currency
}
@Override
public List<Fact> createFacts(final AcctSchema as) | {
return ImmutableList.of();
}
private I_C_Order getOrder()
{
return getModel(I_C_Order.class);
}
@Nullable
@Override
protected OrderId getSalesOrderId()
{
final I_C_Order order = getOrder();
return order.isSOTrx() ? OrderId.ofRepoId(order.getC_Order_ID()) : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Order.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductCategoriesRestController
{
private static final Logger logger = LogManager.getLogger(ProductCategoriesRestController.class);
private final ProductsServicesFacade productsServicesFacade;
public ProductCategoriesRestController(@NonNull final ProductsServicesFacade productsServicesFacade)
{
this.productsServicesFacade = productsServicesFacade;
}
@GetMapping
public ResponseEntity<JsonGetProductCategoriesResponse> getProductCategories()
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
try
{
final JsonGetProductCategoriesResponse response = GetProductCategoriesCommand.builder()
.servicesFacade(productsServicesFacade) | .adLanguage(adLanguage)
.execute();
return ResponseEntity.ok(response);
}
catch (final Exception ex)
{
logger.debug("Got exception", ex);
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(JsonGetProductCategoriesResponse.error(ex, adLanguage));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\product\ProductCategoriesRestController.java | 2 |
请完成以下Java代码 | public static void main(String... args) throws Exception {
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
try (SseEventSource eventSource = SseEventSource.target(target).build()) {
eventSource.register(onEvent, onError, onComplete);
eventSource.open();
//Consuming events for one hour
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
client.close();
System.out.println("End");
} | // A new event is received
private static Consumer<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
} | repos\tutorials-master\apache-cxf-modules\sse-jaxrs\sse-jaxrs-client\src\main\java\com\baeldung\sse\jaxrs\client\SseClientApp.java | 1 |
请完成以下Java代码 | protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
// Invalidate views
getPickingSlotsClearingView().invalidateAll();
getPackingHUsView().invalidateAll();
}
private BigDecimal getQtyCUsPerTU()
{
if (isAllQty)
{
return getSingleSelectedPickingSlotRow().getHuQtyCU();
}
else
{
final BigDecimal qtyCU = this.qtyCUsPerTU;
if (qtyCU == null || qtyCU.signum() <= 0)
{
throw new FillMandatoryException(PARAM_QtyCUsPerTU);
}
return qtyCU;
} | }
private List<I_M_HU> getSourceCUs()
{
return getSelectedPickingSlotRows()
.stream()
.peek(huRow -> Check.assume(huRow.isCU(), "row {} shall be a CU", huRow))
.map(PickingSlotRow::getHuId)
.distinct()
.map(huId -> load(huId, I_M_HU.class))
.collect(ImmutableList.toImmutableList());
}
private I_M_HU getTargetTU()
{
final HUEditorRow huRow = getSingleSelectedPackingHUsRow();
Check.assume(huRow.isTU(), "row {} shall be a TU", huRow);
return huRow.getM_HU();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutCUsAndAddToTU.java | 1 |
请完成以下Java代码 | public String getDecisionId() {
return decisionId;
}
public void setDecisionId(String decisionId) {
this.decisionId = decisionId;
}
public int getDecisionVersion() {
return decisionVersion;
}
public void setDecisionVersion(int decisionVersion) {
this.decisionVersion = decisionVersion;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public String getTenantId() {
return tenantId; | }
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) {
this.fallbackToDefaultTenant = fallbackToDefaultTenant;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
public boolean isDisableHistory() {
return disableHistory;
}
public void setDisableHistory(boolean disableHistory) {
this.disableHistory = disableHistory;
}
public DmnElement getDmnElement() {
return dmnElement;
}
public void setDmnElement(DmnElement dmnElement) {
this.dmnElement = dmnElement;
}
public DecisionExecutionAuditContainer getDecisionExecution() {
return decisionExecution;
}
public void setDecisionExecution(DecisionExecutionAuditContainer decisionExecution) {
this.decisionExecution = decisionExecution;
}
} | repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\ExecuteDecisionContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InstanceRegistry {
private final InstanceRepository repository;
private final InstanceIdGenerator generator;
private final InstanceFilter filter;
public InstanceRegistry(InstanceRepository repository, InstanceIdGenerator generator, InstanceFilter filter) {
this.repository = repository;
this.generator = generator;
this.filter = filter;
}
/**
* Register instance.
* @param registration instance to be registered.
* @return the id of the registered instance.
*/
public Mono<InstanceId> register(Registration registration) {
Assert.notNull(registration, "'registration' must not be null");
InstanceId id = generator.generateId(registration);
Assert.notNull(id, "'id' must not be null");
return repository.compute(id, (key, instance) -> {
if (instance == null) {
instance = Instance.create(key);
}
return Mono.just(instance.register(registration));
}).map(Instance::getId);
}
/**
* Get a list of all registered instances that satisfy the filter.
* @return list of all instances satisfying the filter.
*/
public Flux<Instance> getInstances() {
return repository.findAll().filter(filter::filter); | }
/**
* Get a list of all registered application instances that satisfy the filter.
* @param name the name to search for.
* @return list of instances for the given application that satisfy the filter.
*/
public Flux<Instance> getInstances(String name) {
return repository.findByName(name).filter(filter::filter);
}
/**
* Get a specific instance
* @param id the id
* @return a Mono with the Instance.
*/
public Mono<Instance> getInstance(InstanceId id) {
return repository.find(id).filter(filter::filter);
}
/**
* Remove a specific instance from services
* @param id the instances id to unregister
* @return the id of the unregistered instance
*/
public Mono<InstanceId> deregister(InstanceId id) {
return repository.computeIfPresent(id, (key, instance) -> Mono.just(instance.deregister()))
.map(Instance::getId);
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\InstanceRegistry.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Logbook chunkSink() {
Logbook logbook = Logbook.builder()
.sink(new ChunkingSink(new CommonsLogFormatSink(new DefaultHttpLogWriter()), 1000))
.build();
return logbook;
}
//@Bean
public Logbook compositesink() {
CompositeSink comsink = new CompositeSink(Arrays.asList(new CommonsLogFormatSink(new DefaultHttpLogWriter()), new ExtendedLogFormatSink(
new DefaultHttpLogWriter())));
Logbook logbook = Logbook.builder()
.sink(comsink)
.build();
return logbook;
}
// to run logstash example set spring.profiles.active=logbooklogstash in application.properties and enable following bean disabling all others
//@Bean
public Logbook logstashsink() {
HttpLogFormatter formatter = new JsonHttpLogFormatter();
LogstashLogbackSink logstashsink = new LogstashLogbackSink(formatter, Level.INFO);
Logbook logbook = Logbook.builder() | .sink(logstashsink)
.build();
return logbook;
}
//@Bean
public Logbook commonLogFormat() {
Logbook logbook = Logbook.builder()
.sink(new CommonsLogFormatSink(new DefaultHttpLogWriter()))
.build();
return logbook;
}
//@Bean
public Logbook extendedLogFormat() {
Logbook logbook = Logbook.builder()
.sink(new ExtendedLogFormatSink(new DefaultHttpLogWriter()))
.build();
return logbook;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-logging-logback\src\main\java\com\baeldung\logbookconfig\LogBookConfig.java | 2 |
请完成以下Java代码 | public class UmsRole implements Serializable {
private Long id;
@ApiModelProperty(value = "名称")
private String name;
@ApiModelProperty(value = "描述")
private String description;
@ApiModelProperty(value = "后台用户数量")
private Integer adminCount;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "启用状态:0->禁用;1->启用")
private Integer status;
private Integer sort;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getAdminCount() {
return adminCount;
}
public void setAdminCount(Integer adminCount) {
this.adminCount = adminCount;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) { | this.status = status;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", description=").append(description);
sb.append(", adminCount=").append(adminCount);
sb.append(", createTime=").append(createTime);
sb.append(", status=").append(status);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsRole.java | 1 |
请完成以下Java代码 | public static void main(final String[] arguments) {
final BuilderMethods simple1 = new BuilderMethods(1, "The First One");
System.out.println(simple1.getName());
System.out.println(simple1.hashCode());
System.out.println(simple1.toString());
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
try {
sampleLazyInitializer.get();
} catch (ConcurrentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
sampleBackgroundInitializer.start();
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
try { | Object result = sampleBackgroundInitializer.get();
} catch (ConcurrentException e) {
e.printStackTrace();
}
}
}
class SampleBackgroundInitializer extends BackgroundInitializer<String> {
@Override
protected String initialize() throws Exception {
return null;
}
// Any complex task that takes some time
} | repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\lang3\BuilderMethods.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Binding demo05Binding() {
return BindingBuilder.bind(demo05Queue()).to(demo05Exchange()).with(Demo05Message.ROUTING_KEY);
}
}
@Bean
public BatchingRabbitTemplate batchRabbitTemplate(ConnectionFactory connectionFactory) {
// 创建 BatchingStrategy 对象,代表批量策略
int batchSize = 16384; // 超过收集的消息数量的最大条数。
int bufferLimit = 33554432; // 每次批量发送消息的最大内存
int timeout = 30000; // 超过收集的时间的最大等待时长,单位:毫秒
BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(batchSize, bufferLimit, timeout);
// 创建 TaskScheduler 对象,用于实现超时发送的定时器
TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
// 创建 BatchingRabbitTemplate 对象
BatchingRabbitTemplate batchTemplate = new BatchingRabbitTemplate(batchingStrategy, taskScheduler);
batchTemplate.setConnectionFactory(connectionFactory); | return batchTemplate;
}
@Bean(name = "consumerBatchContainerFactory")
public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory(
SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
// 创建 SimpleRabbitListenerContainerFactory 对象
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
// 额外添加批量消费的属性
factory.setBatchListener(true);
return factory;
}
} | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo-batch-consume\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\config\RabbitConfig.java | 2 |
请完成以下Java代码 | public static String toString(JSONObject jo) throws JSONException {
StringBuilder sb = new StringBuilder();
Object e;
int i;
JSONArray ja;
String k;
Iterator keys;
int len;
String tagName;
String v;
// Emit <tagName
tagName = jo.optString("tagName");
if (tagName == null) {
return XML.escape(jo.toString());
}
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
// Emit the attributes
keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
if (!k.equals("tagName") && !k.equals("childNodes")) {
XML.noSpace(k);
v = jo.optString(k);
if (v != null) {
sb.append(' ');
sb.append(XML.escape(k));
sb.append('=');
sb.append('"');
sb.append(XML.escape(v));
sb.append('"');
} | }
}
// Emit content in body
ja = jo.optJSONArray("childNodes");
if (ja == null) {
sb.append('/');
sb.append('>');
} else {
sb.append('>');
len = ja.length();
for (i = 0; i < len; i += 1) {
e = ja.get(i);
if (e != null) {
if (e instanceof String) {
sb.append(XML.escape(e.toString()));
} else if (e instanceof JSONObject) {
sb.append(toString((JSONObject) e));
} else if (e instanceof JSONArray) {
sb.append(toString((JSONArray) e));
}
}
}
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONML.java | 1 |
请完成以下Java代码 | public List<? extends Future<?>> sendNotification(Notification notification) {
String message;
if (StringUtils.isEmpty(messagePrefix)) {
message = notification.getText();
} else {
message = messagePrefix + " " + notification.getText();
}
return notificationChannels.stream().map(notificationChannel ->
notificationExecutor.submit(() -> {
try {
notificationChannel.sendNotification(message);
} catch (Exception e) {
log.error("Failed to send notification to {}", notificationChannel.getClass().getSimpleName(), e);
}
})
).toList();
} | @PreDestroy
public void shutdownExecutor() {
try {
notificationExecutor.shutdown();
if (!notificationExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
var dropped = notificationExecutor.shutdownNow();
log.warn("Notification executor did not terminate in time. Forced shutdown; {} task(s) will not be executed.", dropped.size());
}
} catch (InterruptedException e) {
var dropped = notificationExecutor.shutdownNow();
Thread.currentThread().interrupt();
log.warn("Interrupted during notification executor shutdown. Forced shutdown; {} task(s) will not be executed.", dropped.size());
} catch (Exception e) {
log.warn("Unexpected error while shutting down notification executor", e);
}
}
} | repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\notification\NotificationService.java | 1 |
请完成以下Java代码 | private Set<ProductId> retrieveSelectedProductIDs()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
final ImmutableList<PPOrderLineRow> selectedRows = getView()
.streamByIds(selectedRowIds)
.collect(ImmutableList.toImmutableList());
final Set<ProductId> productIds = new HashSet<>();
for (final PPOrderLineRow row : selectedRows)
{
productIds.add(row.getProductId());
}
return productIds;
}
private ReportResult printLabel()
{
final PInstanceRequest pinstanceRequest = createPInstanceRequest();
final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder()
.setCtx(getCtx())
.setProcessCalledFrom(ProcessCalledFrom.WebUI)
.setAD_Process_ID(getPrintFormat().getReportProcessId())
.setAD_PInstance(adPInstanceDAO.getById(pinstanceId))
.setReportLanguage(getProcessInfo().getReportLanguage())
.setJRDesiredOutputType(OutputType.PDF)
.build();
final ReportsClient reportsClient = ReportsClient.get();
return reportsClient.report(jasperProcessInfo);
}
private PInstanceRequest createPInstanceRequest()
{
return PInstanceRequest.builder()
.processId(getPrintFormat().getReportProcessId())
.processParams(ImmutableList.of(
ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId()), | ProcessInfoParameter.of("AD_PrintFormat_ID", printFormatId)))
.build();
}
private String buildFilename()
{
final String instance = String.valueOf(getPinstanceId().getRepoId());
final String title = getProcessInfo().getTitle();
return Joiner.on("_").skipNulls().join(instance, title) + ".pdf";
}
private PrintFormat getPrintFormat()
{
return pfRepo.getById(PrintFormatId.ofRepoId(printFormatId));
}
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (Objects.equals(I_M_Product.COLUMNNAME_M_Product_ID, parameter.getColumnName()))
{
return retrieveSelectedProductIDs().stream().findFirst().orElse(null);
}
return DEFAULT_VALUE_NOTAVAILABLE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_PrintLabel.java | 1 |
请完成以下Java代码 | public String docValidate(final PO po, final int timing)
{
// nothing
return null;
}
private void registerInstanceValidator(final I_C_ReferenceNo_Type type)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(type);
final IReferenceNoGeneratorInstance instance = Services.get(IReferenceNoBL.class).getReferenceNoGeneratorInstance(ctx, type);
if (instance == null)
{
return;
}
final ReferenceNoGeneratorInstanceValidator validator = new ReferenceNoGeneratorInstanceValidator(instance);
engine.addModelValidator(validator);
docValidators.add(validator);
}
private void unregisterInstanceValidator(final I_C_ReferenceNo_Type type)
{
final Iterator<ReferenceNoGeneratorInstanceValidator> it = docValidators.iterator();
while (it.hasNext())
{ | final ReferenceNoGeneratorInstanceValidator validator = it.next();
if (validator.getInstance().getType().getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID())
{
validator.unregister();
it.remove();
}
}
}
public void updateInstanceValidator(final I_C_ReferenceNo_Type type)
{
unregisterInstanceValidator(type);
registerInstanceValidator(type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\Main.java | 1 |
请完成以下Java代码 | public class RuecknahmeangebotAntwort {
@XmlElement(name = "ReferenzId", required = true)
protected String referenzId;
@XmlAttribute(name = "Id", required = true)
protected String id;
/**
* Gets the value of the referenzId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReferenzId() {
return referenzId;
}
/**
* Sets the value of the referenzId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenzId(String value) {
this.referenzId = value;
}
/**
* Gets the value of the id property. | *
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\RuecknahmeangebotAntwort.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getKeyStore() {
return keyStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getKeyPassword() {
return keyPassword;
}
public void setKeyPassword(String keyPassword) {
this.keyPassword = keyPassword;
}
public List<String> getTrustedX509Certificates() {
return trustedX509Certificates;
}
public void setTrustedX509Certificates(List<String> trustedX509) {
this.trustedX509Certificates = trustedX509;
}
public boolean isUseInsecureTrustManager() {
return useInsecureTrustManager;
}
public void setUseInsecureTrustManager(boolean useInsecureTrustManager) {
this.useInsecureTrustManager = useInsecureTrustManager;
}
public Duration getHandshakeTimeout() {
return handshakeTimeout;
}
public void setHandshakeTimeout(Duration handshakeTimeout) {
this.handshakeTimeout = handshakeTimeout;
}
public Duration getCloseNotifyFlushTimeout() {
return closeNotifyFlushTimeout;
}
public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) {
this.closeNotifyFlushTimeout = closeNotifyFlushTimeout;
}
public Duration getCloseNotifyReadTimeout() {
return closeNotifyReadTimeout;
}
public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) {
this.closeNotifyReadTimeout = closeNotifyReadTimeout;
}
public String getSslBundle() {
return sslBundle;
}
public void setSslBundle(String sslBundle) {
this.sslBundle = sslBundle;
}
@Override | public String toString() {
return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager)
.append("trustedX509Certificates", trustedX509Certificates)
.append("handshakeTimeout", handshakeTimeout)
.append("closeNotifyFlushTimeout", closeNotifyFlushTimeout)
.append("closeNotifyReadTimeout", closeNotifyReadTimeout)
.toString();
}
}
public static class Websocket {
/** Max frame payload length. */
private Integer maxFramePayloadLength;
/** Proxy ping frames to downstream services, defaults to true. */
private boolean proxyPing = true;
public Integer getMaxFramePayloadLength() {
return this.maxFramePayloadLength;
}
public void setMaxFramePayloadLength(Integer maxFramePayloadLength) {
this.maxFramePayloadLength = maxFramePayloadLength;
}
public boolean isProxyPing() {
return proxyPing;
}
public void setProxyPing(boolean proxyPing) {
this.proxyPing = proxyPing;
}
@Override
public String toString() {
return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength)
.append("proxyPing", proxyPing)
.toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java | 2 |
请完成以下Java代码 | public JsonProcessHealthResponse healthCheck(
@RequestParam(name = "adProcessIds", required = false) final String onlyAdProcesIdsCommaSeparated
)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
final ImmutableSet<AdProcessId> onlyAdProcessIds = RepoIdAwares.ofCommaSeparatedSet(onlyAdProcesIdsCommaSeparated, AdProcessId.class);
final ImmutableSet<AdProcessId> allAdProcessIds = adProcessDAO.retrieveAllActiveAdProcesIds();
final ImmutableSet<AdProcessId> adProcesIds = !onlyAdProcessIds.isEmpty() ? onlyAdProcessIds : allAdProcessIds;
final ArrayList<JsonProcessHealthResponse.Entry> errors = new ArrayList<>();
final int countTotal = adProcesIds.size();
int countCurrent = 0;
final Stopwatch stopwatch = Stopwatch.createStarted();
for (final AdProcessId adProcessId : adProcesIds)
{
countCurrent++;
final ProcessId processId = ProcessId.ofAD_Process_ID(adProcessId);
try
{
if (!allAdProcessIds.contains(adProcessId))
{
throw new AdempiereException("Not an existing/active process");
}
final IProcessInstancesRepository repository = getRepository(processId);
repository.cacheReset();
final ProcessDescriptor processDescriptor = repository.getProcessDescriptor(processId);
// Try loading & instantiating the process class if any
if (processDescriptor.getProcessClassname() != null)
{
ProcessInfo.newProcessClassInstance(processDescriptor.getProcessClassname());
} | repository.cacheReset();
logger.info("healthCheck [{}/{}] Process {} is OK", countCurrent, countTotal, processId);
}
catch (final Exception ex)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
final I_AD_Process adProcess = adProcessDAO.getById(adProcessId);
final String processValue = adProcess != null ? adProcess.getValue() : "?";
final String processName = adProcess != null ? adProcess.getName() : "?";
final String processClassname = adProcess != null ? adProcess.getClassname() : "?";
logger.info("healthCheck [{}/{}] Process {}_{} ({}) is NOK: {}", countCurrent, countTotal, processValue, processName, processId, ex.getLocalizedMessage());
final Throwable cause = DocumentLayoutBuildException.extractCause(ex);
errors.add(JsonProcessHealthResponse.Entry.builder()
.processId(processId)
.value(processValue)
.name(processName)
.classname(processClassname)
.error(JsonErrors.ofThrowable(cause, adLanguage))
.build());
}
}
stopwatch.stop();
return JsonProcessHealthResponse.builder()
.countTotal(countTotal)
.countErrors(errors.size())
.took(stopwatch.toString())
.errors(errors)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessRestController.java | 1 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class);
}
@Override
public void setC_BPartner_Location(org.compiere.model.I_C_BPartner_Location C_BPartner_Location)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_Location_ID, org.compiere.model.I_C_BPartner_Location.class, C_BPartner_Location);
}
/** Set Partner Location.
@param C_BPartner_Location_ID
Identifies the (ship to) address for this Business Partner
*/
@Override
public void setC_BPartner_Location_ID (int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID));
}
/** Get Partner Location.
@return Identifies the (ship to) address for this Business Partner
*/
@Override
public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Recurrent Payment.
@param C_RecurrentPayment_ID Recurrent Payment */
@Override
public void setC_RecurrentPayment_ID (int C_RecurrentPayment_ID)
{
if (C_RecurrentPayment_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RecurrentPayment_ID, Integer.valueOf(C_RecurrentPayment_ID));
}
/** Get Recurrent Payment.
@return Recurrent Payment */
@Override
public int getC_RecurrentPayment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RecurrentPayment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPayment.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return executionEntity.getProcessDefinitionId();
}
@Override
public String getBusinessKey() {
return executionEntity.getBusinessKey();
}
@Override
public String getCaseInstanceId() {
return executionEntity.getCaseInstanceId();
}
@Override
public boolean isSuspended() {
return executionEntity.isSuspended();
}
@Override
public String getId() {
return executionEntity.getId();
}
@Override
public String getRootProcessInstanceId() {
return executionEntity.getRootProcessInstanceId(); | }
@Override
public boolean isEnded() {
return executionEntity.isEnded();
}
@Override
public String getProcessInstanceId() {
return executionEntity.getProcessInstanceId();
}
@Override
public String getTenantId() {
return executionEntity.getTenantId();
}
@Override
public String getProcessDefinitionKey() {
return executionEntity.getProcessDefinitionKey();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessInstanceWithVariablesImpl.java | 1 |
请完成以下Java代码 | public class QrCodeSettings extends BaseData<QrCodeSettingsId> implements HasTenantId {
private static final long serialVersionUID = 2628323657987010348L;
@Schema(description = "JSON object with Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY)
private TenantId tenantId;
@Schema(description = "Use settings from system level", example = "true")
private boolean useSystemSettings;
@Schema(description = "Type of application: true means use default Thingsboard app", example = "true")
private boolean useDefaultApp;
@Schema(description = "Mobile app bundle.")
private MobileAppBundleId mobileAppBundleId;
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "QR code config configuration.")
@Valid
@NotNull
private QRCodeConfig qrCodeConfig;
@Schema(description = "Indicates if google play link is available", example = "true")
private boolean androidEnabled; | @Schema(description = "Indicates if apple store link is available", example = "true")
private boolean iosEnabled;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String googlePlayLink;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private String appStoreLink;
public QrCodeSettings() {
}
public QrCodeSettings(QrCodeSettingsId id) {
super(id);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\mobile\qrCodeSettings\QrCodeSettings.java | 1 |
请完成以下Spring Boot application配置 | server.port=8080
spring.redis.database=1
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.poo | l.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=500
test.value=???? | repos\spring-boot-quick-master\quick-container\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | private void init() {
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();
cluster = CouchbaseCluster.create(env, "localhost");
}
@Override
synchronized public Bucket openBucket(String name, String password) {
if (!buckets.containsKey(name)) {
Bucket bucket = cluster.openBucket(name, password);
buckets.put(name, bucket);
}
return buckets.get(name);
}
@Override
public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) {
List<JsonDocument> docs = new ArrayList<>();
for (String key : keys) {
JsonDocument doc = bucket.get(key);
if (doc != null) {
docs.add(doc);
}
}
return docs;
}
@Override
public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) {
Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() {
public Observable<JsonDocument> call(String key) {
return asyncBucket.get(key);
} | });
final List<JsonDocument> docs = new ArrayList<>();
try {
asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() {
public void call(JsonDocument doc) {
docs.add(doc);
}
});
} catch (Exception e) {
logger.error("Error during bulk get", e);
}
return docs;
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\spring\service\ClusterServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String sendMsg(String msg) {
String msgId = IdUtil.simpleUUID();
msgMap.put(msgId, msg);
return msgId;
}
/**
* conversation
* @param msgId mapper with sendmsg
* @return
*/
@GetMapping(value = "/conversation/{msgId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter conversation(@PathVariable("msgId") String msgId) {
SseEmitter emitter = new SseEmitter();
String msg = msgMap.remove(msgId);
//mock chatgpt response
new Thread(() -> { | try {
for (int i = 0; i < 10; i++) {
ChatMessage chatMessage = new ChatMessage("test", new String(i+""));
emitter.send(chatMessage);
Thread.sleep(1000);
}
emitter.send(SseEmitter.event().name("stop").data(""));
emitter.complete(); // close connection
} catch (IOException | InterruptedException e) {
emitter.completeWithError(e); // error finish
}
}).start();
return emitter;
}
} | repos\springboot-demo-master\sse\src\main\java\com\et\sse\controller\ChatController.java | 2 |
请完成以下Java代码 | public void reportSent(NotificationDeliveryMethod deliveryMethod, NotificationRecipient recipient) {
sent.computeIfAbsent(deliveryMethod, k -> new AtomicInteger()).incrementAndGet();
totalSent.incrementAndGet();
}
public void reportError(NotificationDeliveryMethod deliveryMethod, Throwable error, NotificationRecipient recipient) {
if (error instanceof AlreadySentException) {
return;
}
String errorMessage = error.getMessage();
if (errorMessage == null) {
errorMessage = error.getClass().getSimpleName();
}
Map<String, String> errors = this.errors.computeIfAbsent(deliveryMethod, k -> new ConcurrentHashMap<>());
if (errors.size() < 100) { | errors.put(recipient.getTitle(), errorMessage);
}
totalErrors.incrementAndGet();
}
public void reportProcessed(NotificationDeliveryMethod deliveryMethod, Object recipientId) {
processedRecipients.computeIfAbsent(deliveryMethod, k -> ConcurrentHashMap.newKeySet()).add(recipientId);
}
public boolean contains(NotificationDeliveryMethod deliveryMethod, Object recipientId) {
Set<Object> processedRecipients = this.processedRecipients.get(deliveryMethod);
return processedRecipients != null && processedRecipients.contains(recipientId);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\NotificationRequestStats.java | 1 |
请完成以下Java代码 | public class SysFilesModel {
/**主键id*/
private String id;
/**文件名称*/
private String fileName;
/**文件地址*/
private String url;
/**文档类型(folder:文件夹 excel:excel doc:word pp:ppt image:图片 archive:其他文档 video:视频)*/
private String fileType;
/**文件上传类型(temp/本地上传(临时文件) manage/知识库)*/
private String storeType;
/**文件大小(kb)*/
private Double fileSize;
/**租户id*/
private String tenantId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getStoreType() { | return storeType;
}
public void setStoreType(String storeType) {
this.storeType = storeType;
}
public Double getFileSize() {
return fileSize;
}
public void setFileSize(Double fileSize) {
this.fileSize = fileSize;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysFilesModel.java | 1 |
请完成以下Java代码 | public class ApplicationServer {
private ServerSocket serverSocket;
private Socket connectedSocket;
private PrintWriter out;
private BufferedReader in;
public void startServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
connectedSocket = serverSocket.accept();
InetSocketAddress socketAddress = (InetSocketAddress) connectedSocket.getRemoteSocketAddress();
String clientIpAddress = socketAddress.getAddress()
.getHostAddress();
System.out.println("IP address of the connected client :: " + clientIpAddress);
out = new PrintWriter(connectedSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(connectedSocket.getInputStream()));
String msg = in.readLine();
System.out.println("Message received from the client :: " + msg);
out.println("Hello Client !!");
closeIO();
stopServer();
} | private void closeIO() throws IOException {
in.close();
out.close();
}
private void stopServer() throws IOException {
connectedSocket.close();
serverSocket.close();
}
public static void main(String[] args) throws IOException {
ApplicationServer server = new ApplicationServer();
server.startServer(5000);
}
} | repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\clientaddress\ApplicationServer.java | 1 |
请完成以下Java代码 | public ResponseEntity<Object> deleteDeploy(@RequestBody Set<Long> ids){
deployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("上传文件部署")
@ApiOperation(value = "上传文件部署")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> uploadDeploy(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
Long id = Long.valueOf(request.getParameter("id"));
String fileName = "";
if(file != null){
fileName = FileUtil.verifyFilename(file.getOriginalFilename());
File deployFile = new File(fileSavePath + fileName);
FileUtil.del(deployFile);
file.transferTo(deployFile);
//文件下一步要根据文件名字来
deployService.deploy(fileSavePath + fileName ,id);
}else{
log.warn("没有找到相对应的文件");
}
Map<String,Object> map = new HashMap<>(2);
map.put("error",0);
map.put("id",fileName);
return new ResponseEntity<>(map,HttpStatus.OK);
}
@Log("系统还原")
@ApiOperation(value = "系统还原")
@PostMapping(value = "/serverReduction")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources){
String result = deployService.serverReduction(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("服务运行状态")
@ApiOperation(value = "服务运行状态")
@PostMapping(value = "/serverStatus")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources){ | String result = deployService.serverStatus(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("启动服务")
@ApiOperation(value = "启动服务")
@PostMapping(value = "/startServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources){
String result = deployService.startServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("停止服务")
@ApiOperation(value = "停止服务")
@PostMapping(value = "/stopServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources){
String result = deployService.stopServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\DeployController.java | 1 |
请完成以下Java代码 | public boolean isOr() {
return or;
}
public void setOr(boolean or) {
this.or = or;
}
public boolean isOrAlphabetic() {
return orAlphabetic;
}
public void setOrAlphabetic(boolean orAlphabetic) {
this.orAlphabetic = orAlphabetic;
}
public boolean isNot() {
return not;
}
public void setNot(boolean not) {
this.not = not;
}
public boolean isNotAlphabetic() {
return notAlphabetic;
}
public void setNotAlphabetic(boolean notAlphabetic) { | this.notAlphabetic = notAlphabetic;
}
@Override
public String toString() {
return "SpelLogical{" +
"and=" + and +
", andAlphabetic=" + andAlphabetic +
", or=" + or +
", orAlphabetic=" + orAlphabetic +
", not=" + not +
", notAlphabetic=" + notAlphabetic +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelLogical.java | 1 |
请完成以下Java代码 | public boolean isUseAd ()
{
Object oo = get_Value(COLUMNNAME_IsUseAd);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Valid.
@param IsValid
Element is valid
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Valid.
@return Element is valid
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{ | Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set TemplateXST.
@param TemplateXST
Contains the template code itself
*/
public void setTemplateXST (String TemplateXST)
{
set_Value (COLUMNNAME_TemplateXST, TemplateXST);
}
/** Get TemplateXST.
@return Contains the template code itself
*/
public String getTemplateXST ()
{
return (String)get_Value(COLUMNNAME_TemplateXST);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Template.java | 1 |
请完成以下Java代码 | public Integer getCollectCommentCount() {
return collectCommentCount;
}
public void setCollectCommentCount(Integer collectCommentCount) {
this.collectCommentCount = collectCommentCount;
}
public Integer getInviteFriendCount() {
return inviteFriendCount;
}
public void setInviteFriendCount(Integer inviteFriendCount) {
this.inviteFriendCount = inviteFriendCount;
}
public Date getRecentOrderTime() {
return recentOrderTime;
}
public void setRecentOrderTime(Date recentOrderTime) {
this.recentOrderTime = recentOrderTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()); | sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", consumeAmount=").append(consumeAmount);
sb.append(", orderCount=").append(orderCount);
sb.append(", couponCount=").append(couponCount);
sb.append(", commentCount=").append(commentCount);
sb.append(", returnOrderCount=").append(returnOrderCount);
sb.append(", loginCount=").append(loginCount);
sb.append(", attendCount=").append(attendCount);
sb.append(", fansCount=").append(fansCount);
sb.append(", collectProductCount=").append(collectProductCount);
sb.append(", collectSubjectCount=").append(collectSubjectCount);
sb.append(", collectTopicCount=").append(collectTopicCount);
sb.append(", collectCommentCount=").append(collectCommentCount);
sb.append(", inviteFriendCount=").append(inviteFriendCount);
sb.append(", recentOrderTime=").append(recentOrderTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberStatisticsInfo.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.