instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Season AD_Reference_ID=540588
* Reference name: Season
*/
public static final int SEASON_AD_Reference_ID=540588;
/** Winter = 4 */
public static final String SEASON_Winter = "4";
/** Spring = 1 */
public static final String SEASON_Spring = "1";
/** Summer = 2 */
public static final String SEASON_Summer = "2";
/** Autumn = 3 */
public static final String SEASON_Autumn = "3";
/** Set Jahreszeit.
@param Season Jahreszeit */
@Override
public void setSeason (java.lang.String Season)
{
set_Value (COLUMNNAME_Season, Season);
}
/** Get Jahreszeit.
@return Jahreszeit */
@Override
public java.lang.String getSeason ()
{
return (java.lang.String)get_Value(COLUMNNAME_Season);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab. | @return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\model\X_M_Material_Tracking.java | 1 |
请完成以下Java代码 | public void setMD_Available_For_Sales_ID (final int MD_Available_For_Sales_ID)
{
if (MD_Available_For_Sales_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Available_For_Sales_ID, MD_Available_For_Sales_ID);
}
@Override
public int getMD_Available_For_Sales_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Available_For_Sales_ID);
}
@Override
public void setQtyOnHandStock (final @Nullable BigDecimal QtyOnHandStock)
{
set_Value (COLUMNNAME_QtyOnHandStock, QtyOnHandStock);
}
@Override
public BigDecimal getQtyOnHandStock()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandStock);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setQtyToBeShipped (final @Nullable BigDecimal QtyToBeShipped)
{
set_Value (COLUMNNAME_QtyToBeShipped, QtyToBeShipped);
}
@Override
public BigDecimal getQtyToBeShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToBeShipped);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setStorageAttributesKey (final java.lang.String StorageAttributesKey)
{
set_Value (COLUMNNAME_StorageAttributesKey, StorageAttributesKey);
}
@Override
public java.lang.String getStorageAttributesKey()
{
return get_ValueAsString(COLUMNNAME_StorageAttributesKey);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MD_Available_For_Sales.java | 1 |
请完成以下Java代码 | public String getRdesc() {
return rdesc;
}
public void setRdesc(String rdesc) {
this.rdesc = rdesc;
}
public String getRval() {
return rval;
}
public void setRval(String rval) {
this.rval = rval;
}
public Date getCreated() { | return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\Role.java | 1 |
请完成以下Java代码 | public class HRCreatePeriods extends JavaProcess
{
/**
* Prepare
*/
protected void prepare ()
{
// prepare
}
/**
* Process
* @return info
* @throws Exception
*/
protected String doIt ()
throws Exception
{
int year_ID = getRecord_ID(); | MHRYear year = new MHRYear (getCtx(), getRecord_ID(), get_TrxName());
if (year.get_ID() <= 0 || year.get_ID() != year_ID)
return "Year not exist";
else if(year.isProcessed())
return "No Created, The Period's exist";
log.info(year.toString());
//
if (year.createPeriods())
{
//arhipac: Cristina Ghita -- because of the limitation of UI, you can not enter more records on a tab which has
//TabLevel>0 and there are just processed records, so we have not to set year processed
//tracker: 2584313 https://sourceforge.net/tracker/index.php?func=detail&aid=2584313&group_id=176962&atid=934929
year.setProcessed(false);
year.save();
return "@OK@ Create Periods";
}
return Msg.translate(getCtx(), "PeriodNotValid");
} // doIt
} // YearCreatePeriods | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\process\HRCreatePeriods.java | 1 |
请完成以下Java代码 | public class C_Payment_Reservation_AuthorizePayPalOrder extends JavaProcess implements IProcessPrecondition
{
private final PayPal paypal = SpringContextHolder.instance.getBean(PayPal.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(IProcessPreconditionsContext context)
{
final PaymentReservationId reservationId = PaymentReservationId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
if (reservationId == null)
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal();
}
if (!paypal.hasActivePaypalOrder(reservationId))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no active paypal order exists");
} | return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final PaymentReservationId reservationId = getPaymentReservationId();
paypal.authorizePayPalReservation(reservationId);
return MSG_OK;
}
private PaymentReservationId getPaymentReservationId()
{
return PaymentReservationId.ofRepoId(getRecord_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\ui\process\C_Payment_Reservation_AuthorizePayPalOrder.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Received Inquiry Reply.
@param ReceiveInquiryReply Received Inquiry Reply */
public void setReceiveInquiryReply (boolean ReceiveInquiryReply)
{
set_Value (COLUMNNAME_ReceiveInquiryReply, Boolean.valueOf(ReceiveInquiryReply));
}
/** Get Received Inquiry Reply.
@return Received Inquiry Reply */
public boolean isReceiveInquiryReply ()
{
Object oo = get_Value(COLUMNNAME_ReceiveInquiryReply);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Receive Order Reply.
@param ReceiveOrderReply Receive Order Reply */
public void setReceiveOrderReply (boolean ReceiveOrderReply)
{
set_Value (COLUMNNAME_ReceiveOrderReply, Boolean.valueOf(ReceiveOrderReply));
}
/** Get Receive Order Reply.
@return Receive Order Reply */
public boolean isReceiveOrderReply ()
{
Object oo = get_Value(COLUMNNAME_ReceiveOrderReply);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Send Inquiry.
@param SendInquiry
Quantity Availability Inquiry
*/
public void setSendInquiry (boolean SendInquiry)
{
set_Value (COLUMNNAME_SendInquiry, Boolean.valueOf(SendInquiry));
}
/** Get Send Inquiry. | @return Quantity Availability Inquiry
*/
public boolean isSendInquiry ()
{
Object oo = get_Value(COLUMNNAME_SendInquiry);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Send Order.
@param SendOrder Send Order */
public void setSendOrder (boolean SendOrder)
{
set_Value (COLUMNNAME_SendOrder, Boolean.valueOf(SendOrder));
}
/** Get Send Order.
@return Send Order */
public boolean isSendOrder ()
{
Object oo = get_Value(COLUMNNAME_SendOrder);
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_C_BP_EDI.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setConsumerBatchEnabled(boolean consumerBatchEnabled) {
this.consumerBatchEnabled = consumerBatchEnabled;
if (consumerBatchEnabled) {
setBatchListener(true);
}
}
/**
* Set to {@code true} to enforce {@link com.rabbitmq.client.Channel#basicAck(long, boolean)}
* for {@link org.springframework.amqp.core.AcknowledgeMode#MANUAL}
* when {@link org.springframework.amqp.ImmediateAcknowledgeAmqpException} is thrown.
* This might be a tentative solution to not break behavior for current minor version.
* @param enforceImmediateAckForManual the flag to ack message for MANUAL mode on ImmediateAcknowledgeAmqpException
* @since 3.1.2
*/
public void setEnforceImmediateAckForManual(Boolean enforceImmediateAckForManual) {
this.enforceImmediateAckForManual = enforceImmediateAckForManual;
}
@Override
protected SimpleMessageListenerContainer createContainerInstance() {
return new SimpleMessageListenerContainer();
}
@Override
protected void initializeContainer(SimpleMessageListenerContainer instance,
@Nullable RabbitListenerEndpoint endpoint) {
super.initializeContainer(instance, endpoint);
JavaUtils javaUtils = JavaUtils.INSTANCE
.acceptIfNotNull(this.batchSize, instance::setBatchSize);
String concurrency = null;
if (endpoint != null) { | concurrency = endpoint.getConcurrency();
javaUtils.acceptIfNotNull(concurrency, instance::setConcurrency);
}
javaUtils
.acceptIfCondition(concurrency == null && this.concurrentConsumers != null, this.concurrentConsumers,
instance::setConcurrentConsumers)
.acceptIfCondition((concurrency == null || !(concurrency.contains("-")))
&& this.maxConcurrentConsumers != null,
this.maxConcurrentConsumers, instance::setMaxConcurrentConsumers)
.acceptIfNotNull(this.startConsumerMinInterval, instance::setStartConsumerMinInterval)
.acceptIfNotNull(this.stopConsumerMinInterval, instance::setStopConsumerMinInterval)
.acceptIfNotNull(this.consecutiveActiveTrigger, instance::setConsecutiveActiveTrigger)
.acceptIfNotNull(this.consecutiveIdleTrigger, instance::setConsecutiveIdleTrigger)
.acceptIfNotNull(this.receiveTimeout, instance::setReceiveTimeout)
.acceptIfNotNull(this.batchReceiveTimeout, instance::setBatchReceiveTimeout)
.acceptIfNotNull(this.enforceImmediateAckForManual, instance::setEnforceImmediateAckForManual);
if (Boolean.TRUE.equals(this.consumerBatchEnabled)) {
instance.setConsumerBatchEnabled(true);
/*
* 'batchListener=true' turns off container debatching by default, it must be
* true when consumer batching is enabled.
*/
instance.setDeBatchingEnabled(true);
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\SimpleRabbitListenerContainerFactory.java | 2 |
请完成以下Java代码 | private static WarehouseInfo fromRecord(final I_M_Warehouse record)
{
return WarehouseInfo.builder()
.warehouseId(WarehouseId.ofRepoId(record.getM_Warehouse_ID()))
.warehouseName(record.getName())
.build();
}
public String getLocatorName(final LocatorId locatorId)
{
return getWarehouseLocators(locatorId.getWarehouseId()).getLocatorName(locatorId);
}
private WarehouseLocatorsInfo getWarehouseLocators(@NonNull final WarehouseId warehouseId)
{
return locatorsByWarehouseId.computeIfAbsent(warehouseId, this::retrieveWarehouseLocators);
}
private WarehouseLocatorsInfo retrieveWarehouseLocators(@NonNull final WarehouseId warehouseId)
{
return WarehouseLocatorsInfo.builder()
.warehouseId(warehouseId) | .locators(dao.getLocators(warehouseId)
.stream()
.map(WarehousesLoadingCache::fromRecord)
.collect(ImmutableList.toImmutableList()))
.build();
}
private static LocatorInfo fromRecord(final I_M_Locator record)
{
return LocatorInfo.builder()
.locatorId(LocatorId.ofRepoId(record.getM_Warehouse_ID(), record.getM_Locator_ID()))
.locatorName(record.getValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\warehouse\WarehousesLoadingCache.java | 1 |
请完成以下Java代码 | public void complete() {
this.asyncContext.complete();
}
@Override
public void start(Runnable run) {
this.asyncContext.start(new DelegatingSecurityContextRunnable(run));
}
@Override
public void addListener(AsyncListener listener) {
this.asyncContext.addListener(listener);
}
@Override
public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) {
this.asyncContext.addListener(listener, request, response);
} | @Override
public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
return this.asyncContext.createListener(clazz);
}
@Override
public long getTimeout() {
return this.asyncContext.getTimeout();
}
@Override
public void setTimeout(long timeout) {
this.asyncContext.setTimeout(timeout);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\HttpServlet3RequestFactory.java | 1 |
请完成以下Java代码 | private Mono<Void> save() {
return Mono.defer(() -> saveChangeSessionId().then(saveDelta()).doOnSuccess((aVoid) -> this.isNew = false));
}
private Mono<Void> saveDelta() {
if (this.delta.isEmpty()) {
return Mono.empty();
}
String sessionKey = getSessionKey(getId());
Mono<Boolean> update = ReactiveRedisSessionRepository.this.sessionRedisOperations.opsForHash()
.putAll(sessionKey, new HashMap<>(this.delta));
Mono<Boolean> setTtl;
if (getMaxInactiveInterval().getSeconds() >= 0) {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.expire(sessionKey,
getMaxInactiveInterval());
}
else {
setTtl = ReactiveRedisSessionRepository.this.sessionRedisOperations.persist(sessionKey);
}
Mono<Object> clearDelta = Mono.fromDirect((s) -> {
this.delta.clear();
s.onComplete();
});
return update.flatMap((unused) -> setTtl).flatMap((unused) -> clearDelta).then();
}
private Mono<Void> saveChangeSessionId() {
if (!hasChangedSessionId()) {
return Mono.empty();
}
String sessionId = getId();
Publisher<Void> replaceSessionId = (s) -> { | this.originalSessionId = sessionId;
s.onComplete();
};
if (this.isNew) {
return Mono.from(replaceSessionId);
}
else {
String originalSessionKey = getSessionKey(this.originalSessionId);
String sessionKey = getSessionKey(sessionId);
return ReactiveRedisSessionRepository.this.sessionRedisOperations.rename(originalSessionKey, sessionKey)
.flatMap((unused) -> Mono.fromDirect(replaceSessionId))
.onErrorResume((ex) -> {
String message = NestedExceptionUtils.getMostSpecificCause(ex).getMessage();
return StringUtils.startsWithIgnoreCase(message, "ERR no such key");
}, (ex) -> Mono.empty());
}
}
}
private static final class RedisSessionMapperAdapter
implements BiFunction<String, Map<String, Object>, Mono<MapSession>> {
private final RedisSessionMapper mapper = new RedisSessionMapper();
@Override
public Mono<MapSession> apply(String sessionId, Map<String, Object> map) {
return Mono.fromSupplier(() -> this.mapper.apply(sessionId, map));
}
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\ReactiveRedisSessionRepository.java | 1 |
请完成以下Java代码 | public final class ImmutableModelCacheInvalidateRequestFactoriesList
{
private final ImmutableSetMultimap<String, ModelCacheInvalidateRequestFactory> factoriesByTableName;
@Getter private final TableNamesGroup tableNamesToEnableRemoveCacheInvalidation;
@Builder
private ImmutableModelCacheInvalidateRequestFactoriesList(
@NonNull final SetMultimap<String, ModelCacheInvalidateRequestFactory> factoriesByTableName,
@NonNull final TableNamesGroup tableNamesToEnableRemoveCacheInvalidation)
{
this.factoriesByTableName = ImmutableSetMultimap.copyOf(factoriesByTableName);
this.tableNamesToEnableRemoveCacheInvalidation = tableNamesToEnableRemoveCacheInvalidation;
}
@Override | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("size", factoriesByTableName.size())
.add("factories", factoriesByTableName)
.toString();
}
public int size() {return factoriesByTableName.size();}
public Set<ModelCacheInvalidateRequestFactory> getFactoriesByTableName(@NonNull final String tableName)
{
return factoriesByTableName.get(tableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\ImmutableModelCacheInvalidateRequestFactoriesList.java | 1 |
请完成以下Java代码 | public void onSuccess(WriteRequest request, WriteResponse response) {
client.getSharedAttributes().put(versionedId, tsKvProto);
super.onSuccess(request, response);
}
});
} else if (logFailedUpdateOfNonChangedValue) {
log.warn("Didn't update resource [{}] [{}]", versionedId, newValProto);
String logMsg = String.format("%s: Didn't update resource versionedId - %s value - %s. Value is not changed",
LOG_LWM2M_WARN, versionedId, newValProto);
logService.log(client, logMsg);
}
}
/**
* @param pathIdVer - path resource
* @return - value of Resource into format KvProto or null
*/
private Object getResourceValueFormatKv(LwM2mClient lwM2MClient, String pathIdVer) {
LwM2mResource resourceValue = LwM2MTransportUtil.getResourceValueFromLwM2MClient(lwM2MClient, pathIdVer);
if (resourceValue != null) {
ResourceModel.Type currentType = resourceValue.getType(); | ResourceModel.Type expectedType = helper.getResourceModelTypeEqualsKvProtoValueType(currentType, pathIdVer);
if (!resourceValue.isMultiInstances()) {
return LwM2mValueConverterImpl.getInstance().convertValue(resourceValue.getValue(), currentType, expectedType,
new LwM2mPath(fromVersionedIdToObjectId(pathIdVer)));
} else if (resourceValue.getInstances().size() > 0) {
return resourceValue.getInstances();
} else {
return null;
}
} else {
return null;
}
}
private String getStrValue(TransportProtos.TsKvProto tsKvProto) {
return tsKvProto.getKv().getStringV();
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\attributes\DefaultLwM2MAttributesService.java | 1 |
请完成以下Java代码 | public class HibernateUtil {
private static SessionFactory sessionFactory;
private static String PROPERTY_FILE_NAME;
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
PROPERTY_FILE_NAME = propertyFileName;
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = getSessionFactoryBuilder(serviceRegistry).build();
}
return sessionFactory;
}
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.proxy");
metadataSources.addAnnotatedClass(Company.class);
metadataSources.addAnnotatedClass(Employee.class);
Metadata metadata = metadataSources.buildMetadata(); | return metadata.getSessionFactoryBuilder();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\proxy\HibernateUtil.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8094
servlet:
session:
timeout: 30m
spring:
application:
name: roncoo-pay-web-sample-shop
mvc:
view:
pref | ix: /
suffix: .jsp
logging:
config: classpath:logback.xml | repos\roncoo-pay-master\roncoo-pay-web-sample-shop\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public synchronized void doUpdate(Map<EntityId, EntityData> newDataMap) {
this.updateLatestTsData(this.data);
List<Integer> subIdsToCancel = new ArrayList<>();
List<TbSubscription> subsToAdd = new ArrayList<>();
Set<EntityId> currentSubs = new HashSet<>();
subToEntityIdMap.forEach((subId, entityId) -> {
if (!newDataMap.containsKey(entityId)) {
subIdsToCancel.add(subId);
} else {
currentSubs.add(entityId);
}
});
log.trace("[{}][{}] Subscriptions that are invalid: {}", sessionRef.getSessionId(), cmdId, subIdsToCancel);
subIdsToCancel.forEach(subToEntityIdMap::remove);
List<EntityData> newSubsList = newDataMap.entrySet().stream().filter(entry -> !currentSubs.contains(entry.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
if (!newSubsList.isEmpty()) {
// NOTE: We ignore the TS subscriptions for new entities here, because widgets will re-init it's content and will create new subscriptions.
if (curTsCmd == null && latestValueCmd != null) {
List<EntityKey> keys = latestValueCmd.getKeys();
if (keys != null && !keys.isEmpty()) {
Map<EntityKeyType, List<EntityKey>> keysByType = getEntityKeyByTypeMap(keys);
newSubsList.forEach(
entity -> {
log.trace("[{}][{}] Found new subscription for entity: {}", sessionRef.getSessionId(), cmdId, entity.getEntityId());
subsToAdd.addAll(addSubscriptions(entity, keysByType, true, 0, 0));
} | );
}
}
}
subIdsToCancel.forEach(subId -> localSubscriptionService.cancelSubscription(getTenantId(), getSessionId(), subId));
subsToAdd.forEach(subscription -> localSubscriptionService.addSubscription(subscription, sessionRef));
sendWsMsg(new EntityDataUpdate(cmdId, data, null, maxEntitiesPerDataSubscription));
}
public void setCurrentCmd(EntityDataCmd cmd) {
curTsCmd = cmd.getTsCmd();
latestValueCmd = cmd.getLatestCmd();
}
@Override
protected EntityDataQuery buildEntityDataQuery() {
return query;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\TbEntityDataSubCtx.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Post {
@Id
private Long id;
private String title;
private LocalDate publicationDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title; | }
public void setTitle(String title) {
this.title = title;
}
public LocalDate getPublicationDate() {
return publicationDate;
}
public void setPublicationDate(LocalDate publicationDate) {
this.publicationDate = publicationDate;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\listrepositories\lastrecord\Post.java | 2 |
请完成以下Java代码 | public Object getAttribute(String name) {
checkState();
return this.session.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
checkState();
return Collections.enumeration(this.session.getAttributeNames());
}
@Override
public void setAttribute(String name, Object value) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.setAttribute(name, value);
if (value != oldValue) {
if (oldValue instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) oldValue)
.valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
if (value instanceof HttpSessionBindingListener) {
try {
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
}
@Override
public void removeAttribute(String name) {
checkState();
Object oldValue = this.session.getAttribute(name);
this.session.removeAttribute(name);
if (oldValue instanceof HttpSessionBindingListener) {
try { | ((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name, oldValue));
}
catch (Throwable th) {
logger.error("Error invoking session binding event listener", th);
}
}
}
@Override
public void invalidate() {
checkState();
this.invalidated = true;
}
@Override
public boolean isNew() {
checkState();
return !this.old;
}
void markNotNew() {
this.old = true;
}
private void checkState() {
if (this.invalidated) {
throw new IllegalStateException("The HttpSession has already be invalidated.");
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HttpSessionAdapter.java | 1 |
请完成以下Java代码 | public KotlinPropertyDeclaration empty() {
return new KotlinPropertyDeclaration(this);
}
@Override
protected VarBuilder self() {
return this;
}
}
/**
* Builder for a property accessor.
*
* @param <T> the type of builder
*/
public static final class AccessorBuilder<T extends Builder<T>> {
private final AnnotationContainer annotations = new AnnotationContainer();
private CodeBlock code;
private final T parent;
private final Consumer<Accessor> accessorFunction;
private AccessorBuilder(T parent, Consumer<Accessor> accessorFunction) {
this.parent = parent;
this.accessorFunction = accessorFunction;
}
/**
* Adds an annotation.
* @param className the class name of the annotation
* @return this for method chaining
*/
public AccessorBuilder<?> withAnnotation(ClassName className) {
return withAnnotation(className, null);
}
/**
* Adds an annotation.
* @param className the class name of the annotation
* @param annotation configurer for the annotation
* @return this for method chaining
*/
public AccessorBuilder<?> withAnnotation(ClassName className, Consumer<Annotation.Builder> annotation) {
this.annotations.addSingle(className, annotation);
return this;
}
/**
* Sets the body.
* @param code the code for the body
* @return this for method chaining
*/ | public AccessorBuilder<?> withBody(CodeBlock code) {
this.code = code;
return this;
}
/**
* Builds the accessor.
* @return the parent getter / setter
*/
public T buildAccessor() {
this.accessorFunction.accept(new Accessor(this));
return this.parent;
}
}
static final class Accessor implements Annotatable {
private final AnnotationContainer annotations;
private final CodeBlock code;
Accessor(AccessorBuilder<?> builder) {
this.annotations = builder.annotations.deepCopy();
this.code = builder.code;
}
CodeBlock getCode() {
return this.code;
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java | 1 |
请完成以下Java代码 | public void removeActiveSessionId(final WebuiSessionId sessionId)
{
activeSessions.remove(sessionId);
logger.debug("Removed sessionId '{}' to {}", sessionId, this);
}
public boolean hasActiveSessions()
{
return !activeSessions.isEmpty();
}
/* package */void addNotification(@NonNull final UserNotification notification)
{
final UserId adUserId = getUserId();
Check.assume(notification.getRecipientUserId() == adUserId.getRepoId(), "notification's recipient user ID shall be {}: {}", adUserId, notification);
final JSONNotification jsonNotification = JSONNotification.of(notification, jsonOptions);
fireEventOnWebsocket(JSONNotificationEvent.eventNew(jsonNotification, getUnreadCount()));
}
public void markAsRead(final String notificationId)
{
notificationsRepo.markAsReadById(Integer.parseInt(notificationId));
fireEventOnWebsocket(JSONNotificationEvent.eventRead(notificationId, getUnreadCount()));
}
public void markAllAsRead()
{ | logger.trace("Marking all notifications as read (if any) for {}...", this);
notificationsRepo.markAllAsReadByUserId(getUserId());
fireEventOnWebsocket(JSONNotificationEvent.eventReadAll());
}
public int getUnreadCount()
{
return notificationsRepo.getUnreadCountByUserId(getUserId());
}
public void setLanguage(@NonNull final String adLanguage)
{
this.jsonOptions = jsonOptions.withAdLanguage(adLanguage);
}
public void delete(final String notificationId)
{
notificationsRepo.deleteById(Integer.parseInt(notificationId));
fireEventOnWebsocket(JSONNotificationEvent.eventDeleted(notificationId, getUnreadCount()));
}
public void deleteAll()
{
notificationsRepo.deleteAllByUserId(getUserId());
fireEventOnWebsocket(JSONNotificationEvent.eventDeletedAll());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsQueue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Task {
private @Id @GeneratedValue Long id;
private String description;
private String assignee;
public Task() {
}
public Task(String description, String assignee) {
this.description = description;
this.assignee = assignee;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id; | }
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
} | repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\app\entity\Task.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable SQLDialect getSqlDialect() {
return this.sqlDialect;
}
public void setSqlDialect(@Nullable SQLDialect sqlDialect) {
this.sqlDialect = sqlDialect;
}
public @Nullable Resource getConfig() {
return this.config;
}
public void setConfig(@Nullable Resource config) {
this.config = config;
} | /**
* Determine the {@link SQLDialect} to use based on this configuration and the primary
* {@link DataSource}.
* @param dataSource the data source
* @return the {@code SQLDialect} to use for that {@link DataSource}
*/
public SQLDialect determineSqlDialect(DataSource dataSource) {
if (this.sqlDialect != null) {
return this.sqlDialect;
}
return SqlDialectLookup.getDialect(dataSource);
}
} | repos\spring-boot-4.0.1\module\spring-boot-jooq\src\main\java\org\springframework\boot\jooq\autoconfigure\JooqProperties.java | 2 |
请完成以下Java代码 | private Connector httpToHttpsRedirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8082);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
/***
* JWT (JSON WEB TOKEN)
* Question 1 : I see you haven't talk about the refresh token, is it necessary?
*
* Question 2: is it good idea to store the generated jwt token in database?
* | * Question 3 : how long is the best expiration time?
*
* Question 4 : will you talk on how to implement remember me and session timeout in jwt.
*
* Question 5: you've user maven oauth0 dependency, is it the best for jwt? Because I saw that some others have used io.
* JSON WEB Token dependency ', how to choose?
*
* Last question, best place to store jwt in production?
*
* Memory storage, session storage or cookies with http secure? If so how to access the authorities when used rest controller and angular
*
*
*
*
* */ | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\11.SpringSecurityJwt\src\main\java\spring\security\SecurityApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SimpleUrlLogoutSuccessHandler successLogoutHandler() {
SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler();
successLogoutHandler.setDefaultTargetUrl("/");
return successLogoutHandler;
}
@Bean
public SecurityContextLogoutHandler logoutHandler() {
SecurityContextLogoutHandler logoutHandler = new SecurityContextLogoutHandler();
logoutHandler.setInvalidateHttpSession(true);
logoutHandler.setClearAuthentication(true);
return logoutHandler;
}
@Bean
public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() {
return new SAMLLogoutProcessingFilter(successLogoutHandler(), logoutHandler());
}
@Bean
public SAMLLogoutFilter samlLogoutFilter() {
return new SAMLLogoutFilter(successLogoutHandler(),
new LogoutHandler[] { logoutHandler() }, | new LogoutHandler[] { logoutHandler() });
}
@Bean
public HTTPPostBinding httpPostBinding() {
return new HTTPPostBinding(parserPool(), VelocityFactory.getEngine());
}
@Bean
public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() {
return new HTTPRedirectDeflateBinding(parserPool());
}
@Bean
public SAMLProcessorImpl processor() {
ArrayList<SAMLBinding> bindings = new ArrayList<>();
bindings.add(httpRedirectDeflateBinding());
bindings.add(httpPostBinding());
return new SAMLProcessorImpl(bindings);
}
} | repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\SamlSecurityConfig.java | 2 |
请完成以下Java代码 | public Builder expiresAt(Instant expiresAt) {
return this.claim(IdTokenClaimNames.EXP, expiresAt);
}
/**
* Use this issued-at timestamp in the resulting {@link OidcIdToken}
* @param issuedAt The issued-at timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder issuedAt(Instant issuedAt) {
return this.claim(IdTokenClaimNames.IAT, issuedAt);
}
/**
* Use this issuer in the resulting {@link OidcIdToken}
* @param issuer The issuer to use
* @return the {@link Builder} for further configurations
*/
public Builder issuer(String issuer) {
return this.claim(IdTokenClaimNames.ISS, issuer);
}
/**
* Use this nonce in the resulting {@link OidcIdToken}
* @param nonce The nonce to use
* @return the {@link Builder} for further configurations
*/
public Builder nonce(String nonce) {
return this.claim(IdTokenClaimNames.NONCE, nonce);
} | /**
* Use this subject in the resulting {@link OidcIdToken}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
return this.claim(IdTokenClaimNames.SUB, subject);
}
/**
* Build the {@link OidcIdToken}
* @return The constructed {@link OidcIdToken}
*/
public OidcIdToken build() {
Instant iat = toInstant(this.claims.get(IdTokenClaimNames.IAT));
Instant exp = toInstant(this.claims.get(IdTokenClaimNames.EXP));
return new OidcIdToken(this.tokenValue, iat, exp, this.claims);
}
private Instant toInstant(Object timestamp) {
if (timestamp != null) {
Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
}
return (Instant) timestamp;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcIdToken.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ContractLine extends AbstractEntity
{
@ManyToOne(fetch = FetchType.EAGER)
@NonNull
private Contract contract;
@ManyToOne
@NonNull
private Product product;
@Override
protected void toString(final MoreObjects.ToStringHelper toStringHelper)
{
toStringHelper
.add("product", product);
}
public void setContract(final Contract contract)
{
this.contract = contract;
} | public Contract getContract()
{
return contract;
}
public Product getProduct()
{
return product;
}
public void setProduct(final Product product)
{
this.product = product;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\ContractLine.java | 2 |
请完成以下Java代码 | public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
private static final IsNumeric subject = new IsNumeric();
@State(Scope.Thread)
public static class ExecutionPlan {
private final Map<String, Boolean> testPlan = testPlan();
void validate(Function<String, Boolean> functionUnderTest) {
testPlan.forEach((key, value) -> {
Boolean result = functionUnderTest.apply(key);
assertEquals(value, result, key);
});
}
private void assertEquals(Boolean expectedResult, Boolean result, String input) {
if (result != expectedResult) {
throw new IllegalStateException("The output does not match the expected output, for input: " + input);
}
}
private Map<String, Boolean> testPlan() {
HashMap<String, Boolean> plan = new HashMap<>();
plan.put(Integer.toString(Integer.MAX_VALUE), true);
if (MODE == TestMode.SIMPLE) {
return plan;
}
plan.put("x0", false);
plan.put("0..005", false);
plan.put("--11", false);
plan.put("test", false);
plan.put(null, false);
for (int i = 0; i < 94; i++) {
plan.put(Integer.toString(i), true);
}
return plan;
}
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingCoreJava(ExecutionPlan plan) {
plan.validate(subject::usingCoreJava); | }
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingRegularExpressions(ExecutionPlan plan) {
plan.validate(subject::usingPreCompiledRegularExpressions);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
plan.validate(subject::usingNumberUtils_isCreatable);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
plan.validate(subject::usingNumberUtils_isParsable);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
plan.validate(subject::usingStringUtils_isNumeric);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
plan.validate(subject::usingStringUtils_isNumericSpace);
}
private enum TestMode {
SIMPLE, DIVERS
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\isnumeric\Benchmarking.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws IOException, InterruptedException {
DataSet allData;
try (RecordReader recordReader = new CSVRecordReader(0, ',')) {
recordReader.initialize(new FileSplit(new ClassPathResource("iris.txt").getFile()));
DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, 150, FEATURES_COUNT, CLASSES_COUNT);
allData = iterator.next();
}
allData.shuffle(42);
DataNormalization normalizer = new NormalizerStandardize();
normalizer.fit(allData);
normalizer.transform(allData);
SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
DataSet trainingData = testAndTrain.getTrain();
DataSet testData = testAndTrain.getTest();
MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder()
.iterations(1000)
.activation(Activation.TANH)
.weightInit(WeightInit.XAVIER)
.regularization(true)
.learningRate(0.1).l2(0.0001)
.list()
.layer(0, new DenseLayer.Builder().nIn(FEATURES_COUNT).nOut(3)
.build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(3)
.build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.activation(Activation.SOFTMAX) | .nIn(3).nOut(CLASSES_COUNT).build())
.backpropType(BackpropType.Standard).pretrain(false)
.build();
MultiLayerNetwork model = new MultiLayerNetwork(configuration);
model.init();
model.fit(trainingData);
INDArray output = model.output(testData.getFeatures());
Evaluation eval = new Evaluation(CLASSES_COUNT);
eval.eval(testData.getLabels(), output);
System.out.println(eval.stats());
}
} | repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\deeplearning4j\IrisClassifier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderHeader
{
private final H100 h100;
private final List<H110> h110Lines = new ArrayList<H110>();
private final List<H120> h120Lines = new ArrayList<H120>();
private final List<H130> h130Lines = new ArrayList<H130>();
private final List<OrderLine> orderLines = new ArrayList<OrderLine>();
private final List<T100> t100Lines = new ArrayList<T100>();
public OrderHeader(final H100 h100)
{
this.h100 = h100;
}
public void addH110(final H110 h110)
{
h110Lines.add(h110);
}
public void addH120(final H120 h120)
{
h120Lines.add(h120);
}
public void addH130(final H130 h130)
{
h130Lines.add(h130);
}
public void addOrderLine(final OrderLine orderLine)
{
orderLines.add(orderLine);
}
public void addT100(final T100 t100)
{
t100Lines.add(t100); | }
public H100 getH100()
{
return h100;
}
public List<H110> getH110Lines()
{
return h110Lines;
}
public List<H120> getH120Lines()
{
return h120Lines;
}
public List<H130> getH130Lines()
{
return h130Lines;
}
public List<OrderLine> getOrderLines()
{
return orderLines;
}
public List<T100> getT100Lines()
{
return t100Lines;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\OrderHeader.java | 2 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getUrc() {
return urc;
}
public void setUrc(int urc) {
this.urc = urc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + this.urc;
hash = 79 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} | if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Publisher other = (Publisher) obj;
if (this.urc != other.urc) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Publisher{" + "id=" + id + ", urc=" + urc + ", name=" + name + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddableMapRel\src\main\java\com\bookstore\entity\Publisher.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final String parameterName = parameter.getColumnName();
if (PARAM_M_Product_ID.equals(parameterName))
{
final IQueryFilter<I_M_DiscountSchemaBreak> selectionQueryFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final ProductId uniqueProductIdForSelection = pricingConditionsRepo.retrieveUniqueProductIdForSelectionOrNull(selectionQueryFilter);
if (uniqueProductIdForSelection == null)
{
// should not happen because of the preconditions above
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
return uniqueProductIdForSelection.getRepoId();
}
else
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
}
private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final String breaksTableName = I_M_DiscountSchemaBreak.Table_Name;
return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(breaksTableName));
}
@Override
protected String doIt()
{
final IQueryFilter<I_M_DiscountSchemaBreak> queryFilter = getProcessInfo().getQueryFilterOrElse(null);
if (queryFilter == null)
{
throw new AdempiereException("@NoSelection@"); | }
final boolean allowCopyToSameSchema = true;
final CopyDiscountSchemaBreaksRequest request = CopyDiscountSchemaBreaksRequest.builder()
.filter(queryFilter)
.pricingConditionsId(PricingConditionsId.ofRepoId(p_PricingConditionsId))
.productId(ProductId.ofRepoId(p_ProductId))
.allowCopyToSameSchema(allowCopyToSameSchema)
.direction(Direction.SourceTarget)
.build();
pricingConditionsRepo.copyDiscountSchemaBreaksWithProductId(request);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pricing\process\M_DiscountSchemaBreak_CopyToOtherSchema_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultEdqsApiService implements EdqsApiService {
private final EdqsPartitionService edqsPartitionService;
private final EdqsClientQueueFactory queueFactory;
private TbQueueRequestTemplate<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> requestTemplate;
@PostConstruct
private void init() {
requestTemplate = queueFactory.createEdqsRequestTemplate();
requestTemplate.init();
}
@Override
public ListenableFuture<EdqsResponse> processRequest(TenantId tenantId, CustomerId customerId, EdqsRequest request) {
var requestMsg = ToEdqsMsg.newBuilder()
.setTenantIdMSB(tenantId.getId().getMostSignificantBits())
.setTenantIdLSB(tenantId.getId().getLeastSignificantBits())
.setTs(System.currentTimeMillis())
.setRequestMsg(TransportProtos.EdqsRequestMsg.newBuilder()
.setValue(JacksonUtil.toString(request))
.build());
if (customerId != null && !customerId.isNullUid()) {
requestMsg.setCustomerIdMSB(customerId.getId().getMostSignificantBits());
requestMsg.setCustomerIdLSB(customerId.getId().getLeastSignificantBits());
}
UUID key = UUID.randomUUID();
Integer partition = edqsPartitionService.resolvePartition(tenantId, key); | ListenableFuture<TbProtoQueueMsg<FromEdqsMsg>> resultFuture = requestTemplate.send(new TbProtoQueueMsg<>(key, requestMsg.build()), partition);
return Futures.transform(resultFuture, msg -> {
TransportProtos.EdqsResponseMsg responseMsg = msg.getValue().getResponseMsg();
return JacksonUtil.fromString(responseMsg.getValue(), EdqsResponse.class);
}, MoreExecutors.directExecutor());
}
@Override
public boolean isSupported() {
return true;
}
@PreDestroy
private void stop() {
requestTemplate.stop();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edqs\DefaultEdqsApiService.java | 2 |
请完成以下Java代码 | public void setCode (java.lang.String Code)
{
set_Value (COLUMNNAME_Code, Code);
}
/** Get Validation code.
@return Validation Code
*/
@Override
public java.lang.String getCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_Code);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/**
* Type AD_Reference_ID=540047
* Reference name: AD_BoilerPlate_VarType
*/
public static final int TYPE_AD_Reference_ID=540047;
/** SQL = S */
public static final String TYPE_SQL = "S";
/** Rule Engine = R */ | public static final String TYPE_RuleEngine = "R";
/** Set Type.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Type.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java | 1 |
请完成以下Java代码 | private void setCompanyDetailsIfNotNull(
@NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails,
@NonNull final String labelPrefix,
@Nullable final XmlCompany billerCompany)
{
if (billerCompany != null)
{
setPhoneIfNotNull(invoiceWithDetails, billerCompany.getTelecom(), labelPrefix + LABEL_SUFFIX_PHONE);
setEmailIfNotNull(invoiceWithDetails, billerCompany.getOnline(), labelPrefix + LABEL_SUFFIX_EMAIL);
setPostalIfNotNull(invoiceWithDetails, billerCompany.getPostal(), labelPrefix);
setIfNotBlank(invoiceWithDetails, billerCompany.getCompanyname(), labelPrefix + LABEL_SUFFIX_GIVEN_NAME);
setIfNotBlank(invoiceWithDetails, billerCompany.getDepartment(), labelPrefix + LABEL_SUFFIX_FAMILY_NAME);
}
}
private void setPostalIfNotNull(
@NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails,
@NonNull final XmlPostal postal,
@NonNull final String labelPrefix)
{
setIfNotBlank(invoiceWithDetails, postal.getZip(), labelPrefix + LABEL_SUFFIX_ZIP);
setIfNotBlank(invoiceWithDetails, postal.getCity(), labelPrefix + LABEL_SUFFIX_CITY);
setIfNotBlank(invoiceWithDetails, postal.getStreet(), labelPrefix + LABEL_SUFFIX_STREET);
}
private void setPhoneIfNotNull(
@NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails,
@Nullable final XmlTelecom telecom,
@NonNull final String detailItemLabel)
{
if (telecom != null)
{
final List<String> phones = telecom.getPhones();
if (phones != null && !phones.isEmpty())
{
setIfNotBlank(invoiceWithDetails, phones.get(0), detailItemLabel);
}
} | }
private void setEmailIfNotNull(
@NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails,
@Nullable final XmlOnline online,
@NonNull final String detailItemLabel)
{
if (online != null)
{
final List<String> emails = online.getEmails();
if (emails != null && !emails.isEmpty())
{
setIfNotBlank(invoiceWithDetails, emails.get(0), detailItemLabel);
}
}
}
private void setIfNotBlank(
@NonNull final InvoiceWithDetails.InvoiceWithDetailsBuilder invoiceWithDetails,
@Nullable final String description,
@NonNull final String detailItemLabel)
{
createItemIfNotBlank(description, detailItemLabel).ifPresent(invoiceWithDetails::detailItem);
}
private Optional<InvoiceDetailItem> createItemIfNotBlank(
@Nullable final String description,
@NonNull final String detailItemLabel)
{
if (Check.isBlank(description))
{
return Optional.empty();
}
return Optional.of(InvoiceDetailItem.builder().label(detailItemLabel).description(description).build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\export\HealthcareXMLToInvoiceDetailPersister.java | 1 |
请完成以下Java代码 | public int toInt()
{
return value;
}
public boolean isZero() { return value == 0; }
public boolean isGreaterThanZero() { return value > 0; }
public boolean isGreaterThanOne() { return value > 1; }
public PrintCopies minimumOne()
{
return isZero() ? ONE : this;
} | public PrintCopies plus(@NonNull final PrintCopies other)
{
if (other.isZero())
{
return this;
}
else if (isZero())
{
return other;
}
else
{
return ofInt(this.value + other.value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\PrintCopies.java | 1 |
请完成以下Java代码 | public ILUTUConfigurationEditor edit(final Function<I_M_HU_LUTU_Configuration, I_M_HU_LUTU_Configuration> lutuConfigurationEditor)
{
assertEditing();
Check.assumeNotNull(lutuConfigurationEditor, "lutuConfigurationEditor not null");
final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration();
final I_M_HU_LUTU_Configuration lutuConfigurationEditingNew = lutuConfigurationEditor.apply(lutuConfigurationEditing);
setEditingLUTUConfiguration(lutuConfigurationEditingNew);
return this;
}
@Override
public ILUTUConfigurationEditor updateFromModel()
{
assertEditing();
final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration();
lutuConfigurationManager.updateLUTUConfigurationFromModel(lutuConfigurationEditing);
return this;
}
@Override
public boolean isEditing()
{
return _lutuConfigurationEditing != null;
}
private final void assertEditing()
{
Check.assume(isEditing(), HUException.class, "Editor shall be in editing mode");
}
@Override
public ILUTUConfigurationEditor save()
{
assertEditing();
final I_M_HU_LUTU_Configuration lutuConfigurationInitial = getLUTUConfiguration();
final I_M_HU_LUTU_Configuration lutuConfigurationEditing = getEditingLUTUConfiguration(); | //
// Check if we need to use the new configuration or we are ok with the old one
final I_M_HU_LUTU_Configuration lutuConfigurationToUse;
if (InterfaceWrapperHelper.isNew(lutuConfigurationInitial))
{
lutuFactory.save(lutuConfigurationEditing);
lutuConfigurationToUse = lutuConfigurationEditing;
}
else if (lutuFactory.isSameForHUProducer(lutuConfigurationInitial, lutuConfigurationEditing))
{
// Copy all values from our new configuration to initial configuration
InterfaceWrapperHelper.copyValues(lutuConfigurationEditing, lutuConfigurationInitial, false); // honorIsCalculated=false
lutuFactory.save(lutuConfigurationInitial);
lutuConfigurationToUse = lutuConfigurationInitial;
}
else
{
lutuFactory.save(lutuConfigurationEditing);
lutuConfigurationToUse = lutuConfigurationEditing;
}
_lutuConfigurationInitial = lutuConfigurationToUse;
_lutuConfigurationEditing = null; // stop editing mode
return this;
}
@Override
public ILUTUConfigurationEditor pushBackToModel()
{
if (isEditing())
{
save();
}
final I_M_HU_LUTU_Configuration lutuConfiguration = getLUTUConfiguration();
lutuConfigurationManager.setCurrentLUTUConfigurationAndSave(lutuConfiguration);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\LUTUConfigurationEditor.java | 1 |
请完成以下Java代码 | public class SaleGoods {
private Integer id;
private String goodsName;
private float weight;
private int type;
private Boolean onSale;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public float getWeight() {
return weight;
}
public void setWeight(float weight) {
this.weight = weight;
}
public Boolean getOnSale() {
return onSale;
} | public void setOnSale(Boolean onSale) {
this.onSale = onSale;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "SaleGoods{" +
"id=" + id +
", goodsName='" + goodsName + '\'' +
", weight=" + weight +
", type=" + type +
", onSale=" + onSale +
'}';
}
} | repos\spring-boot-projects-main\玩转SpringBoot系列案例源码\spring-boot-message-converter\src\main\java\cn\lanqiao\springboot3\entity\SaleGoods.java | 1 |
请完成以下Java代码 | void transferAttributes(Map<String, Object> attributes, HttpSession newSession) {
if (attributes != null) {
attributes.forEach(newSession::setAttribute);
}
}
@SuppressWarnings("unchecked")
private HashMap<String, Object> createMigratedAttributeMap(HttpSession session) {
HashMap<String, Object> attributesToMigrate = new HashMap<>();
Enumeration<String> enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement();
if (!this.migrateSessionAttributes && !key.startsWith("SPRING_SECURITY_")) {
// Only retain Spring Security attributes
continue;
}
attributesToMigrate.put(key, session.getAttribute(key));
}
return attributesToMigrate;
} | /**
* Defines whether attributes should be migrated to a new session or not. Has no
* effect if you override the {@code extractAttributes} method.
* <p>
* Attributes used by Spring Security (to store cached requests, for example) will
* still be retained by default, even if you set this value to {@code false}.
* @param migrateSessionAttributes whether the attributes from the session should be
* transferred to the new, authenticated session.
*/
public void setMigrateSessionAttributes(boolean migrateSessionAttributes) {
this.migrateSessionAttributes = migrateSessionAttributes;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\session\SessionFixationProtectionStrategy.java | 1 |
请完成以下Java代码 | public final class BeanUtil {
/**
* 此类不需要实例化
*/
private BeanUtil() {
}
/**
* 判断对象是否为null
*
* @param object 需要判断的对象
* @return 是否为null
*/
public static boolean isNull(Object object) {
return null == object;
}
/**
* 判断对象是否不为null
* | * @param object 需要判断的对象
* @return 是否不为null
*/
public static boolean nonNull(Object object) {
return null != object;
}
/**
* 判断对象是否为空,如果为空,直接抛出异常
*
* @param object 需要检查的对象
* @param errorMessage 异常信息
* @return 非空的对象
*/
public static Object requireNonNull(Object object, String errorMessage) {
if (null == object) {
throw new NullPointerException(errorMessage);
}
return object;
}
} | repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\utils\BeanUtil.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final OrderId orderId = OrderId.ofRepoId(context.getSingleSelectedRecordId());
final I_C_Order order = orderBL.getById(orderId);
return checkPreconditionsApplicable(order);
}
public abstract ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull I_C_Order order);
protected void openOrder(@NonNull final I_C_Order order)
{
final AdWindowId orderWindowId = RecordWindowFinder
.findAdWindowId(TableRecordReference.of(order))
.orElse(null); | openOrder(order, orderWindowId);
}
protected void openOrder(@NonNull final I_C_Order order, @Nullable final AdWindowId orderWindowId)
{
if (orderWindowId == null)
{
log.warn("Skip opening {} because no window found for it", order);
return;
}
getResult().setRecordToOpen(
TableRecordReference.of(order),
orderWindowId.getRepoId(),
ProcessExecutionResult.RecordsToOpen.OpenTarget.SingleDocument,
ProcessExecutionResult.RecordsToOpen.TargetTab.SAME_TAB);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreationProcess.java | 1 |
请完成以下Java代码 | private void processInTrx_unpackHU(@NonNull final PickingCandidate pickingCandidate)
{
final HuId packedToHUId = pickingCandidate.getPackedToHuId();
if (packedToHUId == null)
{
return;
}
final I_M_HU packedToHU = handlingUnitsBL.getById(packedToHUId);
if (handlingUnitsBL.isDestroyed(packedToHU))
{
// shall not happen
return;
}
if (X_M_HU.HUSTATUS_Picked.equals(packedToHU.getHUStatus()))
{
handlingUnitsBL.setHUStatus(packedToHU, PlainContextAware.newWithThreadInheritedTrx(), X_M_HU.HUSTATUS_Active);
} | pickingCandidate.changeStatusToDraft();
pickingCandidateRepository.save(pickingCandidate);
huShipmentScheduleBL.deleteByTopLevelHUAndShipmentScheduleId(packedToHUId, pickingCandidate.getShipmentScheduleId());
}
@NonNull
private ProductId getProductId(final PickingCandidate pickingCandidate)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(pickingCandidate.getShipmentScheduleId());
return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
}
private I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return shipmentSchedulesCache.computeIfAbsent(shipmentScheduleId, huShipmentScheduleBL::getById);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\UnProcessPickingCandidatesCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class SpinDataFormatConfigurationJdk8 {
@Bean
@ConditionalOnMissingBean(name = "spinDataFormatConfiguratorJdk8")
public static CamundaJacksonFormatConfiguratorJdk8 spinDataFormatConfiguratorJdk8() {
return new CamundaJacksonFormatConfiguratorJdk8();
}
}
@ConditionalOnClass(SpinProcessEnginePlugin.class)
@Configuration
static class SpinConfiguration {
@Bean
@ConditionalOnMissingBean(name = "spinProcessEnginePlugin")
public static ProcessEnginePlugin spinProcessEnginePlugin() {
return new SpringBootSpinProcessEnginePlugin();
}
}
@ConditionalOnClass(ConnectProcessEnginePlugin.class)
@Configuration
static class ConnectConfiguration {
@Bean
@ConditionalOnMissingBean(name = "connectProcessEnginePlugin")
public static ProcessEnginePlugin connectProcessEnginePlugin() { | return new ConnectProcessEnginePlugin();
}
}
/*
Provide option to apply application context classloader switch when Spring
Spring Developer tools are enabled
For more details: https://jira.camunda.com/browse/CAM-9043
*/
@ConditionalOnInitializedRestarter
@Configuration
static class InitializedRestarterConfiguration {
@Bean
@ConditionalOnMissingBean(name = "applicationContextClassloaderSwitchPlugin")
public ApplicationContextClassloaderSwitchPlugin applicationContextClassloaderSwitchPlugin() {
return new ApplicationContextClassloaderSwitchPlugin();
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmPluginConfiguration.java | 2 |
请完成以下Java代码 | public class PP_Order_Weighting_Run_Process extends JavaProcess implements IProcessPrecondition
{
private final PPOrderWeightingRunService ppOrderWeightingRunService = SpringContextHolder.instance.getBean(PPOrderWeightingRunService.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final PPOrderWeightingRunId weightingRunId = PPOrderWeightingRunId.ofRepoId(context.getSingleSelectedRecordId());
final PPOrderWeightingRun weightingRun = ppOrderWeightingRunService.getById(weightingRunId);
if (weightingRun.isProcessed()) | {
return ProcessPreconditionsResolution.rejectWithInternalReason("Already processed");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final PPOrderWeightingRunId weightingRunId = PPOrderWeightingRunId.ofRepoId(getRecord_ID());
ppOrderWeightingRunService.process(weightingRunId);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\process\PP_Order_Weighting_Run_Process.java | 1 |
请完成以下Java代码 | public static I_C_Location createLocation(@NonNull final Address pickupAddress)
{
final I_C_Location pickupFromLocation = InterfaceWrapperHelper.newInstance(I_C_Location.class);
pickupFromLocation.setAddress1(pickupAddress.getStreet1() + " " + pickupAddress.getHouseNo());
pickupFromLocation.setAddress2(pickupAddress.getStreet2());
pickupFromLocation.setPostal(pickupAddress.getZipCode());
pickupFromLocation.setCity(pickupAddress.getCity());
final I_C_Country i_c_country = InterfaceWrapperHelper.newInstance(I_C_Country.class);
i_c_country.setCountryCode(pickupAddress.getCountry().getAlpha2());
InterfaceWrapperHelper.save(i_c_country);
pickupFromLocation.setC_Country(i_c_country);
return pickupFromLocation;
}
@NonNull
public static I_C_BPartner createBPartner(@NonNull final Address pickupAddress)
{ | final I_C_BPartner pickupFromBPartner = InterfaceWrapperHelper.newInstance(I_C_BPartner.class);
pickupFromBPartner.setName(pickupAddress.getCompanyName1());
pickupFromBPartner.setName2(pickupAddress.getCompanyName2());
return pickupFromBPartner;
}
public static void dumpPdfToDisk(final byte[] pdf)
{
try
{
Files.write(Paths.get("C:", "a", Instant.now().toString().replace(":", ".") + ".pdf"), pdf);
}
catch (final IOException e)
{
e.printStackTrace();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\ShipperTestHelper.java | 1 |
请完成以下Java代码 | public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes)
{
this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes);
}
@Override
public List<IInvoiceLineAttribute> getInvoiceLineAttributes()
{
return invoiceLineAttributes;
}
@Override
public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate()
{
return iciolsToUpdate; | }
@Override
public int getC_PaymentTerm_ID()
{
return C_PaymentTerm_ID;
}
@Override
public void setC_PaymentTerm_ID(final int paymentTermId)
{
C_PaymentTerm_ID = paymentTermId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java | 1 |
请完成以下Java代码 | public static <T> Set<T> copyBySetAddAll(Set<T> original) {
Set<T> copy = new HashSet<>();
copy.addAll(original);
return copy;
}
// Set.clone
public static <T> Set<T> copyBySetClone(HashSet<T> original) {
Set<T> copy = (Set<T>) original.clone();
return copy;
}
// JSON
public static <T> Set<T> copyByJson(Set<T> original) {
Gson gson = new Gson();
String jsonStr = gson.toJson(original);
Set<T> copy = gson.fromJson(jsonStr, Set.class);
return copy;
}
// Apache Commons Lang | public static <T extends Serializable> Set<T> copyByApacheCommonsLang(Set<T> original) {
Set<T> copy = new HashSet<>();
for (T item : original) {
copy.add((T) SerializationUtils.clone(item));
}
return copy;
}
// Collectors.toSet
public static <T extends Serializable> Set<T> copyByCollectorsToSet(Set<T> original) {
Set<T> copy = original.stream()
.collect(Collectors.toSet());
return copy;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\set\CopySets.java | 1 |
请完成以下Java代码 | public class SAP_GLJournal_OpenItems_Launcher extends JavaProcess implements IProcessPrecondition
{
private final SAPGLJournalService sapglJournalService = SpringContextHolder.instance.getBean(SAPGLJournalService.class);
private final IViewsRepository viewsFactory = SpringContextHolder.instance.getBean(IViewsRepository.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final SAPGLJournalId sapglJournalId = context.getSingleSelectedRecordId(SAPGLJournalId.class);
if (!sapglJournalService.getDocStatus(sapglJournalId).isDraftedOrInProgress())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Not drafted");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{ | final SAPGLJournalId sapglJournalId = getSelectedSAPGLJournalId();
final ViewId viewId = viewsFactory.createView(OIViewFactory.createViewRequest(sapglJournalId))
.getViewId();
getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder()
.viewId(viewId.getViewId())
.target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay)
.build());
return MSG_OK;
}
private SAPGLJournalId getSelectedSAPGLJournalId()
{
return getRecordIdAssumingTableName(I_SAP_GLJournal.Table_Name, SAPGLJournalId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\SAP_GLJournal_OpenItems_Launcher.java | 1 |
请完成以下Java代码 | public class ProcessValidatorImpl implements ProcessValidator {
protected List<ValidatorSet> validatorSets;
protected ValidationErrorDecorator validationErrorDecorator;
public ProcessValidatorImpl() {
this.validationErrorDecorator = new ValidationErrorDecorator();
}
@Override
public List<ValidationError> validate(BpmnModel bpmnModel) {
List<ValidationError> allErrors = new ArrayList<ValidationError>();
for (ValidatorSet validatorSet : validatorSets) {
for (Validator validator : validatorSet.getValidators()) {
List<ValidationError> validatorErrors = new ArrayList<ValidationError>();
validator.validate(bpmnModel, validatorErrors);
if (!validatorErrors.isEmpty()) {
for (ValidationError error : validatorErrors) {
error.setValidatorSetName(validatorSet.getName());
validationErrorDecorator.decorate(error);
}
allErrors.addAll(validatorErrors);
} | }
}
return allErrors;
}
public List<ValidatorSet> getValidatorSets() {
return validatorSets;
}
public void setValidatorSets(List<ValidatorSet> validatorSets) {
this.validatorSets = validatorSets;
}
public void addValidatorSet(ValidatorSet validatorSet) {
if (validatorSets == null) {
validatorSets = new ArrayList<ValidatorSet>();
}
validatorSets.add(validatorSet);
}
} | repos\Activiti-develop\activiti-core\activiti-process-validation\src\main\java\org\activiti\validation\ProcessValidatorImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SendToFileRouteBuilder extends RouteBuilder
{
public static final String SEND_TO_FILE_ROUTE_ID = "LeichUndMehl-sendToFile";
@Override
public void configure() throws Exception
{
//@formatter:off
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(SEND_TO_FILE_ROUTE_ID))
.routeId(SEND_TO_FILE_ROUTE_ID)
.log("Route invoked!")
.log(LoggingLevel.DEBUG, "exchange body: ${body}")
.doTry()
.process(this::prepareForFileEndpoint)
.to(file("").fileName("${in.header.LeichUndMehl_Path}/${in.header.LeichUndMehl_Filename}"))
.endDoTry()
.doCatch(RuntimeException.class)
.to(direct(MF_ERROR_ROUTE_ID));
//@formatter:on
}
private void prepareForFileEndpoint(@NonNull final Exchange exchange)
{
final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class);
final DispatchMessageRequest dispatchMessageRequest = exchange.getIn().getBody(DispatchMessageRequest.class);
exchange.getIn().setHeader("LeichUndMehl_Path", dispatchMessageRequest.getDestinationDetails().getPluFileServerFolderNotBlank());
exchange.getIn().setHeader("LeichUndMehl_Filename", extractFilename(context.getPLUTemplateFilename()));
exchange.getIn().setBody(dispatchMessageRequest.getPayload()); | }
@VisibleForTesting
static String extractFilename(@NonNull final String pluTemplateFilename)
{
final int lastIndexOfDot = pluTemplateFilename.lastIndexOf('.');
if (lastIndexOfDot == -1)
{
return pluTemplateFilename + "_" + SystemTime.millis();
}
return pluTemplateFilename.substring(0, lastIndexOfDot) + "_" + SystemTime.millis() + pluTemplateFilename.substring(lastIndexOfDot);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\file\SendToFileRouteBuilder.java | 2 |
请完成以下Java代码 | static CostingDocumentRef extractDocumentRef(final I_M_CostDetail record)
{
if (record.getM_MatchPO_ID() > 0)
{
return CostingDocumentRef.ofMatchPOId(record.getM_MatchPO_ID());
}
else if (record.getM_MatchInv_ID() > 0)
{
return CostingDocumentRef.ofMatchInvoiceId(record.getM_MatchInv_ID());
}
else if (record.getM_InOutLine_ID() > 0)
{
if (record.isSOTrx())
{
return CostingDocumentRef.ofShipmentLineId(record.getM_InOutLine_ID());
}
else
{
return CostingDocumentRef.ofReceiptLineId(record.getM_InOutLine_ID());
}
}
else if (record.getM_InventoryLine_ID() > 0)
{
return CostingDocumentRef.ofInventoryLineId(record.getM_InventoryLine_ID());
}
else if (record.getM_MovementLine_ID() > 0)
{
if (record.isSOTrx())
{
return CostingDocumentRef.ofOutboundMovementLineId(record.getM_MovementLine_ID());
}
else
{
return CostingDocumentRef.ofInboundMovementLineId(record.getM_MovementLine_ID());
}
}
else if (record.getPP_Cost_Collector_ID() > 0)
{
return CostingDocumentRef.ofCostCollectorId(record.getPP_Cost_Collector_ID());
}
else if (record.getM_CostRevaluationLine_ID() > 0)
{
return CostingDocumentRef.ofCostRevaluationLineId(CostRevaluationLineId.ofRepoId(record.getM_CostRevaluation_ID(), record.getM_CostRevaluationLine_ID()));
}
else
{ | throw new AdempiereException("Cannot determine " + CostingDocumentRef.class + " for " + record);
}
}
@Override
public boolean hasCostDetailsByProductId(@NonNull final ProductId productId)
{
return toSqlQuery(CostDetailQuery.builder().productId(productId).build())
.anyMatch();
}
@Override
public Stream<CostDetail> stream(@NonNull final CostDetailQuery query)
{
return toSqlQuery(query)
.iterateAndStream()
.map(this::toCostDetail);
}
@Override
public ImmutableList<CostDetail> list(@NonNull final CostDetailQuery query)
{
return toSqlQuery(query)
.stream()
.map(this::toCostDetail)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\impl\CostDetailRepository.java | 1 |
请完成以下Java代码 | default boolean removeListener(Listener<K, V> listener) {
return false;
}
/**
* Add a listener at a specific index.
* @param index the index (list position).
* @param listener the listener.
* @since 2.5.3
*/
default void addListener(int index, Listener<K, V> listener) {
}
/**
* Add a listener.
* @param listener the listener.
* @since 2.5.3
*/
default void addListener(Listener<K, V> listener) {
}
/**
* Get the current list of listeners.
* @return the listeners.
* @since 2.5.3
*/
default List<Listener<K, V>> getListeners() {
return Collections.emptyList();
}
/**
* Add a post processor.
* @param postProcessor the post processor.
* @since 2.5.3
*/
default void addPostProcessor(ConsumerPostProcessor<K, V> postProcessor) {
}
/**
* Remove a post processor.
* @param postProcessor the post processor.
* @return true if removed.
* @since 2.5.3
*/
default boolean removePostProcessor(ConsumerPostProcessor<K, V> postProcessor) {
return false;
}
/**
* Get the current list of post processors.
* @return the post processor.
* @since 2.5.3
*/
default List<ConsumerPostProcessor<K, V>> getPostProcessors() {
return Collections.emptyList();
}
/**
* Update the consumer configuration map; useful for situations such as
* credential rotation.
* @param updates the configuration properties to update.
* @since 2.7
*/
default void updateConfigs(Map<String, Object> updates) {
} | /**
* Remove the specified key from the configuration map.
* @param configKey the key to remove.
* @since 2.7
*/
default void removeConfig(String configKey) {
}
/**
* Called whenever a consumer is added or removed.
*
* @param <K> the key type.
* @param <V> the value type.
*
* @since 2.5
*
*/
interface Listener<K, V> {
/**
* A new consumer was created.
* @param id the consumer id (factory bean name and client.id separated by a
* period).
* @param consumer the consumer.
*/
default void consumerAdded(String id, Consumer<K, V> consumer) {
}
/**
* An existing consumer was removed.
* @param id the consumer id (factory bean name and client.id separated by a
* period).
* @param consumer the consumer.
*/
default void consumerRemoved(@Nullable String id, Consumer<K, V> consumer) {
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ConsumerFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Collection<InvoiceId> getInvoiceIdsForVerificationSet(@NonNull final InvoiceVerificationSetId verificationSetId)
{
return new ArrayList<>(queryBL.createQueryBuilder(I_C_Invoice_Verification_SetLine.class)
.addEqualsFilter(I_C_Invoice_Verification_SetLine.COLUMNNAME_C_Invoice_Verification_Set_ID, verificationSetId)
.andCollect(I_C_Invoice_Verification_SetLine.COLUMN_C_Invoice_ID)
.create()
.idsAsSet(InvoiceId::ofRepoId));
}
@NonNull
private TaxCategoryId getTaxCategoryId(
@NonNull final I_C_Invoice invoice,
@NonNull final I_C_InvoiceLine invoiceLine,
@NonNull final CountryId taxCountryId)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final I_C_UOM uom = uomDAO.getById(invoiceLine.getPrice_UOM_ID());
final IEditablePricingContext pricingContext = pricingBL.createInitialContext(OrgId.ofRepoId(invoice.getAD_Org_ID()),
ProductId.ofRepoId(invoiceLine.getM_Product_ID()),
bPartnerId,
Quantity.of(invoiceLine.getQtyInvoicedInPriceUOM(), uom),
SOTrx.ofBoolean(invoice.isSOTrx()))
.setCountryId(taxCountryId);
final IPricingResult priceResult = pricingBL.calculatePrice(pricingContext);
if (!priceResult.isCalculated())
{
throw new AdempiereException("Price could not be calculated for C_InvoiceLine")
.appendParametersToMessage()
.setParameter("C_InvoiceLine_ID", invoiceLine.getC_InvoiceLine_ID());
}
return priceResult.getTaxCategoryId();
}
@NonNull
private CountryId getTaxCountryId(@NonNull final I_C_Invoice invoice, @NonNull final I_C_InvoiceLine invoiceLine)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final Supplier<LocationId> getLocationFromBillPartner = () -> {
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(bPartnerId, invoice.getC_BPartner_Location_ID());
return bpartnerDAO.getLocationId(bPartnerLocationId);
};
final LocationId locationId = Stream.of(invoiceLine.getC_Shipping_Location_ID(), invoice.getC_BPartner_Location_Value_ID())
.map(LocationId::ofRepoIdOrNull)
.filter(Objects::nonNull)
.findFirst()
.orElseGet(getLocationFromBillPartner);
return locationDAO.getCountryIdByLocationId(locationId);
}
@Value
private static class InvoiceVerificationRunResult
{ | @NonNull
Tax invoiceTax;
@Nullable
Tax resultingTax;
@NonNull
InvoiceVerificationSetLineId setLineId;
@NonNull
OrgId orgId;
@Nullable
String log;
@Builder
public InvoiceVerificationRunResult(final @NonNull Tax invoiceTax,
final @Nullable Tax resultingTax,
final @NonNull InvoiceVerificationSetLineId setLineId,
final @NonNull OrgId orgId,
@Nullable final String log)
{
this.invoiceTax = invoiceTax;
this.resultingTax = resultingTax;
this.setLineId = setLineId;
this.orgId = orgId;
this.log = log;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceVerificationBL.java | 2 |
请完成以下Java代码 | public class AdviseDeliveryOrderWorkpackageProcessor extends WorkpackageProcessorAdapter
{
public static void enqueueOnTrxCommit(
@NonNull final ShipmentScheduleId shipmentScheduleId,
@Nullable final AsyncBatchId asyncBatchId)
{
final IWorkPackageQueueFactory workPackageQueueFactory = Services.get(IWorkPackageQueueFactory.class);
workPackageQueueFactory
.getQueueForEnqueuing(AdviseDeliveryOrderWorkpackageProcessor.class)
.newWorkPackage()
.setAsyncBatchId(asyncBatchId)
.setUserInChargeId(Env.getLoggedUserIdIfExists().orElse(null))
.bindToThreadInheritedTrx()
.parameters()
.setParameter(PARAM_ShipmentScheduleId, shipmentScheduleId)
.end()
.buildAndEnqueue();
}
private static final String PARAM_ShipmentScheduleId = "ShipmentScheduleId";
@Override | public boolean isRunInTransaction()
{
return false;
}
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName_NOTUSED)
{
final int shipmentSchedule = getParameters().getParameterAsInt(PARAM_ShipmentScheduleId, -1);
CarrierAdviseCommand.of(ShipmentScheduleId.ofRepoId(shipmentSchedule))
.execute();
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\async\AdviseDeliveryOrderWorkpackageProcessor.java | 1 |
请完成以下Java代码 | public boolean setValue(final String columnName, final Object value)
{
final Object valueToSet = POWrapper.checkZeroIdValue(columnName, value);
final POInfo poInfo = po.getPOInfo();
if (!poInfo.isColumnUpdateable(columnName))
{
// If the column is not updateable we need to use set_ValueNoCheck
// because else is not consistent with how the generated classes were created
// see org.adempiere.util.ModelClassGenerator.createColumnMethods
return po.set_ValueNoCheck(columnName, valueToSet);
}
else
{
return po.set_ValueOfColumn(columnName, valueToSet);
}
}
@Override
public boolean setValueNoCheck(String propertyName, Object value)
{
return po.set_ValueOfColumn(propertyName, value);
}
@Override
public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception
{
final Class<?> returnType = interfaceMethod.getReturnType();
return po.get_ValueAsPO(propertyName, returnType);
}
@Override
public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value)
{
po.set_ValueFromPO(idPropertyName, parameterType, value);
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
if (methodArgs == null || methodArgs.length != 1) | {
throw new IllegalArgumentException("Invalid method arguments to be used for equals(): " + methodArgs);
}
return po.equals(methodArgs[0]);
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
return method.invoke(po, methodArgs);
}
@Override
public boolean isCalculated(final String columnName)
{
return getPOInfo().isCalculated(columnName);
}
@Override
public boolean hasColumnName(final String columnName)
{
return getPOInfo().hasColumnName(columnName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POModelInternalAccessor.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
application:
name: djl-image-classification-demo
servlet:
multipart:
max-file-size: 100MB
max-request-size: | 100MB
mvc:
pathmatch:
matching-strategy: ant_path_matcher | repos\springboot-demo-master\djl\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public void start() {
// Do nothing
}
@Override
public void stop() {
// Do nothing
}
@Override
public Scope lockScope() {
return NoopScope.INSTANCE;
}
@Override
public void lockError(Throwable lockException) {
// Do nothing
}
@Override
public Scope executionScope() {
return NoopScope.INSTANCE;
} | @Override
public void executionError(Throwable exception) {
// Do nothing
}
}
static class NoopScope implements JobExecutionObservation.Scope {
static final NoopScope INSTANCE = new NoopScope();
@Override
public void close() {
// Do nothing
}
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\NoopJobExecutionObservationProvider.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_C_ValidCombination getWriteOff_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setWriteOff_A(org.compiere.model.I_C_ValidCombination WriteOff_A)
{
set_ValueFromPO(COLUMNNAME_WriteOff_Acct, org.compiere.model.I_C_ValidCombination.class, WriteOff_A);
}
/** Set Forderungsverluste.
@param WriteOff_Acct
Konto für Forderungsverluste
*/
@Override
public void setWriteOff_Acct (int WriteOff_Acct) | {
set_Value (COLUMNNAME_WriteOff_Acct, Integer.valueOf(WriteOff_Acct));
}
/** Get Forderungsverluste.
@return Konto für Forderungsverluste
*/
@Override
public int getWriteOff_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WriteOff_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Default.java | 1 |
请完成以下Java代码 | public int remove(Filter filter)
{
int size = trie.size();
for (Map.Entry<String, V> entry : entrySet())
{
if (filter.remove(entry))
{
trie.remove(entry.getKey());
}
}
return size - trie.size();
}
public interface Filter<V>
{ | boolean remove(Map.Entry<String, V> entry);
}
/**
* 向中加入单词
* @param key
* @param value
*/
public void add(String key, V value)
{
trie.put(key, value);
}
public int size()
{
return trie.size();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SimpleDictionary.java | 1 |
请完成以下Java代码 | public String getRequestedTokenType() {
return this.requestedTokenType;
}
/**
* Returns the subject token.
* @return the subject token
*/
public String getSubjectToken() {
return this.subjectToken;
}
/**
* Returns the subject token type.
* @return the subject token type
*/
public String getSubjectTokenType() {
return this.subjectTokenType;
}
/**
* Returns the actor token.
* @return the actor token
*/
public String getActorToken() {
return this.actorToken;
}
/**
* Returns the actor token type.
* @return the actor token type
*/
public String getActorTokenType() { | return this.actorTokenType;
}
/**
* Returns the requested resource URI(s).
* @return the requested resource URI(s), or an empty {@code Set} if not available
*/
public Set<String> getResources() {
return this.resources;
}
/**
* Returns the requested audience value(s).
* @return the requested audience value(s), or an empty {@code Set} if not available
*/
public Set<String> getAudiences() {
return this.audiences;
}
/**
* Returns the requested scope(s).
* @return the requested scope(s), or an empty {@code Set} if not available
*/
public Set<String> getScopes() {
return this.scopes;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2TokenExchangeAuthenticationToken.java | 1 |
请完成以下Java代码 | public Set<String> getFieldNames() {return values.getFieldNames();}
@Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() {return values.get(this);}
public OIRow withSelected(final boolean selected)
{
return this.selected != selected
? toBuilder().selected(selected).build()
: this;
}
public OIRow withUserInputCleared()
{
return this.selected
? toBuilder().selected(false).build()
: this;
}
@Nullable
public OIRowUserInputPart getUserInputPart()
{
if (selected)
{
return OIRowUserInputPart.builder()
.rowId(rowId)
.factAcctId(factAcctId) | .selected(selected)
.build();
}
else
{
return null;
}
}
public OIRow withUserInput(@Nullable final OIRowUserInputPart userInput)
{
final boolean selectedNew = userInput != null && userInput.isSelected();
return this.selected != selectedNew
? toBuilder().selected(selectedNew).build()
: this;
}
public Amount getOpenAmountEffective() {return openAmount;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.webui\src\main\java\de\metas\acct\gljournal_sap\select_open_items\OIRow.java | 1 |
请完成以下Java代码 | public void setNextPaymentDate (java.sql.Timestamp NextPaymentDate)
{
set_ValueNoCheck (COLUMNNAME_NextPaymentDate, NextPaymentDate);
}
/** Get Next Payment Date.
@return Next Payment Date */
@Override
public java.sql.Timestamp getNextPaymentDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_NextPaymentDate);
}
/** Set Payment amount.
@param PayAmt
Amount being paid
*/
@Override
public void setPayAmt (java.math.BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Payment amount.
@return Amount being paid
*/
@Override
public java.math.BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID) | {
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentLine.java | 1 |
请完成以下Java代码 | public void putOtherProperty(final String name, final Object jsonValue)
{
otherProperties.put(name, jsonValue);
}
public JSONDocumentField putDebugProperty(final String name, final Object jsonValue)
{
otherProperties.put("debug-" + name, jsonValue);
return this;
}
public void putDebugProperties(final Map<String, Object> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
for (final Map.Entry<String, Object> e : debugProperties.entrySet())
{
putDebugProperty(e.getKey(), e.getValue());
} | }
public JSONDocumentField setViewEditorRenderMode(final ViewEditorRenderMode viewEditorRenderMode)
{
this.viewEditorRenderMode = viewEditorRenderMode != null ? viewEditorRenderMode.toJson() : null;
return this;
}
public void setFieldWarning(@Nullable final JSONDocumentFieldWarning fieldWarning)
{
this.fieldWarning = fieldWarning;
}
public JSONDocumentField setDevices(@Nullable final List<JSONDeviceDescriptor> devices)
{
this.devices = devices;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentField.java | 1 |
请完成以下Java代码 | public class PlayerDTO {
private Long id;
private String name;
private GameDTO currentGame;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
} | public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public GameDTO getCurrentGame() {
return this.currentGame;
}
public void setCurrentGame(GameDTO currentGame) {
this.currentGame = currentGame;
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\modelmapper\dto\PlayerDTO.java | 1 |
请完成以下Java代码 | public class CompositeAggregationKeyBuilder<ModelType> implements IAggregationKeyBuilder<ModelType>
{
private final String tableName;
private final List<String> columnNames = new ArrayList<>();
private final List<String> columnNamesRO = Collections.unmodifiableList(columnNames);
private final CopyOnWriteArrayList<IAggregationKeyBuilder<ModelType>> aggregationKeyBuilders = new CopyOnWriteArrayList<>();
public CompositeAggregationKeyBuilder(final Class<ModelType> modelClass)
{
super();
this.tableName = InterfaceWrapperHelper.getTableName(modelClass);
}
public CompositeAggregationKeyBuilder<ModelType> addAggregationKeyBuilder(final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder)
{
Check.assumeNotNull(aggregationKeyBuilder, "aggregationKeyBuilder not null");
if (!aggregationKeyBuilders.addIfAbsent(aggregationKeyBuilder))
{
return this;
}
for (final String columnName : aggregationKeyBuilder.getDependsOnColumnNames())
{
if (columnNames.contains(columnName))
{
continue;
}
columnNames.add(columnName);
}
return this;
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public List<String> getDependsOnColumnNames()
{
return columnNamesRO;
}
@Override
public String buildKey(final ModelType model)
{
return buildAggregationKey(model)
.getAggregationKeyString();
}
@Override
public AggregationKey buildAggregationKey(final ModelType model)
{
if (aggregationKeyBuilders.isEmpty())
{
throw new AdempiereException("No aggregation key builders added"); | }
final List<String> keyParts = new ArrayList<>();
final Set<AggregationId> aggregationIds = new HashSet<>();
for (final IAggregationKeyBuilder<ModelType> aggregationKeyBuilder : aggregationKeyBuilders)
{
final AggregationKey keyPart = aggregationKeyBuilder.buildAggregationKey(model);
keyParts.add(keyPart.getAggregationKeyString());
aggregationIds.add(keyPart.getAggregationId());
}
final AggregationId aggregationId = CollectionUtils.singleElementOrDefault(aggregationIds, null);
return new AggregationKey(Util.mkKey(keyParts.toArray()), aggregationId);
}
@Override
public boolean isSame(final ModelType model1, final ModelType model2)
{
if (model1 == model2)
{
return true;
}
final String key1 = buildKey(model1);
final String key2 = buildKey(model2);
return Objects.equals(key1, key2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\CompositeAggregationKeyBuilder.java | 1 |
请完成以下Java代码 | public Optional<User> get(long id) {
return Optional.ofNullable(entityManager.find(User.class, id));
}
@Override
public List<User> getAll() {
Query query = entityManager.createQuery("SELECT e FROM User e");
return query.getResultList();
}
@Override
public void save(User user) {
executeInsideTransaction(entityManager -> entityManager.persist(user));
}
@Override
public void update(User user, String[] params) {
user.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null"));
executeInsideTransaction(entityManager -> entityManager.merge(user));
}
@Override
public void delete(User user) {
executeInsideTransaction(entityManager -> entityManager.remove(user)); | }
private void executeInsideTransaction(Consumer<EntityManager> action) {
final EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
action.accept(entityManager);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e;
}
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\daos\JpaUserDao.java | 1 |
请完成以下Java代码 | public class MD_Cockpit_SetProcurementStatus extends MaterialCockpitViewBasedProcess
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
private static final String PARAM_PROCUREMENT_STATUS = X_M_Product.COLUMNNAME_ProcurementStatus;
@Param(parameterName = PARAM_PROCUREMENT_STATUS)
String procurementStatus;
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (getSelectedRowIds().isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No MaterialCockpitRows are selected");
}
final String commaSeparatedFieldNames = sysConfigBL.getValue(SYSCFG_Layout, (String)null);
final String commaSeparatedFieldNamesNorm = StringUtils.trimBlankToNull(commaSeparatedFieldNames);
if(Check.isNotBlank(commaSeparatedFieldNamesNorm)
&& !commaSeparatedFieldNamesNorm.equals(SYSCFG_DISABLED)
&& !commaSeparatedFieldNamesNorm.contains(PARAM_PROCUREMENT_STATUS))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Column Procurement Status isn't displayed");
}
final boolean paramIsDisplayed = sysConfigBL.getBooleanValue(SYSCFG_PREFIX + "." + PARAM_PROCUREMENT_STATUS + SYSCFG_DISPLAYED_SUFFIX, false);
if(Check.isBlank(commaSeparatedFieldNamesNorm) && !paramIsDisplayed)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Column Procurement Status isn't displayed");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final Set<ProductId> productIds = getSelectedProductIdsRecursively();
final ICompositeQueryUpdater<I_M_Product> updater = queryBL.createCompositeQueryUpdater(I_M_Product.class)
.addSetColumnValue(X_M_Product.COLUMNNAME_ProcurementStatus, procurementStatus);
queryBL.createQueryBuilder(I_M_Product.class) | .addInArrayFilter(I_M_Product.COLUMNNAME_M_Product_ID, productIds)
.create()
.updateDirectly(updater);
productIds.forEach(this::cacheResetProduct);
invalidateView();
invalidateParentView();
return MSG_OK;
}
private void cacheResetProduct(final ProductId productId)
{
CacheMgt.get().reset(I_M_Product.Table_Name, productId.getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\process\MD_Cockpit_SetProcurementStatus.java | 1 |
请完成以下Java代码 | public abstract class InstanceConsumer
{
private static char[] tableChar;
static
{
tableChar = new char[CharTable.CONVERT.length];
System.arraycopy(CharTable.CONVERT, 0, tableChar, 0, tableChar.length);
for (int c = 0; c <= 32; ++c)
{
tableChar[c] = '&'; // 也可以考虑用 '。'
}
}
protected abstract Instance createInstance(Sentence sentence, final FeatureMap featureMap);
protected double[] evaluate(String developFile, String modelFile) throws IOException
{
return evaluate(developFile, new LinearModel(modelFile));
}
protected double[] evaluate(String developFile, final LinearModel model) throws IOException
{
final int[] stat = new int[2];
IOUtility.loadInstance(developFile, new InstanceHandler()
{ | @Override
public boolean process(Sentence sentence)
{
Utility.normalize(sentence);
Instance instance = createInstance(sentence, model.featureMap);
IOUtility.evaluate(instance, model, stat);
return false;
}
});
return new double[]{stat[1] / (double) stat[0] * 100};
}
protected String normalize(String text)
{
char[] result = new char[text.length()];
for (int i = 0; i < result.length; i++)
{
result[i] = tableChar[text.charAt(i)];
}
return new String(result);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\InstanceConsumer.java | 1 |
请完成以下Java代码 | private static IStringExpression computeSqlWhereClause(@NonNull final ImmutableList<SqlLookupFilter> filters)
{
if (filters.isEmpty())
{
return IStringExpression.NULL;
}
final CompositeStringExpression.Builder builder = IStringExpression.composer();
for (SqlLookupFilter filter : filters)
{
final IStringExpression sqlWhereClause = filter.getSqlWhereClause();
if (sqlWhereClause != null && !sqlWhereClause.isNullExpression())
{
builder.appendIfNotEmpty("\n AND ").append("(").append(sqlWhereClause).append(")");
}
}
return builder.build();
}
private static INamePairPredicate computePostQueryPredicate(@NonNull final ImmutableList<SqlLookupFilter> filters)
{
if (filters.isEmpty())
{
return NamePairPredicates.ACCEPT_ALL;
}
final NamePairPredicates.Composer builder = NamePairPredicates.compose();
for (SqlLookupFilter filter : filters)
{
final INamePairPredicate postQueryPredicate = filter.getPostQueryPredicate();
if (postQueryPredicate != null)
{
builder.add(postQueryPredicate);
}
} | return builder.build();
}
private static ImmutableSet<String> computeDependsOnTableNames(final ImmutableList<SqlLookupFilter> filters)
{
return filters.stream()
.flatMap(filter -> filter.getDependsOnTableNames().stream())
.collect(ImmutableSet.toImmutableSet());
}
private static ImmutableSet<String> computeDependsOnFieldNames(final ImmutableList<SqlLookupFilter> filters)
{
return filters.stream()
.flatMap(filter -> filter.getDependsOnFieldNames().stream())
.collect(ImmutableSet.toImmutableSet());
}
public CompositeSqlLookupFilter withOnlyScope(@Nullable LookupDescriptorProvider.LookupScope onlyScope)
{
return !Objects.equals(this.onlyScope, onlyScope)
? new CompositeSqlLookupFilter(this.allFilters, onlyScope, this.onlyForAvailableParameterNames)
: this;
}
public CompositeSqlLookupFilter withOnlyForAvailableParameterNames(@Nullable Set<String> onlyForAvailableParameterNames)
{
return !Objects.equals(this.onlyForAvailableParameterNames, onlyForAvailableParameterNames)
? new CompositeSqlLookupFilter(this.allFilters, this.onlyScope, onlyForAvailableParameterNames)
: this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo == null ? null : accountNo.trim();
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public String getFundDirection() {
return fundDirection;
}
public void setFundDirection(String fundDirection) {
this.fundDirection = fundDirection;
}
public String getFundDirectionDesc() {
return AccountFundDirectionEnum.getEnum(this.getFundDirection()).getLabel();
}
public String getIsAllowSett() {
return isAllowSett;
}
public void setIsAllowSett(String isAllowSett) {
this.isAllowSett = isAllowSett == null ? null : isAllowSett.trim();
}
public String getIsCompleteSett() {
return isCompleteSett;
}
public void setIsCompleteSett(String isCompleteSett) {
this.isCompleteSett = isCompleteSett == null ? null : isCompleteSett.trim();
}
public String getRequestNo() {
return requestNo;
}
public void setRequestNo(String requestNo) {
this.requestNo = requestNo == null ? null : requestNo.trim();
}
public String getBankTrxNo() {
return bankTrxNo;
}
public void setBankTrxNo(String bankTrxNo) {
this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim();
} | public String getTrxType() {
return trxType;
}
public void setTrxType(String trxType) {
this.trxType = trxType == null ? null : trxType.trim();
}
public String getTrxTypeDesc() {
return TrxTypeEnum.getEnum(this.getTrxType()).getDesc();
}
public Integer getRiskDay() {
return riskDay;
}
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getAmountDesc() {
if(this.getFundDirection().equals(AccountFundDirectionEnum.ADD.name())){
return "<span style=\"color: blue;\">+"+this.amount.doubleValue()+"</span>";
}else{
return "<span style=\"color: red;\">-"+this.amount.doubleValue()+"</span>";
}
}
public String getCreateTimeDesc() {
return DateUtils.formatDate(this.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccountHistory.java | 2 |
请完成以下Java代码 | private PriceListId retrievePriceListForTerm()
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class);
final PricingSystemId pricingSystemIdToUse = CoalesceUtil.coalesceSuppliersNotNull(
() -> PricingSystemId.ofRepoIdOrNull(term.getM_PricingSystem_ID()),
() -> PricingSystemId.ofRepoIdOrNull(term.getC_Flatrate_Conditions().getM_PricingSystem_ID()),
() -> bpartnerDAO.retrievePricingSystemIdOrNull(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), SOTrx.SALES));
final BPartnerLocationAndCaptureId dropShipLocationId = ContractLocationHelper.extractDropshipLocationId(term);
final BPartnerLocationAndCaptureId billLocationId = ContractLocationHelper.extractBillToLocationId(term);
final BPartnerLocationAndCaptureId bpLocationIdToUse = dropShipLocationId != null ? dropShipLocationId : billLocationId;
final PriceListId priceListId = priceListDAO.retrievePriceListIdByPricingSyst(
pricingSystemIdToUse,
bpLocationIdToUse,
SOTrx.SALES);
if (priceListId == null)
{
final I_C_BPartner_Location billLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(billLocationId.getBpartnerLocationId());
throw new AdempiereException(MSG_FLATRATEBL_PRICE_LIST_MISSING_2P,
priceListDAO.getPricingSystemName(pricingSystemIdToUse),
billLocationRecord.getName());
}
return priceListId;
}
private IPricingResult retrievePricingResultUsingPriceList(@NonNull final PriceListId priceListId)
{
final IPricingBL pricingBL = Services.get(IPricingBL.class);
final boolean isSOTrx = true;
final IEditablePricingContext pricingCtx = pricingBL.createInitialContext(
term.getAD_Org_ID(),
termRelatedProductId.getRepoId(),
term.getBill_BPartner_ID(),
Services.get(IProductBL.class).getStockUOMId(termRelatedProductId).getRepoId(), | qty,
isSOTrx);
pricingCtx.setPriceDate(priceDate);
pricingCtx.setPriceListId(priceListId);
final IPricingResult result = pricingBL.calculatePrice(pricingCtx);
throwExceptionIfNotCalculated(result);
return result;
}
private void throwExceptionIfNotCalculated(@NonNull final IPricingResult result)
{
if (result.isCalculated())
{
return;
}
final String priceListName = Services.get(IPriceListDAO.class).getPriceListName(result.getPriceListId());
final String productName = Services.get(IProductBL.class).getProductValueAndName(termRelatedProductId);
throw new AdempiereException(MSG_FLATRATEBL_PRICE_MISSING_2P, priceListName, productName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\FlatrateTermPricing.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ByteArrayRef getExceptionByteArrayRef() {
return exceptionByteArrayRef;
}
@Override
public String getExceptionStacktrace() {
return getJobByteArrayRefAsString(exceptionByteArrayRef);
}
@Override
public void setExceptionStacktrace(String exception) {
if (exceptionByteArrayRef == null) {
exceptionByteArrayRef = new ByteArrayRef();
}
exceptionByteArrayRef.setValue("stacktrace", exception, getEngineType());
}
@Override
public String getExceptionMessage() {
return exceptionMessage;
}
@Override
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, JobInfo.MAX_EXCEPTION_MESSAGE_LENGTH);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String getLockOwner() {
return lockOwner;
}
@Override
public void setLockOwner(String claimedBy) {
this.lockOwner = claimedBy;
}
@Override
public Date getLockExpirationTime() {
return lockExpirationTime;
}
@Override
public void setLockExpirationTime(Date claimedUntil) {
this.lockExpirationTime = claimedUntil; | }
@Override
public String getScopeType() {
return scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
protected String getJobByteArrayRefAsString(ByteArrayRef jobByteArrayRef) {
if (jobByteArrayRef == null) {
return null;
}
return jobByteArrayRef.asString(getEngineType());
}
protected String getEngineType() {
if (StringUtils.isNotEmpty(scopeType)) {
return scopeType;
} else {
return ScopeTypes.BPMN;
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoryJobEntity[").append("id=").append(id)
.append(", jobHandlerType=").append(jobHandlerType);
if (scopeType != null) {
sb.append(", scopeType=").append(scopeType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\HistoryJobEntityImpl.java | 2 |
请完成以下Java代码 | private void createMissingValues()
{
String sql = "SELECT ra.A_RegistrationAttribute_ID "
+ "FROM A_RegistrationAttribute ra"
+ " LEFT OUTER JOIN A_RegistrationProduct rp ON (rp.A_RegistrationAttribute_ID=ra.A_RegistrationAttribute_ID)"
+ " LEFT OUTER JOIN A_Registration r ON (r.M_Product_ID=rp.M_Product_ID) "
+ "WHERE r.A_Registration_ID=?"
// Not in Registration
+ " AND NOT EXISTS (SELECT A_RegistrationAttribute_ID FROM A_RegistrationValue v "
+ "WHERE ra.A_RegistrationAttribute_ID=v.A_RegistrationAttribute_ID AND r.A_Registration_ID=v.A_Registration_ID)";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
pstmt.setInt(1, getA_Registration_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
MRegistrationValue v = new MRegistrationValue (this, rs.getInt(1), "?");
v.save();
}
rs.close();
pstmt.close();
pstmt = null; | }
catch (Exception e)
{
log.error(null, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
} // createMissingValues
} // MRegistration | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MRegistration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BankStatementLineReference createBankStatementLineRef(@NonNull final BankStatementLineRefCreateRequest request)
{
final I_C_BankStatementLine_Ref record = newInstance(I_C_BankStatementLine_Ref.class);
record.setAD_Org_ID(request.getOrgId().getRepoId());
record.setC_BankStatement_ID(request.getBankStatementId().getRepoId());
record.setC_BankStatementLine_ID(request.getBankStatementLineId().getRepoId());
record.setProcessed(request.isProcessed());
record.setLine(request.getLineNo());
record.setC_BPartner_ID(request.getBpartnerId().getRepoId());
record.setC_Payment_ID(request.getPaymentId().getRepoId());
record.setC_Invoice_ID(InvoiceId.toRepoId(request.getInvoiceId()));
// we store the psl's discount amount, because if we create a payment from this line, then we don't want the psl's Discount to end up as a mere underpayment.
record.setC_Currency_ID(request.getTrxAmt().getCurrencyId().getRepoId());
record.setTrxAmt(request.getTrxAmt().toBigDecimal());
InterfaceWrapperHelper.saveRecord(record);
return toBankStatementLineReference(record);
}
@Override
public void updateBankStatementLinesProcessedFlag(@NonNull final BankStatementId bankStatementId, final boolean processed)
{
queryBL.createQueryBuilder(I_C_BankStatementLine.class) | .addEqualsFilter(I_C_BankStatementLine.COLUMNNAME_C_BankStatement_ID, bankStatementId)
.create()
.updateDirectly()
.addSetColumnValue(I_C_BankStatementLine.COLUMNNAME_Processed, processed)
.execute();
queryBL.createQueryBuilder(I_C_BankStatementLine_Ref.class)
.addEqualsFilter(I_C_BankStatementLine_Ref.COLUMNNAME_C_BankStatement_ID, bankStatementId)
.create()
.updateDirectly()
.addSetColumnValue(I_C_BankStatementLine_Ref.COLUMNNAME_Processed, processed)
.execute();
}
@Override
public int getLastLineNo(@NonNull final BankStatementId bankStatementId)
{
return queryBL
.createQueryBuilder(I_C_BankStatementLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BankStatementLine.COLUMNNAME_C_BankStatement_ID, bankStatementId)
.create()
.maxInt(I_C_BankStatementLine.COLUMNNAME_Line);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\impl\BankStatementDAO.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAttributesKey (final @Nullable java.lang.String AttributesKey)
{
set_ValueNoCheck (COLUMNNAME_AttributesKey, AttributesKey);
}
@Override
public java.lang.String getAttributesKey()
{
return get_ValueAsString(COLUMNNAME_AttributesKey);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} | @Override
public void setM_Warehouse_ID (final int M_Warehouse_ID)
{
if (M_Warehouse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID);
}
@Override
public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOnHandChange (final @Nullable BigDecimal QtyOnHandChange)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHandChange, QtyOnHandChange);
}
@Override
public BigDecimal getQtyOnHandChange()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHandChange);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_Stock_From_HUs_V.java | 1 |
请完成以下Java代码 | public void customizeConnection(final Connection c) throws DBException
{
if (Adempiere.isUnitTestMode())
{
logger.debug("doing nothing because we are in unit test mode");
return;
}
final boolean wasAlreadyInMethod = inMethod.get();
if (wasAlreadyInMethod)
{
return;
}
try
{
inMethod.set(true); | DLMConnectionUtils.setSearchPathForDLM(c);
DLMConnectionUtils.changeDLMLevel(c, getDlmLevel());
DLMConnectionUtils.changeDLMCoalesceLevel(c, getDlmCoalesceLevel());
}
catch (final SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
finally
{
inMethod.set(false);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\connection\AbstractDLMCustomizer.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuilder sb = new StringBuilder ("CTabbedPane [");
sb.append(super.toString());
MFColor bg = getBackgroundColor();
if (bg != null)
sb.append(bg.toString());
sb.append("]");
return sb.toString();
} // toString
/** Select Action Text */
private static final String ACTION_SELECT = "CAS";
/** Select Action */
private static final CTAction s_action = new CTAction(ACTION_SELECT);
/**
* Select Action
*
* @author Jorg Janke
* @version $Id: CTabbedPane.java,v 1.2 2006/07/30 00:52:24 jjanke Exp $
*/
private static class CTAction extends UIAction
{
/**
* Constructor
*/
public CTAction (String actionName)
{
super (actionName);
} // Action
@Override
public void actionPerformed (ActionEvent e)
{ | String key = getName();
if (!key.equals(ACTION_SELECT)
|| !(e.getSource() instanceof CTabbedPane))
return;
CTabbedPane pane = (CTabbedPane)e.getSource();
String command = e.getActionCommand();
if (command == null || command.length() != 1)
return;
int index = command.charAt(0)-'1';
if (index > -1 && index < pane.getTabCount())
pane.setSelectedIndex(index);
else
System.out.println("Action: " + e);
} // actionPerformed
} // Action
} // CTabbedPane | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTabbedPane.java | 1 |
请完成以下Java代码 | public static DecisionEntityManager getDecisionEntityManager(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getDecisionEntityManager();
}
public static HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager() {
return getHistoricDecisionExecutionEntityManager(getCommandContext());
}
public static HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getHistoricDecisionExecutionEntityManager();
}
public static DmnRepositoryService getDmnRepositoryService() {
return getDmnRepositoryService(getCommandContext());
} | public static DmnRepositoryService getDmnRepositoryService(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getDmnRepositoryService();
}
public static DmnEngineAgenda getAgenda() {
return getAgenda(getCommandContext());
}
public static DmnEngineAgenda getAgenda(CommandContext commandContext) {
return commandContext.getSession(DmnEngineAgenda.class);
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\util\CommandContextUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Xlief4H {
@XmlElement(name = "HEADER", required = true)
protected HEADERXlief header;
@XmlElement(name = "TRAILR", required = true)
protected TRAILR trailr;
/**
* Gets the value of the header property.
*
* @return
* possible object is
* {@link HEADERXlief }
*
*/
public HEADERXlief getHEADER() {
return header;
}
/**
* Sets the value of the header property.
*
* @param value
* allowed object is
* {@link HEADERXlief }
*
*/
public void setHEADER(HEADERXlief value) {
this.header = value;
}
/**
* Gets the value of the trailr property.
*
* @return | * possible object is
* {@link TRAILR }
*
*/
public TRAILR getTRAILR() {
return trailr;
}
/**
* Sets the value of the trailr property.
*
* @param value
* allowed object is
* {@link TRAILR }
*
*/
public void setTRAILR(TRAILR value) {
this.trailr = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\Xlief4H.java | 2 |
请完成以下Java代码 | public String getStylePath() {
return stylePath;
}
public void setStylePath(String stylePath) {
this.stylePath = stylePath;
}
public String[] getVueStyle() {
return vueStyle;
}
public void setVueStyle(String[] vueStyle) {
this.vueStyle = vueStyle;
}
/**
* 根据code找枚举
*
* @param code
* @return
*/
public static CgformEnum getCgformEnumByConfig(String code) {
for (CgformEnum e : CgformEnum.values()) {
if (e.code.equals(code)) {
return e;
}
}
return null;
}
/**
* 根据类型找所有
*
* @param type | * @return
*/
public static List<Map<String, Object>> getJspModelList(int type) {
List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();
for (CgformEnum e : CgformEnum.values()) {
if (e.type == type) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", e.code);
map.put("note", e.note);
ls.add(map);
}
}
return ls;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\CgformEnum.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
@ApiModelProperty(example = "2013-04-17T10:17:43.902+0000")
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@ApiModelProperty(example = "variableUpdate")
public String getDetailType() {
return detailType;
}
public void setDetailType(String detailType) {
this.detailType = detailType;
}
@ApiModelProperty(example = "2")
public Integer getRevision() {
return revision;
}
public void setRevision(Integer revision) { | this.revision = revision;
}
public RestVariable getVariable() {
return variable;
}
public void setVariable(RestVariable variable) {
this.variable = variable;
}
@ApiModelProperty(example = "null")
public String getPropertyId() {
return propertyId;
}
public void setPropertyId(String propertyId) {
this.propertyId = propertyId;
}
@ApiModelProperty(example = "null")
public String getPropertyValue() {
return propertyValue;
}
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setAMOUNT(String value) {
this.amount = value;
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCY() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCY(String value) {
this.currency = value;
}
/**
* Gets the value of the taxcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXCODE() {
return taxcode;
}
/**
* Sets the value of the taxcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXCODE(String value) {
this.taxcode = value;
}
/**
* Gets the value of the taxrate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXRATE() {
return taxrate;
}
/**
* Sets the value of the taxrate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXRATE(String value) {
this.taxrate = value;
}
/**
* Gets the value of the taxcategory property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXCATEGORY() {
return taxcategory;
}
/** | * Sets the value of the taxcategory property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXCATEGORY(String value) {
this.taxcategory = value;
}
/**
* Gets the value of the taxamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXAMOUNT() {
return taxamount;
}
/**
* Sets the value of the taxamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXAMOUNT(String value) {
this.taxamount = value;
}
/**
* Gets the value of the taxableamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXABLEAMOUNT() {
return taxableamount;
}
/**
* Sets the value of the taxableamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXABLEAMOUNT(String value) {
this.taxableamount = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DALCH1.java | 2 |
请完成以下Java代码 | protected void loadDocumentDetails()
{
setDateDoc(costRevaluation.getDateAcct());
setDateAcct(costRevaluation.getDateAcct());
setDocLines(loadDocLines());
}
private ImmutableList<DocLine_CostRevaluation> loadDocLines()
{
return costRevaluationRepository.streamAllLineRecordsByCostRevaluationId(costRevaluation.getCostRevaluationId())
.filter(I_M_CostRevaluationLine::isActive)
.sorted(Comparator.comparing(I_M_CostRevaluationLine::getM_CostRevaluationLine_ID))
.map(lineRecord -> new DocLine_CostRevaluation(lineRecord, this))
.collect(ImmutableList.toImmutableList());
}
@Override
protected BigDecimal getBalance() {return BigDecimal.ZERO;}
@Override
protected List<Fact> createFacts(final AcctSchema as)
{
if (!AcctSchemaId.equals(as.getId(), costRevaluation.getAcctSchemaId()))
{
return ImmutableList.of();
}
setC_Currency_ID(as.getCurrencyId());
final Fact fact = new Fact(this, as, PostingType.Actual);
getDocLines().forEach(line -> createFactsForLine(fact, line));
return ImmutableList.of(fact);
}
private void createFactsForLine(@NonNull final Fact fact, @NonNull final DocLine_CostRevaluation docLine)
{
final AcctSchema acctSchema = fact.getAcctSchema();
final CostAmount costs = docLine.getCreateCosts(acctSchema);
//
// Revenue
// -------------------
// Product Asset DR
// Revenue CR
if (costs.signum() >= 0)
{
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(costs, null)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
fact.createLine() | .setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Revenue_Acct, acctSchema))
.setAmtSource(null, costs)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
}
//
// Expense
// ------------------------------------
// Product Asset CR
// Expense DR
else // deltaAmountToBook.signum() < 0
{
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(null, costs.negate())
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
fact.createLine()
.setDocLine(docLine)
.setAccount(docLine.getAccount(ProductAcctType.P_Asset_Acct, acctSchema))
.setAmtSource(costs.negate(), null)
// .locatorId(line.getM_Locator_ID()) // N/A atm
.buildAndAdd();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_CostRevaluation.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.getSelectionSize().isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@NonNull
private ApiRequestIterator getSelectedRequests()
{
final IQueryBuilder<I_API_Request_Audit> selectedApiRequestsQueryBuilder = retrieveSelectedRecordsQueryBuilder(I_API_Request_Audit.class);
if (isOnlyWithError) | {
selectedApiRequestsQueryBuilder.addEqualsFilter(I_API_Request_Audit.COLUMNNAME_Status, Status.ERROR.getCode());
}
final IQueryOrderBy orderBy = queryBL.createQueryOrderByBuilder(I_API_Request_Audit.class)
.addColumnAscending(I_API_Request_Audit.COLUMNNAME_Time)
.createQueryOrderBy();
final Iterator<I_API_Request_Audit> timeSortedApiRequests = selectedApiRequestsQueryBuilder.create()
.setOrderBy(orderBy)
.iterate(I_API_Request_Audit.class);
return ApiRequestIterator.of(timeSortedApiRequests, ApiRequestAuditRepository::recordToRequestAudit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\process\API_Audit_Repeat.java | 1 |
请完成以下Java代码 | public static boolean isDeployable(String filename) {
return hasSuffix(filename, BpmnDeployer.BPMN_RESOURCE_SUFFIXES)
|| hasSuffix(filename, CmmnDeployer.CMMN_RESOURCE_SUFFIXES)
|| hasSuffix(filename, DecisionDefinitionDeployer.DMN_RESOURCE_SUFFIXES);
}
public static boolean isDeployable(String filename, String[] additionalResourceSuffixes) {
return isDeployable(filename) || hasSuffix(filename, additionalResourceSuffixes);
}
public static boolean hasSuffix(String filename, String[] suffixes) {
if (suffixes == null || suffixes.length == 0) {
return false;
} else {
for (String suffix : suffixes) {
if (filename.endsWith(suffix)) {
return true;
}
}
return false;
}
}
public static boolean isDiagram(String fileName, String modelFileName) {
// process resources
boolean isBpmnDiagram = checkDiagram(fileName, modelFileName, BpmnDeployer.DIAGRAM_SUFFIXES, BpmnDeployer.BPMN_RESOURCE_SUFFIXES);
// case resources
boolean isCmmnDiagram = checkDiagram(fileName, modelFileName, CmmnDeployer.DIAGRAM_SUFFIXES, CmmnDeployer.CMMN_RESOURCE_SUFFIXES);
// decision resources
boolean isDmnDiagram = checkDiagram(fileName, modelFileName, DecisionDefinitionDeployer.DIAGRAM_SUFFIXES, DecisionDefinitionDeployer.DMN_RESOURCE_SUFFIXES);
return isBpmnDiagram || isCmmnDiagram || isDmnDiagram; | }
/**
* Checks, whether a filename is a diagram for the given modelFileName.
*
* @param fileName filename to check.
* @param modelFileName model file name.
* @param diagramSuffixes suffixes of the diagram files.
* @param modelSuffixes suffixes of model files.
* @return true, if a file is a diagram for the model.
*/
protected static boolean checkDiagram(String fileName, String modelFileName, String[] diagramSuffixes, String[] modelSuffixes) {
for (String modelSuffix : modelSuffixes) {
if (modelFileName.endsWith(modelSuffix)) {
String caseFilePrefix = modelFileName.substring(0, modelFileName.length() - modelSuffix.length());
if (fileName.startsWith(caseFilePrefix)) {
for (String diagramResourceSuffix : diagramSuffixes) {
if (fileName.endsWith(diagramResourceSuffix)) {
return true;
}
}
}
}
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\scanning\ProcessApplicationScanningUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Crawler implements CommandLineRunner {
@Autowired
private DataCache dataCache;
@Override
public void run(String... strings) {
new VWCrawler.Builder().setUrl("https://blog.csdn.net/qqHJQS").setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36")
.setTargetUrlRex("https://blog.csdn.net/qqHJQS/article/details/[0-9]+","https://blog.csdn.net/qqhjqs/article/details/[0-9]+").setThreadCount(5)
.setThreadCount(5)
.setTimeOut(5000).setPageParser(new CrawlerService<Blog>() {
@Override
public void parsePage(Document doc, Blog pageObj) {
pageObj.setReadCount(Integer.parseInt(pageObj.getReadCountStr().replace("阅读数:", "")));
pageObj.setUrl(doc.baseUri()); | pageObj.setUrlMd5(Md5Util.getMD5(pageObj.getUrl().getBytes()));
/**
* todo 评论列表还未处理
*/
}
@Override
public void save(Blog pageObj) {
dataCache.save(pageObj);
}
}).build().start();
}
} | repos\spring-boot-quick-master\quick-vw-crawler\src\main\java\com\crawler\vw\init\Crawler.java | 2 |
请完成以下Java代码 | public class GCDImplementation {
public static int gcdByBruteForce(int n1, int n2) {
int gcd = 1;
for (int i = 1; i <= n1 && i <= n2; i++) {
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
public static int gcdByEuclidsAlgorithm(int n1, int n2) {
if (n2 == 0) {
return n1;
}
return gcdByEuclidsAlgorithm(n2, n1 % n2);
}
public static int gcdBySteinsAlgorithm(int n1, int n2) {
if (n1 == 0) {
return n2;
}
if (n2 == 0) {
return n1;
}
int n;
for (n = 0; ((n1 | n2) & 1) == 0; n++) {
n1 >>= 1;
n2 >>= 1;
} | while ((n1 & 1) == 0) {
n1 >>= 1;
}
do {
while ((n2 & 1) == 0) {
n2 >>= 1;
}
if (n1 > n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
n2 = (n2 - n1);
} while (n2 != 0);
return n1 << n;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-5\src\main\java\com\baeldung\algorithms\gcd\GCDImplementation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configureGlobal(AuthenticationManagerBuilder auth,
UserDetailsService userDetailsService) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
// @formatter:on
// @formatter:off
@Bean
WebSecurityCustomizer ignoringCustomizer() {
return (web) -> web
.ignoring().requestMatchers(PathRequest.toH2Console());
}
// @formatter:on
// @formatter:off | @Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.anyRequest().authenticated()
)
.formLogin((formLogin) -> formLogin
.permitAll()
)
.build();
}
// @formatter:on
} | repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\config\WebSecurityConfig.java | 2 |
请完成以下Java代码 | public GroupDto getGroup(UriInfo context) {
Group dbGroup = findGroupObject();
if(dbGroup == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Group with id " + resourceId + " does not exist");
}
GroupDto group = GroupDto.fromGroup(dbGroup);
return group;
}
public ResourceOptionsDto availableOperations(UriInfo context) {
ResourceOptionsDto dto = new ResourceOptionsDto();
// add links if operations are authorized
URI uri = context.getBaseUriBuilder()
.path(rootResourcePath)
.path(GroupRestService.PATH)
.path(resourceId)
.build();
dto.addReflexiveLink(uri, HttpMethod.GET, "self");
if(!identityService.isReadOnly() && isAuthorized(DELETE)) {
dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete");
}
if(!identityService.isReadOnly() && isAuthorized(UPDATE)) {
dto.addReflexiveLink(uri, HttpMethod.PUT, "update");
}
return dto;
}
public void updateGroup(GroupDto group) {
ensureNotReadOnly();
Group dbGroup = findGroupObject();
if(dbGroup == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Group with id " + resourceId + " does not exist");
}
group.update(dbGroup);
identityService.saveGroup(dbGroup);
} | public void deleteGroup() {
ensureNotReadOnly();
identityService.deleteGroup(resourceId);
}
public GroupMembersResource getGroupMembersResource() {
return new GroupMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper());
}
protected Group findGroupObject() {
try {
return identityService.createGroupQuery()
.groupId(resourceId)
.singleResult();
} catch(ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing group query: "+e.getMessage());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\identity\impl\GroupResourceImpl.java | 1 |
请完成以下Java代码 | public BatchInformation2 getBtch() {
return btch;
}
/**
* Sets the value of the btch property.
*
* @param value
* allowed object is
* {@link BatchInformation2 }
*
*/
public void setBtch(BatchInformation2 value) {
this.btch = value;
}
/**
* Gets the value of the txDtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the txDtls property.
* | * <p>
* For example, to add a new item, do as follows:
* <pre>
* getTxDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EntryTransaction2 }
*
*
*/
public List<EntryTransaction2> getTxDtls() {
if (txDtls == null) {
txDtls = new ArrayList<EntryTransaction2>();
}
return this.txDtls;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\EntryDetails1.java | 1 |
请完成以下Java代码 | public ResponseEntity<Object> createFile(@RequestParam String name, @RequestParam("file") MultipartFile file){
localStorageService.create(name, file);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@ApiOperation("上传图片")
@PostMapping("/pictures")
public ResponseEntity<LocalStorage> uploadPicture(@RequestParam MultipartFile file){
// 判断文件是否为图片
String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
if(!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))){
throw new BadRequestException("只能上传图片");
}
LocalStorage localStorage = localStorageService.create(null, file);
return new ResponseEntity<>(localStorage, HttpStatus.OK);
}
@PutMapping
@Log("修改文件") | @ApiOperation("修改文件")
@PreAuthorize("@el.check('storage:edit')")
public ResponseEntity<Object> updateFile(@Validated @RequestBody LocalStorage resources){
localStorageService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除文件")
@DeleteMapping
@ApiOperation("多选删除")
public ResponseEntity<Object> deleteFile(@RequestBody Long[] ids) {
localStorageService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\LocalStorageController.java | 1 |
请完成以下Java代码 | public abstract class ExternalTaskCmd implements Command<Void> {
/**
* The corresponding external task id.
*/
protected String externalTaskId;
public ExternalTaskCmd(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
@Override
public Void execute(CommandContext commandContext) {
EnsureUtil.ensureNotNull("externalTaskId", externalTaskId);
validateInput();
ExternalTaskEntity externalTask = commandContext.getExternalTaskManager().findExternalTaskById(externalTaskId);
ensureNotNull(NotFoundException.class,
"Cannot find external task with id " + externalTaskId, "externalTask", externalTask);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateProcessInstanceById(externalTask.getProcessInstanceId());
}
writeUserOperationLog(commandContext, externalTask, getUserOperationLogOperationType(),
getUserOperationLogPropertyChanges(externalTask));
execute(externalTask);
return null;
}
protected void writeUserOperationLog(CommandContext commandContext, ExternalTaskEntity externalTask, String operationType, List<PropertyChange> propertyChanges) {
if (operationType != null) {
commandContext.getOperationLogManager().logExternalTaskOperation(operationType, externalTask, | propertyChanges == null || propertyChanges.isEmpty() ?
Collections.singletonList(PropertyChange.EMPTY_CHANGE) : propertyChanges);
}
}
protected String getUserOperationLogOperationType() {
return null;
}
protected List<PropertyChange> getUserOperationLogPropertyChanges(ExternalTaskEntity externalTask) {
return Collections.emptyList();
}
/**
* Executes the specific external task commands, which belongs to the current sub class.
*
* @param externalTask the external task which is used for the command execution
*/
protected abstract void execute(ExternalTaskEntity externalTask);
/**
* Validates the current input of the command.
*/
protected abstract void validateInput();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ExternalTaskCmd.java | 1 |
请完成以下Java代码 | public void onIsAttributeDependent(final I_M_ProductPrice productPrice)
{
if (!productPrice.isAttributeDependant())
{
return;
}
if (productPrice.getSeqNo() <= 0)
{
final int nextMatchSeqNo = Services.get(IPriceListDAO.class).retrieveNextMatchSeqNo(productPrice);
productPrice.setMatchSeqNo(nextMatchSeqNo);
}
}
@CalloutMethod(columnNames = { I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID })
public void onPriceListVersionId(final I_M_ProductPrice productPrice)
{
setTaxCategoryIdFromPriceListVersion(productPrice);
} | static void setTaxCategoryIdFromPriceListVersion(final I_M_ProductPrice productPrice)
{
final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoIdOrNull(productPrice.getM_PriceList_Version_ID());
if (priceListVersionId == null)
{
return;
}
final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
final TaxCategoryId defaultTaxCategoryId = priceListsRepo
.getDefaultTaxCategoryByPriceListVersionId(priceListVersionId)
.orElse(null);
if (defaultTaxCategoryId == null)
{
return;
}
productPrice.setC_TaxCategory_ID(defaultTaxCategoryId.getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\pricing\callout\M_ProductPrice.java | 1 |
请完成以下Java代码 | private boolean isASIValid(final I_C_BPartner_Product bpProduct, final AttributeSetInstanceId attributeSetInstanceId)
{
final IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class);
if (bpProduct.getM_AttributeSetInstance_ID() <= 0)
{
return true;
}
final AttributeSetInstanceId bpProductASIId = AttributeSetInstanceId.ofRepoId(bpProduct.getM_AttributeSetInstance_ID());
final ImmutableAttributeSet bpAttributeSet = asiBL.getImmutableAttributeSetById(bpProductASIId);
final ImmutableAttributeSet attributeSet = asiBL.getImmutableAttributeSetById(attributeSetInstanceId);
return !attributeSet.equals(bpAttributeSet);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_C_BPartner_Product.COLUMNNAME_GTIN, I_C_BPartner_Product.COLUMNNAME_EAN_CU, I_C_BPartner_Product.COLUMNNAME_EAN13_ProductCode })
private void normalizeProductCodeFields(@NonNull I_C_BPartner_Product record)
{
if (InterfaceWrapperHelper.isValueChanged(record, I_C_BPartner_Product.COLUMNNAME_GTIN))
{ | final GTIN gtin = GTIN.ofNullableString(record.getGTIN());
bpartnerProductBL.setProductCodeFieldsFromGTIN(record, gtin);
}
else if (InterfaceWrapperHelper.isValueChanged(record, I_C_BPartner_Product.COLUMNNAME_EAN_CU))
{
final EAN13 ean13 = EAN13.ofNullableString(record.getEAN_CU());
final GTIN gtin = ean13 != null ? ean13.toGTIN() : null;
bpartnerProductBL.setProductCodeFieldsFromGTIN(record, gtin);
}
// NOTE: syncing UPC to GTIN is not quite correct, but we have a lot of BPs which are relying on this logic
else if (InterfaceWrapperHelper.isValueChanged(record, I_C_BPartner_Product.COLUMNNAME_UPC))
{
final GTIN gtin = GTIN.ofNullableString(record.getUPC());
bpartnerProductBL.setProductCodeFieldsFromGTIN(record, gtin);
}
else if (InterfaceWrapperHelper.isValueChanged(record, I_C_BPartner_Product.COLUMNNAME_EAN13_ProductCode))
{
final EAN13ProductCode ean13ProductCode = EAN13ProductCode.ofNullableString(record.getEAN13_ProductCode());
bpartnerProductBL.setProductCodeFieldsFromEAN13ProductCode(record, ean13ProductCode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner_product\interceptor\C_BPartner_Product.java | 1 |
请完成以下Java代码 | public class WordAnalogy extends AbstractClosestVectors
{
protected WordAnalogy(String file)
{
super(file);
}
static void usage()
{
System.err.printf("Usage: java %s <FILE>\nwhere FILE contains word projections in the text format\n",
WordAnalogy.class.getName());
System.exit(0);
}
public static void main(String[] args) throws IOException
{
if (args.length < 1) usage();
new WordAnalogy(args[0]).execute();
}
protected Result getTargetVector()
{
final int words = vectorsReader.getNumWords();
final int size = vectorsReader.getSize();
String[] input = null;
while ((input = nextWords(3, "Enter 3 words")) != null)
{
// linear search the input word in vocabulary
int[] bi = new int[input.length];
int found = 0;
for (int k = 0; k < input.length; k++)
{
for (int i = 0; i < words; i++)
{
if (input[k].equals(vectorsReader.getWord(i)))
{
bi[k] = i;
System.out.printf("\nWord: %s Position in vocabulary: %d\n", input[k], bi[k]);
found++;
}
}
if (found == k)
{
System.out.printf("%s : Out of dictionary word!\n", input[k]);
}
}
if (found < input.length)
{
continue; | }
float[] vec = new float[size];
double len = 0;
for (int j = 0; j < size; j++)
{
vec[j] = vectorsReader.getMatrixElement(bi[1], j) -
vectorsReader.getMatrixElement(bi[0], j) + vectorsReader.getMatrixElement(bi[2], j);
len += vec[j] * vec[j];
}
len = Math.sqrt(len);
for (int i = 0; i < size; i++)
{
vec[i] /= len;
}
return new Result(vec, bi);
}
return null;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\WordAnalogy.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
application:
name: gateway-application
cloud:
# Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway:
# 路由配置项,对应 RouteDefinition 数组
routes:
- id: yudaoyuanma # 路由的编号
uri: http://www.iocoder.cn # 路由到的目标地址
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
- Path=/blog
filters:
- StripPrefix=1
- id: oschina # 路由的编号
uri: https://www.oschina.net # 路由的目标地址
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
- Path=/oschina
filters: # 过滤器,对请求进行拦截,实现自定义的功能,对应 FilterDefinition 数组
- StripPrefix=1
# 与 Spring Cloud 注册中心的 | 集成,对应 DiscoveryLocatorProperties 类
discovery:
locator:
enabled: true # 是否开启,默认为 false 关闭
url-expression: "'lb://' + serviceId" # 路由的目标地址的表达式,默认为 "'lb://' + serviceId"
# Nacos 作为注册中心的配置项
nacos:
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址 | repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo02-registry\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public Quantity getQtyPicked()
{
return byActualHUIdPicked.values()
.stream()
.map(DDOrderMoveSchedulePickedHU::getQtyPicked)
.reduce(Quantity::add)
.orElseThrow(() -> new IllegalStateException("empty list: " + this));
}
public boolean isDroppedTo()
{
return byActualHUIdPicked.values().stream().allMatch(DDOrderMoveSchedulePickedHU::isDroppedTo);
}
public void setDroppedTo(@NonNull LocatorId dropToLocatorId, @NonNull final MovementId dropToMovementId)
{
for (final DDOrderMoveSchedulePickedHU pickedHU : byActualHUIdPicked.values())
{
pickedHU.setDroppedTo(dropToLocatorId, dropToMovementId);
}
}
public ExplainedOptional<LocatorId> getInTransitLocatorId()
{
final ImmutableSet<LocatorId> inTransitLocatorIds = byActualHUIdPicked.values()
.stream()
.map(DDOrderMoveSchedulePickedHU::getInTransitLocatorId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
if (inTransitLocatorIds.isEmpty())
{
// shall not happen
return ExplainedOptional.emptyBecause("No in transit locator found");
} | else if (inTransitLocatorIds.size() == 1)
{
final LocatorId inTransitLocatorId = inTransitLocatorIds.iterator().next();
return ExplainedOptional.of(inTransitLocatorId);
}
else
{
// shall not happen
return ExplainedOptional.emptyBecause("More than one in transit locator found: " + inTransitLocatorIds);
}
}
public ImmutableSet<HuId> getActualHUIdsPicked()
{
return byActualHUIdPicked.keySet();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveSchedulePickedHUs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CaseDefinitionEntity findLatestDefinitionByKey(String key) {
return findLatestCaseDefinitionByKey(key);
}
@Override
public CaseDefinitionEntity findLatestDefinitionById(String id) {
return findCaseDefinitionById(id);
}
@Override
public CaseDefinitionEntity getCachedResourceDefinitionEntity(String definitionId) {
return getDbEntityManager().getCachedEntity(CaseDefinitionEntity.class, definitionId);
}
@Override
public CaseDefinitionEntity findLatestDefinitionByKeyAndTenantId(String definitionKey, String tenantId) {
return findLatestCaseDefinitionByKeyAndTenantId(definitionKey, tenantId);
} | @Override
public CaseDefinitionEntity findDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId) {
throw new UnsupportedOperationException("Currently finding case definition by version tag and tenant is not implemented.");
}
@Override
public CaseDefinitionEntity findDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId) {
return findCaseDefinitionByKeyVersionAndTenantId(definitionKey, definitionVersion, tenantId);
}
@Override
public CaseDefinitionEntity findDefinitionByDeploymentAndKey(String deploymentId, String definitionKey) {
return findCaseDefinitionByDeploymentAndKey(deploymentId, definitionKey);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionManager.java | 2 |
请完成以下Java代码 | public ShipmentScheduleReferencedLine provideFor(@NonNull final I_M_ShipmentSchedule shipmentSchedule)
{
final OrderAndLineId orderAndLineId = extractOrderAndLineId(shipmentSchedule);
return provideFor(orderAndLineId);
}
private ShipmentScheduleReferencedLine provideFor(@NonNull final OrderAndLineId orderAndLineId)
{
final OrderId orderId = orderAndLineId.getOrderId();
final I_C_Order order = ordersRepo.getById(orderId);
final I_C_OrderLine orderLine = ordersRepo.getOrderLineById(orderAndLineId);
return ShipmentScheduleReferencedLine.builder()
.recordRef(TableRecordReference.of(I_C_Order.Table_Name, orderId))
.preparationDate(TimeUtil.asZonedDateTime(order.getPreparationDate()))
.deliveryDate(computeOrderLineDeliveryDate(orderLine, order))
.warehouseId(warehouseAdvisor.evaluateWarehouse(orderLine))
.shipperId(ShipperId.optionalOfRepoId(orderLine.getM_Shipper_ID()))
.documentLineDescriptor(createDocumentLineDescriptor(orderAndLineId, order))
.build();
}
private static OrderAndLineId extractOrderAndLineId(final I_M_ShipmentSchedule shipmentSchedule)
{
return OrderAndLineId.ofRepoIds(shipmentSchedule.getC_Order_ID(), shipmentSchedule.getC_OrderLine_ID());
}
@VisibleForTesting
static ZonedDateTime computeOrderLineDeliveryDate(
@NonNull final I_C_OrderLine orderLine,
@NonNull final I_C_Order order)
{
final ZonedDateTime presetDateShipped = TimeUtil.asZonedDateTime(orderLine.getPresetDateShipped());
if (presetDateShipped != null)
{
return presetDateShipped;
} | // Fetch it from order line if possible
final ZonedDateTime datePromised = TimeUtil.asZonedDateTime(orderLine.getDatePromised());
if (datePromised != null)
{
return datePromised;
}
// Fetch it from order header if possible
final ZonedDateTime datePromisedFromOrder = TimeUtil.asZonedDateTime(order.getDatePromised());
if (datePromisedFromOrder != null)
{
return datePromisedFromOrder;
}
// Fail miserably...
throw new AdempiereException("@NotFound@ @DeliveryDate@")
.appendParametersToMessage()
.setParameter("oderLine", orderLine)
.setParameter("order", order);
}
private static DocumentLineDescriptor createDocumentLineDescriptor(
@NonNull final OrderAndLineId orderAndLineId,
@NonNull final I_C_Order order)
{
return OrderLineDescriptor.builder()
.orderId(orderAndLineId.getOrderRepoId())
.orderLineId(orderAndLineId.getOrderLineRepoId())
.orderBPartnerId(order.getC_BPartner_ID())
.docTypeId(order.getC_DocType_ID())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\ShipmentScheduleOrderReferenceProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonMappingConfig
{
int seqNo;
@Nullable String shipperProductExternalId;
@NonNull String attributeType;
@Nullable String groupKey;
@Nullable String attributeKey;
@NonNull String attributeValue;
@Nullable String mappingRule;
@Nullable String mappingRuleValue;
@JsonIgnore
public boolean isConfigFor(@NonNull final Function<String, String> valueProvider)
{
if (!isConfigForShipperProduct(valueProvider.apply(DeliveryMappingConstants.ATTRIBUTE_VALUE_SHIPPER_PRODUCT_EXTERNAL_ID))) {return false;}
if (Check.isBlank(mappingRule)){return true;}
switch (mappingRule) | {
case DeliveryMappingConstants.MAPPING_RULE_RECEIVER_COUNTRY_CODE:
return valueProvider.apply(DeliveryMappingConstants.ATTRIBUTE_VALUE_RECEIVER_COUNTRY_CODE)
.equals(mappingRuleValue);
default:
throw new IllegalArgumentException("Unknown mappingRule: " + mappingRule);
}
}
@JsonIgnore
private boolean isConfigForShipperProduct(@NonNull final String shipperProduct)
{
return this.shipperProductExternalId == null || this.shipperProductExternalId.equals(shipperProduct);
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-delivery\src\main\java\de\metas\common\delivery\v1\json\request\JsonMappingConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class DefaultMatchInvListener implements MatchInvListener
{
private final IMatchPOBL matchPOBL = Services.get(IMatchPOBL.class);
private final MatchInvoiceService matchInvoiceService;
private final OrderCostService orderCostService;
DefaultMatchInvListener(
@NonNull final MatchInvoiceService matchInvoiceService,
@NonNull final OrderCostService orderCostService)
{
this.matchInvoiceService = matchInvoiceService;
this.orderCostService = orderCostService;
}
@Override
public void onAfterCreated(@NonNull final MatchInv matchInv)
{
if (matchInv.getType().isCost())
{
final MatchInvCostPart matchInvCost = matchInv.getCostPartNotNull();
orderCostService.updateInOutCostById(
matchInvCost.getInoutCostId(),
inoutCost -> inoutCost.addCostAmountInvoiced(matchInvCost.getCostAmountInOut()));
}
}
@Override
public void onAfterDeleted(@NonNull final List<MatchInv> matchInvs)
{ | for (final MatchInv matchInv : matchInvs)
{
final MatchInvType type = matchInv.getType();
if (type.isMaterial())
{
clearInvoiceLineFromMatchPOs(matchInv);
}
else if (type.isCost())
{
final MatchInvCostPart matchInvCost = matchInv.getCostPartNotNull();
orderCostService.updateInOutCostById(
matchInvCost.getInoutCostId(),
inoutCost -> inoutCost.addCostAmountInvoiced(matchInvCost.getCostAmountInOut().negate()));
}
}
matchInvs.forEach(this::clearInvoiceLineFromMatchPOs);
}
private void clearInvoiceLineFromMatchPOs(@NonNull final MatchInv matchInv)
{
matchInvoiceService.getOrderLineId(matchInv)
.ifPresent(orderLineId -> matchPOBL.unlink(orderLineId, matchInv.getInvoiceAndLineId()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\listeners\DefaultMatchInvListener.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Article {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String content;
private String slug;
public Article(Long id, String name, String content, String slug) {
this.id = id;
this.name = name;
this.content = content;
this.slug = slug;
}
public Article() {
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
} | repos\tutorials-master\patterns-modules\vertical-slice-architecture\src\main\java\com\baeldung\hexagonal\persistence\entity\Article.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.