instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public String sendTx() {
String transactionHash = "";
try {
List inputParams = new ArrayList();
List outputParams = new ArrayList();
Function function = new Function("fuctionName", inputParams, outputParams);
String encodedFunction = FunctionEncoder.encode(function);
BigInteger nonce = BigInteger.valueOf(100);
BigInteger gasprice = BigInteger.valueOf(100);
BigInteger gaslimit = BigInteger.valueOf(100);
Transaction transaction = Transaction.createFunctionCallTransaction("FROM_ADDRESS", nonce, gasprice, gaslimit, "TO_ADDRESS", encodedFunction);
org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();
transactionHash = transactionResponse.getTransactionHash();
} catch (Exception ex) { | System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return transactionHash;
}
} | repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\services\Web3Service.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
private Author author;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public void authorNotEqualsProxy() {
// behind findById() we have EntityManager#find()
author = authorRepository.findById(1L).orElseThrow();
// behind getOne() we have EntityManager#getReference()
Author proxy = authorRepository.getOne(1L); | System.out.println("Author class: " + author.getClass().getName());
System.out.println("Proxy class: " + proxy.getClass().getName());
System.out.println("'author' equals 'proxy'? " + author.equals(proxy));
}
@Transactional(readOnly = true)
public void authorEqualsUnproxy() {
// behind getOne() we have EntityManager#getReference()
Author proxy = authorRepository.getOne(1L);
Object unproxy = Hibernate.unproxy(proxy);
System.out.println("Author class: " + author.getClass().getName());
System.out.println("Unproxy class: " + unproxy.getClass().getName());
System.out.println("'author' equals 'unproxy'? " + author.equals(unproxy));
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootUnproxyAProxy\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public OAuth2ClientRegistrationTemplate toData() {
OAuth2ClientRegistrationTemplate clientRegistrationTemplate = new OAuth2ClientRegistrationTemplate();
clientRegistrationTemplate.setId(new OAuth2ClientRegistrationTemplateId(id));
clientRegistrationTemplate.setCreatedTime(createdTime);
clientRegistrationTemplate.setAdditionalInfo(additionalInfo);
clientRegistrationTemplate.setProviderId(providerId);
clientRegistrationTemplate.setMapperConfig(
OAuth2MapperConfig.builder()
.type(type)
.basic(OAuth2BasicMapperConfig.builder()
.emailAttributeKey(emailAttributeKey)
.firstNameAttributeKey(firstNameAttributeKey)
.lastNameAttributeKey(lastNameAttributeKey)
.tenantNameStrategy(tenantNameStrategy)
.tenantNamePattern(tenantNamePattern)
.customerNamePattern(customerNamePattern)
.defaultDashboardName(defaultDashboardName)
.alwaysFullScreen(alwaysFullScreen)
.build()
)
.build() | );
clientRegistrationTemplate.setAuthorizationUri(authorizationUri);
clientRegistrationTemplate.setAccessTokenUri(tokenUri);
clientRegistrationTemplate.setScope(Arrays.asList(scope.split(",")));
clientRegistrationTemplate.setUserInfoUri(userInfoUri);
clientRegistrationTemplate.setUserNameAttributeName(userNameAttributeName);
clientRegistrationTemplate.setJwkSetUri(jwkSetUri);
clientRegistrationTemplate.setClientAuthenticationMethod(clientAuthenticationMethod);
clientRegistrationTemplate.setComment(comment);
clientRegistrationTemplate.setLoginButtonIcon(loginButtonIcon);
clientRegistrationTemplate.setLoginButtonLabel(loginButtonLabel);
clientRegistrationTemplate.setHelpLink(helpLink);
return clientRegistrationTemplate;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\OAuth2ClientRegistrationTemplateEntity.java | 1 |
请完成以下Java代码 | public class MessageEventDefinition extends EventDefinition {
protected String messageRef;
protected String messageExpression;
public String getMessageRef() {
return messageRef;
}
public void setMessageRef(String messageRef) {
this.messageRef = messageRef;
}
public String getMessageExpression() {
return messageExpression;
} | public void setMessageExpression(String messageExpression) {
this.messageExpression = messageExpression;
}
@Override
public MessageEventDefinition clone() {
MessageEventDefinition clone = new MessageEventDefinition();
clone.setValues(this);
return clone;
}
public void setValues(MessageEventDefinition otherDefinition) {
super.setValues(otherDefinition);
setMessageRef(otherDefinition.getMessageRef());
setMessageExpression(otherDefinition.getMessageExpression());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MessageEventDefinition.java | 1 |
请完成以下Java代码 | public class SimulatedAnnealing {
private static Travel travel = new Travel(10);
public static double simulateAnnealing(double startingTemperature, int numberOfIterations, double coolingRate) {
System.out.println("Starting SA with temperature: " + startingTemperature + ", # of iterations: " + numberOfIterations + " and colling rate: " + coolingRate);
double t = startingTemperature;
travel.generateInitialTravel();
double bestDistance = travel.getDistance();
System.out.println("Initial distance of travel: " + bestDistance);
Travel bestSolution = travel;
Travel currentSolution = bestSolution;
for (int i = 0; i < numberOfIterations; i++) {
if (t > 0.1) {
currentSolution.swapCities();
double currentDistance = currentSolution.getDistance();
if (currentDistance < bestDistance) { | bestDistance = currentDistance;
} else if (Math.exp((bestDistance - currentDistance) / t) < Math.random()) {
currentSolution.revertSwap();
}
t *= coolingRate;
} else {
continue;
}
if (i % 100 == 0) {
System.out.println("Iteration #" + i);
}
}
return bestDistance;
}
} | repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\annealing\SimulatedAnnealing.java | 1 |
请完成以下Java代码 | public void onStateTransition(CommandContext commandContext, DelegatePlanItemInstance planItemInstance, String transition) {
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
if (planItemInstanceEntity.getPlanItemDefinition() instanceof ReactivateEventListener) {
CommandContextUtil.getAgenda(commandContext).planOccurPlanItemInstanceOperation(planItemInstanceEntity);
} else {
RepetitionRule repetitionRule = ExpressionUtil.getRepetitionRule(planItemInstanceEntity);
if (repetitionRule != null && ExpressionUtil.evaluateRepetitionRule(commandContext, planItemInstanceEntity, planItemInstanceEntity.getStagePlanItemInstanceEntity())) {
PlanItemInstanceEntity eventPlanItemInstanceEntity = PlanItemInstanceUtil.copyAndInsertPlanItemInstance(commandContext, planItemInstanceEntity, false, false);
CmmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext);
agenda.planCreatePlanItemInstanceWithoutEvaluationOperation(eventPlanItemInstanceEntity);
agenda.planOccurPlanItemInstanceOperation(eventPlanItemInstanceEntity); | CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper().executeLifecycleListeners(
commandContext, planItemInstanceEntity, PlanItemInstanceState.ACTIVE, PlanItemInstanceState.AVAILABLE);
} else {
CommandContextUtil.getAgenda(commandContext).planOccurPlanItemInstanceOperation(planItemInstanceEntity);
}
}
}
@Override
public void trigger(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
execute(commandContext, planItemInstanceEntity);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\UserEventListenerActivityBehaviour.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
final ModelElementTypeBuilder typeBuilder =
modelBuilder
.defineType(Category.class, BPMN_ELEMENT_CATEGORY)
.namespaceUri(BPMN20_NS)
.extendsType(RootElement.class)
.instanceProvider(
new ModelTypeInstanceProvider<Category>() {
@Override
public Category newInstance(ModelTypeInstanceContext instanceContext) {
return new CategoryImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME).required().build();
final SequenceBuilder sequenceBuilder = typeBuilder.sequence();
categoryValuesCollection = sequenceBuilder.elementCollection(CategoryValue.class).build();
typeBuilder.build();
} | @Override
public String getName() {
return nameAttribute.getValue(this);
}
@Override
public void setName(String name) {
nameAttribute.setValue(this, name);
}
@Override
public Collection<CategoryValue> getCategoryValues() {
return categoryValuesCollection.get(this);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CategoryImpl.java | 1 |
请完成以下Java代码 | public class CommonsDbcp2DataSourcePoolMetadata extends AbstractDataSourcePoolMetadata<BasicDataSource> {
public CommonsDbcp2DataSourcePoolMetadata(BasicDataSource dataSource) {
super(dataSource);
}
@Override
public @Nullable Integer getActive() {
return getDataSource().getNumActive();
}
@Override
public @Nullable Integer getIdle() {
return getDataSource().getNumIdle();
}
@Override
public @Nullable Integer getMax() {
return getDataSource().getMaxTotal(); | }
@Override
public @Nullable Integer getMin() {
return getDataSource().getMinIdle();
}
@Override
public @Nullable String getValidationQuery() {
return getDataSource().getValidationQuery();
}
@Override
public @Nullable Boolean getDefaultAutoCommit() {
return getDataSource().getDefaultAutoCommit();
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\CommonsDbcp2DataSourcePoolMetadata.java | 1 |
请完成以下Java代码 | public static final PostingExecutionException wrapIfNeeded(final Throwable throwable)
{
if (throwable == null)
{
return null;
}
else if (throwable instanceof PostingExecutionException)
{
return (PostingExecutionException)throwable;
}
else
{
final Throwable cause = extractCause(throwable);
if (cause instanceof PostingExecutionException)
{
return (PostingExecutionException)cause;
}
else
{
final String message = extractMessage(cause);
return new PostingExecutionException(message, cause);
}
}
}
public PostingExecutionException(final String message)
{
this(message, /* serverStackTrace */(String)null);
}
private PostingExecutionException(final String message, final String serverStackTrace)
{
super(buildMessage(message, serverStackTrace));
setIssueCategory(IssueCategory.ACCOUNTING);
} | private PostingExecutionException(final String message, final Throwable cause)
{
super(message, cause);
setIssueCategory(IssueCategory.ACCOUNTING);
}
private static final String buildMessage(final String message, final String serverStackTrace)
{
final StringBuilder sb = new StringBuilder();
sb.append(!Check.isEmpty(message) ? message.trim() : "unknow error");
if (!Check.isEmpty(serverStackTrace))
{
sb.append("\nServer stack trace: ").append(serverStackTrace.trim());
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\acct\PostingExecutionException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDATE1() {
return date1;
}
/**
* Sets the value of the date1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE1(String value) {
this.date1 = value;
}
/**
* Gets the value of the date2 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE2() {
return date2;
}
/**
* Sets the value of the date2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE2(String value) {
this.date2 = value;
}
/**
* Gets the value of the date3 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE3() {
return date3;
}
/**
* Sets the value of the date3 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE3(String value) {
this.date3 = value;
}
/**
* Gets the value of the date4 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE4() {
return date4;
}
/**
* Sets the value of the date4 property.
* | * @param value
* allowed object is
* {@link String }
*
*/
public void setDATE4(String value) {
this.date4 = value;
}
/**
* Gets the value of the date5 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDATE5() {
return date5;
}
/**
* Sets the value of the date5 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDATE5(String value) {
this.date5 = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DPLQU1.java | 2 |
请完成以下Java代码 | protected String getTargetTableName()
{
return I_C_Flatrate_Term.Table_Name;
}
@Override
protected String getImportOrderBySql()
{
return I_I_Flatrate_Term.COLUMNNAME_I_Flatrate_Term_ID;
}
@Override
protected void updateAndValidateImportRecordsImpl()
{
final ImportRecordsSelection selection = getImportRecordsSelection();
final String sqlImportWhereClause = ImportTableDescriptor.COLUMNNAME_I_IsImported + "<>" + DB.TO_BOOLEAN(true)
+ "\n " + selection.toSqlWhereClause("i");
FlatrateTermImportTableSqlUpdater.updateFlatrateTermImportTable(sqlImportWhereClause);
}
@Override
public I_I_Flatrate_Term retrieveImportRecord(final Properties ctx, final ResultSet rs)
{
final PO po = TableModelLoader.instance.getPO(ctx, I_I_Flatrate_Term.Table_Name, rs, ITrx.TRXNAME_ThreadInherited);
return InterfaceWrapperHelper.create(po, I_I_Flatrate_Term.class);
}
@Override
protected ImportRecordResult importRecord(final @NonNull IMutable<Object> state,
final @NonNull I_I_Flatrate_Term importRecord,
final boolean isInsertOnly /* not used. This import always inserts*/)
{ | flatRateImporter.importRecord(importRecord);
return ImportRecordResult.Inserted;
}
@Override
protected void markImported(final I_I_Flatrate_Term importRecord)
{
// NOTE: overriding the method from abstract class because in case of I_Flatrate_Term,
// * the I_IsImported is a List (as it should be) and not YesNo
// * there is no Processing column
importRecord.setI_IsImported(X_I_Flatrate_Term.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImportProcess.java | 1 |
请完成以下Java代码 | public long findLargestPowerOf2LessThanTheGivenNumberUsingLogBase2(long input) {
Assert.isTrue(input > 1, "Invalid input");
long temp = input;
if (input % 2 == 0) {
temp = input - 1;
}
// Find log base 2 of a given number
long power = (long) (Math.log(temp) / Math.log(2));
long result = (long) Math.pow(2, power);
return result;
}
public long findLargestPowerOf2LessThanTheGivenNumberUsingBitwiseAnd(long input) {
Assert.isTrue(input > 1, "Invalid input");
long result = 1;
for (long i = input - 1; i > 1; i--) {
if ((i & (i - 1)) == 0) {
result = i;
break; | }
}
return result;
}
public long findLargestPowerOf2LessThanTheGivenNumberUsingBitShiftApproach(long input) {
Assert.isTrue(input > 1, "Invalid input");
long result = 1;
long powerOf2;
for (long i = 0; i < Long.BYTES * 8; i++) {
powerOf2 = 1 << i;
if (powerOf2 >= input) {
break;
}
result = powerOf2;
}
return result;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\algorithms\largestpowerof2\LargestPowerOf2.java | 1 |
请完成以下Java代码 | private MigrationScriptFileLogger getWriter()
{
final MigrationScriptFileLogger temporaryLogger = temporaryMigrationScriptWriterHolder.get();
return temporaryLogger != null ? temporaryLogger : _pgMigrationScriptWriter;
}
public static Optional<Path> getCurrentScriptPathIfPresent()
{
return getWriter().getFilePathIfPresent();
}
@NonNull
public static Path getCurrentScriptPath()
{
return getCurrentScriptPathIfPresent()
.orElseThrow(() -> new AdempiereException("No current script file found"));
}
public static void closeMigrationScriptFiles()
{
getWriter().close();
}
public static void setMigrationScriptDirectory(@NonNull final Path path)
{
MigrationScriptFileLogger.setMigrationScriptDirectory(path);
}
public static Path getMigrationScriptDirectory()
{
return MigrationScriptFileLogger.getMigrationScriptDirectory();
}
private static boolean isSkipLogging(@NonNull final Sql sql)
{
return sql.isEmpty() || isSkipLogging(sql.getSqlCommand());
}
private static boolean isSkipLogging(@NonNull final String sqlCommand)
{
// Always log DDL (flagged) commands
if (sqlCommand.startsWith(DDL_PREFIX))
{
return false;
}
final String sqlCommandUC = sqlCommand.toUpperCase().trim();
//
// Don't log selects
if (sqlCommandUC.startsWith("SELECT ")) | {
return true;
}
//
// Don't log DELETE FROM Some_Table WHERE AD_Table_ID=? AND Record_ID=?
if (sqlCommandUC.startsWith("DELETE FROM ") && sqlCommandUC.endsWith(" WHERE AD_TABLE_ID=? AND RECORD_ID=?"))
{
return true;
}
//
// Check that INSERT/UPDATE/DELETE statements are about our ignored tables
final ImmutableSet<String> exceptionTablesUC = Services.get(IMigrationLogger.class).getTablesToIgnoreUC(Env.getClientIdOrSystem());
for (final String tableNameUC : exceptionTablesUC)
{
if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("DELETE FROM " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("DELETE " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("UPDATE " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + "("))
return true;
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLoggerHolder.java | 1 |
请完成以下Java代码 | public static String decrypt(String ciphertext, String password, String salt) {
Key key = getPbeKey(password);
byte[] passDec = null;
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT);
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
passDec = cipher.doFinal(hexStringToBytes(ciphertext));
}
catch (Exception e) {
// TODO: handle exception
}
return new String(passDec);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param src
* 字节数组
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 将十六进制字符串转换为字节数组
* | * @param hexString
* 十六进制字符串
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || "".equals(hexString)) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\PasswordUtil.java | 1 |
请完成以下Java代码 | private void refreshFromSource(PO sourcePO, int changeType)
{
final String sourceTableName = sourcePO.get_TableName();
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
for (I_AD_Table_MView mview : mviewBL.fetchAll(Env.getCtx()))
{
MViewMetadata mdata = mviewBL.getMetadata(mview);
if (mdata == null)
{
mview.setIsValid(false);
InterfaceWrapperHelper.save(mview);
log.info("No metadata found for " + mview + " [SKIP]");
continue;
}
if (!mdata.getSourceTables().contains(sourceTableName))
{
// not relevant PO for this MView
continue;
}
if (!mviewBL.isSourceChanged(mdata, sourcePO, changeType))
{
// no relevant changes for this view
continue;
}
refreshFromSource(mdata, sourcePO, new RefreshMode[] { RefreshMode.Partial });
}
}
public void refreshFromSource(MViewMetadata mdata, PO sourcePO, RefreshMode[] refreshModes)
{
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
final I_AD_Table_MView mview = mviewBL.fetchForTableName(sourcePO.getCtx(), mdata.getTargetTableName(), sourcePO.get_TrxName());
boolean staled = true;
for (RefreshMode refreshMode : refreshModes)
{
if (mviewBL.isAllowRefresh(mview, sourcePO, refreshMode))
{
mviewBL.refresh(mview, sourcePO, refreshMode, sourcePO.get_TrxName());
staled = false;
break;
}
}
//
// We should do a complete refresh => marking mview as staled
if (staled)
{
mviewBL.setStaled(mview);
}
}
private boolean addMView(I_AD_Table_MView mview, boolean invalidateIfNecessary) | {
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
MViewMetadata mdata = mviewBL.getMetadata(mview);
if (mdata == null)
{
// no metadata found => IGNORE
if (invalidateIfNecessary)
{
mview.setIsValid(false);
InterfaceWrapperHelper.save(mview);
}
return false;
}
for (String sourceTableName : mdata.getSourceTables())
{
engine.addModelChange(sourceTableName, this);
}
registeredTables.add(mview.getAD_Table_ID());
return true;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\engine\MViewModelValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataEntryRestController
{
private static final transient Logger log = LogManager.getLogger(DataEntryRestController.class);
private final DataEntryLayoutRepository layoutRepo;
private final DataEntryRecordCache dataRecords;
DataEntryRestController(
@NonNull final DataEntryLayoutRepository layoutRepo,
@NonNull final DataEntryRecordRepository recordsRepo,
@Value("${de.metas.dataentry.rest_api.DataEntryRestController.cacheCapacity:200}") final int cacheCapacity)
{
this.layoutRepo = layoutRepo;
this.dataRecords = new DataEntryRecordCache(recordsRepo, cacheCapacity);
}
@GetMapping("/byId/{windowId}/{recordId}")
public ResponseEntity<JsonDataEntryResponse> getByRecordId(
// with swagger 2.9.2, parameters are always ordered alphabetically, see https://github.com/springfox/springfox/issues/2418
@PathVariable("windowId") final int windowId,
@PathVariable("recordId") final int recordId)
{
final Stopwatch w = Stopwatch.createStarted();
final String adLanguage = RestApiUtilsV1.getAdLanguage();
final ResponseEntity<JsonDataEntryResponse> jsonDataEntry = getByRecordId0(AdWindowId.ofRepoId(windowId), recordId, adLanguage);
w.stop();
log.trace("getJsonDataEntry by {windowId '{}' and recordId '{}'} duration: {}", windowId, recordId, w);
return jsonDataEntry; | }
@VisibleForTesting
ResponseEntity<JsonDataEntryResponse> getByRecordId0(final AdWindowId windowId, final int recordId, final String adLanguage)
{
final DataEntryLayout layout = layoutRepo.getByWindowId(windowId);
if (layout.isEmpty())
{
return JsonDataEntryResponse.notFound(String.format("No dataentry for windowId '%d'.", windowId.getRepoId()));
}
final DataEntryRecordsMap records = dataRecords.get(recordId, layout.getSubTabIds());
if (records.getSubTabIds().isEmpty())
{
return JsonDataEntryResponse.notFound(String.format("No dataentry for windowId '%d' and recordId '%s'.", windowId.getRepoId(), recordId));
}
final JsonDataEntry jsonDataEntry = JsonDataEntryFactory.builder()
.layout(layout)
.records(records)
.adLanguage(adLanguage)
.build();
return JsonDataEntryResponse.ok(jsonDataEntry);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\dataentry\impl\DataEntryRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static <B extends HttpSecurityBuilder<B>> OAuth2AuthorizedClientService getAuthorizedClientServiceBean(
B builder) {
Map<String, OAuth2AuthorizedClientService> authorizedClientServiceMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(builder.getSharedObject(ApplicationContext.class),
OAuth2AuthorizedClientService.class);
if (authorizedClientServiceMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(OAuth2AuthorizedClientService.class,
authorizedClientServiceMap.size(),
"Expected single matching bean of type '" + OAuth2AuthorizedClientService.class.getName()
+ "' but found " + authorizedClientServiceMap.size() + ": "
+ StringUtils.collectionToCommaDelimitedString(authorizedClientServiceMap.keySet()));
}
return (!authorizedClientServiceMap.isEmpty() ? authorizedClientServiceMap.values().iterator().next() : null);
}
static <B extends HttpSecurityBuilder<B>> OidcSessionRegistry getOidcSessionRegistry(B builder) {
OidcSessionRegistry sessionRegistry = builder.getSharedObject(OidcSessionRegistry.class); | if (sessionRegistry != null) {
return sessionRegistry;
}
ApplicationContext context = builder.getSharedObject(ApplicationContext.class);
if (context.getBeanNamesForType(OidcSessionRegistry.class).length == 1) {
sessionRegistry = context.getBean(OidcSessionRegistry.class);
}
else {
sessionRegistry = new InMemoryOidcSessionRegistry();
}
builder.setSharedObject(OidcSessionRegistry.class, sessionRegistry);
return sessionRegistry;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\client\OAuth2ClientConfigurerUtils.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected final B getBuilder() {
Assert.state(this.securityBuilder != null, "securityBuilder cannot be null");
return this.securityBuilder;
}
/**
* Performs post processing of an object. The default is to delegate to the
* {@link ObjectPostProcessor}.
* @param object the Object to post process
* @return the possibly modified Object to use
*/
@SuppressWarnings("unchecked")
protected <T> T postProcess(T object) {
return (T) this.objectPostProcessor.postProcess(object);
}
/**
* Adds an {@link ObjectPostProcessor} to be used for this
* {@link SecurityConfigurerAdapter}. The default implementation does nothing to the
* object.
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
*/
public void addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.objectPostProcessor.addObjectPostProcessor(objectPostProcessor);
}
/**
* Sets the {@link SecurityBuilder} to be used. This is automatically set when using
* {@link AbstractConfiguredSecurityBuilder#with(SecurityConfigurerAdapter, Customizer)}
* @param builder the {@link SecurityBuilder} to set
*/
public void setBuilder(B builder) {
this.securityBuilder = builder;
}
/**
* An {@link ObjectPostProcessor} that delegates work to numerous
* {@link ObjectPostProcessor} implementations.
*
* @author Rob Winch
*/
private static final class CompositeObjectPostProcessor implements ObjectPostProcessor<Object> {
private List<ObjectPostProcessor<?>> postProcessors = new ArrayList<>();
@Override | @SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) {
for (ObjectPostProcessor opp : this.postProcessors) {
Class<?> oppClass = opp.getClass();
Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
object = opp.postProcess(object);
}
}
return object;
}
/**
* Adds an {@link ObjectPostProcessor} to use
* @param objectPostProcessor the {@link ObjectPostProcessor} to add
* @return true if the {@link ObjectPostProcessor} was added, else false
*/
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\SecurityConfigurerAdapter.java | 2 |
请完成以下Java代码 | private List<I_C_CountryArea_Assign> retrieveCountryAreaAssignments(final I_C_CountryArea countryArea, final int countryId)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(countryArea);
final String trxName = InterfaceWrapperHelper.getTrxName(countryArea);
final int countryAreaId = countryArea.getC_CountryArea_ID();
final List<I_C_CountryArea_Assign> result = new ArrayList<>();
for (final I_C_CountryArea_Assign assignment : retrieveCountryAreaAssignments(ctx, countryAreaId, trxName))
{
if (assignment.getC_Country_ID() == countryId)
{
result.add(assignment);
}
}
return result;
}
@Override
public void validate(final I_C_CountryArea_Assign assignment)
{
final I_C_CountryArea countryArea = assignment.getC_CountryArea();
for (final I_C_CountryArea_Assign instance : retrieveCountryAreaAssignments(countryArea, assignment.getC_Country_ID()))
{
if (isTimeConflict(assignment, instance))
{
throw new AdempiereException("Period overlaps with existing period: " + instance.getValidFrom()
+ ((instance.getValidTo() == null) ? "" : (" to " + instance.getValidTo()))
+ " for the country " + assignment.getC_Country() + " in area " + countryArea.getName());
}
}
}
/**
* @param newEntry
* @param oldEntry
* @return true if <code>newEntry</code>'s and <code>oldEntry</code>'s date/time intervals are overlapping
*/
protected boolean isTimeConflict(final I_C_CountryArea_Assign newEntry, final I_C_CountryArea_Assign oldEntry)
{
if (newEntry.equals(oldEntry))
{
return false; | }
if (newEntry.getValidFrom().compareTo(oldEntry.getValidFrom()) <= 0)
{
return (newEntry.getValidTo() == null) || (newEntry.getValidTo().compareTo(oldEntry.getValidFrom()) > 0);
}
else
{
return (oldEntry.getValidTo() == null) || (oldEntry.getValidTo().compareTo(newEntry.getValidFrom()) > 0);
}
}
public boolean isMemberOf(@NonNull final CountryAreaId countryAreaId, @NonNull final CountryId countryId)
{
return retrieveCountryAreaAssignments(Env.getCtx(), countryAreaId.getRepoId(), ITrx.TRXNAME_None)
.stream()
.map(I_C_CountryArea_Assign::getC_Country_ID)
.map(CountryId::ofRepoId)
.anyMatch(countryId::equals);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impl\CountryAreaBL.java | 1 |
请完成以下Java代码 | protected void ensureResourcesWithIdsExist(String deploymentId, Set<String> expectedIds, List<ResourceEntity> actual) {
Map<String, ResourceEntity> resources = new HashMap<>();
for (ResourceEntity resource : actual) {
resources.put(resource.getId(), resource);
}
ensureResourcesWithKeysExist(deploymentId, expectedIds, resources, "id");
}
protected void ensureResourcesWithNamesExist(String deploymentId, Set<String> expectedNames, List<ResourceEntity> actual) {
Map<String, ResourceEntity> resources = new HashMap<>();
for (ResourceEntity resource : actual) {
resources.put(resource.getName(), resource);
}
ensureResourcesWithKeysExist(deploymentId, expectedNames, resources, "name");
} | protected void ensureResourcesWithKeysExist(String deploymentId, Set<String> expectedKeys, Map<String, ResourceEntity> actual, String valueProperty) {
List<String> missingResources = getMissingElements(expectedKeys, actual);
if (!missingResources.isEmpty()) {
StringBuilder builder = new StringBuilder();
builder.append("The deployment with id '");
builder.append(deploymentId);
builder.append("' does not contain the following resources with ");
builder.append(valueProperty);
builder.append(": ");
builder.append(StringUtil.join(missingResources.iterator()));
throw new NotFoundException(builder.toString());
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeployCmd.java | 1 |
请完成以下Java代码 | public void setUserDetailsChecker(UserDetailsChecker userDetailsChecker) {
this.userDetailsChecker = userDetailsChecker;
}
/**
* Allows the parameter containing the username to be customized.
* @param usernameParameter the parameter name. Defaults to {@code username}
*/
public void setUsernameParameter(String usernameParameter) {
this.usernameParameter = usernameParameter;
}
/**
* Allows the role of the switchAuthority to be customized.
* @param switchAuthorityRole the role name. Defaults to
* {@link #ROLE_PREVIOUS_ADMINISTRATOR}
*/
public void setSwitchAuthorityRole(String switchAuthorityRole) {
Assert.notNull(switchAuthorityRole, "switchAuthorityRole cannot be null");
this.switchAuthorityRole = switchAuthorityRole;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/** | * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on
* switch user success. The default is
* {@link RequestAttributeSecurityContextRepository}.
* @param securityContextRepository the {@link SecurityContextRepository} to use.
* Cannot be null.
* @since 5.7.7
*/
public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
private static RequestMatcher createMatcher(String pattern) {
return pathPattern(HttpMethod.POST, pattern);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\switchuser\SwitchUserFilter.java | 1 |
请完成以下Java代码 | public static void writeDocument(final Writer writer, final Node node)
{
// Construct Transformer Factory and Transformer
final TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer;
try
{
aTransformer = tranFactory.newTransformer();
}
catch (final TransformerConfigurationException e)
{
throw new AdempiereException(e);
}
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); | final Source src = new DOMSource(node);
// =================================== Write to String
// Writer writer = new StringWriter();
final Result dest2 = new StreamResult(writer);
try
{
aTransformer.transform(src, dest2);
}
catch (final TransformerException e)
{
throw new AdempiereException(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\XMLHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void putMediaConvertCache(String key, String value) {
mediaConvertCache.put(key, value);
}
@Override
public String getMediaConvertCache(String key) {
return mediaConvertCache.get(key);
}
@Override
public void cleanCache() {
initPDFCachePool(CacheService.DEFAULT_PDF_CAPACITY);
initIMGCachePool(CacheService.DEFAULT_IMG_CAPACITY);
initPdfImagesCachePool(CacheService.DEFAULT_PDFIMG_CAPACITY);
initMediaConvertCachePool(CacheService.DEFAULT_MEDIACONVERT_CAPACITY);
}
@Override
public void addQueueTask(String url) {
blockingQueue.add(url);
}
@Override
public String takeQueueTask() throws InterruptedException {
return blockingQueue.take();
}
@Override
public void initPDFCachePool(Integer capacity) {
pdfCache = new ConcurrentLinkedHashMap.Builder<String, String>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton()) | .build();
}
@Override
public void initIMGCachePool(Integer capacity) {
imgCache = new ConcurrentLinkedHashMap.Builder<String, List<String>>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
@Override
public void initPdfImagesCachePool(Integer capacity) {
pdfImagesCache = new ConcurrentLinkedHashMap.Builder<String, Integer>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
@Override
public void initMediaConvertCachePool(Integer capacity) {
mediaConvertCache = new ConcurrentLinkedHashMap.Builder<String, String>()
.maximumWeightedCapacity(capacity).weigher(Weighers.singleton())
.build();
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceJDKImpl.java | 2 |
请完成以下Java代码 | public class SetParameterRequestWrapper extends HttpServletRequestWrapper {
private final Map<String, String[]> paramMap;
public SetParameterRequestWrapper(HttpServletRequest request) {
super(request);
paramMap = new HashMap<>(request.getParameterMap());
}
@Override
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(paramMap);
}
@Override
public String[] getParameterValues(String name) {
return Optional.ofNullable(getParameterMap().get(name)) | .map(values -> Arrays.copyOf(values, values.length))
.orElse(null);
}
@Override
public String getParameter(String name) {
return Optional.ofNullable(getParameterValues(name))
.map(values -> values[0])
.orElse(null);
}
public void setParameter(String name, String value) {
paramMap.put(name, new String[] {value});
}
} | repos\tutorials-master\web-modules\jakarta-servlets\src\main\java\com\baeldung\setparam\SetParameterRequestWrapper.java | 1 |
请完成以下Java代码 | public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public blink addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public blink addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/** | Adds an Element to the element.
@param element Adds an Element to the element.
*/
public blink addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public blink addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public blink removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\blink.java | 1 |
请完成以下Java代码 | 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 setSectionName (final java.lang.String SectionName)
{
set_Value (COLUMNNAME_SectionName, SectionName);
}
@Override
public java.lang.String getSectionName() | {
return get_ValueAsString(COLUMNNAME_SectionName);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Section.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyOrdered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Region.
@param RegionName
Name of the Region
*/
public void setRegionName (String RegionName)
{
set_Value (COLUMNNAME_RegionName, RegionName);
}
/** Get Region.
@return Name of the Region
*/
public String getRegionName ()
{
return (String)get_Value(COLUMNNAME_RegionName);
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SKU.
@param SKU
Stock Keeping Unit
*/
public void setSKU (String SKU)
{
set_Value (COLUMNNAME_SKU, SKU);
} | /** Get SKU.
@return Stock Keeping Unit
*/
public String getSKU ()
{
return (String)get_Value(COLUMNNAME_SKU);
}
/** Set Tax Amount.
@param TaxAmt
Tax Amount for a document
*/
public void setTaxAmt (BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
/** Get Tax Amount.
@return Tax Amount for a document
*/
public BigDecimal getTaxAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TaxAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Tax Indicator.
@param TaxIndicator
Short form for Tax to be printed on documents
*/
public void setTaxIndicator (String TaxIndicator)
{
set_Value (COLUMNNAME_TaxIndicator, TaxIndicator);
}
/** Get Tax Indicator.
@return Short form for Tax to be printed on documents
*/
public String getTaxIndicator ()
{
return (String)get_Value(COLUMNNAME_TaxIndicator);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Invoice.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getCreated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Created_Print_Job_Instructions);
}
@Override
public void setPrintServiceName (java.lang.String PrintServiceName)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceName, PrintServiceName);
}
@Override
public java.lang.String getPrintServiceName()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceName);
}
@Override
public void setPrintServiceTray (java.lang.String PrintServiceTray)
{
set_ValueNoCheck (COLUMNNAME_PrintServiceTray, PrintServiceTray);
}
@Override
public java.lang.String getPrintServiceTray()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintServiceTray);
}
@Override
public void setStatus_Print_Job_Instructions (boolean Status_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Status_Print_Job_Instructions, Boolean.valueOf(Status_Print_Job_Instructions));
}
@Override
public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
} | @Override
public void setUpdatedby_Print_Job_Instructions (int Updatedby_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updatedby_Print_Job_Instructions, Integer.valueOf(Updatedby_Print_Job_Instructions));
}
@Override
public int getUpdatedby_Print_Job_Instructions()
{
return get_ValueAsInt(COLUMNNAME_Updatedby_Print_Job_Instructions);
}
@Override
public void setUpdated_Print_Job_Instructions (java.sql.Timestamp Updated_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updated_Print_Job_Instructions, Updated_Print_Job_Instructions);
}
@Override
public java.sql.Timestamp getUpdated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Updated_Print_Job_Instructions);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_PrintInfo_v.java | 1 |
请完成以下Java代码 | public class ClusterServerModifyRequest implements ClusterModifyRequest {
private String app;
private String ip;
private Integer port;
private Integer mode;
private ServerFlowConfig flowConfig;
private ServerTransportConfig transportConfig;
private Set<String> namespaceSet;
@Override
public String getApp() {
return app;
}
public ClusterServerModifyRequest setApp(String app) {
this.app = app;
return this;
}
@Override
public String getIp() {
return ip;
}
public ClusterServerModifyRequest setIp(String ip) {
this.ip = ip;
return this;
}
@Override
public Integer getPort() {
return port;
}
public ClusterServerModifyRequest setPort(Integer port) {
this.port = port;
return this;
}
@Override
public Integer getMode() {
return mode;
}
public ClusterServerModifyRequest setMode(Integer mode) {
this.mode = mode;
return this;
}
public ServerFlowConfig getFlowConfig() {
return flowConfig;
}
public ClusterServerModifyRequest setFlowConfig(
ServerFlowConfig flowConfig) { | this.flowConfig = flowConfig;
return this;
}
public ServerTransportConfig getTransportConfig() {
return transportConfig;
}
public ClusterServerModifyRequest setTransportConfig(
ServerTransportConfig transportConfig) {
this.transportConfig = transportConfig;
return this;
}
public Set<String> getNamespaceSet() {
return namespaceSet;
}
public ClusterServerModifyRequest setNamespaceSet(Set<String> namespaceSet) {
this.namespaceSet = namespaceSet;
return this;
}
@Override
public String toString() {
return "ClusterServerModifyRequest{" +
"app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", mode=" + mode +
", flowConfig=" + flowConfig +
", transportConfig=" + transportConfig +
", namespaceSet=" + namespaceSet +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterServerModifyRequest.java | 1 |
请完成以下Java代码 | public void setAD_Printer_Config_Shared_ID (int AD_Printer_Config_Shared_ID)
{
if (AD_Printer_Config_Shared_ID < 1)
set_Value (COLUMNNAME_AD_Printer_Config_Shared_ID, null);
else
set_Value (COLUMNNAME_AD_Printer_Config_Shared_ID, Integer.valueOf(AD_Printer_Config_Shared_ID));
}
@Override
public int getAD_Printer_Config_Shared_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Config_Shared_ID);
}
@Override
public void setAD_User_PrinterMatchingConfig_ID (int AD_User_PrinterMatchingConfig_ID)
{
if (AD_User_PrinterMatchingConfig_ID < 1)
set_Value (COLUMNNAME_AD_User_PrinterMatchingConfig_ID, null);
else
set_Value (COLUMNNAME_AD_User_PrinterMatchingConfig_ID, Integer.valueOf(AD_User_PrinterMatchingConfig_ID));
}
@Override
public int getAD_User_PrinterMatchingConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_PrinterMatchingConfig_ID);
}
@Override
public void setConfigHostKey (java.lang.String ConfigHostKey)
{
set_Value (COLUMNNAME_ConfigHostKey, ConfigHostKey);
}
@Override
public java.lang.String getConfigHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_ConfigHostKey);
}
@Override
public void setIsSharedPrinterConfig (boolean IsSharedPrinterConfig)
{
set_Value (COLUMNNAME_IsSharedPrinterConfig, Boolean.valueOf(IsSharedPrinterConfig)); | }
@Override
public boolean isSharedPrinterConfig()
{
return get_ValueAsBoolean(COLUMNNAME_IsSharedPrinterConfig);
}
@Override
public org.compiere.model.I_C_Workplace getC_Workplace()
{
return get_ValueAsPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class);
}
@Override
public void setC_Workplace(final org.compiere.model.I_C_Workplace C_Workplace)
{
set_ValueFromPO(COLUMNNAME_C_Workplace_ID, org.compiere.model.I_C_Workplace.class, C_Workplace);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Config.java | 1 |
请完成以下Java代码 | public ExecuteReportResult executeReport(
@NonNull final ProcessInfo processInfo,
@NonNull final OutputType outputType)
{
final DunningDocId dunningDocId = DunningDocId.ofRepoId(processInfo.getRecord_ID());
final Resource dunningDocData = ExecuteReportStrategyUtil.executeJasperProcess(dunningDocJasperProcessId, processInfo, outputType);
final boolean isPDF = OutputType.PDF.equals(outputType);
if (!isPDF)
{
Loggables.withLogger(logger, Level.WARN).addLog("Concatenating additional PDF-Data is not supported with outputType={}; returning only the jasper data itself.", outputType);
return ExecuteReportResult.of(outputType, dunningDocData);
}
final DunningService dunningService = SpringContextHolder.instance.getBean(DunningService.class);
final List<I_C_Invoice> dunnedInvoices = dunningService.retrieveDunnedInvoices(dunningDocId);
final List<PdfDataProvider> additionalDataItemsToAttach = retrieveAdditionalDataItems(dunnedInvoices);
final Resource data = ExecuteReportStrategyUtil.concatenatePDF(dunningDocData, additionalDataItemsToAttach);
return ExecuteReportResult.of(outputType, data); | }
private List<PdfDataProvider> retrieveAdditionalDataItems(@NonNull final List<I_C_Invoice> dunnedInvoices)
{
final ImmutableList.Builder<PdfDataProvider> result = ImmutableList.builder();
for (final I_C_Invoice invoice : dunnedInvoices)
{
final TableRecordReference invoiceRef = TableRecordReference.of(invoice);
final Resource data = archiveBL.getLastArchiveBinaryData(invoiceRef).orElse(null);
if(data == null)
{
continue;
}
result.add(PdfDataProvider.forData(data));
}
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_DunningDoc_JasperWithInvoicePDFsStrategy.java | 1 |
请完成以下Java代码 | public void setDescription(String description) {
this.description = description;
}
public String getId() {
return this.id;
}
public ServiceCapabilityType getType() {
return this.type;
}
/**
* Return the "content" of this capability. The structure of the content vastly
* depends on the {@link ServiceCapability type} of the capability.
* @return the content
*/
public abstract T getContent();
/**
* Merge the content of this instance with the specified content.
* @param otherContent the content to merge
* @see #merge(io.spring.initializr.metadata.ServiceCapability)
*/
public abstract void merge(T otherContent);
/**
* Merge this capability with the specified argument. The service capabilities should
* match (i.e have the same {@code id} and {@code type}). Sub-classes may merge | * additional content.
* @param other the content to merge
*/
public void merge(ServiceCapability<T> other) {
Assert.notNull(other, "Other must not be null");
Assert.isTrue(this.id.equals(other.id), "Ids must be equals");
Assert.isTrue(this.type.equals(other.type), "Types must be equals");
if (StringUtils.hasText(other.title)) {
this.title = other.title;
}
if (StringUtils.hasText(other.description)) {
this.description = other.description;
}
merge(other.getContent());
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\ServiceCapability.java | 1 |
请完成以下Java代码 | public class DelegatingJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
private final Collection<Converter<Jwt, Collection<GrantedAuthority>>> authoritiesConverters;
/**
* Constructs a {@link DelegatingJwtGrantedAuthoritiesConverter} using the provided
* {@link Collection} of {@link Converter}s
* @param authoritiesConverters the {@link Collection} of {@link Converter}s to use
*/
public DelegatingJwtGrantedAuthoritiesConverter(
Collection<Converter<Jwt, Collection<GrantedAuthority>>> authoritiesConverters) {
Assert.notNull(authoritiesConverters, "authoritiesConverters cannot be null");
this.authoritiesConverters = new ArrayList<>(authoritiesConverters);
}
/**
* Constructs a {@link DelegatingJwtGrantedAuthoritiesConverter} using the provided
* array of {@link Converter}s
* @param authoritiesConverters the array of {@link Converter}s to use
*/
@SafeVarargs
public DelegatingJwtGrantedAuthoritiesConverter(
Converter<Jwt, Collection<GrantedAuthority>>... authoritiesConverters) {
this(Arrays.asList(authoritiesConverters));
}
/**
* Extract {@link GrantedAuthority}s from the given {@link Jwt}.
* <p>
* The authorities are extracted from each delegated {@link Converter} one at a time.
* For each converter, its authorities are added in order, with duplicates removed. | * @param jwt The {@link Jwt} token
* @return The {@link GrantedAuthority authorities} read from the token scopes
*/
@Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
Collection<GrantedAuthority> result = new LinkedHashSet<>();
for (Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter : this.authoritiesConverters) {
Collection<GrantedAuthority> authorities = authoritiesConverter.convert(jwt);
if (authorities != null) {
result.addAll(authorities);
}
}
return result;
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\DelegatingJwtGrantedAuthoritiesConverter.java | 1 |
请完成以下Java代码 | public void deleteAll() {
repository.deleteAll();
}
public List<S> saveAll(Iterable<S> entities) {
return repository.saveAll(entities);
}
public List<S> findAll() {
return repository.findAll();
}
public Optional<S> getUserByIdWithPredicate(long id, Predicate<S> predicate) {
Optional<S> user = repository.findById(id);
user.ifPresent(predicate::test);
return user; | }
public int getUserByIdWithFunction(Long id, ToIntFunction<S> function) {
Optional<S> optionalUser = repository.findById(id);
if (optionalUser.isPresent()) {
return function.applyAsInt(optionalUser.get());
} else {
return 0;
}
}
public void save(S entity) {
repository.save(entity);
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-2\src\main\java\com\baeldung\listvsset\Service.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public I_M_ShipmentSchedule getByIdAsRecord(@NonNull final ShipmentScheduleId id)
{
return huShipmentScheduleBL.getById(id);
}
public Quantity getQtyToDeliver(@NonNull final I_M_ShipmentSchedule schedule)
{
return huShipmentScheduleBL.getQtyToDeliver(schedule);
}
public Quantity getQtyScheduledForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
return huShipmentScheduleBL.getQtyScheduledForPicking(shipmentScheduleRecord);
}
public ImmutableList<ShipmentSchedule> getBy(@NonNull final ShipmentScheduleQuery query)
{
return shipmentScheduleRepository.getBy(query);
}
private ShipmentScheduleInfo fromRecord(final I_M_ShipmentSchedule shipmentSchedule)
{
return ShipmentScheduleInfo.builder()
.clientAndOrgId(ClientAndOrgId.ofClientAndOrg(shipmentSchedule.getAD_Client_ID(), shipmentSchedule.getAD_Org_ID()))
.warehouseId(shipmentScheduleBL.getWarehouseId(shipmentSchedule))
.bpartnerId(shipmentScheduleBL.getBPartnerId(shipmentSchedule))
.salesOrderLineId(Optional.ofNullable(OrderLineId.ofRepoIdOrNull(shipmentSchedule.getC_OrderLine_ID())))
.productId(ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()))
.asiId(AttributeSetInstanceId.ofRepoIdOrNone(shipmentSchedule.getM_AttributeSetInstance_ID()))
.bestBeforePolicy(ShipmentAllocationBestBeforePolicy.optionalOfNullableCode(shipmentSchedule.getShipmentAllocation_BestBefore_Policy()))
.record(shipmentSchedule)
.build();
}
public void addQtyPickedAndUpdateHU(final AddQtyPickedRequest request)
{
huShipmentScheduleBL.addQtyPickedAndUpdateHU(request);
}
public void deleteByTopLevelHUsAndShipmentScheduleId(@NonNull final Collection<I_M_HU> topLevelHUs, @NonNull final ShipmentScheduleId shipmentScheduleId) | {
huShipmentScheduleBL.deleteByTopLevelHUsAndShipmentScheduleId(topLevelHUs, shipmentScheduleId);
}
public Stream<Packageable> stream(@NonNull final PackageableQuery query)
{
return packagingDAO.stream(query);
}
public Quantity getQtyRemainingToScheduleForPicking(@NonNull final I_M_ShipmentSchedule shipmentScheduleRecord)
{
return huShipmentScheduleBL.getQtyRemainingToScheduleForPicking(shipmentScheduleRecord);
}
public void flagForRecompute(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds)
{
huShipmentScheduleBL.flagForRecompute(shipmentScheduleIds);
}
public ShipmentScheduleLoadingCache<de.metas.handlingunits.model.I_M_ShipmentSchedule> newHuShipmentLoadingCache()
{
return huShipmentScheduleBL.newLoadingCache();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\shipmentschedule\PickingJobShipmentScheduleService.java | 2 |
请完成以下Java代码 | public List<String> getMessageParts() {
if (message == null) {
return null;
}
List<String> messageParts = new ArrayList<String>();
String[] parts = MESSAGE_PARTS_MARKER_REGEX.split(message);
for (String part : parts) {
if ("null".equals(part)) {
messageParts.add(null);
} else {
messageParts.add(part);
}
}
return messageParts;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getProcessInstanceId() {
return processInstanceId; | }
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityImpl.java | 1 |
请完成以下Spring Boot application配置 | #
# use this port on order to not collide with the ports of other metasfresh services that might run in the same box
# also note that this is the port that we have to app in the default docker-compose.yml
server.port=8282
#
# Tomcat
#
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force-response=true
# because of infrastructure-reasons it's currently not easy to make the actuator available on /actuator/info
# thx to https://www.allprogrammingtutorials.com/tutorials/mapping-boot-endpoints-to-custom-path.php on how to change it back to the way it was with spring-boot-1
# also see https://github.com/metasfresh/metasfresh/issues/10969
management.endpoints.web.base-path=/
#
# actuator-endpoints
#
management.endpoints.web.exposure.include=*
# --------------------------------------------------------------------------------
# Build info
# --------------------------------------------------------------------------------
info.build.projectName=metasfresh-dist
info.build.ciBuildNo=@env.BUILD_NUMBER@
info.build.ciBuildTag=@env.BUILD_TAG@
info.build.ciBuildUrl=@env.BUILD_URL@
info.build.ciJobName=@env.JOB_NAME@
# --------------------------------------------------------------------------------
# Logging
# --------------------------------------------------------------------------------
#logging.path=f:/
# Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
#logging.config=file:./logback.xml
#
# - metasfresh
logging.level.root=INFO
#logging.level.de.metas=INFO
#logging.level.org.adempiere=INFO
#logging.level.org.compiere=INFO
#logging.level.org.eevolution=INFO
#logging.level.org.adempiere.ad.housekeeping=INFO
#logging.level.org.compiere.model=INFO
# ---------------------------------------------------------------------- | ----------
# Elasticsearch
# --------------------------------------------------------------------------------
metasfresh.elasticsearch.host=search:9200
# --------------------------------------------------------------------------------
# RabbitMQ
# --------------------------------------------------------------------------------
# Goal: make sure to have strict in-order processing of messages
# Source for property-names: https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/appendix-application-properties.html#common-application-properties
spring.rabbitmq.listener.direct.consumers-per-queue=1
spring.rabbitmq.listener.direct.prefetch=1
spring.rabbitmq.listener.simple.max-concurrency=1
spring.rabbitmq.listener.simple.prefetch=1
server.tomcat.threads.max=10 | repos\metasfresh-new_dawn_uat\backend\metasfresh-dist\base\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static String toUUIDString(final I_PMM_Product pmmProduct)
{
return UUIDs.fromIdAsString(pmmProduct.getPMM_Product_ID());
}
public static int getPMM_Product_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
public static String toUUIDString(final I_C_Flatrate_Term contract)
{
return UUIDs.fromIdAsString(contract.getC_Flatrate_Term_ID());
}
public static int getC_Flatrate_Term_ID(final String uuid)
{
return UUIDs.toId(uuid);
} | public static String toUUIDString(final I_C_RfQResponseLine rfqResponseLine)
{
return toC_RfQReponseLine_UUID(rfqResponseLine.getC_RfQResponseLine_ID());
}
public static String toC_RfQReponseLine_UUID(final int C_RfQResponseLine_ID)
{
return UUIDs.fromIdAsString(C_RfQResponseLine_ID);
}
public static int getC_RfQResponseLine_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncUUIDs.java | 1 |
请完成以下Java代码 | static class SpringCacheWrapper implements Cache {
private org.springframework.cache.Cache springCache;
SpringCacheWrapper(org.springframework.cache.Cache springCache) {
this.springCache = springCache;
}
@Override
public Object get(Object key) throws CacheException {
Object value = springCache.get(key);
if (value instanceof SimpleValueWrapper) {
return ((SimpleValueWrapper) value).get();
}
return value;
}
@Override
public Object put(Object key, Object value) throws CacheException {
springCache.put(key, value);
return value;
}
@Override
public Object remove(Object key) throws CacheException {
springCache.evict(key);
return null;
}
@Override
public void clear() throws CacheException {
springCache.clear();
}
@Override
public int size() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return ehcache.getSize();
}
throw new UnsupportedOperationException("invoke spring cache abstract size method not supported");
}
@SuppressWarnings("unchecked")
@Override | public Set keys() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return new HashSet(ehcache.getKeys());
}
throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
}
@SuppressWarnings("unchecked")
@Override
public Collection values() {
if (springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
List keys = ehcache.getKeys();
if (!CollectionUtils.isEmpty(keys)) {
List values = new ArrayList(keys.size());
for (Object key : keys) {
Object value = get(key);
if (value != null) {
values.add(value);
}
}
return Collections.unmodifiableList(values);
} else {
return Collections.emptyList();
}
}
throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");
}
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\spring\SpringCacheManagerWrapper.java | 1 |
请完成以下Java代码 | public static Period detectAndParse(String value) {
return detectAndParse(value, null);
}
/**
* Detect the style then parse the value to return a period.
* @param value the value to parse
* @param unit the period unit to use if the value doesn't specify one ({@code null}
* will default to ms)
* @return the parsed period
* @throws IllegalArgumentException if the value is not a known style or cannot be
* parsed
*/
public static Period detectAndParse(String value, @Nullable ChronoUnit unit) {
return detect(value).parse(value, unit);
}
/**
* Detect the style from the given source value.
* @param value the source value
* @return the period style
* @throws IllegalArgumentException if the value is not a known style
*/
public static PeriodStyle detect(String value) {
Assert.notNull(value, "'value' must not be null");
for (PeriodStyle candidate : values()) {
if (candidate.matches(value)) {
return candidate;
}
}
throw new IllegalArgumentException("'" + value + "' is not a valid period");
}
private enum Unit {
/**
* Days, represented by suffix {@code d}.
*/
DAYS(ChronoUnit.DAYS, "d", Period::getDays, Period::ofDays),
/**
* Weeks, represented by suffix {@code w}.
*/
WEEKS(ChronoUnit.WEEKS, "w", null, Period::ofWeeks),
/**
* Months, represented by suffix {@code m}.
*/
MONTHS(ChronoUnit.MONTHS, "m", Period::getMonths, Period::ofMonths),
/**
* Years, represented by suffix {@code y}.
*/
YEARS(ChronoUnit.YEARS, "y", Period::getYears, Period::ofYears);
private final ChronoUnit chronoUnit;
private final String suffix;
private final @Nullable Function<Period, Integer> intValue;
private final Function<Integer, Period> factory;
Unit(ChronoUnit chronoUnit, String suffix, @Nullable Function<Period, Integer> intValue,
Function<Integer, Period> factory) {
this.chronoUnit = chronoUnit;
this.suffix = suffix;
this.intValue = intValue;
this.factory = factory; | }
private Period parse(String value) {
return this.factory.apply(Integer.parseInt(value));
}
private String print(Period value) {
return intValue(value) + this.suffix;
}
private boolean isZero(Period value) {
return intValue(value) == 0;
}
private int intValue(Period value) {
Assert.state(this.intValue != null, () -> "intValue cannot be extracted from " + name());
return this.intValue.apply(value);
}
private static Unit fromChronoUnit(@Nullable ChronoUnit chronoUnit) {
if (chronoUnit == null) {
return Unit.DAYS;
}
for (Unit candidate : values()) {
if (candidate.chronoUnit == chronoUnit) {
return candidate;
}
}
throw new IllegalArgumentException("Unsupported unit " + chronoUnit);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\PeriodStyle.java | 1 |
请完成以下Java代码 | public void setPicking_User_ID (final int Picking_User_ID)
{
if (Picking_User_ID < 1)
set_Value (COLUMNNAME_Picking_User_ID, null);
else
set_Value (COLUMNNAME_Picking_User_ID, Picking_User_ID);
}
@Override
public int getPicking_User_ID()
{
return get_ValueAsInt(COLUMNNAME_Picking_User_ID);
}
@Override
public void setPreparationDate (final @Nullable java.sql.Timestamp PreparationDate)
{
set_Value (COLUMNNAME_PreparationDate, PreparationDate);
} | @Override
public java.sql.Timestamp getPreparationDate()
{
return get_ValueAsTimestamp(COLUMNNAME_PreparationDate);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job.java | 1 |
请完成以下Java代码 | public Thread createUserThread(final Runnable runnable, final String threadName)
{
return getCurrentInstance().createUserThread(runnable, threadName);
}
@Override
public String getClientInfo()
{
return getCurrentInstance().getClientInfo();
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}.
*/
@Deprecated
@Override
public void hideBusyDialog()
{
// nothing
}
@Override
public void showWindow(final Object model)
{
getCurrentInstance().showWindow(model);
}
@Override
public void executeLongOperation(final Object component, final Runnable runnable)
{
getCurrentInstance().executeLongOperation(component, runnable);
} | @Override
public IClientUIInvoker invoke()
{
return getCurrentInstance().invoke();
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
return getCurrentInstance().invokeAsync();
}
@Override
public void showURL(String url)
{
getCurrentInstance().showURL(url);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUI.java | 1 |
请完成以下Java代码 | public String getAddress() {
return super.getAddress();
}
@Schema(description = "Address Line 2", example = "")
@Override
public String getAddress2() {
return super.getAddress2();
}
@Schema(description = "Zip code", example = "10004")
@Override
public String getZip() {
return super.getZip();
}
@Schema(description = "Phone number", example = "+1(415)777-7777")
@Override
public String getPhone() {
return super.getPhone();
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Email", example = "example@company.com")
@Override
public String getEmail() {
return super.getEmail();
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
@JsonIgnore
public boolean isPublic() {
if (getAdditionalInfo() != null && getAdditionalInfo().has("isPublic")) {
return getAdditionalInfo().get("isPublic").asBoolean();
}
return false;
}
@JsonIgnore
public ShortCustomerInfo toShortCustomerInfo() {
return new ShortCustomerInfo(id, title, isPublic()); | }
@Override
@JsonProperty(access = Access.READ_ONLY)
@Schema(description = "Name of the customer. Read-only, duplicated from title for backward compatibility", example = "Company A", accessMode = Schema.AccessMode.READ_ONLY)
public String getName() {
return title;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [title=");
builder.append(title);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", additionalInfo=");
builder.append(getAdditionalInfo());
builder.append(", country=");
builder.append(country);
builder.append(", state=");
builder.append(state);
builder.append(", city=");
builder.append(city);
builder.append(", address=");
builder.append(address);
builder.append(", address2=");
builder.append(address2);
builder.append(", zip=");
builder.append(zip);
builder.append(", phone=");
builder.append(phone);
builder.append(", email=");
builder.append(email);
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Customer.java | 1 |
请完成以下Java代码 | public void setAD_Column(final org.compiere.model.I_AD_Column AD_Column)
{
set_ValueFromPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class, AD_Column);
}
@Override
public void setAD_Column_ID (final int AD_Column_ID)
{
if (AD_Column_ID < 1)
set_Value (COLUMNNAME_AD_Column_ID, null);
else
set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID);
}
@Override
public int getAD_Column_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Column_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setWEBUI_Board_CardField_ID (final int WEBUI_Board_CardField_ID)
{
if (WEBUI_Board_CardField_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_CardField_ID, WEBUI_Board_CardField_ID);
}
@Override
public int getWEBUI_Board_CardField_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Board_CardField_ID);
}
@Override
public de.metas.ui.web.base.model.I_WEBUI_Board getWEBUI_Board()
{
return get_ValueAsPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class); | }
@Override
public void setWEBUI_Board(final de.metas.ui.web.base.model.I_WEBUI_Board WEBUI_Board)
{
set_ValueFromPO(COLUMNNAME_WEBUI_Board_ID, de.metas.ui.web.base.model.I_WEBUI_Board.class, WEBUI_Board);
}
@Override
public void setWEBUI_Board_ID (final int WEBUI_Board_ID)
{
if (WEBUI_Board_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Board_ID, WEBUI_Board_ID);
}
@Override
public int getWEBUI_Board_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Board_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Board_CardField.java | 1 |
请完成以下Java代码 | protected boolean isOrderByCreateTimeEnabled() {
return clientConfiguration.getOrderByCreateTime() != null;
}
protected boolean isUseCreateTimeEnabled() {
return Boolean.TRUE.equals(clientConfiguration.getUseCreateTime());
}
protected void checkForCreateTimeMisconfiguration() {
if (isUseCreateTimeEnabled() && isOrderByCreateTimeEnabled()) {
throw new SpringExternalTaskClientException(
"Both \"useCreateTime\" and \"orderByCreateTime\" are enabled. Please use one or the other");
}
}
@Autowired(required = false)
public void setRequestInterceptors(List<ClientRequestInterceptor> requestInterceptors) {
if (requestInterceptors != null) {
this.requestInterceptors.addAll(requestInterceptors);
LOG.requestInterceptorsFound(this.requestInterceptors.size());
}
}
@Autowired(required = false)
public void setClientBackoffStrategy(BackoffStrategy backoffStrategy) {
this.backoffStrategy = backoffStrategy;
LOG.backoffStrategyFound();
}
@Override
public Class<ExternalTaskClient> getObjectType() {
return ExternalTaskClient.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
}
public ClientConfiguration getClientConfiguration() {
return clientConfiguration;
}
public void setClientConfiguration(ClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
}
public List<ClientRequestInterceptor> getRequestInterceptors() {
return requestInterceptors; | }
protected void close() {
if (client != null) {
client.stop();
}
}
@Autowired(required = false)
protected void setPropertyConfigurer(PropertySourcesPlaceholderConfigurer configurer) {
PropertySources appliedPropertySources = configurer.getAppliedPropertySources();
propertyResolver = new PropertySourcesPropertyResolver(appliedPropertySources);
}
protected String resolve(String property) {
if (propertyResolver == null) {
return property;
}
if (property != null) {
return propertyResolver.resolvePlaceholders(property);
} else {
return null;
}
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\client\ClientFactory.java | 1 |
请完成以下Java代码 | public class SimplePage implements Paginable {
private static final long serialVersionUID = 1L;
public static final int DEF_COUNT = 20;
public SimplePage() {
}
public SimplePage(int pageNo, int pageSize, int totalCount) {
if (totalCount <= 0) {
this.totalCount = 0;
} else {
this.totalCount = totalCount;
}
if (pageSize <= 0) {
this.pageSize = DEF_COUNT;
} else {
this.pageSize = pageSize;
}
if (pageNo <= 0) {
this.pageNo = 1;
} else {
this.pageNo = pageNo;
}
if ((this.pageNo - 1) * this.pageSize >= totalCount) {
this.pageNo = totalCount / pageSize;
if(this.pageNo==0){
this.pageNo = 1 ;
}
}
}
/**
* 调整分页参数,使合理化
*/
public void adjustPage() {
if (totalCount <= 0) {
totalCount = 0;
}
if (pageSize <= 0) {
pageSize = DEF_COUNT;
}
if (pageNo <= 0) {
pageNo = 1;
}
if ((pageNo - 1) * pageSize >= totalCount) {
pageNo = totalCount / pageSize;
}
}
public int getPageNo() {
return pageNo;
}
public int getPageSize() {
return pageSize;
}
public int getTotalCount() {
return totalCount;
}
public int getTotalPage() {
int totalPage = totalCount / pageSize;
if (totalCount % pageSize != 0 || totalPage == 0) {
totalPage++;
}
return totalPage;
}
public boolean isFirstPage() {
return pageNo <= 1;
}
public boolean isLastPage() {
return pageNo >= getTotalPage(); | }
public int getNextPage() {
if (isLastPage()) {
return pageNo;
} else {
return pageNo + 1;
}
}
public int getPrePage() {
if (isFirstPage()) {
return pageNo;
} else {
return pageNo - 1;
}
}
protected int totalCount = 0;
protected int pageSize = 20;
protected int pageNo = 1;
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
protected int filterNo;
public int getFilterNo() {
return filterNo;
}
public void setFilterNo(int filterNo) {
this.filterNo = filterNo;
}
} | repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\page\SimplePage.java | 1 |
请完成以下Java代码 | private void loadNextPage()
{
final TypedSqlQuery<T> queryToUse;
query.setLimit(QueryLimit.ofInt(bufferSize));
if (Check.isEmpty(rowNumberColumn, true))
{
query.setLimit(QueryLimit.ofInt(bufferSize), offset);
queryToUse = query;
}
else
{
query.setLimit(QueryLimit.ofInt(bufferSize));
queryToUse = query.addWhereClause(true, rowNumberColumn + " > " + offset);
}
final List<ET> buffer = queryToUse.list(clazz);
bufferIterator = buffer.iterator();
final int bufferSizeActual = buffer.size();
bufferFullyLoaded = bufferSizeActual >= bufferSize;
if (logger.isDebugEnabled())
{
logger.debug("Loaded next page: bufferSize=" + bufferSize + ", offset=" + offset + " -> " + bufferSizeActual + " records (fullyLoaded=" + bufferFullyLoaded + ")");
}
offset += bufferSizeActual;
} | /**
* Sets buffer/page size, i.e. the number of rows to be loaded by this iterator at a time.
*
* @see IQuery#OPTION_GuaranteedIteratorRequired
*/
public void setBufferSize(final int bufferSize)
{
Check.assume(bufferSize > 0, "bufferSize > 0");
this.bufferSize = bufferSize;
}
public int getBufferSize()
{
return bufferSize;
}
@Override
public String toString()
{
return "POBufferedIterator [clazz=" + clazz
+ ", bufferSize=" + bufferSize
+ ", offset=" + offset
+ ", query=" + query
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\POBufferedIterator.java | 1 |
请完成以下Java代码 | public class CommonMixedErrorHandler implements CommonErrorHandler {
private final CommonErrorHandler recordErrorHandler;
private final CommonErrorHandler batchErrorHandler;
/**
* Construct an instance with the provided delegate {@link CommonErrorHandler}s.
* @param recordErrorHandler the error handler for record listeners.
* @param batchErrorHandler the error handler for batch listeners.
*/
public CommonMixedErrorHandler(CommonErrorHandler recordErrorHandler, CommonErrorHandler batchErrorHandler) {
Assert.notNull(recordErrorHandler, "'recordErrorHandler' cannot be null");
Assert.notNull(batchErrorHandler, "'batchErrorHandler' cannot be null");
this.recordErrorHandler = recordErrorHandler;
this.batchErrorHandler = batchErrorHandler;
}
@Override
public boolean seeksAfterHandling() {
return this.recordErrorHandler.seeksAfterHandling();
}
@Override
public boolean deliveryAttemptHeader() {
return this.recordErrorHandler.deliveryAttemptHeader();
}
@Override
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer,
MessageListenerContainer container, boolean batchListener) {
if (batchListener) {
this.batchErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
else {
this.recordErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
}
@Override
public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer,
MessageListenerContainer container) {
return this.recordErrorHandler.handleOne(thrownException, record, consumer, container);
}
@Override
public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, | MessageListenerContainer container) {
this.recordErrorHandler.handleRemaining(thrownException, records, consumer, container);
}
@Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) {
this.batchErrorHandler.handleBatch(thrownException, data, consumer, container, invokeListener);
}
@Override
public int deliveryAttempt(TopicPartitionOffset topicPartitionOffset) {
return this.recordErrorHandler.deliveryAttempt(topicPartitionOffset);
}
@Override
public void clearThreadState() {
this.batchErrorHandler.clearThreadState();
this.recordErrorHandler.clearThreadState();
}
@Override
public boolean isAckAfterHandle() {
return this.recordErrorHandler.isAckAfterHandle();
}
@Override
public void setAckAfterHandle(boolean ack) {
this.batchErrorHandler.setAckAfterHandle(ack);
this.recordErrorHandler.setAckAfterHandle(ack);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonMixedErrorHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static List toList() {
BusCategoryEnum[] ary = BusCategoryEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", ary[i].name());
map.put("desc", ary[i].getDesc());
map.put("minAmount", ary[i].getMinAmount());
map.put("maxAmount", ary[i].getMaxAmount());
map.put("beginTime", ary[i].getBeginTime());
map.put("endTime", ary[i].getEndTime());
list.add(map);
}
return list;
}
/** | * 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
BusCategoryEnum[] enums = BusCategoryEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (BusCategoryEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\BusCategoryEnum.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public org.compiere.model.I_M_InOutLine getM_InOutLine()
{
return get_ValueAsPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class);
}
@Override
public void setM_InOutLine(final org.compiere.model.I_M_InOutLine M_InOutLine)
{
set_ValueFromPO(COLUMNNAME_M_InOutLine_ID, org.compiere.model.I_M_InOutLine.class, M_InOutLine);
}
@Override
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 setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEntered (final @Nullable BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM)
{
set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM);
}
@Override
public BigDecimal getQtyInvoicedInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderDetail.java | 1 |
请完成以下Java代码 | public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", description=").append(description);
sb.append(", adminCount=").append(adminCount);
sb.append(", createTime=").append(createTime);
sb.append(", status=").append(status);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsRole.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<SizeType.AdditionalSizeInformation> getAdditionalSizeInformation() {
if (additionalSizeInformation == null) {
additionalSizeInformation = new ArrayList<SizeType.AdditionalSizeInformation>();
}
return this.additionalSizeInformation;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="Type" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
public static class AdditionalSizeInformation {
@XmlValue
protected String content;
@XmlAttribute(name = "Type", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
@XmlSchemaType(name = "anySimpleType")
protected String type;
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* Sets the value of the content property. | *
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\SizeType.java | 2 |
请完成以下Java代码 | public static Builder builderFrom(StartMessageSubscriptionImpl startMessageSubscriptionImpl) {
return new Builder(startMessageSubscriptionImpl);
}
/**
* Builder to build {@link StartMessageSubscriptionImpl}.
*/
public static final class Builder {
private String id;
private String eventName;
private String processDefinitionId;
private String configuration;
private String activityId;
private Date created;
public Builder() {}
private Builder(StartMessageSubscriptionImpl startMessageSubscriptionImpl) {
this.id = startMessageSubscriptionImpl.id;
this.eventName = startMessageSubscriptionImpl.eventName;
this.processDefinitionId = startMessageSubscriptionImpl.processDefinitionId;
this.configuration = startMessageSubscriptionImpl.configuration;
this.activityId = startMessageSubscriptionImpl.activityId;
this.created = startMessageSubscriptionImpl.created;
}
/**
* Builder method for id parameter.
* @param id field to set
* @return builder
*/
public Builder withId(String id) {
this.id = id;
return this;
}
/**
* Builder method for eventName parameter.
* @param eventName field to set
* @return builder
*/
public Builder withEventName(String eventName) {
this.eventName = eventName;
return this;
}
/**
* Builder method for processDefinitionId parameter.
* @param processDefinitionId field to set
* @return builder
*/
public Builder withProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
return this;
}
/**
* Builder method for configuration parameter.
* @param configuration field to set
* @return builder
*/
public Builder withConfiguration(String configuration) {
this.configuration = configuration;
return this; | }
/**
* Builder method for activityId parameter.
* @param activityId field to set
* @return builder
*/
public Builder withActivityId(String activityId) {
this.activityId = activityId;
return this;
}
/**
* Builder method for created parameter.
* @param created field to set
* @return builder
*/
public Builder withCreated(Date created) {
this.created = created;
return this;
}
/**
* Builder method of the builder.
* @return built class
*/
public StartMessageSubscriptionImpl build() {
return new StartMessageSubscriptionImpl(this);
}
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\StartMessageSubscriptionImpl.java | 1 |
请完成以下Java代码 | public int getAD_Workflow_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Workflow_ID);
}
@Override
public void setDateLastAlert (final java.sql.Timestamp DateLastAlert)
{
set_Value (COLUMNNAME_DateLastAlert, DateLastAlert);
}
@Override
public java.sql.Timestamp getDateLastAlert()
{
return get_ValueAsTimestamp(COLUMNNAME_DateLastAlert);
}
@Override
public void setDynPriorityStart (final int DynPriorityStart)
{
set_Value (COLUMNNAME_DynPriorityStart, DynPriorityStart);
}
@Override
public int getDynPriorityStart()
{
return get_ValueAsInt(COLUMNNAME_DynPriorityStart);
}
@Override
public void setEndWaitTime (final java.sql.Timestamp EndWaitTime)
{
set_Value (COLUMNNAME_EndWaitTime, EndWaitTime);
}
@Override
public java.sql.Timestamp getEndWaitTime()
{
return get_ValueAsTimestamp(COLUMNNAME_EndWaitTime);
}
@Override
public void setPriority (final int Priority)
{
set_Value (COLUMNNAME_Priority, Priority);
}
@Override
public int getPriority()
{
return get_ValueAsInt(COLUMNNAME_Priority);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing); | }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
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);
}
/**
* 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_Activity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setColumnValue(PreparedStatement sqlInsertStatement, String value) throws SQLException {
if (value == null) {
sqlInsertStatement.setNull(this.sqlIndex, this.sqlType);
} else {
switch (this.type) {
case DOUBLE:
sqlInsertStatement.setDouble(this.sqlIndex, Double.parseDouble(value));
break;
case INTEGER:
sqlInsertStatement.setInt(this.sqlIndex, Integer.parseInt(value));
break;
case FLOAT:
sqlInsertStatement.setFloat(this.sqlIndex, Float.parseFloat(value));
break;
case BIGINT:
sqlInsertStatement.setLong(this.sqlIndex, Long.parseLong(value));
break;
case BOOLEAN:
sqlInsertStatement.setBoolean(this.sqlIndex, Boolean.parseBoolean(value));
break;
case ENUM_TO_INT:
@SuppressWarnings("unchecked")
Enum<?> enumVal = Enum.valueOf(this.enumClass, value);
int intValue = enumVal.ordinal();
sqlInsertStatement.setInt(this.sqlIndex, intValue);
break;
case JSON:
case STRING: | case ID:
default:
sqlInsertStatement.setString(this.sqlIndex, value);
break;
}
}
}
private String replaceNullChars(String strValue) {
if (strValue != null) {
return PATTERN_THREAD_LOCAL.get().matcher(strValue).replaceAll(EMPTY_STR);
}
return strValue;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\migrate\CassandraToSqlColumn.java | 2 |
请完成以下Java代码 | public void setProductPrice(final I_M_Product product, final BigDecimal price)
{
productId2price.put(ProductId.ofRepoId(product.getM_Product_ID()), price);
}
@Override
public boolean applies(IPricingContext pricingCtx, IPricingResult result)
{
return true;
}
@Override
public void calculate(IPricingContext pricingCtx, IPricingResult result)
{
//
// Check product price
final ProductId productId = pricingCtx.getProductId();
BigDecimal price = productId2price.get(productId);
if (price == null)
{
price = priceToReturn;
}
result.setPriceLimit(price);
result.setPriceList(price); | result.setPriceStd(price);
result.setPrecision(precision);
result.setTaxCategoryId(TaxCategoryId.ofRepoId(100));
final I_C_UOM priceUOM = productId2priceUOM.get(productId);
if (priceUOM != null)
{
result.setPriceUomId(UomId.ofRepoId(priceUOM.getC_UOM_ID()));
}
result.setCalculated(true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\MockedPricingRule.java | 1 |
请完成以下Java代码 | public class AddressInfo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstLine;
private String secondLine;
private String zipCode;
private String state;
private String country;
@OneToOne(mappedBy = "addressInfo") | @JsonIgnore
private OrderInfo order;
// Bank
@OneToMany(mappedBy = "addressInfo", orphanRemoval = true, cascade = CascadeType.ALL)
@JsonIgnore
private List<BankInfo> banks;
// Customer
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id")
@JsonIgnore
private Customer customer;
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-5.Spring-ReactJS-Ecommerce-Shopping\fullstack\backend\model\src\main\java\com\urunov\entity\info\AddressInfo.java | 1 |
请完成以下Java代码 | public void onDeviceProfileUpdated(DeviceProfile deviceProfile, DeviceSessionContext sessionContext) {
log.debug("Handling device profile {} update event for device {}", deviceProfile.getId(), sessionContext.getDeviceId());
updateDeviceSession(sessionContext, sessionContext.getDevice(), deviceProfile);
}
public void onSnmpTransportListChanged() {
log.trace("SNMP transport list changed. Updating sessions");
List<DeviceId> deleted = new LinkedList<>();
for (DeviceId deviceId : allSnmpDevicesIds) {
if (balancingService.isManagedByCurrentTransport(deviceId.getId())) {
if (!sessions.containsKey(deviceId)) {
Device device = protoEntityService.getDeviceById(deviceId);
if (device != null) {
log.info("SNMP device {} is now managed by current transport node", deviceId);
establishDeviceSession(device);
} else {
deleted.add(deviceId);
}
}
} else {
Optional.ofNullable(sessions.get(deviceId)) | .ifPresent(sessionContext -> {
log.info("SNMP session for device {} is not managed by current transport node anymore", deviceId);
destroyDeviceSession(sessionContext);
});
}
}
log.trace("Removing deleted SNMP devices: {}", deleted);
allSnmpDevicesIds.removeAll(deleted);
}
public Collection<DeviceSessionContext> getSessions() {
return sessions.values();
}
@PreDestroy
public void destroy() {
snmpExecutor.shutdown();
}
} | repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\SnmpTransportContext.java | 1 |
请完成以下Java代码 | protected void openSpecific()
{
final String folder = (String)getCurrentParams().get(
IInboundProcessorBL.LOCAL_FOLDER).getValue();
final List<File> files = inboundProcessorBL.getFiles(folder);
currentFiles = files.iterator();
}
@Override
protected void closeSpecific()
{
currentFile = null;
currentFiles = null;
}
private FileInputStream currentStream;
@Override
public InputStream connectNext(final boolean lastWasSuccess)
{
if (currentStream != null)
{
try
{
// note: close alone didn't suffice (at least in WinXP when
// running in eclipse debug session)
currentStream.getFD().sync();
currentStream.close();
}
catch (IOException e)
{
throw new AdempiereException(e);
}
}
if (lastWasSuccess && currentFile != null)
{
final String archiveFolder = (String)getCurrentParams().get(
IInboundProcessorBL.ARCHIVE_FOLDER).getValue();
inboundProcessorBL.moveToArchive(currentFile, archiveFolder); | }
if (currentFiles.hasNext())
{
currentFile = currentFiles.next();
try
{
currentStream = new FileInputStream(currentFile);
return currentStream;
}
catch (FileNotFoundException e)
{
ConfigException.throwNew(ConfigException.FILE_ACCESS_FAILED_2P,
currentFile.getAbsolutePath(), e.getMessage());
}
}
return null;
}
@Override
public List<Parameter> getParameters()
{
final List<Parameter> result = new ArrayList<Parameter>();
result.add(new Parameter(IInboundProcessorBL.LOCAL_FOLDER,
"Import-Ordner", "Name of the folder to import from",
DisplayType.FilePath, 1));
result.add(new Parameter(IInboundProcessorBL.ARCHIVE_FOLDER,
"Archiv-Ordner",
"Name of the folder to move files to after import",
DisplayType.FilePath, 2));
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\spi\impl\FileImporter.java | 1 |
请完成以下Java代码 | public void associateWithRefundCandidate(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
if (!Services.get(IInvoiceCandBL.class).isUpdateProcessInProgress())
{
return; // only the update process shall manage refund invoice candidates, to avoid locking problems and other race conditions
}
final boolean readyForAnyProcessing = extractReadyForAnyProcessing(invoiceCandidateRecord);
if (!readyForAnyProcessing)
{
return;
}
if (refundInvoiceCandidateService.isRefundInvoiceCandidateRecord(invoiceCandidateRecord))
{
return; // it's already associated
}
associateDuringUpdateProcess0(invoiceCandidateRecord);
}
private void associateDuringUpdateProcess0(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord)
{
try
{
final AssignableInvoiceCandidate assignableInvoiceCandidate = assignableInvoiceCandidateRepository.ofRecord(invoiceCandidateRecord);
invoiceCandidateAssignmentService.updateAssignment(assignableInvoiceCandidate);
}
catch (final RuntimeException e)
{
// allow the "normal ICs" to be updated, even if something is wrong with the "refund-ICs"
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e);
Loggables.withLogger(logger, Level.WARN)
.addLog("associateDuringUpdateProcess0 - Caught an exception withe processing C_Invoice_Candidate_ID={}; "
+ "please check the async workpackage log; AD_Issue_ID={}; e={}",
invoiceCandidateRecord.getC_Invoice_Candidate_ID(), issueId, e.toString());
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteAssignment(@NonNull final I_C_Invoice_Candidate icRecord) | {
if (refundInvoiceCandidateService.isRefundInvoiceCandidateRecord(icRecord))
{
final RefundInvoiceCandidate refundCandidate = refundInvoiceCandidateRepository.ofRecord(icRecord);
invoiceCandidateAssignmentService.removeAllAssignments(refundCandidate);
}
else
{
final boolean readyForAnyProcessing = extractReadyForAnyProcessing(icRecord);
if (!readyForAnyProcessing)
{
return; // this IC was not yet once validated, or has no currency; it's certainly not assigned, and we can't create an AssignableInvoiceCandidate from it
}
final AssignableInvoiceCandidate assignableCandidate = assignableInvoiceCandidateRepository.ofRecord(icRecord);
if (assignableCandidate.isAssigned())
{
invoiceCandidateAssignmentService.unassignCandidate(assignableCandidate);
}
}
}
private boolean extractReadyForAnyProcessing(@NonNull final I_C_Invoice_Candidate icRecord)
{
if (icRecord.getC_Currency_ID() <= 0)
{
return false;
}
final Timestamp invoicableFromDate = coalesceSuppliers(
() -> icRecord.getDateToInvoice_Override(),
() -> icRecord.getDateToInvoice());
if (invoicableFromDate == null)
{
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\interceptor\C_Invoice_Candidate_Manage_Refund_Candidates.java | 1 |
请完成以下Java代码 | public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
} | @Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCorrelationId() {
// v5 Jobs have no correlationId
return null;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java | 1 |
请完成以下Java代码 | public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime;
return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache;
return this;
} | public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
return this;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) {
this.engineAgendaFactory = engineAgendaFactory;
}
public ActivitiEngineAgendaFactory getEngineAgendaFactory() {
return engineAgendaFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CaseDefinitionDecisionCollectionResource extends BaseCaseDefinitionResource {
@ApiOperation(value = "List decisions for a case definition", nickname = "listCaseDefinitionDecisions", tags = { "Case Definitions" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the case definition was found and the decisions are returned.", response = DmnDecision.class, responseContainer = "List"),
@ApiResponse(code = 404, message = "Indicates the requested case definition was not found.")
})
@GetMapping(value = "/cmmn-repository/case-definitions/{caseDefinitionId}/decisions", produces = "application/json")
public List<DecisionResponse> getDecisionsForCaseDefinition(
@ApiParam(name = "caseDefinitionId") @PathVariable String caseDefinitionId) {
CaseDefinition caseDefinition = getCaseDefinitionFromRequest(caseDefinitionId);
List<DmnDecision> decisions = repositoryService.getDecisionsForCaseDefinition(caseDefinition.getId());
return restResponseFactory.createDecisionResponseList(decisions, caseDefinitionId);
} | /**
* @deprecated
*/
@Deprecated
@ApiOperation(value = "List decision tables for a case definition", nickname = "listCaseDefinitionDecisionTables", tags = { "Case Definitions" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the case definition was found and the decision tables are returned.", response = DmnDecision.class, responseContainer = "List"),
@ApiResponse(code = 404, message = "Indicates the requested case definition was not found.")
})
@GetMapping(value = "/cmmn-repository/case-definitions/{caseDefinitionId}/decision-tables", produces = "application/json")
public List<DecisionResponse> getDecisionTablesForCaseDefinition(
@ApiParam(name = "caseDefinitionId") @PathVariable String caseDefinitionId) {
return getDecisionsForCaseDefinition(caseDefinitionId);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CaseDefinitionDecisionCollectionResource.java | 2 |
请完成以下Java代码 | public void setDelayForTopic(String topic, Duration delay) {
Objects.requireNonNull(topic, "Topic cannot be null");
Objects.requireNonNull(delay, "Delay cannot be null");
this.logger.debug(() -> String.format("Setting %s seconds delay for topic %s", delay, topic));
this.delaysPerTopic.put(topic, delay);
}
public void setDefaultDelay(Duration delay) {
Objects.requireNonNull(delay, "Delay cannot be null");
this.logger.debug(() -> String.format("Setting %s seconds delay for listener id %s", delay, this.listenerId));
this.defaultDelay = delay;
}
private void invokeDelegateOnMessage(ConsumerRecord<K, V> consumerRecord, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
switch (this.delegateType) {
case ACKNOWLEDGING_CONSUMER_AWARE:
this.delegate.onMessage(consumerRecord, acknowledgment, consumer);
break;
case ACKNOWLEDGING:
this.delegate.onMessage(consumerRecord, acknowledgment);
break;
case CONSUMER_AWARE:
this.delegate.onMessage(consumerRecord, consumer);
break;
case SIMPLE:
this.delegate.onMessage(consumerRecord);
}
}
private KafkaConsumerBackoffManager.Context createContext(ConsumerRecord<K, V> data, long nextExecutionTimestamp, Consumer<?, ?> consumer) {
return this.kafkaConsumerBackoffManager.createContext(nextExecutionTimestamp, this.listenerId, new TopicPartition(data.topic(), data.partition()),
consumer);
} | @Override
public void onMessage(ConsumerRecord<K, V> data) {
onMessage(data, null, null);
}
@Override
public void onMessage(ConsumerRecord<K, V> data, Acknowledgment acknowledgment) {
onMessage(data, acknowledgment, null);
}
@Override
public void onMessage(ConsumerRecord<K, V> data, Consumer<?, ?> consumer) {
onMessage(data, null, consumer);
}
} | repos\tutorials-master\spring-kafka-3\src\main\java\com\baeldung\spring\kafka\delay\DelayedMessageListenerAdapter.java | 1 |
请完成以下Java代码 | public String toString()
{
return "MPPOrder[ID=" + get_ID()
+ "-DocumentNo=" + getDocumentNo()
+ ",IsSOTrx=" + isSOTrx()
+ ",C_DocType_ID=" + getC_DocType_ID()
+ "]";
}
/**
* Auto report the first Activity and Sub contracting if are Milestone Activity
*/
private void autoReportActivities()
{
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities())
{
if (activity.isMilestone()
&& (activity.isSubcontracting() || orderRouting.isFirstActivity(activity)))
{
ppCostCollectorBL.createActivityControl(ActivityControlCreateRequest.builder()
.order(this)
.orderActivity(activity)
.qtyMoved(activity.getQtyToDeliver()) | .durationSetup(Duration.ZERO)
.duration(Duration.ZERO)
.build());
}
}
}
private void createVariances()
{
final IPPCostCollectorBL ppCostCollectorBL = Services.get(IPPCostCollectorBL.class);
//
for (final I_PP_Order_BOMLine bomLine : getLines())
{
ppCostCollectorBL.createMaterialUsageVariance(this, bomLine);
}
//
final PPOrderRouting orderRouting = getOrderRouting();
for (final PPOrderRoutingActivity activity : orderRouting.getActivities())
{
ppCostCollectorBL.createResourceUsageVariance(this, activity);
}
}
} // MPPOrder | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPOrder.java | 1 |
请完成以下Java代码 | public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValue (final @Nullable 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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities_Summary.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Message {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String content;
public Message(){}
public Message(String name, String content) {
this.name = name;
this.content = content;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} | repos\SpringBoot-Learning-master\1.x\Chapter3-2-4\src\main\java\com\didispace\domain\s\Message.java | 2 |
请完成以下Java代码 | private static boolean kthSmallesElementFound(int[] list1, int[] list2, int nElementsList1, int nElementsList2) {
// we do not take any element from the second list
if(nElementsList2 < 1) {
return true;
}
if(list1[nElementsList1-1] == list2[nElementsList2-1]) {
return true;
}
if(nElementsList1 == list1.length) {
return list1[nElementsList1-1] <= list2[nElementsList2];
}
if(nElementsList2 == list2.length) {
return list2[nElementsList2-1] <= list1[nElementsList1];
}
return list1[nElementsList1-1] <= list2[nElementsList2] && list2[nElementsList2-1] <= list1[nElementsList1];
}
private static void checkInput(int k, int[] list1, int[] list2) throws NoSuchElementException, IllegalArgumentException {
if(list1 == null || list2 == null || k < 1) {
throw new IllegalArgumentException();
}
if(list1.length == 0 || list2.length == 0) {
throw new IllegalArgumentException();
}
if(k > list1.length + list2.length) {
throw new NoSuchElementException();
}
}
public static int getKthElementSorted(int[] list1, int[] list2, int k) {
int length1 = list1.length, length2 = list2.length;
int[] combinedArray = new int[length1 + length2];
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
Arrays.sort(combinedArray); | return combinedArray[k-1];
}
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
int i1 = 0, i2 = 0;
while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
if(list1[i1] < list2[i2]) {
i1++;
} else {
i2++;
}
}
if((i1 + i2) < k) {
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
} else if(i1 > 0 && i2 > 0) {
return Math.max(list1[i1-1], list2[i2-1]);
} else {
return i1 == 0 ? list2[i2-1] : list1[i1-1];
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\kthsmallest\KthSmallest.java | 1 |
请完成以下Java代码 | private void invalidateCandidatesForInOut(final I_M_InOut inout)
{
//
// Retrieve inout line handlers
final Properties ctx = InterfaceWrapperHelper.getCtx(inout);
final List<IInvoiceCandidateHandler> inoutLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, org.compiere.model.I_M_InOutLine.Table_Name);
for (final IInvoiceCandidateHandler handler : inoutLineHandlers)
{
for (final org.compiere.model.I_M_InOutLine line : inOutDAO.retrieveLines(inout))
{
handler.invalidateCandidatesFor(line);
}
}
}
@Override
public String getSourceTable()
{
return org.compiere.model.I_M_InOut.Table_Name;
}
@Override
public boolean isUserInChargeUserEditable()
{
return false;
}
@Override
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
} | @Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
throw new UnsupportedOperationException();
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOut_Handler.java | 1 |
请完成以下Java代码 | public class MutableMoney {
@Override
public String toString() {
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
} | public void setCurrency(String currency) {
this.currency = currency;
}
private long amount;
private String currency;
public MutableMoney(long amount, String currency) {
super();
this.amount = amount;
this.currency = currency;
}
} | repos\tutorials-master\google-auto-project\src\main\java\com\baeldung\autovalue\MutableMoney.java | 1 |
请完成以下Java代码 | public boolean isFinished() {
for (Pairing pairing : this) {
if (pairing.getHole() < 18) {
return false;
}
}
return true;
}
public GolfTournament at(GolfCourse golfCourse) {
Assert.notNull(golfCourse, "Golf Course must not be null");
this.golfCourse = golfCourse;
return this;
}
public GolfTournament buildPairings() {
Assert.notEmpty(this.players,
() -> String.format("No players are registered for this golf tournament [%s]", getName()));
Assert.isTrue(this.players.size() % 2 == 0,
() -> String.format("An even number of players must register to play this golf tournament [%s]; currently at [%d]",
getName(), this.players.size()));
List<Golfer> playersToPair = new ArrayList<>(this.players);
Collections.shuffle(playersToPair);
for (int index = 0, size = playersToPair.size(); index < size; index += 2) {
this.pairings.add(Pairing.of(playersToPair.get(index), playersToPair.get(index + 1)));
}
return this;
}
@Override
public Iterator<GolfTournament.Pairing> iterator() {
return Collections.unmodifiableList(this.pairings).iterator();
}
public GolfTournament play() {
Assert.state(this.golfCourse != null, "No golf course was declared");
Assert.state(!this.players.isEmpty(), "Golfers must register to play before the golf tournament is played");
Assert.state(!this.pairings.isEmpty(), "Pairings must be formed before the golf tournament is played");
Assert.state(!isFinished(), () -> String.format("Golf tournament [%s] has already been played", getName()));
return this;
}
public GolfTournament register(Golfer... players) {
return register(Arrays.asList(ArrayUtils.nullSafeArray(players, Golfer.class)));
}
public GolfTournament register(Iterable<Golfer> players) {
StreamSupport.stream(CollectionUtils.nullSafeIterable(players).spliterator(), false)
.filter(Objects::nonNull)
.forEach(this.players::add); | return this;
}
@Getter
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor(staticName = "of")
public static class Pairing {
private final AtomicBoolean signedScorecard = new AtomicBoolean(false);
@NonNull
private final Golfer playerOne;
@NonNull
private final Golfer playerTwo;
public synchronized void setHole(int hole) {
this.playerOne.setHole(hole);
this.playerTwo.setHole(hole);
}
public synchronized int getHole() {
return getPlayerOne().getHole();
}
public boolean in(@NonNull Golfer golfer) {
return this.playerOne.equals(golfer) || this.playerTwo.equals(golfer);
}
public synchronized int nextHole() {
return getHole() + 1;
}
public synchronized boolean signScorecard() {
return getHole() >= 18
&& this.signedScorecard.compareAndSet(false, true);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\GolfTournament.java | 1 |
请完成以下Java代码 | public void updateRenderedAddressAndCapturedLocation(final IDocumentLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::withUpdatedLocationId)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddressAndCapturedLocation);
}
@Override
public void updateRenderedAddress(final IDocumentLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddress);
}
@Override
public void updateRenderedAddress(final IDocumentBillLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddress);
}
@Override
public void updateRenderedAddressAndCapturedLocation(final IDocumentBillLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::withUpdatedLocationId)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddressAndCapturedLocation);
}
@Override
public void updateRenderedAddressAndCapturedLocation(final IDocumentDeliveryLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::withUpdatedLocationId)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddressAndCapturedLocation);
}
@Override
public void updateRenderedAddress(final IDocumentDeliveryLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddress);
}
@Override
public void updateRenderedAddressAndCapturedLocation(final IDocumentHandOverLocationAdapter locationAdapter)
{ | toPlainDocumentLocation(locationAdapter)
.map(this::withUpdatedLocationId)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddressAndCapturedLocation);
}
@Override
public void updateRenderedAddress(final IDocumentHandOverLocationAdapter locationAdapter)
{
toPlainDocumentLocation(locationAdapter)
.map(this::computeRenderedAddress)
.ifPresent(locationAdapter::setRenderedAddress);
}
@Override
public Set<DocumentLocation> getDocumentLocations(@NonNull final Set<BPartnerLocationId> bpartnerLocationIds)
{
if (bpartnerLocationIds.isEmpty())
{
return ImmutableSet.of();
}
return bpartnerLocationIds
.stream()
.map(this::getDocumentLocation)
.collect(ImmutableSet.toImmutableSet());
}
@Override
public DocumentLocation getDocumentLocation(@NonNull final BPartnerLocationId bpartnerLocationId)
{
DocumentLocation documentLocation = DocumentLocation.ofBPartnerLocationId(bpartnerLocationId);
final RenderedAddressAndCapturedLocation renderedAddress = computeRenderedAddress(documentLocation);
return documentLocation.withRenderedAddress(renderedAddress);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\location\impl\DocumentLocationBL.java | 1 |
请完成以下Java代码 | default ConsumerRecord<K, V> receive(String topic, int partition, long offset) {
return receive(topic, partition, offset, DEFAULT_POLL_TIMEOUT);
}
/**
* Receive a single record.
* @param topic the topic.
* @param partition the partition.
* @param offset the offset.
* @param pollTimeout the timeout.
* @return the record or null.
* @since 2.8
*/
@Nullable
ConsumerRecord<K, V> receive(String topic, int partition, long offset, Duration pollTimeout);
/**
* Receive a multiple records with the default poll timeout (5 seconds). Only
* absolute, positive offsets are supported.
* @param requested a collection of record requests (topic/partition/offset).
* @return the records
* @since 2.8
* @see #DEFAULT_POLL_TIMEOUT
*/
default ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested) {
return receive(requested, DEFAULT_POLL_TIMEOUT);
}
/**
* Receive multiple records. Only absolute, positive offsets are supported.
* @param requested a collection of record requests (topic/partition/offset).
* @param pollTimeout the timeout.
* @return the record or null.
* @since 2.8
*/ | ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout);
/**
* A callback for executing arbitrary operations on the {@link Producer}.
* @param <K> the key type.
* @param <V> the value type.
* @param <T> the return type.
* @since 1.3
*/
interface ProducerCallback<K, V, T> {
T doInKafka(Producer<K, V> producer);
}
/**
* A callback for executing arbitrary operations on the {@link KafkaOperations}.
* @param <K> the key type.
* @param <V> the value type.
* @param <T> the return type.
* @since 1.3
*/
interface OperationsCallback<K, V, T> {
@Nullable
T doInOperations(KafkaOperations<K, V> operations);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaOperations.java | 1 |
请完成以下Java代码 | public void onMsg(TbContext ctx, TbMsg msg) {
TbEmail email = convert(msg);
TbMsg emailMsg = buildEmailMsg(ctx, msg, email);
ctx.tellNext(emailMsg, TbNodeConnectionType.SUCCESS);
}
private TbMsg buildEmailMsg(TbContext ctx, TbMsg msg, TbEmail email) {
String emailJson = JacksonUtil.toString(email);
return ctx.transformMsg(msg, TbMsgType.SEND_EMAIL, msg.getOriginator(), msg.getMetaData().copy(), emailJson);
}
private TbEmail convert(TbMsg msg) {
TbEmail.TbEmailBuilder builder = TbEmail.builder();
builder.from(fromTemplate(config.getFromTemplate(), msg));
builder.to(fromTemplate(config.getToTemplate(), msg));
builder.cc(fromTemplate(config.getCcTemplate(), msg));
builder.bcc(fromTemplate(config.getBccTemplate(), msg));
String htmlStr = dynamicMailBodyType ? | fromTemplate(config.getIsHtmlTemplate(), msg) : config.getMailBodyType();
builder.html(Boolean.parseBoolean(htmlStr));
builder.subject(fromTemplate(config.getSubjectTemplate(), msg));
builder.body(fromTemplate(config.getBodyTemplate(), msg));
String imagesStr = msg.getMetaData().getValue(IMAGES);
if (!StringUtils.isEmpty(imagesStr)) {
Map<String, String> imgMap = JacksonUtil.fromString(imagesStr, new TypeReference<HashMap<String, String>>() {});
builder.images(imgMap);
}
return builder.build();
}
private String fromTemplate(String template, TbMsg msg) {
return StringUtils.isNotEmpty(template) ? TbNodeUtils.processPattern(template, msg) : null;
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mail\TbMsgToEmailNode.java | 1 |
请完成以下Java代码 | public void print(@NonNull final OutputStream bos) throws Exception
{
final I_C_Print_Job_Instructions print_Job_Instructions = printPackage.getC_Print_Job_Instructions();
final Document document = new Document();
final PdfCopy copy = new PdfCopy(document, bos);
document.open();
final PrintablePDF printable = createPrintable();
if (printable == null)
{
return;
}
try
{
for (final I_C_Print_PackageInfo printPackageInfo : printingDAO.retrievePrintPackageInfos(printPackage))
{
final byte[] pdf = print(printPackageInfo, printable);
final PdfReader reader = new PdfReader(pdf);
for (int page = 0; page < reader.getNumberOfPages(); )
{
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}
document.close();
print_Job_Instructions.setErrorMsg(null);
print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Done); | InterfaceWrapperHelper.save(print_Job_Instructions);
}
catch (final Exception e)
{
print_Job_Instructions.setErrorMsg(e.getLocalizedMessage());
print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Error);
InterfaceWrapperHelper.save(print_Job_Instructions);
throw new AdempiereException(e.getLocalizedMessage());
}
}
private byte[] print(@NonNull final I_C_Print_PackageInfo printPackageInfo, @NonNull final PrintablePDF printable)
{
printable.setCalX(printPackageInfo.getCalX());
printable.setCalY(printPackageInfo.getCalY());
final PrintablePDF clone = printable;
return PdfPrinter.print(printable, clone);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\PrintPackagePDFBuilder.java | 1 |
请完成以下Java代码 | protected void deleteTenantMembershipsOfTenant(String tenant) {
getDbEntityManager().delete(TenantMembershipEntity.class, "deleteTenantMembershipsOfTenant", tenant);
}
// authorizations ////////////////////////////////////////////////////////////
protected void createDefaultAuthorizations(UserEntity userEntity) {
if(Context.getProcessEngineConfiguration().isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newUser(userEntity));
}
}
protected void createDefaultAuthorizations(Group group) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newGroup(group));
}
}
protected void createDefaultAuthorizations(Tenant tenant) {
if (isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().newTenant(tenant));
}
}
protected void createDefaultMembershipAuthorizations(String userId, String groupId) { | if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().groupMembershipCreated(groupId, userId));
}
}
protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, User user) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, user));
}
}
protected void createDefaultTenantMembershipAuthorizations(Tenant tenant, Group group) {
if(isAuthorizationEnabled()) {
saveDefaultAuthorizations(getResourceAuthorizationProvider().tenantMembershipCreated(tenant, group));
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbIdentityServiceProvider.java | 1 |
请完成以下Java代码 | public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getDateDoc());
}
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
return "MJournal["
+ get_ID() + "," + getDescription()
+ ",DR=" + getTotalDr()
+ ",CR=" + getTotalCr()
+ "]";
} // toString
/**
* Get Document Info
*
* @return document info (untranslated)
*/
@Override
public String getDocumentInfo()
{
MDocType dt = MDocType.get(getCtx(), getC_DocType_ID());
return dt.getName() + " " + getDocumentNo();
} // getDocumentInfo
/**
* Create PDF
*
* @return File or null
*/
@Override
public File createPDF()
{
return null;
}
/**
* Get Process Message
*
* @return clear text error message
*/
@Override
public String getProcessMsg()
{ | return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
*
* @return AD_User_ID (Created)
*/
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount
*
* @return DR amount
*/
@Override
public BigDecimal getApprovalAmt()
{
return getTotalDr();
} // getApprovalAmt
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
@Deprecated
public boolean isComplete()
{
return Services.get(IGLJournalBL.class).isComplete(this);
} // isComplete
// metas: cg: 02476
private static void setAmtPrecision(final I_GL_Journal journal)
{
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoIdOrNull(journal.getC_AcctSchema_ID());
if (acctSchemaId == null)
{
return;
}
final AcctSchema as = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId);
final CurrencyPrecision precision = as.getStandardPrecision();
final BigDecimal controlAmt = precision.roundIfNeeded(journal.getControlAmt());
journal.setControlAmt(controlAmt);
}
} // MJournal | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StockChangedEvent implements MaterialEvent
{
public static final String TYPE = "StockChangedEvent";
EventDescriptor eventDescriptor;
ProductDescriptor productDescriptor;
WarehouseId warehouseId;
/** may be negative if a storage attribute is changed! */
BigDecimal qtyOnHand;
BigDecimal qtyOnHandOld;
/** optional; might be used by some handlers; if null then "now" is assumed. */
Instant changeDate;
StockChangeDetails stockChangeDetails;
@JsonCreator
@Builder
public StockChangedEvent(
@JsonProperty("eventDescriptor") final EventDescriptor eventDescriptor,
@JsonProperty("productDescriptor") final ProductDescriptor productDescriptor,
@JsonProperty("warehouseId") final WarehouseId warehouseId,
@JsonProperty("qtyOnHand") final BigDecimal qtyOnHand,
@JsonProperty("qtyOnHandOld") final BigDecimal qtyOnHandOld,
@JsonProperty("changeDate") final Instant changeDate,
@JsonProperty("stockChangeDetails") final StockChangeDetails stockChangeDetails)
{
this.eventDescriptor = eventDescriptor;
this.productDescriptor = productDescriptor;
this.warehouseId = warehouseId;
this.qtyOnHand = qtyOnHand;
this.qtyOnHandOld = qtyOnHandOld;
this.changeDate = changeDate;
this.stockChangeDetails = stockChangeDetails;
}
public void validate()
{
Check.errorIf(eventDescriptor == null, "eventDescriptor may not be null; this={}", this);
Check.errorIf(productDescriptor == null, "productDescriptor may not be null; this={}", this);
Check.errorIf(qtyOnHand == null, "qtyOnHand may not be null; this={}", this);
Check.errorIf(qtyOnHandOld == null, "qtyOnHandOld may not be null; this={}", this);
Check.errorIf(warehouseId == null, "warehouseId needs to set; this={}", this); | Check.errorIf(stockChangeDetails == null, "stockChangeDetails may not be null; this={}", this);
Check.errorIf(stockChangeDetails.getStockId() <= 0, "stockChangeDetails.stockId may not be null; this={}", this);
}
public int getProductId()
{
return productDescriptor.getProductId();
}
@Value
public static class StockChangeDetails
{
ResetStockPInstanceId resetStockPInstanceId;
int transactionId;
int stockId;
@JsonCreator
@Builder
public StockChangeDetails(
@JsonProperty("resetStockPInstanceId") final ResetStockPInstanceId resetStockPInstanceId,
@JsonProperty("transactionId") final int transactionId,
@JsonProperty("stockId") final int stockId)
{
this.resetStockPInstanceId = resetStockPInstanceId;
this.transactionId = transactionId;
this.stockId = stockId;
}
}
@Nullable
@Override
public TableRecordReference getSourceTableReference()
{
return TableRecordReference.ofNullable(I_M_Transaction.Table_Name, stockChangeDetails.getTransactionId());
}
@Override
public String getEventName() {return TYPE;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\stock\StockChangedEvent.java | 2 |
请完成以下Java代码 | public void fireBeforeCommit(final ITrx trx)
{
// Execute the "beforeCommit". On error, propagate the exception.
fireListeners(OnError.ThrowException, TrxEventTiming.BEFORE_COMMIT, trx);
}
private TrxEventTiming getCurrentTiming()
{
return runningWithinTrxEventTiming.get();
}
@Override
public void fireAfterCommit(final ITrx trx)
{
// Execute the "afterCommit", but don't fail because we are not allowed to fail by method's contract
fireListeners(OnError.LogAndSkip, TrxEventTiming.AFTER_COMMIT, trx);
}
@Override
public void fireAfterRollback(final ITrx trx)
{
// Execute the "afterRollback", but don't fail because we are not allowed to fail by method's contract
fireListeners(OnError.LogAndSkip, TrxEventTiming.AFTER_ROLLBACK, trx);
}
@Override
public void fireAfterClose(final ITrx trx)
{
// Execute the "afterClose", but don't fail because we are not allowed to fail by method's contract
fireListeners(OnError.LogAndSkip, TrxEventTiming.AFTER_CLOSE, trx);
}
private final void fireListeners(
@NonNull final OnError onError,
@NonNull final TrxEventTiming timingInfo,
@NonNull final ITrx trx)
{
if (listeners == null)
{
return;
}
runningWithinTrxEventTiming.set(timingInfo);
try
{
listeners.hardList().stream()
.filter(Objects::nonNull)
.filter(listener -> timingInfo.equals(listener.getTiming()))
.forEach(listener -> fireListener(onError, timingInfo, trx, listener));
}
finally
{
runningWithinTrxEventTiming.set(TrxEventTiming.NONE); | }
}
private void fireListener(
@NonNull final OnError onError,
@NonNull final TrxEventTiming timingInfo,
@NonNull final ITrx trx,
@Nullable final RegisterListenerRequest listener)
{
// shouldn't be necessary but in fact i just had an NPE at this place
if (listener == null || !listener.isActive())
{
return;
}
// Execute the listener method
try
{
listener.getHandlingMethod().onTransactionEvent(trx);
}
catch (final Exception ex)
{
handleException(onError, timingInfo, listener, ex);
}
finally
{
if (listener.isInvokeMethodJustOnce())
{
listener.deactivate();
}
}
}
private void handleException(
@NonNull final OnError onError,
@NonNull final TrxEventTiming timingInfo,
@NonNull final RegisterListenerRequest listener,
@NonNull final Exception ex)
{
if (onError == OnError.LogAndSkip)
{
logger.warn("Error while invoking {} using {}. Error was discarded.", timingInfo, listener, ex);
}
else // if (onError == OnError.ThrowException)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("listener", listener)
.setParameter(timingInfo)
.appendParametersToMessage();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\TrxListenerManager.java | 1 |
请完成以下Java代码 | public IReplRequestHandler getRequestHandlerInstance(@NonNull final I_IMP_RequestHandler requestHandlerDef)
{
Check.assume(requestHandlerDef.isActive(), "Request handler {} is active", requestHandlerDef);
final I_IMP_RequestHandlerType requestHandlerType = requestHandlerDef.getIMP_RequestHandlerType();
Check.assume(requestHandlerType.isActive(), "Request handler type {} is active", requestHandlerType);
final String classname = requestHandlerType.getClassname();
final IReplRequestHandler requestHandler = Util.getInstance(IReplRequestHandler.class, classname);
return requestHandler;
}
@Override
public Document processRequestHandlerResult(final IReplRequestHandlerResult result)
{
final PO poToExport = result.getPOToExport();
if (poToExport == null)
{
logger.debug("Skip because poToExport is null");
return null;
}
final I_EXP_Format formatToUse = result.getFormatToUse();
Check.errorIf(formatToUse == null, "formatToUse shall be set");
final MEXPFormat formatToUsePO = (MEXPFormat)InterfaceWrapperHelper.getStrictPO(formatToUse);
final ExportHelper exportHelper = new ExportHelper(
poToExport.getCtx(),
ClientId.ofRepoId(formatToUse.getAD_Client_ID()));
return exportHelper.createExportDOM(poToExport,
formatToUsePO,
0, // ReplicationMode
X_AD_ReplicationTable.REPLICATIONTYPE_Merge,
0 // ReplicationEvent
);
}
@Override
public IReplRequestHandlerResult createInitialRequestHandlerResult()
{ | return new ReplRequestHandlerResult();
}
@Override
public I_IMP_RequestHandlerType registerHandlerType(
final String name,
final Class<? extends IReplRequestHandler> clazz,
final String entityType)
{
// TODO check if it already exists (by clazz and entityType).
// If it exists, then Util.assume that AD_Client_ID=0 and return it
// if it doesn't yet exist, then create it, save and return
// final String classname = clazz.getName();
// final int adClientId = 0;
//
// final String whereClause = I_IMP_RequestHandlerType.COLUMNNAME_Classname+"=?"
// +" AND "+I_IMP_RequestHandlerType.COLUMNNAME_EntityType+"=?"
// +" AND "+I_IMP_RequestHandlerType.COLUMNNAME_AD_Client_ID+"=?"
// new Query(Env.getCtx(), I_IMP_RequestHandlerType.Table_Name, whereClause, Trx.TRXNAME_None)
// .setParameters(classname, entityType, adClientId)
return null;
}
@Override
public IReplRequestHandlerCtx createCtx(
final Properties ctxForHandler,
final I_EXP_Format importFormat,
final I_IMP_RequestHandler requestHandlerRecord)
{
final ReplRequestHandlerCtx ctx = new ReplRequestHandlerCtx();
ctx.setEnvCtxToUse(ctxForHandler);
ctx.setImportFormat(importFormat);
ctx.setRequestHandlerRecord(requestHandlerRecord);
return ctx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\requesthandler\api\impl\ReplRequestHandlerBL.java | 1 |
请完成以下Java代码 | public Set<I_M_HU> getHUsForReceipts(final Collection<? extends I_M_InOut> receipts)
{
final Set<I_M_HU> hus = new TreeSet<>(HUByIdComparator.instance);
for (final I_M_InOut receipt : receipts)
{
final int inoutId = receipt.getM_InOut_ID();
final Collection<I_M_HU> husForReceipt = inoutId2hus.get(inoutId);
if (Check.isEmpty(husForReceipt))
{
continue;
}
hus.addAll(husForReceipt);
}
return hus;
}
public static final class Builder
{
private I_M_ReceiptSchedule receiptSchedule;
private boolean tolerateNoHUsFound = false;
private Builder()
{
super();
}
public ReceiptCorrectHUsProcessor build()
{
return new ReceiptCorrectHUsProcessor(this);
}
public Builder setM_ReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule) | {
this.receiptSchedule = receiptSchedule;
return this;
}
private I_M_ReceiptSchedule getM_ReceiptSchedule()
{
Check.assumeNotNull(receiptSchedule, "Parameter receiptSchedule is not null");
return receiptSchedule;
}
public Builder tolerateNoHUsFound()
{
tolerateNoHUsFound = true;
return this;
}
private boolean isFailOnNoHUsFound()
{
return !tolerateNoHUsFound;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\ReceiptCorrectHUsProcessor.java | 1 |
请完成以下Java代码 | public static EmailAddress ofString(@NonNull final String emailAddress)
{
return new EmailAddress(emailAddress, DeactivatedOnRemotePlatform.UNKNOWN);
}
public static EmailAddress ofStringOrNull(@Nullable final String emailAddress)
{
return emailAddress != null && !Check.isBlank(emailAddress)
? ofString(emailAddress)
: null;
}
public static EmailAddress of(
@NonNull final String emailAddress,
@NonNull final DeactivatedOnRemotePlatform deactivatedOnRemotePlatform)
{
return new EmailAddress(emailAddress, deactivatedOnRemotePlatform);
}
private EmailAddress(
@NonNull final String value,
@NonNull final DeactivatedOnRemotePlatform deactivatedOnRemotePlatform) | {
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm == null)
{
throw new AdempiereException("blank email address is not allowed");
}
this.value = valueNorm;
this.deactivatedOnRemotePlatform = deactivatedOnRemotePlatform;
}
@Override
public TYPE getType()
{
return TYPE.EMAIL;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\EmailAddress.java | 1 |
请完成以下Java代码 | public class ImageSearcher {
private MilvusServiceClient milvusClient;
public ImageSearcher() {
// 连接到Milvus
milvusClient = new MilvusServiceClient(
ConnectParam.newBuilder()
.withUri("https://in03-xxx.serverless.gcp-us-west1.cloud.zilliz.com")
.withToken("xx")
.build());
}
public void search(INDArray queryFeatures) {
// 在Milvus中进行相似性搜索
float[] floatArray = queryFeatures.toFloatVector();
List<Float> floatList = new ArrayList<>();
for (float f : floatArray) {
floatList.add(f);
} | List<List<Float>> vectors = Collections.singletonList(floatList);
SearchParam searchParam = SearchParam.newBuilder()
.withCollectionName("image_collection")
.withMetricType(MetricType.L2)
.withTopK(5)
.withVectors(vectors)
.withVectorFieldName("embedding")
.build();
R<SearchResults> searchResults = milvusClient.search(searchParam);
System.out.println("Searching vector: " + queryFeatures.toFloatVector());
System.out.println("Result: " + searchResults.getData().getResults().getFieldsDataList());
}
} | repos\springboot-demo-master\Milvus\src\main\java\com\et\imagesearch\ImageSearcher.java | 1 |
请完成以下Java代码 | public final class JwtClaimNames {
/**
* {@code iss} - the Issuer claim identifies the principal that issued the JWT
*/
public static final String ISS = "iss";
/**
* {@code sub} - the Subject claim identifies the principal that is the subject of the
* JWT
*/
public static final String SUB = "sub";
/**
* {@code aud} - the Audience claim identifies the recipient(s) that the JWT is
* intended for
*/
public static final String AUD = "aud";
/**
* {@code exp} - the Expiration time claim identifies the expiration time on or after
* which the JWT MUST NOT be accepted for processing
*/
public static final String EXP = "exp";
/** | * {@code nbf} - the Not Before claim identifies the time before which the JWT MUST
* NOT be accepted for processing
*/
public static final String NBF = "nbf";
/**
* {@code iat} - The Issued at claim identifies the time at which the JWT was issued
*/
public static final String IAT = "iat";
/**
* {@code jti} - The JWT ID claim provides a unique identifier for the JWT
*/
public static final String JTI = "jti";
private JwtClaimNames() {
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimNames.java | 1 |
请完成以下Java代码 | public void setPort(int port) {
this.port = port;
}
public String[] getCc() {
return cc;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public List<String> getBcc() {
return bcc;
}
public void setBcc(List<String> bcc) {
this.bcc = bcc;
}
public class Credential {
@NotNull
private String userName;
@Size(max= 15, min=6)
private String password; | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
} | repos\SpringBoot-Projects-FullStack-master\Part-1 Spring Boot Basic Fund Projects\SpringBootSourceCode\SpringEmailProcess\src\main\java\spring\basic\MailProperties.java | 1 |
请完成以下Java代码 | public int getC_Async_Batch_Type_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Async_Batch_Type_ID);
}
@Override
public void setInternalName (final String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
@Override
public void setKeepAliveTimeHours (final @Nullable String KeepAliveTimeHours)
{
set_Value (COLUMNNAME_KeepAliveTimeHours, KeepAliveTimeHours);
}
@Override
public String getKeepAliveTimeHours()
{
return get_ValueAsString(COLUMNNAME_KeepAliveTimeHours);
}
/**
* NotificationType AD_Reference_ID=540643 | * Reference name: _NotificationType
*/
public static final int NOTIFICATIONTYPE_AD_Reference_ID=540643;
/** Async Batch Processed = ABP */
public static final String NOTIFICATIONTYPE_AsyncBatchProcessed = "ABP";
/** Workpackage Processed = WPP */
public static final String NOTIFICATIONTYPE_WorkpackageProcessed = "WPP";
@Override
public void setNotificationType (final @Nullable String NotificationType)
{
set_Value (COLUMNNAME_NotificationType, NotificationType);
}
@Override
public String getNotificationType()
{
return get_ValueAsString(COLUMNNAME_NotificationType);
}
@Override
public void setSkipTimeoutMillis (final int SkipTimeoutMillis)
{
set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis);
}
@Override
public int getSkipTimeoutMillis()
{
return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Async_Batch_Type.java | 1 |
请完成以下Java代码 | private void validate(ReadTsKvQuery query) {
if (query == null) {
throw new IncorrectParameterException("ReadTsKvQuery can't be null");
} else if (isBlank(query.getKey())) {
throw new IncorrectParameterException("Incorrect ReadTsKvQuery. Key can't be empty");
} else if (query.getAggregation() == null) {
throw new IncorrectParameterException("Incorrect ReadTsKvQuery. Aggregation can't be empty");
}
if (!Aggregation.NONE.equals(query.getAggregation())) {
long interval = query.getInterval();
if (interval < 1) {
throw new IncorrectParameterException("Invalid TsKvQuery: 'interval' must be greater than 0, but got " + interval +
". Please check your query parameters and ensure 'endTs' is greater than 'startTs' or increase 'interval'.");
}
long step = Math.max(interval, 1000);
long intervalCounts = (query.getEndTs() - query.getStartTs()) / step; | if (intervalCounts > maxTsIntervals || intervalCounts < 0) {
throw new IncorrectParameterException("Incorrect TsKvQuery. Number of intervals is to high - " + intervalCounts + ". " +
"Please increase 'interval' parameter for your query or reduce the time range of the query.");
}
}
}
private static void validate(DeleteTsKvQuery query) {
if (query == null) {
throw new IncorrectParameterException("DeleteTsKvQuery can't be null");
} else if (isBlank(query.getKey())) {
throw new IncorrectParameterException("Incorrect DeleteTsKvQuery. Key can't be empty");
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\timeseries\BaseTimeseriesService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (messageNo == null ? 0 : messageNo.hashCode());
result = prime * result + (partner == null ? 0 : partner.hashCode());
result = prime * result + (qualifier == null ? 0 : qualifier.hashCode());
result = prime * result + (record == null ? 0 : record.hashCode());
result = prime * result + (text1 == null ? 0 : text1.hashCode());
result = prime * result + (text2 == null ? 0 : text2.hashCode());
result = prime * result + (text3 == null ? 0 : text3.hashCode());
result = prime * result + (text4 == null ? 0 : text4.hashCode());
result = prime * result + (text5 == null ? 0 : text5.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final H120 other = (H120)obj;
if (messageNo == null)
{
if (other.messageNo != null)
{
return false;
}
}
else if (!messageNo.equals(other.messageNo))
{
return false;
}
if (partner == null)
{
if (other.partner != null)
{
return false;
}
}
else if (!partner.equals(other.partner))
{
return false;
}
if (qualifier == null)
{
if (other.qualifier != null)
{
return false;
}
}
else if (!qualifier.equals(other.qualifier))
{
return false;
}
if (record == null)
{
if (other.record != null)
{
return false;
}
}
else if (!record.equals(other.record))
{
return false;
}
if (text1 == null)
{
if (other.text1 != null)
{
return false;
}
}
else if (!text1.equals(other.text1))
{
return false;
}
if (text2 == null)
{
if (other.text2 != null)
{
return false;
}
}
else if (!text2.equals(other.text2))
{
return false; | }
if (text3 == null)
{
if (other.text3 != null)
{
return false;
}
}
else if (!text3.equals(other.text3))
{
return false;
}
if (text4 == null)
{
if (other.text4 != null)
{
return false;
}
}
else if (!text4.equals(other.text4))
{
return false;
}
if (text5 == null)
{
if (other.text5 != null)
{
return false;
}
}
else if (!text5.equals(other.text5))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "H120 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", qualifier=" + qualifier + ", text1=" + text1 + ", text2=" + text2
+ ", text3=" + text3 + ", text4="
+ text4 + ", text5=" + text5 + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\ordersimport\compudata\H120.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private Quantity getQtyToReserveParam()
{
final Quantity qtyToReserve = Quantitys.of(qty, uomId);
if (qtyToReserve.signum() <= 0)
{
throw new FillMandatoryException(PARAM_Qty);
}
return qtyToReserve;
}
private ServiceRepairProjectTask getTask()
{
return tasksCache.computeIfAbsent(getTaskId(), projectService::getTaskById);
}
private ServiceRepairProjectTaskId getTaskId() | {
final HUsToIssueViewContext husToIssueViewContext = getHusToIssueViewContext();
return husToIssueViewContext.getTaskId();
}
private ImmutableSet<HuId> getSelectedTopLevelHUIds()
{
return streamSelectedHUIds(HUEditorRowFilter.Select.ONLY_TOPLEVEL).collect(ImmutableSet.toImmutableSet());
}
private HUsToIssueViewContext getHusToIssueViewContext()
{
return getView()
.getParameter(HUsToIssueViewFactory.PARAM_HUsToIssueViewContext, HUsToIssueViewContext.class)
.orElseThrow(() -> new AdempiereException("No view context"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\HUsToIssueView_IssueHUs.java | 2 |
请完成以下Java代码 | public String getReplacement() {
return replacement;
}
public void setReplacement(String replacement) {
this.replacement = replacement;
}
}
public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> {
private final Pattern fields;
private final String replacement;
public Scrubber(Config config) {
this.fields = Pattern.compile(config.getFields());
this.replacement = config.getReplacement();
}
@Override
public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) {
return Mono.just(scrubRecursively(u));
}
private JsonNode scrubRecursively(JsonNode u) {
if ( !u.isContainerNode()) {
return u;
}
if ( u.isObject()) {
ObjectNode node = (ObjectNode)u;
node.fields().forEachRemaining((f) -> { | if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) {
f.setValue(TextNode.valueOf(replacement));
}
else {
f.setValue(scrubRecursively(f.getValue()));
}
});
}
else if ( u.isArray()) {
ArrayNode array = (ArrayNode)u;
for ( int i = 0 ; i < array.size() ; i++ ) {
array.set(i, scrubRecursively(array.get(i)));
}
}
return u;
}
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ScrubResponseGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name); | sb.append(", type=").append(type);
sb.append(", pic=").append(pic);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", status=").append(status);
sb.append(", clickCount=").append(clickCount);
sb.append(", orderCount=").append(orderCount);
sb.append(", url=").append(url);
sb.append(", note=").append(note);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeAdvertise.java | 1 |
请完成以下Java代码 | public Connection getConnection(final boolean autoCommit, final int transactionIsolation)
{
final AdempiereDatabase db = getDatabase(); // creates connection if not already exist
if (db == null)
{
throw new DBNoConnectionException("No AdempiereDatabase found");
}
Connection conn = null;
boolean connOk = false;
try
{
conn = db.getCachedConnection(this, autoCommit, transactionIsolation);
if (conn == null)
{
// shall not happen
throw new DBNoConnectionException();
}
// Mark the database connection status as OK
_okDB = true;
connOk = true;
return conn;
}
catch (final UnsatisfiedLinkError ule)
{
_okDB = false;
final String msg = ule.getLocalizedMessage() + " -> Did you set the LD_LIBRARY_PATH ? - " + getConnectionURL();
throw new DBNoConnectionException(msg, ule);
}
catch (final Exception ex)
{
_okDB = false;
throw DBNoConnectionException.wrapIfNeeded(ex);
}
finally
{
if (!connOk)
{
DB.close(conn);
}
}
} // getConnection
/**
* Get Transaction Isolation Info
*
* @return transaction isolation name
*/
@SuppressWarnings("unused")
private static String getTransactionIsolationInfo(int transactionIsolation)
{
if (transactionIsolation == Connection.TRANSACTION_NONE)
{ | return "NONE";
}
if (transactionIsolation == Connection.TRANSACTION_READ_COMMITTED)
{
return "READ_COMMITTED";
}
if (transactionIsolation == Connection.TRANSACTION_READ_UNCOMMITTED)
{
return "READ_UNCOMMITTED";
}
if (transactionIsolation == Connection.TRANSACTION_REPEATABLE_READ)
{
return "REPEATABLE_READ";
}
if (transactionIsolation == Connection.TRANSACTION_SERIALIZABLE)
{
return "SERIALIZABLE";
}
return "<?" + transactionIsolation + "?>";
} // getTransactionIsolationInfo
@Override
public Object clone() throws CloneNotSupportedException
{
CConnection c = (CConnection)super.clone();
return c;
}
} // CConnection | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Replacement
{
@NonNull
Type type;
@NonNull
String value;
@NonNull
@Getter(AccessLevel.NONE)
String replacementValue;
private Replacement(
@NonNull final Type type,
@NonNull final String value,
@NonNull final String replacementValue)
{
this.type = type;
this.value = value;
this.replacementValue = replacementValue;
}
@NonNull
public static Replacement of(@NonNull final String value)
{
final Matcher jsonPathMatcher = Type.JSON_PATH.pattern.matcher(value);
if (jsonPathMatcher.matches())
{
final String jsonPathReplacementValue = jsonPathMatcher.group(1);
return new Replacement(Type.JSON_PATH, value, jsonPathReplacementValue);
} | throw new RuntimeCamelException("Unknown Replacement type!");
}
@NonNull
public String getJsonPath()
{
Check.assume(this.type.equals(Type.JSON_PATH), "Type should be JSON_PATH at this stage, but instead is {}", this.type);
return replacementValue;
}
@AllArgsConstructor
@Getter
public enum Type
{
JSON_PATH(Pattern.compile("\\@JsonPath=(.*)\\@"));
private final Pattern pattern;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\util\Replacement.java | 2 |
请完成以下Java代码 | public int getM_Product_ID()
{
return M_Product_ID;
}
@Override
public int getC_Charge_ID()
{
return C_Charge_ID;
}
@Override
public int getC_OrderLine_ID()
{
return C_OrderLine_ID;
}
@Override
public void setM_Product_ID(final int m_Product_ID)
{
M_Product_ID = m_Product_ID;
}
@Override
public void setC_Charge_ID(final int c_Charge_ID)
{
C_Charge_ID = c_Charge_ID;
}
@Override
public void setC_OrderLine_ID(final int c_OrderLine_ID)
{
C_OrderLine_ID = c_OrderLine_ID;
}
@Override
public final void addQtysToInvoice(@NonNull final StockQtyAndUOMQty qtysToInvoiceToAdd)
{
final StockQtyAndUOMQty qtysToInvoiceOld = getQtysToInvoice();
final StockQtyAndUOMQty qtysToInvoiceNew;
if (qtysToInvoiceOld == null)
{
qtysToInvoiceNew = qtysToInvoiceToAdd;
}
else
{
qtysToInvoiceNew = qtysToInvoiceOld.add(qtysToInvoiceToAdd);
}
setQtysToInvoice(qtysToInvoiceNew);
}
@Nullable
@Override
public String getDescription()
{
return description;
}
@Override
public void setDescription(@Nullable final String description)
{
this.description = description;
}
@Override
public Collection<Integer> getC_InvoiceCandidate_InOutLine_IDs()
{
return iciolIds;
}
@Override
public void negateAmounts()
{
setQtysToInvoice(getQtysToInvoice().negate());
setNetLineAmt(getNetLineAmt().negate());
}
@Override
public int getC_Activity_ID()
{
return activityID;
}
@Override
public void setC_Activity_ID(final int activityID)
{
this.activityID = activityID;
}
@Override
public Tax getC_Tax()
{
return tax;
}
@Override
public void setC_Tax(final Tax tax)
{
this.tax = tax;
}
@Override
public boolean isPrinted()
{
return printed;
} | @Override
public void setPrinted(final boolean printed)
{
this.printed = printed;
}
@Override
public int getLineNo()
{
return lineNo;
}
@Override
public void setLineNo(final int lineNo)
{
this.lineNo = lineNo;
}
@Override
public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes)
{
this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes);
}
@Override
public List<IInvoiceLineAttribute> getInvoiceLineAttributes()
{
return invoiceLineAttributes;
}
@Override
public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate()
{
return iciolsToUpdate;
}
@Override
public int getC_PaymentTerm_ID()
{
return C_PaymentTerm_ID;
}
@Override
public void setC_PaymentTerm_ID(final int paymentTermId)
{
C_PaymentTerm_ID = paymentTermId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java | 1 |
请完成以下Java代码 | public void setAD_Session_ID (int AD_Session_ID)
{
if (AD_Session_ID < 1)
set_Value (COLUMNNAME_AD_Session_ID, null);
else
set_Value (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID));
}
@Override
public int getAD_Session_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Session_ID);
}
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Login_ID (int AD_User_Login_ID)
{
if (AD_User_Login_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Login_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Login_ID, Integer.valueOf(AD_User_Login_ID));
}
@Override
public int getAD_User_Login_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Login_ID);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey() | {
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
@Override
public void setPassword (java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return (java.lang.String)get_Value(COLUMNNAME_Password);
}
@Override
public void setUserName (java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_User_Login.java | 1 |
请完成以下Java代码 | public String getTenantId() {
return activiti5ProcessInstance.getTenantId();
}
@Override
public String getName() {
return activiti5ProcessInstance.getName();
}
@Override
public String getDescription() {
return activiti5ProcessInstance.getDescription();
}
@Override
public String getLocalizedName() {
return activiti5ProcessInstance.getLocalizedName();
}
@Override
public String getLocalizedDescription() {
return activiti5ProcessInstance.getLocalizedDescription();
}
public org.activiti.engine.runtime.ProcessInstance getRawObject() {
return activiti5ProcessInstance;
}
@Override
public Date getStartTime() {
return null;
} | @Override
public String getStartUserId() {
return null;
}
@Override
public String getCallbackId() {
return null;
}
@Override
public String getCallbackType() {
return null;
}
@Override
public String getReferenceId() {
return null;
}
@Override
public String getReferenceType() {
return null;
}
@Override
public String getPropagatedStageInstanceId() {
return null;
}
} | repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5ProcessInstanceWrapper.java | 1 |
请完成以下Java代码 | public Object getCellEditorValue()
{
if (editor == null)
{
return null;
}
return editor.getValue();
}
@Override
public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int rowIndex, final int columnIndex)
{
final IUserQueryRestriction row = getRow(table, rowIndex);
//
// Update valueTo enabled
final Operator operator = row.getOperator();
isValueToEnabled = isValueToColumn && operator != null && operator.isRangeOperator();
final FindPanelSearchField searchField = FindPanelSearchField.castToFindPanelSearchField(row.getSearchField());
if (searchField == null)
{
// shall not happen
return null;
}
// Make sure the old editor is destroyed
destroyEditor();
// Create editor
editor = searchField.createEditor(true);
editor.setReadWrite(isValueDisplayed());
editor.setValue(value);
return swingEditorFactory.getEditorComponent(editor);
}
private final boolean isValueDisplayed()
{
return !isValueToColumn || isValueToColumn && isValueToEnabled;
}
@Override
public boolean isCellEditable(final EventObject e)
{
return true;
}
@Override
public boolean shouldSelectCell(final EventObject e) | {
return isValueDisplayed();
}
private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex)
{
final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel();
final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex);
return model.getRow(modelRowIndex);
}
/**
* Destroy existing editor.
*
* Very important to be called because this will also unregister the listeners from editor to underlying lookup (if any).
*/
private final void destroyEditor()
{
if (editor == null)
{
return;
}
editor.dispose();
editor = null;
}
@Override
public boolean stopCellEditing()
{
if (!super.stopCellEditing())
{
return false;
}
destroyEditor();
return true;
}
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
destroyEditor();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindValueEditor.java | 1 |
请完成以下Java代码 | Banner print(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) {
Banner banner = getBanner(environment);
banner.printBanner(environment, sourceClass, out);
return new PrintedBanner(banner, sourceClass);
}
private Banner getBanner(Environment environment) {
Banner textBanner = getTextBanner(environment);
if (textBanner != null) {
return textBanner;
}
if (this.fallbackBanner != null) {
return this.fallbackBanner;
}
return DEFAULT_BANNER;
}
private @Nullable Banner getTextBanner(Environment environment) {
String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
Resource resource = this.resourceLoader.getResource(location);
try {
if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) {
return new ResourceBanner(resource);
}
}
catch (IOException ex) {
// Ignore
}
return null;
}
private String createStringFromBanner(Banner banner, Environment environment,
@Nullable Class<?> mainApplicationClass) throws UnsupportedEncodingException {
String charset = environment.getProperty("spring.banner.charset", StandardCharsets.UTF_8.name());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (PrintStream out = new PrintStream(byteArrayOutputStream, false, charset)) {
banner.printBanner(environment, mainApplicationClass, out);
}
return byteArrayOutputStream.toString(charset);
}
/** | * Decorator that allows a {@link Banner} to be printed again without needing to
* specify the source class.
*/
private static class PrintedBanner implements Banner {
private final Banner banner;
private final @Nullable Class<?> sourceClass;
PrintedBanner(Banner banner, @Nullable Class<?> sourceClass) {
this.banner = banner;
this.sourceClass = sourceClass;
}
@Override
public void printBanner(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) {
sourceClass = (sourceClass != null) ? sourceClass : this.sourceClass;
this.banner.printBanner(environment, sourceClass, out);
}
}
static class SpringApplicationBannerPrinterRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern(DEFAULT_BANNER_LOCATION);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationBannerPrinter.java | 1 |
请完成以下Java代码 | private POSProduct toPOSProductNoFail(@NonNull final I_M_ProductPrice productPrice)
{
try
{
return toPOSProduct(productPrice);
}
catch (Exception ex)
{
logger.warn("Failed converting {} to POSProduct. Skipped.", productPrice, ex);
return null;
}
}
private POSProduct toPOSProduct(@NonNull final I_M_ProductPrice productPrice)
{
final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID());
final UomId uomId;
final UomId catchWeightUomId;
final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.ofCode(productPrice.getInvoicableQtyBasedOn());
switch (invoicableQtyBasedOn)
{
case NominalWeight:
uomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
catchWeightUomId = null;
break;
case CatchWeight:
uomId = getProductUomId(productId);
catchWeightUomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
break;
default:
throw new AdempiereException("Unknown invoicableQtyBasedOn: " + invoicableQtyBasedOn);
}
return POSProduct.builder()
.id(productId)
.name(getProductName(productId))
.price(extractPrice(productPrice))
.currencySymbol(currency.getSymbol())
.uom(toUomIdAndSymbol(uomId))
.catchWeightUom(catchWeightUomId != null ? toUomIdAndSymbol(catchWeightUomId) : null)
.taxCategoryId(TaxCategoryId.ofRepoId(productPrice.getC_TaxCategory_ID()))
.build();
} | private ITranslatableString getProductName(final ProductId productId)
{
final I_M_Product product = getProductById(productId);
final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(product);
return trls.getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName());
}
private UomId getProductUomId(final ProductId productId)
{
final I_M_Product product = getProductById(productId);
return UomId.ofRepoId(product.getC_UOM_ID());
}
private Amount extractPrice(final I_M_ProductPrice productPrice)
{
return Amount.of(productPrice.getPriceStd(), currency.getCurrencyCode());
}
private String getUOMSymbol(final UomId uomId)
{
final I_C_UOM uom = uomDAO.getById(uomId);
return StringUtils.trimBlankToOptional(uom.getUOMSymbol()).orElseGet(uom::getName);
}
private UomIdAndSymbol toUomIdAndSymbol(final UomId uomId)
{
return UomIdAndSymbol.of(uomId, getUOMSymbol(uomId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StudentManagementController {
//
private static final List<Student> STUDENTS = Arrays.asList(
new Student(1, "James Bond"),
new Student(2, "Lary Gaga"),
new Student(3, "Faktor2"),
new Student(4, "Anna "),
new Student(5, "Anna German ")
);
@GetMapping
@PreAuthorize("hasAnyRole('ROLE_ADMIN, ROLE_ADMINTRAINEE')")
public List<Student> getAllStudents(){
return STUDENTS;
}
@PostMapping
@PreAuthorize("hasAuthority('student:write')")
public void registerNewStudent(@RequestBody Student student){ | System.out.println("registerNewStudent");
System.out.println(student);
}
@DeleteMapping(path = "{studentId}")
@PreAuthorize("hasAuthority('student:write')")
public void deleteStudent(@PathVariable() Integer studentId){
System.out.println("deleteStudent");
System.out.println(studentId);
}
@PutMapping(path = "{studentId}")
@PreAuthorize("hasAuthority('student:write')")
public void updateStudent(@PathVariable("studentId") Integer studentId, @RequestBody Student student){
System.out.println("Update student INFO.");
System.out.println(String.format("%s %s", studentId, student));
}
} | repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\form-based-authentication\form-based-authentication\src\main\java\uz\bepro\formbasedauthentication\controller\StudentManagementController.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.