instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class Cockpit {
/**
* The {@link CockpitRuntimeDelegate} is an delegate that will be
* initialized by bootstrapping camunda cockpit with an specific
* instance
*/
protected static CockpitRuntimeDelegate COCKPIT_RUNTIME_DELEGATE;
/**
* Returns a configured {@link QueryService} to execute custom
* statements to the corresponding process engine
*
* @param processEngineName
*
* @return a {@link QueryService}
*/
public static QueryService getQueryService(String processEngineName) {
return getRuntimeDelegate().getQueryService(processEngineName);
}
/**
* Returns a configured {@link CommandExecutor} to execute
* commands to the corresponding process engine
*
* @param processEngineName
*
* @return a {@link CommandExecutor}
*/
public static CommandExecutor getCommandExecutor(String processEngineName) {
return getRuntimeDelegate().getCommandExecutor(processEngineName);
}
public static ProcessEngine getProcessEngine(String processEngineName) { | return getRuntimeDelegate().getProcessEngine(processEngineName);
}
/**
* Returns an instance of {@link CockpitRuntimeDelegate}
*
* @return
*/
public static CockpitRuntimeDelegate getRuntimeDelegate() {
return COCKPIT_RUNTIME_DELEGATE;
}
/**
* A setter to set the {@link CockpitRuntimeDelegate}.
* @param cockpitRuntimeDelegate
*/
public static void setCockpitRuntimeDelegate(CockpitRuntimeDelegate cockpitRuntimeDelegate) {
COCKPIT_RUNTIME_DELEGATE = cockpitRuntimeDelegate;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\Cockpit.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void applyReaderBuilderCustomizers(List<ReaderBuilderCustomizer<?>> customizers, ReaderBuilder<?> builder) {
LambdaSafe.callbacks(ReaderBuilderCustomizer.class, customizers, builder)
.invoke((customizer) -> customizer.customize(builder));
}
@Bean
@ConditionalOnMissingBean(name = "pulsarReaderContainerFactory")
DefaultPulsarReaderContainerFactory<?> pulsarReaderContainerFactory(PulsarReaderFactory<?> pulsarReaderFactory,
SchemaResolver schemaResolver, Environment environment,
PulsarContainerFactoryCustomizers containerFactoryCustomizers) {
PulsarReaderContainerProperties readerContainerProperties = new PulsarReaderContainerProperties();
readerContainerProperties.setSchemaResolver(schemaResolver);
if (Threading.VIRTUAL.isActive(environment)) {
readerContainerProperties.setReaderTaskExecutor(new VirtualThreadTaskExecutor("pulsar-reader-"));
} | this.propertiesMapper.customizeReaderContainerProperties(readerContainerProperties);
DefaultPulsarReaderContainerFactory<?> containerFactory = new DefaultPulsarReaderContainerFactory<>(
pulsarReaderFactory, readerContainerProperties);
containerFactoryCustomizers.customize(containerFactory);
return containerFactory;
}
@Configuration(proxyBeanMethods = false)
@EnablePulsar
@ConditionalOnMissingBean(name = { PulsarAnnotationSupportBeanNames.PULSAR_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME,
PulsarAnnotationSupportBeanNames.PULSAR_READER_ANNOTATION_PROCESSOR_BEAN_NAME })
static class EnablePulsarConfiguration {
}
} | repos\spring-boot-4.0.1\module\spring-boot-pulsar\src\main\java\org\springframework\boot\pulsar\autoconfigure\PulsarAutoConfiguration.java | 2 |
请完成以下Java代码 | public EventRegistryEngine getObject() throws Exception {
configureExternallyManagedTransactions();
if (eventEngineConfiguration.getBeans() == null) {
eventEngineConfiguration.setBeans(new SpringBeanFactoryProxyMap(applicationContext));
}
this.eventRegistryEngine = eventEngineConfiguration.buildEventRegistryEngine();
return this.eventRegistryEngine;
}
protected void configureExternallyManagedTransactions() {
if (eventEngineConfiguration instanceof SpringEventRegistryEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringEventRegistryEngineConfiguration engineConfiguration = (SpringEventRegistryEngineConfiguration) eventEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
eventEngineConfiguration.setTransactionsExternallyManaged(true);
}
}
} | @Override
public Class<EventRegistryEngine> getObjectType() {
return EventRegistryEngine.class;
}
@Override
public boolean isSingleton() {
return true;
}
public EventRegistryEngineConfiguration getEventEngineConfiguration() {
return eventEngineConfiguration;
}
public void setEventEngineConfiguration(EventRegistryEngineConfiguration eventEngineConfiguration) {
this.eventEngineConfiguration = eventEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\EventRegistryFactoryBean.java | 1 |
请完成以下Java代码 | private static String getErrorMessage(Long currentRequestSize, Long maxSize) {
return String.format(ERROR, getReadableByteCount(currentRequestSize), getReadableByteCount(maxSize));
}
private static String getReadableByteCount(long bytes) {
int unit = 1000;
if (bytes < unit) {
return bytes + " B";
}
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = Character.toString(PREFIX.charAt(exp - 1));
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
@Override
public GatewayFilter apply(RequestSizeGatewayFilterFactory.RequestSizeConfig requestSizeConfig) {
requestSizeConfig.validate();
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String contentLength = request.getHeaders().getFirst("content-length");
if (!ObjectUtils.isEmpty(contentLength)) {
Long currentRequestSize = Long.valueOf(contentLength);
if (currentRequestSize > requestSizeConfig.getMaxSize().toBytes()) {
exchange.getResponse().setStatusCode(HttpStatus.CONTENT_TOO_LARGE);
if (!exchange.getResponse().isCommitted()) {
exchange.getResponse()
.getHeaders()
.add("errorMessage",
getErrorMessage(currentRequestSize, requestSizeConfig.getMaxSize().toBytes()));
}
return exchange.getResponse().setComplete();
}
}
return chain.filter(exchange);
} | @Override
public String toString() {
return filterToStringCreator(RequestSizeGatewayFilterFactory.this)
.append("max", requestSizeConfig.getMaxSize())
.toString();
}
};
}
public static class RequestSizeConfig {
// TODO: use boot data size type
private DataSize maxSize = DataSize.ofBytes(5000000L);
public DataSize getMaxSize() {
return maxSize;
}
public RequestSizeGatewayFilterFactory.RequestSizeConfig setMaxSize(DataSize maxSize) {
this.maxSize = maxSize;
return this;
}
// TODO: use validator annotation
public void validate() {
Objects.requireNonNull(this.maxSize, "maxSize may not be null");
Assert.isTrue(this.maxSize.toBytes() > 0, "maxSize must be greater than 0");
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestSizeGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public void setM_Nutrition_Fact_ID (int M_Nutrition_Fact_ID)
{
if (M_Nutrition_Fact_ID < 1)
set_Value (COLUMNNAME_M_Nutrition_Fact_ID, null);
else
set_Value (COLUMNNAME_M_Nutrition_Fact_ID, Integer.valueOf(M_Nutrition_Fact_ID));
}
/** Get Nutrition Fact.
@return Nutrition Fact */
@Override
public int getM_Nutrition_Fact_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Nutrition_Fact_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Product Nutrition.
@param M_Product_Nutrition_ID Product Nutrition */
@Override
public void setM_Product_Nutrition_ID (int M_Product_Nutrition_ID)
{
if (M_Product_Nutrition_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_Nutrition_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_Nutrition_ID, Integer.valueOf(M_Product_Nutrition_ID));
}
/** Get Product Nutrition.
@return Product Nutrition */
@Override
public int getM_Product_Nutrition_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Nutrition_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Nutrition Quanitity.
@param NutritionQty Nutrition Quanitity */
@Override
public void setNutritionQty (java.lang.String NutritionQty)
{
set_Value (COLUMNNAME_NutritionQty, NutritionQty);
}
/** Get Nutrition Quanitity.
@return Nutrition Quanitity */
@Override
public java.lang.String getNutritionQty ()
{
return (java.lang.String)get_Value(COLUMNNAME_NutritionQty);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Nutrition.java | 1 |
请完成以下Java代码 | public List<I_AD_User_SortPref_Line> retrieveConferenceSortPreferenceLines(final Properties ctx, final String action, final int recordId)
{
final I_AD_User_SortPref_Hdr hdr = retrieveConferenceSortPreferenceHdr(ctx, action, recordId);
return retrieveSortPreferenceLines(hdr);
}
@Override
public List<I_AD_User_SortPref_Line_Product> retrieveSortPreferenceLineProducts(final I_AD_User_SortPref_Line sortPreferenceLine)
{
//
// Services
final IQueryBL queryBL = Services.get(IQueryBL.class);
final Object contextProvider = sortPreferenceLine;
final IQueryBuilder<I_AD_User_SortPref_Line_Product> queryBuilder = queryBL.createQueryBuilder(I_AD_User_SortPref_Line_Product.class, contextProvider)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User_SortPref_Line_Product.COLUMN_AD_User_SortPref_Line_ID, sortPreferenceLine.getAD_User_SortPref_Line_ID());
final IQueryOrderBy orderBy = queryBL.createQueryOrderByBuilder(I_AD_User_SortPref_Line_Product.class)
.addColumn(I_AD_User_SortPref_Line_Product.COLUMN_SeqNo)
.createQueryOrderBy();
return queryBuilder.create()
.setOrderBy(orderBy)
.list(I_AD_User_SortPref_Line_Product.class);
}
@Override
public int clearSortPreferenceLines(final I_AD_User_SortPref_Hdr hdr)
{ | final IQueryBL queryBL = Services.get(IQueryBL.class);
int count = 0;
final List<I_AD_User_SortPref_Line> linesToDelete = retrieveSortPreferenceLines(hdr);
for (final I_AD_User_SortPref_Line line : linesToDelete)
{
final int countProductLinesDeleted = queryBL.createQueryBuilder(I_AD_User_SortPref_Line_Product.class, hdr)
.addEqualsFilter(I_AD_User_SortPref_Line_Product.COLUMN_AD_User_SortPref_Line_ID, line.getAD_User_SortPref_Line_ID())
.create()
.deleteDirectly();
count += countProductLinesDeleted;
InterfaceWrapperHelper.delete(line);
count++;
}
logger.info("Deleted {} records in sum", count);
return count;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserSortPrefDAO.java | 1 |
请完成以下Java代码 | public I_AD_ReplicationTable getAD_ReplicationTable() throws RuntimeException
{
return (I_AD_ReplicationTable)MTable.get(getCtx(), I_AD_ReplicationTable.Table_Name)
.getPO(getAD_ReplicationTable_ID(), get_TrxName()); }
/** Set Replication Table.
@param AD_ReplicationTable_ID
Data Replication Strategy Table Info
*/
public void setAD_ReplicationTable_ID (int AD_ReplicationTable_ID)
{
if (AD_ReplicationTable_ID < 1)
set_Value (COLUMNNAME_AD_ReplicationTable_ID, null);
else
set_Value (COLUMNNAME_AD_ReplicationTable_ID, Integer.valueOf(AD_ReplicationTable_ID));
}
/** Get Replication Table.
@return Data Replication Strategy Table Info
*/
public int getAD_ReplicationTable_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_ReplicationTable_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Replicated.
@param IsReplicated
The data is successfully replicated
*/
public void setIsReplicated (boolean IsReplicated)
{ | set_Value (COLUMNNAME_IsReplicated, Boolean.valueOf(IsReplicated));
}
/** Get Replicated.
@return The data is successfully replicated
*/
public boolean isReplicated ()
{
Object oo = get_Value(COLUMNNAME_IsReplicated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Message.
@param P_Msg Process Message */
public void setP_Msg (String P_Msg)
{
set_Value (COLUMNNAME_P_Msg, P_Msg);
}
/** Get Process Message.
@return Process Message */
public String getP_Msg ()
{
return (String)get_Value(COLUMNNAME_P_Msg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication_Log.java | 1 |
请完成以下Java代码 | public static DateTruncQueryFilterModifier forTruncString(final String trunc)
{
if (TimeUtil.TRUNC_DAY.equals(trunc))
{
return DAY;
}
else if (TimeUtil.TRUNC_WEEK.equals(trunc))
{
return WEEK;
}
else if (TimeUtil.TRUNC_MONTH.equals(trunc))
{
return MONTH;
}
else if (TimeUtil.TRUNC_YEAR.equals(trunc))
{
return YEAR;
}
else
{
return new DateTruncQueryFilterModifier(trunc);
}
}
private final String trunc;
private final String truncSql;
/**
*
* @param trunc see {@link TimeUtil}.TRUNC_*
*/
protected DateTruncQueryFilterModifier(final String trunc)
{
this.trunc = trunc;
if (trunc == null)
{
truncSql = null;
}
else
{
truncSql = getTruncSql(trunc);
}
}
@Override
public String toString()
{
return "DateTrunc-" + trunc;
}
/**
* Convert {@link TimeUtil}.TRUNC_* values to their correspondent TRUNC db function parameter
*
* @param trunc
* @return
*/
private static String getTruncSql(final String trunc)
{
if (TimeUtil.TRUNC_DAY.equals(trunc))
{
return "DD";
}
else if (TimeUtil.TRUNC_WEEK.equals(trunc))
{
return "WW";
}
else if (TimeUtil.TRUNC_MONTH.equals(trunc))
{
return "MM";
}
else if (TimeUtil.TRUNC_YEAR.equals(trunc))
{
return "Y";
}
else if (TimeUtil.TRUNC_QUARTER.equals(trunc))
{
return "Q";
}
else
{
throw new IllegalArgumentException("Invalid date truncate option: " + trunc);
}
}
@Override
public @NonNull String getColumnSql(final @NonNull String columnName)
{
if (truncSql == null)
{
return columnName;
}
// TODO: optimization: instead of using TRUNC we shall use BETWEEN and precalculated values because:
// * using BETWEEN is INDEX friendly | // * using functions is not INDEX friendly at all and if we have an index on this date column, the index won't be used
final String columnSqlNew = "TRUNC(" + columnName + ", " + DB.TO_STRING(truncSql) + ")";
return columnSqlNew;
}
@Override
public String getValueSql(final Object value, final List<Object> params)
{
final String valueSql;
if (value instanceof ModelColumnNameValue<?>)
{
final ModelColumnNameValue<?> modelValue = (ModelColumnNameValue<?>)value;
valueSql = modelValue.getColumnName();
}
else
{
valueSql = "?";
params.add(value);
}
if (truncSql == null)
{
return valueSql;
}
// note: cast is needed for postgresql, else you get "ERROR: function trunc(unknown, unknown) is not unique"
return "TRUNC(?::timestamp, " + DB.TO_STRING(truncSql) + ")";
}
/**
* @deprecated Please use {@link #convertValue(java.util.Date)}
*/
@Nullable
@Override
@Deprecated
public Object convertValue(@Nullable final String columnName, @Nullable final Object value, final @Nullable Object model)
{
return convertValue(TimeUtil.asTimestamp(value));
}
public java.util.Date convertValue(final java.util.Date date)
{
if (date == null)
{
return null;
}
return TimeUtil.trunc(date, trunc);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateTruncQueryFilterModifier.java | 1 |
请完成以下Java代码 | public void setLastReceiptDate (java.sql.Timestamp LastReceiptDate)
{
set_ValueNoCheck (COLUMNNAME_LastReceiptDate, LastReceiptDate);
}
/** Get Letzter Wareneingang.
@return Letzter Wareneingang */
@Override
public java.sql.Timestamp getLastReceiptDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastReceiptDate);
}
/** Set Letzte Lieferung.
@param LastShipDate Letzte Lieferung */
@Override
public void setLastShipDate (java.sql.Timestamp LastShipDate)
{
set_ValueNoCheck (COLUMNNAME_LastShipDate, LastShipDate);
}
/** Get Letzte Lieferung.
@return Letzte Lieferung */
@Override
public java.sql.Timestamp getLastShipDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt. | @param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_C_BPartner_Product_Stats_InOut_Online_v.java | 1 |
请完成以下Java代码 | public class ZkTest {
private static final String address = "127.0.0.1:2181";
private static final int session_timeout = 5000;
private static final CountDownLatch cout = new CountDownLatch(1);
private static Stat stat=new Stat();
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = new ZooKeeper(address, session_timeout, new Watcher() {
// 事件通知
@Override
public void process(WatchedEvent event) {
// 事件状态
Event.KeeperState state = event.getState();
// 连接状态
if (Event.KeeperState.SyncConnected == state) {
Event.EventType type = event.getType();
// 事件类型
if (Event.EventType.None == type) {
cout.countDown(); | System.out.println("--------zk开始连接.");
}
}
}
});
cout.await();
//创建节点
String path="/test";
String create = zk.create(path, "fzp".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("-------创建节点: " + create);
System.out.println(new String(zk.getData(path,true,stat)));
System.out.println(stat.getCzxid()+","+ stat.getMzxid()+","+stat.getVersion());
zk.setData(path,"123".getBytes(),-1);
zk.close();
}
} | repos\SpringBootLearning-master\version2.x\springboot-zk-demo\src\main\java\io\github\forezp\springbootzkdemo\ZkTest.java | 1 |
请完成以下Java代码 | public String getWhereClause(MTree_Base tree)
{
return null;
}
@Override
public void setParent_ID(MTree_Base tree, int nodeId, int parentId, String trxName)
{
final MTable table = MTable.get(tree.getCtx(), tree.getAD_Table_ID());
if (I_M_Product_Category.Table_Name.equals(table.getTableName()))
{
final I_M_Product_Category pc = InterfaceWrapperHelper.create(table.getPO(nodeId, trxName), I_M_Product_Category.class);
pc.setM_Product_Category_Parent_ID(parentId);
InterfaceWrapperHelper.save(pc);
}
}
@Override
public boolean isParentChanged(PO po)
{
return po.is_ValueChanged(I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID);
}
@Override
public int getOldParent_ID(PO po)
{
return po.get_ValueOldAsInt(I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID);
}
@Override
public String getParentIdSQL() | {
return I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID;
}
@Override
public MTreeNode getNodeInfo(GridTab gridTab)
{
MTreeNode info = super.getNodeInfo(gridTab);
info.setAllowsChildren(true); // we always allow children because IsSummary field will be automatically
// maintained
return info;
}
@Override
public MTreeNode loadNodeInfo(MTree tree, ResultSet rs) throws SQLException
{
MTreeNode info = super.loadNodeInfo(tree, rs);
info.setAllowsChildren(true); // we always allow children because IsSummary field will be automatically
info.setImageIndicator(I_M_Product_Category.Table_Name);
return info;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\tree\spi\impl\MProductCategoryTreeSupport.java | 1 |
请完成以下Java代码 | public Color getColor (int percent)
{
int AD_PrintColor_ID = 0;
if (percent <= getMark1Percent() || getMark2Percent() == 0)
AD_PrintColor_ID = getAD_PrintColor1_ID();
else if (percent <= getMark2Percent() || getMark3Percent() == 0)
AD_PrintColor_ID = getAD_PrintColor2_ID();
else if (percent <= getMark3Percent() || getMark4Percent() == 0)
AD_PrintColor_ID = getAD_PrintColor3_ID();
else
AD_PrintColor_ID = getAD_PrintColor4_ID();
if (AD_PrintColor_ID == 0)
{
if (getAD_PrintColor3_ID() != 0)
AD_PrintColor_ID = getAD_PrintColor3_ID();
else if (getAD_PrintColor2_ID() != 0)
AD_PrintColor_ID = getAD_PrintColor2_ID();
else if (getAD_PrintColor1_ID() != 0)
AD_PrintColor_ID = getAD_PrintColor1_ID();
}
if (AD_PrintColor_ID == 0) | return Color.black;
//
MPrintColor pc = MPrintColor.get(getCtx(), AD_PrintColor_ID);
if (pc != null)
return pc.getColor();
return Color.black;
} // getColor
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MColorSchema[");
sb.append (get_ID()).append ("-").append (getName()).append ("]");
return sb.toString ();
} // toString
} // MColorSchema | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MColorSchema.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class DefaultProfileUtil {
private static final String SPRING_PROFILE_DEFAULT = "spring.profiles.default";
private DefaultProfileUtil() {
}
/**
* Set a default to use when no profile is configured.
*
* @param app the Spring application
*/
public static void addDefaultProfile(SpringApplication app) {
Map<String, Object> defProperties = new HashMap<>();
/*
* The default profile to use when no other profiles are defined
* This cannot be set in the <code>application.yml</code> file.
* See https://github.com/spring-projects/spring-boot/issues/1219
*/
defProperties.put(SPRING_PROFILE_DEFAULT, JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); | app.setDefaultProperties(defProperties);
}
/**
* Get the profiles that are applied else get default profiles.
*
* @param env spring environment
* @return profiles
*/
public static String[] getActiveProfiles(Environment env) {
String[] profiles = env.getActiveProfiles();
if (profiles.length == 0) {
return env.getDefaultProfiles();
}
return profiles;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\DefaultProfileUtil.java | 2 |
请完成以下Java代码 | public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
/**
* DisposeReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int DISPOSEREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String DISPOSEREASON_NotFound = "N";
/** Damaged = D */
public static final String DISPOSEREASON_Damaged = "D";
@Override
public void setDisposeReason (final @Nullable java.lang.String DisposeReason)
{
set_Value (COLUMNNAME_DisposeReason, DisposeReason);
}
@Override
public java.lang.String getDisposeReason()
{
return get_ValueAsString(COLUMNNAME_DisposeReason);
}
@Override
public void setIsWholeHU (final boolean IsWholeHU)
{
set_Value (COLUMNNAME_IsWholeHU, IsWholeHU);
}
@Override
public boolean isWholeHU()
{
return get_ValueAsBoolean(COLUMNNAME_IsWholeHU);
}
@Override
public de.metas.handlingunits.model.I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
} | @Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_Inventory_Candidate_ID (final int M_Inventory_Candidate_ID)
{
if (M_Inventory_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Inventory_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Inventory_Candidate_ID, M_Inventory_Candidate_ID);
}
@Override
public int getM_Inventory_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Inventory_Candidate_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 setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToDispose (final BigDecimal QtyToDispose)
{
set_Value (COLUMNNAME_QtyToDispose, QtyToDispose);
}
@Override
public BigDecimal getQtyToDispose()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToDispose);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Inventory_Candidate.java | 1 |
请完成以下Java代码 | public Operation newInstance(ModelTypeInstanceContext instanceContext) {
return new OperationImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.required()
.build();
implementationRefAttribute = typeBuilder.stringAttribute(BPMN_ELEMENT_IMPLEMENTATION_REF)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inMessageRefChild = sequenceBuilder.element(InMessageRef.class)
.required()
.qNameElementReference(Message.class)
.build();
outMessageRefChild = sequenceBuilder.element(OutMessageRef.class)
.qNameElementReference(Message.class)
.build();
errorRefCollection = sequenceBuilder.elementCollection(ErrorRef.class)
.qNameElementReferenceCollection(Error.class)
.build();
typeBuilder.build();
}
public OperationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
} | public void setName(String name) {
nameAttribute.setValue(this, name);
}
public String getImplementationRef() {
return implementationRefAttribute.getValue(this);
}
public void setImplementationRef(String implementationRef) {
implementationRefAttribute.setValue(this, implementationRef);
}
public Message getInMessage() {
return inMessageRefChild.getReferenceTargetElement(this);
}
public void setInMessage(Message message) {
inMessageRefChild.setReferenceTargetElement(this, message);
}
public Message getOutMessage() {
return outMessageRefChild.getReferenceTargetElement(this);
}
public void setOutMessage(Message message) {
outMessageRefChild.setReferenceTargetElement(this, message);
}
public Collection<Error> getErrors() {
return errorRefCollection.getReferenceTargetElements(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\OperationImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DistributionProductService
{
private final IProductBL productBL = Services.get(IProductBL.class);
public ProductInfo getProductInfo(@NonNull final ProductId productId)
{
return ProductInfo.builder()
.productId(productId)
.caption(productBL.getProductNameTrl(productId))
.build();
}
public String getProductValueAndName(@NonNull ProductId productId)
{
return productBL.getProductValueAndName(productId);
}
public Optional<GTIN> getGTIN(@NonNull ProductId productId)
{
return productBL.getGTIN(productId);
}
public ProductId getProductIdByScannedProductCode(@NonNull final ScannedCode scannedProductCode) | {
ProductId productId = null;
final GTIN gtin = GTIN.ofScannedCode(scannedProductCode).orElse(null);
if (gtin != null)
{
productId = productBL.getProductIdByGTIN(gtin).orElse(null);
}
if (productId == null)
{
throw new AdempiereException("No product found for scanned product code: " + scannedProductCode);
}
return productId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\external_services\product\DistributionProductService.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class);
}
@Override
public void setC_DocType(org.compiere.model.I_C_DocType C_DocType)
{
set_ValueFromPO(COLUMNNAME_C_DocType_ID, org.compiere.model.I_C_DocType.class, C_DocType);
}
/** Set Belegart.
@param C_DocType_ID
Belegart oder Verarbeitungsvorgaben
*/
@Override
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Belegart.
@return Belegart oder Verarbeitungsvorgaben
*/
@Override
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Document Type Sequence assignment.
@param C_DocType_Sequence_ID Document Type Sequence assignment */
@Override
public void setC_DocType_Sequence_ID (int C_DocType_Sequence_ID)
{
if (C_DocType_Sequence_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DocType_Sequence_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocType_Sequence_ID, Integer.valueOf(C_DocType_Sequence_ID));
}
/** Get Document Type Sequence assignment.
@return Document Type Sequence assignment */
@Override
public int getC_DocType_Sequence_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_Sequence_ID); | if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Sequence getDocNoSequence() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class);
}
@Override
public void setDocNoSequence(org.compiere.model.I_AD_Sequence DocNoSequence)
{
set_ValueFromPO(COLUMNNAME_DocNoSequence_ID, org.compiere.model.I_AD_Sequence.class, DocNoSequence);
}
/** Set Nummernfolgen für Belege.
@param DocNoSequence_ID
Document sequence determines the numbering of documents
*/
@Override
public void setDocNoSequence_ID (int DocNoSequence_ID)
{
if (DocNoSequence_ID < 1)
set_Value (COLUMNNAME_DocNoSequence_ID, null);
else
set_Value (COLUMNNAME_DocNoSequence_ID, Integer.valueOf(DocNoSequence_ID));
}
/** Get Nummernfolgen für Belege.
@return Document sequence determines the numbering of documents
*/
@Override
public int getDocNoSequence_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DocNoSequence_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_C_DocType_Sequence.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BulkUpdateByQueryResult bulkUpdateByQuery(
@NonNull final SumUpTransactionQuery query,
boolean isForceSendingChangeEvents,
@NonNull final UnaryOperator<SumUpTransaction> updater)
{
trxManager.assertThreadInheritedTrxNotExists();
final AtomicInteger countOK = new AtomicInteger(0);
final AtomicInteger countError = new AtomicInteger(0);
try (IAutoCloseable ignored = SumUpEventsDispatcher.temporaryForceSendingChangeEventsIf(isForceSendingChangeEvents))
{
toSqlQuery(query)
.clearOrderBys()
.orderBy(I_SUMUP_Transaction.COLUMNNAME_SUMUP_Transaction_ID)
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
.iterateAndStream()
.forEach(record -> {
try
{
trxManager.runInThreadInheritedTrx(() -> updateRecord(record, updater));
countOK.incrementAndGet(); | }
catch (final Exception ex)
{
countError.incrementAndGet();
logger.warn("Failed updating transaction {}", record.getSUMUP_ClientTransactionId(), ex);
}
});
return BulkUpdateByQueryResult.builder()
.countOK(countOK.get())
.countError(countError.get())
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\repository\SumUpTransactionRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private Message messagePostProcess(final Message message)
{
if (msv3PeerAuthToken != null)
{
message.getMessageProperties().getHeaders().put(MSV3PeerAuthToken.NAME, msv3PeerAuthToken.toJson());
}
return message;
}
public void requestAllUpdates()
{
convertAndSend(RabbitMQConfig.QUEUENAME_MSV3ServerRequests, MSV3ServerRequest.requestAll());
logger.info("Requested all data from MSV3 server peer");
}
public void requestConfigUpdates()
{
convertAndSend(RabbitMQConfig.QUEUENAME_MSV3ServerRequests, MSV3ServerRequest.requestConfig());
logger.info("Requested config data from MSV3 server peer");
}
public void publishUserChangedEvent(@NonNull final MSV3UserChangedBatchEvent event)
{
convertAndSend(RabbitMQConfig.QUEUENAME_UserChangedEvents, event);
}
public void publishUserChangedEvent(@NonNull final MSV3UserChangedEvent event) | {
convertAndSend(RabbitMQConfig.QUEUENAME_UserChangedEvents, MSV3UserChangedBatchEvent.builder()
.event(event)
.build());
}
public void publishStockAvailabilityUpdatedEvent(@NonNull final MSV3StockAvailabilityUpdatedEvent event)
{
convertAndSend(RabbitMQConfig.QUEUENAME_StockAvailabilityUpdatedEvent, event);
}
public void publishProductExcludes(@NonNull final MSV3ProductExcludesUpdateEvent event)
{
convertAndSend(RabbitMQConfig.QUEUENAME_ProductExcludeUpdatedEvents, event);
}
public void publishSyncOrderRequest(final MSV3OrderSyncRequest request)
{
convertAndSend(RabbitMQConfig.QUEUENAME_SyncOrderRequestEvents, request);
}
public void publishSyncOrderResponse(@NonNull final MSV3OrderSyncResponse response)
{
convertAndSend(RabbitMQConfig.QUEUENAME_SyncOrderResponseEvents, response);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\service\MSV3ServerPeerService.java | 2 |
请完成以下Java代码 | public class X_C_Workplace_Carrier_Product extends org.compiere.model.PO implements I_C_Workplace_Carrier_Product, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 535687672L;
/** Standard Constructor */
public X_C_Workplace_Carrier_Product (final Properties ctx, final int C_Workplace_Carrier_Product_ID, @Nullable final String trxName)
{
super (ctx, C_Workplace_Carrier_Product_ID, trxName);
}
/** Load Constructor */
public X_C_Workplace_Carrier_Product (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCarrier_Product_ID (final int Carrier_Product_ID)
{
if (Carrier_Product_ID < 1)
set_Value (COLUMNNAME_Carrier_Product_ID, null);
else
set_Value (COLUMNNAME_Carrier_Product_ID, Carrier_Product_ID);
}
@Override
public int getCarrier_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Product_ID); | }
@Override
public void setC_Workplace_Carrier_Product_ID (final int C_Workplace_Carrier_Product_ID)
{
if (C_Workplace_Carrier_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Workplace_Carrier_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Workplace_Carrier_Product_ID, C_Workplace_Carrier_Product_ID);
}
@Override
public int getC_Workplace_Carrier_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_Carrier_Product_ID);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_Carrier_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PickingJobScheduleCollection list(@NonNull final PickingJobScheduleQuery query)
{
return pickingJobScheduleRepository.list(query);
}
public Stream<PickingJobSchedule> stream(@NonNull final PickingJobScheduleQuery query)
{
return pickingJobScheduleRepository.stream(query);
}
public void markAsProcessed(final Set<PickingJobScheduleId> ids)
{
pickingJobScheduleRepository.updateByIds(ids, jobSchedule -> jobSchedule.toBuilder().processed(true).build());
}
public Set<ShipmentScheduleId> getShipmentScheduleIdsWithAllJobSchedulesProcessedOrMissing(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds)
{
if (shipmentScheduleIds.isEmpty()) {return ImmutableSet.of();}
final Map<ShipmentScheduleId, PickingJobScheduleCollection> jobSchedulesByShipmentScheduleId = stream(PickingJobScheduleQuery.builder().onlyShipmentScheduleIds(shipmentScheduleIds).build())
.collect(Collectors.groupingBy(PickingJobSchedule::getShipmentScheduleId, PickingJobScheduleCollection.collect()));
final HashSet<ShipmentScheduleId> result = new HashSet<>();
for (final ShipmentScheduleId shipmentScheduleId : shipmentScheduleIds)
{
final PickingJobScheduleCollection jobSchedules = jobSchedulesByShipmentScheduleId.get(shipmentScheduleId);
if (jobSchedules == null || jobSchedules.isAllProcessed())
{
result.add(shipmentScheduleId);
}
}
return result;
}
public Quantity getQtyRemainingToScheduleForPicking(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = pickingJobShipmentScheduleService.getByIdAsRecord(shipmentScheduleId);
final Quantity qtyToDeliver = pickingJobShipmentScheduleService.getQtyToDeliver(shipmentSchedule); | final Quantity qtyScheduledForPicking = pickingJobShipmentScheduleService.getQtyScheduledForPicking(shipmentSchedule);
return qtyToDeliver.subtract(qtyScheduledForPicking);
}
public void autoAssign(@NonNull final PickingJobScheduleAutoAssignRequest request)
{
PickingJobScheduleAutoAssignCommand.builder()
.workplaceRepository(workplaceRepository)
.pickingJobScheduleRepository(pickingJobScheduleRepository)
.pickingJobShipmentScheduleService(pickingJobShipmentScheduleService)
.sysConfigBL(sysConfigBL)
.pickingJobProductService(pickingJobProductService)
.request(request)
.build()
.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job_schedule\service\PickingJobScheduleService.java | 2 |
请完成以下Java代码 | private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final I_EDI_Desadv desadv = desadvDAO.retrieveById(EDIDesadvId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(desadv.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus);
}
@Override
@Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final I_EDI_Desadv desadv = desadvDAO.retrieveById(EDIDesadvId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(desadv.getEDI_ExportStatus()); | return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
{
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
final boolean isProcessed = ChangeEDI_ExportStatusHelper.computeIsProcessedByTargetExportStatus(targetExportStatus);
ChangeEDI_ExportStatusHelper.EDI_DesadvDoIt(EDIDesadvId.ofRepoId(getRecord_ID()),
targetExportStatus,
isProcessed);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_EDI_Desadv_SingleView.java | 1 |
请完成以下Java代码 | public long executeCount(CommandContext commandContext) {
provideHistoryCleanupStrategy(commandContext);
checkQueryOk();
return commandContext
.getHistoricProcessInstanceManager()
.findCleanableHistoricProcessInstancesReportCountByCriteria(this);
}
@Override
public List<CleanableHistoricProcessInstanceReportResult> executeList(CommandContext commandContext, final Page page) {
provideHistoryCleanupStrategy(commandContext);
checkQueryOk();
return commandContext
.getHistoricProcessInstanceManager()
.findCleanableHistoricProcessInstancesReportByCriteria(this, page);
}
public Date getCurrentTimestamp() {
return currentTimestamp;
}
public void setCurrentTimestamp(Date currentTimestamp) {
this.currentTimestamp = currentTimestamp;
}
public String[] getProcessDefinitionIdIn() {
return processDefinitionIdIn;
}
public String[] getProcessDefinitionKeyIn() {
return processDefinitionKeyIn;
}
public String[] getTenantIdIn() {
return tenantIdIn;
}
public void setTenantIdIn(String[] tenantIdIn) {
this.tenantIdIn = tenantIdIn;
} | public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isCompact() {
return isCompact;
}
protected void provideHistoryCleanupStrategy(CommandContext commandContext) {
String historyCleanupStrategy = commandContext.getProcessEngineConfiguration()
.getHistoryCleanupStrategy();
isHistoryCleanupStrategyRemovalTimeBased = HISTORY_CLEANUP_STRATEGY_REMOVAL_TIME_BASED.equals(historyCleanupStrategy);
}
public boolean isHistoryCleanupStrategyRemovalTimeBased() {
return isHistoryCleanupStrategyRemovalTimeBased;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\CleanableHistoricProcessInstanceReportImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<TopicPartition, Long> computeLags(
Map<TopicPartition, Long> consumerGrpOffsets,
Map<TopicPartition, Long> producerOffsets) {
Map<TopicPartition, Long> lags = new HashMap<>();
for (Map.Entry<TopicPartition, Long> entry : consumerGrpOffsets.entrySet()) {
Long producerOffset = producerOffsets.get(entry.getKey());
Long consumerOffset = consumerGrpOffsets.get(entry.getKey());
long lag = Math.abs(Math.max(0, producerOffset) - Math.max(0, consumerOffset));
lags.putIfAbsent(entry.getKey(), lag);
}
return lags;
}
private AdminClient getAdminClient(String bootstrapServerConfig) {
Properties config = new Properties();
config.put(
AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
bootstrapServerConfig);
return AdminClient.create(config);
} | private KafkaConsumer<String, String> getKafkaConsumer(
String bootstrapServerConfig) {
Properties properties = new Properties();
properties.setProperty(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
bootstrapServerConfig);
properties.setProperty(
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName());
properties.setProperty(
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName());
return new KafkaConsumer<>(properties);
}
} | repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\monitoring\service\LagAnalyzerService.java | 2 |
请完成以下Java代码 | public void setA_Asset_Info_Lic_ID (int A_Asset_Info_Lic_ID)
{
if (A_Asset_Info_Lic_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Asset_Info_Lic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Asset_Info_Lic_ID, Integer.valueOf(A_Asset_Info_Lic_ID));
}
/** Get A_Asset_Info_Lic_ID.
@return A_Asset_Info_Lic_ID */
public int getA_Asset_Info_Lic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Asset_Info_Lic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Info_Lic_ID()));
}
/** Set Issuing Agency.
@param A_Issuing_Agency Issuing Agency */
public void setA_Issuing_Agency (String A_Issuing_Agency)
{
set_Value (COLUMNNAME_A_Issuing_Agency, A_Issuing_Agency);
}
/** Get Issuing Agency.
@return Issuing Agency */
public String getA_Issuing_Agency ()
{
return (String)get_Value(COLUMNNAME_A_Issuing_Agency);
}
/** Set License Fee.
@param A_License_Fee License Fee */
public void setA_License_Fee (BigDecimal A_License_Fee)
{
set_Value (COLUMNNAME_A_License_Fee, A_License_Fee);
}
/** Get License Fee.
@return License Fee */
public BigDecimal getA_License_Fee ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_License_Fee);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set License No.
@param A_License_No License No */
public void setA_License_No (String A_License_No)
{
set_Value (COLUMNNAME_A_License_No, A_License_No);
}
/** Get License No.
@return License No */
public String getA_License_No () | {
return (String)get_Value(COLUMNNAME_A_License_No);
}
/** Set Policy Renewal Date.
@param A_Renewal_Date Policy Renewal Date */
public void setA_Renewal_Date (Timestamp A_Renewal_Date)
{
set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date);
}
/** Get Policy Renewal Date.
@return Policy Renewal Date */
public Timestamp getA_Renewal_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date);
}
/** Set Account State.
@param A_State
State of the Credit Card or Account holder
*/
public void setA_State (String A_State)
{
set_Value (COLUMNNAME_A_State, A_State);
}
/** Get Account State.
@return State of the Credit Card or Account holder
*/
public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State);
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Lic.java | 1 |
请完成以下Java代码 | protected Boolean initialValue()
{
return super.initialValue();
}
};
public boolean booleanValue()
{
final Boolean value = threadLocal.get();
return value == null ? false : value.booleanValue();
}
/**
* Enables the flag and returns an {@link IAutoCloseable} which restores the flag status.
*
* @return auto closeable which restores the flag status
*/
public IAutoCloseable enable()
{
final Boolean valueOld = threadLocal.get();
threadLocal.set(true); | // Return an auto-closeable which will put it back
return new IAutoCloseable()
{
private volatile boolean closed = false;
@Override
public void close()
{
if (closed)
{
return;
}
// restore the old value
threadLocal.set(valueOld);
closed = true;
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\AutoClosableThreadLocalBoolean.java | 1 |
请完成以下Java代码 | public class DBConvertUtil {
protected final static Logger logger = LoggerFactory.getLogger(DBConvertUtil.class);
private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
/**
* binlog行数据列转换成DBObject
*
* @param columns
* @return
*/
public static Document columnToJson(List<CanalEntry.Column> columns) {
Document obj = new Document();
for (CanalEntry.Column column : columns) {
Object value = dataTypeConvert(column.getMysqlType(), column.getValue());
obj.put(column.getName(), value);
}
return obj;
}
/**
* 数据类型转换
*
* @param mysqlType
* @param value
* @return
*/
private static Object dataTypeConvert(String mysqlType, String value) {
try {
if (mysqlType.startsWith("int") || mysqlType.startsWith("tinyint") || mysqlType.startsWith("smallint") || mysqlType.startsWith("mediumint")) {
//int(32)
return StringUtils.isBlank(value) ? null : Integer.parseInt(value);
} else if (mysqlType.startsWith("bigint")) {
//int(64)
return StringUtils.isBlank(value) ? null : Long.parseLong(value);
} else if (mysqlType.startsWith("float") || mysqlType.startsWith("double")) {
return StringUtils.isBlank(value) ? null : Double.parseDouble(value);
} else if (mysqlType.startsWith("decimal")) {
//小数精度为0时转换成long类型,否则转换为double类型
int lenBegin = mysqlType.indexOf('(');
int lenCenter = mysqlType.indexOf(',');
int lenEnd = mysqlType.indexOf(')');
if (lenBegin > 0 && lenEnd > 0 && lenCenter > 0) {
int length = Integer.parseInt(mysqlType.substring(lenCenter + 1, lenEnd)); | if (length == 0) {
return StringUtils.isBlank(value) ? null : Long.parseLong(value);
}
}
return StringUtils.isBlank(value) ? null : Double.parseDouble(value);
} else if (mysqlType.startsWith("datetime") || mysqlType.startsWith("timestamp")) {
return StringUtils.isBlank(value) ? null : DATE_TIME_FORMAT.parse(value);
} else if (mysqlType.equals("date")) {
return StringUtils.isBlank(value) ? null : DATE_FORMAT.parse(value);
} else if (mysqlType.startsWith("varchar")) {
//设置默认空串
return value == null ? "" : value;
} else {
logger.error("unknown data type :[{}]-[{}]", mysqlType, value);
}
} catch (Exception e) {
logger.error("data type convert error ", e);
}
return value;
}
} | repos\spring-boot-leaning-master\2.x_data\3-3 使用 canal 将业务数据从 Mysql 同步到 MongoDB\spring-boot-canal-mongodb\src\main\java\com\neo\util\DBConvertUtil.java | 1 |
请完成以下Java代码 | public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(" "));
Instant now = Instant.now();
Instant validity;
if (rememberMe) {
validity = now.plus(this.tokenValidityInSecondsForRememberMe, ChronoUnit.SECONDS);
} else {
validity = now.plus(this.tokenValidityInSeconds, ChronoUnit.SECONDS);
}
// @formatter:off
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuedAt(now)
.expiresAt(validity)
.subject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.build();
JwsHeader jwsHeader = JwsHeader.with(JWT_ALGORITHM).build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims)).getTokenValue();
}
/**
* Object to return as body in JWT Authentication.
*/
static class JWTToken {
private String idToken; | JWTToken(String idToken) {
this.idToken = idToken;
}
@JsonProperty("id_token")
String getIdToken() {
return idToken;
}
void setIdToken(String idToken) {
this.idToken = idToken;
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-monolithic\src\main\java\com\baeldung\jhipster8\web\rest\AuthenticateController.java | 1 |
请完成以下Java代码 | public MDistributionListLine[] getLines()
{
ArrayList<MDistributionListLine> list = new ArrayList<MDistributionListLine>();
BigDecimal ratioTotal = Env.ZERO;
//
String sql = "SELECT * FROM M_DistributionListLine WHERE M_DistributionList_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getM_DistributionList_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
MDistributionListLine line = new MDistributionListLine(getCtx(), rs, get_TrxName());
list.add(line);
BigDecimal ratio = line.getRatio();
if (ratio != null)
ratioTotal = ratioTotal.add(ratio);
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error("getLines", e);
}
try
{
if (pstmt != null) | pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
// Update Ratio
if (ratioTotal.compareTo(getRatioTotal()) != 0)
{
log.info("getLines - Set RatioTotal from " + getRatioTotal() + " to " + ratioTotal);
setRatioTotal(ratioTotal);
save();
}
MDistributionListLine[] retValue = new MDistributionListLine[list.size ()];
list.toArray (retValue);
return retValue;
} // getLines
} // MDistributionList | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDistributionList.java | 1 |
请完成以下Java代码 | public class AvroSchemaBuilder {
//@formatter:off
static Schema clientIdentifierSchema() {
return SchemaBuilder.record("ClientIdentifier")
.namespace("com.baeldung.avro.model")
.fields()
.requiredString("hostName")
.requiredString("ipAddress")
.endRecord();
}
static Schema avroHttpRequestSchema() {
return SchemaBuilder.record("AvroHttpRequest")
.namespace("com.baeldung.avro.model").fields()
.requiredLong("requestTime")
.name("clientIdentifier")
.type(clientIdentifierSchema())
.noDefault()
.name("employeeNames")
.type() | .array()
.items()
.stringType()
.arrayDefault(emptyList())
.name("active")
.type()
.enumeration("Active")
.symbols("YES", "NO")
.noDefault()
.endRecord();
}
//@formatter:on
} | repos\tutorials-master\apache-libraries\src\main\java\com\baeldung\apache\avro\util\AvroSchemaBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AppDeploymentBuilder addBytes(String resourceName, byte[] bytes) {
if (bytes == null) {
throw new FlowableException("bytes array is null");
}
AppResourceEntity resource = resourceEntityManager.create();
resource.setName(resourceName);
resource.setBytes(bytes);
deployment.addResource(resource);
return this;
}
@Override
public AppDeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
try {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
String entryName = entry.getName();
byte[] bytes = IoUtil.readInputStream(zipInputStream, entryName);
AppResourceEntity resource = resourceEntityManager.create();
resource.setName(entryName);
resource.setBytes(bytes);
deployment.addResource(resource);
}
entry = zipInputStream.getNextEntry();
}
} catch (Exception e) {
throw new FlowableException("problem reading zip input stream", e);
}
return this;
}
@Override
public AppDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public AppDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public AppDeploymentBuilder key(String key) {
deployment.setKey(key);
return this;
}
@Override
public AppDeploymentBuilder disableSchemaValidation() {
this.isXsdValidationEnabled = false;
return this; | }
@Override
public AppDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public AppDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
@Override
public AppDeployment deploy() {
return repositoryService.deploy(this);
}
public AppDeploymentEntity getDeployment() {
return deployment;
}
public boolean isXsdValidationEnabled() {
return isXsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentBuilderImpl.java | 2 |
请完成以下Spring Boot application配置 | # 默认激活dev配置
spring:
profiles:
active: "dev"
---
spring:
config:
activate:
on-profile: "dev"
name: dev.didispace.com
---
spring:
config:
activate:
on-profile: "test"
name: test.didispa | ce.com
---
spring:
config:
activate:
on-profile: "prod"
name: prod.didispace.com | repos\SpringBoot-Learning-master\2.x\chapter1-2\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public class StartProgressTaskCmd extends NeedsActiveTaskCmd<Void> {
private static final long serialVersionUID = 1L;
protected String userId;
public StartProgressTaskCmd(String taskId, String userId) {
super(taskId);
this.userId = userId;
}
@Override
protected Void execute(CommandContext commandContext, TaskEntity task) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
Clock clock = cmmnEngineConfiguration.getClock();
Date updateTime = clock.getCurrentTime();
task.setInProgressStartTime(updateTime);
task.setInProgressStartedBy(userId);
task.setState(Task.IN_PROGRESS); | HistoricTaskService historicTaskService = cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskService();
historicTaskService.recordTaskInfoChange(task, updateTime, cmmnEngineConfiguration);
if (cmmnEngineConfiguration.getHumanTaskStateInterceptor() != null) {
cmmnEngineConfiguration.getHumanTaskStateInterceptor().handleInProgressStart(task, userId);
}
return null;
}
@Override
protected String getSuspendedTaskExceptionPrefix() {
return "Cannot start progress on";
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\StartProgressTaskCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getProfile() {
return this.reference.getProfile();
}
boolean isEmptyDirectory() {
return this.emptyDirectory;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
StandardConfigDataResource other = (StandardConfigDataResource) obj;
return (this.emptyDirectory == other.emptyDirectory) && isSameUnderlyingResource(this.resource, other.resource);
}
private boolean isSameUnderlyingResource(Resource ours, Resource other) {
return ours.equals(other) || isSameFile(getUnderlyingFile(ours), getUnderlyingFile(other));
}
private boolean isSameFile(@Nullable File ours, @Nullable File other) {
return (ours != null) && ours.equals(other);
}
@Override
public int hashCode() {
File underlyingFile = getUnderlyingFile(this.resource);
return (underlyingFile != null) ? underlyingFile.hashCode() : this.resource.hashCode();
}
@Override
public String toString() {
if (this.resource instanceof FileSystemResource || this.resource instanceof FileUrlResource) {
try {
return "file [" + this.resource.getFile() + "]"; | }
catch (IOException ex) {
// Ignore
}
}
return this.resource.toString();
}
private @Nullable File getUnderlyingFile(Resource resource) {
try {
if (resource instanceof ClassPathResource || resource instanceof FileSystemResource
|| resource instanceof FileUrlResource) {
return resource.getFile().getAbsoluteFile();
}
}
catch (IOException ex) {
// Ignore
}
return null;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataResource.java | 2 |
请完成以下Java代码 | public static String writeLineByLineExample() throws Exception {
Path path = Helpers.fileOutOnePath();
return CsvWriterExamples.writeLineByLine(Helpers.fourColumnCsvString(), path);
}
public static String writeAllLinesExample() throws Exception {
Path path = Helpers.fileOutAllPath();
return CsvWriterExamples.writeAllLines(Helpers.fourColumnCsvString(), path);
}
// Bean Examples
public static List<CsvBean> simplePositionBeanExample() throws Exception {
Path path = Helpers.twoColumnCsvPath();
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class);
}
public static List<CsvBean> namedColumnBeanExample() throws Exception {
Path path = Helpers.namedColumnCsvPath();
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class);
}
public static String writeCsvFromBeanExample() throws Exception { | Path path = Helpers.fileOutBeanPath();
return BeanExamples.writeCsvFromBean(path);
}
public static void main(String[] args) {
try {
simplePositionBeanExample();
namedColumnBeanExample();
writeCsvFromBeanExample();
readLineByLineExample();
readAllLinesExample();
writeLineByLineExample();
writeAllLinesExample();
} catch (Exception e) {
throw new RuntimeException("Error during csv processing", e);
}
}
} | repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\libraries\opencsv\Application.java | 1 |
请完成以下Java代码 | public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String name = Objects.requireNonNull(config.getName(), "name must not be null");
String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null");
ServerHttpRequest req = exchange.getRequest();
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(req.getURI());
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>(req.getQueryParams());
if (queryParams.containsKey(name)) {
queryParams.remove(name);
queryParams.add(name, replacement);
}
try {
MultiValueMap<String, String> encodedQueryParams = ServerWebExchangeUtils
.encodeQueryParams(queryParams);
URI uri = uriComponentsBuilder.replaceQueryParams(unmodifiableMultiValueMap(encodedQueryParams))
.build(true)
.toUri();
ServerHttpRequest request = req.mutate().uri(uri).build();
return chain.filter(exchange.mutate().request(request).build());
}
catch (IllegalArgumentException ex) {
throw new IllegalStateException("Invalid URI query: \"" + queryParams + "\"");
}
}
@Override | public String toString() {
String name = Objects.requireNonNull(config.getName(), "name must not be null");
String replacement = Objects.requireNonNull(config.getReplacement(), "replacement must not be null");
return filterToStringCreator(RewriteRequestParameterGatewayFilterFactory.this).append(name, replacement)
.toString();
}
};
}
public static class Config extends AbstractGatewayFilterFactory.NameConfig {
private @Nullable String replacement;
public @Nullable String getReplacement() {
return replacement;
}
public Config setReplacement(String replacement) {
this.replacement = replacement;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewriteRequestParameterGatewayFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.embeddedValueResolver = resolver;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisWebSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;
}
this.maxInactiveInterval = Duration.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds"));
String redisNamespaceValue = attributes.getString("redisNamespace");
if (StringUtils.hasText(redisNamespaceValue)) {
this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue);
}
this.saveMode = attributes.getEnum("saveMode");
}
private ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() {
RedisSerializer<String> keySerializer = RedisSerializer.string();
RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer | : new JdkSerializationRedisSerializer(this.classLoader);
RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext(defaultSerializer)
.key(keySerializer)
.hashKey(keySerializer)
.build();
return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext);
}
@Autowired(required = false)
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\RedisWebSessionConfiguration.java | 2 |
请完成以下Java代码 | public void save()
{
final FactTrxStrategy factTrxLinesStrategy = getFactTrxLinesStrategyEffective();
if (factTrxLinesStrategy != null)
{
factTrxLinesStrategy
.createFactTrxLines(m_lines)
.forEach(this::saveNew);
}
else
{
m_lines.forEach(this::saveNew);
}
}
private void saveNew(FactLine line) {services.saveNew(line);}
private void saveNew(final FactTrxLines factTrxLines)
{
//
// Case: 1 debit line, one or more credit lines
if (factTrxLines.getType() == FactTrxLinesType.Debit)
{
final FactLine drLine = factTrxLines.getDebitLine();
saveNew(drLine);
factTrxLines.forEachCreditLine(crLine -> {
crLine.setCounterpart_Fact_Acct_ID(drLine.getIdNotNull());
saveNew(crLine);
});
}
//
// Case: 1 credit line, one or more debit lines
else if (factTrxLines.getType() == FactTrxLinesType.Credit)
{
final FactLine crLine = factTrxLines.getCreditLine();
saveNew(crLine);
factTrxLines.forEachDebitLine(drLine -> {
drLine.setCounterpart_Fact_Acct_ID(crLine.getIdOrNull());
saveNew(drLine);
});
}
// | // Case: no debit lines, no credit lines
else if (factTrxLines.getType() == FactTrxLinesType.EmptyOrZero)
{
// nothing to do
}
else
{
throw new AdempiereException("Unknown type: " + factTrxLines.getType());
}
//
// also save the zero lines, if they are here
factTrxLines.forEachZeroLine(this::saveNew);
}
public void forEach(final Consumer<FactLine> consumer)
{
m_lines.forEach(consumer);
}
} // Fact | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Fact.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public InsuranceContractQuantity getQuantity() {
return quantity;
}
public void setQuantity(InsuranceContractQuantity quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InsuranceContractMaximumAmountForProductGroups insuranceContractMaximumAmountForProductGroups = (InsuranceContractMaximumAmountForProductGroups) o;
return Objects.equals(this.productGroupId, insuranceContractMaximumAmountForProductGroups.productGroupId) &&
Objects.equals(this.quantity, insuranceContractMaximumAmountForProductGroups.quantity);
}
@Override
public int hashCode() {
return Objects.hash(productGroupId, quantity);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append("class InsuranceContractMaximumAmountForProductGroups {\n");
sb.append(" productGroupId: ").append(toIndentedString(productGroupId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractMaximumAmountForProductGroups.java | 2 |
请完成以下Java代码 | public Integer getDefaultStatus() {
return defaultStatus;
}
public void setDefaultStatus(Integer defaultStatus) {
this.defaultStatus = defaultStatus;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
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(", memberId=").append(memberId);
sb.append(", name=").append(name);
sb.append(", phoneNumber=").append(phoneNumber);
sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", postCode=").append(postCode);
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\UmsMemberReceiveAddress.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonDistributionJobLine
{
@NonNull DistributionJobLineId lineId;
@NonNull String caption;
@NonNull String productId;
@NonNull String productName;
@NonNull String uom;
@NonNull BigDecimal qtyToMove;
//
// Pick From
@NonNull JsonLocatorInfo pickFromLocator;
//
// Drop To
@NonNull JsonLocatorInfo dropToLocator;
@NonNull List<JsonDistributionJobStep> steps;
boolean allowPickingAnyHU;
static JsonDistributionJobLine of(
@NonNull final DistributionJobLine line,
@NonNull final DistributionJob job,
@NonNull final JsonOpts jsonOpts)
{
final String adLanguage = jsonOpts.getAdLanguage();
final String productName = line.getProduct().getCaption().translate(adLanguage);
return builder()
.lineId(line.getId()) | .caption(productName)
.productId(line.getProduct().getProductId().getAsString())
.productName(productName)
.uom(line.getQtyToMove().getUOMSymbol())
.qtyToMove(line.getQtyToMove().toBigDecimal())
.pickFromLocator(JsonLocatorInfo.of(line.getPickFromLocator()))
.dropToLocator(JsonLocatorInfo.of(line.getDropToLocator()))
.steps(line.getSteps()
.stream()
.map(step -> JsonDistributionJobStep.of(step, line, jsonOpts))
.collect(ImmutableList.toImmutableList()))
.allowPickingAnyHU(job.isAllowPickingAnyHU())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\rest_api\json\JsonDistributionJobLine.java | 2 |
请完成以下Java代码 | public static DmnResourceEntityManager getResourceEntityManager() {
return getResourceEntityManager(getCommandContext());
}
public static DmnResourceEntityManager getResourceEntityManager(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getResourceEntityManager();
}
public static DmnDeploymentEntityManager getDeploymentEntityManager() {
return getDeploymentEntityManager(getCommandContext());
}
public static DmnDeploymentEntityManager getDeploymentEntityManager(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getDeploymentEntityManager();
}
public static DecisionEntityManager getDecisionEntityManager() {
return getDecisionEntityManager(getCommandContext());
}
public static DecisionEntityManager getDecisionEntityManager(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getDecisionEntityManager();
}
public static HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager() {
return getHistoricDecisionExecutionEntityManager(getCommandContext());
}
public static HistoricDecisionExecutionEntityManager getHistoricDecisionExecutionEntityManager(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getHistoricDecisionExecutionEntityManager(); | }
public static DmnRepositoryService getDmnRepositoryService() {
return getDmnRepositoryService(getCommandContext());
}
public static DmnRepositoryService getDmnRepositoryService(CommandContext commandContext) {
return getDmnEngineConfiguration(commandContext).getDmnRepositoryService();
}
public static DmnEngineAgenda getAgenda() {
return getAgenda(getCommandContext());
}
public static DmnEngineAgenda getAgenda(CommandContext commandContext) {
return commandContext.getSession(DmnEngineAgenda.class);
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\util\CommandContextUtil.java | 1 |
请完成以下Java代码 | public boolean isOK()
{
return error == null;
}
public boolean isError()
{
return error != null;
}
public ResultType getResult()
{
if (result == null)
{
throw toException();
}
return result;
}
public ErrorType getError()
{
if (error == null)
{
throw new AdempiereException("Not an error response: " + this);
}
return error;
} | public AdempiereException toException()
{
if (error == null)
{
throw new AdempiereException("Not an error response: " + this);
}
if (errorCause != null)
{
return AdempiereException.wrapIfNeeded(errorCause)
.setParameter("error", error);
}
else
{
return new AdempiereException(error.toString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\PayPalClientResponse.java | 1 |
请完成以下Java代码 | public void run()
{
if (!X_AD_Scheduler.SCHEDULETYPE_CronSchedulingPattern.equals(m_model.getScheduleType()))
{
super.run();
return;
}
final String cronPattern = m_model.getCronPattern();
if (Check.isNotBlank(cronPattern) && SchedulingPattern.validate(cronPattern))
{
cronScheduler = new it.sauronsoftware.cron4j.Scheduler();
cronScheduler.schedule(cronPattern, () -> {
runNow();
final long next = predictor.nextMatchingTime();
setDateNextRun(new Timestamp(next));
});
predictor = new Predictor(cronPattern);
final long next = predictor.nextMatchingTime();
setDateNextRun(new Timestamp(next)); | cronScheduler.start();
while (true)
{
if (!sleep())
{
cronScheduler.stop();
break;
}
else if (!cronScheduler.isStarted())
{
break;
}
}
}
else
{
super.run();
}
}
} // Scheduler | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\Scheduler.java | 1 |
请完成以下Java代码 | public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/**
* Status AD_Reference_ID=541011
* Reference name: C_Payment_Reservation_Status
*/
public static final int STATUS_AD_Reference_ID=541011; | /** WAITING_PAYER_APPROVAL = W */
public static final String STATUS_WAITING_PAYER_APPROVAL = "W";
/** APPROVED = A */
public static final String STATUS_APPROVED = "A";
/** VOIDED = V */
public static final String STATUS_VOIDED = "V";
/** COMPLETED = C */
public static final String STATUS_COMPLETED = "C";
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EvaluatorOptimizerWorkflow {
private final CodeReviewClient codeReviewClient;
static final ParameterizedTypeReference<Map<String, String>> mapClass = new ParameterizedTypeReference<>() {};
public EvaluatorOptimizerWorkflow(CodeReviewClient codeReviewClient) {
this.codeReviewClient = codeReviewClient;
}
public Map<String, String> evaluate(String task) {
return loop(task, new HashMap<>(), "");
}
private Map<String, String> loop(String task, Map<String, String> latestSuggestions, String evaluation) {
latestSuggestions = generate(task, latestSuggestions, evaluation);
Map<String, String> evaluationResponse = evaluate(latestSuggestions, task);
String outcome = evaluationResponse.keySet().iterator().next();
evaluation = evaluationResponse.values().iterator().next();
if ("PASS".equals(outcome)) {
System.out.println("Accepted RE Review Suggestions:\n" + latestSuggestions);
return latestSuggestions;
}
return loop(task, latestSuggestions, evaluation);
}
private Map<String, String> generate(String task, Map<String, String> previousSuggestions, String evaluation) {
String request = CODE_REVIEW_PROMPT +
"\n PR: " + task +
"\n previous suggestions: " + previousSuggestions +
"\n evaluation on previous suggestions: " + evaluation;
System.out.println("PR REVIEW PROMPT: " + request);
ChatClient.ChatClientRequestSpec requestSpec = codeReviewClient.prompt(request);
ChatClient.CallResponseSpec responseSpec = requestSpec.call(); | Map<String, String> response = responseSpec.entity(mapClass);
System.out.println("PR REVIEW OUTCOME: " + response);
return response;
}
private Map<String, String> evaluate(Map<String, String> latestSuggestions, String task) {
String request = EVALUATE_PROPOSED_IMPROVEMENTS_PROMPT +
"\n PR: " + task +
"\n proposed suggestions: " + latestSuggestions;
System.out.println("EVALUATION PROMPT: " + request);
ChatClient.ChatClientRequestSpec requestSpec = codeReviewClient.prompt(request);
ChatClient.CallResponseSpec responseSpec = requestSpec.call();
Map<String, String> response = responseSpec.entity(mapClass);
System.out.println("EVALUATION OUTCOME: " + response);
return response;
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-agentic-patterns\src\main\java\com\baeldung\springai\agenticpatterns\workflows\evaluator\EvaluatorOptimizerWorkflow.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<HistoricVariableInstanceEntity> findHistoricalVariableInstancesByTaskId(String taskId) {
return dataManager.findHistoricVariableInstancesByTaskId(taskId);
}
@Override
public List<HistoricVariableInstanceEntity> findHistoricalVariableInstancesByScopeIdAndScopeType(String scopeId, String scopeType) {
return dataManager.findHistoricalVariableInstancesByScopeIdAndScopeType(scopeId, scopeType);
}
@Override
public List<HistoricVariableInstanceEntity> findHistoricalVariableInstancesByScopeIdAndScopeType(String scopeId, String scopeType,
Collection<String> variableNames) {
return dataManager.findHistoricalVariableInstancesByScopeIdAndScopeType(scopeId, scopeType, variableNames);
}
@Override
public List<HistoricVariableInstanceEntity> findHistoricalVariableInstancesBySubScopeIdAndScopeType(String subScopeId, String scopeType) {
return dataManager.findHistoricalVariableInstancesBySubScopeIdAndScopeType(subScopeId, scopeType);
}
@Override
public void deleteHistoricVariableInstancesByTaskId(String taskId) {
List<HistoricVariableInstanceEntity> historicProcessVariables = dataManager.findHistoricVariableInstancesByTaskId(taskId);
for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
delete(historicProcessVariable);
}
}
@Override
public void bulkDeleteHistoricVariableInstancesByProcessInstanceIds(Collection<String> processInstanceIds) {
dataManager.bulkDeleteHistoricVariableInstancesByProcessInstanceIds(processInstanceIds);
}
@Override
public void bulkDeleteHistoricVariableInstancesByTaskIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricVariableInstancesByTaskIds(taskIds);
}
@Override
public void bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
dataManager.bulkDeleteHistoricVariableInstancesByScopeIdsAndScopeType(scopeIds, scopeType); | }
@Override
public void deleteHistoricVariableInstancesForNonExistingProcessInstances() {
dataManager.deleteHistoricVariableInstancesForNonExistingProcessInstances();
}
@Override
public void deleteHistoricVariableInstancesForNonExistingCaseInstances() {
dataManager.deleteHistoricVariableInstancesForNonExistingCaseInstances();
}
@Override
public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricVariableInstancesByNativeQuery(parameterMap);
}
@Override
public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap);
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\HistoricVariableInstanceEntityManagerImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Mono<User> updateUser(String id, User user) {
return this.userDao.findById(id)
.flatMap(u -> {
u.setName(user.getName());
u.setAge(user.getAge());
u.setDescription(user.getDescription());
return this.userDao.save(u);
});
}
public Flux<User> getUserByAge(Integer from, Integer to) {
return this.userDao.findByAgeBetween(from, to);
}
public Flux<User> getUserByName(String name) {
return this.userDao.findByNameEquals(name);
}
public Flux<User> getUserByDescription(String description) {
return this.userDao.findByDescriptionIsLike(description);
}
/**
* 分页查询,只返回分页后的数据,count值需要通过 getUserByConditionCount
* 方法获取
*/
public Flux<User> getUserByCondition(int size, int page, User user) {
Query query = getQuery(user);
Sort sort = new Sort(Sort.Direction.DESC, "age");
Pageable pageable = PageRequest.of(page, size, sort);
return template.find(query.with(pageable), User.class);
}
/**
* 返回 count,配合 getUserByCondition使用
*/ | public Mono<Long> getUserByConditionCount(User user) {
Query query = getQuery(user);
return template.count(query, User.class);
}
private Query getQuery(User user) {
Query query = new Query();
Criteria criteria = new Criteria();
if (!StringUtils.isEmpty(user.getName())) {
criteria.and("name").is(user.getName());
}
if (!StringUtils.isEmpty(user.getDescription())) {
criteria.and("description").regex(user.getDescription());
}
query.addCriteria(criteria);
return query;
}
} | repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\service\UserService.java | 2 |
请完成以下Java代码 | public ResponseEntity<JsonResponseContactList> retrieveContactsSince(
@ApiParam(value = SINCE_DOC, allowEmptyValue = true) //
@RequestParam(name = "since", required = false) //
@Nullable final Long epochTimestampMillis,
@ApiParam(value = NEXT_DOC, allowEmptyValue = true) //
@RequestParam(name = "next", required = false) //
@Nullable final String next)
{
final Optional<JsonResponseContactList> list = bpartnerEndpointService.retrieveContactsSince(epochTimestampMillis, next);
return toResponseEntity(list);
}
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Successfully created or updated contact"),
@ApiResponse(code = 401, message = "You are not authorized to create or update the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden")
})
@ApiOperation("Create of update a contact for a particular bpartner. If the contact exists, then the properties that are *not* specified are left untouched.")
@PutMapping
public ResponseEntity<JsonResponseUpsert> createOrUpdateContact(
@RequestBody @NonNull final JsonRequestContactUpsert contacts)
{
final JsonResponseUpsertBuilder response = JsonResponseUpsert.builder();
final SyncAdvise syncAdvise = SyncAdvise.builder().ifExists(IfExists.UPDATE_MERGE).ifNotExists(IfNotExists.CREATE).build();
final JsonPersisterService persister = jsonServiceFactory.createPersister();
jsonRequestConsolidateService.consolidateWithIdentifier(contacts); | for (final JsonRequestContactUpsertItem requestItem : contacts.getRequestItems())
{
final JsonResponseUpsertItem responseItem = persister.persist(
IdentifierString.of(requestItem.getContactIdentifier()),
requestItem.getContact(),
syncAdvise);
response.responseItem(responseItem);
}
return new ResponseEntity<>(response.build(), HttpStatus.CREATED);
}
private static <T> ResponseEntity<T> toResponseEntity(@NonNull final Optional<T> optionalResult)
{
return optionalResult
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\ContactRestController.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Table getDLM_Referencing_Table() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class);
}
@Override
public void setDLM_Referencing_Table(final org.compiere.model.I_AD_Table DLM_Referencing_Table)
{
set_ValueFromPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class, DLM_Referencing_Table);
}
/**
* Set Referenzierende Tabelle.
*
* @param DLM_Referencing_Table_ID Referenzierende Tabelle
*/
@Override
public void setDLM_Referencing_Table_ID(final int DLM_Referencing_Table_ID)
{
if (DLM_Referencing_Table_ID < 1)
{
set_Value(COLUMNNAME_DLM_Referencing_Table_ID, null);
}
else
{
set_Value(COLUMNNAME_DLM_Referencing_Table_ID, Integer.valueOf(DLM_Referencing_Table_ID));
}
}
/**
* Get Referenzierende Tabelle.
*
* @return Referenzierende Tabelle
*/
@Override
public int getDLM_Referencing_Table_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Table_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/** | * Set DLM aktiviert.
*
* @param IsDLM
* Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public void setIsDLM(final boolean IsDLM)
{
throw new IllegalArgumentException("IsDLM is virtual column");
}
/**
* Get DLM aktiviert.
*
* @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public boolean isDLM()
{
final Object oo = get_Value(COLUMNNAME_IsDLM);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Line.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Instant getDateTrx() {return _dateTrx;}
@NonNull
private Instant getDateAcct()
{
final Instant invoiceDateAcct = getInvoice().getDateAcct().toInstant();
final Instant inoutDateAcct = getInOut().getDateAcct().toInstant();
return invoiceDateAcct.isAfter(inoutDateAcct) ? invoiceDateAcct : inoutDateAcct;
}
/**
* Enables matching creation to be skipped if there exists at least one matching between invoice line and inout line.
*/
public MatchInvBuilder skipIfMatchingsAlreadyExist()
{
assertNotBuilt();
this._skipIfMatchingsAlreadyExist = true;
return this;
}
private boolean isSkipBecauseMatchingsAlreadyExist()
{
return _skipIfMatchingsAlreadyExist && matchInvoiceService.hasMatchInvs(getInvoiceLineId(), getInOutLineId(), getInoutCostId());
}
/**
* @return true if underlying invoice line is part of a credit memo invoice
*/
private boolean isCreditMemoInvoice()
{
if (_creditMemoInvoice == null)
{
_creditMemoInvoice = invoiceBL.isCreditMemo(getInvoice());
}
return _creditMemoInvoice;
}
/**
* @return true if underlying inout line is part of a material returns (customer or vendor).
*/
private boolean isMaterialReturns()
{
if (_materialReturns == null)
{
final I_M_InOut inout = getInOut();
_materialReturns = MovementType.isMaterialReturn(inout.getMovementType());
}
return _materialReturns; | }
private ProductId getProductId()
{
final I_M_InOutLine inoutLine = getInOutLine();
final ProductId inoutLineProductId = ProductId.ofRepoId(inoutLine.getM_Product_ID());
//
// Make sure M_Product_ID matches
if (getType().isMaterial())
{
final I_C_InvoiceLine invoiceLine = getInvoiceLine();
final ProductId invoiceLineProductId = ProductId.ofRepoId(invoiceLine.getM_Product_ID());
if (!ProductId.equals(invoiceLineProductId, inoutLineProductId))
{
final String invoiceProductName = productBL.getProductValueAndName(invoiceLineProductId);
final String inoutProductName = productBL.getProductValueAndName(inoutLineProductId);
throw new AdempiereException("@Invalid@ @M_Product_ID@"
+ "\n @C_InvoiceLine_ID@: " + invoiceLine + ", @M_Product_ID@=" + invoiceProductName
+ "\n @M_InOutLine_ID@: " + inoutLine + ", @M_Product_ID@=" + inoutProductName);
}
}
return inoutLineProductId;
}
private boolean isSOTrx()
{
final I_C_Invoice invoice = getInvoice();
final I_M_InOut inout = getInOut();
final boolean invoiceIsSOTrx = invoice.isSOTrx();
final boolean inoutIsSOTrx = inout.isSOTrx();
//
// Make sure IsSOTrx matches
if (invoiceIsSOTrx != inoutIsSOTrx)
{
throw new AdempiereException("@Invalid @IsSOTrx@"
+ "\n @C_Invoice_ID@: " + invoice + ", @IsSOTrx@=" + invoiceIsSOTrx
+ "\n @M_InOut_ID@: " + inout + ", @IsSOTrx@=" + inoutIsSOTrx);
}
return inoutIsSOTrx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\service\MatchInvBuilder.java | 2 |
请完成以下Java代码 | public class Bird extends Animal {
private boolean walks;
public Bird() {
super("bird");
}
public Bird(String name, boolean walks) {
super(name);
setWalks(walks);
}
public Bird(String name) {
super(name);
}
@Override
public String eats() { | return "grains";
}
@Override
protected String getSound() {
return "chaps";
}
public boolean walks() {
return walks;
}
public void setWalks(boolean walks) {
this.walks = walks;
}
} | repos\tutorials-master\core-java-modules\core-java-11-2\src\main\java\com\baeldung\reflection\Bird.java | 1 |
请完成以下Java代码 | public java.lang.String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
@Override
public void setIsAutoSendCustomers (final boolean IsAutoSendCustomers)
{
set_Value (COLUMNNAME_IsAutoSendCustomers, IsAutoSendCustomers);
}
@Override
public boolean isAutoSendCustomers()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoSendCustomers);
}
@Override
public void setIsAutoSendVendors (final boolean IsAutoSendVendors)
{
set_Value (COLUMNNAME_IsAutoSendVendors, IsAutoSendVendors);
}
@Override
public boolean isAutoSendVendors()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoSendVendors);
}
@Override
public void setIsCreateBPartnerFolders (final boolean IsCreateBPartnerFolders)
{
set_Value (COLUMNNAME_IsCreateBPartnerFolders, IsCreateBPartnerFolders);
}
@Override
public boolean isCreateBPartnerFolders()
{
return get_ValueAsBoolean(COLUMNNAME_IsCreateBPartnerFolders);
}
@Override
public void setIsSyncBPartnersToRestEndpoint (final boolean IsSyncBPartnersToRestEndpoint)
{
set_Value (COLUMNNAME_IsSyncBPartnersToRestEndpoint, IsSyncBPartnersToRestEndpoint);
}
@Override
public boolean isSyncBPartnersToRestEndpoint()
{
return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRestEndpoint);
}
@Override
public void setIsSyncHUsOnMaterialReceipt (final boolean IsSyncHUsOnMaterialReceipt)
{
set_Value (COLUMNNAME_IsSyncHUsOnMaterialReceipt, IsSyncHUsOnMaterialReceipt);
}
@Override
public boolean isSyncHUsOnMaterialReceipt() | {
return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnMaterialReceipt);
}
@Override
public void setIsSyncHUsOnProductionReceipt (final boolean IsSyncHUsOnProductionReceipt)
{
set_Value (COLUMNNAME_IsSyncHUsOnProductionReceipt, IsSyncHUsOnProductionReceipt);
}
@Override
public boolean isSyncHUsOnProductionReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsSyncHUsOnProductionReceipt);
}
/**
* TenantId AD_Reference_ID=276
* Reference name: AD_Org (all)
*/
public static final int TENANTID_AD_Reference_ID=276;
@Override
public void setTenantId (final java.lang.String TenantId)
{
set_Value (COLUMNNAME_TenantId, TenantId);
}
@Override
public java.lang.String getTenantId()
{
return get_ValueAsString(COLUMNNAME_TenantId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_GRSSignum.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public Integer getChargeType() {
return chargeType;
}
public void setChargeType(Integer chargeType) {
this.chargeType = chargeType;
}
public BigDecimal getFirstWeight() {
return firstWeight;
}
public void setFirstWeight(BigDecimal firstWeight) {
this.firstWeight = firstWeight;
}
public BigDecimal getFirstFee() {
return firstFee;
}
public void setFirstFee(BigDecimal firstFee) {
this.firstFee = firstFee;
}
public BigDecimal getContinueWeight() {
return continueWeight;
}
public void setContinueWeight(BigDecimal continueWeight) {
this.continueWeight = continueWeight;
}
public BigDecimal getContinmeFee() {
return continmeFee;
}
public void setContinmeFee(BigDecimal continmeFee) {
this.continmeFee = continmeFee;
} | public String getDest() {
return dest;
}
public void setDest(String dest) {
this.dest = dest;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", chargeType=").append(chargeType);
sb.append(", firstWeight=").append(firstWeight);
sb.append(", firstFee=").append(firstFee);
sb.append(", continueWeight=").append(continueWeight);
sb.append(", continmeFee=").append(continmeFee);
sb.append(", dest=").append(dest);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsFeightTemplate.java | 1 |
请完成以下Spring Boot application配置 | # Spring Boot main application.properties for Multi-Site (WAN) Caching Example
spring.profiles.group.server-site1=locator-manager,gateway-receiver,gateway-sender
spring.p | rofiles.group.server-site2=locator-manager,gateway-receiver,gateway-sender | repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public final class WebServerNamespace {
private static final String WEB_SERVER_CONTEXT_CLASS = "org.springframework.boot.web.server.context.WebServerApplicationContext";
/**
* {@link WebServerNamespace} that represents the main server.
*/
public static final WebServerNamespace SERVER = new WebServerNamespace("server");
/**
* {@link WebServerNamespace} that represents the management server.
*/
public static final WebServerNamespace MANAGEMENT = new WebServerNamespace("management");
private final String value;
private WebServerNamespace(String value) {
this.value = value;
}
/**
* Return the value of the namespace.
* @return the value
*/
public String getValue() {
return this.value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
WebServerNamespace other = (WebServerNamespace) obj;
return this.value.equals(other.value);
}
@Override | public int hashCode() {
return this.value.hashCode();
}
@Override
public String toString() {
return this.value;
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* context is {@code null} or not a web server context then {@link #SERVER} is
* returned.
* @param context the application context
* @return the web server namespace
* @since 4.0.1
*/
public static WebServerNamespace from(@Nullable ApplicationContext context) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return SERVER;
}
return from(WebServerApplicationContext.getServerNamespace(context));
}
/**
* Factory method to create a new {@link WebServerNamespace} from a value. If the
* value is empty or {@code null} then {@link #SERVER} is returned.
* @param value the namespace value or {@code null}
* @return the web server namespace
*/
public static WebServerNamespace from(@Nullable String value) {
if (StringUtils.hasText(value)) {
return new WebServerNamespace(value);
}
return SERVER;
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\WebServerNamespace.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPropertyName() {
return this.propertyName;
}
/**
* Return the origin or the property or {@code null}.
* @return the property origin
*/
public @Nullable Origin getOrigin() {
return this.origin;
}
/**
* Throw an {@link InactiveConfigDataAccessException} if the given
* {@link ConfigDataEnvironmentContributor} contains the property.
* @param contributor the contributor to check | * @param name the name to check
*/
static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor, ConfigurationPropertyName name) {
ConfigurationPropertySource source = contributor.getConfigurationPropertySource();
ConfigurationProperty property = (source != null) ? source.getConfigurationProperty(name) : null;
if (property != null) {
PropertySource<?> propertySource = contributor.getPropertySource();
ConfigDataResource location = contributor.getResource();
Assert.state(propertySource != null, "'propertySource' must not be null");
throw new InactiveConfigDataAccessException(propertySource, location, name.toString(),
property.getOrigin());
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InactiveConfigDataAccessException.java | 2 |
请完成以下Java代码 | public final String getText()
{
if (editor == null)
{
return null;
}
final Object value = editor.getValue();
if (value == null)
{
return null;
}
return value.toString();
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
final Object field;
if (returnValueTo)
{
field = getParameterToComponent(index);
}
else
{
field = getParameterComponent(index);
}
if (field instanceof CEditor)
{ | final CEditor editor = (CEditor)field;
return editor.getValue();
}
else
{
throw new AdempiereException("Component type not supported - " + field);
}
}
/**
* Method called when one of the parameter fields changed
*/
protected void onFieldChanged()
{
// parent.executeQuery(); we don't want to query each time, because we might block the search
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\AbstractInfoQueryCriteriaGeneral.java | 1 |
请完成以下Java代码 | public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
return null;
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? Object.class : null;
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (resolve(context, base, property)) {
if (!isProperty((String) property)) {
throw new PropertyNotFoundException("Cannot find property " + property);
}
return getProperty((String) property);
}
return null;
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return resolve(context, base, property) ? readOnly : false;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value)
throws PropertyNotWritableException {
if (resolve(context, base, property)) {
if (readOnly) {
throw new PropertyNotWritableException("Resolver is read only!");
}
setProperty((String) property, value);
}
}
@Override
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
if (resolve(context, base, method)) {
throw new NullPointerException("Cannot invoke method " + method + " on null");
}
return null;
}
/**
* Get property value
*
* @param property
* property name
* @return value associated with the given property
*/
public Object getProperty(String property) {
return map.get(property);
} | /**
* Set property value
*
* @param property
* property name
* @param value
* property value
*/
public void setProperty(String property, Object value) {
map.put(property, value);
}
/**
* Test property
*
* @param property
* property name
* @return <code>true</code> if the given property is associated with a value
*/
public boolean isProperty(String property) {
return map.containsKey(property);
}
/**
* Get properties
*
* @return all property names (in no particular order)
*/
public Iterable<String> properties() {
return map.keySet();
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setHeartbeatInterval(@Nullable Duration heartbeatInterval) {
this.heartbeatInterval = heartbeatInterval;
}
}
public static class Controlconnection {
/**
* Timeout to use for control queries.
*/
private @Nullable Duration timeout;
public @Nullable Duration getTimeout() {
return this.timeout;
}
public void setTimeout(@Nullable Duration timeout) {
this.timeout = timeout;
}
}
public static class Throttler {
/**
* Request throttling type.
*/
private @Nullable ThrottlerType type;
/**
* Maximum number of requests that can be enqueued when the throttling threshold
* is exceeded.
*/
private @Nullable Integer maxQueueSize;
/**
* Maximum number of requests that are allowed to execute in parallel.
*/
private @Nullable Integer maxConcurrentRequests;
/**
* Maximum allowed request rate.
*/
private @Nullable Integer maxRequestsPerSecond;
/**
* How often the throttler attempts to dequeue requests. Set this high enough that
* each attempt will process multiple entries in the queue, but not delay requests
* too much.
*/
private @Nullable Duration drainInterval;
public @Nullable ThrottlerType getType() {
return this.type;
}
public void setType(@Nullable ThrottlerType type) {
this.type = type;
}
public @Nullable Integer getMaxQueueSize() {
return this.maxQueueSize;
}
public void setMaxQueueSize(@Nullable Integer maxQueueSize) {
this.maxQueueSize = maxQueueSize;
}
public @Nullable Integer getMaxConcurrentRequests() {
return this.maxConcurrentRequests;
}
public void setMaxConcurrentRequests(@Nullable Integer maxConcurrentRequests) {
this.maxConcurrentRequests = maxConcurrentRequests;
} | public @Nullable Integer getMaxRequestsPerSecond() {
return this.maxRequestsPerSecond;
}
public void setMaxRequestsPerSecond(@Nullable Integer maxRequestsPerSecond) {
this.maxRequestsPerSecond = maxRequestsPerSecond;
}
public @Nullable Duration getDrainInterval() {
return this.drainInterval;
}
public void setDrainInterval(@Nullable Duration drainInterval) {
this.drainInterval = drainInterval;
}
}
/**
* Name of the algorithm used to compress protocol frames.
*/
public enum Compression {
/**
* Requires 'net.jpountz.lz4:lz4'.
*/
LZ4,
/**
* Requires org.xerial.snappy:snappy-java.
*/
SNAPPY,
/**
* No compression.
*/
NONE
}
public enum ThrottlerType {
/**
* Limit the number of requests that can be executed in parallel.
*/
CONCURRENCY_LIMITING("ConcurrencyLimitingRequestThrottler"),
/**
* Limits the request rate per second.
*/
RATE_LIMITING("RateLimitingRequestThrottler"),
/**
* No request throttling.
*/
NONE("PassThroughRequestThrottler");
private final String type;
ThrottlerType(String type) {
this.type = type;
}
public String type() {
return this.type;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cassandra\src\main\java\org\springframework\boot\cassandra\autoconfigure\CassandraProperties.java | 2 |
请完成以下Java代码 | private Optional<Resource[]> retrieveResources() throws IOException {
Optional<Resource[]> resources = Optional.empty();
Resource connectorRootPath = resourceLoader.getResource(connectorRoot);
if (connectorRootPath.exists()) {
return Optional.ofNullable(resourceLoader.getResources(connectorRoot + "**.json"));
}
return resources;
}
private ConnectorDefinition read(InputStream inputStream) throws IOException {
return objectMapper.readValue(inputStream, ConnectorDefinition.class);
}
public List<ConnectorDefinition> get() throws IOException {
List<ConnectorDefinition> connectorDefinitions = new ArrayList<>();
Optional<Resource[]> resourcesOptional = retrieveResources();
if (resourcesOptional.isPresent()) {
for (Resource resource : resourcesOptional.get()) {
connectorDefinitions.add(read(resource.getInputStream()));
}
validate(connectorDefinitions);
}
return connectorDefinitions;
} | protected void validate(List<ConnectorDefinition> connectorDefinitions) {
if (!connectorDefinitions.isEmpty()) {
Set<String> processedNames = new HashSet<>();
for (ConnectorDefinition connectorDefinition : connectorDefinitions) {
String name = connectorDefinition.getName();
if (name == null || name.isEmpty()) {
throw new IllegalStateException("connectorDefinition name cannot be null or empty");
}
if (name.contains(".")) {
throw new IllegalStateException("connectorDefinition name cannot have '.' character");
}
if (!processedNames.add(name)) {
throw new IllegalStateException(
"More than one connectorDefinition with name '" + name + "' was found. Names must be unique."
);
}
}
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-spring-connector\src\main\java\org\activiti\core\common\spring\connector\ConnectorDefinitionService.java | 1 |
请完成以下Java代码 | public Store where(Condition condition) {
return new Store(getQualifiedName(), aliased() ? this : null, null, condition);
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Collection<? extends Condition> conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Condition... conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Field<Boolean> condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(SQL condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL | public Store where(@Stringly.SQL String condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition, Object... binds) {
return where(DSL.condition(condition, binds));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition, QueryPart... parts) {
return where(DSL.condition(condition, parts));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store whereExists(Select<?> select) {
return where(DSL.exists(select));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store whereNotExists(Select<?> select) {
return where(DSL.notExists(select));
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Store.java | 1 |
请完成以下Java代码 | public String getNormalName() {
return "AI model";
}
},
API_KEY(44);
@Getter
private final int protoNumber; // Corresponds to EntityTypeProto
@Getter
private final String tableName;
@Getter
private final String normalName = StringUtils.capitalize(Strings.CS.removeStart(name(), "TB_")
.toLowerCase().replaceAll("_", " "));
public static final List<String> NORMAL_NAMES = EnumSet.allOf(EntityType.class).stream()
.map(EntityType::getNormalName).toList();
private static final EntityType[] BY_PROTO;
static {
BY_PROTO = new EntityType[Arrays.stream(values()).mapToInt(EntityType::getProtoNumber).max().orElse(0) + 1];
for (EntityType entityType : values()) {
BY_PROTO[entityType.getProtoNumber()] = entityType;
}
}
EntityType(int protoNumber) {
this.protoNumber = protoNumber;
this.tableName = name().toLowerCase();
}
EntityType(int protoNumber, String tableName) { | this.protoNumber = protoNumber;
this.tableName = tableName;
}
public boolean isOneOf(EntityType... types) {
if (types == null) {
return false;
}
for (EntityType type : types) {
if (this == type) {
return true;
}
}
return false;
}
public static EntityType forProtoNumber(int protoNumber) {
if (protoNumber < 0 || protoNumber >= BY_PROTO.length) {
throw new IllegalArgumentException("Invalid EntityType proto number " + protoNumber);
}
return BY_PROTO[protoNumber];
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\EntityType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean determineQosEnabled() {
if (this.qosEnabled != null) {
return this.qosEnabled;
}
return (getDeliveryMode() != null || getPriority() != null || getTimeToLive() != null);
}
public @Nullable Boolean getQosEnabled() {
return this.qosEnabled;
}
public void setQosEnabled(@Nullable Boolean qosEnabled) {
this.qosEnabled = qosEnabled;
}
public @Nullable Duration getReceiveTimeout() {
return this.receiveTimeout;
}
public void setReceiveTimeout(@Nullable Duration receiveTimeout) {
this.receiveTimeout = receiveTimeout;
}
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Acknowledge mode used when creating sessions.
*/
private AcknowledgeMode acknowledgeMode = AcknowledgeMode.AUTO;
/**
* Whether to use transacted sessions.
*/
private boolean transacted;
public AcknowledgeMode getAcknowledgeMode() {
return this.acknowledgeMode;
}
public void setAcknowledgeMode(AcknowledgeMode acknowledgeMode) {
this.acknowledgeMode = acknowledgeMode; | }
public boolean isTransacted() {
return this.transacted;
}
public void setTransacted(boolean transacted) {
this.transacted = transacted;
}
}
}
public enum DeliveryMode {
/**
* Does not require that the message be logged to stable storage. This is the
* lowest-overhead delivery mode but can lead to lost of message if the broker
* goes down.
*/
NON_PERSISTENT(1),
/*
* Instructs the JMS provider to log the message to stable storage as part of the
* client's send operation.
*/
PERSISTENT(2);
private final int value;
DeliveryMode(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsProperties.java | 2 |
请完成以下Java代码 | public class AbstractStartCaseInstanceBeforeContext {
protected String businessKey;
protected String businessStatus;
protected String caseInstanceName;
protected Map<String, Object> variables;
protected Case caseModel;
protected CaseDefinition caseDefinition;
protected CmmnModel cmmnModel;
public AbstractStartCaseInstanceBeforeContext() {
}
public AbstractStartCaseInstanceBeforeContext(String businessKey, String businessStatus, String caseInstanceName, Map<String, Object> variables,
Case caseModel, CaseDefinition caseDefinition, CmmnModel cmmnModel) {
this.businessKey = businessKey;
this.businessStatus = businessStatus;
this.caseInstanceName = caseInstanceName;
this.variables = variables;
this.caseModel = caseModel;
this.caseDefinition = caseDefinition;
this.cmmnModel = cmmnModel;
}
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getBusinessStatus() {
return businessStatus;
}
public String getCaseInstanceName() {
return caseInstanceName;
}
public void setCaseInstanceName(String caseInstanceName) {
this.caseInstanceName = caseInstanceName;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables; | }
public Case getCaseModel() {
return caseModel;
}
public void setCaseModel(Case caseModel) {
this.caseModel = caseModel;
}
public CaseDefinition getCaseDefinition() {
return caseDefinition;
}
public void setCaseDefinition(CaseDefinition caseDefinition) {
this.caseDefinition = caseDefinition;
}
public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\AbstractStartCaseInstanceBeforeContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
public static class Timeouts {
/**
* Bucket connect timeout.
*/
private Duration connect = Duration.ofSeconds(10);
/**
* Bucket disconnect timeout.
*/
private Duration disconnect = Duration.ofSeconds(10);
/**
* Timeout for operations on a specific key-value.
*/
private Duration keyValue = Duration.ofMillis(2500);
/**
* Timeout for operations on a specific key-value with a durability level.
*/
private Duration keyValueDurable = Duration.ofSeconds(10);
/**
* N1QL query operations timeout.
*/
private Duration query = Duration.ofSeconds(75);
/**
* Regular and geospatial view operations timeout.
*/
private Duration view = Duration.ofSeconds(75);
/**
* Timeout for the search service.
*/
private Duration search = Duration.ofSeconds(75);
/**
* Timeout for the analytics service.
*/
private Duration analytics = Duration.ofSeconds(75);
/**
* Timeout for the management operations.
*/
private Duration management = Duration.ofSeconds(75);
public Duration getConnect() {
return this.connect;
}
public void setConnect(Duration connect) {
this.connect = connect;
}
public Duration getDisconnect() {
return this.disconnect; | }
public void setDisconnect(Duration disconnect) {
this.disconnect = disconnect;
}
public Duration getKeyValue() {
return this.keyValue;
}
public void setKeyValue(Duration keyValue) {
this.keyValue = keyValue;
}
public Duration getKeyValueDurable() {
return this.keyValueDurable;
}
public void setKeyValueDurable(Duration keyValueDurable) {
this.keyValueDurable = keyValueDurable;
}
public Duration getQuery() {
return this.query;
}
public void setQuery(Duration query) {
this.query = query;
}
public Duration getView() {
return this.view;
}
public void setView(Duration view) {
this.view = view;
}
public Duration getSearch() {
return this.search;
}
public void setSearch(Duration search) {
this.search = search;
}
public Duration getAnalytics() {
return this.analytics;
}
public void setAnalytics(Duration analytics) {
this.analytics = analytics;
}
public Duration getManagement() {
return this.management;
}
public void setManagement(Duration management) {
this.management = management;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DemoController {
@Autowired
private OrderProperties orderProperties;
/**
* 测试 @ConfigurationProperties 注解的配置属性类
*/
@GetMapping("/test01")
public OrderProperties test01() {
return orderProperties;
}
@Value(value = "${order.pay-timeout-seconds}")
private Integer payTimeoutSeconds;
@Value(value = "${order.create-frequency-seconds}")
private Integer createFrequencySeconds; | /**
* 测试 @Value 注解的属性
*/
@GetMapping("/test02")
public Map<String, Object> test02() {
return new JSONObject().fluentPut("payTimeoutSeconds", payTimeoutSeconds)
.fluentPut("createFrequencySeconds", createFrequencySeconds);
}
private Logger logger = LoggerFactory.getLogger(getClass());
@GetMapping("/logger")
public void logger() {
logger.debug("[logger][测试一下]");
}
} | repos\SpringBoot-Labs-master\labx-05-spring-cloud-alibaba-nacos-config\labx-05-sca-nacos-config-auto-refresh\src\main\java\cn\iocoder\springcloudalibaba\labx5\nacosdemo\controller\DemoController.java | 2 |
请完成以下Java代码 | public class JaasSubjectHolder implements Serializable {
private static final long serialVersionUID = 8174713761131577405L;
private Subject jaasSubject;
private String username;
private Map<String, byte[]> savedTokens = new HashMap<String, byte[]>();
public JaasSubjectHolder(Subject jaasSubject) {
this.jaasSubject = jaasSubject;
}
public JaasSubjectHolder(Subject jaasSubject, String username) {
this.jaasSubject = jaasSubject;
this.username = username;
} | public String getUsername() {
return this.username;
}
public Subject getJaasSubject() {
return this.jaasSubject;
}
public void addToken(String targetService, byte[] outToken) {
this.savedTokens.put(targetService, outToken);
}
public byte[] getToken(String principalName) {
return this.savedTokens.get(principalName);
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\JaasSubjectHolder.java | 1 |
请完成以下Java代码 | public ResponseEntity<PageResult<JobDto>> queryJob(JobQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK);
}
@Log("新增岗位")
@ApiOperation("新增岗位")
@PostMapping
@PreAuthorize("@el.check('job:add')")
public ResponseEntity<Object> createJob(@Validated @RequestBody Job resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
jobService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改岗位")
@ApiOperation("修改岗位")
@PutMapping
@PreAuthorize("@el.check('job:edit')")
public ResponseEntity<Object> updateJob(@Validated(Job.Update.class) @RequestBody Job resources){ | jobService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除岗位")
@ApiOperation("删除岗位")
@DeleteMapping
@PreAuthorize("@el.check('job:del')")
public ResponseEntity<Object> deleteJob(@RequestBody Set<Long> ids){
// 验证是否被用户关联
jobService.verification(ids);
jobService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\JobController.java | 1 |
请完成以下Java代码 | static final class BeanPropertiesStandalone extends BeanELResolver.BeanProperties {
BeanPropertiesStandalone(Class<?> type) throws ELException {
super(type);
PropertyDescriptor[] pds = getPropertyDescriptors(this.type);
for (PropertyDescriptor pd : pds) {
this.properties.put(pd.getName(), new BeanPropertyStandalone(type, pd));
}
/*
* Populating from any interfaces causes default methods to be included.
*/
populateFromInterfaces(type);
}
private void populateFromInterfaces(Class<?> aClass) {
Class<?>[] interfaces = aClass.getInterfaces();
for (Class<?> ifs : interfaces) {
PropertyDescriptor[] pds = getPropertyDescriptors(type);
for (PropertyDescriptor pd : pds) {
if (!this.properties.containsKey(pd.getName())) {
this.properties.put(pd.getName(), new BeanPropertyStandalone(this.type, pd));
}
}
populateFromInterfaces(ifs);
}
Class<?> superclass = aClass.getSuperclass();
if (superclass != null) {
populateFromInterfaces(superclass);
}
}
}
static final class BeanPropertyStandalone extends BeanELResolver.BeanProperty {
private final String name; | private final Method readMethod;
private final Method writeMethod;
BeanPropertyStandalone(Class<?> owner, PropertyDescriptor pd) {
super(owner, pd.getType());
name = pd.getName();
readMethod = pd.getReadMethod();
writeMethod = pd.getWriteMethod();
}
@Override
String getName() {
return name;
}
@Override
Method getReadMethod() {
return readMethod;
}
@Override
Method getWriteMethod() {
return writeMethod;
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanSupportStandalone.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne
private User administrator;
@OneToMany(mappedBy = "id")
private Set<User> users = new HashSet<>();
public void addUser(User user) {
users.add(user);
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
} | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getAdministrator() {
return administrator;
}
public void setAdministrator(User administrator) {
this.administrator = administrator;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\data\persistence\findvsget\entity\Group.java | 2 |
请完成以下Java代码 | protected DataBuffer wrap(ByteBuf byteBuf, ServerHttpResponse response) {
DataBufferFactory bufferFactory = response.bufferFactory();
if (bufferFactory instanceof NettyDataBufferFactory) {
NettyDataBufferFactory factory = (NettyDataBufferFactory) bufferFactory;
return factory.wrap(byteBuf);
}
// MockServerHttpResponse creates these
else if (bufferFactory instanceof DefaultDataBufferFactory) {
DataBuffer buffer = ((DefaultDataBufferFactory) bufferFactory).allocateBuffer(byteBuf.readableBytes());
buffer.write(byteBuf.nioBuffer());
byteBuf.release();
return buffer;
}
throw new IllegalArgumentException("Unknown DataBufferFactory type " + bufferFactory.getClass());
}
private void cleanup(ServerWebExchange exchange) {
Connection connection = exchange.getAttribute(CLIENT_RESPONSE_CONN_ATTR);
if (connection != null) {
connection.dispose();
} | }
// TODO: use framework if possible
private boolean isStreamingMediaType(@Nullable MediaType contentType) {
if (contentType != null) {
for (int i = 0; i < streamingMediaTypes.size(); i++) {
if (streamingMediaTypes.get(i).isCompatibleWith(contentType)) {
return true;
}
}
}
return false;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\NettyWriteResponseFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setQUANTITY(String value) {
this.quantity = value;
}
/**
* Gets the value of the measurementunit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMEASUREMENTUNIT() {
return measurementunit;
}
/**
* Sets the value of the measurementunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMEASUREMENTUNIT(String value) {
this.measurementunit = value;
}
/**
* Gets the value of the date1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE1() {
return date1;
}
/**
* Sets the value of the date1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE1(String value) {
this.date1 = value;
}
/**
* Gets the value of the date2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE2() {
return date2;
}
/**
* Sets the value of the date2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE2(String value) {
this.date2 = value;
}
/**
* Gets the value of the date3 property.
*
* @return | * possible object is
* {@link String }
*
*/
public String getDATE3() {
return date3;
}
/**
* Sets the value of the date3 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE3(String value) {
this.date3 = value;
}
/**
* Gets the value of the date4 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE4() {
return date4;
}
/**
* Sets the value of the date4 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE4(String value) {
this.date4 = value;
}
/**
* Gets the value of the date5 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE5() {
return date5;
}
/**
* Sets the value of the date5 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE5(String value) {
this.date5 = 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\DPLQU1.java | 2 |
请完成以下Java代码 | public void setCostingMethod (final java.lang.String CostingMethod)
{
set_Value (COLUMNNAME_CostingMethod, CostingMethod);
}
@Override
public java.lang.String getCostingMethod()
{
return get_ValueAsString(COLUMNNAME_CostingMethod);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsCalculated (final boolean IsCalculated)
{
set_Value (COLUMNNAME_IsCalculated, IsCalculated);
}
@Override
public boolean isCalculated()
{ | return get_ValueAsBoolean(COLUMNNAME_IsCalculated);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostElement.java | 1 |
请完成以下Java代码 | public String getId() {
return null;
}
@Override
public void setId(String id) {}
@Override
public boolean isInserted() {
return false;
}
@Override
public void setInserted(boolean inserted) {}
@Override
public boolean isUpdated() {
return false;
}
@Override
public void setUpdated(boolean updated) {}
@Override
public boolean isDeleted() {
return false;
}
@Override
public void setDeleted(boolean deleted) {}
@Override
public Object getPersistentState() {
return null;
}
@Override
public void setRevision(int revision) {}
@Override
public int getRevision() {
return 0;
}
@Override
public int getRevisionNext() {
return 0;
} | @Override
public void setName(String name) {}
@Override
public void setProcessInstanceId(String processInstanceId) {}
@Override
public void setExecutionId(String executionId) {}
@Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {}
@Override
public String getExecutionId() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java | 1 |
请完成以下Java代码 | public void changeState() {
if (runtimeService == null) {
throw new FlowableException("CmmnRuntimeService cannot be null, Obtain your builder instance from the CmmnRuntimeService to access this feature");
}
runtimeService.changePlanItemState(this);
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public Set<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitions() {
return activatePlanItemDefinitions;
}
public Set<MoveToAvailablePlanItemDefinitionMapping> getChangeToAvailableStatePlanItemDefinitions() {
return changeToAvailableStatePlanItemDefinitions;
}
public Set<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitions() {
return terminatePlanItemDefinitions;
}
public Set<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitions() {
return waitingForRepetitionPlanItemDefinitions;
}
public Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitions() {
return removeWaitingForRepetitionPlanItemDefinitions;
}
public Set<ChangePlanItemIdMapping> getChangePlanItemIds() { | return changePlanItemIds;
}
public Set<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdsWithDefinitionId() {
return changePlanItemIdsWithDefinitionId;
}
public Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIds() {
return changePlanItemDefinitionWithNewTargetIds;
}
public Map<String, Object> getCaseVariables() {
return caseVariables;
}
public Map<String, Map<String, Object>> getChildInstanceTaskVariables() {
return childInstanceTaskVariables;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\ChangePlanItemStateBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getAuthToken() {
return authToken;
}
/**
* Sets the value of the authToken property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthToken(String value) {
this.authToken = value;
}
/**
* Gets the value of the depot property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getDepot() {
return depot;
}
/**
* Sets the value of the depot property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDepot(String value) {
this.depot = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\Login.java | 2 |
请完成以下Java代码 | public BigDecimal getA_Purchase_Option_Credit_Per ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Purchase_Option_Credit_Per);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Option Purchase Price.
@param A_Purchase_Price Option Purchase Price */
public void setA_Purchase_Price (BigDecimal A_Purchase_Price)
{
set_Value (COLUMNNAME_A_Purchase_Price, A_Purchase_Price);
}
/** Get Option Purchase Price.
@return Option Purchase Price */
public BigDecimal getA_Purchase_Price ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Purchase_Price);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Business Partner .
@param C_BPartner_ID
Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Business Partner .
@return Identifies a Business Partner
*/
public int getC_BPartner_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Fin.java | 1 |
请完成以下Java代码 | public void setProcessDefinitionIdIn(String[] processDefinitionIdIn) {
this.processDefinitionIdIn = processDefinitionIdIn;
}
public String[] getProcessInstanceIdIn() {
return processInstanceIdIn;
}
@CamundaQueryParam(value="processInstanceIdIn", converter = StringArrayConverter.class)
public void setProcessInstanceIdIn(String[] processInstanceIdIn) {
this.processInstanceIdIn = processInstanceIdIn;
}
public String[] getActivityIdIn() {
return activityIdIn; | }
@CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class)
public void setActivityIdIn(String[] activityIdIn) {
this.activityIdIn = activityIdIn;
}
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
protected String getOrderByValue(String sortBy) {
return ORDER_BY_VALUES.get(sortBy);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\IncidentQueryDto.java | 1 |
请完成以下Java代码 | public class GitHubExample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
// static final JsonFactory JSON_FACTORY = new GsonFactory();
private static void run() throws Exception {
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10;
url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url);
ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
Type type = new TypeToken<List<User>>() {
}.getType();
List<User> users = (List<User>) request.execute().parseAs(type);
System.out.println(users);
url.appendRawPath("/eugenp"); | request = requestFactory.buildGetRequest(url);
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<HttpResponse> responseFuture = request.executeAsync(executor);
User eugen = responseFuture.get().parseAs(User.class);
System.out.println(eugen);
executor.shutdown();
}
public static void main(String[] args) {
try {
run();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
} | repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\googlehttpclientguide\GitHubExample.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDefaultVersion() {
return defaultVersion;
}
public void setDefaultVersion(String defaultVersion) {
this.defaultVersion = defaultVersion;
}
public boolean isDetectSupportedVersions() {
return detectSupportedVersions;
}
public void setDetectSupportedVersions(boolean detectSupportedVersions) {
this.detectSupportedVersions = detectSupportedVersions;
}
public String getHeaderName() {
return headerName;
}
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
public MediaType getMediaType() {
return mediaType;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
public String getMediaTypeParamName() {
return mediaTypeParamName;
}
public void setMediaTypeParamName(String mediaTypeParamName) {
this.mediaTypeParamName = mediaTypeParamName;
}
public Integer getPathSegment() {
return pathSegment;
}
public void setPathSegment(Integer pathSegment) {
this.pathSegment = pathSegment;
}
public String getRequestParamName() {
return requestParamName;
}
public void setRequestParamName(String requestParamName) {
this.requestParamName = requestParamName;
} | public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<String> getSupportedVersions() {
return supportedVersions;
}
public void setSupportedVersions(List<String> supportedVersions) {
this.supportedVersions = supportedVersions;
}
@Override
public String toString() {
// @formatter:off
return new ToStringCreator(this)
.append("defaultVersion", defaultVersion)
.append("detectSupportedVersions", detectSupportedVersions)
.append("headerName", headerName)
.append("mediaType", mediaType)
.append("mediaTypeParamName", mediaTypeParamName)
.append("pathSegment", pathSegment)
.append("requestParamName", requestParamName)
.append("required", required)
.append("supportedVersions", supportedVersions)
.toString();
// @formatter:on
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\VersionProperties.java | 2 |
请完成以下Java代码 | public String refreshHeadToken(String oldToken) {
if(StrUtil.isEmpty(oldToken)){
return null;
}
String token = oldToken.substring(tokenHead.length());
if(StrUtil.isEmpty(token)){
return null;
}
//token校验不通过
Claims claims = getClaimsFromToken(token);
if(claims==null){
return null;
}
//如果token已经过期,不支持刷新
if(isTokenExpired(token)){
return null;
}
//如果token在30分钟之内刚刷新过,返回原token
if(tokenRefreshJustBefore(token,30*60)){
return token;
}else{
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
} | }
/**
* 判断token在指定时间内是否刚刚刷新过
* @param token 原token
* @param time 指定时间(秒)
*/
private boolean tokenRefreshJustBefore(String token, int time) {
Claims claims = getClaimsFromToken(token);
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
Date refreshDate = new Date();
//刷新时间在创建时间的指定时间内
if(refreshDate.after(created)&&refreshDate.before(DateUtil.offsetSecond(created,time))){
return true;
}
return false;
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\util\JwtTokenUtil.java | 1 |
请完成以下Java代码 | public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
ServiceRegistry serviceRegistry = configureServiceRegistry(properties);
return makeSessionFactory(serviceRegistry);
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Student.class);
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException { | return configureServiceRegistry(getProperties());
}
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
public static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\HibernateUtil.java | 1 |
请完成以下Java代码 | public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>public.Book.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>public.Book.author_id</code>.
*/
public void setAuthorId(Integer value) {
set(1, value);
}
/**
* Getter for <code>public.Book.author_id</code>.
*/
public Integer getAuthorId() {
return (Integer) get(1);
}
/**
* Setter for <code>public.Book.title</code>.
*/
public void setTitle(String value) {
set(2, value);
}
/**
* Getter for <code>public.Book.title</code>.
*/
public String getTitle() {
return (String) get(2);
}
/**
* Setter for <code>public.Book.description</code>.
*/
public void setDescription(String value) {
set(3, value);
}
/**
* Getter for <code>public.Book.description</code>.
*/
public String getDescription() {
return (String) get(3);
}
/**
* Setter for <code>public.Book.store_id</code>.
*/
public void setStoreId(Integer value) {
set(4, value);
}
/**
* Getter for <code>public.Book.store_id</code>.
*/
public Integer getStoreId() {
return (Integer) get(4);
} | // -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached BookRecord
*/
public BookRecord() {
super(Book.BOOK);
}
/**
* Create a detached, initialised BookRecord
*/
public BookRecord(Integer id, Integer authorId, String title, String description, Integer storeId) {
super(Book.BOOK);
setId(id);
setAuthorId(authorId);
setTitle(title);
setDescription(description);
setStoreId(storeId);
resetChangedOnNotNull();
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\BookRecord.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("sentMsg", sentMsg)
.add("sentConnectionError", sentConnectionError)
.add("messageId", messageId)
.toString();
}
@JsonIgnore
public boolean isSentOK()
{
return Util.same(sentMsg, SENT_OK);
}
public void throwIfNotOK()
{
throwIfNotOK(null);
} | public void throwIfNotOK(@Nullable final Consumer<EMailSendException> exceptionDecorator)
{
if (!isSentOK())
{
final EMailSendException exception = new EMailSendException(this);
if (exceptionDecorator != null)
{
exceptionDecorator.accept(exception);
}
throw exception;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailSentStatus.java | 1 |
请完成以下Java代码 | public static LMQRCode fromGlobalQRCode(final GlobalQRCode globalQRCode)
{
if (!isHandled(globalQRCode))
{
throw new AdempiereException("Invalid Leich und Mehl QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
}
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), VERSION_1))
{
return fromGlobalQRCode_version1(globalQRCode);
}
else
{
throw new AdempiereException("Invalid Leich und Mehl QR Code version: " + version);
}
}
private static LMQRCode fromGlobalQRCode_version1(final GlobalQRCode globalQRCode) | {
// NOTE to dev: keep in sync with huQRCodes.js, parseQRCodePayload_LeichMehl_v1
try
{
final List<String> parts = SPLITTER.splitToList(globalQRCode.getPayloadAsJson());
return LMQRCode.builder()
.code(globalQRCode)
.weightInKg(new BigDecimal(parts.get(0)))
.bestBeforeDate(parts.size() >= 2 ? LocalDate.parse(parts.get(1), BEST_BEFORE_DATE_FORMAT) : null)
.lotNumber(parts.size() >= 3 ? StringUtils.trimBlankToNull(parts.get(2)) : null)
.productNo(parts.size() >= 4 ? StringUtils.trimBlankToNull(parts.get(3)) : null)
.build();
}
catch (Exception ex)
{
throw new AdempiereException("Invalid Leich und Mehl QR Code: " + globalQRCode, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\leich_und_mehl\LMQRCodeParser.java | 1 |
请完成以下Java代码 | public String toString()
{
final String permissionsName = getClass().getSimpleName();
final Collection<MobileApplicationPermission> permissionsList = byMobileApplicationId.values();
final StringBuilder sb = new StringBuilder();
sb.append(permissionsName).append(": ");
if (permissionsList.isEmpty())
{
sb.append("@NoRestrictions@");
}
else
{
sb.append(Env.NL);
}
Joiner.on(Env.NL)
.skipNulls()
.appendTo(sb, permissionsList); | return sb.toString();
}
public boolean isAllowAccess(@NonNull final MobileApplicationRepoId mobileApplicationId)
{
final MobileApplicationPermission permission = byMobileApplicationId.get(mobileApplicationId);
return permission != null && permission.isAllowAccess();
}
public boolean isAllowAction(@NonNull final MobileApplicationRepoId mobileApplicationId, @NonNull final MobileApplicationActionId actionId)
{
final MobileApplicationPermission permission = byMobileApplicationId.get(mobileApplicationId);
return permission != null && permission.isAllowAction(actionId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\mobile_application\MobileApplicationPermissions.java | 1 |
请完成以下Java代码 | public class DefaultTaskFormHandler extends DefaultFormHandler implements TaskFormHandler {
public TaskFormData createTaskForm(TaskEntity task) {
TaskFormDataImpl taskFormData = new TaskFormDataImpl();
TaskDefinition taskDefinition = task.getTaskDefinition();
FormDefinition formDefinition = taskDefinition.getFormDefinition();
Expression formKey = formDefinition.getFormKey();
Expression camundaFormDefinitionKey = formDefinition.getCamundaFormDefinitionKey();
String camundaFormDefinitionBinding = formDefinition.getCamundaFormDefinitionBinding();
Expression camundaFormDefinitionVersion = formDefinition.getCamundaFormDefinitionVersion();
if (formKey != null) {
Object formValue = formKey.getValue(task);
if (formValue != null) {
taskFormData.setFormKey(formValue.toString());
}
} else if (camundaFormDefinitionKey != null && camundaFormDefinitionBinding != null) {
Object formRefKeyValue = camundaFormDefinitionKey.getValue(task);
if(formRefKeyValue != null) {
CamundaFormRefImpl ref = new CamundaFormRefImpl(formRefKeyValue.toString(), camundaFormDefinitionBinding); | if(camundaFormDefinitionBinding.equals(FORM_REF_BINDING_VERSION) && camundaFormDefinitionVersion != null) {
Object formRefVersionValue = camundaFormDefinitionVersion.getValue(task);
if(formRefVersionValue != null) {
ref.setVersion(Integer.parseInt((String)formRefVersionValue));
}
}
taskFormData.setCamundaFormRef(ref);
}
}
taskFormData.setDeploymentId(deploymentId);
taskFormData.setTask(task);
initializeFormProperties(taskFormData, task.getExecution());
initializeFormFields(taskFormData, task.getExecution());
return taskFormData;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\DefaultTaskFormHandler.java | 1 |
请完成以下Java代码 | public MqttQoS getQos() {
return qos;
}
public Builder setQos(MqttQoS qos) {
if(qos == null){
throw new NullPointerException("qos");
}
this.qos = qos;
return this;
}
public MqttLastWill build(){
return new MqttLastWill(topic, message, retain, qos);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MqttLastWill that = (MqttLastWill) o;
if (retain != that.retain) return false;
if (!topic.equals(that.topic)) return false;
if (!message.equals(that.message)) return false;
return qos == that.qos; | }
@Override
public int hashCode() {
int result = topic.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (retain ? 1 : 0);
result = 31 * result + qos.hashCode();
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("MqttLastWill{");
sb.append("topic='").append(topic).append('\'');
sb.append(", message='").append(message).append('\'');
sb.append(", retain=").append(retain);
sb.append(", qos=").append(qos.name());
sb.append('}');
return sb.toString();
}
} | repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttLastWill.java | 1 |
请完成以下Java代码 | class ValueAndUomSQLRowLoader implements SQLRowLoader
{
@NonNull private final KPIField valueField;
@Nullable private final KPIField uomField;
ValueAndUomSQLRowLoader(final List<KPIField> fields)
{
this.uomField = extractUOMField(fields);
this.valueField = extractValueField(fields, uomField);
}
@Nullable
private static KPIField extractUOMField(final List<KPIField> fields)
{
if (fields.size() < 2)
{
return null;
}
for (final KPIField field : fields)
{
final String fieldName = field.getFieldName();
if ("Currency".equalsIgnoreCase(fieldName)
|| "CurrencyCode".equalsIgnoreCase(fieldName)
|| "UOMSymbol".equalsIgnoreCase(fieldName)
|| "UOM".equalsIgnoreCase(fieldName))
{
return field;
}
}
return null;
}
private static KPIField extractValueField(
final List<KPIField> fields,
final KPIField... excludeFields)
{
final List<KPIField> excludeFieldsList = Arrays.asList(excludeFields); | for (final KPIField field : fields)
{
if (!excludeFieldsList.contains(field))
{
return field;
}
}
throw new AdempiereException("Cannot determine value field: " + fields);
}
@Override
public void loadRowToResult(@NonNull final KPIDataResult.Builder data, final @NonNull ResultSet rs) throws SQLException
{
final KPIDataValue value = SQLRowLoaderUtils.retrieveValue(rs, valueField);
final String unit = uomField != null ? rs.getString(uomField.getFieldName()) : null;
data.dataSet(valueField.getFieldName())
.unit(unit)
.dataSetValue(KPIDataSetValuesAggregationKey.NO_KEY)
.put(valueField.getFieldName(), value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\ValueAndUomSQLRowLoader.java | 1 |
请完成以下Java代码 | public Execution getExecution() {
return associationManager.getExecution();
}
/**
* @see #getExecution()
*/
public String getExecutionId() {
Execution e = getExecution();
return e != null ? e.getId() : null;
}
/**
* Returns the {@link ProcessInstance} currently associated or 'null'
*
* @throws ProcessEngineCdiException
* if no {@link Execution} is associated. Use
* {@link #isAssociated()} to check whether an association exists.
*/
public ProcessInstance getProcessInstance() {
Execution execution = getExecution();
if(execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))){
return processEngine
.getRuntimeService()
.createProcessInstanceQuery()
.processInstanceId(execution.getProcessInstanceId())
.singleResult();
}
return (ProcessInstance) execution; | }
// internal implementation //////////////////////////////////////////////////////////
protected void assertExecutionAssociated() {
if (associationManager.getExecution() == null) {
throw new ProcessEngineCdiException("No execution associated. Call busniessProcess.associateExecutionById() or businessProcess.startTask() first.");
}
}
protected void assertTaskAssociated() {
if (associationManager.getTask() == null) {
throw new ProcessEngineCdiException("No task associated. Call businessProcess.startTask() first.");
}
}
protected void assertCommandContextNotActive() {
if(Context.getCommandContext() != null) {
throw new ProcessEngineCdiException("Cannot use this method of the BusinessProcess bean from an active command context.");
}
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\BusinessProcess.java | 1 |
请完成以下Java代码 | public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@PrePersist
private void prePersist() {
logger.info("@PrePersist callback ...");
}
@PreUpdate
private void preUpdate() {
logger.info("@PreUpdate callback ...");
}
@PreRemove
private void preRemove() {
logger.info("@PreRemove callback ...");
}
@PostLoad
private void postLoad() { | logger.info("@PostLoad callback ...");
}
@PostPersist
private void postPersist() {
logger.info("@PostPersist callback ...");
}
@PostUpdate
private void postUpdate() {
logger.info("@PostUpdate callback ...");
}
@PostRemove
private void postRemove() {
logger.info("@PostRemove callback ...");
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJpaCallbacks\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public class DeleteTimerJobCmd implements Command<Object>, Serializable {
private static final Logger log = LoggerFactory.getLogger(DeleteTimerJobCmd.class);
private static final long serialVersionUID = 1L;
protected String timerJobId;
public DeleteTimerJobCmd(String timerJobId) {
this.timerJobId = timerJobId;
}
public Object execute(CommandContext commandContext) {
TimerJobEntity jobToDelete = getJobToDelete(commandContext);
sendCancelEvent(jobToDelete);
commandContext.getTimerJobEntityManager().delete(jobToDelete);
return null;
}
protected void sendCancelEvent(TimerJobEntity jobToDelete) {
if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
Context.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.JOB_CANCELED, jobToDelete));
}
}
protected TimerJobEntity getJobToDelete(CommandContext commandContext) {
if (timerJobId == null) {
throw new ActivitiIllegalArgumentException("jobId is null");
}
if (log.isDebugEnabled()) { | log.debug("Deleting job {}", timerJobId);
}
TimerJobEntity job = commandContext.getTimerJobEntityManager().findById(timerJobId);
if (job == null) {
throw new ActivitiObjectNotFoundException("No timer job found with id '" + timerJobId + "'", Job.class);
}
// We need to check if the job was locked, ie acquired by the job acquisition thread
// This happens if the job was already acquired, but not yet executed.
// In that case, we can't allow to delete the job.
if (job.getLockOwner() != null) {
throw new ActivitiException("Cannot delete timer job when the job is being executed. Try again later.");
}
return job;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteTimerJobCmd.java | 1 |
请完成以下Java代码 | public class MAssetChange extends X_A_Asset_Change
{
/**
*
*/
private static final long serialVersionUID = 5906751299228645904L;
/**
* Default Constructor
* @param ctx context
* @param M_InventoryLine_ID line
*/
public MAssetChange (Properties ctx, int A_Asset_Change_ID, String trxName)
{
super (ctx, A_Asset_Change_ID, trxName);
if (A_Asset_Change_ID == 0)
{
//
}
} // MAssetAddition
/**
* Load Constructor
* @param ctx context
* @param rs result set | */
public MAssetChange (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MInventoryLine
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
if (getA_Reval_Cal_Method() == null)
setA_Reval_Cal_Method("DFT");
return true;
} // beforeSave
} // MAssetAddition | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAssetChange.java | 1 |
请完成以下Java代码 | public Object getTransientVariable(String variableName) {
if (transientVariabes != null && transientVariabes.containsKey(variableName)) {
return transientVariabes.get(variableName).getValue();
}
VariableScopeImpl parentScope = getParentVariableScope();
if (parentScope != null) {
return parentScope.getTransientVariable(variableName);
}
return null;
}
public Map<String, Object> getTransientVariables() {
return collectTransientVariables(new HashMap<String, Object>());
}
protected Map<String, Object> collectTransientVariables(HashMap<String, Object> variables) {
VariableScopeImpl parentScope = getParentVariableScope();
if (parentScope != null) {
variables.putAll(parentScope.collectVariables(variables));
}
if (transientVariabes != null) {
for (String variableName : transientVariabes.keySet()) {
variables.put(variableName, transientVariabes.get(variableName).getValue());
}
}
return variables;
}
public void removeTransientVariableLocal(String variableName) {
if (transientVariabes != null) {
transientVariabes.remove(variableName);
}
}
public void removeTransientVariablesLocal() {
if (transientVariabes != null) {
transientVariabes.clear();
}
}
public void removeTransientVariable(String variableName) { | if (transientVariabes != null && transientVariabes.containsKey(variableName)) {
removeTransientVariableLocal(variableName);
return;
}
VariableScopeImpl parentVariableScope = getParentVariableScope();
if (parentVariableScope != null) {
parentVariableScope.removeTransientVariable(variableName);
}
}
public void removeTransientVariables() {
removeTransientVariablesLocal();
VariableScopeImpl parentVariableScope = getParentVariableScope();
if (parentVariableScope != null) {
parentVariableScope.removeTransientVariablesLocal();
}
}
/**
* Execution variable updates have activity instance ids, but historic task variable updates don't.
*/
protected boolean isActivityIdUsedForDetails() {
return true;
}
// getters and setters
// //////////////////////////////////////////////////////
public ELContext getCachedElContext() {
return cachedElContext;
}
public void setCachedElContext(ELContext cachedElContext) {
this.cachedElContext = cachedElContext;
}
public <T> T getVariable(String variableName, Class<T> variableClass) {
return variableClass.cast(getVariable(variableName));
}
public <T> T getVariableLocal(String variableName, Class<T> variableClass) {
return variableClass.cast(getVariableLocal(variableName));
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\VariableScopeImpl.java | 1 |
请完成以下Java代码 | public OAuth2AccessToken sendRefreshGrant(String refreshTokenValue) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "refresh_token");
params.add("refresh_token", refreshTokenValue);
HttpHeaders headers = new HttpHeaders();
addAuthentication(headers, params);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
log.debug("contacting OAuth2 token endpoint to refresh OAuth2 JWT tokens");
ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.postForEntity(getTokenEndpoint(), entity,
OAuth2AccessToken.class);
if (responseEntity.getStatusCode() != HttpStatus.OK) {
log.debug("failed to refresh tokens: {}", responseEntity.getStatusCodeValue());
throw new HttpClientErrorException(responseEntity.getStatusCode());
}
OAuth2AccessToken accessToken = responseEntity.getBody();
log.info("refreshed OAuth2 JWT cookies using refresh_token grant");
return accessToken;
}
protected abstract void addAuthentication(HttpHeaders reqHeaders, MultiValueMap<String, String> formParams);
protected String getClientSecret() {
String clientSecret = oAuth2Properties.getWebClientConfiguration().getSecret();
if (clientSecret == null) {
throw new InvalidClientException("no client-secret configured in application properties");
}
return clientSecret;
} | protected String getClientId() {
String clientId = oAuth2Properties.getWebClientConfiguration().getClientId();
if (clientId == null) {
throw new InvalidClientException("no client-id configured in application properties");
}
return clientId;
}
/**
* Returns the configured OAuth2 token endpoint URI.
*
* @return the OAuth2 token endpoint URI.
*/
protected String getTokenEndpoint() {
String tokenEndpointUrl = jHipsterProperties.getSecurity().getClientAuthorization().getAccessTokenUri();
if (tokenEndpointUrl == null) {
throw new InvalidClientException("no token endpoint configured in application properties");
}
return tokenEndpointUrl;
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\OAuth2TokenEndpointClientAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class ContainedPackagingItems {
@XmlValue
protected BigDecimal value;
@XmlAttribute(name = "Unit", namespace = "http://erpel.at/schemas/1p0/documents")
protected String unit;
@XmlAttribute(name = "SupplierUnit", namespace = "http://erpel.at/schemas/1p0/documents")
protected String supplierUnit;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Packaging unit type of the contained packages. If customer's and supplier's packaging unit type is different this should be used for customer's packaging unit type.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnit() {
return unit;
}
/**
* Sets the value of the unit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnit(String value) {
this.unit = value;
} | /**
* Packaging unit type used by the supplier. If customer's and supplier's packaging unit type is different this should be used for suppliers's packaging unit type.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSupplierUnit() {
return supplierUnit;
}
/**
* Sets the value of the supplierUnit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSupplierUnit(String value) {
this.supplierUnit = value;
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ConsignmentPackagingSequenceType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ChainWorkflow {
private final OpsClient opsClient;
public ChainWorkflow(OpsClient opsClient) {
this.opsClient = opsClient;
}
public String opsPipeline(String userInput) {
String response = userInput;
System.out.printf("User input: [%s]\n", response);
for (String prompt : OpsClientPrompts.DEV_PIPELINE_STEPS) {
// Compose the request using the response from the previous step.
String request = String.format("{%s}\n {%s}", prompt, response);
System.out.printf("PROMPT: %s:\n", request); | // Call the ops client with the new request and get the new response.
ChatClient.ChatClientRequestSpec requestSpec = opsClient.prompt(request);
ChatClient.CallResponseSpec responseSpec = requestSpec.call();
response = responseSpec.content();
System.out.printf("OUTCOME: %s:\n", response);
// If there is an error, print the error and break
if (response.startsWith("ERROR:")) {
break;
}
}
return response;
}
} | repos\tutorials-master\spring-ai-modules\spring-ai-agentic-patterns\src\main\java\com\baeldung\springai\agenticpatterns\workflows\chain\ChainWorkflow.java | 2 |
请完成以下Java代码 | public static class Stop {
/**
* Command used to stop Docker Compose.
*/
private StopCommand command = StopCommand.STOP;
/**
* Timeout for stopping Docker Compose. Use '0' for forced stop.
*/
private Duration timeout = Duration.ofSeconds(10);
/**
* Arguments to pass to the stop command.
*/
private final List<String> arguments = new ArrayList<>();
public StopCommand getCommand() {
return this.command;
}
public void setCommand(StopCommand command) {
this.command = command;
}
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public List<String> getArguments() {
return this.arguments;
}
}
/**
* Profiles properties.
*/
public static class Profiles {
/**
* Docker compose profiles that should be active.
*/
private Set<String> active = new LinkedHashSet<>();
public Set<String> getActive() {
return this.active;
}
public void setActive(Set<String> active) {
this.active = active;
}
}
/**
* Skip options.
*/
public static class Skip {
/**
* Whether to skip in tests.
*/
private boolean inTests = true;
public boolean isInTests() {
return this.inTests;
}
public void setInTests(boolean inTests) {
this.inTests = inTests;
}
}
/**
* Readiness properties.
*/
public static class Readiness {
/**
* Wait strategy to use.
*/
private Wait wait = Wait.ALWAYS;
/**
* Timeout of the readiness checks.
*/
private Duration timeout = Duration.ofMinutes(2);
/**
* TCP properties.
*/
private final Tcp tcp = new Tcp();
public Wait getWait() {
return this.wait;
}
public void setWait(Wait wait) {
this.wait = wait; | }
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public Tcp getTcp() {
return this.tcp;
}
/**
* Readiness wait strategies.
*/
public enum Wait {
/**
* Always perform readiness checks.
*/
ALWAYS,
/**
* Never perform readiness checks.
*/
NEVER,
/**
* Only perform readiness checks if docker was started with lifecycle
* management.
*/
ONLY_IF_STARTED
}
/**
* TCP properties.
*/
public static class Tcp {
/**
* Timeout for connections.
*/
private Duration connectTimeout = Duration.ofMillis(200);
/**
* Timeout for reads.
*/
private Duration readTimeout = Duration.ofMillis(200);
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataSource dataSource2() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(env.getProperty("mysql.url"));
dataSource.setUsername(env.getProperty("mysql.user") != null ? env.getProperty("mysql.user") : "");
dataSource.setPassword(env.getProperty("mysql.pass") != null ? env.getProperty("mysql.pass") : "");
return dataSource;
}
@Bean
@ConditionalOnBean(name = "dataSource")
@ConditionalOnMissingBean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan("com.baeldung.autoconfiguration.example");
em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
if (additionalProperties() != null) {
em.setJpaProperties(additionalProperties());
}
return em;
}
@Bean
@ConditionalOnMissingBean(type = "JpaTransactionManager")
JpaTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
@ConditionalOnResource(resources = "classpath:mysql.properties")
@Conditional(HibernateCondition.class)
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties(); | hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false");
return hibernateProperties;
}
static class HibernateCondition extends SpringBootCondition {
private static final String[] CLASS_NAMES = { "org.hibernate.ejb.HibernateEntityManager", "org.hibernate.jpa.HibernateEntityManager" };
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");
return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
.orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
}
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-autoconfiguration\src\main\java\com\baeldung\autoconfiguration\MySQLAutoconfiguration.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.