instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class SpringProcessApplication extends AbstractProcessApplication implements ApplicationContextAware, BeanNameAware, ApplicationListener<ApplicationContextEvent> {
protected Map<String, String> properties = new HashMap<String, String>();
protected ApplicationContext applicationContext;
protected String beanName;
@Override
protected String autodetectProcessApplicationName() {
return beanName;
}
public ProcessApplicationReference getReference() {
return new ProcessApplicationReferenceImpl(this);
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void setBeanName(String name) {
this.beanName = name;
}
@Override
public Map<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
try {
// we only want to listen for context events of the main application
// context, not its children
if (event.getSource().equals(applicationContext)) {
if (event instanceof ContextRefreshedEvent && !isDeployed) {
// deploy the process application
afterPropertiesSet(); | } else if (event instanceof ContextClosedEvent) {
// undeploy the process application
destroy();
} else {
// ignore
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void start() {
deploy();
}
public void stop() {
undeploy();
}
public void afterPropertiesSet() throws Exception {
// for backwards compatibility
start();
}
public void destroy() throws Exception {
// for backwards compatibility
stop();
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\application\SpringProcessApplication.java | 1 |
请完成以下Java代码 | public void setSKU (String SKU)
{
set_ValueNoCheck (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
public void setUOMSymbol (String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
public String getUOMSymbol ()
{
return (String)get_Value(COLUMNNAME_UOMSymbol);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC () | {
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Warehouse.
@param WarehouseName
Warehouse Name
*/
public void setWarehouseName (String WarehouseName)
{
set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName);
}
/** Get Warehouse.
@return Warehouse Name
*/
public String getWarehouseName ()
{
return (String)get_Value(COLUMNNAME_WarehouseName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_RV_WarehousePrice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public MessageHandler anotherTargetDirectory() {
FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(OUTPUT_DIR2));
handler.setExpectReply(false); // end of pipeline, reply not needed
return handler;
}
@Bean
public MessageChannel holdingTank() {
return MessageChannels.queue().get();
}
// @Bean
public IntegrationFlow fileReader() {
return IntegrationFlow.from(sourceDirectory(), configurer -> configurer.poller(Pollers.fixedDelay(10)))
.filter(onlyJpgs())
.channel("holdingTank")
.get();
}
// @Bean
public IntegrationFlow fileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(1, TimeUnit.SECONDS.toChronoUnit()), Duration.of(20, TimeUnit.SECONDS.toChronoUnit()))))
.handle(targetDirectory())
.get(); | }
// @Bean
public IntegrationFlow anotherFileWriter() {
return IntegrationFlow.from("holdingTank")
.bridge(e -> e.poller(Pollers.fixedRate(Duration.of(2, TimeUnit.SECONDS.toChronoUnit()), Duration.of(10, TimeUnit.SECONDS.toChronoUnit()))))
.handle(anotherTargetDirectory())
.get();
}
public static void main(final String... args) {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(JavaDSLFileCopyConfig.class);
context.registerShutdownHook();
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a string and press <enter>: ");
while (true) {
final String input = scanner.nextLine();
if ("q".equals(input.trim())) {
context.close();
scanner.close();
break;
}
}
System.exit(0);
}
} | repos\tutorials-master\spring-integration\src\main\java\com\baeldung\dsl\JavaDSLFileCopyConfig.java | 2 |
请完成以下Java代码 | public class MobileAppBundleInfo extends MobileAppBundle {
@Schema(description = "Android package name")
private String androidPkgName;
@Schema(description = "IOS package name")
private String iosPkgName;
@Schema(description = "List of available oauth2 clients")
private List<OAuth2ClientInfo> oauth2ClientInfos;
@Schema(description = "Indicates if qr code is available for bundle")
private boolean qrCodeEnabled;
public MobileAppBundleInfo(MobileAppBundle mobileApp, String androidPkgName, String iosPkgName, boolean qrCodeEnabled) {
super(mobileApp);
this.androidPkgName = androidPkgName;
this.iosPkgName = iosPkgName;
this.qrCodeEnabled = qrCodeEnabled;
}
public MobileAppBundleInfo(MobileAppBundle mobileApp, String androidPkgName, String iosPkgName, boolean qrCodeEnabled, List<OAuth2ClientInfo> oauth2ClientInfos) {
super(mobileApp); | this.androidPkgName = androidPkgName;
this.iosPkgName = iosPkgName;
this.qrCodeEnabled = qrCodeEnabled;
this.oauth2ClientInfos = oauth2ClientInfos;
}
public MobileAppBundleInfo() {
super();
}
public MobileAppBundleInfo(MobileAppBundleId mobileAppBundleId) {
super(mobileAppBundleId);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\mobile\bundle\MobileAppBundleInfo.java | 1 |
请完成以下Java代码 | private static void addSubProducer(final List<KeyNamePair> subProducerBPartners, final Properties ctx, final int bpartnerId)
{
if (bpartnerId <= 0)
{
return;
}
//
// Check if our BPartner is already in the list.
// If yes, there is no point to add it.
if (subProducerBPartners != null)
{
for (final KeyNamePair subProducer : subProducerBPartners)
{
if (subProducer == null)
{
continue;
}
if (subProducer.getKey() == bpartnerId)
{
// our bpartner is already in the list
return;
}
}
}
//
// Load the new BPartner and add it to our list
final I_C_BPartner bpartner = InterfaceWrapperHelper.create(ctx, bpartnerId, I_C_BPartner.class, ITrx.TRXNAME_None);
if (bpartner == null)
{
return; | }
final KeyNamePair bpartnerKNP = toKeyNamePair(bpartner);
subProducerBPartners.add(bpartnerKNP);
}
/**
* Retrieves suggested SubProducer BPartners for given <code>bpartnerId</code>
*
* @return list of bpartner's suggested SubProducers
*/
private static List<KeyNamePair> retrieveSubProducerKeyNamePairs(final Properties ctx, final int bpartnerId)
{
return Services.get(ISubProducerAttributeDAO.class)
.retrieveSubProducerBPartners(ctx, bpartnerId)
.stream()
.map(bpartner -> toKeyNamePair(bpartner))
.collect(GuavaCollectors.toImmutableList());
}
/**
* Convert given {@link I_C_BPartner} to a {@link KeyNamePair}.
*/
private static final KeyNamePair toKeyNamePair(@NonNull final I_C_BPartner bpartner)
{
return KeyNamePair.of(bpartner.getC_BPartner_ID(), bpartner.getName(), bpartner.getDescription());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUSubProducerBPartnerAttributeValuesProvider.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Reval_Index_ID()));
}
/** Set A_Effective_Date.
@param A_Effective_Date A_Effective_Date */
public void setA_Effective_Date (Timestamp A_Effective_Date)
{
set_Value (COLUMNNAME_A_Effective_Date, A_Effective_Date);
}
/** Get A_Effective_Date.
@return A_Effective_Date */
public Timestamp getA_Effective_Date ()
{
return (Timestamp)get_Value(COLUMNNAME_A_Effective_Date);
}
/** A_Reval_Code AD_Reference_ID=53262 */
public static final int A_REVAL_CODE_AD_Reference_ID=53262;
/** Revaluation Code #1 = R01 */
public static final String A_REVAL_CODE_RevaluationCode1 = "R01";
/** Revaluation Code #2 = R02 */
public static final String A_REVAL_CODE_RevaluationCode2 = "R02";
/** Revaluation Code #3 = R03 */
public static final String A_REVAL_CODE_RevaluationCode3 = "R03";
/** Set A_Reval_Code.
@param A_Reval_Code A_Reval_Code */
public void setA_Reval_Code (String A_Reval_Code)
{
set_Value (COLUMNNAME_A_Reval_Code, A_Reval_Code);
}
/** Get A_Reval_Code.
@return A_Reval_Code */
public String getA_Reval_Code ()
{
return (String)get_Value(COLUMNNAME_A_Reval_Code);
}
/** A_Reval_Multiplier AD_Reference_ID=53260 */
public static final int A_REVAL_MULTIPLIER_AD_Reference_ID=53260;
/** Factor = FAC */
public static final String A_REVAL_MULTIPLIER_Factor = "FAC";
/** Index = IND */
public static final String A_REVAL_MULTIPLIER_Index = "IND";
/** Set A_Reval_Multiplier.
@param A_Reval_Multiplier A_Reval_Multiplier */
public void setA_Reval_Multiplier (String A_Reval_Multiplier)
{ | set_Value (COLUMNNAME_A_Reval_Multiplier, A_Reval_Multiplier);
}
/** Get A_Reval_Multiplier.
@return A_Reval_Multiplier */
public String getA_Reval_Multiplier ()
{
return (String)get_Value(COLUMNNAME_A_Reval_Multiplier);
}
/** Set A_Reval_Rate.
@param A_Reval_Rate A_Reval_Rate */
public void setA_Reval_Rate (BigDecimal A_Reval_Rate)
{
set_Value (COLUMNNAME_A_Reval_Rate, A_Reval_Rate);
}
/** Get A_Reval_Rate.
@return A_Reval_Rate */
public BigDecimal getA_Reval_Rate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Reval_Rate);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Reval_Index.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception {
X_AD_HouseKeeping houseKeeping = new X_AD_HouseKeeping(getCtx(), p_AD_HouseKeeping_ID,get_TrxName());
int tableID = houseKeeping.getAD_Table_ID();
MTable table = new MTable(getCtx(), tableID, get_TrxName());
String tableName = table.getTableName();
String whereClause = houseKeeping.getWhereClause();
int noins = 0;
int noexp = 0;
int nodel = 0;
if (houseKeeping.isSaveInHistoric()){
String sql = "INSERT INTO hst_"+tableName + " SELECT * FROM " + tableName;
if (whereClause != null && whereClause.length() > 0)
sql = sql + " WHERE " + whereClause;
noins = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
if (noins == -1)
throw new AdempiereSystemError("Cannot insert into hst_"+tableName);
addLog("@Inserted@ " + noins);
} //saveInHistoric
Date date = new Date();
if (houseKeeping.isExportXMLBackup()){
String pathFile = houseKeeping.getBackupFolder();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = dateFormat.format(date);
FileWriter file = new FileWriter(pathFile+File.separator+tableName+dateString+".xml");
String sql = "SELECT * FROM " + tableName;
if (whereClause != null && whereClause.length() > 0)
sql = sql + " WHERE " + whereClause;
PreparedStatement pstmt = null;
ResultSet rs = null;
StringBuilder linexml = null;
try
{
pstmt = DB.prepareStatement(sql, get_TrxName());
rs = pstmt.executeQuery();
while (rs.next()) {
GenericPO po = new GenericPO(tableName, getCtx(), rs, get_TrxName());
linexml = po.get_xmlString(linexml);
noexp++;
}
if(linexml != null)
file.write(linexml.toString());
file.close();
} | catch (Exception e)
{
throw e;
}
finally
{
DB.close(rs, pstmt);
pstmt = null;
rs=null;
}
addLog("@Exported@ " + noexp);
}//XmlExport
String sql = "DELETE FROM " + tableName;
if (whereClause != null && whereClause.length() > 0)
sql = sql + " WHERE " + whereClause;
nodel = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
if (nodel == -1)
throw new AdempiereSystemError("Cannot delete from " + tableName);
Timestamp time = new Timestamp(date.getTime());
houseKeeping.setLastRun(time);
houseKeeping.setLastDeleted(nodel);
houseKeeping.saveEx();
addLog("@Deleted@ " + nodel);
String msg = Msg.translate(getCtx(), tableName + "_ID") + " #" + nodel;
return msg;
}//doIt
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\HouseKeeping.java | 1 |
请完成以下Java代码 | private static boolean load(String path)
{
String binPath = path + Predefine.BIN_EXT;
if (loadBin(binPath)) return true;
CONVERT = new char[Character.MAX_VALUE + 1];
for (int i = 0; i < CONVERT.length; i++)
{
CONVERT[i] = (char) i;
}
IOUtil.LineIterator iterator = new IOUtil.LineIterator(path);
while (iterator.hasNext())
{
String line = iterator.next();
if (line == null) return false;
if (line.length() != 3) continue;
CONVERT[line.charAt(0)] = CONVERT[line.charAt(2)];
}
loadSpace();
logger.info("正在缓存字符正规化表到" + binPath);
IOUtil.saveObjectTo(CONVERT, binPath);
return true;
}
private static void loadSpace() {
for (int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; i++) {
if (Character.isWhitespace(i) || Character.isSpaceChar(i)) {
CONVERT[i] = ' ';
}
}
}
private static boolean loadBin(String path)
{
try
{
ObjectInputStream in = new ObjectInputStream(IOUtil.newInputStream(path));
CONVERT = (char[]) in.readObject();
in.close();
}
catch (Exception e)
{
logger.warning("字符正规化表缓存加载失败,原因如下:" + e);
return false;
}
return true;
}
/**
* 将一个字符正规化
* @param c 字符
* @return 正规化后的字符
*/
public static char convert(char c)
{
return CONVERT[c];
}
public static char[] convert(char[] charArray)
{
char[] result = new char[charArray.length];
for (int i = 0; i < charArray.length; i++)
{
result[i] = CONVERT[charArray[i]];
} | return result;
}
public static String convert(String sentence)
{
assert sentence != null;
char[] result = new char[sentence.length()];
convert(sentence, result);
return new String(result);
}
public static void convert(String charArray, char[] result)
{
for (int i = 0; i < charArray.length(); i++)
{
result[i] = CONVERT[charArray.charAt(i)];
}
}
/**
* 正规化一些字符(原地正规化)
* @param charArray 字符
*/
public static void normalization(char[] charArray)
{
assert charArray != null;
for (int i = 0; i < charArray.length; i++)
{
charArray[i] = CONVERT[charArray[i]];
}
}
public static void normalize(Sentence sentence)
{
for (IWord word : sentence)
{
if (word instanceof CompoundWord)
{
for (Word w : ((CompoundWord) word).innerList)
{
w.value = convert(w.value);
}
}
else
word.setValue(word.getValue());
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\other\CharTable.java | 1 |
请完成以下Java代码 | public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
return Objects.hash(city, email, firstName, id, lastName, phoneNumber, postalCode, state, street);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Customer)) {
return false;
} | Customer other = (Customer) obj;
return Objects.equals(city, other.city) && Objects.equals(email, other.email) && Objects.equals(firstName, other.firstName) && id == other.id && Objects.equals(lastName, other.lastName) && Objects.equals(phoneNumber, other.phoneNumber)
&& Objects.equals(postalCode, other.postalCode) && Objects.equals(state, other.state) && Objects.equals(street, other.street);
}
@Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", street=" + street + ", postalCode=" + postalCode + ", city=" + city + ", state=" + state + ", phoneNumber=" + phoneNumber + ", email=" + email + "]";
}
public static Customer[] fromMockFile() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
InputStream jsonFile = new FileInputStream("src/test/resources/json_optimization_mock_data.json");
Customer[] feedback = objectMapper.readValue(jsonFile, Customer[].class);
return feedback;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\Customer.java | 1 |
请完成以下Java代码 | protected void init(String keyspaceName) {
this.keyspaceName = keyspaceName;
this.sessionBuilder = GuavaSessionUtils.builder().withConfigLoader(this.driverOptions.getLoader());
if (!isInstall()) {
initSession();
}
}
public GuavaSession getSession() {
if (!isInstall()) {
return session;
} else {
if (session == null) {
initSession();
}
return session;
}
}
public String getKeyspaceName() {
return keyspaceName;
}
private boolean isInstall() {
return environment.acceptsProfiles(Profiles.of("install"));
}
private void initSession() {
if (this.keyspaceName != null) {
this.sessionBuilder.withKeyspace(this.keyspaceName);
}
this.sessionBuilder.withLocalDatacenter(localDatacenter);
if (StringUtils.isNotBlank(cloudSecureConnectBundlePath)) {
this.sessionBuilder.withCloudSecureConnectBundle(Paths.get(cloudSecureConnectBundlePath));
this.sessionBuilder.withAuthCredentials(cloudClientId, cloudClientSecret);
}
session = sessionBuilder.build();
if (this.metrics && this.jmx) {
MetricRegistry registry =
session.getMetrics().orElseThrow( | () -> new IllegalStateException("Metrics are disabled"))
.getRegistry();
this.reporter =
JmxReporter.forRegistry(registry)
.inDomain("com.datastax.oss.driver")
.build();
this.reporter.start();
}
}
@PreDestroy
public void close() {
if (reporter != null) {
reporter.stop();
}
if (session != null) {
session.close();
}
}
public ConsistencyLevel getDefaultReadConsistencyLevel() {
return driverOptions.getDefaultReadConsistencyLevel();
}
public ConsistencyLevel getDefaultWriteConsistencyLevel() {
return driverOptions.getDefaultWriteConsistencyLevel();
}
} | repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\AbstractCassandraCluster.java | 1 |
请完成以下Java代码 | final class UserQueryRestriction implements IUserQueryRestriction
{
private Join join = Join.AND;
private IUserQueryField searchField;
private Operator operator = Operator.EQUAL;
private Object value;
private Object valueTo;
private boolean mandatory;
private boolean internalParameter;
@Override
public boolean isEmpty()
{
// NOTE: don't check if getJoin() == null because that's always set
// NOTE: don't check if getOperator() == null because that's always set
return getSearchField() == null | && getValue() == null
&& getValueTo() == null;
}
public boolean hasNullValues()
{
if (operator != null && operator.isRangeOperator())
{
return value == null || valueTo == null;
}
else
{
return value == null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\apps\search\UserQueryRestriction.java | 1 |
请完成以下Java代码 | private static DocumentPath createDocumentPathOrNull(final WindowId windowId, final String documentId, final String tabId, final String rowIdStr)
{
if (windowId != null && !Check.isEmpty(documentId))
{
if (Check.isEmpty(tabId) && Check.isEmpty(rowIdStr))
{
return DocumentPath.rootDocumentPath(windowId, documentId);
}
else
{
return DocumentPath.includedDocumentPath(windowId, documentId, tabId, rowIdStr);
}
}
return null;
}
private static List<DocumentPath> createSelectedIncludedDocumentPaths(final WindowId windowId, final String documentIdStr, final JSONSelectedIncludedTab selectedTab)
{
if (windowId == null || Check.isEmpty(documentIdStr, true) || selectedTab == null)
{
return ImmutableList.of();
}
final DocumentId documentId = DocumentId.of(documentIdStr);
final DetailId selectedTabId = DetailId.fromJson(selectedTab.getTabId());
return selectedTab.getRowIds()
.stream()
.map(DocumentId::of)
.map(rowId -> DocumentPath.includedDocumentPath(windowId, documentId, selectedTabId, rowId)) | .collect(ImmutableList.toImmutableList());
}
public DocumentQueryOrderByList getViewOrderBys()
{
return JSONViewOrderBy.toDocumentQueryOrderByList(viewOrderBy);
}
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@Data
public static final class JSONSelectedIncludedTab
{
@JsonProperty("tabId")
private final String tabId;
@JsonProperty("rowIds")
private final List<String> rowIds;
private JSONSelectedIncludedTab(@NonNull @JsonProperty("tabId") final String tabId, @JsonProperty("rowIds") final List<String> rowIds)
{
this.tabId = tabId;
this.rowIds = rowIds != null ? ImmutableList.copyOf(rowIds) : ImmutableList.of();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\json\JSONCreateProcessInstanceRequest.java | 1 |
请完成以下Spring Boot application配置 | spring:
application.name: resilience4j-demo
jackson.serialization.indent_output: true
management:
endpoints.web.exposure.include:
- '*'
endpoint.health.show-details: always
health.circuitbreakers.enabled: true
resilience4j:
circuitbreaker:
configs:
default:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
waitDurationInOpenState: 5s
failureRateThreshold: 50
eventConsumerBufferSize: 10
ratelimiter:
instances:
ratelimitApi:
limit-for-period: 5
limit-refresh-period: 1s
timeout-duration: 100ms
retry:
instances:
bac | kendA:
maxAttempts: 3
waitDuration: 10s
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
retryExceptions:
- org.springframework.web.client.HttpServerErrorException
- java.io.IOException
bulkhead:
instances:
backendA:
maxConcurrentCalls: 10 | repos\springboot-demo-master\resilience4j\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | private static class QueueConfigurationsMap
{
private final ImmutableList<IEventBusQueueConfiguration> list;
private final ImmutableMap<String, IEventBusQueueConfiguration> byTopicName;
private final IEventBusQueueConfiguration defaultQueueConfiguration;
QueueConfigurationsMap(final List<IEventBusQueueConfiguration> list)
{
final ImmutableMap.Builder<String, IEventBusQueueConfiguration> byTopicName = ImmutableMap.builder();
final ArrayList<DefaultQueueConfiguration> defaultQueueConfigurations = new ArrayList<>();
for (final IEventBusQueueConfiguration queueConfig : list)
{
queueConfig.getTopicName().ifPresent(topicName -> byTopicName.put(topicName, queueConfig));
if (queueConfig instanceof DefaultQueueConfiguration)
{
defaultQueueConfigurations.add((DefaultQueueConfiguration)queueConfig);
}
}
if (defaultQueueConfigurations.size() != 1)
{
throw new AdempiereException("There shall be exactly one default queue configuration but found " + defaultQueueConfigurations)
.setParameter("all configurations", list)
.appendParametersToMessage();
}
this.list = ImmutableList.copyOf(list);
this.byTopicName = byTopicName.build();
this.defaultQueueConfiguration = CollectionUtils.singleElement(defaultQueueConfigurations);
}
@Nullable
public IEventBusQueueConfiguration getByTopicNameOrNull(@NonNull final String topicName)
{
return byTopicName.get(topicName);
}
@NonNull
public IEventBusQueueConfiguration getByTopicNameOrDefault(@NonNull final String topicName)
{
return byTopicName.getOrDefault(topicName, defaultQueueConfiguration);
}
public QueueConfigurationsMap withQueueAdded(@NonNull final IEventBusQueueConfiguration queueConfig) | {
final ArrayList<IEventBusQueueConfiguration> newList = new ArrayList<>(list);
newList.add(queueConfig);
return new QueueConfigurationsMap(newList);
}
public QueueConfigurationsMap withQueueRemovedByTopicName(@NonNull final String topicName)
{
final IEventBusQueueConfiguration queueConfig = getByTopicNameOrNull(topicName);
return queueConfig != null ? withQueueRemoved(queueConfig) : this;
}
public QueueConfigurationsMap withQueueRemoved(@NonNull final IEventBusQueueConfiguration queueConfig)
{
final ArrayList<IEventBusQueueConfiguration> newList = new ArrayList<>(list);
newList.remove(queueConfig);
return new QueueConfigurationsMap(newList);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\remote\rabbitmq\RabbitMQDestinationResolver.java | 1 |
请完成以下Java代码 | public NotificationRule findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(notificationRuleRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public NotificationRule findByTenantIdAndName(UUID tenantId, String name) {
return DaoUtil.getData(notificationRuleRepository.findByTenantIdAndName(tenantId, name));
}
@Override
public PageData<NotificationRule> findByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.toPageData(notificationRuleRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink)));
}
@Override
public NotificationRuleId getExternalIdByInternal(NotificationRuleId internalId) {
return DaoUtil.toEntityId(notificationRuleRepository.getExternalIdByInternal(internalId.getId()), NotificationRuleId::new);
}
@Override
public PageData<NotificationRule> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
} | @Override
protected Class<NotificationRuleEntity> getEntityClass() {
return NotificationRuleEntity.class;
}
@Override
protected JpaRepository<NotificationRuleEntity, UUID> getRepository() {
return notificationRuleRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_RULE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRuleDao.java | 1 |
请完成以下Java代码 | public abstract class QueryParameters extends ListQueryParameterObject {
private static final long serialVersionUID = 1L;
protected boolean historyEnabled = true;
protected boolean maxResultsLimitEnabled = true;
public QueryParameters() { }
public QueryParameters(int firstResult, int maxResults) {
this.firstResult = firstResult;
this.maxResults = maxResults;
}
public boolean isHistoryEnabled() {
return historyEnabled; | }
public void setHistoryEnabled(boolean historyEnabled) {
this.historyEnabled = historyEnabled;
}
public boolean isMaxResultsLimitEnabled() {
return maxResultsLimitEnabled;
}
public void disableMaxResultsLimit() {
maxResultsLimitEnabled = false;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\db\QueryParameters.java | 1 |
请完成以下Java代码 | public void updateFlatrateAmt(final I_C_Flatrate_DataEntry dataEntry, final ICalloutField unused)
{
updateFlatrateAmt0(dataEntry);
}
private void updateFlatrateAmt0(final I_C_Flatrate_DataEntry dataEntry)
{
// gh #770: null values in one of the two factors shall result in the product being null and not 0.
if (InterfaceWrapperHelper.isNull(dataEntry, I_C_Flatrate_DataEntry.COLUMNNAME_FlatrateAmtPerUOM)
|| InterfaceWrapperHelper.isNull(dataEntry, I_C_Flatrate_DataEntry.COLUMNNAME_Qty_Planned))
{
dataEntry.setFlatrateAmt(null);
return;
}
final BigDecimal product = dataEntry.getQty_Planned().multiply(dataEntry.getFlatrateAmtPerUOM()); | final BigDecimal flatrateAmt;
if (dataEntry.getC_Currency_ID() > 0)
{
// round to currency precision
final CurrencyId currencyId = CurrencyId.ofRepoId(dataEntry.getC_Currency_ID());
final CurrencyPrecision precision = Services.get(ICurrencyDAO.class).getStdPrecision(currencyId);
flatrateAmt = precision.round(product);
}
else
{
flatrateAmt = product;
}
dataEntry.setFlatrateAmt(flatrateAmt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\model\interceptor\C_Flatrate_DataEntry.java | 1 |
请完成以下Java代码 | public class OLCandASIAwareFactory implements IAttributeSetInstanceAwareFactory
{
@Override
public IAttributeSetInstanceAware createOrNull(final Object model)
{
if (model == null)
{
return null;
}
if (!InterfaceWrapperHelper.isInstanceOf(model, I_C_OLCand.class))
{
return null;
}
final I_C_OLCand olCand = InterfaceWrapperHelper.create(model, I_C_OLCand.class);
// note: returning an anonymous implementation because it is rather trivial and it feels a bit like pollution to add another "real" class just for this purpose.
return new IAttributeSetInstanceAware()
{
@Override
public I_M_Product getM_Product()
{
return Services.get(IOLCandEffectiveValuesBL.class).getM_Product_Effective(olCand);
}
@Override
public int getM_Product_ID()
{
final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class);
return ProductId.toRepoId(olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand));
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return olCand.getM_AttributeSetInstance();
} | @Override
public int getM_AttributeSetInstance_ID()
{
return olCand.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance(final I_M_AttributeSetInstance asi)
{
olCand.setM_AttributeSetInstance(asi);
}
@Override
public String toString()
{
return "IAttributeSetInstanceAware[" + olCand.toString() + "]";
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\OLCandASIAwareFactory.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_Language AD_Reference_ID=106
* Reference name: AD_Language
*/
public static final int AD_LANGUAGE_AD_Reference_ID=106;
@Override
public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public org.compiere.model.I_M_HazardSymbol getM_HazardSymbol()
{
return get_ValueAsPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class);
}
@Override | public void setM_HazardSymbol(final org.compiere.model.I_M_HazardSymbol M_HazardSymbol)
{
set_ValueFromPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class, M_HazardSymbol);
}
@Override
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID)
{
if (M_HazardSymbol_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID);
}
@Override
public int getM_HazardSymbol_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_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_HazardSymbol_Trl.java | 1 |
请完成以下Java代码 | public static List getRawList() {
List result = new ArrayList();
result.add("I am the 1st String.");
result.add("I am the 2nd String.");
result.add("I am the 3rd String.");
return result;
}
public static List getRawListWithMixedTypes() {
List result = new ArrayList();
result.add("I am the 1st String.");
result.add("I am the 2nd String.");
result.add("I am the 3rd String.");
result.add(new Date());
return result;
}
public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> rawCollection) { | List<T> result = new ArrayList<>(rawCollection.size());
for (Object o : rawCollection) {
try {
result.add(clazz.cast(o));
} catch (ClassCastException e) {
// log the exception or other error handling
}
}
return result;
}
public static <T> List<T> castList2(Class<? extends T> clazz, Collection<?> rawCollection) throws ClassCastException {
List<T> result = new ArrayList<>(rawCollection.size());
for (Object o : rawCollection) {
result.add(clazz.cast(o));
}
return result;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-generics-2\src\main\java\com\baeldung\uncheckedconversion\UncheckedConversion.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Currency getBase() {
return base;
}
public void setBase(Currency base) {
this.base = base;
} | public Map<String, BigDecimal> getRates() {
return rates;
}
public void setRates(Map<String, BigDecimal> rates) {
this.rates = rates;
}
@Override
public String toString() {
return "RateList{" +
"date=" + date +
", base=" + base +
", rates=" + rates +
'}';
}
} | repos\piggymetrics-master\statistics-service\src\main\java\com\piggymetrics\statistics\domain\ExchangeRatesContainer.java | 2 |
请完成以下Java代码 | public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = new Date(timestamp);
}
public String getName() {
return MetricsUtil.resolvePublicName(name);
}
public void setName(String name) {
this.name = name;
}
public String getReporter() {
return reporter;
}
public void setReporter(String reporter) {
this.reporter = reporter;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
@Override
public String getId() {
return name + reporter + timestamp.toString();
}
@Override
public void setId(String id) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getPersistentState() {
return MetricIntervalEntity.class; | }
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (this.timestamp != null ? this.timestamp.hashCode() : 0);
hash = 67 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 67 * hash + (this.reporter != null ? this.reporter.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MetricIntervalEntity other = (MetricIntervalEntity) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
if ((this.reporter == null) ? (other.reporter != null) : !this.reporter.equals(other.reporter)) {
return false;
}
if (this.timestamp != other.timestamp && (this.timestamp == null || !this.timestamp.equals(other.timestamp))) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MetricIntervalEntity.java | 1 |
请完成以下Java代码 | public void setToolTipText(String text)
{
// metas-tsa: we don't need to set Text from here, nor setting the mnemonic
super.setToolTipText(text);
// if (text == null) {
// super.setText(text);
// return;
// }
//
// int pos = text.indexOf('&');
// if (pos != -1) // We have a nemonic - creates ALT-_
// {
// int mnemonic = text.toUpperCase().charAt(pos + 1);
// if (mnemonic != ' ') {
// setMnemonic(mnemonic);
// text = text.substring(0, pos) + text.substring(pos + 1);
// }
// }
// super.setToolTipText(text);
// if (getName() == null)
// setName(text);
} // setToolTipText
/**
* Set Action Command
*
* @param actionCommand
* command
*/
@Override
public void setActionCommand(String actionCommand) {
super.setActionCommand(actionCommand);
if (getName() == null && actionCommand != null
&& actionCommand.length() > 0)
setName(actionCommand);
} // setActionCommand
// @formatter:off
// 08267: on german and swiss keyboards, this "CTRL+ALT" stuff also activates when the user presses '\'...which happens often in the file editor (VFile).
// The result is that if you press backslash in a process dialog's file editor, the dialog is canceled..explain that to the customer ;-).
// Note: see https://bugs.openjdk.java.net/browse/JDK-4274105 for the best background info I found so far
//
// /**
// * Overrides the JButton.setMnemonic() method, setting modifier keys to
// * CTRL+ALT.
// *
// * @param mnemonic | // * The mnemonic character code.
// */
// @Override
// public void setMnemonic(int mnemonic) {
// super.setMnemonic(mnemonic);
//
// InputMap map = SwingUtilities.getUIInputMap(this,
// JComponent.WHEN_IN_FOCUSED_WINDOW);
//
// if (map == null) {
// map = new ComponentInputMapUIResource(this);
// SwingUtilities.replaceUIInputMap(this,
// JComponent.WHEN_IN_FOCUSED_WINDOW, map);
// }
// map.clear();
//
// int mask = InputEvent.ALT_MASK + InputEvent.CTRL_MASK; // Default
// // Buttons
// map.put(KeyStroke.getKeyStroke(mnemonic, mask, false), "pressed");
// map.put(KeyStroke.getKeyStroke(mnemonic, mask, true), "released");
// map.put(KeyStroke.getKeyStroke(mnemonic, 0, true), "released");
// setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, map);
// } // setMnemonic
// @formatter:on
} // CButton | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CButton.java | 1 |
请完成以下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);
}
@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);
}
/**
* InvoicableQtyBasedOn AD_Reference_ID=541023
* Reference name: InvoicableQtyBasedOn
*/
public static final int INVOICABLEQTYBASEDON_AD_Reference_ID=541023;
/** Nominal = Nominal */
public static final String INVOICABLEQTYBASEDON_Nominal = "Nominal";
/** CatchWeight = CatchWeight */
public static final String INVOICABLEQTYBASEDON_CatchWeight = "CatchWeight";
@Override
public void setInvoicableQtyBasedOn (final java.lang.String InvoicableQtyBasedOn)
{
set_Value (COLUMNNAME_InvoicableQtyBasedOn, InvoicableQtyBasedOn);
}
@Override
public java.lang.String getInvoicableQtyBasedOn()
{
return get_ValueAsString(COLUMNNAME_InvoicableQtyBasedOn);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_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 setPriceList (final @Nullable BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
@Override
public BigDecimal getPriceList()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceList);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriceStd (final BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
@Override
public BigDecimal getPriceStd()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign_Price.java | 1 |
请完成以下Java代码 | public boolean isSingleShipper(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds)
{
return getShipperIds(shipmentScheduleIds).size() == 1;
}
public ImmutableSet<ShipperId> getShipperIds(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds)
{
return CollectionUtils.extractDistinctElements(shipmentScheduleService.getByIds(shipmentScheduleIds), ShipmentSchedule::getShipperId)
.stream()
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
public void requestCarrierAdvises(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds, final boolean isIncludeCarrierAdviseManual)
{
shipmentScheduleService.getByIds(shipmentScheduleIds)
.forEach(schedule -> requestCarrierAdvise(schedule, isIncludeCarrierAdviseManual));
}
public void requestCarrierAdvises(@NonNull final ShipmentScheduleQuery query)
{
shipmentScheduleService.getBy(query)
.forEach(schedule -> requestCarrierAdvise(schedule, false));
}
private void requestCarrierAdvise(@NonNull final ShipmentSchedule shipmentSchedule, final boolean isIncludeCarrierAdviseManual)
{
trxManager.runInThreadInheritedTrx(() -> {
if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(shipmentSchedule, isIncludeCarrierAdviseManual))
{
return;
}
shipmentSchedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Requested);
shipmentSchedule.setCarrierProductId(null); | shipmentScheduleService.save(shipmentSchedule);
});
}
public void updateEligibleShipmentSchedules(@NonNull final CarrierAdviseUpdateRequest request)
{
shipmentScheduleService.updateByQuery(request.getQuery(), schedule -> updateEligibleShipmentSchedule(schedule, request));
}
private void updateEligibleShipmentSchedule(@NonNull final ShipmentSchedule schedule, @NonNull final CarrierAdviseUpdateRequest request)
{
if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(schedule, request.isIncludeCarrierAdviseManual()))
{
return;
}
schedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Manual);
schedule.setCarrierProductId(request.getCarrierProductId());
schedule.setCarrierGoodsTypeId(request.getCarrierGoodsTypeId());
schedule.setCarrierServices(request.getCarrierServiceIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\process\CarrierAdviseProcessService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisConfig {
// redis缓存的有效时间单位是秒
@Value("${redis.default.expiration:3600}")
private long redisDefaultExpiration;
/**
* 重写Redis序列化方式,使用Json方式:
* 当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。
* Spring Data JPA为我们提供了下面的Serializer:
* GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。
* 在此我们将自己配置RedisTemplate并定义Serializer。
*
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// 全局开启AutoType,不建议使用
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
ParserConfig.getGlobalInstance().addAccept("com.xiaolyuh.");
// 设置值(value)的序列化采用FastJsonRedisSerializer。
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 重写RedisCacheManager的getCache方法,实现设置key的有效时间
* 重写RedisCache的get方法,实现触发式自动刷新
* <p> | * 自动刷新方案:
* 1、获取缓存后再获取一次有效时间,拿这个时间和我们配置的自动刷新时间比较,如果小于这个时间就刷新。
* 2、每次创建缓存的时候维护一个Map,存放key和方法信息(反射)。当要刷新缓存的时候,根据key获取方法信息。
* 通过获取其代理对象执行方法,刷新缓存。
*
* @param redisTemplate
* @return
*/
@Bean
public RedisCacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager redisCacheManager = new CustomizedRedisCacheManager(redisTemplate);
redisCacheManager.setUsePrefix(true);
//这里可以设置一个默认的过期时间 单位是秒
redisCacheManager.setDefaultExpiration(redisDefaultExpiration);
return redisCacheManager;
}
/**
* 显示声明缓存key生成器
*
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\config\RedisConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DeliveryOrderCreateRequest
{
Set<Integer> packageIds;
ShipperTransportationId shipperTransportationId;
ShipperGatewayId shipperGatewayId;
LocalDate pickupDate;
LocalTime timeFrom;
LocalTime timeTo;
AsyncBatchId asyncBatchId;
@Builder
public DeliveryOrderCreateRequest(
@NonNull final LocalDate pickupDate, | @NonNull @Singular final Set<Integer> packageIds,
final ShipperTransportationId shipperTransportationId,
@NonNull final ShipperGatewayId shipperGatewayId,
@Nullable final LocalTime timeFrom,
@Nullable final LocalTime timeTo,
@Nullable final AsyncBatchId asyncBatchId)
{
this.pickupDate = pickupDate;
this.packageIds = Check.assumeNotEmpty(packageIds, "packageIds is not empty");
this.shipperTransportationId = shipperTransportationId;
this.shipperGatewayId = shipperGatewayId;
this.timeFrom = CoalesceUtil.coalesceNotNull(timeFrom, LocalTime.MIN);
this.timeTo = CoalesceUtil.coalesceNotNull(timeTo, LocalTime.MAX);
this.asyncBatchId = asyncBatchId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\model\DeliveryOrderCreateRequest.java | 2 |
请完成以下Java代码 | public final Date getLatestDocumentDateOfSelectedRows()
{
Date latestDocumentDate = null;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final Date documentDate = row.getDocumentDate();
latestDocumentDate = TimeUtil.max(latestDocumentDate, documentDate);
}
return latestDocumentDate;
}
/**
* @return latest {@link IInvoiceCandidateRow#getDateAcct()} of selected rows
*/
public final Date getLatestDateAcctOfSelectedRows()
{
Date latestDateAcct = null;
for (final IInvoiceCandidateRow row : getRowsSelected())
{ | final Date dateAcct = row.getDateAcct();
latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct);
}
return latestDateAcct;
}
public final BigDecimal getTotalNetAmtToInvoiceOfSelectedRows()
{
BigDecimal totalNetAmtToInvoiced = BigDecimal.ZERO;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final BigDecimal netAmtToInvoice = row.getNetAmtToInvoice();
totalNetAmtToInvoiced = totalNetAmtToInvoiced.add(netAmtToInvoice);
}
return totalNetAmtToInvoiced;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidatesTableModel.java | 1 |
请完成以下Java代码 | public String serialize(EventInstance eventInstance) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement(eventInstance.getEventKey());
doc.appendChild(rootElement);
if (!eventInstance.getPayloadInstances().isEmpty()) {
for (EventPayloadInstance payloadInstance : eventInstance.getPayloadInstances()) {
if (!payloadInstance.getEventPayloadDefinition().isNotForBody()) {
Element element = doc.createElement(payloadInstance.getDefinitionName());
element.setTextContent(payloadInstance.getValue().toString());
rootElement.appendChild(element);
} | }
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.toString();
} catch (Exception e) {
throw new FlowableException("XML serialization failed for " + eventInstance, e);
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\serialization\EventPayloadToXmlStringSerializer.java | 1 |
请完成以下Java代码 | public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
@Override
public void setMovementQty (final BigDecimal MovementQty)
{
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
@Override
public BigDecimal getMovementQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MovementQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerLU (final @Nullable BigDecimal QtyCUsPerLU)
{
set_Value (COLUMNNAME_QtyCUsPerLU, QtyCUsPerLU);
}
@Override
public BigDecimal getQtyCUsPerLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerLU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerLU_InInvoiceUOM)
{
set_Value (COLUMNNAME_QtyCUsPerLU_InInvoiceUOM, QtyCUsPerLU_InInvoiceUOM);
}
@Override
public BigDecimal getQtyCUsPerLU_InInvoiceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU_InInvoiceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerTU (final @Nullable BigDecimal QtyCUsPerTU)
{
set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU);
}
@Override
public BigDecimal getQtyCUsPerTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerTU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerTU_InInvoiceUOM)
{
set_Value (COLUMNNAME_QtyCUsPerTU_InInvoiceUOM, QtyCUsPerTU_InInvoiceUOM);
} | @Override
public BigDecimal getQtyCUsPerTU_InInvoiceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU_InInvoiceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity)
{
set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity);
}
@Override
public BigDecimal getQtyItemCapacity()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final int QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public int getQtyTU()
{
return get_ValueAsInt(COLUMNNAME_QtyTU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack_Item.java | 1 |
请完成以下Java代码 | public org.eevolution.model.I_HR_Payroll getHR_Payroll() throws RuntimeException
{
return (org.eevolution.model.I_HR_Payroll)MTable.get(getCtx(), org.eevolution.model.I_HR_Payroll.Table_Name)
.getPO(getHR_Payroll_ID(), get_TrxName()); }
/** Set Payroll.
@param HR_Payroll_ID Payroll */
public void setHR_Payroll_ID (int HR_Payroll_ID)
{
if (HR_Payroll_ID < 1)
set_Value (COLUMNNAME_HR_Payroll_ID, null);
else
set_Value (COLUMNNAME_HR_Payroll_ID, Integer.valueOf(HR_Payroll_ID));
}
/** Get Payroll.
@return Payroll */
public int getHR_Payroll_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Employee.
@param IsEmployee
Indicates if this Business Partner is an employee
*/
public void setIsEmployee (boolean IsEmployee)
{
set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee));
}
/** Get Employee.
@return Indicates if this Business Partner is an employee
*/
public boolean isEmployee ()
{
Object oo = get_Value(COLUMNNAME_IsEmployee);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{ | return new KeyNamePair(get_ID(), getName());
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_List.java | 1 |
请完成以下Java代码 | public ActivityInstance getActivityInstanceTree(final CommandContext commandContext) {
return commandContext.runWithoutAuthorization(new GetActivityInstanceCmd(processInstanceId));
}
public String getActivityId() {
return activityId;
}
public void setActivityInstanceTreeToCancel(ActivityInstance activityInstanceTreeToCancel) {
this.activityInstanceTree = activityInstanceTreeToCancel;
}
@Override
protected String describe() {
return "Cancel all instances of activity '" + activityId + "'";
}
public List<AbstractInstanceCancellationCmd> createActivityInstanceCancellations(ActivityInstance activityInstanceTree, CommandContext commandContext) {
List<AbstractInstanceCancellationCmd> commands = new ArrayList<AbstractInstanceCancellationCmd>();
ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId);
ProcessDefinitionImpl processDefinition = processInstance.getProcessDefinition();
Set<String> parentScopeIds = collectParentScopeIdsForActivity(processDefinition, activityId);
List<ActivityInstance> childrenForActivity = getActivityInstancesForActivity(activityInstanceTree, parentScopeIds);
for (ActivityInstance instance : childrenForActivity) {
commands.add(new ActivityInstanceCancellationCmd(processInstanceId, instance.getId()));
} | List<TransitionInstance> transitionInstancesForActivity = getTransitionInstancesForActivity(activityInstanceTree, parentScopeIds);
for (TransitionInstance instance : transitionInstancesForActivity) {
commands.add(new TransitionInstanceCancellationCmd(processInstanceId, instance.getId()));
}
return commands;
}
public boolean isCancelCurrentActiveActivityInstances() {
return cancelCurrentActiveActivityInstances;
}
public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) {
this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ActivityCancellationCmd.java | 1 |
请完成以下Java代码 | public String getDatabaseTablePrefix() {
return databaseTablePrefix;
}
public String getDatabaseCatalog() {
return databaseCatalog;
}
public void setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog;
}
public String getDatabaseSchema() {
return databaseSchema;
}
public void setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
}
public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) {
this.tablePrefixIsSchema = tablePrefixIsSchema;
}
public boolean isTablePrefixIsSchema() {
return tablePrefixIsSchema;
}
public List<Class<? extends Entity>> getInsertionOrder() {
return insertionOrder;
}
public void setInsertionOrder(List<Class<? extends Entity>> insertionOrder) {
this.insertionOrder = insertionOrder;
}
public List<Class<? extends Entity>> getDeletionOrder() {
return deletionOrder;
}
public void setDeletionOrder(List<Class<? extends Entity>> deletionOrder) {
this.deletionOrder = deletionOrder;
}
public Collection<Class<? extends Entity>> getImmutableEntities() { | return immutableEntities;
}
public void setImmutableEntities(Collection<Class<? extends Entity>> immutableEntities) {
this.immutableEntities = immutableEntities;
}
public void addLogicalEntityClassMapping(String logicalName, Class<?> entityClass) {
logicalNameToClassMapping.put(logicalName, entityClass);
}
public Map<String, Class<?>> getLogicalNameToClassMapping() {
return logicalNameToClassMapping;
}
public void setLogicalNameToClassMapping(Map<String, Class<?>> logicalNameToClassMapping) {
this.logicalNameToClassMapping = logicalNameToClassMapping;
}
public boolean isUsePrefixId() {
return usePrefixId;
}
public void setUsePrefixId(boolean usePrefixId) {
this.usePrefixId = usePrefixId;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\DbSqlSessionFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean isCarrierCompatible(
@NonNull final Workplace workplace,
@NonNull final ShipmentSchedule schedule)
{
final ImmutableSet<CarrierProductId> workplaceCarrierProducts = workplace.getCarrierProductIds();
if (workplaceCarrierProducts.isEmpty())
{
return true;
}
final CarrierProductId carrierProductId = schedule.getCarrierProductId();
if (carrierProductId == null)
{
return false;
}
return workplaceCarrierProducts.contains(carrierProductId);
}
private boolean isExternalSystemCompatible(
@NonNull final Workplace workplace,
@NonNull final ShipmentSchedule schedule)
{
final ImmutableSet<ExternalSystemId> workplaceExternalSystems = workplace.getExternalSystemIds();
if (workplaceExternalSystems.isEmpty())
{
return true;
}
final ExternalSystemId externalSystemId = schedule.getExternalSystemId();
if (externalSystemId == null)
{
return false;
} | return workplaceExternalSystems.contains(externalSystemId);
}
private boolean isPriorityCompatible(
@NonNull final Workplace workplace,
@NonNull final ShipmentSchedule schedule)
{
final PriorityRule priorityRule = workplace.getPriorityRule();
if (priorityRule == null)
{
return true;
}
return PriorityRule.equals(priorityRule, schedule.getPriorityRule());
}
private static class WorkplacesCapacity
{
private final Map<WorkplaceId, Integer> assignedCountPerWorkplace = new HashMap<>();
void increase(@NonNull final WorkplaceId workplaceId)
{
assignedCountPerWorkplace.merge(workplaceId, 1, Integer::sum);
}
boolean hasCapacity(@NonNull final Workplace workplace)
{
final int currentAssigned = assignedCountPerWorkplace.getOrDefault(workplace.getId(), 0);
return currentAssigned < workplace.getMaxPickingJobs();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job_schedule\service\commands\PickingJobScheduleAutoAssignCommand.java | 2 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Set Start Count Impression.
@param StartImpression
For rotation we need a start count
*/
public void setStartImpression (int StartImpression)
{
set_Value (COLUMNNAME_StartImpression, Integer.valueOf(StartImpression));
}
/** Get Start Count Impression.
@return For rotation we need a start count
*/
public int getStartImpression ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartImpression); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Target Frame.
@param Target_Frame
Which target should be used if user clicks?
*/
public void setTarget_Frame (String Target_Frame)
{
set_Value (COLUMNNAME_Target_Frame, Target_Frame);
}
/** Get Target Frame.
@return Which target should be used if user clicks?
*/
public String getTarget_Frame ()
{
return (String)get_Value(COLUMNNAME_Target_Frame);
}
/** Set Target URL.
@param TargetURL
URL for the Target
*/
public void setTargetURL (String TargetURL)
{
set_Value (COLUMNNAME_TargetURL, TargetURL);
}
/** Get Target URL.
@return URL for the Target
*/
public String getTargetURL ()
{
return (String)get_Value(COLUMNNAME_TargetURL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Ad.java | 1 |
请完成以下Java代码 | public boolean isEmpty() {
return getVariablesMap().isEmpty();
}
public boolean containsValue(T value) {
return getVariablesMap().containsValue(value);
}
public boolean containsKey(String key) {
return getVariablesMap().containsKey(key);
}
public Set<String> getKeys() {
return new HashSet<>(getVariablesMap().keySet());
}
public boolean isInitialized() {
return variables != null;
}
public void forceInitialization() {
if (!isInitialized()) {
variables = new HashMap<>();
for (T variable : variablesProvider.provideVariables()) {
variables.put(variable.getName(), variable);
}
}
}
public T removeVariable(String variableName) {
if (!getVariablesMap().containsKey(variableName)) {
return null;
}
T value = getVariablesMap().remove(variableName);
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(value);
}
removedVariables.put(variableName, value);
return value;
}
public void removeVariables() {
Iterator<T> valuesIt = getVariablesMap().values().iterator();
removedVariables.putAll(variables);
while (valuesIt.hasNext()) {
T nextVariable = valuesIt.next();
valuesIt.remove();
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(nextVariable);
} | }
}
public void addObserver(VariableStoreObserver<T> observer) {
observers.add(observer);
}
public void removeObserver(VariableStoreObserver<T> observer) {
observers.remove(observer);
}
public static interface VariableStoreObserver<T extends CoreVariableInstance> {
void onAdd(T variable);
void onRemove(T variable);
}
public static interface VariablesProvider<T extends CoreVariableInstance> {
Collection<T> provideVariables();
Collection<T> provideVariables(Collection<String> variableNames);
}
public boolean isRemoved(String variableName) {
return removedVariables.containsKey(variableName);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableStore.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookReview {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_reviews_reviews_id_seq")
@SequenceGenerator(name = "book_reviews_reviews_id_seq", sequenceName = "book_reviews_reviews_id_seq", allocationSize = 1)
private Long reviewsId;
private String userId;
private String isbn;
private String bookRating;
public Long getReviewsId() {
return reviewsId;
}
public void setReviewsId(Long reviewsId) {
this.reviewsId = reviewsId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) { | this.userId = userId;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getBookRating() {
return bookRating;
}
public void setBookRating(String bookRating) {
this.bookRating = bookRating;
}
@Override
public String toString() {
return "BookReview{" + "reviewsId=" + reviewsId + ", userId='" + userId + '\'' + ", isbn='" + isbn + '\'' + ", bookRating='" + bookRating + '\'' + '}';
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\scrollapi\entity\BookReview.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_M_DiscountSchema getM_DiscountSchema()
{
return get_ValueAsPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class);
}
@Override
public void setM_DiscountSchema(final org.compiere.model.I_M_DiscountSchema M_DiscountSchema)
{
set_ValueFromPO(COLUMNNAME_M_DiscountSchema_ID, org.compiere.model.I_M_DiscountSchema.class, M_DiscountSchema);
}
@Override
public void setM_DiscountSchema_ID (final int M_DiscountSchema_ID)
{
if (M_DiscountSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_ID, M_DiscountSchema_ID);
}
@Override
public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setM_DiscountSchemaBreak_V_ID (final int M_DiscountSchemaBreak_V_ID)
{ | if (M_DiscountSchemaBreak_V_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchemaBreak_V_ID, M_DiscountSchemaBreak_V_ID);
}
@Override
public int getM_DiscountSchemaBreak_V_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchemaBreak_V_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchemaBreak_V.java | 1 |
请完成以下Java代码 | public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTextMsg (final java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
@Override
public java.lang.String getTextMsg()
{
return get_ValueAsString(COLUMNNAME_TextMsg);
}
@Override
public void setWF_Initial_User_ID (final int WF_Initial_User_ID)
{
if (WF_Initial_User_ID < 1)
set_Value (COLUMNNAME_WF_Initial_User_ID, null);
else
set_Value (COLUMNNAME_WF_Initial_User_ID, WF_Initial_User_ID);
}
@Override
public int getWF_Initial_User_ID()
{
return get_ValueAsInt(COLUMNNAME_WF_Initial_User_ID);
}
/**
* WFState AD_Reference_ID=305
* Reference name: WF_Instance State | */
public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */
public static final String WFSTATE_NotStarted = "ON";
/** Running = OR */
public static final String WFSTATE_Running = "OR";
/** Suspended = OS */
public static final String WFSTATE_Suspended = "OS";
/** Completed = CC */
public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */
public static final String WFSTATE_Aborted = "CA";
/** Terminated = CT */
public static final String WFSTATE_Terminated = "CT";
@Override
public void setWFState (final java.lang.String WFState)
{
set_Value (COLUMNNAME_WFState, WFState);
}
@Override
public java.lang.String getWFState()
{
return get_ValueAsString(COLUMNNAME_WFState);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Process.java | 1 |
请完成以下Java代码 | static final Date findMinDateOfWithComparator(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(Event::getDate)
.min(Comparator.naturalOrder())
.get();
}
static final LocalDate findMaxDateOfLocalEvents(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(LocalEvent::getDate)
.max(LocalDate::compareTo)
.get();
}
static final LocalDate findMaxDateOfLocalEventsWithComparator(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(LocalEvent::getDate)
.max(Comparator.naturalOrder())
.get();
}
static final LocalDate findMinDateOfLocalEvents(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream()
.map(LocalEvent::getDate)
.min(LocalDate::compareTo)
.get();
}
static final LocalDate findMinDateOfLocalEventsWithComparator(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return events.stream() | .map(LocalEvent::getDate)
.min(Comparator.naturalOrder())
.get();
}
static Date findMaxDateWithCollections(List<Event> events) {
if (events == null || events.isEmpty()) {
return null;
}
return Collections.max(events.stream()
.map(Event::getDate)
.collect(Collectors.toList()));
}
static LocalDate findMaxLocalDateWithCollections(List<LocalEvent> events) {
if (events == null || events.isEmpty()) {
return null;
}
return Collections.max(events.stream()
.map(LocalEvent::getDate)
.collect(Collectors.toList()));
}
} | repos\tutorials-master\core-java-modules\core-java-streams-4\src\main\java\com\baeldung\streams\maxdate\DateHelper.java | 1 |
请完成以下Java代码 | protected void doAuthCheck(CommandContext commandContext) {
// since a report does only make sense in context of historic
// data, the authorization check will be performed here
for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
if (processDefinitionIdIn == null && processDefinitionKeyIn == null) {
checker.checkReadHistoryAnyProcessDefinition();
} else {
List<String> processDefinitionKeys = new ArrayList<String>();
if (processDefinitionKeyIn != null) {
processDefinitionKeys.addAll(Arrays.asList(processDefinitionKeyIn));
}
if (processDefinitionIdIn != null) {
for (String processDefinitionId : processDefinitionIdIn) {
ProcessDefinition processDefinition = commandContext.getProcessDefinitionManager()
.findLatestProcessDefinitionById(processDefinitionId);
if (processDefinition != null && processDefinition.getKey() != null) {
processDefinitionKeys.add(processDefinition.getKey());
}
}
}
if (!processDefinitionKeys.isEmpty()) {
for (String processDefinitionKey : processDefinitionKeys) {
checker.checkReadHistoryProcessDefinition(processDefinitionKey);
}
}
}
}
}
// getter //////////////////////////////////////////////////////
public Date getStartedAfter() {
return startedAfter;
}
public Date getStartedBefore() {
return startedBefore;
}
public String[] getProcessDefinitionIdIn() {
return processDefinitionIdIn; | }
public String[] getProcessDefinitionKeyIn() {
return processDefinitionKeyIn;
}
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public String getReportPeriodUnitName() {
return durationPeriodUnit.name();
}
protected class ExecuteDurationReportCmd implements Command<List<DurationReportResult>> {
@Override
public List<DurationReportResult> execute(CommandContext commandContext) {
return executeDurationReport(commandContext);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricProcessInstanceReportImpl.java | 1 |
请完成以下Java代码 | protected void onAfterInit()
{
if (!isEnabled())
{
return;
}
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
huTrxBL.addListener(TraceHUTrxListener.INSTANCE);
}
/**
* Allow the {@link HUTraceEventsService} to be set from outside. Goal: allow testing without the need to fire up the spring-boot test runner.
*
* @param huTraceEventsService
*/
@VisibleForTesting
public void setHUTraceEventsService(@NonNull final HUTraceEventsService huTraceEventsService)
{
this.huTraceEventsService = huTraceEventsService;
}
public HUTraceEventsService getHUTraceEventsService()
{
if (huTraceEventsService != null)
{
return huTraceEventsService; | }
return Adempiere.getBean(HUTraceEventsService.class);
}
/**
* Uses {@link ISysConfigBL} to check if tracing shall be enabled. Note that the default value is false,
* because we don't want this to fire in <i>"unit"</i> tests by default.
* If you want to test against this feature, you can explicitly enable it for your test.
*
* @return
*/
public boolean isEnabled()
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
final boolean enabled = sysConfigBL.getBooleanValue(SYSCONFIG_ENABLED, false, Env.getAD_Client_ID(Env.getCtx()), Env.getAD_Org_ID(Env.getCtx()));
return enabled;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\interceptor\HUTraceModuleInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getRevision() {
return revision;
}
public void setRevision(Integer revision) {
this.revision = revision;
}
public RestVariable getVariable() {
return variable;
}
public void setVariable(RestVariable variable) {
this.variable = variable;
}
@ApiModelProperty(example = "null") | public String getPropertyId() {
return propertyId;
}
public void setPropertyId(String propertyId) {
this.propertyId = propertyId;
}
@ApiModelProperty(example = "null")
public String getPropertyValue() {
return propertyValue;
}
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java | 2 |
请完成以下Java代码 | public de.metas.handlingunits.model.I_M_ShipmentSchedule retrieveM_ShipmentScheduleOrNull(@NonNull final I_EDI_DesadvLine desadvLine)
{
final IQueryBuilder<I_C_OrderLine> orderLinesQuery = createAllOrderLinesQuery(desadvLine);
final IQueryBuilder<I_M_ShipmentSchedule> queryBuilder = orderLinesQuery
.andCollectChildren(I_M_ShipmentSchedule.COLUMN_C_OrderLine_ID, I_M_ShipmentSchedule.class);
queryBuilder.orderBy()
.addColumn(I_M_ShipmentSchedule.COLUMN_M_ShipmentSchedule_ID);
return queryBuilder.create().first(de.metas.handlingunits.model.I_M_ShipmentSchedule.class);
}
@Override
public BigDecimal retrieveMinimumSumPercentage()
{
final String minimumPercentageAccepted_Value = sysConfigBL.getValue(
SYS_CONFIG_DefaultMinimumPercentage, SYS_CONFIG_DefaultMinimumPercentage_DEFAULT);
try
{
return new BigDecimal(minimumPercentageAccepted_Value);
}
catch (final NumberFormatException e)
{
Check.errorIf(true, "AD_SysConfig {} = {} can't be parsed as a number", SYS_CONFIG_DefaultMinimumPercentage, minimumPercentageAccepted_Value);
return null; // shall not be reached
}
}
@Override
public void save(@NonNull final I_EDI_Desadv ediDesadv)
{
InterfaceWrapperHelper.save(ediDesadv);
} | @Override
public void save(@NonNull final I_EDI_DesadvLine ediDesadvLine)
{
InterfaceWrapperHelper.save(ediDesadvLine);
}
@Override
@NonNull
public List<I_M_InOut> retrieveShipmentsWithStatus(@NonNull final I_EDI_Desadv desadv, @NonNull final ImmutableSet<EDIExportStatus> statusSet)
{
return queryBL.createQueryBuilder(I_M_InOut.class, desadv)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut.COLUMNNAME_EDI_Desadv_ID, desadv.getEDI_Desadv_ID())
.addInArrayFilter(I_M_InOut.COLUMNNAME_EDI_ExportStatus, statusSet)
.create()
.list(I_M_InOut.class);
}
@Override
@NonNull
public I_M_InOut_Desadv_V getInOutDesadvByInOutId(@NonNull final InOutId shipmentId)
{
return queryBL.createQueryBuilder(I_M_InOut_Desadv_V.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut_Desadv_V.COLUMNNAME_M_InOut_ID, shipmentId)
.create()
.firstOnlyNotNull(I_M_InOut_Desadv_V.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\DesadvDAO.java | 1 |
请完成以下Java代码 | public static ApiResponse ofStatus(Status status) {
return ofStatus(status, null);
}
/**
* 构造一个有状态且带数据的API返回
*
* @param status 状态 {@link Status}
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse ofStatus(Status status, Object data) {
return of(status.getCode(), status.getMessage(), data);
}
/**
* 构造一个异常且带数据的API返回
*
* @param t 异常
* @param data 返回数据
* @param <T> {@link BaseException} 的子类 | * @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t, Object data) {
return of(t.getCode(), t.getMessage(), data);
}
/**
* 构造一个异常且带数据的API返回
*
* @param t 异常
* @param <T> {@link BaseException} 的子类
* @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t) {
return ofException(t, null);
}
} | repos\spring-boot-demo-master\demo-exception-handler\src\main\java\com\xkcoding\exception\handler\model\ApiResponse.java | 1 |
请完成以下Java代码 | public int getM_LU_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_LU_HU_PI_Item_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 de.metas.handlingunits.model.I_M_HU_PI getM_TU_HU_PI()
{
return get_ValueAsPO(COLUMNNAME_M_TU_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class);
}
@Override
public void setM_TU_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_TU_HU_PI)
{
set_ValueFromPO(COLUMNNAME_M_TU_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_TU_HU_PI);
}
@Override
public void setM_TU_HU_PI_ID (final int M_TU_HU_PI_ID)
{
if (M_TU_HU_PI_ID < 1)
set_Value (COLUMNNAME_M_TU_HU_PI_ID, null);
else
set_Value (COLUMNNAME_M_TU_HU_PI_ID, M_TU_HU_PI_ID);
}
@Override
public int getM_TU_HU_PI_ID()
{
return get_ValueAsInt(COLUMNNAME_M_TU_HU_PI_ID);
}
@Override
public void setQtyCUsPerTU (final BigDecimal QtyCUsPerTU) | {
set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU);
}
@Override
public BigDecimal getQtyCUsPerTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyLU (final BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
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_HU_LUTU_Configuration.java | 1 |
请完成以下Java代码 | public class RewritePathGatewayFilterFactory
extends AbstractGatewayFilterFactory<RewritePathGatewayFilterFactory.Config> {
/**
* Regexp key.
*/
public static final String REGEXP_KEY = "regexp";
/**
* Replacement key.
*/
public static final String REPLACEMENT_KEY = "replacement";
public RewritePathGatewayFilterFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(REGEXP_KEY, REPLACEMENT_KEY);
}
@Override
public GatewayFilter apply(Config config) {
String replacementValue = Objects.requireNonNull(config.replacement, "replacement must not be null");
String replacement = replacementValue.replace("$\\", "$");
String regexpValue = Objects.requireNonNull(config.regexp, "regexp must not be null");
Pattern pattern = Pattern.compile(regexpValue);
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest req = exchange.getRequest();
addOriginalRequestUrl(exchange, req.getURI());
String path = req.getURI().getRawPath();
String newPath = pattern.matcher(path).replaceAll(replacement);
ServerHttpRequest request = req.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
return chain.filter(exchange.mutate().request(request).build()); | }
@Override
public String toString() {
String regexp = config.getRegexp();
return filterToStringCreator(RewritePathGatewayFilterFactory.this)
.append(regexp != null ? regexp : "", replacement)
.toString();
}
};
}
public static class Config {
private @Nullable String regexp;
private @Nullable String replacement;
public @Nullable String getRegexp() {
return regexp;
}
public Config setRegexp(String regexp) {
Assert.hasText(regexp, "regexp must have a value");
this.regexp = regexp;
return this;
}
public @Nullable String getReplacement() {
return replacement;
}
public Config setReplacement(String replacement) {
Objects.requireNonNull(replacement, "replacement must not be null");
this.replacement = replacement;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewritePathGatewayFilterFactory.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final I_C_BPartner partner = getRecord(I_C_BPartner.class);
partner.setIsPharmaAgentPermission(p_IsPharmaAgentPermission);
partner.setIsPharmaciePermission(p_IsPharmaciePermission);
partner.setIsPharmaManufacturerPermission(p_IsPharmaManufacturerPermission);
partner.setIsPharmaWholesalePermission(p_IsPharmaWholesalePermission);
partner.setIsVeterinaryPharmacyPermission(p_IsVeterinaryPharmacyPermission);
partner.setIsPharmaCustomerNarcoticsPermission(p_IsPharmaCustomerNarcoticsPermission);
save(partner);
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection()) | {
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final I_C_BPartner partner = context.getSelectedModel(I_C_BPartner.class);
if (!partner.isCustomer())
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText("OnlyCustomers"));
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pharma\process\WEBUI_C_BPartner_UpdateCustomerPharmaPermissions.java | 1 |
请完成以下Java代码 | public LicenseKeyDataImpl getLicenseKey() {
return licenseKey;
}
public void setLicenseKey(LicenseKeyDataImpl licenseKey) {
this.licenseKey = licenseKey;
}
public synchronized Set<String> getWebapps() {
return webapps;
}
public synchronized void setWebapps(Set<String> webapps) {
this.webapps = webapps;
}
public void markOccurrence(String name) {
markOccurrence(name, 1);
}
public void markOccurrence(String name, long times) {
CommandCounter counter = commands.get(name);
if (counter == null) {
synchronized (commands) {
if (counter == null) {
counter = new CommandCounter(name); | commands.put(name, counter);
}
}
}
counter.mark(times);
}
public synchronized void addWebapp(String webapp) {
if (!webapps.contains(webapp)) {
webapps.add(webapp);
}
}
public void clearCommandCounts() {
commands.clear();
}
public void clear() {
commands.clear();
licenseKey = null;
applicationServer = null;
webapps.clear();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsRegistry.java | 1 |
请完成以下Java代码 | public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public double getPrice() {
return price;
} | public void setPrice(double price) {
this.price = price;
}
@Transient
public double getDiscounted() {
return discounted;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn="
+ isbn + ", price=" + price + ", discounted=" + discounted + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootCalculatePropertyFormula\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public void setQtyReceived (java.math.BigDecimal QtyReceived)
{
throw new IllegalArgumentException ("QtyReceived is virtual column"); }
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null); | else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\model\X_M_Material_Tracking_Ref.java | 1 |
请完成以下Java代码 | protected Deployment desired(DeptrackResource primary, Context<DeptrackResource> context) {
ObjectMeta meta = fromPrimary(primary,COMPONENT)
.build();
return new DeploymentBuilder(template)
.withMetadata(meta)
.withSpec(buildSpec(primary, meta))
.build();
}
private DeploymentSpec buildSpec(DeptrackResource primary, ObjectMeta primaryMeta) {
return new DeploymentSpecBuilder()
.withSelector(buildSelector(primaryMeta.getLabels()))
.withReplicas(1) // Dependenty track does not support multiple pods (yet)
.withTemplate(buildPodTemplate(primary,primaryMeta))
.build();
}
private LabelSelector buildSelector(Map<String, String> labels) {
return new LabelSelectorBuilder()
.addToMatchLabels(labels)
.build();
}
private PodTemplateSpec buildPodTemplate(DeptrackResource primary, ObjectMeta primaryMeta) {
return new PodTemplateSpecBuilder()
.withMetadata(primaryMeta)
.withSpec(buildPodSpec(primary))
.build();
}
private PodSpec buildPodSpec(DeptrackResource primary) {
// Check for version override
String imageVersion = StringUtils.hasText(primary.getSpec().getApiServerVersion())?
":" + primary.getSpec().getApiServerVersion().trim():"";
// Check for image override | String imageName = StringUtils.hasText(primary.getSpec().getApiServerImage())?
primary.getSpec().getApiServerImage().trim(): Constants.DEFAULT_API_SERVER_IMAGE;
//@formatter:off
return new PodSpecBuilder(template.getSpec().getTemplate().getSpec())
.editContainer(0) // Assumes we have a single container
.withImage(imageName + imageVersion)
.and()
.build();
//@formatter:on
}
static class Discriminator extends ResourceIDMatcherDiscriminator<Deployment,DeptrackResource> {
public Discriminator() {
super(COMPONENT, (p) -> new ResourceID(p.getMetadata()
.getName() + "-" + COMPONENT, p.getMetadata()
.getNamespace()));
}
}
} | repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackApiServerDeploymentResource.java | 1 |
请完成以下Java代码 | public BigInteger getRequestTimestamp() {
return requestTimestamp;
}
/**
* Sets the value of the requestTimestamp property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setRequestTimestamp(BigInteger value) {
this.requestTimestamp = value;
}
/**
* Gets the value of the requestDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getRequestDate() {
return requestDate;
}
/**
* Sets the value of the requestDate property.
*
* @param value | * allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setRequestDate(XMLGregorianCalendar value) {
this.requestDate = value;
}
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestId(String value) {
this.requestId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CreditType.java | 1 |
请完成以下Java代码 | public List<JobDto> findCleanupJobs() {
List<Job> jobs = processEngine.getHistoryService().findHistoryCleanupJobs();
if (jobs == null || jobs.isEmpty()) {
throw new RestException(Status.NOT_FOUND, "History cleanup jobs are empty");
}
List<JobDto> dtos = new ArrayList<JobDto>();
for (Job job : jobs) {
JobDto dto = JobDto.fromJob(job);
dtos.add(dto);
}
return dtos;
}
public HistoryCleanupConfigurationDto getHistoryCleanupConfiguration() {
ProcessEngineConfigurationImpl engineConfiguration =
(ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); | HistoryCleanupConfigurationDto configurationDto = new HistoryCleanupConfigurationDto();
configurationDto.setEnabled(engineConfiguration.isHistoryCleanupEnabled());
BatchWindow batchWindow = engineConfiguration.getBatchWindowManager()
.getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), engineConfiguration);
if (batchWindow != null) {
configurationDto.setBatchWindowStartTime(batchWindow.getStart());
configurationDto.setBatchWindowEndTime(batchWindow.getEnd());
}
return configurationDto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoryCleanupRestServiceImpl.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Expense.
@param Expense Expense */
public void setExpense (BigDecimal Expense)
{
set_Value (COLUMNNAME_Expense, Expense);
}
/** Get Expense.
@return Expense */
public BigDecimal getExpense ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Expense);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Depreciate.
@param IsDepreciated
The asset will be depreciated
*/
public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Exp.java | 1 |
请完成以下Java代码 | public void processChanges(final List<JSONDocumentChangedEvent> events)
{
throw new UnsupportedOperationException();
}
@Override
public LookupValuesList getAttributeTypeahead(final String attributeName, final String query)
{
throw new UnsupportedOperationException();
// return asiDoc.getFieldLookupValuesForQuery(attributeName, query);
}
@Override
public LookupValuesList getAttributeDropdown(final String attributeName)
{
throw new UnsupportedOperationException();
// return asiDoc.getFieldLookupValues(attributeName);
}
@Override
public JSONViewRowAttributes toJson(final JSONOptions jsonOpts)
{
final JSONViewRowAttributes jsonDocument = new JSONViewRowAttributes(documentPath);
final List<JSONDocumentField> jsonFields = asiDoc.getFieldViews()
.stream() | .map(field -> toJSONDocumentField(field, jsonOpts))
.collect(Collectors.toList());
jsonDocument.setFields(jsonFields);
return jsonDocument;
}
private JSONDocumentField toJSONDocumentField(final IDocumentFieldView field, final JSONOptions jsonOpts)
{
final String fieldName = field.getFieldName();
final Object jsonValue = field.getValueAsJsonObject(jsonOpts);
final DocumentFieldWidgetType widgetType = field.getWidgetType();
return JSONDocumentField.ofNameAndValue(fieldName, jsonValue)
.setDisplayed(true)
.setMandatory(false)
.setReadonly(true)
.setWidgetType(JSONLayoutWidgetType.fromNullable(widgetType));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ASIViewRowAttributes.java | 1 |
请完成以下Java代码 | public class BulkOperations {
private static MongoClient mongoClient;
private static MongoDatabase database;
private static MongoCollection<Document> collection;
private static String testCollectionName;
private static String databaseName;
public static void setUp() {
databaseName = "baeldung";
testCollectionName = "populations";
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
database = mongoClient.getDatabase(databaseName);
collection = database.getCollection(testCollectionName);
}
}
public static void bulkOperations() {
List<WriteModel<Document>> writeOperations = new ArrayList<WriteModel<Document>>();
writeOperations.add(new InsertOneModel<Document>(new Document("cityId", 1128).append("cityName", "Kathmandu")
.append("countryName", "Nepal")
.append("continentName", "Asia")
.append("population", 12)));
writeOperations.add(new InsertOneModel<Document>(new Document("cityId", 1130).append("cityName", "Mumbai")
.append("countryName", "India")
.append("continentName", "Asia")
.append("population", 55)));
writeOperations.add(new UpdateOneModel<Document>(new Document("cityName", "New Delhi"), // filter to update document
new Document("$set", new Document("status", "High Population")) // update
));
writeOperations.add(new UpdateManyModel<Document>(new Document("cityName", "London"), // filter to update multiple documents
new Document("$set", new Document("status", "Low Population")) // update
));
writeOperations.add(new DeleteOneModel<Document>(new Document("cityName", "Mexico City")));
writeOperations.add(new ReplaceOneModel<Document>(new Document("cityName", "New York"), new Document("cityId", 1124).append("cityName", "New York") | .append("countryName", "United States")
.append("continentName", "North America")
.append("population", 28)));
BulkWriteResult bulkWriteResult = collection.bulkWrite(writeOperations);
System.out.println("bulkWriteResult:- " + bulkWriteResult);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Bulk operations
//
bulkOperations();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\BulkOperations.java | 1 |
请完成以下Java代码 | public class StudentV2 extends StudentV1 {
@Expose
private String firstName;
@Expose
private String lastName;
@Expose
private String major;
@Override
public String getFirstName() {
return firstName;
}
@Override
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String getLastName() {
return lastName;
}
@Override
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMajor() {
return major; | }
public void setMajor(String major) {
this.major = major;
}
// Default constructor for Gson
public StudentV2() {
}
public StudentV2(String firstName, String lastName, String major) {
this.firstName = firstName;
this.lastName = lastName;
this.major = major;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StudentV2))
return false;
StudentV2 studentV2 = (StudentV2) o;
return Objects.equals(firstName, studentV2.firstName) && Objects.equals(lastName, studentV2.lastName) && Objects.equals(major, studentV2.major);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, major);
}
} | repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\multiplefields\StudentV2.java | 1 |
请完成以下Java代码 | public class TruncateString {
private static final String EMPTY = "";
public static String usingSubstringMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
if (text.length() <= length) {
return text;
} else {
return text.substring(0, length);
}
}
public static String usingSplitMethod(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
String[] results = text.split("(?<=\\G.{" + length + "})");
return results[0];
}
public static String usingPattern(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Optional<String> result = Pattern.compile(".{1," + length + "}")
.matcher(text)
.results()
.map(MatchResult::group)
.findFirst();
return result.isPresent() ? result.get() : EMPTY;
}
public static String usingCodePointsMethod(String text, int length) { | if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
return text.codePoints()
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
public static String usingLeftMethod(String text, int length) {
return StringUtils.left(text, length);
}
public static String usingTruncateMethod(String text, int length) {
return StringUtils.truncate(text, length);
}
public static String usingSplitter(String text, int length) {
if (length < 0) {
throw new IllegalArgumentException("length cannot be negative");
}
if (text == null) {
return EMPTY;
}
Iterable<String> parts = Splitter.fixedLength(length)
.split(text);
return parts.iterator()
.next();
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-11\src\main\java\com\baeldung\truncate\TruncateString.java | 1 |
请完成以下Java代码 | public IModelCopyHelper setTo(final Object toModel)
{
this._toModel = toModel;
this._toModelAccessor = null;
return this;
}
private final IModelInternalAccessor getToAccessor()
{
if (_toModelAccessor == null)
{
Check.assumeNotNull(_toModel, "_toModel not null");
_toModelAccessor = InterfaceWrapperHelper.getModelInternalAccessor(_toModel);
}
return _toModelAccessor;
}
public final boolean isSkipCalculatedColumns()
{
return _skipCalculatedColumns; | }
@Override
public IModelCopyHelper setSkipCalculatedColumns(boolean skipCalculatedColumns)
{
this._skipCalculatedColumns = skipCalculatedColumns;
return this;
}
@Override
public IModelCopyHelper addTargetColumnNameToSkip(final String columnName)
{
targetColumnNamesToSkip.add(columnName);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\model\util\ModelCopyHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
return Objects.hash(amount, availableChoices, buyerProvided, buyerUsername, closedDate, evidence, evidenceRequests, lineItems, monetaryTransactions, openDate, orderId, paymentDisputeId, paymentDisputeStatus, reason, resolution, respondByDate, returnAddress, revision, sellerResponse);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class PaymentDispute {\n");
sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" availableChoices: ").append(toIndentedString(availableChoices)).append("\n");
sb.append(" buyerProvided: ").append(toIndentedString(buyerProvided)).append("\n");
sb.append(" buyerUsername: ").append(toIndentedString(buyerUsername)).append("\n");
sb.append(" closedDate: ").append(toIndentedString(closedDate)).append("\n");
sb.append(" evidence: ").append(toIndentedString(evidence)).append("\n");
sb.append(" evidenceRequests: ").append(toIndentedString(evidenceRequests)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" monetaryTransactions: ").append(toIndentedString(monetaryTransactions)).append("\n");
sb.append(" openDate: ").append(toIndentedString(openDate)).append("\n");
sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n");
sb.append(" paymentDisputeId: ").append(toIndentedString(paymentDisputeId)).append("\n");
sb.append(" paymentDisputeStatus: ").append(toIndentedString(paymentDisputeStatus)).append("\n");
sb.append(" reason: ").append(toIndentedString(reason)).append("\n");
sb.append(" resolution: ").append(toIndentedString(resolution)).append("\n");
sb.append(" respondByDate: ").append(toIndentedString(respondByDate)).append("\n");
sb.append(" returnAddress: ").append(toIndentedString(returnAddress)).append("\n");
sb.append(" revision: ").append(toIndentedString(revision)).append("\n");
sb.append(" sellerResponse: ").append(toIndentedString(sellerResponse)).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(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\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PaymentDispute.java | 2 |
请完成以下Java代码 | public class Purpose2Choice {
@XmlElement(name = "Cd")
protected String cd;
@XmlElement(name = "Prtry")
protected String prtry;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCd(String value) {
this.cd = value;
}
/**
* Gets the value of the prtry property.
*
* @return | * possible object is
* {@link String }
*
*/
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\Purpose2Choice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure(Map<String, ?> configs) {
this.configs = configs;
this.sslBundle = (SslBundle) configs.get(SSL_BUNDLE_CONFIG_NAME);
}
@Override
public void close() throws IOException {
}
@Override
public SSLEngine createClientSslEngine(String peerHost, int peerPort, String endpointIdentification) {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
SSLEngine sslEngine = sslBundle.createSslContext().createSSLEngine(peerHost, peerPort);
sslEngine.setUseClientMode(true);
SSLParameters sslParams = sslEngine.getSSLParameters();
sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
sslEngine.setSSLParameters(sslParams);
return sslEngine;
}
@Override
public SSLEngine createServerSslEngine(String peerHost, int peerPort) {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
SSLEngine sslEngine = sslBundle.createSslContext().createSSLEngine(peerHost, peerPort);
sslEngine.setUseClientMode(false);
return sslEngine;
} | @Override
public boolean shouldBeRebuilt(Map<String, Object> nextConfigs) {
return !nextConfigs.equals(this.configs);
}
@Override
public Set<String> reconfigurableConfigs() {
return Set.of(SSL_BUNDLE_CONFIG_NAME);
}
@Override
public @Nullable KeyStore keystore() {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
return sslBundle.getStores().getKeyStore();
}
@Override
public @Nullable KeyStore truststore() {
SslBundle sslBundle = this.sslBundle;
Assert.state(sslBundle != null, "'sslBundle' must not be null");
return sslBundle.getStores().getTrustStore();
}
} | repos\spring-boot-4.0.1\module\spring-boot-kafka\src\main\java\org\springframework\boot\kafka\autoconfigure\SslBundleSslEngineFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setFee(BigDecimal fee) {
this.fee = fee;
}
public Date getBankTradeTime() {
return bankTradeTime;
}
public void setBankTradeTime(Date bankTradeTime) {
this.bankTradeTime = bankTradeTime;
}
public String getBankOrderNo() {
return bankOrderNo;
}
public void setBankOrderNo(String bankOrderNo) {
this.bankOrderNo = bankOrderNo == null ? null : bankOrderNo.trim();
}
public String getBankTrxNo() {
return bankTrxNo;
}
public void setBankTrxNo(String bankTrxNo) {
this.bankTrxNo = bankTrxNo == null ? null : bankTrxNo.trim();
}
public String getBankTradeStatus() {
return bankTradeStatus;
}
public void setBankTradeStatus(String bankTradeStatus) {
this.bankTradeStatus = bankTradeStatus == null ? null : bankTradeStatus.trim();
}
public BigDecimal getBankAmount() {
return bankAmount;
}
public void setBankAmount(BigDecimal bankAmount) {
this.bankAmount = bankAmount;
}
public BigDecimal getBankRefundAmount() {
return bankRefundAmount;
}
public void setBankRefundAmount(BigDecimal bankRefundAmount) {
this.bankRefundAmount = bankRefundAmount;
}
public BigDecimal getBankFee() {
return bankFee;
}
public void setBankFee(BigDecimal bankFee) {
this.bankFee = bankFee;
}
public String getErrType() {
return errType;
}
public void setErrType(String errType) {
this.errType = errType == null ? null : errType.trim();
}
public String getHandleStatus() {
return handleStatus;
}
public void setHandleStatus(String handleStatus) {
this.handleStatus = handleStatus == null ? null : handleStatus.trim();
} | public String getHandleValue() {
return handleValue;
}
public void setHandleValue(String handleValue) {
this.handleValue = handleValue == null ? null : handleValue.trim();
}
public String getHandleRemark() {
return handleRemark;
}
public void setHandleRemark(String handleRemark) {
this.handleRemark = handleRemark == null ? null : handleRemark.trim();
}
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName == null ? null : operatorName.trim();
}
public String getOperatorAccountNo() {
return operatorAccountNo;
}
public void setOperatorAccountNo(String operatorAccountNo) {
this.operatorAccountNo = operatorAccountNo == null ? null : operatorAccountNo.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistake.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public JwtSettings saveJwtSettings(JwtSettings jwtSettings) {
jwtSettingsValidator.validate(jwtSettings);
final AdminSettings adminJwtSettings = mapJwtToAdminSettings(jwtSettings);
final AdminSettings existedSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, ADMIN_SETTINGS_JWT_KEY);
if (existedSettings != null) {
adminJwtSettings.setId(existedSettings.getId());
}
log.info("Saving new JWT admin settings. From this moment, the JWT parameters from YAML and ENV will be ignored");
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, adminJwtSettings);
tbClusterService.ifPresent(cs -> cs.broadcastEntityStateChangeEvent(TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID, ComponentLifecycleEvent.UPDATED));
return reloadJwtSettings();
}
@Override
public JwtSettings reloadJwtSettings() {
log.trace("Executing reloadJwtSettings");
var settings = getJwtSettings(true);
jwtTokenFactory.ifPresent(JwtTokenFactory::reload);
return settings;
}
@Override
public JwtSettings getJwtSettings() {
log.trace("Executing getJwtSettings");
return getJwtSettings(false);
}
public JwtSettings getJwtSettings(boolean forceReload) {
if (this.jwtSettings == null || forceReload) {
synchronized (this) {
if (this.jwtSettings == null || forceReload) {
jwtSettings = getJwtSettingsFromDb();
}
}
}
return this.jwtSettings; | }
private JwtSettings getJwtSettingsFromDb() {
AdminSettings adminJwtSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, ADMIN_SETTINGS_JWT_KEY);
return adminJwtSettings != null ? mapAdminToJwtSettings(adminJwtSettings) : null;
}
private JwtSettings mapAdminToJwtSettings(AdminSettings adminSettings) {
Objects.requireNonNull(adminSettings, "adminSettings for JWT is null");
return JacksonUtil.treeToValue(adminSettings.getJsonValue(), JwtSettings.class);
}
private AdminSettings mapJwtToAdminSettings(JwtSettings jwtSettings) {
Objects.requireNonNull(jwtSettings, "jwtSettings is null");
AdminSettings adminJwtSettings = new AdminSettings();
adminJwtSettings.setTenantId(TenantId.SYS_TENANT_ID);
adminJwtSettings.setKey(ADMIN_SETTINGS_JWT_KEY);
adminJwtSettings.setJsonValue(JacksonUtil.valueToTree(jwtSettings));
return adminJwtSettings;
}
public static boolean isSigningKeyDefault(JwtSettings settings) {
return TOKEN_SIGNING_KEY_DEFAULT.equals(settings.getTokenSigningKey());
}
public static boolean validateKeyLength(String key) {
return Base64.getDecoder().decode(key).length * Byte.SIZE >= KEY_LENGTH;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\settings\DefaultJwtSettingsService.java | 2 |
请完成以下Java代码 | private void dbUpdateErrorMessages(@NonNull final ImportRecordsSelection selection)
{
//
// No Locator
{
final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ")
.append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Locator, ' ")
.append(" WHERE M_Locator_ID IS NULL ")
.append(" AND I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause());
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
if (no != 0)
{
logger.warn("No Locator = {}", no);
}
}
//
// No Warehouse
{
final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ")
.append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Warehouse, ' ")
.append(" WHERE M_Warehouse_ID IS NULL ")
.append(" AND I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause());
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
if (no != 0)
{
logger.warn("No Warehouse = {}", no);
}
}
//
// No Product
{
final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ")
.append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Product, ' ")
.append(" WHERE M_Product_ID IS NULL ")
.append(" AND I_IsImported<>'Y' ") | .append(selection.toSqlWhereClause());
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
if (no != 0)
{
logger.warn("No Product = {}", no);
}
}
// No QtyCount
{
final StringBuilder sql = new StringBuilder("UPDATE I_Inventory ")
.append(" SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No qtycount, ' ")
.append(" WHERE qtycount IS NULL ")
.append(" AND I_IsImported<>'Y' ")
.append(selection.toSqlWhereClause());
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
if (no != 0)
{
logger.warn("No qtycount = {}", no);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inventory\impexp\MInventoryImportTableSqlUpdater.java | 1 |
请完成以下Java代码 | public String getContentSecurityPolicyValue() {
return contentSecurityPolicyValue;
}
public void setContentSecurityPolicyValue(String contentSecurityPolicyValue) {
this.contentSecurityPolicyValue = contentSecurityPolicyValue;
}
public boolean isContentTypeOptionsDisabled() {
return contentTypeOptionsDisabled;
}
public void setContentTypeOptionsDisabled(boolean contentTypeOptionsDisabled) {
this.contentTypeOptionsDisabled = contentTypeOptionsDisabled;
}
public String getContentTypeOptionsValue() {
return contentTypeOptionsValue;
}
public void setContentTypeOptionsValue(String contentTypeOptionsValue) {
this.contentTypeOptionsValue = contentTypeOptionsValue;
}
public boolean isHstsDisabled() {
return hstsDisabled;
}
public void setHstsDisabled(boolean hstsDisabled) {
this.hstsDisabled = hstsDisabled;
}
public boolean isHstsIncludeSubdomainsDisabled() {
return hstsIncludeSubdomainsDisabled;
}
public void setHstsIncludeSubdomainsDisabled(boolean hstsIncludeSubdomainsDisabled) {
this.hstsIncludeSubdomainsDisabled = hstsIncludeSubdomainsDisabled;
} | public String getHstsValue() {
return hstsValue;
}
public void setHstsValue(String hstsValue) {
this.hstsValue = hstsValue;
}
public String getHstsMaxAge() {
return hstsMaxAge;
}
public void setHstsMaxAge(String hstsMaxAge) {
this.hstsMaxAge = hstsMaxAge;
}
@Override
public String toString() {
StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled)
.add("xssProtectionOption=" + xssProtectionOption)
.add("xssProtectionValue=" + xssProtectionValue)
.add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled)
.add("contentSecurityPolicyValue=" + contentSecurityPolicyValue)
.add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled)
.add("contentTypeOptionsValue=" + contentTypeOptionsValue)
.add("hstsDisabled=" + hstsDisabled)
.add("hstsMaxAge=" + hstsMaxAge)
.add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled)
.add("hstsValue=" + hstsValue);
return joinedString.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCollectiveCustomsClearance(Boolean value) {
this.collectiveCustomsClearance = value;
}
/**
* Gets the value of the invoicePosition property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInvoicePosition() {
return invoicePosition;
}
/**
* Sets the value of the invoicePosition property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInvoicePosition(String value) {
this.invoicePosition = value;
}
/**
* Gets the value of the comment1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getComment1() {
return comment1;
}
/**
* Sets the value of the comment1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment1(String value) {
this.comment1 = value;
}
/**
* Gets the value of the comment2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getComment2() {
return comment2;
}
/**
* Sets the value of the comment2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment2(String value) {
this.comment2 = value;
}
/**
* Gets the value of the commercialInvoiceConsigneeVatNumber property.
*
* @return
* possible object is
* {@link String }
* | */
public String getCommercialInvoiceConsigneeVatNumber() {
return commercialInvoiceConsigneeVatNumber;
}
/**
* Sets the value of the commercialInvoiceConsigneeVatNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCommercialInvoiceConsigneeVatNumber(String value) {
this.commercialInvoiceConsigneeVatNumber = value;
}
/**
* Gets the value of the commercialInvoiceConsignee property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getCommercialInvoiceConsignee() {
return commercialInvoiceConsignee;
}
/**
* Sets the value of the commercialInvoiceConsignee property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setCommercialInvoiceConsignee(Address value) {
this.commercialInvoiceConsignee = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\International.java | 2 |
请完成以下Java代码 | public Collection<ProductsToPickRow> getTopLevelRows()
{
final Map<DocumentId, ProductsToPickRow> rowsById = getAllRowsById();
return topLevelRowIdsOrdered.stream()
.map(rowsById::get)
.collect(ImmutableList.toImmutableList());
}
@Override
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
changeRow(ctx.getRowId(), row -> applyFieldChangeRequests(row, fieldChangeRequests));
}
private ProductsToPickRow applyFieldChangeRequests(@NonNull final ProductsToPickRow row, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
fieldChangeRequests.forEach(JSONDocumentChangedEvent::assertReplaceOperation);
ProductsToPickRow changedRow = row;
for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests)
{
final String fieldName = fieldChangeRequest.getPath();
if (ProductsToPickRow.FIELD_QtyOverride.equals(fieldName))
{
if (!row.isQtyOverrideEditableByUser())
{
throw new AdempiereException("QtyOverride is not editable")
.setParameter("row", row);
}
final BigDecimal qtyOverride = fieldChangeRequest.getValueAsBigDecimal();
changedRow = changedRow.withQtyOverride(qtyOverride);
}
else if (ProductsToPickRow.FIELD_QtyReview.equals(fieldName))
{
final BigDecimal qtyReviewed = fieldChangeRequest.getValueAsBigDecimal();
final PickingCandidate pickingCandidate = pickingCandidateService.setQtyReviewed(row.getPickingCandidateId(), qtyReviewed);
changedRow = changedRow.withUpdatesFromPickingCandidate(pickingCandidate);
}
else
{
throw new AdempiereException("Field " + fieldName + " is not editable");
}
}
return changedRow;
}
@Override | public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
final Set<PickingCandidateId> pickingCandidateIds = recordRefs
.streamIds(I_M_Picking_Candidate.Table_Name, PickingCandidateId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (pickingCandidateIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
}
return getAllRowsByIdNoUpdate()
.values()
.stream()
.filter(row -> pickingCandidateIds.contains(row.getPickingCandidateId()))
.map(ProductsToPickRow::getId)
.collect(DocumentIdsSelection.toDocumentIdsSelection());
}
@Override
public void invalidateAll()
{
rowIdsInvalid = true;
}
public void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate)
{
changeRow(rowId, row -> row.withUpdatesFromPickingCandidate(pickingCandidate));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowsData.java | 1 |
请完成以下Java代码 | public class ExtendContractOrder
{
private static final AdMessageKey MSG_EXTEND_CONTRACT_ALREADY_PROLONGED = AdMessageKey.of("de.metas.contracts.subscription.impl.subscriptioncommands.ExtendContractOrder");
public static I_C_Order extend(@NonNull final I_C_Order existentOrder)
{
if (I_C_Order.CONTRACTSTATUS_Extended.equals(existentOrder.getContractStatus()))
{
throw new AdempiereException(MSG_EXTEND_CONTRACT_ALREADY_PROLONGED);
}
else
{
final I_C_Order newOrder = InterfaceWrapperHelper.newInstance(I_C_Order.class, existentOrder);
final PO newOrderPO = InterfaceWrapperHelper.getPO(newOrder);
final PO existentOrderPO = InterfaceWrapperHelper.getPO(existentOrder);
PO.copyValues(existentOrderPO, newOrderPO, true);
InterfaceWrapperHelper.save(newOrder);
CopyRecordFactory.getCopyRecordSupport(I_C_Order.Table_Name)
.copyChildren(newOrderPO, existentOrderPO);
newOrder.setDocStatus(DocStatus.Drafted.getCode());
newOrder.setDocAction(X_C_Order.DOCACTION_Complete);
final I_C_Flatrate_Term lastTerm = Services.get(ISubscriptionBL.class).retrieveLastFlatrateTermFromOrder(existentOrder);
if (lastTerm != null)
{
final Timestamp addDays = TimeUtil.addDays(lastTerm.getEndDate(), 1); | newOrder.setDatePromised(addDays);
newOrder.setPreparationDate(addDays);
}
InterfaceWrapperHelper.save(newOrder);
// link the existent order to the new one
existentOrder.setRef_FollowupOrder_ID(newOrder.getC_Order_ID());
InterfaceWrapperHelper.save(existentOrder);
return newOrder;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\subscriptioncommands\ExtendContractOrder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ArticleMapping customerId(String customerId) {
this.customerId = customerId;
return this;
}
/**
* eindeutige Artikelnummer aus WaWi
* @return customerId
**/
@Schema(example = "43435", required = true, description = "eindeutige Artikelnummer aus WaWi")
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public ArticleMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArticleMapping articleMapping = (ArticleMapping) o;
return Objects.equals(this._id, articleMapping._id) &&
Objects.equals(this.customerId, articleMapping.customerId) &&
Objects.equals(this.updated, articleMapping.updated);
} | @Override
public int hashCode() {
return Objects.hash(_id, customerId, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ArticleMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).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\ArticleMapping.java | 2 |
请在Spring Boot框架中完成以下Java代码 | Output expandDims(Output input, Output dim) {
return binaryOp("ExpandDims", input, dim);
}
Output cast(Output value, DataType dtype) {
return g.opBuilder("Cast", "Cast", scope).addInput(value).setAttr("DstT", dtype).build().output(0);
}
Output decodeJpeg(Output contents, long channels) {
return g.opBuilder("DecodeJpeg", "DecodeJpeg", scope)
.addInput(contents)
.setAttr("channels", channels)
.build()
.output(0);
}
Output<? extends TType> constant(String name, Tensor t) {
return g.opBuilder("Const", name, scope)
.setAttr("dtype", t.dataType())
.setAttr("value", t)
.build()
.output(0);
}
private Output binaryOp(String type, Output in1, Output in2) {
return g.opBuilder(type, type, scope).addInput(in1).addInput(in2).build().output(0);
}
private final Graph g;
} | @PreDestroy
public void close() {
session.close();
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class LabelWithProbability {
private String label;
private float probability;
private long elapsed;
}
} | repos\springboot-demo-master\Tensorflow\src\main\java\com\et\tf\service\ClassifyImageService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OtaPackageImportService extends BaseEntityImportService<OtaPackageId, OtaPackage, OtaPackageExportData> {
private final OtaPackageService otaPackageService;
@Override
protected void setOwner(TenantId tenantId, OtaPackage otaPackage, IdProvider idProvider) {
otaPackage.setTenantId(tenantId);
}
@Override
protected OtaPackage prepare(EntitiesImportCtx ctx, OtaPackage otaPackage, OtaPackage oldOtaPackage, OtaPackageExportData exportData, IdProvider idProvider) {
otaPackage.setDeviceProfileId(idProvider.getInternalId(otaPackage.getDeviceProfileId()));
return otaPackage;
}
@Override
protected OtaPackage findExistingEntity(EntitiesImportCtx ctx, OtaPackage otaPackage, IdProvider idProvider) {
OtaPackage existingOtaPackage = super.findExistingEntity(ctx, otaPackage, idProvider);
if (existingOtaPackage == null && ctx.isFindExistingByName()) {
existingOtaPackage = otaPackageService.findOtaPackageByTenantIdAndTitleAndVersion(ctx.getTenantId(), otaPackage.getTitle(), otaPackage.getVersion());
}
return existingOtaPackage;
}
@Override
protected OtaPackage deepCopy(OtaPackage otaPackage) {
return new OtaPackage(otaPackage); | }
@Override
protected OtaPackage saveOrUpdate(EntitiesImportCtx ctx, OtaPackage otaPackage, OtaPackageExportData exportData, IdProvider idProvider, CompareResult compareResult) {
if (otaPackage.hasUrl()) {
OtaPackageInfo info = new OtaPackageInfo(otaPackage);
return new OtaPackage(otaPackageService.saveOtaPackageInfo(info, info.hasUrl()));
}
return otaPackageService.saveOtaPackage(otaPackage);
}
@Override
public EntityType getEntityType() {
return EntityType.OTA_PACKAGE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\OtaPackageImportService.java | 2 |
请完成以下Java代码 | public void setM_ChangeNotice(final org.compiere.model.I_M_ChangeNotice M_ChangeNotice)
{
set_ValueFromPO(COLUMNNAME_M_ChangeNotice_ID, org.compiere.model.I_M_ChangeNotice.class, M_ChangeNotice);
}
@Override
public void setM_ChangeNotice_ID (final int M_ChangeNotice_ID)
{
if (M_ChangeNotice_ID < 1)
set_Value (COLUMNNAME_M_ChangeNotice_ID, null);
else
set_Value (COLUMNNAME_M_ChangeNotice_ID, M_ChangeNotice_ID);
}
@Override
public int getM_ChangeNotice_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ChangeNotice_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setRevision (final @Nullable java.lang.String Revision)
{
set_Value (COLUMNNAME_Revision, Revision);
}
@Override
public java.lang.String getRevision()
{
return get_ValueAsString(COLUMNNAME_Revision);
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
} | @Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistribution.java | 1 |
请完成以下Java代码 | public void onChildSaved(final Document document)
{
if (!document.hasChangesRecursivelly())
{
forgetChangedDocument(document.getDocumentId());
}
}
@Override
public void onChildChanged(final Document document)
{
// NOTE: we assume the document has changes
// if(document.hasChangesRecursivelly())
addChangedDocument(document);
}
@Override
public void markStaleAll()
{
staled = true;
parentDocument.getChangesCollector().collectStaleDetailId(parentDocumentPath, detailId);
}
@Override
public void markStale(@NonNull final DocumentIdsSelection rowIds)
{
// TODO: implement staling only given rowId
markStaleAll();
}
@Override
public boolean isStale()
{
return staled;
}
@Override
public int getNextLineNo()
{
final int lastLineNo = DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setExistingDocumentsSupplier(this::getChangedDocumentOrNull)
.setChangesCollector(NullDocumentChangesCollector.instance)
.retrieveLastLineNo();
final int nextLineNo = lastLineNo / 10 * 10 + 10;
return nextLineNo;
}
//
//
//
@AllArgsConstructor
private final class ActionsContext implements IncludedDocumentsCollectionActionsContext
{
@Override
public boolean isParentDocumentProcessed()
{
return parentDocument.isProcessed();
}
@Override
public boolean isParentDocumentActive()
{
return parentDocument.isActive();
} | @Override
public boolean isParentDocumentNew()
{
return parentDocument.isNew();
}
@Override
public boolean isParentDocumentInvalid()
{
return !parentDocument.getValidStatus().isValid();
}
@Override
public Collection<Document> getIncludedDocuments()
{
return getChangedDocuments();
}
@Override
public Evaluatee toEvaluatee()
{
return parentDocument.asEvaluatee();
}
@Override
public void collectAllowNew(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
parentDocument.getChangesCollector().collectAllowNew(parentDocumentPath, detailId, allowNew);
}
@Override
public void collectAllowDelete(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
parentDocument.getChangesCollector().collectAllowDelete(parentDocumentPath, detailId, allowDelete);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadWriteIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | public void setTo_Region_ID (final int To_Region_ID)
{
if (To_Region_ID < 1)
set_Value (COLUMNNAME_To_Region_ID, null);
else
set_Value (COLUMNNAME_To_Region_ID, To_Region_ID);
}
@Override
public int getTo_Region_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Region_ID);
}
/**
* TypeOfDestCountry AD_Reference_ID=541323
* Reference name: TypeDestCountry
*/
public static final int TYPEOFDESTCOUNTRY_AD_Reference_ID=541323;
/** Domestic = DOMESTIC */
public static final String TYPEOFDESTCOUNTRY_Domestic = "DOMESTIC";
/** EU-foreign = WITHIN_COUNTRY_AREA */
public static final String TYPEOFDESTCOUNTRY_EU_Foreign = "WITHIN_COUNTRY_AREA";
/** Non-EU country = OUTSIDE_COUNTRY_AREA */
public static final String TYPEOFDESTCOUNTRY_Non_EUCountry = "OUTSIDE_COUNTRY_AREA";
@Override
public void setTypeOfDestCountry (final @Nullable java.lang.String TypeOfDestCountry)
{
set_Value (COLUMNNAME_TypeOfDestCountry, TypeOfDestCountry);
}
@Override
public java.lang.String getTypeOfDestCountry()
{
return get_ValueAsString(COLUMNNAME_TypeOfDestCountry);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom) | {
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Tax.java | 1 |
请完成以下Java代码 | public Parameter getParameter() {
return parameterChild.getChild(this);
}
public void setParameter(Parameter parameter) {
parameterChild.setChild(this, parameter);
}
public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Binding.class, DMN_ELEMENT_BINDING)
.namespaceUri(LATEST_DMN_NS)
.instanceProvider(new ModelTypeInstanceProvider<Binding>() {
public Binding newInstance(ModelTypeInstanceContext instanceContext) {
return new BindingImpl(instanceContext);
} | });
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterChild = sequenceBuilder.element(Parameter.class)
.required()
.build();
expressionChild = sequenceBuilder.element(Expression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\BindingImpl.java | 1 |
请完成以下Java代码 | public boolean supports(ConfigAttribute configAttribute) {
return configAttribute instanceof Jsr250SecurityConfig;
}
/**
* All classes are supported.
* @param clazz the class.
* @return true
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
/**
* Votes according to JSR 250.
* <p>
* If no JSR-250 attributes are found, it will abstain, otherwise it will grant or
* deny access based on the attributes that are found.
* @param authentication The authentication object.
* @param object The access object.
* @param definition The configuration definition.
* @return The vote.
*/
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> definition) {
boolean jsr250AttributeFound = false; | for (ConfigAttribute attribute : definition) {
if (Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE.equals(attribute)) {
return ACCESS_GRANTED;
}
if (Jsr250SecurityConfig.DENY_ALL_ATTRIBUTE.equals(attribute)) {
return ACCESS_DENIED;
}
if (supports(attribute)) {
jsr250AttributeFound = true;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authentication.getAuthorities()) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\annotation\Jsr250Voter.java | 1 |
请完成以下Java代码 | public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public org.compiere.model.I_M_HazardSymbol getM_HazardSymbol()
{
return get_ValueAsPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class);
}
@Override
public void setM_HazardSymbol(final org.compiere.model.I_M_HazardSymbol M_HazardSymbol)
{
set_ValueFromPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class, M_HazardSymbol); | }
@Override
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID)
{
if (M_HazardSymbol_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID);
}
@Override
public int getM_HazardSymbol_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_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_HazardSymbol_Trl.java | 1 |
请完成以下Java代码 | public int getMinValue ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MinValue);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Service date.
@param ServiceDate
Date service was provided
*/
public void setServiceDate (Timestamp ServiceDate)
{
set_Value (COLUMNNAME_ServiceDate, ServiceDate);
}
/** Get Service date.
@return Date service was provided
*/
public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** 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);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Attribute.java | 1 |
请完成以下Java代码 | public List<HistoricIdentityLink> execute(CommandContext commandContext) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
HistoricTaskInstanceEntity task = cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskService().getHistoricTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("No historic task exists with the given id: " + taskId, HistoricTaskInstance.class);
}
HistoricIdentityLinkService historicIdentityLinkService = cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkService();
List<HistoricIdentityLinkEntity> identityLinks = historicIdentityLinkService.findHistoricIdentityLinksByTaskId(taskId);
HistoricIdentityLinkEntity assigneeIdentityLink = null;
HistoricIdentityLinkEntity ownerIdentityLink = null;
for (HistoricIdentityLinkEntity historicIdentityLink : identityLinks) {
if (IdentityLinkType.ASSIGNEE.equals(historicIdentityLink.getType())) {
assigneeIdentityLink = historicIdentityLink;
} else if (IdentityLinkType.OWNER.equals(historicIdentityLink.getType())) {
ownerIdentityLink = historicIdentityLink;
}
} | // Similar to GetIdentityLinksForTask, return assignee and owner as identity link
if (task.getAssignee() != null && assigneeIdentityLink == null) {
HistoricIdentityLinkEntity identityLink = historicIdentityLinkService.createHistoricIdentityLink();
identityLink.setUserId(task.getAssignee());
identityLink.setTaskId(task.getId());
identityLink.setType(IdentityLinkType.ASSIGNEE);
identityLinks.add(identityLink);
}
if (task.getOwner() != null && ownerIdentityLink == null) {
HistoricIdentityLinkEntity identityLink = historicIdentityLinkService.createHistoricIdentityLink();
identityLink.setTaskId(task.getId());
identityLink.setUserId(task.getOwner());
identityLink.setType(IdentityLinkType.OWNER);
identityLinks.add(identityLink);
}
return (List) identityLinks;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetHistoricIdentityLinksForTaskCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CLR implements CommandLineRunner {
@Autowired UserRepository repository;
@Override
public void run(String... args) throws Exception {
User luke = new User("id-1", "luke");
luke.setFirstname("Luke");
luke.setLastname("Skywalker");
luke.setPosts(List.of(new Post("I have a bad feeling about this.")));
User leia = new User("id-2", "leia");
leia.setFirstname("Leia");
leia.setLastname("Organa");
User han = new User("id-3", "han");
han.setFirstname("Han");
han.setLastname("Solo");
han.setPosts(List.of(new Post("It's the ship that made the Kessel Run in less than 12 Parsecs.")));
User chewbacca = new User("id-4", "chewbacca");
User yoda = new User("id-5", "yoda");
yoda.setPosts(List.of(new Post("Do. Or do not. There is no try."), new Post("Decide you must, how to serve them best. If you leave now, help them you could; but you would destroy all for which they have fought, and suffered.")));
User vader = new User("id-6", "vader");
vader.setFirstname("Anakin");
vader.setLastname("Skywalker");
vader.setPosts(List.of(new Post("I am your father"))); | User kylo = new User("id-7", "kylo");
kylo.setFirstname("Ben");
kylo.setLastname("Solo");
repository.saveAll(List.of(luke, leia, han, chewbacca, yoda, vader, kylo));
repository.usersWithUsernamesStartingWith("l");
repository.findUserByUsername("yoda");
repository.findUserByPostsMessageLike("father");
repository.findOptionalUserByUsername("yoda");
Long count = repository.countUsersByLastnameLike("Sky");
Boolean exists = repository.existsByUsername("vader");
repository.findUserByLastnameLike("Sky");
}
} | repos\spring-data-examples-main\mongodb\aot-optimization\src\main\java\example\springdata\aot\CLR.java | 2 |
请完成以下Java代码 | public class S3StorageController {
private final AmzS3Config amzS3Config;
private final S3StorageService s3StorageService;
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('storage:list')")
public void exportS3Storage(HttpServletResponse response, S3StorageQueryCriteria criteria) throws IOException {
s3StorageService.download(s3StorageService.queryAll(criteria), response);
}
@GetMapping
@ApiOperation("查询文件")
@PreAuthorize("@el.check('storage:list')")
public ResponseEntity<PageResult<S3Storage>> queryS3Storage(S3StorageQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(s3StorageService.queryAll(criteria, pageable),HttpStatus.OK);
}
@PostMapping
@ApiOperation("上传文件")
public ResponseEntity<Object> uploadS3Storage(@RequestParam MultipartFile file){
S3Storage storage = s3StorageService.upload(file);
Map<String,Object> map = new HashMap<>(3);
map.put("id",storage.getId());
map.put("errno",0);
map.put("data",new String[]{amzS3Config.getDomain() + "/" + storage.getFilePath()});
return new ResponseEntity<>(map,HttpStatus.OK); | }
@Log("下载文件")
@ApiOperation("下载文件")
@GetMapping(value = "/download/{id}")
public ResponseEntity<Object> downloadS3Storage(@PathVariable Long id){
Map<String,Object> map = new HashMap<>(1);
S3Storage storage = s3StorageService.getById(id);
if (storage == null) {
map.put("message", "文件不存在或已被删除");
return new ResponseEntity<>(map, HttpStatus.NOT_FOUND);
}
// 仅适合公开文件访问,私有文件可以使用服务中的 privateDownload 方法
String url = amzS3Config.getDomain() + "/" + storage.getFilePath();
map.put("url", url);
return new ResponseEntity<>(map,HttpStatus.OK);
}
@Log("删除多个文件")
@DeleteMapping
@ApiOperation("删除多个文件")
@PreAuthorize("@el.check('storage:del')")
public ResponseEntity<Object> deleteAllS3Storage(@RequestBody List<Long> ids) {
s3StorageService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\S3StorageController.java | 1 |
请完成以下Java代码 | class Tags {
@JsonProperty("toptags") private Map<String, Object> topTags;
@SuppressWarnings("unchecked")
public Map<String, Double> all() {
try {
Map<String, Double> all = new HashMap<>();
List<Map<String, Object>> tags = (List<Map<String, Object>>) topTags.get("tag");
for (Map<String, Object> tag : tags) {
all.put(((String) tag.get("name")), ((Integer) tag.get("count")).doubleValue());
}
return all;
} catch (Exception e) {
return Collections.emptyMap();
}
}
} | @JsonAutoDetect(fieldVisibility = ANY)
class Artists {
private Map<String, Object> artists;
@SuppressWarnings("unchecked")
public List<String> all() {
try {
List<Map<String, Object>> artists = (List<Map<String, Object>>) this.artists.get("artist");
return artists
.stream()
.map(e -> ((String) e.get("name")))
.collect(toList());
} catch (Exception e) {
return Collections.emptyList();
}
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\kmeans\LastFmService.java | 1 |
请完成以下Java代码 | public void forbidReactivateOnCompletedShipmentDeclaration(final I_M_InOut inout)
{
try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inout))
{
if (!inout.isSOTrx())
{
// Only applies to shipments
return;
}
final InOutId shipmentId = InOutId.ofRepoId(inout.getM_InOut_ID());
if (shipmentDeclarationRepo.existCompletedShipmentDeclarationsForShipmentId(shipmentId))
{
throw new AdempiereException(ERR_ShipmentDeclaration).markAsUserValidationError();
}
}
} | @ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE,
}, ifColumnsChanged = {
I_M_InOut.COLUMNNAME_DropShip_Location_ID, I_M_InOut.COLUMNNAME_C_BPartner_Location_ID
})
public void onBPartnerLocation(final I_M_InOut inout)
{
if (InterfaceWrapperHelper.isUIAction(inout))
{
inOutBL.setShipperId(inout);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\model\interceptor\M_InOut.java | 1 |
请完成以下Java代码 | public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
} | public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public File getMainDirectory() {
return mainDirectory;
}
public void setMainDirectory(File mainDirectory) {
this.mainDirectory = mainDirectory;
}
} | repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\bval\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getPathPrefix() {
return this.pathPrefix;
}
public void setPathPrefix(@Nullable String pathPrefix) {
this.pathPrefix = pathPrefix;
}
public Restclient getRestclient() {
return this.restclient;
}
public static class Restclient {
private final Sniffer sniffer = new Sniffer();
private final Ssl ssl = new Ssl();
public Sniffer getSniffer() {
return this.sniffer;
}
public Ssl getSsl() {
return this.ssl;
}
public static class Sniffer {
/**
* Whether the sniffer is enabled.
*/
private boolean enabled;
/**
* Interval between consecutive ordinary sniff executions.
*/
private Duration interval = Duration.ofMinutes(5);
/**
* Delay of a sniff execution scheduled after a failure.
*/
private Duration delayAfterFailure = Duration.ofMinutes(1);
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getInterval() {
return this.interval;
}
public void setInterval(Duration interval) { | this.interval = interval;
}
public Duration getDelayAfterFailure() {
return this.delayAfterFailure;
}
public void setDelayAfterFailure(Duration delayAfterFailure) {
this.delayAfterFailure = delayAfterFailure;
}
}
public static class Ssl {
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java | 2 |
请完成以下Java代码 | private static OrderCostType fromRecord(@NonNull final I_C_Cost_Type record)
{
return OrderCostType.builder()
.id(OrderCostTypeId.ofRepoId(record.getC_Cost_Type_ID()))
.code(record.getValue())
.name(record.getName())
.distributionMethod(CostDistributionMethod.ofCode(record.getCostDistributionMethod()))
.calculationMethod(CostCalculationMethod.ofCode(record.getCostCalculationMethod()))
.costElementId(CostElementId.ofRepoId(record.getM_CostElement_ID()))
.invoiceableProductId(record.isAllowInvoicing() ? ProductId.ofRepoId(record.getM_Product_ID()) : null)
.build();
}
//
//
// | private static class OrderCostTypeMap
{
private final ImmutableMap<OrderCostTypeId, OrderCostType> byId;
public OrderCostTypeMap(final ImmutableList<OrderCostType> list)
{
this.byId = Maps.uniqueIndex(list, OrderCostType::getId);
}
public OrderCostType getById(@NonNull final OrderCostTypeId id)
{
return Check.assumeNotNull(byId.get(id), "No cost type found for {}", id);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostTypeRepository.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("key", key)
.add("caption", caption)
.add("attributes", attributes)
.add("active", active)
.add("validationInformation", validationInformation)
.toString();
}
public int getKeyAsInt()
{
Integer keyAsInt = this.keyAsInt;
if (keyAsInt == null)
{
keyAsInt = this.keyAsInt = Integer.parseInt(getKey());
}
return keyAsInt;
}
public IntegerLookupValue toIntegerLookupValue()
{ | return IntegerLookupValue.builder()
.id(getKeyAsInt())
.displayName(TranslatableStrings.constant(getCaption()))
.attributes(getAttributes())
.active(isActive())
.build();
}
public StringLookupValue toStringLookupValue()
{
return StringLookupValue.builder()
.id(getKey())
.displayName(TranslatableStrings.constant(getCaption()))
.attributes(getAttributes())
.active(isActive())
.validationInformation(null) // NOTE: converting back from JSON is not supported nor needed atm
.build();
}
private boolean isActive()
{
return active == null || active;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONLookupValue.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getDBAddress());
}
/** Set Profile.
@param ProfileInfo
Information to help profiling the system for solving support issues
*/
public void setProfileInfo (String ProfileInfo)
{
set_ValueNoCheck (COLUMNNAME_ProfileInfo, ProfileInfo);
}
/** Get Profile.
@return Information to help profiling the system for solving support issues
*/
public String getProfileInfo ()
{
return (String)get_Value(COLUMNNAME_ProfileInfo);
}
/** Set Issue System.
@param R_IssueSystem_ID
System creating the issue
*/
public void setR_IssueSystem_ID (int R_IssueSystem_ID)
{
if (R_IssueSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_IssueSystem_ID, Integer.valueOf(R_IssueSystem_ID));
}
/** Get Issue System.
@return System creating the issue
*/
public int getR_IssueSystem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueSystem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistics.
@param StatisticsInfo
Information to help profiling the system for solving support issues
*/
public void setStatisticsInfo (String StatisticsInfo)
{
set_ValueNoCheck (COLUMNNAME_StatisticsInfo, StatisticsInfo);
}
/** Get Statistics. | @return Information to help profiling the system for solving support issues
*/
public String getStatisticsInfo ()
{
return (String)get_Value(COLUMNNAME_StatisticsInfo);
}
/** SystemStatus AD_Reference_ID=374 */
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
public void setSystemStatus (String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
public String getSystemStatus ()
{
return (String)get_Value(COLUMNNAME_SystemStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueSystem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void update(Job resources) {
Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new);
Job old = jobRepository.findByName(resources.getName());
if(old != null && !old.getId().equals(resources.getId())){
throw new EntityExistException(Job.class,"name",resources.getName());
}
ValidationUtil.isNull( job.getId(),"Job","id",resources.getId());
resources.setId(job.getId());
jobRepository.save(resources);
// 删除缓存
delCaches(resources.getId());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
jobRepository.deleteAllByIdIn(ids);
// 删除缓存
redisUtils.delByKeys(CacheKey.JOB_ID, ids);
}
@Override
public void download(List<JobDto> jobDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (JobDto jobDTO : jobDtos) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("岗位名称", jobDTO.getName());
map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用");
map.put("创建日期", jobDTO.getCreateTime());
list.add(map); | }
FileUtil.downloadExcel(list, response);
}
@Override
public void verification(Set<Long> ids) {
if(userRepository.countByJobs(ids) > 0){
throw new BadRequestException("所选的岗位中存在用户关联,请解除关联再试!");
}
}
/**
* 删除缓存
* @param id /
*/
public void delCaches(Long id){
redisUtils.del(CacheKey.JOB_ID + id);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\JobServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UserService {
@Autowired
private UserDao userDao;
@Autowired
private ReactiveMongoTemplate template;
public Flux<User> getUsers() {
return userDao.findAll();
}
public Mono<User> getUser(String id) {
return this.userDao.findById(id);
}
/**
* 新增和修改都是 save方法,
* id 存在为修改,id 不存在为新增
*/
public Mono<User> createUser(User user) {
return userDao.save(user);
}
public Mono<Void> deleteUser(String id) {
return this.userDao.findById(id)
.flatMap(user -> this.userDao.delete(user));
}
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 Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getLimitApp() {
return limitApp;
}
public void setLimitApp(String limitApp) {
this.limitApp = limitApp;
}
public Double getCount() {
return count;
}
public void setCount(Double count) {
this.count = count;
}
public Integer getTimeWindow() {
return timeWindow;
} | public void setTimeWindow(Integer timeWindow) {
this.timeWindow = timeWindow;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public DegradeRule toRule() {
DegradeRule rule = new DegradeRule();
rule.setResource(resource);
rule.setLimitApp(limitApp);
rule.setCount(count);
rule.setTimeWindow(timeWindow);
rule.setGrade(grade);
return rule;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\DegradeRuleEntity.java | 1 |
请完成以下Java代码 | protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
if (newRecord)
{
StringBuffer sb = new StringBuffer ("INSERT INTO AD_TreeNodeCMM "
+ "(AD_Client_ID,AD_Org_ID, IsActive,Created,CreatedBy,Updated,UpdatedBy, "
+ "AD_Tree_ID, Node_ID, Parent_ID, SeqNo) "
+ "VALUES (")
.append(getAD_Client_ID()).append(",0, 'Y', now(), 0, now(), 0,")
.append(getAD_Tree_ID()).append(",").append(get_ID())
.append(", 0, 999)");
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
if (no > 0)
log.debug("#" + no + " - TreeType=CMM");
else
log.warn("#" + no + " - TreeType=CMM");
return no > 0;
}
return success;
} // afterSave
/**
* After Delete
* @param success
* @return deleted
*/
@Override
protected boolean afterDelete (boolean success)
{
if (!success)
return success;
//
StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMM ")
.append(" WHERE Node_ID=").append(get_IDOld())
.append(" AND AD_Tree_ID=").append(getAD_Tree_ID());
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
if (no > 0)
log.debug("#" + no + " - TreeType=CMM");
else
log.warn("#" + no + " - TreeType=CMM");
return no > 0;
} // afterDelete
/**
* Get File Name
* @return file name return ID
*/
public String getFileName()
{
return get_ID() + getExtension();
} // getFileName
/**
* Get Extension with . | * @return extension
*/
public String getExtension()
{
String mt = getMediaType();
if (MEDIATYPE_ApplicationPdf.equals(mt))
return ".pdf";
if (MEDIATYPE_ImageGif.equals(mt))
return ".gif";
if (MEDIATYPE_ImageJpeg.equals(mt))
return ".jpg";
if (MEDIATYPE_ImagePng.equals(mt))
return ".png";
if (MEDIATYPE_TextCss.equals(mt))
return ".css";
// Unknown
return ".dat";
} // getExtension
/**
* Get Image
* @return image or null
*/
public MImage getImage()
{
if (getAD_Image_ID() != 0)
return MImage.get(getCtx(), getAD_Image_ID());
return null;
} // getImage
} // MMedia | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMedia.java | 1 |
请完成以下Java代码 | public void visitEnd() {
tracer.visitEnd();
System.out.println(tracer.p.getText());
}
}
public class AddFieldAdapter extends ClassVisitor {
String fieldName;
int access;
boolean isFieldPresent;
public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) {
super(ASM4, cv);
this.cv = cv;
this.access = access;
this.fieldName = fieldName;
}
@Override
public FieldVisitor visitField(int access, String name, String desc,
String signature, Object value) {
if (name.equals(fieldName)) {
isFieldPresent = true;
} | return cv.visitField(access, name, desc, signature, value);
}
@Override
public void visitEnd() {
if (!isFieldPresent) {
FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null);
if (fv != null) {
fv.visitEnd();
}
}
cv.visitEnd();
}
}
} | repos\tutorials-master\libraries-bytecode\src\main\java\com\baeldung\asm\CustomClassWriter.java | 1 |
请完成以下Java代码 | public Runnable getProcessEngineCloseRunnable() {
return new Runnable() {
@Override
public void run() {
for (String tenantId : tenantInfoHolder.getAllTenants()) {
tenantInfoHolder.setCurrentTenantId(tenantId);
if (asyncExecutor != null) {
commandExecutor.execute(new ClearProcessInstanceLockTimesCmd(asyncExecutor.getLockOwner()));
}
commandExecutor.execute(getProcessEngineCloseCommand());
tenantInfoHolder.clearCurrentTenantId();
}
}
};
} | public Command<Void> getProcessEngineCloseCommand() {
return new Command<>() {
@Override
public Void execute(CommandContext commandContext) {
CommandContextUtil.getProcessEngineConfiguration(commandContext).getCommandExecutor().execute(new SchemaOperationProcessEngineClose());
return null;
}
};
}
public TenantInfoHolder getTenantInfoHolder() {
return tenantInfoHolder;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cfg\multitenant\MultiSchemaMultiTenantProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | public int size()
{
return trie.size();
}
@Override
public boolean isEmpty()
{
return trie.isEmpty();
}
@Override
public boolean contains(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<Entry<String, V>> iterator()
{
return new Iterator<Entry<String, V>>()
{
MutableDoubleArrayTrieInteger.KeyValuePair iterator = trie.iterator();
@Override
public boolean hasNext()
{
return iterator.hasNext();
}
@Override
public Entry<String, V> next()
{
iterator.next();
return new AbstractMap.SimpleEntry<String, V>(iterator.key(), values.get(iterator.value()));
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(Entry<String, V> stringVEntry)
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c)
{
throw new UnsupportedOperationException();
} | @Override
public boolean addAll(Collection<? extends Entry<String, V>> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
MutableDoubleArrayTrie.this.clear();
}
};
}
@Override
public Iterator<Entry<String, V>> iterator()
{
return entrySet().iterator();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrie.java | 1 |
请完成以下Java代码 | public List<EngineDeployer> getDeployers() {
return deployers;
}
public void setDeployers(List<EngineDeployer> deployers) {
this.deployers = deployers;
}
public DeploymentCache<AppDefinitionCacheEntry> getAppDefinitionCache() {
return appDefinitionCache;
}
public void setAppDefinitionCache(DeploymentCache<AppDefinitionCacheEntry> appDefinitionCache) {
this.appDefinitionCache = appDefinitionCache;
}
public AppEngineConfiguration getAppEngineConfiguration() {
return appEngineConfiguration;
}
public void setAppEngineConfiguration(AppEngineConfiguration appEngineConfiguration) {
this.appEngineConfiguration = appEngineConfiguration;
}
public AppDefinitionEntityManager getAppDefinitionEntityManager() {
return appDefinitionEntityManager; | }
public void setAppDefinitionEntityManager(AppDefinitionEntityManager appDefinitionEntityManager) {
this.appDefinitionEntityManager = appDefinitionEntityManager;
}
public AppDeploymentEntityManager getDeploymentEntityManager() {
return deploymentEntityManager;
}
public void setDeploymentEntityManager(AppDeploymentEntityManager deploymentEntityManager) {
this.deploymentEntityManager = deploymentEntityManager;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\AppDeploymentManager.java | 1 |
请完成以下Java代码 | public void afterPropertiesSet() throws Exception {
adminConfig = this;
xxlJobScheduler = new XxlJobScheduler();
xxlJobScheduler.init();
}
@Override
public void destroy() throws Exception {
xxlJobScheduler.destroy();
}
// ---------------------- XxlJobScheduler ----------------------
// conf
@Value("${xxl.job.i18n}")
private String i18n;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${spring.mail.from}")
private String emailFrom;
@Value("${xxl.job.triggerpool.fast.max}")
private int triggerPoolFastMax;
@Value("${xxl.job.triggerpool.slow.max}")
private int triggerPoolSlowMax;
@Value("${xxl.job.logretentiondays}")
private int logretentiondays;
// dao, service
@Resource
private XxlJobLogDao xxlJobLogDao;
@Resource
private XxlJobInfoDao xxlJobInfoDao;
@Resource
private XxlJobRegistryDao xxlJobRegistryDao;
@Resource
private XxlJobGroupDao xxlJobGroupDao;
@Resource
private XxlJobLogReportDao xxlJobLogReportDao;
@Resource
private JavaMailSender mailSender;
@Resource
private DataSource dataSource;
@Resource
private JobAlarmer jobAlarmer;
public String getI18n() {
if (!Arrays.asList("zh_CN", "zh_TC", "en").contains(i18n)) {
return "zh_CN";
}
return i18n;
}
public String getAccessToken() {
return accessToken;
} | public String getEmailFrom() {
return emailFrom;
}
public int getTriggerPoolFastMax() {
if (triggerPoolFastMax < 200) {
return 200;
}
return triggerPoolFastMax;
}
public int getTriggerPoolSlowMax() {
if (triggerPoolSlowMax < 100) {
return 100;
}
return triggerPoolSlowMax;
}
public int getLogretentiondays() {
if (logretentiondays < 7) {
return -1; // Limit greater than or equal to 7, otherwise close
}
return logretentiondays;
}
public XxlJobLogDao getXxlJobLogDao() {
return xxlJobLogDao;
}
public XxlJobInfoDao getXxlJobInfoDao() {
return xxlJobInfoDao;
}
public XxlJobRegistryDao getXxlJobRegistryDao() {
return xxlJobRegistryDao;
}
public XxlJobGroupDao getXxlJobGroupDao() {
return xxlJobGroupDao;
}
public XxlJobLogReportDao getXxlJobLogReportDao() {
return xxlJobLogReportDao;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public DataSource getDataSource() {
return dataSource;
}
public JobAlarmer getJobAlarmer() {
return jobAlarmer;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\conf\XxlJobAdminConfig.java | 1 |
请完成以下Java代码 | public class WEBUI_PP_Order_M_Source_HU_IssueTuQty
extends WEBUI_PP_Order_Template
implements IProcessPrecondition
{
@Param(parameterName = "QtyTU", mandatory = true)
private BigDecimal qtyTU;
@Override
public final ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final PPOrderLineRow singleSelectedRow = getSingleSelectedRow();
if (singleSelectedRow.isProcessed())
{
final String internalReason = StringUtils.formatMessage("The selected row is already processed; row={}", singleSelectedRow);
return ProcessPreconditionsResolution.rejectWithInternalReason(internalReason);
}
return WEBUI_PP_Order_ProcessHelper.checkIssueSourceDefaultPreconditionsApplicable(singleSelectedRow);
}
@Override
protected String doIt() throws Exception
{
final PPOrderLineRow row = getSingleSelectedRow();
final List<I_M_Source_HU> sourceHus = WEBUI_PP_Order_ProcessHelper.retrieveActiveSourceHus(row);
if (sourceHus.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final Map<Integer, I_M_Source_HU> huId2SourceHu = new HashMap<>();
final ImmutableList<I_M_HU> husThatAreFlaggedAsSource = sourceHus.stream()
.peek(sourceHu -> huId2SourceHu.put(sourceHu.getM_HU_ID(), sourceHu))
.map(I_M_Source_HU::getM_HU)
.collect(ImmutableList.toImmutableList());
final HUsToNewTUsRequest request = HUsToNewTUsRequest.builder()
.sourceHUs(husThatAreFlaggedAsSource)
.qtyTU(qtyTU.intValue())
.build();
EmptyHUListener emptyHUListener = EmptyHUListener
.doBeforeDestroyed(hu -> { | if (huId2SourceHu.containsKey(hu.getM_HU_ID()))
{
SourceHUsService.get().snapshotSourceHU(huId2SourceHu.get(hu.getM_HU_ID()));
}
}, "Create snapshot of source-HU before it is destroyed");
final LUTUResult.TUsList extractedTUs = HUTransformService.builder()
.emptyHUListener(emptyHUListener)
.build()
.husToNewTUs(request);
final PPOrderLinesView ppOrderView = getView();
final PPOrderId ppOrderId = ppOrderView.getPpOrderId();
Services.get(IHUPPOrderBL.class)
.createIssueProducer(ppOrderId)
.createIssues(extractedTUs.toHURecords());
getView().invalidateAll();
ppOrderView.invalidateAll();
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_M_Source_HU_IssueTuQty.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.