instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Spring Boot application配置 | server:
port: 8079
spring:
application:
name: user-service-consumer
# dubbo 配置项,对应 DubboConfigurationProperties 配置类
dubbo:
# Dubbo 应用配置
application:
name: ${spring.application.name} # 应用名
# Dubbo 注册中心配置
registry:
address: zookeeper://127 | .0.0.1:2181 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。 | repos\SpringBoot-Labs-master\lab-39\lab-39-skywalking-dubbo\lab-39-skywalking-dubbo-consumer\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public WarehouseAccounts getAccounts(@NonNull final WarehouseId warehouseId, @NonNull final AcctSchemaId acctSchemaId)
{
final ImmutableMap<AcctSchemaId, WarehouseAccounts> map = cache.getOrLoad(warehouseId, this::retrieveAccounts);
final WarehouseAccounts accounts = map.get(acctSchemaId);
if (accounts == null)
{
throw new AdempiereException("No Warehouse accounts defined for " + warehouseId + " and " + acctSchemaId);
}
return accounts;
}
private ImmutableMap<AcctSchemaId, WarehouseAccounts> retrieveAccounts(@NonNull final WarehouseId warehouseId)
{
return queryBL.createQueryBuilder(I_M_Warehouse_Acct.class)
.addOnlyActiveRecordsFilter() | .addEqualsFilter(I_M_Warehouse_Acct.COLUMNNAME_M_Warehouse_ID, warehouseId)
.create()
.stream()
.map(WarehouseAccountsRepository::fromRecord)
.collect(ImmutableMap.toImmutableMap(WarehouseAccounts::getAcctSchemaId, accounts -> accounts));
}
private static WarehouseAccounts fromRecord(@NonNull final I_M_Warehouse_Acct record)
{
return WarehouseAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.W_Differences_Acct(Account.of(AccountId.ofRepoId(record.getW_Differences_Acct()), WarehouseAccountType.W_Differences_Acct))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\WarehouseAccountsRepository.java | 1 |
请完成以下Java代码 | public class OrderedClientInterceptor implements ClientInterceptor, Ordered {
private final ClientInterceptor clientInterceptor;
private final int order;
/**
* Creates a new OrderedClientInterceptor with the given client interceptor and order.
*
* @param clientInterceptor The client interceptor to delegate to.
* @param order The order of this interceptor.
*/
public OrderedClientInterceptor(ClientInterceptor clientInterceptor, int order) {
this.clientInterceptor = requireNonNull(clientInterceptor, "clientInterceptor");
this.order = order;
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, | CallOptions callOptions, Channel next) {
return this.clientInterceptor.interceptCall(method, callOptions, next);
}
@Override
public int getOrder() {
return this.order;
}
@Override
public String toString() {
return "OrderedClientInterceptor [interceptor=" + this.clientInterceptor + ", order=" + this.order + "]";
}
} | repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\interceptor\OrderedClientInterceptor.java | 1 |
请完成以下Java代码 | public static class Column
{
private final String name;
private final String dbTableNameOrAlias;
private final String dbColumnName;
private final String dbColumnSQL;
private boolean exported;
public Column(String name, String dbTableNameOrAlias, String dbColumnName, String dbColumnSQL)
{
super();
this.name = name;
this.dbTableNameOrAlias = dbTableNameOrAlias;
this.dbColumnName = dbColumnName;
this.dbColumnSQL = dbColumnSQL;
this.exported = true;
}
@Override
public String toString()
{
return "Column ["
+ "name=" + name
+ ", dbTableNameOrAlias=" + dbTableNameOrAlias
+ ", dbColumnName=" + dbColumnName
+ ", dbColumnSQL=" + dbColumnSQL
+ ", exported=" + exported
+ "]";
}
public String getName()
{
return name;
} | public String getDbTableNameOrAlias()
{
return dbTableNameOrAlias;
}
public String getDbColumnName()
{
return dbColumnName;
}
public String getDbColumnSQL()
{
return dbColumnSQL;
}
public boolean isExported()
{
return exported;
}
public void setExported(boolean exported)
{
this.exported = exported;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExporterBuilder.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == mRefresh)
{
if (m_goals != null)
{
for (MGoal m_goal : m_goals)
{
m_goal.updateGoal(true);
}
}
htmlUpdate(lastUrl);
Container parent = getParent();
if (parent != null)
{
parent.invalidate();
}
invalidate();
if (parent != null)
{
parent.repaint();
}
else
{
repaint();
}
}
}
class PageLoader implements Runnable
{
private JEditorPane html;
private URL url;
private Cursor cursor;
PageLoader( JEditorPane html, URL url, Cursor cursor )
{
this.html = html;
this.url = url;
this.cursor = cursor;
} | @Override
public void run()
{
if( url == null )
{
// restore the original cursor
html.setCursor( cursor );
// PENDING(prinz) remove this hack when
// automatic validation is activated.
Container parent = html.getParent();
parent.repaint();
}
else
{
Document doc = html.getDocument();
try {
html.setPage( url );
}
catch( IOException ioe )
{
html.setDocument( doc );
}
finally
{
// schedule the cursor to revert after
// the paint has happended.
url = null;
SwingUtilities.invokeLater( this );
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addFirst(PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addFirst(original);
}
}
/**
* <p>addLast.</p>
*
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addLast(PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addLast(original);
}
}
/**
* <p>addBefore.</p>
*
* @param relativePropertySourceName a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addBefore(relativePropertySourceName, original);
}
}
/**
* <p>addAfter.</p>
*
* @param relativePropertySourceName a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
if (isAllowed(propertySource)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().addAfter(relativePropertySourceName, original);
}
}
/**
* <p>replace.</p> | *
* @param name a {@link java.lang.String} object
* @param propertySource a {@link org.springframework.core.env.PropertySource} object
*/
public void replace(String name, PropertySource<?> propertySource) {
if(isAllowed(propertySource)) {
if(copy.getPropertySources().contains(name)) {
final PropertySource<?> original = getOriginal(propertySource);
copy.getPropertySources().replace(name, original);
}
}
}
/**
* <p>remove.</p>
*
* @param name a {@link java.lang.String} object
* @return a {@link org.springframework.core.env.PropertySource} object
*/
public PropertySource<?> remove(String name) {
return copy.getPropertySources().remove(name);
}
/**
* <p>get.</p>
*
* @return a {@link org.springframework.core.env.ConfigurableEnvironment} object
*/
public ConfigurableEnvironment get() {
return copy;
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\configuration\EnvCopy.java | 2 |
请完成以下Java代码 | public I_C_UOM getC_UOM()
{
return candidate.getC_UOM();
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
final I_C_Flatrate_DataEntry flatrateDataEntry = getC_Flatrate_DataEntry();
if(flatrateDataEntry == null)
{
return null;
}
return flatrateDataEntry.getC_Flatrate_Term();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{
return InterfaceWrapperHelper.create(candidate.getC_Flatrate_DataEntry(), I_C_Flatrate_DataEntry.class);
}
@Override
public Object getWrappedModel()
{
return candidate;
}
@Override
public Timestamp getDate()
{
return candidate.getDatePromised();
}
@Override
public BigDecimal getQty()
{
// TODO: shall we use QtyToOrder instead... but that could affect our price (if we have some prices defined on breaks)
return candidate.getQtyPromised();
} | @Override
public void setM_PricingSystem_ID(int M_PricingSystem_ID)
{
candidate.setM_PricingSystem_ID(M_PricingSystem_ID);
}
@Override
public void setM_PriceList_ID(int M_PriceList_ID)
{
candidate.setM_PriceList_ID(M_PriceList_ID);
}
@Override
public void setCurrencyId(final CurrencyId currencyId)
{
candidate.setC_Currency_ID(CurrencyId.toRepoId(currencyId));
}
@Override
public void setPrice(BigDecimal priceStd)
{
candidate.setPrice(priceStd);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_PurchaseCandidate.java | 1 |
请完成以下Java代码 | public int getT_Receivables_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_T_Receivables_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getT_Revenue_A()
{
return get_ValueAsPO(COLUMNNAME_T_Revenue_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setT_Revenue_A(org.compiere.model.I_C_ValidCombination T_Revenue_A)
{
set_ValueFromPO(COLUMNNAME_T_Revenue_Acct, org.compiere.model.I_C_ValidCombination.class, T_Revenue_A);
}
/** Set Erlös Konto.
@param T_Revenue_Acct
Steuerabhängiges Konto zur Verbuchung Erlöse
*/
@Override
public void setT_Revenue_Acct (int T_Revenue_Acct) | {
set_Value (COLUMNNAME_T_Revenue_Acct, Integer.valueOf(T_Revenue_Acct));
}
/** Get Erlös Konto.
@return Steuerabhängiges Konto zur Verbuchung Erlöse
*/
@Override
public int getT_Revenue_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_T_Revenue_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_Tax_Acct.java | 1 |
请完成以下Java代码 | public class ContextLogger extends ProcessEngineLogger {
public void debugExecutingAtomicOperation(CoreAtomicOperation<?> executionOperation, CoreExecution execution) {
logDebug(
"001",
"Executing atomic operation {} on {}", executionOperation, execution);
}
public void debugException(Throwable throwable) {
logDebug(
"002",
"Exception while closing command context: {}",throwable.getMessage(), throwable);
}
public void infoException(Throwable throwable) {
logInfo(
"003",
"Exception while closing command context: {}",throwable.getMessage(), throwable);
}
public void errorException(Throwable throwable) { | logError(
"004",
"Exception while closing command context: {}",throwable.getMessage(), throwable);
}
public void exceptionWhileInvokingOnCommandFailed(Throwable t) {
logError(
"005",
"Exception while invoking onCommandFailed()", t);
}
public void bpmnStackTrace(String string) {
log(Context.getProcessEngineConfiguration().getLogLevelBpmnStackTrace(),
"006",
string);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\ContextLogger.java | 1 |
请完成以下Java代码 | public void putContext(final String name, final boolean value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public void putContext(final String name, final java.util.Date value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public void putContext(final String name, final int value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public boolean getContextAsBoolean(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
return DisplayType.toBoolean(valueObj);
}
@Override
public int getContextAsInt(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
if (valueObj == null) | {
return -1;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else
{
return Integer.parseInt(valueObj.toString());
}
}
@Override
public ICalloutRecord getCalloutRecord()
{
return getDocument().asCalloutRecord();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id)
{
return documentField.getLookupValueById(id) != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldAsCalloutField.java | 1 |
请完成以下Java代码 | public void addSolrDocument(String documentId, String itemName, String itemPrice) throws SolrServerException, IOException {
SolrInputDocument document = new SolrInputDocument();
document.addField("id", documentId);
document.addField("name", itemName);
document.addField("price", itemPrice);
solrClient.add(document);
solrClient.commit();
}
public void deleteSolrDocumentById(String documentId) throws SolrServerException, IOException {
solrClient.deleteById(documentId);
solrClient.commit();
} | public void deleteSolrDocumentByQuery(String query) throws SolrServerException, IOException {
solrClient.deleteByQuery(query);
solrClient.commit();
}
protected HttpSolrClient getSolrClient() {
return solrClient;
}
protected void setSolrClient(HttpSolrClient solrClient) {
this.solrClient = solrClient;
}
} | repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\apache\solrjava\SolrJavaIntegration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderDO {
/** 订单编号 **/
private Integer id;
/** 用户编号 **/
private Long userId;
/** 产品编号 **/
private Long productId;
/** 支付金额 **/
private Integer payAmount;
public Integer getId() {
return id;
}
public OrderDO setId(Integer id) {
this.id = id;
return this;
}
public Long getUserId() {
return userId;
}
public OrderDO setUserId(Long userId) {
this.userId = userId;
return this;
} | public Long getProductId() {
return productId;
}
public OrderDO setProductId(Long productId) {
this.productId = productId;
return this;
}
public Integer getPayAmount() {
return payAmount;
}
public OrderDO setPayAmount(Integer payAmount) {
this.payAmount = payAmount;
return this;
}
} | repos\SpringBoot-Labs-master\labx-17\labx-17-sca-seata-at-dubbo-demo\labx-17-sca-seata-at-dubbo-demo-order-service\src\main\java\cn\iocoder\springcloudalibaba\labx17\orderservice\entity\OrderDO.java | 2 |
请完成以下Java代码 | public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO Auto-generated method stub
}
@Override
public ViewId getIncludedViewId(final IViewRow row)
{
final PackingHUsViewKey key = extractPackingHUsViewKey(PickingSlotRow.cast(row));
return key.getPackingHUsViewId();
}
private PackingHUsViewKey extractPackingHUsViewKey(final PickingSlotRow row)
{
final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(row.getPickingSlotRowId());
return PackingHUsViewKey.builder()
.pickingSlotsClearingViewIdPart(getViewId().getViewIdPart())
.bpartnerId(rootRow.getBPartnerId())
.bpartnerLocationId(rootRow.getBPartnerLocationId())
.build();
}
public Optional<HUEditorView> getPackingHUsViewIfExists(final ViewId packingHUsViewId)
{
final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId);
return packingHUsViewsCollection.getByKeyIfExists(key);
}
public Optional<HUEditorView> getPackingHUsViewIfExists(final PickingSlotRowId rowId) | {
final PickingSlotRow rootRow = getRootRowWhichIncludesRowId(rowId);
final PackingHUsViewKey key = extractPackingHUsViewKey(rootRow);
return packingHUsViewsCollection.getByKeyIfExists(key);
}
public HUEditorView computePackingHUsViewIfAbsent(@NonNull final ViewId packingHUsViewId, @NonNull final PackingHUsViewSupplier packingHUsViewFactory)
{
return packingHUsViewsCollection.computeIfAbsent(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsViewFactory);
}
public void setPackingHUsView(@NonNull final HUEditorView packingHUsView)
{
final ViewId packingHUsViewId = packingHUsView.getViewId();
packingHUsViewsCollection.put(PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId), packingHUsView);
}
void closePackingHUsView(final ViewId packingHUsViewId, final ViewCloseAction closeAction)
{
final PackingHUsViewKey key = PackingHUsViewKey.ofPackingHUsViewId(packingHUsViewId);
packingHUsViewsCollection.removeIfExists(key)
.ifPresent(packingHUsView -> packingHUsView.close(closeAction));
}
public void handleEvent(final HUExtractedFromPickingSlotEvent event)
{
packingHUsViewsCollection.handleEvent(event);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PickingSlotsClearingView.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyToOrder()
{
return model.getQtyToOrder();
}
public BigDecimal getQtyToOrder_TU()
{
return model.getQtyToOrder_TU();
}
public boolean isZeroQty()
{
return getQtyToOrder().signum() == 0
&& getQtyToOrder_TU().signum() == 0;
}
/**
*
* @return the <code>model</code>'s date promised value, truncated to "day".
*/
public Timestamp getDatePromised()
{
return TimeUtil.trunc(model.getDatePromised(), TimeUtil.TRUNC_DAY);
}
public Object getHeaderAggregationKey()
{
// the pricelist is no aggregation criterion, because
// the orderline's price is manually set, i.e. the pricing system is not invoked
// and we often want to combine candidates with C_Flatrate_Terms (-> no pricelist, price take from the term)
// and candidates without a term, where the candidate's price is computed by the pricing system
return Util.mkKey(getAD_Org_ID(),
getM_Warehouse_ID(),
getC_BPartner_ID(),
getDatePromised().getTime(),
getM_PricingSystem_ID(),
// getM_PriceList_ID(),
getC_Currency_ID());
}
/**
* This method is actually used by the item aggregation key builder of {@link OrderLinesAggregator}. | *
* @return
*/
public Object getLineAggregationKey()
{
return Util.mkKey(
getM_Product_ID(),
getAttributeSetInstanceId().getRepoId(),
getC_UOM_ID(),
getM_HU_PI_Item_Product_ID(),
getPrice());
}
/**
* Creates and {@link I_PMM_PurchaseCandidate} to {@link I_C_OrderLine} line allocation using the whole candidate's QtyToOrder.
*
* @param orderLine
*/
/* package */void createAllocation(final I_C_OrderLine orderLine)
{
Check.assumeNotNull(orderLine, "orderLine not null");
final BigDecimal qtyToOrder = getQtyToOrder();
final BigDecimal qtyToOrderTU = getQtyToOrder_TU();
//
// Create allocation
final I_PMM_PurchaseCandidate_OrderLine alloc = InterfaceWrapperHelper.newInstance(I_PMM_PurchaseCandidate_OrderLine.class, orderLine);
alloc.setC_OrderLine(orderLine);
alloc.setPMM_PurchaseCandidate(model);
alloc.setQtyOrdered(qtyToOrder);
alloc.setQtyOrdered_TU(qtyToOrderTU);
InterfaceWrapperHelper.save(alloc);
// NOTE: on alloc's save we expect the model's quantities to be updated
InterfaceWrapperHelper.markStaled(model); // FIXME: workaround because we are modifying the model from alloc's model interceptor
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PurchaseCandidate.java | 1 |
请完成以下Spring Boot application配置 | ## Spring DATASOURCE (DataSource AutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/management?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=posilka2020
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Hibernate Properties
#The SQL dialect makes Hibernate generate better SQL the chosen database
spring. | jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#Hibernate dll auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=create | repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSources\SpringRestAPI\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/ | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
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_A_RegistrationAttribute.java | 1 |
请完成以下Java代码 | public TokenQuery createTokenQuery() {
return commandExecutor.execute(new CreateTokenQueryCmd());
}
@Override
public NativeTokenQuery createNativeTokenQuery() {
return new NativeTokenQueryImpl(commandExecutor);
}
@Override
public void setUserPicture(String userId, Picture picture) {
commandExecutor.execute(new SetUserPictureCmd(userId, picture));
}
@Override
public Picture getUserPicture(String userId) {
return commandExecutor.execute(new GetUserPictureCmd(userId));
}
@Override
public String getUserInfo(String userId, String key) {
return commandExecutor.execute(new GetUserInfoCmd(userId, key));
}
@Override
public List<String> getUserInfoKeys(String userId) {
return commandExecutor.execute(new GetUserInfoKeysCmd(userId, IdentityInfoEntity.TYPE_USERINFO));
}
@Override
public void setUserInfo(String userId, String key, String value) {
commandExecutor.execute(new SetUserInfoCmd(userId, key, value));
}
@Override
public void deleteUserInfo(String userId, String key) {
commandExecutor.execute(new DeleteUserInfoCmd(userId, key));
}
@Override
public Privilege createPrivilege(String name) {
return commandExecutor.execute(new CreatePrivilegeCmd(name, configuration));
}
@Override
public void addUserPrivilegeMapping(String privilegeId, String userId) {
commandExecutor.execute(new AddPrivilegeMappingCmd(privilegeId, userId, null, configuration));
}
@Override
public void deleteUserPrivilegeMapping(String privilegeId, String userId) {
commandExecutor.execute(new DeletePrivilegeMappingCmd(privilegeId, userId, null));
} | @Override
public void addGroupPrivilegeMapping(String privilegeId, String groupId) {
commandExecutor.execute(new AddPrivilegeMappingCmd(privilegeId, null, groupId, configuration));
}
@Override
public void deleteGroupPrivilegeMapping(String privilegeId, String groupId) {
commandExecutor.execute(new DeletePrivilegeMappingCmd(privilegeId, null, groupId));
}
@Override
public List<PrivilegeMapping> getPrivilegeMappingsByPrivilegeId(String privilegeId) {
return commandExecutor.execute(new GetPrivilegeMappingsByPrivilegeIdCmd(privilegeId));
}
@Override
public void deletePrivilege(String id) {
commandExecutor.execute(new DeletePrivilegeCmd(id));
}
@Override
public PrivilegeQuery createPrivilegeQuery() {
return commandExecutor.execute(new CreatePrivilegeQueryCmd());
}
@Override
public List<Group> getGroupsWithPrivilege(String name) {
return commandExecutor.execute(new GetGroupsWithPrivilegeCmd(name));
}
@Override
public List<User> getUsersWithPrivilege(String name) {
return commandExecutor.execute(new GetUsersWithPrivilegeCmd(name));
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\IdmIdentityServiceImpl.java | 1 |
请完成以下Java代码 | public static MStore[] getActive()
{
s_log.info("");
try
{
Collection<MStore> cc = s_cache.values();
Object[] oo = cc.toArray();
for (int i = 0; i < oo.length; i++)
s_log.info(i + ": " + oo[i]);
MStore[] retValue = new MStore[oo.length];
for (int i = 0; i < oo.length; i++)
retValue[i] = (MStore)oo[i];
return retValue;
}
catch (Exception e)
{
s_log.error(e.toString());
}
return new MStore[] {};
} // getActive
/** Cache */
private static CCache<Integer, MStore> s_cache = new CCache<>("W_Store", 2);
/** Logger */
private static Logger s_log = LogManager.getLogger(MStore.class);
/**************************************************************************
* Standard Constructor
*
* @param ctx context
* @param W_Store_ID id
* @param trxName trx
*/
public MStore(Properties ctx, int W_Store_ID, String trxName)
{
super(ctx, W_Store_ID, trxName);
if (W_Store_ID == 0)
{
setIsDefault(false);
setIsMenuAssets(true); // Y
setIsMenuContact(true); // Y
setIsMenuInterests(true); // Y
setIsMenuInvoices(true); // Y
setIsMenuOrders(true); // Y
setIsMenuPayments(true); // Y
setIsMenuRegistrations(true); // Y
setIsMenuRequests(true); // Y
setIsMenuRfQs(true); // Y
setIsMenuShipments(true); // Y
// setC_PaymentTerm_ID (0);
// setM_PriceList_ID (0);
// setM_Warehouse_ID (0);
// setName (null);
// setSalesRep_ID (0);
// setURL (null);
// setWebContext (null);
}
} // MWStore
public MStore(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MWStore
/**
* Get Web Context
*
* @param full if true fully qualified
* @return web context
*/
public String getWebContext(boolean full)
{
if (!full)
return super.getURL();
String url = super.getURL(); | if (url == null || url.length() == 0)
url = "http://localhost";
if (url.endsWith("/"))
url += url.substring(0, url.length() - 1);
return url + getWebContext(); // starts with /
} // getWebContext
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("WStore[");
sb.append(getWebContext(true))
.append("]");
return sb.toString();
} // toString
@Override
protected boolean beforeSave(boolean newRecord)
{
// Context to start with /
if (!getWebContext().startsWith("/"))
setWebContext("/" + getWebContext());
// Org to Warehouse
if (newRecord || is_ValueChanged("M_Warehouse_ID") || getAD_Org_ID() <= 0)
{
final I_M_Warehouse wh = Services.get(IWarehouseDAO.class).getById(WarehouseId.ofRepoId(getM_Warehouse_ID()));
setAD_Org_ID(wh.getAD_Org_ID());
}
String url = getURL();
if (url == null)
url = "";
boolean urlOK = url.startsWith("http://") || url.startsWith("https://");
if (!urlOK) // || url.indexOf("localhost") != -1)
{
throw new FillMandatoryException("URL");
}
return true;
} // beforeSave
} // MWStore | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MStore.java | 1 |
请完成以下Java代码 | public void setDiscount (java.math.BigDecimal Discount)
{
set_Value (COLUMNNAME_Discount, Discount);
}
/** Get Rabatt %.
@return Abschlag in Prozent
*/
@Override
public java.math.BigDecimal getDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Aufschlag auf Standardpreis.
@param Std_AddAmt
Amount added to a price as a surcharge | */
@Override
public void setStd_AddAmt (java.math.BigDecimal Std_AddAmt)
{
set_Value (COLUMNNAME_Std_AddAmt, Std_AddAmt);
}
/** Get Aufschlag auf Standardpreis.
@return Amount added to a price as a surcharge
*/
@Override
public java.math.BigDecimal getStd_AddAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Std_AddAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PriceLimit_Restriction.java | 1 |
请完成以下Java代码 | public class AbstractInexactAction implements Comparable<AbstractInexactAction>
{
int seed;
public AbstractInexactAction()
{
}
/**
* Constructor for inexact action. Empirically, the number of name
* is less than 32. So such inexact action type compile the action
* name and action type into a single integer.
*
* @param name The name for the action.
* @param rel The dependency relation.
*/
AbstractInexactAction(int name, int rel)
{
seed = rel << 6 | name;
}
public int compareTo(AbstractInexactAction o)
{ | return new Integer(seed).compareTo(o.seed);
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof AbstractInexactAction)) return false;
AbstractInexactAction o = (AbstractInexactAction) obj;
return seed == o.seed;
}
public int name()
{
return (seed & 0x3f);
}
public int rel()
{
return (seed >> 6);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\action\AbstractInexactAction.java | 1 |
请完成以下Java代码 | public static void unclosedProducerAndReinitialize() {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("client.id", "my-producer");
props.put("key.serializer", StringSerializer.class);
props.put("value.serializer", StringSerializer.class);
KafkaProducer<String, String> producer1 = new KafkaProducer<>(props);
// Attempting to reinitialize without proper close
producer1 = new KafkaProducer<>(props);
}
}
class MyMBean implements DynamicMBean {
@Override
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
return null;
}
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
}
@Override
public AttributeList getAttributes(String[] attributes) {
return null;
} | @Override
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
return null;
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo[] attributes = new MBeanAttributeInfo[0];
MBeanConstructorInfo[] constructors = new MBeanConstructorInfo[0];
MBeanOperationInfo[] operations = new MBeanOperationInfo[0];
MBeanNotificationInfo[] notifications = new MBeanNotificationInfo[0];
return new MBeanInfo(MyMBean.class.getName(), "My MBean", attributes, constructors, operations, notifications);
}
} | repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\kafkaexception\SimulateInstanceAlreadyExistsException.java | 1 |
请完成以下Java代码 | public void setIsDefaultForPicking (final boolean IsDefaultForPicking)
{
set_Value (COLUMNNAME_IsDefaultForPicking, IsDefaultForPicking);
}
@Override
public boolean isDefaultForPicking()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefaultForPicking);
}
@Override
public void setIsDefaultLU (final boolean IsDefaultLU)
{
set_Value (COLUMNNAME_IsDefaultLU, IsDefaultLU);
}
@Override
public boolean isDefaultLU()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefaultLU);
}
@Override
public void setM_HU_PI_ID (final int M_HU_PI_ID)
{
if (M_HU_PI_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); | }
@Override
public int getM_HU_PI_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected @Nullable <T> T invokeMethod(@NonNull Object target, @NonNull String methodName, Object... args) {
ExceptionThrowingOperation<T> operation = () ->
ObjectUtils.findMethod(target.getClass(), methodName, args)
.map(ObjectUtils::makeAccessible)
.map(method -> (T) ReflectionUtils.invokeMethod(method,
ObjectUtils.resolveInvocationTarget(target, method), args))
.orElse(null);
Function<Throwable, T> exceptionHandlingFunction = cause -> null;
return ObjectUtils.doOperationSafely(operation, exceptionHandlingFunction);
}
protected RestTemplate registerInterceptor(RestTemplate restTemplate,
ClientHttpRequestInterceptor clientHttpRequestInterceptor) {
restTemplate.getInterceptors().add(clientHttpRequestInterceptor);
return restTemplate;
}
public static class SecurityAwareClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final Environment environment;
public SecurityAwareClientHttpRequestInterceptor(Environment environment) {
Assert.notNull(environment, "Environment is required");
this.environment = environment;
}
protected boolean isAuthenticationEnabled() {
return StringUtils.hasText(getUsername()) && StringUtils.hasText(getPassword());
} | protected String getUsername() {
return this.environment.getProperty(SPRING_DATA_GEMFIRE_SECURITY_USERNAME_PROPERTY);
}
protected String getPassword() {
return this.environment.getProperty(SPRING_DATA_GEMFIRE_SECURITY_PASSWORD_PROPERTY);
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
if (isAuthenticationEnabled()) {
HttpHeaders requestHeaders = request.getHeaders();
requestHeaders.add(GeodeConstants.USERNAME, getUsername());
requestHeaders.add(GeodeConstants.PASSWORD, getPassword());
}
return execution.execute(request, body);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\HttpBasicAuthenticationSecurityConfiguration.java | 2 |
请完成以下Java代码 | public static HUReceiptScheduleReportExecutor get(final I_M_ReceiptSchedule receiptSchedule)
{
return new HUReceiptScheduleReportExecutor(receiptSchedule);
}
/**
* Give this service a window number. The default is {@link Env#WINDOW_None}.
*/
public HUReceiptScheduleReportExecutor withWindowNo(final int windowNo)
{
this.windowNo = windowNo;
return this;
}
public void executeHUReport()
{
final I_C_OrderLine orderLine = receiptSchedule.getC_OrderLine();
//
// service
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
//
// Get Process from SysConfig
final int reportProcessId = sysConfigBL.getIntValue(SYSCONFIG_ReceiptScheduleHUPOSJasper_Process,
-1, // default
receiptSchedule.getAD_Client_ID(),
receiptSchedule.getAD_Org_ID());
Check.errorIf(reportProcessId <= 0, "Report SysConfig value not set for for {}", SYSCONFIG_ReceiptScheduleHUPOSJasper_Process);
//
// get number of copies from SysConfig (default=1)
final PrintCopies copies = PrintCopies.ofInt(sysConfigBL.getIntValue(SYSCONFIG_ReceiptScheduleHUPOSJasper_Copies,
1, // default
receiptSchedule.getAD_Client_ID(),
receiptSchedule.getAD_Org_ID()));
final Properties ctx = InterfaceWrapperHelper.getCtx(receiptSchedule);
Check.assumeNotNull(orderLine, "orderLine not null");
final int orderLineId = orderLine.getC_OrderLine_ID();
final I_C_Order order = orderLine.getC_Order(); | final Language bpartnerLaguage = Services.get(IBPartnerBL.class).getLanguage(ctx, order.getC_BPartner_ID());
//
// Create ProcessInfo
ProcessInfo.builder()
.setCtx(ctx)
.setAD_Process_ID(reportProcessId)
.setProcessCalledFrom(ProcessCalledFrom.WebUI)
// .setAD_PInstance_ID() // NO AD_PInstance => we want a new instance
.setRecord(I_C_OrderLine.Table_Name, orderLineId)
.setWindowNo(windowNo)
.setReportLanguage(bpartnerLaguage)
.addParameter(PARA_C_Orderline_ID, orderLineId)
.addParameter(PARA_AD_Table_ID, InterfaceWrapperHelper.getTableId(I_C_OrderLine.class))
.addParameter(IMassPrintingService.PARAM_PrintCopies, copies.toInt())
//
// Execute report in a new AD_PInstance
.buildAndPrepareExecution()
.onErrorThrowException()
.executeSync();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\HUReceiptScheduleReportExecutor.java | 1 |
请完成以下Java代码 | public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getDetailAddress() {
return detailAddress;
}
public void setDetailAddress(String detailAddress) {
this.detailAddress = detailAddress;
}
@Override
public String toString() { | StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", addressName=").append(addressName);
sb.append(", sendStatus=").append(sendStatus);
sb.append(", receiveStatus=").append(receiveStatus);
sb.append(", name=").append(name);
sb.append(", phone=").append(phone);
sb.append(", province=").append(province);
sb.append(", city=").append(city);
sb.append(", region=").append(region);
sb.append(", detailAddress=").append(detailAddress);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCompanyAddress.java | 1 |
请完成以下Java代码 | public static PaymentReconcileReference bankStatementLineRef(@NonNull final BankStatementAndLineAndRefId bankStatementLineRefId)
{
return bankStatementLineRef(
bankStatementLineRefId.getBankStatementId(),
bankStatementLineRefId.getBankStatementLineId(),
bankStatementLineRefId.getBankStatementLineRefId());
}
public static PaymentReconcileReference bankStatementLineRef(
@NonNull final BankStatementId bankStatementId,
@NonNull final BankStatementLineId bankStatementLineId,
@NonNull final BankStatementLineRefId bankStatementLineRefId)
{
return new PaymentReconcileReference(
Type.BANK_STATEMENT_LINE_REF,
bankStatementId,
bankStatementLineId,
bankStatementLineRefId,
null,
null);
}
public static PaymentReconcileReference reversal(@NonNull final PaymentId reversalId)
{
return new PaymentReconcileReference(
Type.REVERSAL,
null,
null, | null,
reversalId,
null);
}
public static PaymentReconcileReference glJournalLine(@NonNull final SAPGLJournalLineId glJournalLineId)
{
return new PaymentReconcileReference(
Type.GL_Journal,
null,
null,
null,
null,
glJournalLineId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\PaymentReconcileReference.java | 1 |
请完成以下Java代码 | public BigDecimal getTotalOfOrderExcludingDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalOfOrderExcludingDiscount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
@Override
public void setUserElementString2 (final @Nullable java.lang.String UserElementString2)
{
set_Value (COLUMNNAME_UserElementString2, UserElementString2);
}
@Override
public java.lang.String getUserElementString2()
{
return get_ValueAsString(COLUMNNAME_UserElementString2);
}
@Override
public void setUserElementString3 (final @Nullable java.lang.String UserElementString3)
{
set_Value (COLUMNNAME_UserElementString3, UserElementString3);
}
@Override
public java.lang.String getUserElementString3()
{
return get_ValueAsString(COLUMNNAME_UserElementString3);
}
@Override
public void setUserElementString4 (final @Nullable java.lang.String UserElementString4)
{
set_Value (COLUMNNAME_UserElementString4, UserElementString4);
}
@Override
public java.lang.String getUserElementString4()
{
return get_ValueAsString(COLUMNNAME_UserElementString4);
}
@Override
public void setUserElementString5 (final @Nullable java.lang.String UserElementString5)
{ | set_Value (COLUMNNAME_UserElementString5, UserElementString5);
}
@Override
public java.lang.String getUserElementString5()
{
return get_ValueAsString(COLUMNNAME_UserElementString5);
}
@Override
public void setUserElementString6 (final @Nullable java.lang.String UserElementString6)
{
set_Value (COLUMNNAME_UserElementString6, UserElementString6);
}
@Override
public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate.java | 1 |
请完成以下Java代码 | public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbEntityManager().selectListWithRawParameter("selectHistoricActivityInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbEntityManager().selectOne("selectHistoricActivityInstanceCountByNativeQuery", parameterMap);
}
protected void configureQuery(HistoricActivityInstanceQueryImpl query) {
getAuthorizationManager().configureHistoricActivityInstanceQuery(query);
getTenantManager().configureQuery(query);
}
public DbOperation addRemovalTimeToActivityInstancesByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("rootProcessInstanceId", rootProcessInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(HistoricActivityInstanceEventEntity.class, "updateHistoricActivityInstancesByRootProcessInstanceId", parameters);
}
public DbOperation addRemovalTimeToActivityInstancesByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize); | return getDbEntityManager()
.updatePreserveOrder(HistoricActivityInstanceEventEntity.class, "updateHistoricActivityInstancesByProcessInstanceId", parameters);
}
public DbOperation deleteHistoricActivityInstancesByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(HistoricActivityInstanceEntity.class, "deleteHistoricActivityInstancesByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricActivityInstanceManager.java | 1 |
请完成以下Java代码 | int transform(Action act)
{
int deprel = 0;
int[] deprel_inference = new int[]{deprel};
if (ActionUtils.is_shift(act))
{
return 0;
}
else if (ActionUtils.is_left_arc(act, deprel_inference))
{
deprel = deprel_inference[0];
return 1 + deprel;
}
else if (ActionUtils.is_right_arc(act, deprel_inference))
{
deprel = deprel_inference[0];
return L + 1 + deprel;
}
else
{
System.err.printf("unknown transition in transform(Action): %d-%d", act.name(), act.rel());
}
return -1;
}
/**
* 转换动作id为动作
* @param act 动作类型的依存关系id
* @return 动作
*/ | Action transform(int act)
{
if (act == 0)
{
return ActionFactory.make_shift();
}
else if (act < 1 + L)
{
return ActionFactory.make_left_arc(act - 1);
}
else if (act < 1 + 2 * L)
{
return ActionFactory.make_right_arc(act - 1 - L);
}
else
{
System.err.printf("unknown transition in transform(int): %d", act);
}
return new Action();
}
int number_of_transitions()
{
return L * 2 + 1;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\TransitionSystem.java | 1 |
请完成以下Java代码 | public class AutomaticallyInvoicePdfPrintinAsyncBatchListener implements IAsyncBatchListener
{
private static final AdMessageKey MSG_Event_PDFGenerated = AdMessageKey.of("AutomaticallyInvoicePdfPrintinAsyncBatchListener_Pdf_Done");
private static final AdWindowId WINDOW_ID_C_Async_Batch = AdWindowId.ofRepoId(540231);
// services
private final IAsyncBatchBL asyncBatchBL = Services.get(IAsyncBatchBL.class);
private final INotificationBL notificationBL = Services.get(INotificationBL.class);
@Override
public void createNotice(@NonNull final I_C_Async_Batch asyncBatch)
{
if(asyncBatchBL.isAsyncBatchTypeInternalName(asyncBatch, Async_Constants.C_Async_Batch_InternalName_AutomaticallyInvoicePdfPrinting))
{
sendUserNotifications(asyncBatch);
} | }
private void sendUserNotifications(@NonNull final I_C_Async_Batch asyncBatch)
{
final TableRecordReference asyncBatchItemRef = TableRecordReference.of(asyncBatch);
notificationBL.send(UserNotificationRequest.builder()
.topic(Printing_Constants.USER_NOTIFICATIONS_TOPIC)
.recipientUserId(UserId.ofRepoId(asyncBatch.getCreatedBy()))
.contentADMessage(MSG_Event_PDFGenerated)
.contentADMessageParam(asyncBatch.getCountProcessed())
.targetAction(TargetRecordAction.ofRecordAndWindow(asyncBatchItemRef, WINDOW_ID_C_Async_Batch))
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\async\spi\impl\AutomaticallyInvoicePdfPrintinAsyncBatchListener.java | 1 |
请完成以下Spring Boot application配置 | server.port=8080
# 主数据源,默认的
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.url=jdbc:mysql://localhost:3306/sakila
spring.datasource.primary.username=root
spring.datasource.primary.password=root123
# 更多数据源
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/world
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root123
# 初始化大小,最小,最大
#最小连接数量
spring.datasource.primary.minIdle=2
spring.datasource.primary.maxActive=5
spring.datasource.primary.maxWait=60000
spring.datasource.primary.timeBetweenEvictionRunsMillis=60000
spring.datasource.primary.minEvictableIdleTimeMillis=300000
spring.datasource.primary.validationQuery=SELECT 'x' FROM DUAL
spring.datasource.primary.testWhileIdle=true
spring.datasource.primary.testOnBorrow=false
spring.datasource.primary.testOnReturn=false
spring.datasource.primary.poolPreparedStatements=true
spring.datasource.primary.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.primary.filters=stat
# 初始化大小,最小,最大
spring.datasource.secondary.minIdle=2
spring.datasource.secondary.maxActive=5
spring.datasource.secondary.maxWait=60000
spring.datasource.secondary.timeBetweenEvictionRunsMillis=60000
spring.datasource.secondar | y.minEvictableIdleTimeMillis=300000
spring.datasource.secondary.validationQuery=SELECT 'x' FROM DUAL
spring.datasource.secondary.testWhileIdle=true
spring.datasource.secondary.testOnBorrow=false
spring.datasource.secondary.testOnReturn=false
spring.datasource.secondary.poolPreparedStatements=true
spring.datasource.secondary.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.secondary.filters=stat
## Mybatis 配置
#mybatis.typeAliasesPackage=com.quick.mulit.entity
#mybatis.mapperLocations=classpath:mapper/*/*.xml
spring.datasource.maximum-pool-size=80 | repos\spring-boot-quick-master\quick-multi-data\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private IQueryBuilder<I_M_ShippingPackage> toShippingPackageQueryBuilder(final @NonNull ShippingPackageQuery query)
{
if(query.getOrderIds().isEmpty() && query.getOrderLineIds().isEmpty())
{
return queryBL.createQueryBuilder(I_M_ShippingPackage.class)
.filter(ConstantQueryFilter.of(false));
}
final IQueryBuilder<I_M_ShippingPackage> builder = queryBL.createQueryBuilder(I_M_ShippingPackage.class)
.addOnlyActiveRecordsFilter();
final Collection<OrderId> orderIds = query.getOrderIds();
if (!orderIds.isEmpty())
{
builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_Order_ID, orderIds); | }
final Collection<OrderLineId> orderLineIds = query.getOrderLineIds();
if (!orderLineIds.isEmpty())
{
builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_OrderLine_ID, orderLineIds);
}
return builder;
}
public void deleteBy(@NonNull final ShippingPackageQuery query)
{
deleteFromShipperTransportation(toPackageSqlQuery(query).listIds(PackageId::ofRepoId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\PurchaseOrderToShipperTransportationRepository.java | 1 |
请完成以下Java代码 | public ResponseEntity<UserDto> getUserWithDefaultCaching(@PathVariable String name) {
return ResponseEntity.ok(new UserDto(name));
}
@GetMapping("/users/{name}")
public ResponseEntity<UserDto> getUser(@PathVariable String name) {
return ResponseEntity
.ok()
.cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS))
.body(new UserDto(name));
}
@GetMapping("/timestamp")
public ResponseEntity<TimestampDto> getServerTimestamp() {
return ResponseEntity | .ok()
.cacheControl(CacheControl.noStore())
.body(new TimestampDto(LocalDateTime
.now()
.toInstant(ZoneOffset.UTC)
.toEpochMilli()));
}
@GetMapping("/private/users/{name}")
public ResponseEntity<UserDto> getUserNotCached(@PathVariable String name) {
return ResponseEntity
.ok()
.body(new UserDto(name));
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\cachecontrol\ResourceEndpoint.java | 1 |
请完成以下Java代码 | public void setWEBUI_NameBrowse(final String webuiNameBrowse)
{
this.webuiNameBrowse = webuiNameBrowse;
}
public String getWEBUI_NameBrowse()
{
return webuiNameBrowse;
}
public void setWEBUI_NameNew(final String webuiNameNew)
{
this.webuiNameNew = webuiNameNew;
}
public String getWEBUI_NameNew()
{
return webuiNameNew;
}
public void setWEBUI_NameNewBreadcrumb(final String webuiNameNewBreadcrumb)
{
this.webuiNameNewBreadcrumb = webuiNameNewBreadcrumb;
}
public String getWEBUI_NameNewBreadcrumb()
{
return webuiNameNewBreadcrumb;
} | /**
* @param mainTableName table name of main tab or null
*/
public void setMainTableName(String mainTableName)
{
this.mainTableName = mainTableName;
}
/**
* @return table name of main tab or null
*/
public String getMainTableName()
{
return mainTableName;
}
} // MTreeNode | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTreeNode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyBatisOrdersConfig {
/**
* 创建 orders 数据源
*/
@Bean(name = "ordersDataSource")
@ConfigurationProperties(prefix = "spring.datasource.orders")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
/**
* 创建 MyBatis SqlSessionFactory
*/
@Bean(name = "ordersSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
// 设置 orders 数据源
bean.setDataSource(this.dataSource());
// 设置 entity 所在包
bean.setTypeAliasesPackage("cn.iocoder.springboot.lab17.dynamicdatasource.dataobject");
// 设置 config 路径 | bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
// 设置 mapper 路径
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/orders/*.xml"));
return bean.getObject();
}
/**
* 创建 MyBatis SqlSessionTemplate
*/
@Bean(name = "ordersSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(this.sqlSessionFactory());
}
/**
* 创建 orders 数据源的 TransactionManager 事务管理器
*/
@Bean(name = DBConstants.TX_MANAGER_ORDERS)
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(this.dataSource());
}
} | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-mybatis\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\config\MyBatisOrdersConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping {
private static final Log logger = LogFactory.getLog(WelcomePageHandlerMapping.class);
private static final List<MediaType> MEDIA_TYPES_ALL = Collections.singletonList(MediaType.ALL);
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
ApplicationContext applicationContext, @Nullable Resource indexHtmlResource, String staticPathPattern) {
setOrder(2);
WelcomePage welcomePage = WelcomePage.resolve(templateAvailabilityProviders, applicationContext,
indexHtmlResource, staticPathPattern);
if (welcomePage != WelcomePage.UNRESOLVED) {
logger.info(LogMessage.of(() -> (!welcomePage.isTemplated()) ? "Adding welcome page: " + indexHtmlResource
: "Adding welcome page template: index"));
ParameterizableViewController controller = new ParameterizableViewController();
controller.setViewName(welcomePage.getViewName());
setRootHandler(controller);
}
}
@Override
public @Nullable Object getHandlerInternal(HttpServletRequest request) throws Exception {
return (!isHtmlTextAccepted(request)) ? null : super.getHandlerInternal(request);
}
private boolean isHtmlTextAccepted(HttpServletRequest request) {
for (MediaType mediaType : getAcceptedMediaTypes(request)) {
if (mediaType.includes(MediaType.TEXT_HTML)) {
return true;
}
}
return false;
} | private List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) {
String acceptHeader = request.getHeader(HttpHeaders.ACCEPT);
if (StringUtils.hasText(acceptHeader)) {
try {
return MediaType.parseMediaTypes(acceptHeader);
}
catch (InvalidMediaTypeException ex) {
logger.warn("Received invalid Accept header. Assuming all media types are accepted",
logger.isDebugEnabled() ? ex : null);
}
}
return MEDIA_TYPES_ALL;
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\WelcomePageHandlerMapping.java | 2 |
请完成以下Java代码 | public StripVersion getStripVersion() {
return stripVersion;
}
public Config setStripVersion(StripVersion stripVersion) {
this.stripVersion = stripVersion;
return this;
}
public String getLocationHeaderName() {
return locationHeaderName;
}
public Config setLocationHeaderName(String locationHeaderName) {
this.locationHeaderName = locationHeaderName;
return this;
}
public @Nullable String getHostValue() {
return hostValue;
}
public Config setHostValue(String hostValue) {
this.hostValue = hostValue;
return this;
}
public String getProtocols() {
return protocols;
} | public Config setProtocols(String protocols) {
this.protocols = protocols;
this.hostPortPattern = compileHostPortPattern(protocols);
this.hostPortVersionPattern = compileHostPortVersionPattern(protocols);
return this;
}
public Pattern getHostPortPattern() {
return hostPortPattern;
}
public Pattern getHostPortVersionPattern() {
return hostPortVersionPattern;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteLocationResponseHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) {
addActivityHandlers(activity);
}
public void parseIntermediateMessageCatchEventDefinition(Element messageEventDefinition, ActivityImpl nestedActivity) {
}
public void parseBoundaryMessageEventDefinition(Element element, boolean interrupting, ActivityImpl messageActivity) {
}
public void parseBoundaryEscalationEventDefinition(Element escalationEventDefinition, boolean interrupting, ActivityImpl boundaryEventActivity) {
}
public void parseBoundaryConditionalEventDefinition(Element element, boolean interrupting, ActivityImpl conditionalActivity) {
}
public void parseIntermediateConditionalEventDefinition(Element conditionalEventDefinition, ActivityImpl conditionalActivity) {
}
public void parseConditionalStartEventForEventSubprocess(Element element, ActivityImpl conditionalActivity, boolean interrupting) {
} | @Override
public void parseIoMapping(Element extensionElements, ActivityImpl activity, IoMapping inputOutput) {
}
// helper methods ///////////////////////////////////////////////////////////
protected void addActivityHandlers(ActivityImpl activity) {
ensureHistoryLevelInitialized();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.ACTIVITY_INSTANCE_START, null)) {
activity.addBuiltInListener(PvmEvent.EVENTNAME_START, ACTIVITY_INSTANCE_START_LISTENER, 0);
}
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.ACTIVITY_INSTANCE_END, null)) {
activity.addBuiltInListener(PvmEvent.EVENTNAME_END, ACTIVITY_INSTANCE_END_LISTENER);
}
}
protected void ensureHistoryLevelInitialized() {
if (historyLevel == null) {
historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\parser\HistoryParseListener.java | 1 |
请完成以下Java代码 | public long getFirstResult() {
return firstResult;
}
public void setFirstResult(long firstResult) {
this.firstResult = firstResult;
}
public void setRows(List<Map<String, Object>> rowData) {
this.rowData = rowData;
}
/**
* @return the actual table content.
*/
public List<Map<String, Object>> getRows() {
return rowData;
}
public void setTotal(long total) { | this.total = total;
}
/**
* @return the total rowcount of the table from which this page is only a subset.
*/
public long getTotal() {
return total;
}
/**
* @return the actual number of rows in this page.
*/
public long getSize() {
return rowData.size();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\management\TablePage.java | 1 |
请完成以下Java代码 | public void set(int index, String value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Boolean value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Short value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Integer value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Long value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, Double value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, BigDecimal value) {
jsonNode.set(index, value);
}
@Override
public void set(int index, BigInteger value) {
jsonNode.set(index, value);
}
@Override
public void setNull(int index) {
jsonNode.setNull(index);
}
@Override
public void set(int index, FlowableJsonNode value) {
jsonNode.set(index, asJsonNode(value));
}
@Override
public void add(Short value) {
jsonNode.add(value);
}
@Override
public void add(Integer value) {
jsonNode.add(value);
}
@Override
public void add(Long value) {
jsonNode.add(value);
}
@Override
public void add(Float value) { | jsonNode.add(value);
}
@Override
public void add(Double value) {
jsonNode.add(value);
}
@Override
public void add(byte[] value) {
jsonNode.add(value);
}
@Override
public void add(String value) {
jsonNode.add(value);
}
@Override
public void add(Boolean value) {
jsonNode.add(value);
}
@Override
public void add(BigDecimal value) {
jsonNode.add(value);
}
@Override
public void add(BigInteger value) {
jsonNode.add(value);
}
@Override
public void add(FlowableJsonNode value) {
jsonNode.add(asJsonNode(value));
}
@Override
public void addNull() {
jsonNode.addNull();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\json\jackson2\FlowableJackson2ArrayNode.java | 1 |
请完成以下Java代码 | public String getDiagramResourceName() {
return diagramResourceName;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public boolean hasStartFormKey() {
return hasStartFormKey;
}
@Override
public boolean getHasStartFormKey() {
return hasStartFormKey;
}
@Override
public void setStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public boolean isGraphicalNotationDefined() {
return isGraphicalNotationDefined;
}
@Override
public boolean hasGraphicalNotation() {
return isGraphicalNotationDefined;
}
public boolean getIsGraphicalNotationDefined() {
return isGraphicalNotationDefined;
}
public void setIsGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
@Override
public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
@Override
public int getSuspensionState() {
return suspensionState;
}
@Override
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState; | }
@Override
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
@Override
public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
}
@Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
}
@Override
public int getDerivedVersion() {
return derivedVersion;
}
@Override
public void setDerivedVersion(int derivedVersion) {
this.derivedVersion = derivedVersion;
}
@Override
public String getEngineVersion() {
return engineVersion;
}
@Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
@Override
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | private final boolean isEditable()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
return textComponent.isEditable() && textComponent.isEnabled();
}
private final boolean hasTextToCopy()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
// Document document = textComponent.getDocument();
// final JComboBox<?> comboBox = getComboBox();
// final ComboBoxEditor editor = comboBox.getEditor();
// comboBox.getClass().getMethod("getDisplay").invoke(comboBox);
final String selectedText = textComponent.getSelectedText();
return selectedText != null && !selectedText.isEmpty();
}
private final boolean isEmpty()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return false;
}
final String text = textComponent.getText();
return Check.isEmpty(text, false);
}
private void doCopy()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.copy();
}
private void doCut()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null) | {
return;
}
textComponent.cut();
}
private void doPaste()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.paste();
}
private void doSelectAll()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
// NOTE: we need to request focus first because it seems in some case the code below is not working when the component does not have the focus.
textComponent.requestFocus();
textComponent.selectAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JComboBoxCopyPasteSupportEditor.java | 1 |
请完成以下Java代码 | public class JimuReportTokenService implements JmReportTokenServiceI {
@Autowired
private SysBaseApiImpl sysBaseApi;
@Autowired
@Lazy
private RedisUtil redisUtil;
@Override
public String getToken(HttpServletRequest request) {
return TokenUtils.getTokenByRequest(request);
}
@Override
public String getUsername(String token) {
return JwtUtil.getUsername(token);
}
@Override
public String[] getRoles(String token) {
String username = JwtUtil.getUsername(token);
Set roles = sysBaseApi.getUserRoleSet(username);
if(CollectionUtils.isEmpty(roles)){
return null;
}
return (String[]) roles.toArray(new String[roles.size()]);
}
@Override
public Boolean verifyToken(String token) {
return TokenUtils.verifyToken(token, sysBaseApi, redisUtil);
}
@Override
public Map<String, Object> getUserInfo(String token) {
Map<String, Object> map = new HashMap(5);
String username = JwtUtil.getUsername(token);
//此处通过token只能拿到一个信息 用户账号 后面的就是根据账号获取其他信息 查询数据或是走redis 用户根据自身业务可自定义
SysUserCacheInfo userInfo = null;
try {
userInfo = sysBaseApi.getCacheUser(username);
} catch (Exception e) {
log.error("获取用户信息异常:"+ e.getMessage());
return map;
}
//设置账号名
map.put(SYS_USER_CODE, userInfo.getSysUserCode());
//设置部门编码
map.put(SYS_ORG_CODE, userInfo.getSysOrgCode());
// 将所有信息存放至map 解析sql/api会根据map的键值解析 | return map;
}
/**
* 将jeecgboot平台的权限传递给积木报表
* @param token
* @return
*/
@Override
public String[] getPermissions(String token) {
// 获取用户信息
String username = JwtUtil.getUsername(token);
SysUserCacheInfo userInfo = null;
try {
userInfo = sysBaseApi.getCacheUser(username);
} catch (Exception e) {
log.error("获取用户信息异常:"+ e.getMessage());
}
if(userInfo == null){
return null;
}
// 查询权限
Set<String> userPermissions = sysBaseApi.getUserPermissionSet(userInfo.getSysUserId());
if(CollectionUtils.isEmpty(userPermissions)){
return null;
}
return userPermissions.toArray(new String[0]);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\config\jimureport\JimuReportTokenService.java | 1 |
请完成以下Java代码 | /* package */class FixedMapSessionRepository implements SessionRepository<MapSession>
{
private static final Logger logger = LogManager.getLogger(FixedMapSessionRepository.class);
private final Map<String, MapSession> sessions = new ConcurrentHashMap<>();
private final ApplicationEventPublisher applicationEventPublisher;
private final Duration defaultMaxInactiveInterval;
@Builder
private FixedMapSessionRepository(
@NonNull final ApplicationEventPublisher applicationEventPublisher,
@Nullable final Duration defaultMaxInactiveInterval)
{
this.applicationEventPublisher = applicationEventPublisher;
this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
}
@Override
public void save(final MapSession session)
{
sessions.put(session.getId(), new MapSession(session));
}
@Override
public MapSession findById(final String id)
{
final MapSession saved = sessions.get(id);
if (saved == null)
{
return null;
}
if (saved.isExpired())
{
final boolean expired = true;
deleteAndFireEvent(saved.getId(), expired);
return null;
}
return new MapSession(saved);
}
@Override
public void deleteById(final String id)
{
final boolean expired = false;
deleteAndFireEvent(id, expired);
}
private void deleteAndFireEvent(final String id, boolean expired)
{
final MapSession deletedSession = sessions.remove(id);
// Fire event
if (deletedSession != null)
{
if (expired)
{
applicationEventPublisher.publishEvent(new SessionExpiredEvent(this, deletedSession));
}
else
{
applicationEventPublisher.publishEvent(new SessionDeletedEvent(this, deletedSession));
}
}
}
@Override
public MapSession createSession()
{
final MapSession result = new MapSession();
if (defaultMaxInactiveInterval != null)
{
result.setMaxInactiveInterval(defaultMaxInactiveInterval); | }
// Fire event
applicationEventPublisher.publishEvent(new SessionCreatedEvent(this, result));
return result;
}
public void purgeExpiredSessionsNoFail()
{
try
{
purgeExpiredSessions();
}
catch (final Throwable ex)
{
logger.warn("Failed purging expired sessions. Ignored.", ex);
}
}
public void purgeExpiredSessions()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
int countExpiredSessions = 0;
final List<MapSession> sessionsToCheck = new ArrayList<>(sessions.values());
for (final MapSession session : sessionsToCheck)
{
if (session.isExpired())
{
deleteAndFireEvent(session.getId(), true /* expired */);
countExpiredSessions++;
}
}
logger.debug("Purged {}/{} expired sessions in {}", countExpiredSessions, sessionsToCheck.size(), stopwatch);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\FixedMapSessionRepository.java | 1 |
请完成以下Java代码 | public Integer getDivisionId() {
return divisionId;
}
public void setDivisionId(Integer divisionId) {
this.divisionId = divisionId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} | public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public Integer getIsLdap() {
return isLdap;
}
public void setIsLdap(Integer isLdap) {
this.isLdap = isLdap;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
} | repos\springBoot-master\springboot-jpa\src\main\java\com\us\example\bean\User.java | 1 |
请完成以下Java代码 | public String getNewsCoverImage() {
return newsCoverImage;
}
public void setNewsCoverImage(String newsCoverImage) {
this.newsCoverImage = newsCoverImage == null ? null : newsCoverImage.trim();
}
public Byte getNewsStatus() {
return newsStatus;
}
public void setNewsStatus(Byte newsStatus) {
this.newsStatus = newsStatus;
}
public Long getNewsViews() {
return newsViews;
}
public void setNewsViews(Long newsViews) {
this.newsViews = newsViews;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) { | this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", newsId=").append(newsId);
sb.append(", newsTitle=").append(newsTitle);
sb.append(", newsCategoryId=").append(newsCategoryId);
sb.append(", newsCoverImage=").append(newsCoverImage);
sb.append(", newsStatus=").append(newsStatus);
sb.append(", newsViews=").append(newsViews);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\News.java | 1 |
请完成以下Java代码 | public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
String destinationUrl = ServletUriComponentsBuilder.fromRequest(request)
.host(null)
.scheme(null)
.port(null)
.toUriString();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Starting new session (if required) and redirecting to '" + destinationUrl + "'");
}
if (this.createNewSession) {
request.getSession();
}
this.redirectStrategy.sendRedirect(request, response, destinationUrl);
}
/**
* Determines whether a new session should be created before redirecting (to avoid
* possible looping issues where the same session ID is sent with the redirected
* request). Alternatively, ensure that the configured URL does not pass through the | * {@code SessionManagementFilter}.
* @param createNewSession defaults to {@code true}.
*/
public void setCreateNewSession(boolean createNewSession) {
this.createNewSession = createNewSession;
}
/**
* Sets the redirect strategy to use. The default is {@link DefaultRedirectStrategy}.
* @param redirectStrategy the redirect strategy to use.
* @since 6.2
*/
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
Assert.notNull(redirectStrategy, "redirectStrategy cannot be null");
this.redirectStrategy = redirectStrategy;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\RequestedUrlRedirectInvalidSessionStrategy.java | 1 |
请完成以下Java代码 | public DmnTransformException unableToFindAnyDecisionTable() {
return new DmnTransformException(exceptionMessage(
"009",
"Unable to find any decision table in model.")
);
}
public DmnDecisionResultException decisionOutputHasMoreThanOneValue(DmnDecisionResultEntries result) {
return new DmnDecisionResultException(exceptionMessage(
"010",
"Unable to get single decision result entry as it has more than one entry '{}'", result)
);
}
public DmnDecisionResultException decisionResultHasMoreThanOneOutput(DmnDecisionResult decisionResult) {
return new DmnDecisionResultException(exceptionMessage(
"011",
"Unable to get single decision result as it has more than one result '{}'", decisionResult) | );
}
public DmnEngineException decisionLogicTypeNotSupported(DmnDecisionLogic decisionLogic) {
return new DmnEngineException(exceptionMessage(
"012",
"Decision logic type '{}' not supported by DMN engine.", decisionLogic.getClass())
);
}
public DmnEngineException decisionIsNotADecisionTable(DmnDecision decision) {
return new DmnEngineException(exceptionMessage(
"013",
"The decision '{}' is not implemented as decision table.", decision)
);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnEngineLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPOSTALCODE(String value) {
this.postalcode = value;
}
/**
* Gets the value of the area property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAREA() {
return area;
}
/**
* Sets the value of the area property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAREA(String value) {
this.area = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCOUNTRY() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCOUNTRY(String value) {
this.country = value;
}
/**
* Gets the value of the locationcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONCODE() {
return locationcode;
}
/**
* Sets the value of the locationcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONCODE(String value) {
this.locationcode = value;
} | /**
* Gets the value of the locationname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONNAME() {
return locationname;
}
/**
* Sets the value of the locationname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONNAME(String value) {
this.locationname = value;
}
/**
* Gets the value of the drfad1 property.
*
* @return
* possible object is
* {@link DRFAD1 }
*
*/
public DRFAD1 getDRFAD1() {
return drfad1;
}
/**
* Sets the value of the drfad1 property.
*
* @param value
* allowed object is
* {@link DRFAD1 }
*
*/
public void setDRFAD1(DRFAD1 value) {
this.drfad1 = value;
}
/**
* Gets the value of the dctad1 property.
*
* @return
* possible object is
* {@link DCTAD1 }
*
*/
public DCTAD1 getDCTAD1() {
return dctad1;
}
/**
* Sets the value of the dctad1 property.
*
* @param value
* allowed object is
* {@link DCTAD1 }
*
*/
public void setDCTAD1(DCTAD1 value) {
this.dctad1 = 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\DADRE1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | ConnectionFactory jmsConnectionFactory(JmsProperties properties) throws NamingException {
JndiLocatorDelegate jndiLocatorDelegate = JndiLocatorDelegate.createDefaultResourceRefLocator();
if (StringUtils.hasLength(properties.getJndiName())) {
return jndiLocatorDelegate.lookup(properties.getJndiName(), ConnectionFactory.class);
}
return findJndiConnectionFactory(jndiLocatorDelegate);
}
private ConnectionFactory findJndiConnectionFactory(JndiLocatorDelegate jndiLocatorDelegate) {
for (String name : JNDI_LOCATIONS) {
try {
return jndiLocatorDelegate.lookup(name, ConnectionFactory.class);
}
catch (NamingException ex) {
// Swallow and continue
}
}
throw new IllegalStateException(
"Unable to find ConnectionFactory in JNDI locations " + Arrays.asList(JNDI_LOCATIONS));
}
/**
* Condition for JNDI name or a specific property.
*/
static class JndiOrPropertyCondition extends AnyNestedCondition {
JndiOrPropertyCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION); | }
@ConditionalOnJndi({ "java:/JmsXA", "java:/XAConnectionFactory" })
static class Jndi {
}
@ConditionalOnProperty("spring.jms.jndi-name")
static class Property {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JndiConnectionFactoryAutoConfiguration.java | 2 |
请完成以下Java代码 | public String asString() {
return "spring.kafka.template.name";
}
},
/**
* Messaging system.
*/
MESSAGING_SYSTEM {
@Override
@NonNull
public String asString() {
return "messaging.system";
}
},
/**
* Messaging operation.
*/
MESSAGING_OPERATION {
@Override
@NonNull
public String asString() {
return "messaging.operation";
}
},
/**
* Messaging destination name.
*/
MESSAGING_DESTINATION_NAME {
@Override
@NonNull
public String asString() {
return "messaging.destination.name";
}
},
/**
* Messaging destination kind.
*/
MESSAGING_DESTINATION_KIND {
@Override
@NonNull
public String asString() {
return "messaging.destination.kind";
}
}
}
/**
* Default {@link KafkaTemplateObservationConvention} for Kafka template key values. | *
* @author Gary Russell
* @author Christian Mergenthaler
* @author Wang Zhiyang
*
* @since 3.0
*
*/
public static class DefaultKafkaTemplateObservationConvention implements KafkaTemplateObservationConvention {
/**
* A singleton instance of the convention.
*/
public static final DefaultKafkaTemplateObservationConvention INSTANCE =
new DefaultKafkaTemplateObservationConvention();
@Override
public KeyValues getLowCardinalityKeyValues(KafkaRecordSenderContext context) {
return KeyValues.of(
TemplateLowCardinalityTags.BEAN_NAME.withValue(context.getBeanName()),
TemplateLowCardinalityTags.MESSAGING_SYSTEM.withValue("kafka"),
TemplateLowCardinalityTags.MESSAGING_OPERATION.withValue("publish"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_KIND.withValue("topic"),
TemplateLowCardinalityTags.MESSAGING_DESTINATION_NAME.withValue(context.getDestination()));
}
@Override
public String getContextualName(KafkaRecordSenderContext context) {
return context.getDestination() + " send";
}
@Override
@NonNull
public String getName() {
return "spring.kafka.template";
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaTemplateObservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean cancelSubscription(String subscriptionId) {
boolean status;
try {
Stripe.apiKey = API_SECRET_KEY;
Subscription sub = Subscription.retrieve(subscriptionId);
sub.cancel((SubscriptionCancelParams) null);
status = true;
} catch (Exception ex) {
ex.printStackTrace();
status = false;
}
return status;
}
public Coupon retrieveCoupon(String code) {
try {
Stripe.apiKey = API_SECRET_KEY;
return Coupon.retrieve(code);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public String createCharge(String email, String token, int amount) {
String id = null;
try { | Stripe.apiKey = API_SECRET_KEY;
Map<String, Object> chargeParams = new HashMap<>();
chargeParams.put("amount", amount);
chargeParams.put("currency", "usd");
chargeParams.put("description", "Charge for " + email);
chargeParams.put("source", token); // ^ obtained with Stripe.js
//create a charge
Charge charge = Charge.create(chargeParams);
id = charge.getId();
} catch (Exception ex) {
ex.printStackTrace();
}
return id;
}
} | repos\springboot-demo-master\stripe\src\main\java\com\et\stripe\service\StripeService.java | 2 |
请完成以下Java代码 | protected @NonNull JsonToObjectConverter getJsonToObjectConverter() {
return this.converter;
}
/**
* @inheritDoc
*/
@Override
public final @NonNull PdxInstance convert(@NonNull String json) {
try {
return convertJsonToPdx(json);
}
catch (JSONFormatterException cause) {
return convertJsonToObjectToPdx(json);
}
}
/**
* Adapts the given {@link Object} as a {@link PdxInstance}.
*
* @param target {@link Object} to adapt as PDX; must not be {@literal null}.
* @return a {@link PdxInstance} representing the given {@link Object}.
* @see org.springframework.geode.pdx.ObjectPdxInstanceAdapter#from(Object)
* @see org.apache.geode.pdx.PdxInstance
*/
protected @NonNull PdxInstance adapt(@NonNull Object target) {
return ObjectPdxInstanceAdapter.from(target);
}
/**
* Converts the given {@link String JSON} into a {@link Object} and then adapts the {@link Object}
* as a {@link PdxInstance}.
*
* @param json {@link String JSON} to convert into an {@link Object} into PDX.
* @return a {@link PdxInstance} converted from the given {@link String JSON}.
* @see org.apache.geode.pdx.PdxInstance
* @see #getJsonToObjectConverter()
* @see #adapt(Object)
*/
protected @NonNull PdxInstance convertJsonToObjectToPdx(@NonNull String json) {
return adapt(getJsonToObjectConverter().convert(json));
}
/**
* Converts the given {@link String JSON} to {@link PdxInstance PDX}.
*
* @param json {@link String} containing JSON to convert to PDX; must not be {@literal null}.
* @return JSON for the given {@link PdxInstance PDX}.
* @see org.apache.geode.pdx.PdxInstance
* @see #jsonFormatterFromJson(String)
* @see #wrap(PdxInstance)
*/
protected @NonNull PdxInstance convertJsonToPdx(@NonNull String json) {
return wrap(jsonFormatterFromJson(json));
} | /**
* Converts {@link String JSON} into {@link PdxInstance PDX} using {@link JSONFormatter#fromJSON(String)}.
*
* @param json {@link String JSON} to convert to {@link PdxInstance PDX}; must not be {@literal null}.
* @return {@link PdxInstance PDX} generated from the given, required {@link String JSON}; never {@literal null}.
* @see org.apache.geode.pdx.JSONFormatter#fromJSON(String)
* @see org.apache.geode.pdx.PdxInstance
*/
protected @NonNull PdxInstance jsonFormatterFromJson(@NonNull String json) {
return JSONFormatter.fromJSON(json);
}
/**
* Wraps the given {@link PdxInstance} in a new instance of {@link PdxInstanceWrapper}.
*
* @param pdxInstance {@link PdxInstance} to wrap.
* @return a new instance of {@link PdxInstanceWrapper} wrapping the given {@link PdxInstance}.
* @see org.springframework.geode.pdx.PdxInstanceWrapper#from(PdxInstance)
* @see org.springframework.geode.pdx.PdxInstanceWrapper
* @see org.apache.geode.pdx.PdxInstance
*/
protected @NonNull PdxInstanceWrapper wrap(@NonNull PdxInstance pdxInstance) {
return PdxInstanceWrapper.from(pdxInstance);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JSONFormatterJsonToPdxConverter.java | 1 |
请完成以下Java代码 | public List<String> getInvolvedGroups() {
return involvedGroups;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getTaskNameLikeIgnoreCase() {
return taskNameLikeIgnoreCase;
}
public String getTaskDescriptionLikeIgnoreCase() {
return taskDescriptionLikeIgnoreCase;
}
public String getTaskOwnerLikeIgnoreCase() { | return taskOwnerLikeIgnoreCase;
}
public String getTaskAssigneeLikeIgnoreCase() {
return taskAssigneeLikeIgnoreCase;
}
public String getLocale() {
return locale;
}
public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricTaskInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public EntityTransaction getTransaction() {
log.info("[I240] getTransaction()");
return delegate.getTransaction();
}
public EntityManagerFactory getEntityManagerFactory() {
return delegate.getEntityManagerFactory();
}
public CriteriaBuilder getCriteriaBuilder() {
return delegate.getCriteriaBuilder();
}
public Metamodel getMetamodel() {
return delegate.getMetamodel();
}
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return delegate.createEntityGraph(rootType);
}
public EntityGraph<?> createEntityGraph(String graphName) {
return delegate.createEntityGraph(graphName); | }
public EntityGraph<?> getEntityGraph(String graphName) {
return delegate.getEntityGraph(graphName);
}
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return delegate.getEntityGraphs(entityClass);
}
public EntityManagerWrapper(EntityManager delegate) {
this.delegate = delegate;
}
}
} | repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\CarsODataJPAServiceFactory.java | 1 |
请完成以下Java代码 | public void setColor (final @Nullable java.lang.String Color)
{
set_Value (COLUMNNAME_Color, Color);
}
@Override
public java.lang.String getColor()
{
return get_ValueAsString(COLUMNNAME_Color);
}
@Override
public void setES_FieldPath (final @Nullable java.lang.String ES_FieldPath)
{
set_Value (COLUMNNAME_ES_FieldPath, ES_FieldPath);
}
@Override
public java.lang.String getES_FieldPath()
{
return get_ValueAsString(COLUMNNAME_ES_FieldPath);
}
@Override
public void setIsGroupBy (final boolean IsGroupBy)
{
set_Value (COLUMNNAME_IsGroupBy, IsGroupBy);
}
@Override
public boolean isGroupBy()
{
return get_ValueAsBoolean(COLUMNNAME_IsGroupBy);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setOffsetName (final @Nullable java.lang.String OffsetName)
{
set_Value (COLUMNNAME_OffsetName, OffsetName);
}
@Override
public java.lang.String getOffsetName()
{
return get_ValueAsString(COLUMNNAME_OffsetName);
}
@Override
public void setSQL_Select (final @Nullable java.lang.String SQL_Select)
{
set_Value (COLUMNNAME_SQL_Select, SQL_Select);
}
@Override
public java.lang.String getSQL_Select()
{
return get_ValueAsString(COLUMNNAME_SQL_Select); | }
@Override
public void setUOMSymbol (final @Nullable java.lang.String UOMSymbol)
{
set_Value (COLUMNNAME_UOMSymbol, UOMSymbol);
}
@Override
public java.lang.String getUOMSymbol()
{
return get_ValueAsString(COLUMNNAME_UOMSymbol);
}
@Override
public void setWEBUI_KPI_Field_ID (final int WEBUI_KPI_Field_ID)
{
if (WEBUI_KPI_Field_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_Field_ID, WEBUI_KPI_Field_ID);
}
@Override
public int getWEBUI_KPI_Field_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_Field_ID);
}
@Override
public de.metas.ui.web.base.model.I_WEBUI_KPI getWEBUI_KPI()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class);
}
@Override
public void setWEBUI_KPI(final de.metas.ui.web.base.model.I_WEBUI_KPI WEBUI_KPI)
{
set_ValueFromPO(COLUMNNAME_WEBUI_KPI_ID, de.metas.ui.web.base.model.I_WEBUI_KPI.class, WEBUI_KPI);
}
@Override
public void setWEBUI_KPI_ID (final int WEBUI_KPI_ID)
{
if (WEBUI_KPI_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_KPI_ID, WEBUI_KPI_ID);
}
@Override
public int getWEBUI_KPI_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_KPI_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_KPI_Field.java | 1 |
请完成以下Java代码 | private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Collection<?> value) {
for (Object elt : value) {
addGrantedAuthorityCollection(result, elt);
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, Object[] value) {
for (Object aValue : value) {
addGrantedAuthorityCollection(result, aValue);
}
}
private void addGrantedAuthorityCollection(Collection<GrantedAuthority> result, String value) {
StringTokenizer tokenizer = new StringTokenizer(value, this.stringSeparator, false);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (StringUtils.hasText(token)) {
result.add(new SimpleGrantedAuthority(token));
}
}
}
/**
*
* @see org.springframework.security.core.authority.mapping.MappableAttributesRetriever#getMappableAttributes() | */
@Override
public Set<String> getMappableAttributes() {
return this.mappableAttributes;
}
/**
* @return Returns the stringSeparator.
*/
public String getStringSeparator() {
return this.stringSeparator;
}
/**
* @param stringSeparator The stringSeparator to set.
*/
public void setStringSeparator(String stringSeparator) {
Assert.notNull(stringSeparator, "stringSeparator cannot be null");
this.stringSeparator = stringSeparator;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\MapBasedAttributes2GrantedAuthoritiesMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HistoricActivityInstanceRestServiceImpl implements HistoricActivityInstanceRestService {
protected ObjectMapper objectMapper;
protected ProcessEngine processEngine;
public HistoricActivityInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) {
this.objectMapper = objectMapper;
this.processEngine = processEngine;
}
@Override
public HistoricActivityInstanceResource getHistoricCaseInstance(String activityInstanceId) {
return new HistoricActivityInstanceResourceImpl(processEngine, activityInstanceId);
}
@Override
public List<HistoricActivityInstanceDto> getHistoricActivityInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
HistoricActivityInstanceQueryDto queryHistoricActivityInstanceDto = new HistoricActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricActivityInstances(queryHistoricActivityInstanceDto, firstResult, maxResults);
}
@Override
public List<HistoricActivityInstanceDto> queryHistoricActivityInstances(HistoricActivityInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(objectMapper);
HistoricActivityInstanceQuery query = queryDto.toQuery(processEngine);
List<HistoricActivityInstance> matchingHistoricActivityInstances = QueryUtil.list(query, firstResult, maxResults);
List<HistoricActivityInstanceDto> historicActivityInstanceResults = new ArrayList<HistoricActivityInstanceDto>();
for (HistoricActivityInstance historicActivityInstance : matchingHistoricActivityInstances) {
HistoricActivityInstanceDto resultHistoricActivityInstance = new HistoricActivityInstanceDto(); | HistoricActivityInstanceDto.fromHistoricActivityInstance(resultHistoricActivityInstance, historicActivityInstance);
historicActivityInstanceResults.add(resultHistoricActivityInstance);
}
return historicActivityInstanceResults;
}
@Override
public CountResultDto getHistoricActivityInstancesCount(UriInfo uriInfo) {
HistoricActivityInstanceQueryDto queryDto = new HistoricActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricActivityInstancesCount(queryDto);
}
@Override
public CountResultDto queryHistoricActivityInstancesCount(HistoricActivityInstanceQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricActivityInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityInstanceRestServiceImpl.java | 2 |
请完成以下Java代码 | private String getPlainTextReport(MAlertRule rule, String sql, String trxName, Collection<File> attachments)
throws Exception
{
StringBuffer result = new StringBuffer();
PreparedStatement pstmt = null;
ResultSet rs = null;
Exception error = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
rs = pstmt.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
while (rs.next())
{
result.append("------------------").append(Env.NL);
for (int col = 1; col <= meta.getColumnCount(); col++)
{
result.append(meta.getColumnLabel(col)).append(" = ");
result.append(rs.getString(col));
result.append(Env.NL);
} // for all columns
}
if (result.length() == 0)
log.debug("No rows selected");
}
catch (Throwable e)
{
log.error(sql, e);
if (e instanceof Exception)
error = (Exception)e;
else
error = new Exception(e.getMessage(), e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
// Error occurred
if (error != null)
throw new Exception("(" + sql + ") " + Env.NL
+ error.getLocalizedMessage());
return result.toString();
}
/**
* Get Excel Report
*
* @param rule
* @param sql
* @param trxName
* @param attachments
* @return summary message to be added into mail content
* @throws Exception
*/
private String getExcelReport(final MAlertRule rule, final String sql, final Collection<File> attachments) throws Exception
{
final SpreadsheetExporterService spreadsheetExporterService = SpringContextHolder.instance.getBean(SpreadsheetExporterService.class); | final File file = rule.createReportFile(ExcelFormats.getDefaultFileExtension());
final JdbcExcelExporter jdbcExcelExporter = JdbcExcelExporter.builder()
.ctx(getCtx())
.resultFile(file)
.build();
spreadsheetExporterService.processDataFromSQL(sql, jdbcExcelExporter);
if(jdbcExcelExporter.isNoDataAddedYet())
{
return null;
}
attachments.add(file);
final String msg = rule.getName() + " (@SeeAttachment@ " + file.getName() + ")" + Env.NL;
return Msg.parseTranslation(Env.getCtx(), msg);
}
/**
* Get Server Info
*
* @return info
*/
@Override
public String getServerInfo()
{
return "#" + getRunCount() + " - Last=" + m_summary.toString();
} // getServerInfo
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AlertProcessor.java | 1 |
请完成以下Java代码 | public class JobExecutorAdd extends AbstractAddStepHandler {
public static final String THREAD_POOL_GRP_NAME = "Camunda BPM ";
public static final JobExecutorAdd INSTANCE = new JobExecutorAdd();
protected JobExecutorAdd() {
super(JOB_EXECUTOR_ATTRIBUTES);
}
@Override
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
String jobExecutorThreadPoolName = THREAD_POOL_NAME.resolveModelAttribute(context, model).asString();
ServiceName jobExecutorThreadPoolServiceName = ServiceNames.forManagedThreadPool(jobExecutorThreadPoolName);
performRuntimeThreadPool(context, model, jobExecutorThreadPoolName, jobExecutorThreadPoolServiceName);
ServiceName serviceName = ServiceNames.forMscExecutorService();
ServiceBuilder<?> builder = context.getServiceTarget().addService(serviceName);
Consumer<ExecutorService> provider = builder.provides(serviceName);
Supplier<EnhancedQueueExecutor> supplier = builder.requires(jobExecutorThreadPoolServiceName);
MscExecutorService service = new MscExecutorService(supplier, provider);
builder.setInitialMode(ServiceController.Mode.ACTIVE);
builder.setInstance(service);
builder.install();
}
protected void performRuntimeThreadPool(OperationContext context,
ModelNode model,
String name,
ServiceName jobExecutorThreadPoolServiceName)
throws OperationFailedException {
ServiceTarget serviceTarget = context.getServiceTarget(); | ThreadFactoryService threadFactory = new ThreadFactoryService();
threadFactory.setThreadGroupName(THREAD_POOL_GRP_NAME + name);
ServiceName threadFactoryServiceName = ServiceNames.forThreadFactoryService(name);
serviceTarget.addService(threadFactoryServiceName, threadFactory).install();
Builder executorBuilder = new Builder()
.setMaximumPoolSize(MAX_THREADS.resolveModelAttribute(context, model).asInt())
.setCorePoolSize(CORE_THREADS.resolveModelAttribute(context, model).asInt())
.setMaximumQueueSize(QUEUE_LENGTH.resolveModelAttribute(context, model).asInt())
.setKeepAliveTime(KEEPALIVE_TIME.resolveModelAttribute(context, model).asInt(), TimeUnit.SECONDS)
.allowCoreThreadTimeOut(ALLOW_CORE_TIMEOUT.resolveModelAttribute(context, model).asBoolean());
ServiceBuilder<EnhancedQueueExecutor> queueExecutorBuilder = serviceTarget.addService(jobExecutorThreadPoolServiceName, new EnhancedQueueExecutorService(executorBuilder));
queueExecutorBuilder.requires(threadFactoryServiceName);
queueExecutorBuilder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\JobExecutorAdd.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID()
{
return AD_Table_ID;
}
@Override
public void setAD_Table_ID(final int aD_Table_ID)
{
AD_Table_ID = aD_Table_ID;
}
@Override
public int getRecord_ID()
{
return Record_ID;
}
@Override
public void setRecord_ID(final int record_ID) | {
Record_ID = record_ID;
}
@Override
public void setM_HU_ID(int m_hu_ID)
{
M_HU_ID = m_hu_ID;
}
@Override
public int getM_HU_ID()
{
return M_HU_ID;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java | 1 |
请完成以下Java代码 | public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Exclude Attribute Set.
@param M_AttributeSetExclude_ID
Exclude the ability to enter Attribute Sets
*/
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID)
{
if (M_AttributeSetExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID));
}
/** Get Exclude Attribute Set.
@return Exclude the ability to enter Attribute Sets
*/
public int getM_AttributeSetExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
public I_M_AttributeSet getM_AttributeSet() throws RuntimeException
{
return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name)
.getPO(getM_AttributeSet_ID(), get_TrxName()); }
/** Set Attribute Set.
@param M_AttributeSet_ID
Product Attribute Set
*/
public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Attribute Set.
@return Product Attribute Set
*/
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetExclude.java | 1 |
请完成以下Java代码 | public boolean hasMapping(String taskId) {
return mappings.get(taskId) != null;
}
public boolean shouldMapAllInputs(String elementId) {
ProcessVariablesMapping processVariablesMapping = mappings.get(elementId);
return (
processVariablesMapping.getMappingType() != null &&
(processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_INPUTS) ||
processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL))
);
}
public boolean shouldMapAllOutputs(String elementId) {
ProcessVariablesMapping processVariablesMapping = mappings.get(elementId);
return (
processVariablesMapping.getMappingType() != null &&
(processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL_OUTPUTS) ||
processVariablesMapping.getMappingType().equals(MappingType.MAP_ALL))
);
} | public TemplatesDefinition getTemplates() {
return templates;
}
public void setTemplates(TemplatesDefinition templates) {
this.templates = templates;
}
public Map<String, AssignmentDefinition> getAssignments() {
return assignments;
}
public void setAssignments(Map<String, AssignmentDefinition> assignments) {
this.assignments = assignments;
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\Extension.java | 1 |
请完成以下Java代码 | public List<Book> getAllBooks() {
return new ArrayList<>(BOOKS_DATA);
}
@GraphQLMutation(name = "addBook")
public Book addBook(@GraphQLArgument(name = "newBook") Book book) {
BOOKS_DATA.add(book);
return book;
}
@GraphQLMutation(name = "updateBook")
public Book updateBook(@GraphQLArgument(name = "modifiedBook") Book book) {
BOOKS_DATA.removeIf(b -> Objects.equals(b.getId(), book.getId()));
BOOKS_DATA.add(book);
return book; | }
@GraphQLMutation(name = "deleteBook")
public boolean deleteBook(@GraphQLArgument(name = "book") Book book) {
return BOOKS_DATA.remove(book);
}
private static Set<Book> initializeData() {
Book book = new Book(1, "J.R.R. Tolkien", "The Lord of the Rings");
Set<Book> books = new HashSet<>();
books.add(book);
return books;
}
} | repos\tutorials-master\graphql-modules\graphql-spqr-boot-starter\src\main\java\com\baeldung\spqr\BookService.java | 1 |
请完成以下Java代码 | public static PricingConditionsId ofRepoIdOrNull(final int discountSchemaId)
{
return discountSchemaId > 0 ? new PricingConditionsId(discountSchemaId) : null;
}
public static Set<PricingConditionsId> ofDiscountSchemaIds(@NonNull final Collection<Integer> discountSchemaIds)
{
return discountSchemaIds.stream()
.map(PricingConditionsId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
public static Set<Integer> toDiscountSchemaIds(@NonNull final Collection<PricingConditionsId> ids)
{
return ids.stream()
.map(PricingConditionsId::getRepoId)
.collect(ImmutableSet.toImmutableSet()); | }
private final int repoId;
private PricingConditionsId(final int discountSchemaId)
{
Check.assumeGreaterThanZero(discountSchemaId, "discountSchemaId");
this.repoId = discountSchemaId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsId.java | 1 |
请完成以下Java代码 | public DeviceData getDeviceData() {
if (deviceData != null) {
return deviceData;
} else {
if (deviceDataBytes != null) {
try {
deviceData = mapper.readValue(new ByteArrayInputStream(deviceDataBytes), DeviceData.class);
} catch (IOException e) {
log.warn("Can't deserialize device data: ", e);
return null;
}
return deviceData;
} else {
return null;
}
}
}
public void setDeviceData(DeviceData data) {
this.deviceData = data;
try {
this.deviceDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize device data: ", e);
}
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getFirmwareId() {
return firmwareId;
}
public void setFirmwareId(OtaPackageId firmwareId) {
this.firmwareId = firmwareId; | }
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getSoftwareId() {
return softwareId;
}
public void setSoftwareId(OtaPackageId softwareId) {
this.softwareId = softwareId;
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Device.java | 1 |
请完成以下Java代码 | public DmnParse sourceUrl(URL url) {
if (name == null) {
name(url.toString());
}
setStreamSource(new UrlStreamSource(url));
return this;
}
public DmnParse sourceUrl(String url) {
try {
return sourceUrl(new URL(url));
} catch (MalformedURLException e) {
throw new FlowableException("malformed url: " + url, e);
}
}
public DmnParse sourceResource(String resource) {
if (name == null) {
name(resource);
}
setStreamSource(new ResourceStreamSource(resource));
return this;
}
public DmnParse sourceString(String string) {
if (name == null) {
name("string");
}
setStreamSource(new StringStreamSource(string));
return this;
}
protected void setStreamSource(StreamSource streamSource) {
if (this.streamSource != null) {
throw new FlowableException("invalid: multiple sources " + this.streamSource + " and " + streamSource);
}
this.streamSource = streamSource;
}
public String getSourceSystemId() {
return sourceSystemId;
}
public DmnParse setSourceSystemId(String sourceSystemId) {
this.sourceSystemId = sourceSystemId;
return this;
}
/*
* ------------------- GETTERS AND SETTERS -------------------
*/
public boolean isValidateSchema() { | return validateSchema;
}
public void setValidateSchema(boolean validateSchema) {
this.validateSchema = validateSchema;
}
public List<DecisionEntity> getDecisions() {
return decisions;
}
public String getTargetNamespace() {
return targetNamespace;
}
public DmnDeploymentEntity getDeployment() {
return deployment;
}
public void setDeployment(DmnDeploymentEntity deployment) {
this.deployment = deployment;
}
public DmnDefinition getDmnDefinition() {
return dmnDefinition;
}
public void setDmnDefinition(DmnDefinition dmnDefinition) {
this.dmnDefinition = dmnDefinition;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\parser\DmnParse.java | 1 |
请完成以下Java代码 | public <T extends RepoIdAware> T asMetasfreshId(@NonNull final IntFunction<T> mapper)
{
Check.assume(Type.METASFRESH_ID.equals(type), "The type of this instance needs to be {}; this={}", Type.METASFRESH_ID, this);
final int repoId = Integer.parseInt(value);
return mapper.apply(repoId);
}
public GLN asGLN()
{
Check.assume(Type.GLN.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN, this);
return GLN.ofString(value);
}
public GlnWithLabel asGlnWithLabel()
{
Check.assume(Type.GLN_WITH_LABEL.equals(type), "The type of this instance needs to be {}; this={}", Type.GLN_WITH_LABEL, this);
return GlnWithLabel.ofString(value);
}
public String asDoc()
{
Check.assume(Type.DOC.equals(type), "The type of this instance needs to be {}; this={}", Type.DOC, this);
return value;
}
public String asValue()
{
Check.assume(Type.VALUE.equals(type), "The type of this instance needs to be {}; this={}", Type.VALUE, this); | return value;
}
public String asInternalName()
{
Check.assume(Type.INTERNALNAME.equals(type), "The type of this instance needs to be {}; this={}", Type.INTERNALNAME, this);
return value;
}
public boolean isMetasfreshId()
{
return Type.METASFRESH_ID.equals(type);
}
public boolean isExternalId()
{
return Type.EXTERNAL_ID.equals(type);
}
public boolean isValue()
{
return Type.VALUE.equals(type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\IdentifierString.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getRetryAttempts() {
return this.retryAttempts;
}
public void setRetryAttempts(int retryAttempts) {
this.retryAttempts = retryAttempts;
}
public String getServerGroup() {
return this.serverGroup;
}
public void setServerGroup(String serverGroup) {
this.serverGroup = serverGroup;
}
public String[] getServers() {
return this.servers;
}
public void setServers(String[] servers) {
this.servers = servers;
}
public int getSocketBufferSize() {
return this.socketBufferSize;
}
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public int getStatisticInterval() {
return this.statisticInterval;
}
public void setStatisticInterval(int statisticInterval) {
this.statisticInterval = statisticInterval;
}
public int getSubscriptionAckInterval() {
return this.subscriptionAckInterval;
}
public void setSubscriptionAckInterval(int subscriptionAckInterval) {
this.subscriptionAckInterval = subscriptionAckInterval;
}
public boolean isSubscriptionEnabled() {
return this.subscriptionEnabled;
} | public void setSubscriptionEnabled(boolean subscriptionEnabled) {
this.subscriptionEnabled = subscriptionEnabled;
}
public int getSubscriptionMessageTrackingTimeout() {
return this.subscriptionMessageTrackingTimeout;
}
public void setSubscriptionMessageTrackingTimeout(int subscriptionMessageTrackingTimeout) {
this.subscriptionMessageTrackingTimeout = subscriptionMessageTrackingTimeout;
}
public int getSubscriptionRedundancy() {
return this.subscriptionRedundancy;
}
public void setSubscriptionRedundancy(int subscriptionRedundancy) {
this.subscriptionRedundancy = subscriptionRedundancy;
}
public boolean isThreadLocalConnections() {
return this.threadLocalConnections;
}
public void setThreadLocalConnections(boolean threadLocalConnections) {
this.threadLocalConnections = threadLocalConnections;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\PoolProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ImageRestController
{
public static final String ENDPOINT = WebConfig.ENDPOINT_ROOT + "/image";
private final UserSession userSession;
private final WebuiImageService imageService;
public ImageRestController(
@NonNull final UserSession userSession,
@NonNull final WebuiImageService imageService)
{
this.userSession = userSession;
this.imageService = imageService;
}
private JSONOptions newJSONOptions()
{
return JSONOptions.of(userSession);
}
@PostMapping
public WebuiImageId uploadImage(@RequestParam("file") final MultipartFile file) throws IOException
{
userSession.assertLoggedIn();
return imageService.uploadImage(file);
}
@GetMapping("/{imageId}")
@ResponseBody
public ResponseEntity<byte[]> getImage(
@PathVariable("imageId") final int imageIdInt,
@RequestParam(name = "maxWidth", required = false, defaultValue = "-1") final int maxWidth,
@RequestParam(name = "maxHeight", required = false, defaultValue = "-1") final int maxHeight,
final WebRequest request)
{ | userSession.assertLoggedIn();
final WebuiImageId imageId = WebuiImageId.ofRepoIdOrNull(imageIdInt);
return ETagResponseEntityBuilder.ofETagAware(request, getWebuiImage(imageId, maxWidth, maxHeight))
.includeLanguageInETag()
.cacheMaxAge(userSession.getHttpCacheMaxAge())
.jsonOptions(this::newJSONOptions)
.toResponseEntity((responseBuilder, webuiImage) -> webuiImage.toResponseEntity(responseBuilder));
}
private WebuiImage getWebuiImage(final WebuiImageId imageId, final int maxWidth, final int maxHeight)
{
final WebuiImage image = imageService.getWebuiImage(imageId, maxWidth, maxHeight);
assertUserHasAccess(image);
return image;
}
private void assertUserHasAccess(final WebuiImage image)
{
final BooleanWithReason hasAccess = userSession.getUserRolePermissions().checkCanView(image.getAdClientId(), image.getAdOrgId(), I_AD_Image.Table_ID, image.getAdImageId().getRepoId());
if (hasAccess.isFalse())
{
throw new EntityNotFoundException(hasAccess.getReason());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\upload\ImageRestController.java | 2 |
请完成以下Java代码 | public ImmutableCollection<SQLDatasourceFieldDescriptor> getFields()
{
return fields.values();
}
private static IStringExpression buildSqlSelect(
@NonNull final List<SQLDatasourceFieldDescriptor> fields,
@NonNull final String sourceTableName,
@Nullable final String sqlFrom,
@Nullable final String sqlWhereClause,
@Nullable final String sqlGroupAndOrderBy)
{
Check.assumeNotEmpty(fields, "fields shall not be empty");
final StringBuilder sqlFields = new StringBuilder();
for (final SQLDatasourceFieldDescriptor field : fields)
{
final String fieldName = field.getFieldName();
final String sqlField = field.getSqlSelect();
if (sqlFields.length() > 0)
{
sqlFields.append("\n, ");
}
sqlFields.append("(").append(sqlField).append(") AS ").append(fieldName);
}
final StringBuilder sql = new StringBuilder();
sql.append("SELECT \n").append(sqlFields);
//
// FROM ....
sql.append("\n");
if (sqlFrom != null && !Check.isBlank(sqlFrom))
{
if (!sqlFrom.trim().toUpperCase().startsWith("FROM"))
{
sql.append("FROM ");
}
sql.append(sqlFrom.trim());
}
else
{
sql.append("FROM ").append(sourceTableName);
}
//
// WHERE
if (sqlWhereClause != null && !Check.isBlank(sqlWhereClause))
{
sql.append("\n");
if (!sqlWhereClause.trim().toUpperCase().startsWith("WHERE"))
{
sql.append("WHERE ");
}
sql.append(sqlWhereClause.trim());
}
//
// GROUP BY / ORDER BY
if (sqlGroupAndOrderBy != null && !Check.isBlank(sqlGroupAndOrderBy))
{
sql.append("\n").append(sqlGroupAndOrderBy.trim());
} | return StringExpressionCompiler.instance.compile(sql.toString());
}
private static IStringExpression buildSqlDetailsWhereClause(
@Nullable final String sqlDetailsWhereClause,
@Nullable final String sqlWhereClause)
{
String sqlDetailsWhereClauseNorm = CoalesceUtil.firstNotEmptyTrimmed(
sqlDetailsWhereClause,
sqlWhereClause);
if (sqlDetailsWhereClauseNorm == null || Check.isBlank(sqlDetailsWhereClauseNorm))
{
return IStringExpression.NULL;
}
if (sqlDetailsWhereClauseNorm.toUpperCase().startsWith("WHERE"))
{
sqlDetailsWhereClauseNorm = sqlDetailsWhereClauseNorm.substring("WHERE".length()).trim();
}
return StringExpressionCompiler.instance.compile(sqlDetailsWhereClauseNorm);
}
public Set<CtxName> getRequiredContextParameters()
{
return ImmutableSet.<CtxName>builder()
.addAll(sqlSelect.getParameters())
.addAll(sqlDetailsWhereClause.getParameters())
.addAll(isApplySecuritySettings() ? PERMISSION_REQUIRED_PARAMS : ImmutableSet.of())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\sql\SQLDatasourceDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GetJobByCorrelationIdCmd implements Command<Job> {
protected JobServiceConfiguration jobServiceConfiguration;
protected String correlationId;
public GetJobByCorrelationIdCmd(String correlationId, JobServiceConfiguration jobServiceConfiguration) {
this.correlationId = correlationId;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Job execute(CommandContext commandContext) {
if (correlationId == null) {
throw new FlowableIllegalArgumentException("correlationId is null");
}
Job job = jobServiceConfiguration.getDeadLetterJobEntityManager().findJobByCorrelationId(correlationId);
if (job != null) {
return job;
}
job = jobServiceConfiguration.getExternalWorkerJobEntityManager().findJobByCorrelationId(correlationId);
if (job != null) { | return job;
}
job = jobServiceConfiguration.getTimerJobEntityManager().findJobByCorrelationId(correlationId);
if (job != null) {
return job;
}
job = jobServiceConfiguration.getSuspendedJobEntityManager().findJobByCorrelationId(correlationId);
if (job != null) {
return job;
}
return jobServiceConfiguration.getJobEntityManager().findJobByCorrelationId(correlationId);
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\GetJobByCorrelationIdCmd.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ReceiptsRouteBuilder extends RouteBuilder
{
private static final String CREATE_RECEIPTS_ROUTE_ID = "To-MF_createReceipts_V2";
@Override
public void configure() throws Exception
{
errorHandler(noErrorHandler());
from(direct(MF_CREATE_RECEIPTS_V2_CAMEL_URI))
.routeId(CREATE_RECEIPTS_ROUTE_ID)
.streamCache("true")
.process(exchange -> {
final var lookupRequest = exchange.getIn().getBody();
if (!(lookupRequest instanceof ReceiptsCamelRequest))
{
throw new RuntimeCamelException("The route " + MF_CREATE_RECEIPTS_V2_CAMEL_URI + " requires the body to be instanceof ReceiptsCamelRequest V2." | + " However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName()));
}
final JsonCreateReceiptsRequest jsonCreateReceiptsRequest = ((ReceiptsCamelRequest)lookupRequest).getJsonCreateReceiptsRequest();
exchange.getIn().setBody(jsonCreateReceiptsRequest);
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonCreateReceiptsRequest.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.POST))
.toD("{{metasfresh.create-receipts-v2.api.uri}}")
.to(direct(UNPACK_V2_API_RESPONSE));
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\ReceiptsRouteBuilder.java | 2 |
请完成以下Java代码 | public void setCtgyDtls(String value) {
this.ctgyDtls = value;
}
/**
* Gets the value of the dbtrSts property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDbtrSts() {
return dbtrSts;
}
/**
* Sets the value of the dbtrSts property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDbtrSts(String value) {
this.dbtrSts = value;
}
/**
* Gets the value of the certId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCertId() {
return certId;
}
/**
* Sets the value of the certId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCertId(String value) {
this.certId = value;
}
/**
* Gets the value of the frmsCd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFrmsCd() {
return frmsCd;
}
/**
* Sets the value of the frmsCd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFrmsCd(String value) {
this.frmsCd = value;
}
/**
* Gets the value of the prd property.
*
* @return
* possible object is
* {@link TaxPeriod1 }
*
*/
public TaxPeriod1 getPrd() {
return prd;
}
/**
* Sets the value of the prd property.
*
* @param value
* allowed object is
* {@link TaxPeriod1 }
*
*/ | public void setPrd(TaxPeriod1 value) {
this.prd = value;
}
/**
* Gets the value of the taxAmt property.
*
* @return
* possible object is
* {@link TaxAmount1 }
*
*/
public TaxAmount1 getTaxAmt() {
return taxAmt;
}
/**
* Sets the value of the taxAmt property.
*
* @param value
* allowed object is
* {@link TaxAmount1 }
*
*/
public void setTaxAmt(TaxAmount1 value) {
this.taxAmt = value;
}
/**
* Gets the value of the addtlInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlInf() {
return addtlInf;
}
/**
* Sets the value of the addtlInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlInf(String value) {
this.addtlInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxRecord1.java | 1 |
请完成以下Java代码 | public class X_U_BlackListCheque extends PO implements I_U_BlackListCheque, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_U_BlackListCheque (Properties ctx, int U_BlackListCheque_ID, String trxName)
{
super (ctx, U_BlackListCheque_ID, trxName);
/** if (U_BlackListCheque_ID == 0)
{
setBankName (null);
setChequeNo (null);
setU_BlackListCheque_ID (0);
} */
}
/** Load Constructor */
public X_U_BlackListCheque (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_U_BlackListCheque[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Bank Name.
@param BankName Bank Name */
public void setBankName (String BankName)
{
set_Value (COLUMNNAME_BankName, BankName);
}
/** Get Bank Name. | @return Bank Name */
public String getBankName ()
{
return (String)get_Value(COLUMNNAME_BankName);
}
/** Set Cheque No.
@param ChequeNo Cheque No */
public void setChequeNo (String ChequeNo)
{
set_Value (COLUMNNAME_ChequeNo, ChequeNo);
}
/** Get Cheque No.
@return Cheque No */
public String getChequeNo ()
{
return (String)get_Value(COLUMNNAME_ChequeNo);
}
/** Set Black List Cheque.
@param U_BlackListCheque_ID Black List Cheque */
public void setU_BlackListCheque_ID (int U_BlackListCheque_ID)
{
if (U_BlackListCheque_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_BlackListCheque_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_BlackListCheque_ID, Integer.valueOf(U_BlackListCheque_ID));
}
/** Get Black List Cheque.
@return Black List Cheque */
public int getU_BlackListCheque_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_BlackListCheque_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_BlackListCheque.java | 1 |
请完成以下Java代码 | public void setAD_Rule(org.compiere.model.I_AD_Rule AD_Rule)
{
set_ValueFromPO(COLUMNNAME_AD_Rule_ID, org.compiere.model.I_AD_Rule.class, AD_Rule);
}
/** Set Rule.
@param AD_Rule_ID Rule */
@Override
public void setAD_Rule_ID (int AD_Rule_ID)
{
if (AD_Rule_ID < 1)
set_Value (COLUMNNAME_AD_Rule_ID, null);
else
set_Value (COLUMNNAME_AD_Rule_ID, Integer.valueOf(AD_Rule_ID));
}
/** Get Rule.
@return Rule */
@Override
public int getAD_Rule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Rule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Validation code.
@param Code
Validation Code
*/
@Override
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代码 | public RejectPickingResult perform()
{
return trxManager.callInThreadInheritedTrx(this::performInTrx);
}
private RejectPickingResult performInTrx()
{
final PickingCandidate pickingCandidate = getOrCreatePickingCandidate();
pickingCandidate.assertDraft();
pickingCandidate.rejectPicking(request.getQtyToReject());
pickingCandidateRepository.save(pickingCandidate);
return RejectPickingResult.of(pickingCandidate);
}
private PickingCandidate getOrCreatePickingCandidate()
{
if (request.getExistingPickingCandidateId() != null)
{
final PickingCandidate existingPickingCandidate = pickingCandidateRepository.getById(request.getExistingPickingCandidateId());
if (!request.getShipmentScheduleId().equals(existingPickingCandidate.getShipmentScheduleId()))
{
throw new AdempiereException("ShipmentScheduleId does not match.")
.appendParametersToMessage()
.setParameter("expectedShipmentScheduleId", request.getShipmentScheduleId()) | .setParameter("pickingCandidate", existingPickingCandidate);
}
return existingPickingCandidate;
}
else
{
return PickingCandidate.builder()
.processingStatus(PickingCandidateStatus.Draft)
.qtyPicked(request.getQtyToReject())
.shipmentScheduleId(request.getShipmentScheduleId())
.pickFrom(PickFrom.ofHuId(request.getRejectPickingFromHuId()))
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\RejectPickingCommand.java | 1 |
请完成以下Java代码 | public abstract class AbstractManager {
protected EventRegistryEngineConfiguration eventEngineConfiguration;
public AbstractManager(EventRegistryEngineConfiguration eventEngineConfiguration) {
this.eventEngineConfiguration = eventEngineConfiguration;
}
// Command scoped
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped | protected EventRegistryEngineConfiguration getEventEngineConfiguration() {
return eventEngineConfiguration;
}
protected EventDeploymentEntityManager getDeploymentEntityManager() {
return getEventEngineConfiguration().getDeploymentEntityManager();
}
protected EventDefinitionEntityManager getFormDefinitionEntityManager() {
return getEventEngineConfiguration().getEventDefinitionEntityManager();
}
protected EventResourceEntityManager getResourceEntityManager() {
return getEventEngineConfiguration().getResourceEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public class MemoryLayout {
public static void main(String[] args) {
GroupLayout pointLayout = structLayout(JAVA_DOUBLE.withName("x"), JAVA_DOUBLE.withName("y"));
SequenceLayout ptsLayout = sequenceLayout(10, pointLayout);
VarHandle xvarHandle = pointLayout.varHandle(PathElement.groupElement("x"));
VarHandle yvarHandle = pointLayout.varHandle(PathElement.groupElement("y"));
try (Arena memorySession = Arena.ofConfined()) {
MemorySegment pointSegment = memorySession.allocate(pointLayout);
xvarHandle.set(pointSegment, 3d);
yvarHandle.set(pointSegment, 4d);
System.out.println(pointSegment.toString());
}
}
static class ValueLayout { | public static void main(String[] args) {
try (Arena memorySession = Arena.ofConfined()) {
int byteSize = 5;
int index = 3;
float value = 6;
try(Arena arena = Arena.ofAuto()) {
MemorySegment segment = arena.allocate(byteSize);
segment.setAtIndex(JAVA_FLOAT, index, value);
float result = segment.getAtIndex(JAVA_FLOAT, index);
System.out.println("Float value is:" + result);
}
}
}
}
} | repos\tutorials-master\java-panama\src\main\java\com\baeldung\java\panama\core\MemoryLayout.java | 1 |
请完成以下Java代码 | public class ChatConversation {
/**
* 会话id
*/
private String id;
/**
* 会话标题
*/
private String title;
/**
* 消息记录
*/
private List<MessageHistory> messages;
/** | * app
*/
private AiragApp app;
/**
* 创建时间
*/
private Date createTime;
/**
* 流程入参配置(工作流的额外参数设置)
* key: 参数field, value: 参数值
* for [issues/8545]新建AI应用的时候只能选择没有自定义参数的AI流程
*/
private Map<String, Object> flowInputs;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\app\vo\ChatConversation.java | 1 |
请完成以下Java代码 | public ImmutableList<InOutCost> getByInOutId(@NonNull final InOutId inoutId)
{
return queryBL.createQueryBuilder(I_M_InOut_Cost.class)
.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_M_InOut_ID, inoutId)
.orderBy(I_M_InOut_Cost.COLUMNNAME_M_InOut_Cost_ID)
.stream()
.map(InOutCostRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
}
public Stream<InOutCost> stream(@NonNull final InOutCostQuery query)
{
return toSqlQuery(query).stream().map(InOutCostRepository::fromRecord);
}
private IQuery<I_M_InOut_Cost> toSqlQuery(@NonNull final InOutCostQuery query)
{
final IQueryBuilder<I_M_InOut_Cost> queryBuilder = queryBL.createQueryBuilder(I_M_InOut_Cost.class)
.setLimit(query.getLimit())
.addOnlyActiveRecordsFilter();
if (query.getBpartnerId() != null)
{
queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_C_BPartner_ID, query.getBpartnerId());
}
if (query.getSoTrx() != null)
{
queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_IsSOTrx, query.getSoTrx().toBoolean());
}
if (query.getOrderId() != null)
{
queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_C_Order_ID, query.getOrderId());
}
if (query.getCostTypeId() != null)
{
queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_C_Cost_Type_ID, query.getCostTypeId());
}
if (!query.isIncludeReversed())
{
queryBuilder.addIsNull(I_M_InOut_Cost.COLUMNNAME_Reversal_ID); | }
if (query.isOnlyWithOpenAmountToInvoice())
{
queryBuilder.addEqualsFilter(I_M_InOut_Cost.COLUMNNAME_IsInvoiced, false);
}
return queryBuilder.create();
}
public void deleteAll(@NonNull final ImmutableList<InOutCost> inoutCosts)
{
if (inoutCosts.isEmpty())
{
return;
}
final ImmutableSet<InOutCostId> inoutCostIds = inoutCosts.stream().map(InOutCost::getId).collect(ImmutableSet.toImmutableSet());
if (inoutCostIds.isEmpty())
{
return;
}
queryBL.createQueryBuilder(I_M_InOut_Cost.class)
.addInArrayFilter(I_M_InOut_Cost.COLUMNNAME_M_InOut_Cost_ID, inoutCostIds)
.create()
.delete();
}
public void updateInOutCostById(final InOutCostId inoutCostId, final Consumer<InOutCost> consumer)
{
final I_M_InOut_Cost record = InterfaceWrapperHelper.load(inoutCostId, I_M_InOut_Cost.class);
final InOutCost inoutCost = fromRecord(record);
consumer.accept(inoutCost);
updateRecord(record, inoutCost);
InterfaceWrapperHelper.save(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\inout\InOutCostRepository.java | 1 |
请完成以下Java代码 | public String toString()
{
if (v == null) return "null";
final StringBuilder sb = new StringBuilder(v.length * v[0].length * 2);
for (String[] line : v)
{
for (String element : line)
{
sb.append(element).append('\t');
}
sb.append('\n');
}
return sb.toString();
}
/**
* 获取表中某一个元素
* @param x
* @param y
* @return
*/
public String get(int x, int y)
{
if (x < 0) return HEAD + x; | if (x >= v.length) return HEAD + "+" + (x - v.length + 1);
return v[x][y];
}
public void setLast(int x, String t)
{
v[x][v[x].length - 1] = t;
}
public int size()
{
return v.length;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\Table.java | 1 |
请完成以下Java代码 | private boolean compareString (Object valueObj, String value1S, String value2S)
{
//m_numeric = false;
String valueObjS = String.valueOf(valueObj);
//
String op = getOperation();
if (OPERATION_Eq.equals(op))
return valueObjS.compareTo(value1S) == 0;
else if (OPERATION_Gt.equals(op))
return valueObjS.compareTo(value1S) > 0;
else if (OPERATION_GtEq.equals(op))
return valueObjS.compareTo(value1S) >= 0;
else if (OPERATION_Le.equals(op))
return valueObjS.compareTo(value1S) < 0;
else if (OPERATION_LeEq.equals(op))
return valueObjS.compareTo(value1S) <= 0;
else if (OPERATION_Like.equals(op))
return valueObjS.compareTo(value1S) == 0; | else if (OPERATION_NotEq.equals(op))
return valueObjS.compareTo(value1S) != 0;
//
else if (OPERATION_Sql.equals(op))
throw new IllegalArgumentException("SQL not Implemented");
//
else if (OPERATION_X.equals(op))
{
if (valueObjS.compareTo(value1S) < 0)
return false;
// To
return valueObjS.compareTo(value2S) <= 0;
}
//
throw new IllegalArgumentException("Unknown Operation=" + op);
} // compareString
} // MForcastLine | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MQMSpecificationLine.java | 1 |
请完成以下Java代码 | public String getFillValue() {
return "none";
}
@Override
public String getStrokeValue() {
return "#585858";
}
@Override
public String getDValue() {
return " M21.820839 10.171502 L18.36734 23.58992 L12.541380000000002 13.281818999999999 L8.338651200000001 19.071607 L12.048949000000002 5.832305699999999 L17.996148000000005 15.132659 L21.820839 10.171502 z";
}
public void drawIcon(
final int imageX,
final int imageY,
final int iconPadding,
final ProcessDiagramSVGGraphics2D svgGenerator
) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 6) + "," + (imageY - 3) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "style", this.getStyleValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue()); | gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getAnchorValue() {
return null;
}
@Override
public String getStyleValue() {
return "fill:none;stroke-width:1.5;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10";
}
@Override
public Integer getWidth() {
return 17;
}
@Override
public Integer getHeight() {
return 22;
}
@Override
public String getStrokeWidth() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\ErrorIconType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DunningDocId implements RepoIdAware
{
@JsonCreator
public static DunningDocId ofRepoId(final int repoId)
{
return new DunningDocId(repoId);
}
public static DunningDocId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new DunningDocId(repoId) : null;
}
public static int getRepoIdOr(final DunningDocId dunningDocId, final int defaultValue)
{
return dunningDocId != null ? dunningDocId.getRepoId() : defaultValue;
}
int repoId; | private DunningDocId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public TableRecordReference toRecordRef() {return TableRecordReference.of(I_C_DunningDoc.Table_Name, repoId);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\DunningDocId.java | 2 |
请完成以下Java代码 | public void delete(Path path) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public void move(Path source, Path target, CopyOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
return path.equals(path2);
}
@Override
public boolean isHidden(Path path) throws IOException {
return false;
}
@Override
public FileStore getFileStore(Path path) throws IOException {
NestedPath nestedPath = NestedPath.cast(path);
nestedPath.assertExists();
return new NestedFileStore(nestedPath.getFileSystem());
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
Path jarPath = getJarPath(path);
jarPath.getFileSystem().provider().checkAccess(jarPath, modes); | }
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options);
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options);
}
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options);
}
protected Path getJarPath(Path path) {
return NestedPath.cast(path).getJarPath();
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java | 1 |
请完成以下Java代码 | public void setElementIndexVariable(String elementIndexVariable) {
this.elementIndexVariable = elementIndexVariable;
}
public boolean isSequential() {
return sequential;
}
public void setSequential(boolean sequential) {
this.sequential = sequential;
}
public boolean isNoWaitStatesAsyncLeave() {
return noWaitStatesAsyncLeave;
}
public void setNoWaitStatesAsyncLeave(boolean noWaitStatesAsyncLeave) {
this.noWaitStatesAsyncLeave = noWaitStatesAsyncLeave;
}
public VariableAggregationDefinitions getAggregations() {
return aggregations;
}
public void setAggregations(VariableAggregationDefinitions aggregations) {
this.aggregations = aggregations;
}
public void addAggregation(VariableAggregationDefinition aggregation) {
if (this.aggregations == null) {
this.aggregations = new VariableAggregationDefinitions();
}
this.aggregations.getAggregations().add(aggregation);
}
@Override
public MultiInstanceLoopCharacteristics clone() { | MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics();
clone.setValues(this);
return clone;
}
public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) {
super.setValues(otherLoopCharacteristics);
setInputDataItem(otherLoopCharacteristics.getInputDataItem());
setCollectionString(otherLoopCharacteristics.getCollectionString());
if (otherLoopCharacteristics.getHandler() != null) {
setHandler(otherLoopCharacteristics.getHandler().clone());
}
setLoopCardinality(otherLoopCharacteristics.getLoopCardinality());
setCompletionCondition(otherLoopCharacteristics.getCompletionCondition());
setElementVariable(otherLoopCharacteristics.getElementVariable());
setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable());
setSequential(otherLoopCharacteristics.isSequential());
setNoWaitStatesAsyncLeave(otherLoopCharacteristics.isNoWaitStatesAsyncLeave());
if (otherLoopCharacteristics.getAggregations() != null) {
setAggregations(otherLoopCharacteristics.getAggregations().clone());
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MultiInstanceLoopCharacteristics.java | 1 |
请完成以下Java代码 | public Builder withProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
return this;
}
/**
* Builder method for configuration parameter.
* @param configuration field to set
* @return builder
*/
public Builder withConfiguration(String configuration) {
this.configuration = configuration;
return this;
}
/**
* Builder method for activityId parameter.
* @param activityId field to set
* @return builder
*/
public Builder withActivityId(String activityId) {
this.activityId = activityId;
return this; | }
/**
* Builder method for created parameter.
* @param created field to set
* @return builder
*/
public Builder withCreated(Date created) {
this.created = created;
return this;
}
/**
* Builder method of the builder.
* @return built class
*/
public StartMessageSubscriptionImpl build() {
return new StartMessageSubscriptionImpl(this);
}
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\StartMessageSubscriptionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEnabled() {
return this.enabled;
}
public InetAddress getRemoteAddress() {
return this.remoteAddress;
}
public Security getSecurity() {
return this.security;
}
// @fold:off
public static class Security {
// @fold:on // fields...
private final String username;
private final String password;
private final List<String> roles;
// @fold:off | public Security(String username, String password, @DefaultValue("USER") List<String> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
// @fold:on // getters...
public String getUsername() {
return this.username;
}
public String getPassword() {
return this.password;
}
public List<String> getRoles() {
return this.roles;
}
// @fold:off
}
} | repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\features\externalconfig\typesafeconfigurationproperties\constructorbinding\MyProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ApiAuditConfig getConfigById(@NonNull final ApiAuditConfigId id)
{
return getMap().getConfigById(id);
}
private ApiAuditConfigsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private ApiAuditConfigsMap retrieveMap()
{
return ApiAuditConfigsMap.ofList(
queryBL.createQueryBuilder(I_API_Audit_Config.class)
.create()
.stream()
.map(ApiAuditConfigRepository::fromRecord)
.collect(ImmutableList.toImmutableList()));
}
@NonNull
private static ApiAuditConfig fromRecord(@NonNull final I_API_Audit_Config record)
{ | return ApiAuditConfig.builder()
.apiAuditConfigId(ApiAuditConfigId.ofRepoId(record.getAPI_Audit_Config_ID()))
.active(record.isActive())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.seqNo(record.getSeqNo())
.isBypassAudit(record.isBypassAudit())
.forceProcessedAsync(record.isForceProcessedAsync())
.keepRequestDays(record.getKeepRequestDays())
.keepRequestBodyDays(record.getKeepRequestBodyDays())
.keepResponseDays(record.getKeepResponseDays())
.keepResponseBodyDays(record.getKeepResponseBodyDays())
.keepErroredRequestDays(record.getKeepErroredRequestDays())
.method(HttpMethod.ofNullableCode(record.getMethod()))
.pathPrefix(record.getPathPrefix())
.notifyUserInCharge(NotificationTriggerType.ofNullableCode(record.getNotifyUserInCharge()))
.userGroupInChargeId(UserGroupId.ofRepoIdOrNull(record.getAD_UserGroup_InCharge_ID()))
.performAuditAsync(!record.isSynchronousAuditLoggingEnabled())
.wrapApiResponse(record.isWrapApiResponse())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\config\ApiAuditConfigRepository.java | 2 |
请完成以下Java代码 | private <T> List<String> appendImports(Stream<T> candidates, Function<T, Collection<String>> mapping) {
return candidates.map(mapping).flatMap(Collection::stream).collect(Collectors.toList());
}
private String getUnqualifiedName(String name) {
if (!name.contains(".")) {
return name;
}
return name.substring(name.lastIndexOf(".") + 1);
}
private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) {
if (name == null || !name.contains(".")) {
return false;
}
String packageName = name.substring(0, name.lastIndexOf('.'));
return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName);
}
static class KotlinFormattingOptions implements FormattingOptions { | @Override
public String statementSeparator() {
return "";
}
@Override
public CodeBlock arrayOf(CodeBlock... values) {
return CodeBlock.of("[$L]", CodeBlock.join(Arrays.asList(values), ", "));
}
@Override
public CodeBlock classReference(ClassName className) {
return CodeBlock.of("$T::class", className);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinSourceCodeWriter.java | 1 |
请完成以下Java代码 | public void setDerKurier_DeliveryOrderLine_Package_ID (int DerKurier_DeliveryOrderLine_Package_ID)
{
if (DerKurier_DeliveryOrderLine_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID, Integer.valueOf(DerKurier_DeliveryOrderLine_Package_ID));
}
/** Get DerKurier_DeliveryOrderLine_Package.
@return DerKurier_DeliveryOrderLine_Package */
@Override
public int getDerKurier_DeliveryOrderLine_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Package getM_Package() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
} | /** Set Packstück.
@param M_Package_ID
Shipment Package
*/
@Override
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get Packstück.
@return Shipment Package
*/
@Override
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine_Package.java | 1 |
请完成以下Java代码 | public boolean isVersionTagBinding() {
CallableElementBinding binding = getBinding();
return CallableElementBinding.VERSION_TAG.equals(binding);
}
public Integer getVersion(VariableScope variableScope) {
Object result = versionValueProvider.getValue(variableScope);
if (result != null) {
if (result instanceof String) {
return Integer.valueOf((String) result);
} else if (result instanceof Integer) {
return (Integer) result;
} else {
throw new ProcessEngineException("It is not possible to transform '"+result+"' into an integer.");
}
}
return null;
}
public ParameterValueProvider getVersionValueProvider() {
return versionValueProvider;
}
public void setVersionValueProvider(ParameterValueProvider version) {
this.versionValueProvider = version;
}
public String getVersionTag(VariableScope variableScope) {
Object result = versionTagValueProvider.getValue(variableScope);
if (result != null) {
if (result instanceof String) {
return (String) result;
} else {
throw new ProcessEngineException("It is not possible to transform '"+result+"' into a string.");
}
}
return null;
}
public ParameterValueProvider getVersionTagValueProvider() { | return versionTagValueProvider;
}
public void setVersionTagValueProvider(ParameterValueProvider version) {
this.versionTagValueProvider = version;
}
public void setTenantIdProvider(ParameterValueProvider tenantIdProvider) {
this.tenantIdProvider = tenantIdProvider;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getDefinitionTenantId(VariableScope variableScope, String defaultTenantId) {
if (tenantIdProvider != null) {
return (String) tenantIdProvider.getValue(variableScope);
} else {
return defaultTenantId;
}
}
public ParameterValueProvider getTenantIdProvider() {
return tenantIdProvider;
}
/**
* @return true if any of the references that specify the callable element are non-literal and need to be resolved with
* potential side effects to determine the process or case definition that is to be called.
*/
public boolean hasDynamicReferences() {
return (tenantIdProvider != null && tenantIdProvider.isDynamic())
|| definitionKeyValueProvider.isDynamic()
|| versionValueProvider.isDynamic()
|| versionTagValueProvider.isDynamic();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\BaseCallableElement.java | 1 |
请完成以下Java代码 | protected ImportRecordResult importRecord(final @NonNull IMutable<Object> state,
final @NonNull I_I_User importRecord,
final boolean isInsertOnly) throws Exception
{
//
// Create a new user
final I_AD_User user = InterfaceWrapperHelper.newInstance(I_AD_User.class, importRecord);
user.setAD_Org_ID(importRecord.getAD_Org_ID());
//
// BPartner
{
int bpartnerId = importRecord.getC_BPartner_ID();
if (bpartnerId <= 0)
{
throw new AdempiereException("BPartner not found");
}
user.setC_BPartner_ID(bpartnerId);
}
//
// set data from the other fields
setUserFieldsAndSave(user, importRecord);
//
// Assign Role
final RoleId roleId = RoleId.ofRepoIdOrNull(importRecord.getAD_Role_ID());
if (roleId != null)
{
final UserId userId = UserId.ofRepoId(user.getAD_User_ID());
Services.get(IRoleDAO.class).createUserRoleAssignmentIfMissing(userId, roleId);
}
//
// Link back the request to current import record
importRecord.setAD_User_ID(user.getAD_User_ID());
//
return ImportRecordResult.Inserted;
}
private void setUserFieldsAndSave(@NonNull final I_AD_User user, @NonNull final I_I_User importRecord)
{
user.setFirstname(importRecord.getFirstname());
user.setLastname(importRecord.getLastname());
// set value after we set first name and last name | user.setValue(importRecord.getUserValue());
user.setEMail(importRecord.getEMail());
user.setIsNewsletter(importRecord.isNewsletter());
user.setPhone(importRecord.getPhone());
user.setFax(importRecord.getFax());
user.setMobilePhone(importRecord.getMobilePhone());
// user.gen
final I_AD_User loginUser = InterfaceWrapperHelper.create(user, I_AD_User.class);
loginUser.setLogin(importRecord.getLogin());
loginUser.setIsSystemUser(importRecord.isSystemUser());
final IUserBL userBL = Services.get(IUserBL.class);
userBL.changePasswordAndSave(loginUser, RandomStringUtils.randomAlphanumeric(8));
}
@Override
protected void markImported(final I_I_User importRecord)
{
importRecord.setI_IsImported(X_I_User.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\impexp\ADUserImportProcess.java | 1 |
请完成以下Java代码 | public int getM_Product_Category_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_Matching_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyPerDelivery (final BigDecimal QtyPerDelivery)
{
set_Value (COLUMNNAME_QtyPerDelivery, QtyPerDelivery);
}
@Override
public BigDecimal getQtyPerDelivery() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPerDelivery);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Matching.java | 1 |
请完成以下Java代码 | public Properties getCtx()
{
return getDocument().getCtx();
}
@Override
public String getTableName()
{
return getDocument().getEntityDescriptor().getTableName();
}
@Override
public String getColumnName()
{
return documentField.getFieldName();
}
@Override
public Object getValue()
{
return documentField.getValue();
}
@Override
public Object getOldValue()
{
return documentField.getOldValue();
}
@Override
public int getWindowNo()
{
return getDocument().getWindowNo();
}
@Override
public boolean isRecordCopyingMode()
{
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isRecordCopyingModeIncludingDetails()
{
// TODO Auto-generated method stub
return false;
}
@Override
public ICalloutExecutor getCurrentCalloutExecutor()
{
return getDocument().getFieldCalloutExecutor();
}
@Override
public void fireDataStatusEEvent(@NonNull final String captionAD_Message, final String message, final boolean isError)
{
final IDocumentChangesCollector changesCollector = Execution.getCurrentDocumentChangesCollectorOrNull();
if (NullDocumentChangesCollector.isNull(changesCollector))
{
logger.warn("Got WARNING on field {} but there is no changes collector to dispatch"
+ "\n captionAD_Message={}"
+ "\n message={}"
+ "\n isError={}",
documentField, captionAD_Message, message, isError);
}
else
{
changesCollector.collectFieldWarning(documentField, DocumentFieldWarning.builder()
.caption(Services.get(IMsgBL.class).translatable(captionAD_Message))
.message(message)
.error(isError)
.build());
}
}
@Override
public void fireDataStatusEEvent(final ValueNamePair errorLog)
{
final boolean isError = true;
fireDataStatusEEvent(errorLog.getValue(), errorLog.getName(), isError);
}
@Override
public void putContext(final String name, final boolean value) | {
getDocument().setDynAttribute(name, value);
}
@Override
public void putContext(final String name, final java.util.Date value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public void putContext(final String name, final int value)
{
getDocument().setDynAttribute(name, value);
}
@Override
public boolean getContextAsBoolean(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
return DisplayType.toBoolean(valueObj);
}
@Override
public int getContextAsInt(final String name)
{
final Object valueObj = getDocument().getDynAttribute(name);
if (valueObj == null)
{
return -1;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else
{
return Integer.parseInt(valueObj.toString());
}
}
@Override
public ICalloutRecord getCalloutRecord()
{
return getDocument().asCalloutRecord();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final RepoIdAware id)
{
return documentField.getLookupValueById(id) != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldAsCalloutField.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getApplicationDisplayName() {
return this.applicationDisplayName;
}
public void setApplicationDisplayName(String displayName) {
this.applicationDisplayName = displayName;
}
public boolean isRegisterDefaultServlet() {
return this.registerDefaultServlet;
}
public void setRegisterDefaultServlet(boolean registerDefaultServlet) {
this.registerDefaultServlet = registerDefaultServlet;
}
public Map<String, String> getContextParameters() {
return this.contextParameters;
}
public Encoding getEncoding() {
return this.encoding;
}
public Jsp getJsp() {
return this.jsp;
}
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
} | /**
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java | 2 |
请完成以下Java代码 | private String applyTransformation(Document doc) throws TransformerException, IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
try (Writer output = new StringWriter()) {
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(output));
return output.toString();
}
}
private Map<String, String> buildMap(Element xml) {
Map<String, String> map = new HashMap<>();
map.put("heading", xml
.getElementsByTagName("heading")
.item(0)
.getTextContent());
map.put("from", String.format("from: %s", xml
.getElementsByTagName("from")
.item(0)
.getTextContent()));
map.put("content", xml
.getElementsByTagName("content")
.item(0)
.getTextContent());
return map;
}
private Element buildHead(Map<String, String> map, Document doc) {
Element head = doc.createElement("head");
Element title = doc.createElement("title");
title.setTextContent(map.get("heading")); | head.appendChild(title);
return head;
}
private Element buildBody(Map<String, String> map, Document doc) {
Element body = doc.createElement("body");
Element from = doc.createElement("p");
from.setTextContent(map.get("from"));
Element success = doc.createElement("p");
success.setTextContent(map.get("content"));
body.appendChild(from);
body.appendChild(success);
return body;
}
} | repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xmlhtml\jaxp\JaxpTransformer.java | 1 |
请完成以下Java代码 | public class ProducerExtendsConsumerSupers {
public void producerExtends() {
List<Operator> operators = Arrays.asList(new Operator("sam"), new Operator("daniel"));
List<Customer> customers = Arrays.asList(new Customer("arys"), new Customer("cristiana"));
// sendEmails(operators); --> will not compile!
sendEmailsFixed(operators);
sendEmailsFixed(customers);
}
private void sendEmails(List<User> users) {
for (User user : users) {
System.out.println("sending email to " + user);
}
}
private void sendEmailsFixed(List<? extends User> users) {
for (User user : users) {
System.out.println("sending email to " + user);
}
}
public void consumerSupers() {
List<Operator> allOperators = Arrays.asList(new Operator("tom"));
List<User> allUsers = Arrays.asList(new Operator("tom"), new Customer("spencer"));
// addUsersFromMarketingDepartment(allUsers); --> will not compile!
addUsersFromMarketingDepartmentFixed(allOperators); | addUsersFromMarketingDepartmentFixed(allUsers);
}
private void addUsersFromMarketingDepartment(List<Operator> users) {
users.add(new Operator("john doe"));
users.add(new Operator("jane doe"));
}
private void addUsersFromMarketingDepartmentFixed(List<? super Operator> users) {
users.add(new Operator("john doe"));
users.add(new Operator("jane doe"));
}
private void addUsersAndSendEmails(List<User> users) {
users.add(new Operator("john doe"));
for (User user : users) {
System.out.println("sending email to: " + user);
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\pecs\ProducerExtendsConsumerSupers.java | 1 |
请完成以下Java代码 | public List<String> shortcutFieldOrder() {
return Arrays.asList(HEADER_KEY, REGEXP_KEY);
}
@Override
public Predicate<ServerWebExchange> apply(Config config) {
Pattern pattern = (StringUtils.hasText(config.regexp)) ? Pattern.compile(config.regexp) : null;
return new GatewayPredicate() {
@Override
public boolean test(ServerWebExchange exchange) {
if (!StringUtils.hasText(config.header)) {
return false;
}
List<String> values = exchange.getRequest().getHeaders().getValuesAsList(config.header);
if (values.isEmpty()) {
return false;
}
// values is now guaranteed to not be empty
if (pattern != null) {
// check if a header value matches
for (int i = 0; i < values.size(); i++) {
String value = values.get(i);
if (pattern.asMatchPredicate().test(value)) {
return true;
}
}
return false;
}
// there is a value and since regexp is empty, we only check existence.
return true;
}
@Override
public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("Header: %s regexp=%s", config.header, config.regexp);
}
};
} | public static class Config {
@NotEmpty
private @Nullable String header;
private @Nullable String regexp;
public @Nullable String getHeader() {
return header;
}
public Config setHeader(String header) {
this.header = header;
return this;
}
public @Nullable String getRegexp() {
return regexp;
}
public Config setRegexp(@Nullable String regexp) {
this.regexp = regexp;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\HeaderRoutePredicateFactory.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.