instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
void loadKeyStore() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
char[] pwdArray = keyStorePassword.toCharArray();
FileInputStream fis = new FileInputStream(keyStoreName);
keyStore.load(fis, pwdArray);
fis.close();
}
void setEntry(String alias, KeyStore.SecretKeyEntry secretKeyEntry, KeyStore.ProtectionParameter protectionParameter) throws KeyStoreException {
keyStore.setEntry(alias, secretKeyEntry, protectionParameter);
}
KeyStore.Entry getEntry(String alias) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException {
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());
return keyStore.getEntry(alias, protParam);
}
void setKeyEntry(String alias, PrivateKey privateKey, String keyPassword, Certificate[] certificateChain) throws KeyStoreException {
keyStore.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), certificateChain);
}
void setCertificateEntry(String alias, Certificate certificate) throws KeyStoreException {
keyStore.setCertificateEntry(alias, certificate);
}
Certificate getCertificate(String alias) throws KeyStoreException {
return keyStore.getCertificate(alias);
}
void deleteEntry(String alias) throws KeyStoreException {
keyStore.deleteEntry(alias);
}
void deleteKeyStore() throws KeyStoreException, IOException {
|
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
keyStore.deleteEntry(alias);
}
keyStore = null;
Path keyStoreFile = Paths.get(keyStoreName);
Files.delete(keyStoreFile);
}
KeyStore getKeyStore() {
return this.keyStore;
}
}
|
repos\tutorials-master\core-java-modules\core-java-security\src\main\java\com\baeldung\keystore\JavaKeyStore.java
| 1
|
请完成以下Java代码
|
public void setCM_CStage_ID (int CM_CStage_ID)
{
if (CM_CStage_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_CStage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_CStage_ID, Integer.valueOf(CM_CStage_ID));
}
/** Get Web Container Stage.
@return Web Container Stage contains the staging content like images, text etc.
*/
public int getCM_CStage_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_CStage_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Content HTML.
@param ContentHTML
Contains the content itself
*/
public void setContentHTML (String ContentHTML)
{
set_Value (COLUMNNAME_ContentHTML, ContentHTML);
}
/** Get Content HTML.
@return Contains the content itself
*/
public String getContentHTML ()
{
return (String)get_Value(COLUMNNAME_ContentHTML);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
|
}
/** Set Valid.
@param IsValid
Element is valid
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Valid.
@return Element is valid
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_CStage_Element.java
| 1
|
请完成以下Java代码
|
public class UnlockJobCmd implements Command<Void> {
protected static final long serialVersionUID = 1L;
private final static JobExecutorLogger LOG = ProcessEngineLogger.JOB_EXECUTOR_LOGGER;
protected String jobId;
public UnlockJobCmd(String jobId) {
this.jobId = jobId;
}
protected JobEntity getJob() {
return Context.getCommandContext().getJobManager().findJobById(jobId);
}
public Void execute(CommandContext commandContext) {
JobEntity job = getJob();
if (Context.getJobExecutorContext() == null) {
EnsureUtil.ensureNotNull("Job with id " + jobId + " does not exist", "job", job);
|
}
else if (Context.getJobExecutorContext() != null && job == null) {
// CAM-1842
// Job was acquired but does not exist anymore. This is not a problem.
// It usually means that the job has been deleted after it was acquired which can happen if the
// the activity instance corresponding to the job is cancelled.
LOG.debugAcquiredJobNotFound(jobId);
return null;
}
job.unlock();
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UnlockJobCmd.java
| 1
|
请完成以下Java代码
|
public abstract class PaginatedUpdater<I, D> {
private static final int DEFAULT_LIMIT = 100;
private int updated = 0;
public void updateEntities(I id) {
updated = 0;
PageLink pageLink = new PageLink(DEFAULT_LIMIT);
boolean hasNext = true;
while (hasNext) {
PageData<D> entities = findEntities(id, pageLink);
for (D entity : entities.getData()) {
updateEntity(entity);
}
updated += entities.getData().size();
hasNext = entities.hasNext();
if (hasNext) {
log.info("{}: {} entities updated so far...", getName(), updated);
pageLink = pageLink.nextPageLink();
} else {
if (updated > DEFAULT_LIMIT || forceReportTotal()) {
log.info("{}: {} total entities updated.", getName(), updated);
}
}
}
|
}
public void updateEntities() {
updateEntities(null);
}
protected boolean forceReportTotal() {
return false;
}
protected abstract String getName();
protected abstract PageData<D> findEntities(I id, PageLink pageLink);
protected abstract void updateEntity(D entity);
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\install\update\PaginatedUpdater.java
| 1
|
请完成以下Java代码
|
public String getFormat()
{
return format;
}
public void setFormat(String format)
{
this.format = format;
}
public List<PrintPackageInfo> getPrintPackageInfos()
{
if (printPackageInfos == null)
{
return Collections.emptyList();
}
return printPackageInfos;
}
public void setPrintPackageInfos(List<PrintPackageInfo> printPackageInfos)
{
this.printPackageInfos = printPackageInfos;
}
public String getPrintJobInstructionsID()
{
return printJobInstructionsID;
}
public void setPrintJobInstructionsID(String printJobInstructionsID)
{
this.printJobInstructionsID = printJobInstructionsID;
}
public int getCopies()
{
return copies;
}
public void setCopies(final int copies)
{
this.copies = copies;
}
@Override
public String toString()
{
return String.format("PrintPackage [transactionId=%s, printPackageId=%s, pageCount=%s, copies=%s, format=%s, printPackageInfos=%s, printJobInstructionsID=%s]", transactionId, printPackageId,
pageCount, copies, format, printPackageInfos, printJobInstructionsID);
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + copies;
result = prime * result + ((format == null) ? 0 : format.hashCode());
result = prime * result + pageCount;
result = prime * result + ((printJobInstructionsID == null) ? 0 : printJobInstructionsID.hashCode());
result = prime * result + ((printPackageId == null) ? 0 : printPackageId.hashCode());
result = prime * result + ((printPackageInfos == null) ? 0 : printPackageInfos.hashCode());
result = prime * result + ((transactionId == null) ? 0 : transactionId.hashCode());
return result;
}
|
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintPackage other = (PrintPackage)obj;
if (copies != other.copies)
return false;
if (format == null)
{
if (other.format != null)
return false;
}
else if (!format.equals(other.format))
return false;
if (pageCount != other.pageCount)
return false;
if (printJobInstructionsID == null)
{
if (other.printJobInstructionsID != null)
return false;
}
else if (!printJobInstructionsID.equals(other.printJobInstructionsID))
return false;
if (printPackageId == null)
{
if (other.printPackageId != null)
return false;
}
else if (!printPackageId.equals(other.printPackageId))
return false;
if (printPackageInfos == null)
{
if (other.printPackageInfos != null)
return false;
}
else if (!printPackageInfos.equals(other.printPackageInfos))
return false;
if (transactionId == null)
{
if (other.transactionId != null)
return false;
}
else if (!transactionId.equals(other.transactionId))
return false;
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackage.java
| 1
|
请完成以下Java代码
|
public static void initialize() {
algorithm = Algorithm.HMAC256(SECRET);
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String createJWT() {
String jwtToken = JWT.create()
.withIssuer(ISSUER)
.withSubject(SUBJECT)
.withClaim(DATA_CLAIM, DATA)
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_VALIDITY_IN_MILLIS))
.withJWTId(UUID.randomUUID()
.toString())
.withNotBefore(new Date(System.currentTimeMillis() + 1000L))
.sign(algorithm);
return jwtToken;
}
private static DecodedJWT verifyJWT(String jwtToken) {
try {
DecodedJWT decodedJWT = verifier.verify(jwtToken);
return decodedJWT;
} catch (JWTVerificationException e) {
System.out.println(e.getMessage());
}
return null;
}
private static boolean isJWTExpired(DecodedJWT decodedJWT) {
Date expiresAt = decodedJWT.getExpiresAt();
return expiresAt.getTime() < System.currentTimeMillis();
}
private static String getClaim(DecodedJWT decodedJWT, String claimName) {
Claim claim = decodedJWT.getClaim(claimName);
return claim != null ? claim.asString() : null;
}
public static void main(String args[]) throws InterruptedException {
initialize();
String jwtToken = createJWT();
System.out.println("Created JWT : " + jwtToken);
|
DecodedJWT decodedJWT = verifyJWT(jwtToken);
if (decodedJWT == null) {
System.out.println("JWT Verification Failed");
}
Thread.sleep(1000L);
decodedJWT = verifyJWT(jwtToken);
if (decodedJWT != null) {
System.out.println("Token Issued At : " + decodedJWT.getIssuedAt());
System.out.println("Token Expires At : " + decodedJWT.getExpiresAt());
System.out.println("Subject : " + decodedJWT.getSubject());
System.out.println("Data : " + getClaim(decodedJWT, DATA_CLAIM));
System.out.println("Header : " + decodedJWT.getHeader());
System.out.println("Payload : " + decodedJWT.getPayload());
System.out.println("Signature : " + decodedJWT.getSignature());
System.out.println("Algorithm : " + decodedJWT.getAlgorithm());
System.out.println("JWT Id : " + decodedJWT.getId());
Boolean isExpired = isJWTExpired(decodedJWT);
System.out.println("Is Expired : " + isExpired);
}
}
}
|
repos\tutorials-master\security-modules\jwt\src\main\java\com\baeldung\jwt\auth0\Auth0JsonWebToken.java
| 1
|
请完成以下Java代码
|
private DocTax toDocTax(@NonNull TaxAmounts taxAmounts)
{
return DocTax.builderFrom(taxAmounts.getTax())
.accountProvider(accountProvider)
.taxBaseAmt(taxAmounts.getTaxBaseAmt().toBigDecimal())
.taxAmt(taxAmounts.getTaxAmt().toBigDecimal())
.reverseChargeTaxAmt(taxAmounts.getReverseChargeAmt().toBigDecimal())
.build();
}
//
//
//
//
//
private static class TaxAmounts
{
@NonNull @Getter private final Tax tax;
@NonNull private final CurrencyPrecision precision;
@NonNull @Getter private Money taxBaseAmt;
private boolean isTaxCalculated = false;
private Money _taxAmt;
private Money _reverseChargeAmt;
public TaxAmounts(@NonNull final Tax tax, @NonNull final CurrencyId currencyId, @NonNull final CurrencyPrecision precision)
{
this.tax = tax;
this.precision = precision;
this.taxBaseAmt = this._taxAmt = this._reverseChargeAmt = Money.zero(currencyId);
}
public void addTaxBaseAmt(@NonNull final Money taxBaseAmtToAdd)
{
if (taxBaseAmtToAdd.isZero())
{
return;
}
this.taxBaseAmt = this.taxBaseAmt.add(taxBaseAmtToAdd);
this.isTaxCalculated = false;
}
|
public Money getTaxAmt()
{
updateTaxAmtsIfNeeded();
return _taxAmt;
}
public Money getReverseChargeAmt()
{
updateTaxAmtsIfNeeded();
return _reverseChargeAmt;
}
private void updateTaxAmtsIfNeeded()
{
if (!isTaxCalculated)
{
final CalculateTaxResult result = tax.calculateTax(taxBaseAmt.toBigDecimal(), false, precision.toInt());
this._taxAmt = Money.of(result.getTaxAmount(), taxBaseAmt.getCurrencyId());
this._reverseChargeAmt = Money.of(result.getReverseChargeAmt(), taxBaseAmt.getCurrencyId());
this.isTaxCalculated = true;
}
}
public void updateDocTax(@NonNull final DocTax docTax)
{
if (!TaxId.equals(tax.getTaxId(), docTax.getTaxId()))
{
throw new AdempiereException("TaxId not matching: " + this + ", " + docTax);
}
docTax.setTaxBaseAmt(getTaxBaseAmt().toBigDecimal());
docTax.setTaxAmt(getTaxAmt().toBigDecimal());
docTax.setReverseChargeTaxAmt(getReverseChargeAmt().toBigDecimal());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxUpdater.java
| 1
|
请完成以下Java代码
|
public List<Product> findProductsUsingChainMethod(String name1, int price1, String category1, boolean available1) {
Criteria criteria = Criteria.where("name")
.is(name1)
.and("price")
.gt(price1)
.and("category")
.is(category1)
.and("available")
.is(available1);
return customProductRepository.find(new Query(criteria), Product.class);
}
public List<Product> findProductsUsingQueryDSLWithAndCondition(String category, boolean available, String name, double minPrice) {
QProduct qProduct = QProduct.product;
Predicate predicate = qProduct.category.eq(category)
.and(qProduct.available.eq(available))
.and(qProduct.name.eq(name))
.and(qProduct.price.gt(minPrice));
return StreamSupport.stream(productRepository.findAll(predicate)
.spliterator(), false)
.collect(Collectors.toList());
}
List<Product> findProductsUsingQueryDSLWithOrCondition(String category, String name, double minPrice) {
QProduct qProduct = QProduct.product;
Predicate predicate = qProduct.category.eq(category)
.or(qProduct.name.eq(name))
.or(qProduct.price.gt(minPrice));
return StreamSupport.stream(productRepository.findAll(predicate)
|
.spliterator(), false)
.collect(Collectors.toList());
}
List<Product> findProductsUsingQueryDSLWithAndOrCondition(String category, boolean available, String name, double minPrice) {
QProduct qProduct = QProduct.product;
Predicate predicate = qProduct.category.eq(category)
.and(qProduct.available.eq(available))
.or(qProduct.name.eq(name)
.and(qProduct.price.gt(minPrice)));
return StreamSupport.stream(productRepository.findAll(predicate)
.spliterator(), false)
.collect(Collectors.toList());
}
public List<Product> findProductsUsingQueryAnnotationWithAndCondition(String name1, int price1, String category1, boolean available) {
return productRepository.findProductsByNamePriceCategoryAndAvailability(name1, price1, category1, available);
}
public List<Product> findProductsUsingQueryAnnotationWithOrCondition(String category1, boolean available1, int price1) {
return productRepository.findProductsByCategoryAndAvailabilityOrPrice(category1, available1, price1);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\multicriteria\ProductService.java
| 1
|
请完成以下Java代码
|
public TaskCompletionBuilder transientVariable(String variableName, Object variableValue) {
if (this.transientVariables == null) {
this.transientVariables = new HashMap<>();
}
this.transientVariables.put(variableName, variableValue);
return this;
}
@Override
public TaskCompletionBuilder transientVariableLocal(String variableName, Object variableValue) {
if (this.transientVariablesLocal == null) {
this.transientVariablesLocal = new HashMap<>();
}
this.transientVariablesLocal.put(variableName, variableValue);
return this;
}
@Override
public TaskCompletionBuilder taskId(String id) {
this.taskId = id;
return this;
}
@Override
public TaskCompletionBuilder formDefinitionId(String formDefinitionId) {
this.formDefinitionId = formDefinitionId;
return this;
|
}
@Override
public TaskCompletionBuilder outcome(String outcome) {
this.outcome = outcome;
return this;
}
protected void completeTask() {
this.commandExecutor.execute(new CompleteTaskCmd(this.taskId, variables, variablesLocal, transientVariables, transientVariablesLocal));
}
protected void completeTaskWithForm() {
this.commandExecutor.execute(new CompleteTaskWithFormCmd(this.taskId, formDefinitionId, outcome,
variables, variablesLocal, transientVariables, transientVariablesLocal));
}
@Override
public void complete() {
if (this.formDefinitionId != null) {
completeTaskWithForm();
} else {
completeTask();
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\task\TaskCompletionBuilderImpl.java
| 1
|
请完成以下Java代码
|
public class IntentEventListenerInstanceImpl implements IntentEventListenerInstance {
protected PlanItemInstance innerPlanItemInstance;
public IntentEventListenerInstanceImpl(PlanItemInstance planItemInstance) {
this.innerPlanItemInstance = planItemInstance;
}
public static IntentEventListenerInstance fromPlanItemInstance(PlanItemInstance planItemInstance) {
if (planItemInstance == null) {
return null;
}
return new IntentEventListenerInstanceImpl(planItemInstance);
}
@Override
public String getId() {
return innerPlanItemInstance.getId();
}
@Override
public String getName() {
return innerPlanItemInstance.getName();
}
@Override
public String getCaseInstanceId() {
return innerPlanItemInstance.getCaseInstanceId();
}
@Override
public String getCaseDefinitionId() {
return innerPlanItemInstance.getCaseDefinitionId();
}
@Override
public String getElementId() {
return innerPlanItemInstance.getElementId();
}
@Override
public String getPlanItemDefinitionId() {
return innerPlanItemInstance.getPlanItemDefinitionId();
}
|
@Override
public String getStageInstanceId() {
return innerPlanItemInstance.getStageInstanceId();
}
@Override
public String getState() {
return innerPlanItemInstance.getState();
}
@Override
public String toString() {
return "IntentEventListenerInstanceImpl{" +
"id='" + getId() + '\'' +
", name='" + getName() + '\'' +
", caseInstanceId='" + getCaseInstanceId() + '\'' +
", caseDefinitionId='" + getCaseDefinitionId() + '\'' +
", elementId='" + getElementId() + '\'' +
", planItemDefinitionId='" + getPlanItemDefinitionId() + '\'' +
", stageInstanceId='" + getStageInstanceId() + '\'' +
'}';
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\IntentEventListenerInstanceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProductAllergensRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<ProductId, ProductAllergens> cache = CCache.<ProductId, ProductAllergens>builder()
.cacheMapType(CCache.CacheMapType.LRU)
.initialCapacity(100)
.tableName(I_M_Product_Allergen.Table_Name)
.build();
public ProductAllergens getByProductId(@NonNull ProductId productId)
{
return cache.getOrLoad(productId, this::retrieveByProductId);
}
private ProductAllergens retrieveByProductId(@NonNull ProductId productId)
|
{
final ImmutableSet<AllergenId> allergenIds = queryBL.createQueryBuilder(I_M_Product_Allergen.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_Product_HazardSymbol.COLUMNNAME_M_Product_ID, productId)
.create()
.stream()
.map(record -> AllergenId.ofRepoId(record.getM_Allergen_ID()))
.collect(ImmutableSet.toImmutableSet());
return ProductAllergens.builder()
.productId(productId)
.allergenIds(allergenIds)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\allergen\ProductAllergensRepository.java
| 2
|
请完成以下Java代码
|
public class PetValidator implements Validator {
private static final String REQUIRED = "required";
@Override
public void validate(Object obj, Errors errors) {
Pet pet = (Pet) obj;
String name = pet.getName();
// name validation
if (!StringUtils.hasText(name)) {
errors.rejectValue("name", REQUIRED, REQUIRED);
}
// type validation
if (pet.isNew() && pet.getType() == null) {
errors.rejectValue("type", REQUIRED, REQUIRED);
}
|
// birth date validation
if (pet.getBirthDate() == null) {
errors.rejectValue("birthDate", REQUIRED, REQUIRED);
}
}
/**
* This Validator validates *just* Pet instances
*/
@Override
public boolean supports(Class<?> clazz) {
return Pet.class.isAssignableFrom(clazz);
}
}
|
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\PetValidator.java
| 1
|
请完成以下Java代码
|
static boolean containsName(@Nullable final String name, @Nullable final String expression)
{
// FIXME: replace it with StringExpression
if (name == null || name.isEmpty())
{
return false;
}
if (expression == null || expression.isEmpty())
{
return false;
}
final int idx = expression.indexOf(NAME_Marker + name);
if (idx < 0)
{
return false;
}
final int idx2 = expression.indexOf(NAME_Marker, idx + 1);
if (idx2 < 0)
{
return false;
}
|
final String nameStr = expression.substring(idx + 1, idx2);
return name.equals(parse(nameStr).getName());
}
/**
* @return true if given string is a registered modifier
*/
private static boolean isModifier(final String modifier)
{
if (Check.isEmpty(modifier))
{
return false;
}
return MODIFIERS.contains(modifier);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\CtxNames.java
| 1
|
请完成以下Java代码
|
public class JuelExpressionResolver implements ExpressionResolver {
private final ExpressionFactory expressionFactory;
private final List<CustomFunctionProvider> customFunctionProviders;
public JuelExpressionResolver() {
this(ExpressionFactory.newInstance());
}
public JuelExpressionResolver(ExpressionFactory expressionFactory) {
this(expressionFactory, new ArrayList<>());
}
public JuelExpressionResolver(
ExpressionFactory expressionFactory,
List<CustomFunctionProvider> customFunctionProviders
) {
this.expressionFactory = expressionFactory;
this.customFunctionProviders = customFunctionProviders;
}
|
@Override
public <T> T resolveExpression(String expression, Map<String, Object> variables, Class<T> type) {
if (expression == null) {
return null;
}
final ELContext context = buildContext(variables);
final ValueExpression valueExpression = expressionFactory.createValueExpression(context, expression, type);
return (T) valueExpression.getValue(context);
}
protected ELContext buildContext(Map<String, Object> variables) {
return new ELContextBuilder()
.withResolvers(arrayResolver(), listResolver(), mapResolver(), jsonNodeResolver(), beanResolver())
.withVariables(variables)
.buildWithCustomFunctions(customFunctionProviders);
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\JuelExpressionResolver.java
| 1
|
请完成以下Java代码
|
public void handle(ServerWebExchange exchange, Mono<CsrfToken> csrfToken) {
Assert.notNull(exchange, "exchange cannot be null");
Assert.notNull(csrfToken, "csrfToken cannot be null");
exchange.getAttributes().put(CsrfToken.class.getName(), csrfToken);
logger.trace(LogMessage.format("Wrote a CSRF token to the [%s] exchange attribute", CsrfToken.class.getName()));
}
@Override
public Mono<String> resolveCsrfTokenValue(ServerWebExchange exchange, CsrfToken csrfToken) {
return ServerCsrfTokenRequestHandler.super.resolveCsrfTokenValue(exchange, csrfToken)
.switchIfEmpty(tokenFromMultipartData(exchange, csrfToken));
}
/**
* Specifies if the {@code ServerCsrfTokenRequestResolver} should try to resolve the
* actual CSRF token from the body of multipart data requests.
* @param tokenFromMultipartDataEnabled true if should read from multipart form body,
* else false. Default is false
*/
public void setTokenFromMultipartDataEnabled(boolean tokenFromMultipartDataEnabled) {
this.isTokenFromMultipartDataEnabled = tokenFromMultipartDataEnabled;
}
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
private Mono<String> tokenFromMultipartData(ServerWebExchange exchange, CsrfToken expected) {
if (!this.isTokenFromMultipartDataEnabled) {
|
return Mono.empty();
}
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
MediaType contentType = headers.getContentType();
if (!MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType)) {
return Mono.empty();
}
return exchange.getMultipartData()
.mapNotNull((d) -> d.getFirst(expected.getParameterName()))
.cast(FormFieldPart.class)
.map(FormFieldPart::value);
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\ServerCsrfTokenRequestAttributeHandler.java
| 1
|
请完成以下Java代码
|
public void writeAttribute(String localName, String value) throws XMLStreamException {
writer.writeAttribute(localName, value);
}
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
throws XMLStreamException {
writer.writeAttribute(prefix, namespaceURI, localName, value);
}
public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException {
writer.writeAttribute(namespaceURI, localName, value);
}
public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
writer.writeNamespace(prefix, namespaceURI);
}
public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
writer.writeDefaultNamespace(namespaceURI);
}
public void writeComment(String data) throws XMLStreamException {
writer.writeComment(data);
}
public void writeProcessingInstruction(String target) throws XMLStreamException {
writer.writeProcessingInstruction(target);
}
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
writer.writeProcessingInstruction(target, data);
}
public void writeCData(String data) throws XMLStreamException {
writer.writeCData(data);
}
public void writeDTD(String dtd) throws XMLStreamException {
writer.writeDTD(dtd);
}
public void writeEntityRef(String name) throws XMLStreamException {
writer.writeEntityRef(name);
}
public void writeStartDocument() throws XMLStreamException {
writer.writeStartDocument();
}
public void writeStartDocument(String version) throws XMLStreamException {
writer.writeStartDocument(version);
}
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
writer.writeStartDocument(encoding, version);
}
public void writeCharacters(String text) throws XMLStreamException {
writer.writeCharacters(text);
}
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
|
writer.writeCharacters(text, start, len);
}
public String getPrefix(String uri) throws XMLStreamException {
return writer.getPrefix(uri);
}
public void setPrefix(String prefix, String uri) throws XMLStreamException {
writer.setPrefix(prefix, uri);
}
public void setDefaultNamespace(String uri) throws XMLStreamException {
writer.setDefaultNamespace(uri);
}
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
writer.setNamespaceContext(context);
}
public NamespaceContext getNamespaceContext() {
return writer.getNamespaceContext();
}
public Object getProperty(String name) throws IllegalArgumentException {
return writer.getProperty(name);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\DelegatingXMLStreamWriter.java
| 1
|
请完成以下Java代码
|
public static Class<?> getClass(String tableName)
{
return TableModelClassLoader.instance.getClass(tableName);
}
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
if (isView() && isDeleteable())
{
setIsDeleteable(false);
}
//
return true;
} // beforeSave
/**
* After Save
*
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
//
// Create/Update table sequences
// NOTE: we shall do this only if it's a new table, else we will change the sequence's next value
// which could be OK on our local development database,
// but when the migration script will be executed on target customer database, their sequences will be wrongly changed (08607)
|
if (success && newRecord)
{
final ISequenceDAO sequenceDAO = Services.get(ISequenceDAO.class);
sequenceDAO.createTableSequenceChecker(getCtx())
.setFailOnFirstError(true)
.setSequenceRangeCheck(false)
.setTable(this)
.setTrxName(get_TrxName())
.run();
}
if (!newRecord && is_ValueChanged(COLUMNNAME_TableName))
{
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class);
adTableDAO.onTableNameRename(this);
}
return success;
} // afterSave
public Query createQuery(String whereClause, String trxName)
{
return new Query(this.getCtx(), this, whereClause, trxName);
}
@Override
public String toString()
{
return "MTable[" + get_ID() + "-" + getTableName() + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTable.java
| 1
|
请完成以下Java代码
|
public int getC_HierarchyCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_HierarchyCommissionSettings_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getCustomer_Group()
{
return get_ValueAsPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setCustomer_Group(final org.compiere.model.I_C_BP_Group Customer_Group)
{
set_ValueFromPO(COLUMNNAME_Customer_Group_ID, org.compiere.model.I_C_BP_Group.class, Customer_Group);
}
@Override
public void setCustomer_Group_ID (final int Customer_Group_ID)
{
if (Customer_Group_ID < 1)
set_Value (COLUMNNAME_Customer_Group_ID, null);
else
set_Value (COLUMNNAME_Customer_Group_ID, Customer_Group_ID);
}
@Override
public int getCustomer_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_Customer_Group_ID);
}
@Override
public void setIsExcludeBPGroup (final boolean IsExcludeBPGroup)
{
set_Value (COLUMNNAME_IsExcludeBPGroup, IsExcludeBPGroup);
}
@Override
public boolean isExcludeBPGroup()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeBPGroup);
}
@Override
public void setIsExcludeProductCategory (final boolean IsExcludeProductCategory)
{
set_Value (COLUMNNAME_IsExcludeProductCategory, IsExcludeProductCategory);
}
@Override
public boolean isExcludeProductCategory()
{
return get_ValueAsBoolean(COLUMNNAME_IsExcludeProductCategory);
}
@Override
|
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_CommissionSettingsLine.java
| 1
|
请完成以下Java代码
|
public static <R> Result<R> ofThrowable(int code, Throwable throwable) {
Result<R> result = new Result<>();
result.setSuccess(false);
result.setCode(code);
result.setMsg(throwable.getClass().getName() + ", " + throwable.getMessage());
return result;
}
public boolean isSuccess() {
return success;
}
public Result<R> setSuccess(boolean success) {
this.success = success;
return this;
}
public int getCode() {
return code;
}
public Result<R> setCode(int code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public Result<R> setMsg(String msg) {
this.msg = msg;
return this;
}
|
public R getData() {
return data;
}
public Result<R> setData(R data) {
this.data = data;
return this;
}
@Override
public String toString() {
return "Result{" +
"success=" + success +
", code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\Result.java
| 1
|
请完成以下Java代码
|
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
|
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", authorizationType=" + authorizationType
+ ", permissions=" + permissions
+ ", userId=" + userId
+ ", groupId=" + groupId
+ ", resourceType=" + resourceType
+ ", resourceId=" + resourceId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Function<RouteProperties, HandlerFunctionDefinition> noHandlerFunctionDefinition() {
return routeProperties -> getResult("no", routeProperties.getId(), routeProperties.getUri(),
HandlerFunctions.no());
}
@Bean
public Function<RouteProperties, HandlerFunctionDefinition> streamHandlerFunctionDefinition() {
return routeProperties -> {
Objects.requireNonNull(routeProperties.getUri(), "routeProperties.uri must not be null");
return new HandlerFunctionDefinition.Default("stream",
HandlerFunctions.stream(routeProperties.getUri().getSchemeSpecificPart()));
};
}
private static HandlerFunctionDefinition getResult(String scheme, @Nullable String id, @Nullable URI uri,
HandlerFunction<ServerResponse> handlerFunction) {
HandlerFilterFunction<ServerResponse, ServerResponse> setId = setIdFilter(id);
HandlerFilterFunction<ServerResponse, ServerResponse> setRequest = setRequestUrlFilter(uri);
return new HandlerFunctionDefinition.Default(scheme, handlerFunction, Arrays.asList(setId, setRequest),
Collections.emptyList());
}
|
private static HandlerFilterFunction<ServerResponse, ServerResponse> setIdFilter(@Nullable String id) {
return (request, next) -> {
MvcUtils.setRouteId(request, id);
return next.handle(request);
};
}
private static HandlerFilterFunction<ServerResponse, ServerResponse> setRequestUrlFilter(@Nullable URI uri) {
return (request, next) -> {
Objects.requireNonNull(uri, "uri must not be null");
MvcUtils.setRequestUrl(request, uri);
return next.handle(request);
};
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\HandlerFunctionAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public BigDecimal getQtyToDeliver()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToDeliver);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSetup_Place_No (final int Setup_Place_No)
{
set_ValueNoCheck (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public int getSetup_Place_No()
{
return get_ValueAsInt(COLUMNNAME_Setup_Place_No);
}
/**
* ShipmentAllocation_BestBefore_Policy AD_Reference_ID=541043
* Reference name: ShipmentAllocation_BestBefore_Policy
*/
public static final int SHIPMENTALLOCATION_BESTBEFORE_POLICY_AD_Reference_ID=541043;
/** Newest_First = N */
public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Newest_First = "N";
/** Expiring_First = E */
public static final String SHIPMENTALLOCATION_BESTBEFORE_POLICY_Expiring_First = "E";
@Override
public void setShipmentAllocation_BestBefore_Policy (final @Nullable java.lang.String ShipmentAllocation_BestBefore_Policy)
{
set_ValueNoCheck (COLUMNNAME_ShipmentAllocation_BestBefore_Policy, ShipmentAllocation_BestBefore_Policy);
}
|
@Override
public java.lang.String getShipmentAllocation_BestBefore_Policy()
{
return get_ValueAsString(COLUMNNAME_ShipmentAllocation_BestBefore_Policy);
}
@Override
public void setShipperName (final @Nullable java.lang.String ShipperName)
{
set_ValueNoCheck (COLUMNNAME_ShipperName, ShipperName);
}
@Override
public java.lang.String getShipperName()
{
return get_ValueAsString(COLUMNNAME_ShipperName);
}
@Override
public void setWarehouseName (final @Nullable java.lang.String WarehouseName)
{
set_ValueNoCheck (COLUMNNAME_WarehouseName, WarehouseName);
}
@Override
public java.lang.String getWarehouseName()
{
return get_ValueAsString(COLUMNNAME_WarehouseName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Packageable_V.java
| 1
|
请完成以下Java代码
|
public RefundConfig smallestMinQty(@NonNull final List<RefundConfig> refundConfigs)
{
Check.assumeNotEmpty(refundConfigs, "The given refundConfigs may not be empty");
return refundConfigs
.stream()
.min(Comparator.comparing(RefundConfig::getMinQty))
.get();
}
public RefundMode extractRefundMode(@NonNull final List<RefundConfig> refundConfigs)
{
final RefundMode refundMode = extractSingleElement(
refundConfigs,
RefundConfig::getRefundMode);
return refundMode;
}
public ProductId extractProductId(@NonNull final List<RefundConfig> refundConfigs)
{
final ProductId productId = extractSingleElement(
refundConfigs,
RefundConfig::getProductId);
return productId;
}
public void assertValid(@NonNull final List<RefundConfig> refundConfigs)
{
Check.assumeNotEmpty(refundConfigs, "refundConfigs");
if (hasDifferentValues(refundConfigs, RefundConfig::getRefundBase))
{
Loggables.addLog("The given refundConfigs need to all have the same RefundBase; refundConfigs={}", refundConfigs);
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_REFUND_BASE).markAsUserValidationError();
}
if (hasDifferentValues(refundConfigs, RefundConfig::getRefundMode))
{
Loggables.addLog("The given refundConfigs need to all have the same RefundMode; refundConfigs={}", refundConfigs);
|
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_REFUND_MODE).markAsUserValidationError();
}
if (RefundMode.APPLY_TO_ALL_QTIES.equals(extractRefundMode(refundConfigs)))
{
// we have one IC with different configs, so those configs need to have the consistent settings
if (hasDifferentValues(refundConfigs, RefundConfig::getInvoiceSchedule))
{
Loggables.addLog(
"Because refundMode={}, all the given refundConfigs need to all have the same invoiceSchedule; refundConfigs={}",
RefundMode.APPLY_TO_ALL_QTIES, refundConfigs);
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_INVOICE_SCHEDULE).markAsUserValidationError();
}
if (hasDifferentValues(refundConfigs, RefundConfig::getRefundInvoiceType))
{
Loggables.addLog(
"Because refundMode={}, all the given refundConfigs need to all have the same refundInvoiceType; refundConfigs={}",
RefundMode.APPLY_TO_ALL_QTIES, refundConfigs);
throw new AdempiereException(MSG_REFUND_CONFIG_SAME_REFUND_INVOICE_TYPE).markAsUserValidationError();
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundConfigs.java
| 1
|
请完成以下Java代码
|
class TcpConnectServiceReadinessCheck {
private static final String DISABLE_LABEL = "org.springframework.boot.readiness-check.tcp.disable";
private final DockerComposeProperties.Readiness.Tcp properties;
TcpConnectServiceReadinessCheck(DockerComposeProperties.Readiness.Tcp properties) {
this.properties = properties;
}
void check(RunningService service) {
if (service.labels().containsKey(DISABLE_LABEL)) {
return;
}
for (int port : service.ports().getAll("tcp")) {
check(service, port);
}
}
private void check(RunningService service, int port) {
int connectTimeout = (int) this.properties.getConnectTimeout().toMillis();
int readTimeout = (int) this.properties.getReadTimeout().toMillis();
try (Socket socket = new Socket()) {
socket.setSoTimeout(readTimeout);
socket.connect(new InetSocketAddress(service.host(), port), connectTimeout);
check(service, port, socket);
}
catch (IOException ex) {
throw new ServiceNotReadyException(service, "IOException while connecting to port %s".formatted(port), ex);
}
|
}
private void check(RunningService service, int port, Socket socket) throws IOException {
try {
// -1 indicates the socket has been closed immediately
// Other responses or a timeout are considered as success
if (socket.getInputStream().read() == -1) {
throw new ServiceNotReadyException(service,
"Immediate disconnect while connecting to port %s".formatted(port));
}
}
catch (SocketTimeoutException ex) {
// Ignore
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\TcpConnectServiceReadinessCheck.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DiskStoreProperties getDisk() {
return this.disk;
}
public EntityProperties getEntities() {
return this.entities;
}
public LocatorProperties getLocator() {
return this.locator;
}
public String[] getLocators() {
return this.locators;
}
public void setLocators(String[] locators) {
this.locators = locators;
}
public LoggingProperties getLogging() {
return this.logging;
}
public ManagementProperties getManagement() {
return this.management;
}
public ManagerProperties getManager() {
return this.manager;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public PdxProperties getPdx() {
return this.pdx;
}
public PoolProperties getPool() {
return this.pool;
}
public SecurityProperties getSecurity() {
return this.security;
}
public ServiceProperties getService() {
return this.service;
}
public boolean isUseBeanFactoryLocator() {
return this.useBeanFactoryLocator;
}
public void setUseBeanFactoryLocator(boolean useBeanFactoryLocator) {
this.useBeanFactoryLocator = useBeanFactoryLocator;
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\GemFireProperties.java
| 2
|
请完成以下Java代码
|
public void remove()
{
throw new UnsupportedOperationException();
}
private List<Object> readLine(ResultSet rs, List<String> sqlFields) throws SQLException
{
final List<Object> values = new ArrayList<Object>();
for (final String columnName : sqlFields)
{
final Object value = rs.getObject(columnName);
values.add(value);
}
return values;
}
private Integer rowsCount = null;
@Override
public int size()
{
if (Check.isEmpty(sqlCount, true))
{
throw new IllegalStateException("Counting is not supported");
}
if (rowsCount == null)
{
logger.info("SQL: {}", sqlCount);
logger.info("SQL Params: {}", sqlParams);
rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams);
logger.info("Rows Count: {}" + rowsCount);
}
return rowsCount;
}
public String getSqlSelect()
|
{
return sqlSelect;
}
public List<Object> getSqlParams()
{
if (sqlParams == null)
{
return Collections.emptyList();
}
return sqlParams;
}
public String getSqlWhereClause()
{
return sqlWhereClause;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java
| 1
|
请完成以下Java代码
|
private RequisitionService getRequisitionService()
{
return Adempiere.getBean(RequisitionService.class);
}
@Override
public I_M_Requisition getM_Requisition()
{
return getParent();
}
public void setPrice()
{
final BigDecimal price = getRequisitionService().computePrice(getParent(), this);
if (price != null)
{
setPriceActual(price);
}
}
@Override
protected boolean beforeSave(boolean newRecord)
{
if (newRecord && getParent().isComplete())
{
throw new AdempiereException("@ParentComplete@ @M_RequisitionLine_ID@");
}
if (getLine() == 0)
{
String sql = "SELECT COALESCE(MAX(Line),0)+10 FROM M_RequisitionLine WHERE M_Requisition_ID=?";
int line = DB.getSQLValueEx(get_TrxName(), sql, getM_Requisition_ID());
setLine(line);
}
// Product & ASI - Charge
if (getM_Product_ID() > 0 && getC_Charge_ID() > 0)
{
setC_Charge_ID(0);
}
if (getM_AttributeSetInstance_ID() > 0 && getC_Charge_ID() > 0)
{
setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId());
}
// Product UOM
if (getM_Product_ID() > 0 && getC_UOM_ID() <= 0)
{
final UomId productUomId = Services.get(IProductBL.class).getStockUOMId(getM_Product_ID());
setC_UOM_ID(productUomId.getRepoId());
}
//
if (getPriceActual().signum() == 0)
{
setPrice();
}
|
getRequisitionService().updateLineNetAmt(this);
return true;
} // beforeSave
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
return success;
updateHeader();
return true;
} // afterSave
@Override
protected boolean afterDelete(boolean success)
{
if (!success)
return success;
updateHeader();
return true;
} // afterDelete
private void updateHeader()
{
String sql = "UPDATE M_Requisition r"
+ " SET TotalLines="
+ "(SELECT COALESCE(SUM(LineNetAmt),0) FROM M_RequisitionLine rl "
+ "WHERE r.M_Requisition_ID=rl.M_Requisition_ID) "
+ "WHERE M_Requisition_ID=?";
DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { getM_Requisition_ID() }, ITrx.TRXNAME_ThreadInherited);
m_parent = null;
}
} // MRequisitionLine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequisitionLine.java
| 1
|
请完成以下Java代码
|
public Optional<Object> unpackValue(Val value, Function<Val, Object> innerValueMapper) {
return Optional.empty();
}
@Override
public int priority() {
return 30;
}
protected Val spinJsonToVal(SpinJsonNode node, Function<Object, Val> innerValueMapper) {
if (node.isObject()) {
Map pairs = node.fieldNames()
.stream()
.collect(toMap(field -> field,
field -> spinJsonToVal(node.prop(field), innerValueMapper)));
return innerValueMapper.apply(pairs);
} else if (node.isArray()) {
List<Val> values = node.elements()
.stream()
.map(e -> spinJsonToVal(e, innerValueMapper)).collect(toList());
return innerValueMapper.apply(values);
} else if (node.isNull()) {
return innerValueMapper.apply(null);
} else {
return innerValueMapper.apply(node.value());
}
}
protected Val spinXmlToVal(SpinXmlElement element, Function<Object, Val> innerValueMapper) {
String name = nodeName(element);
Val value = spinXmlElementToVal(element, innerValueMapper);
Map<String, Object> map = Collections.singletonMap(name, value);
return innerValueMapper.apply(map);
}
protected Val spinXmlElementToVal(final SpinXmlElement e,
Function<Object, Val> innerValueMapper) {
Map<String, Object> membersMap = new HashMap<>();
String content = e.textContent().trim();
if (!content.isEmpty()) {
membersMap.put("$content", new ValString(content));
}
Map<String, ValString> attributes = e.attrs()
.stream()
.collect(toMap(this::spinXmlAttributeToKey, attr -> new ValString(attr.value())));
if (!attributes.isEmpty()) {
membersMap.putAll(attributes);
}
Map<String, Val> childrenMap = e.childElements().stream()
.collect(
groupingBy(
this::nodeName,
mapping(el -> spinXmlElementToVal(el, innerValueMapper), toList())
))
|
.entrySet().stream()
.collect(toMap(Map.Entry::getKey, entry -> {
List<Val> valList = entry.getValue();
if (!valList.isEmpty() && valList.size() > 1) {
return innerValueMapper.apply(valList);
} else {
return valList.get(0);
}
}));
membersMap.putAll(childrenMap);
if (membersMap.isEmpty()) {
return innerValueMapper.apply(null);
} else {
return innerValueMapper.apply(membersMap);
}
}
protected String spinXmlAttributeToKey(SpinXmlAttribute attribute) {
return "@" + nodeName(attribute);
}
protected String nodeName(SpinXmlNode n) {
String prefix = n.prefix();
String name = n.name();
return (prefix != null && !prefix.isEmpty())? prefix + "$" + name : name;
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\feel\integration\SpinValueMapper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
//获取当前请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//记录请求信息
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = pjp.proceed();
stopWatch.stop();
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
String urlStr = request.getRequestURL().toString();
log.info("===================================begin==================================================");
log.info("req path: {}", StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
log.info("req ip: {}", request.getRemoteUser());
log.info("req method: {}", request.getMethod());
log.info("req params: {}", getParameter(method, pjp.getArgs()));
log.info("req result: {}", JSONUtil.toJsonStr(result));
log.info("req uri: {}", request.getRequestURI());
log.info("req url: {}", request.getRequestURL().toString());
log.info("req cost: {}ms", stopWatch.getLastTaskTimeMillis());
log.info("===================================end===================================================");
return result;
}
/**
* 根据方法和传入的参数获取请求参数
*/
private Object getParameter(Method method, Object[] args) {
List<Object> argList = new ArrayList<>();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
//将RequestBody注解修饰的参数作为请求参数
|
RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
if (requestBody != null) {
argList.add(args[i]);
}
//将RequestParam注解修饰的参数作为请求参数
RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
if (requestParam != null) {
Map<String, Object> map = new HashMap<>();
String key = parameters[i].getName();
if (!StringUtils.isEmpty(requestParam.value())) {
key = requestParam.value();
}
map.put(key, args[i]);
argList.add(map);
}
}
if (argList.size() == 0) {
return null;
} else if (argList.size() == 1) {
return argList.get(0);
} else {
return argList;
}
}
}
|
repos\spring-boot-quick-master\quick-platform-component\src\main\java\com\quick\component\config\logAspect\WebLogAspect.java
| 2
|
请完成以下Java代码
|
public static boolean isSumOfTwoSquares(int n) {
if (n < 0) {
LOGGER.warn("Input must be non-negative. Returning false for n = {}", n);
return false;
}
if (n == 0) {
return true; // 0 = 0^2 + 0^2
}
// 1. Reduce n to an odd number if n is even.
while (n % 2 == 0) {
n /= 2;
}
// 2. Iterate through odd prime factors starting from 3
for (int i = 3; i * i <= n; i += 2) {
// 2a. Find the exponent of the factor i
int count = 0;
while (n % i == 0) {
count++;
n /= i;
}
// 2b. Check the condition from Fermat's theorem
|
// If i is of form 4k+3 (i % 4 == 3) and has an odd exponent
if (i % 4 == 3 && count % 2 != 0) {
LOGGER.debug("Failing condition: factor {} (form 4k+3) has odd exponent {}", i, count);
return false;
}
}
// 3. Handle the last remaining factor (which is prime if > 1)
// If n itself is a prime of the form 4k+3, its exponent is 1 (odd).
if (n % 4 == 3) {
LOGGER.debug("Failing condition: remaining factor {} is of form 4k+3", n);
return false;
}
// 4. All 4k+3 primes had even exponents.
return true;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\sumoftwosquares\NumberAsSumOfTwoSquares.java
| 1
|
请完成以下Java代码
|
public class HttpCookieHostKeyStorage implements IHostKeyStorage
{
private static final transient Logger logger = LogManager.getLogger(HttpCookieHostKeyStorage.class);
private static final String COOKIE_Name = "metasfresh.hostkey";
private static final String COOKIE_Description = "Used by metasfresh to identify if user logged in from same browser, no matter on which network he/she connects."
+ " Please note that this information is mandatory for providing host base configuration.";
private static final int COOKIE_MaxAge = 365 * 24 * 60 * 60; // 1year (in seconds)
private HttpServletRequest getActualHttpServletRequest()
{
return Services.get(IHttpSessionProvider.class).getCurrentRequest();
}
private HttpServletResponse getActualHttpServletResponse()
{
return Services.get(IHttpSessionProvider.class).getCurrentResponse();
}
@Override
public void setHostKey(final String hostkey)
{
final HttpServletResponse httpResponse = getActualHttpServletResponse();
|
// Always set back the cookie, because we want to renew the expire date
if (!CookieUtil.setCookie(httpResponse, COOKIE_Name, hostkey, COOKIE_Description, COOKIE_MaxAge))
{
logger.warn("Cannot set cookie " + COOKIE_Name + ": " + hostkey);
}
}
@Override
public String getHostKey()
{
final HttpServletRequest httpRequest = getActualHttpServletRequest();
final String hostkey = CookieUtil.getCookie(httpRequest, COOKIE_Name);
if (Check.isEmpty(hostkey, true))
{
logger.info("No host key found");
}
return hostkey;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\hostkey\spi\impl\HttpCookieHostKeyStorage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) {
UmsAdmin umsAdmin = new UmsAdmin();
umsAdmin.setStatus(status);
int count = adminService.update(id,umsAdmin);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("给用户分配角色")
@RequestMapping(value = "/role/update", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateRole(@RequestParam("adminId") Long adminId,
@RequestParam("roleIds") List<Long> roleIds) {
|
int count = adminService.updateRole(adminId, roleIds);
if (count >= 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("获取指定用户的角色")
@RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) {
List<UmsRole> roleList = adminService.getRoleList(adminId);
return CommonResult.success(roleList);
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\UmsAdminController.java
| 2
|
请完成以下Java代码
|
public class X_PP_Weighting_Spec extends org.compiere.model.PO implements I_PP_Weighting_Spec, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -810691136L;
/** Standard Constructor */
public X_PP_Weighting_Spec (final Properties ctx, final int PP_Weighting_Spec_ID, @Nullable final String trxName)
{
super (ctx, PP_Weighting_Spec_ID, trxName);
}
/** Load Constructor */
public X_PP_Weighting_Spec (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
|
@Override
public void setPP_Weighting_Spec_ID (final int PP_Weighting_Spec_ID)
{
if (PP_Weighting_Spec_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Weighting_Spec_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Weighting_Spec_ID, PP_Weighting_Spec_ID);
}
@Override
public int getPP_Weighting_Spec_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Weighting_Spec_ID);
}
@Override
public void setTolerance_Perc (final BigDecimal Tolerance_Perc)
{
set_Value (COLUMNNAME_Tolerance_Perc, Tolerance_Perc);
}
@Override
public BigDecimal getTolerance_Perc()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Tolerance_Perc);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeightChecksRequired (final int WeightChecksRequired)
{
set_Value (COLUMNNAME_WeightChecksRequired, WeightChecksRequired);
}
@Override
public int getWeightChecksRequired()
{
return get_ValueAsInt(COLUMNNAME_WeightChecksRequired);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Weighting_Spec.java
| 1
|
请完成以下Java代码
|
public Response post(Wallet wallet) {
wallets.save(wallet);
return Response.ok(wallet)
.build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") String id) {
Optional<Wallet> wallet = wallets.findById(id);
wallet.orElseThrow(IllegalArgumentException::new);
return Response.ok(wallet.get())
.build();
}
@PUT
@Path("/{id}/{amount}")
@Produces(MediaType.APPLICATION_JSON)
public Response putAmount(@PathParam("id") String id, @PathParam("amount") Double amount) {
Optional<Wallet> wallet = wallets.findById(id);
wallet.orElseThrow(IllegalArgumentException::new);
if (amount < Wallet.MIN_CHARGE) {
throw new InvalidTradeException(Wallet.MIN_CHARGE_MSG);
}
wallet.get()
.addBalance(amount);
wallets.save(wallet.get());
return Response.ok(wallet)
.build();
}
@POST
@Path("/{wallet}/buy/{ticker}")
@Produces(MediaType.APPLICATION_JSON)
public Response postBuyStock(@PathParam("wallet") String walletId, @PathParam("ticker") String id) {
Optional<Stock> stock = stocks.findById(id);
stock.orElseThrow(InvalidTradeException::new);
Optional<Wallet> w = wallets.findById(walletId);
w.orElseThrow(InvalidTradeException::new);
|
Wallet wallet = w.get();
Double price = stock.get()
.getPrice();
if (!wallet.hasFunds(price)) {
RestErrorResponse response = new RestErrorResponse();
response.setSubject(wallet);
response.setMessage("insufficient balance");
throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE)
.entity(response)
.build());
}
wallet.addBalance(-price);
wallets.save(wallet);
return Response.ok(wallet)
.build();
}
}
|
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\exceptionhandling\rest\WalletsResource.java
| 1
|
请完成以下Java代码
|
public class HDDExportProcessor implements IExportProcessor {
/** Logger */
protected Logger log = LogManager.getLogger(getClass());
public void process(Properties ctx, MEXPProcessor expProcessor, Document document, Trx trx)
throws Exception
{
//String host = expProcessor.getHost();
//int port = expProcessor.getPort();
//String account = expProcessor.getAccount();
//String password = expProcessor.getPasswordInfo();
String fileName = "";
String folder = "";
// Read all processor parameters and set them!
I_EXP_ProcessorParameter[] processorParameters = expProcessor.getEXP_ProcessorParameters();
if (processorParameters != null && processorParameters.length > 0) {
for (int i = 0; i < processorParameters.length; i++) {
// One special parameter which will be used for remote folder name.
// Or could add flag to ProcessorParameters table which will distinguish between
// connection parameters and FTP Upload parameters.
log.info("ProcesParameter Value = " + processorParameters[i].getValue());
log.info("ProcesParameter ParameterValue = " + processorParameters[i].getParameterValue());
if ( processorParameters[i].getValue().equals("fileName") ) {
fileName = processorParameters[i].getParameterValue();
} else if ( processorParameters[i].getValue().equals("folder") ) {
folder = processorParameters[i].getParameterValue();
}
}
}
if (fileName == null || fileName.length() == 0) {
throw new Exception("Missing EXP_ProcessorParameter with key 'fileName'!");
}
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
tranFactory.setAttribute("indent-number", Integer.valueOf(1));
Transformer aTransformer = tranFactory.newTransformer();
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
Source src = new DOMSource(document);
|
// =================================== Write to String
Writer writer = new StringWriter();
Result dest2 = new StreamResult(writer);
aTransformer.transform(src, dest2);
System.err.println(writer.toString());
//writer = new OutputStreamWriter(new FileOutputStream(out), "utf-8");
// =================================== Write to Disk
try {
Result dest = new StreamResult(new File(folder + fileName));
aTransformer.transform(src, dest);
writer.close();
} catch (TransformerException ex) {
ex.printStackTrace();
throw ex;
}
}
@Override
public void createInitialParameters(MEXPProcessor processor)
{
// TODO Auto-generated method stub
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\exp\HDDExportProcessor.java
| 1
|
请完成以下Java代码
|
public void appendEnd(final StringBuffer buffer, final Object object)
{
super.appendEnd(buffer, object);
buffer.setLength(buffer.length() - getContentEnd().length());
buffer.append(SystemUtils.LINE_SEPARATOR);
depth.get().decrement();
padDepth(buffer);
appendContentEnd(buffer);
}
@Override
protected void removeLastFieldSeparator(final StringBuffer buffer)
{
final int len = buffer.length();
final int sepLen = getFieldSeparator().length() + getDepth();
if (len > 0 && sepLen > 0 && len >= sepLen)
{
buffer.setLength(len - sepLen);
}
}
private boolean noReflectionNeeded(final Object value)
{
try
{
return value != null &&
(value.getClass().getName().startsWith("java.lang.")
|| value.getClass().getMethod("toString").getDeclaringClass() != Object.class);
}
catch (final NoSuchMethodException e)
{
throw new IllegalStateException(e);
}
}
@Override
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value)
{
if (getDepth() >= maxDepth || noReflectionNeeded(value))
{
appendTabified(buffer, String.valueOf(value));
}
else
{
new ExtendedReflectionToStringBuilder(value, this, buffer, null, false, false).toString();
}
}
// another helpful method, for collections:
@Override
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> col)
{
appendSummarySize(buffer, fieldName, col.size());
final ExtendedReflectionToStringBuilder builder = new ExtendedReflectionToStringBuilder(
col.toArray(), // object
this, // style,
buffer, //buffer,
null, //reflectUpToClass,
true, // outputTransients,
true // outputStatics
);
builder.toString();
}
@Override
protected String getShortClassName(final Class<?> cls)
{
|
if (cls != null && cls.isArray() && getDepth() > 0)
{
return "";
}
return super.getShortClassName(cls);
}
static class MutableInteger
{
private int value;
MutableInteger(final int value)
{
this.value = value;
}
public final int get()
{
return value;
}
public final void increment()
{
++value;
}
public final void decrement()
{
--value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\RecursiveIndentedMultilineToStringStyle.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setProductNo (final java.lang.String ProductNo)
{
set_Value (COLUMNNAME_ProductNo, ProductNo);
}
@Override
public java.lang.String getProductNo()
{
return get_ValueAsString(COLUMNNAME_ProductNo);
}
@Override
public void setReference (final @Nullable java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
@Override
public java.lang.String getReference()
{
return get_ValueAsString(COLUMNNAME_Reference);
}
@Override
public void setSerialNo (final @Nullable java.lang.String SerialNo)
{
set_Value (COLUMNNAME_SerialNo, SerialNo);
}
@Override
public java.lang.String getSerialNo()
{
return get_ValueAsString(COLUMNNAME_SerialNo);
}
|
@Override
public void setServiceRepair_Old_Shipped_HU_ID (final int ServiceRepair_Old_Shipped_HU_ID)
{
if (ServiceRepair_Old_Shipped_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID, ServiceRepair_Old_Shipped_HU_ID);
}
@Override
public int getServiceRepair_Old_Shipped_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_ServiceRepair_Old_Shipped_HU_ID);
}
@Override
public void setWarrantyStartDate (final @Nullable java.sql.Timestamp WarrantyStartDate)
{
set_Value (COLUMNNAME_WarrantyStartDate, WarrantyStartDate);
}
@Override
public java.sql.Timestamp getWarrantyStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_WarrantyStartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_ServiceRepair_Old_Shipped_HU.java
| 2
|
请完成以下Java代码
|
public long executeCount(CommandContext commandContext) {
checkQueryOk();
long count = commandContext
.getStatisticsManager()
.getStatisticsCountGroupedByDecisionRequirementsDefinition(this);
return count;
}
@Override
public List<HistoricDecisionInstanceStatistics> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
List<HistoricDecisionInstanceStatistics> statisticsList = commandContext
.getStatisticsManager()
.getStatisticsGroupedByDecisionRequirementsDefinition(this, page);
return statisticsList;
}
protected void checkQueryOk() {
|
super.checkQueryOk();
EnsureUtil.ensureNotNull("decisionRequirementsDefinitionId", decisionRequirementsDefinitionId);
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
@Override
public HistoricDecisionInstanceStatisticsQuery decisionInstanceId(String decisionInstanceId) {
this.decisionInstanceId = decisionInstanceId;
return this;
}
public String getDecisionInstanceId() {
return decisionInstanceId;
}
public void setDecisionInstanceId(String decisionInstanceId) {
this.decisionInstanceId = decisionInstanceId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDecisionInstanceStatisticsQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class PropertiesArtemisConnectionDetails implements ArtemisConnectionDetails {
private final ArtemisProperties properties;
PropertiesArtemisConnectionDetails(ArtemisProperties properties) {
this.properties = properties;
}
@Override
public @Nullable ArtemisMode getMode() {
return this.properties.getMode();
}
@Override
public @Nullable String getBrokerUrl() {
return this.properties.getBrokerUrl();
|
}
@Override
public @Nullable String getUser() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-artemis\src\main\java\org\springframework\boot\artemis\autoconfigure\ArtemisAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public UUID getId() {
return id;
}
@Override
public int hashCode() {
if (hash == 0) {
final int prime = 31;
int result = 1;
hash = prime * result + ((id == null) ? 0 : id.hashCode());
}
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
|
UUIDBased other = (UUIDBased) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return String.valueOf(id);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\id\UUIDBased.java
| 1
|
请完成以下Java代码
|
public class RabbitInboundChannelModel extends InboundChannelModel {
protected Collection<String> queues;
protected boolean exclusive;
protected String priority;
protected String admin;
protected String concurrency;
protected String executor;
protected String ackMode;
public RabbitInboundChannelModel() {
super();
setType("rabbit");
}
public Collection<String> getQueues() {
return queues;
}
public void setQueues(Collection<String> queues) {
this.queues = queues;
}
public boolean isExclusive() {
return exclusive;
}
public void setExclusive(boolean exclusive) {
this.exclusive = exclusive;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
|
}
public String getAdmin() {
return admin;
}
public void setAdmin(String admin) {
this.admin = admin;
}
public String getConcurrency() {
return concurrency;
}
public void setConcurrency(String concurrency) {
this.concurrency = concurrency;
}
public String getExecutor() {
return executor;
}
public void setExecutor(String executor) {
this.executor = executor;
}
public String getAckMode() {
return ackMode;
}
public void setAckMode(String ackMode) {
this.ackMode = ackMode;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\RabbitInboundChannelModel.java
| 1
|
请完成以下Java代码
|
public int getC_ServiceLevel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ServiceLevel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Service Level Line.
@param C_ServiceLevelLine_ID
Product Revenue Recognition Service Level Line
*/
public void setC_ServiceLevelLine_ID (int C_ServiceLevelLine_ID)
{
if (C_ServiceLevelLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ServiceLevelLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ServiceLevelLine_ID, Integer.valueOf(C_ServiceLevelLine_ID));
}
/** Get Service Level Line.
@return Product Revenue Recognition Service Level Line
*/
public int getC_ServiceLevelLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ServiceLevelLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
|
}
return false;
}
/** Set Service date.
@param ServiceDate
Date service was provided
*/
public void setServiceDate (Timestamp ServiceDate)
{
set_ValueNoCheck (COLUMNNAME_ServiceDate, ServiceDate);
}
/** Get Service date.
@return Date service was provided
*/
public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getServiceDate()));
}
/** Set Quantity Provided.
@param ServiceLevelProvided
Quantity of service or product provided
*/
public void setServiceLevelProvided (BigDecimal ServiceLevelProvided)
{
set_ValueNoCheck (COLUMNNAME_ServiceLevelProvided, ServiceLevelProvided);
}
/** Get Quantity Provided.
@return Quantity of service or product provided
*/
public BigDecimal getServiceLevelProvided ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ServiceLevelProvided);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ServiceLevelLine.java
| 1
|
请完成以下Java代码
|
default <T> T getModelBeforeChanges(final Class<T> modelClass)
{
final ICalloutRecord calloutRecord = getCalloutRecord();
final T model = calloutRecord.getModelBeforeChanges(modelClass);
Check.assumeNotNull(model, "model not null");
return model;
}
int getWindowNo();
/**
* @return true if we are currently creating this record by copying (with or without details) from another record
*/
boolean isRecordCopyingMode();
/**
* @return true if we are currently creating this record by copying (with details) from another record
*/
boolean isRecordCopyingModeIncludingDetails();
ICalloutExecutor getCurrentCalloutExecutor();
/**
* Create and fire Data Status Error Event
*
* @param AD_Message message
* @param info that is shown to the user when hovering over the actual message
* @param isError if not true, it is a Warning
*/
void fireDataStatusEEvent(String AD_Message, String info, boolean isError);
/**
* Create and fire Data Status Error Event (from Error Log)
*
* @param errorLog log
*/
@Deprecated
void fireDataStatusEEvent(ValueNamePair errorLog);
/**
* Put to window context.
*/
default void putContext(final String name, final String value)
{
Env.setContext(getCtx(), name, value);
}
/**
* Put to window context.
*/
default void putWindowContext(final String name, final String value)
{
Env.setContext(getCtx(), getWindowNo(), name, value);
}
default void putContext(final String name, final boolean value)
|
{
Env.setContext(getCtx(), getWindowNo(), name, value);
}
/**
* Put to window context.
*/
default void putWindowContext(final String name, final boolean value)
{
Env.setContext(getCtx(), getWindowNo(), name, value);
}
default void putContext(final String name, final java.util.Date value)
{
Env.setContext(getCtx(), getWindowNo(), name, value);
}
/**
* Put to window context.
*/
default void putContext(final String name, final int value)
{
Env.setContext(getCtx(), getWindowNo(), name, value);
}
default int getGlobalContextAsInt(final String name)
{
return Env.getContextAsInt(getCtx(), name);
}
default int getTabInfoContextAsInt(final String name)
{
return Env.getContextAsInt(getCtx(), getWindowNo(), Env.TAB_INFO, name);
}
default boolean getContextAsBoolean(final String name)
{
return DisplayType.toBoolean(Env.getContext(getCtx(), getWindowNo(), name));
}
boolean isLookupValuesContainingId(@NonNull RepoIdAware id);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\ICalloutField.java
| 1
|
请完成以下Java代码
|
public class LoggerListener implements ApplicationListener<AbstractAuthorizationEvent> {
private static final Log logger = LogFactory.getLog(LoggerListener.class);
@Override
public void onApplicationEvent(AbstractAuthorizationEvent event) {
if (event instanceof AuthenticationCredentialsNotFoundEvent) {
onAuthenticationCredentialsNotFoundEvent((AuthenticationCredentialsNotFoundEvent) event);
}
if (event instanceof AuthorizationFailureEvent) {
onAuthorizationFailureEvent((AuthorizationFailureEvent) event);
}
if (event instanceof AuthorizedEvent) {
onAuthorizedEvent((AuthorizedEvent) event);
}
if (event instanceof PublicInvocationEvent) {
onPublicInvocationEvent((PublicInvocationEvent) event);
}
}
private void onAuthenticationCredentialsNotFoundEvent(AuthenticationCredentialsNotFoundEvent authEvent) {
logger.warn(LogMessage.format(
"Security interception failed due to: %s; secure object: %s; configuration attributes: %s",
authEvent.getCredentialsNotFoundException(), authEvent.getSource(), authEvent.getConfigAttributes()));
}
|
private void onPublicInvocationEvent(PublicInvocationEvent event) {
logger.info(LogMessage.format("Security interception not required for public secure object: %s",
event.getSource()));
}
private void onAuthorizedEvent(AuthorizedEvent authEvent) {
logger.info(LogMessage.format(
"Security authorized for authenticated principal: %s; secure object: %s; configuration attributes: %s",
authEvent.getAuthentication(), authEvent.getSource(), authEvent.getConfigAttributes()));
}
private void onAuthorizationFailureEvent(AuthorizationFailureEvent authEvent) {
logger.warn(LogMessage.format(
"Security authorization failed due to: %s; authenticated principal: %s; secure object: %s; configuration attributes: %s",
authEvent.getAccessDeniedException(), authEvent.getAuthentication(), authEvent.getSource(),
authEvent.getConfigAttributes()));
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\event\LoggerListener.java
| 1
|
请完成以下Java代码
|
final class ByteArrayBackedDataSource implements DataSource
{
private static final String DEFAULT_MimeType = MimeType.TYPE_TextPlain;
private final String _name;
private final String _mimeType;
private final byte[] _data;
/**
* Create a DataSource from a byte array
*
* @param mimeType type e.g. text/html (see {@link MimeType}.TYPE_*)
* @param data data
*/
public static ByteArrayBackedDataSource of(final String name, final String mimeType, final byte[] data)
{
return new ByteArrayBackedDataSource(name, mimeType, data);
}
/**
* Create a DataSource from a byte array.
*
* The mime type will be extracted from <code>filename</code>.
*
* @param data data
*/
public static ByteArrayBackedDataSource of(final String filename, final byte[] data)
{
Check.assumeNotEmpty(filename, "filename not empty");
final String mimeType = MimeType.getMimeType(filename);
return new ByteArrayBackedDataSource(filename, mimeType, data);
}
private ByteArrayBackedDataSource(final String name, final String mimeType, final byte[] data)
{
_mimeType = Check.isEmpty(mimeType, true) ? DEFAULT_MimeType : mimeType;
Check.assumeNotNull(data, "data not null");
_data = data;
if (Check.isEmpty(name, true))
{
_name = "data" + MimeType.getExtensionByType(_mimeType);
}
else
{
_name = name.trim();
}
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("name", _name)
.add("contentType", _mimeType)
.add("data bytes", (_data == null ? 0 : _data.length))
.toString();
}
/**
* @return file name
|
*/
@Override
public String getName()
{
return _name;
}
@Override
public InputStream getInputStream() throws IOException
{
if (_data == null)
{
throw new IOException("no data");
}
// a new stream must be returned each time.
return new ByteArrayInputStream(_data);
}
/**
* Throws exception
*/
@Override
public OutputStream getOutputStream() throws IOException
{
throw new IOException("cannot do this");
}
/**
* Get Content Type
*
* @return MIME type e.g. text/html
*/
@Override
public String getContentType()
{
return _mimeType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\ByteArrayBackedDataSource.java
| 1
|
请完成以下Java代码
|
public void setProxyPort (int ProxyPort)
{
set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort));
}
/** Get Proxy port.
@return Port of your proxy server
*/
@Override
public int getProxyPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statement Loader Class.
@param StmtLoaderClass
Class name of the bank statement loader
*/
@Override
public void setStmtLoaderClass (java.lang.String StmtLoaderClass)
{
set_Value (COLUMNNAME_StmtLoaderClass, StmtLoaderClass);
}
/** Get Statement Loader Class.
@return Class name of the bank statement loader
|
*/
@Override
public java.lang.String getStmtLoaderClass ()
{
return (java.lang.String)get_Value(COLUMNNAME_StmtLoaderClass);
}
/** Set User ID.
@param UserID
User ID or account number
*/
@Override
public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLoader.java
| 1
|
请完成以下Java代码
|
public class BpmnShapeParser implements BpmnXMLConstants {
public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
String id = xtr.getAttributeValue(null, ATTRIBUTE_DI_BPMNELEMENT);
GraphicInfo graphicInfo = new GraphicInfo();
String strIsExpanded = xtr.getAttributeValue(null, ATTRIBUTE_DI_IS_EXPANDED);
if ("true".equalsIgnoreCase(strIsExpanded)) {
graphicInfo.setExpanded(true);
}
BpmnXMLUtil.addXMLLocation(graphicInfo, xtr);
while (xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement() && ELEMENT_DI_BOUNDS.equalsIgnoreCase(xtr.getLocalName())) {
graphicInfo.setX(Double.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_DI_X)));
|
graphicInfo.setY(Double.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_DI_Y)));
graphicInfo.setWidth(Double.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_DI_WIDTH)));
graphicInfo.setHeight(Double.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_DI_HEIGHT)));
model.addGraphicInfo(id, graphicInfo);
break;
} else if (xtr.isEndElement() && ELEMENT_DI_SHAPE.equalsIgnoreCase(xtr.getLocalName())) {
break;
}
}
}
public BaseElement parseElement() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\parser\BpmnShapeParser.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Outcome handle(Throwable failure) {
CountDownLatch latch = new CountDownLatch(1);
FileSystemWatcher watcher = this.fileSystemWatcherFactory.getFileSystemWatcher();
watcher.addSourceDirectories(new ClassPathDirectories(Restarter.getInstance().getInitialUrls()));
watcher.addListener(new Listener(latch));
watcher.start();
try {
latch.await();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
return Outcome.RETRY;
}
private static class Listener implements FileChangeListener {
|
private final CountDownLatch latch;
Listener(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void onChange(Set<ChangedFiles> changeSet) {
this.latch.countDown();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\FileWatchingFailureHandler.java
| 2
|
请完成以下Java代码
|
public ModelElementInstance newInstance(ModelTypeInstanceContext instanceContext) {
return new CallableElementImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
supportedInterfaceRefCollection = sequenceBuilder.elementCollection(SupportedInterfaceRef.class)
.qNameElementReferenceCollection(Interface.class)
.build();
ioSpecificationChild = sequenceBuilder.element(IoSpecification.class)
.build();
ioBindingCollection = sequenceBuilder.elementCollection(IoBinding.class)
.build();
typeBuilder.build();
}
public CallableElementImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
|
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public Collection<Interface> getSupportedInterfaces() {
return supportedInterfaceRefCollection.getReferenceTargetElements(this);
}
public IoSpecification getIoSpecification() {
return ioSpecificationChild.getChild(this);
}
public void setIoSpecification(IoSpecification ioSpecification) {
ioSpecificationChild.setChild(this, ioSpecification);
}
public Collection<IoBinding> getIoBindings() {
return ioBindingCollection.get(this);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CallableElementImpl.java
| 1
|
请完成以下Java代码
|
public String toSqlStringWithColumnNameAlias(@NonNull final Evaluatee ctx)
{
return toStringExpressionWithColumnNameAlias().evaluate(ctx, OnVariableNotFound.Fail);
}
/**
* @return (sql expression) AS columnNameAlias
*/
public IStringExpression toStringExpressionWithColumnNameAlias()
{
return IStringExpression.composer()
.append("(").append(toStringExpression()).append(") AS ").append(columnNameAlias)
.build();
}
public IStringExpression toStringExpression()
{
final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias)
? joinOnTableNameOrAlias + "." + joinOnColumnName
: joinOnColumnName;
if (sqlExpression == null)
{
return ConstantStringExpression.of(joinOnColumnNameFQ);
}
else
{
return sqlExpression.toStringExpression(joinOnColumnNameFQ);
}
}
public IStringExpression toOrderByStringExpression()
{
final String joinOnColumnNameFQ = !Check.isEmpty(joinOnTableNameOrAlias)
? joinOnTableNameOrAlias + "." + joinOnColumnName
: joinOnColumnName;
if (sqlExpression == null)
{
return ConstantStringExpression.of(joinOnColumnNameFQ);
}
else
{
return sqlExpression.toOrderByStringExpression(joinOnColumnNameFQ);
}
}
|
public SqlSelectDisplayValue withJoinOnTableNameOrAlias(@Nullable final String joinOnTableNameOrAlias)
{
return !Objects.equals(this.joinOnTableNameOrAlias, joinOnTableNameOrAlias)
? toBuilder().joinOnTableNameOrAlias(joinOnTableNameOrAlias).build()
: this;
}
public String toSqlOrderByUsingColumnNameAlias()
{
final String columnNameAliasFQ = joinOnTableNameOrAlias != null ? joinOnTableNameOrAlias + "." + columnNameAlias : columnNameAlias;
if (sqlExpression != null)
{
return columnNameAliasFQ + "[" + sqlExpression.getNameSqlArrayIndex() + "]";
}
else
{
return columnNameAliasFQ;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlSelectDisplayValue.java
| 1
|
请完成以下Java代码
|
public class JuelFormEngine implements FormEngine {
public String getName() {
return "juel";
}
public Object renderStartForm(StartFormData startForm) {
if (startForm.getFormKey()==null) {
return null;
}
String formTemplateString = getFormTemplateString(startForm, startForm.getFormKey());
return executeScript(formTemplateString, null);
}
public Object renderTaskForm(TaskFormData taskForm) {
if (taskForm.getFormKey()==null) {
return null;
}
String formTemplateString = getFormTemplateString(taskForm, taskForm.getFormKey());
TaskEntity task = (TaskEntity) taskForm.getTask();
return executeScript(formTemplateString, task.getExecution());
}
protected Object executeScript(String scriptSrc, VariableScope scope) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
ScriptFactory scriptFactory = processEngineConfiguration.getScriptFactory();
ExecutableScript script = scriptFactory.createScriptFromSource(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE, scriptSrc);
ScriptInvocation invocation = new ScriptInvocation(script, scope);
try {
processEngineConfiguration
.getDelegateInterceptor()
.handleInvocation(invocation);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new ProcessEngineException(e);
}
return invocation.getInvocationResult();
}
|
protected String getFormTemplateString(FormData formInstance, String formKey) {
String deploymentId = formInstance.getDeploymentId();
ResourceEntity resourceStream = Context
.getCommandContext()
.getResourceManager()
.findResourceByDeploymentIdAndResourceName(deploymentId, formKey);
ensureNotNull("Form with formKey '" + formKey + "' does not exist", "resourceStream", resourceStream);
byte[] resourceBytes = resourceStream.getBytes();
String encoding = "UTF-8";
String formTemplateString = "";
try {
formTemplateString = new String(resourceBytes, encoding);
} catch (UnsupportedEncodingException e) {
throw new ProcessEngineException("Unsupported encoding of :" + encoding, e);
}
return formTemplateString;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\JuelFormEngine.java
| 1
|
请完成以下Java代码
|
public class TaskActivatedListenerDelegate implements ActivitiEventListener {
private final List<TaskRuntimeEventListener<TaskActivatedEvent>> listeners;
private final ToTaskActivatedConverter taskActivatedConverter;
public TaskActivatedListenerDelegate(
List<TaskRuntimeEventListener<TaskActivatedEvent>> listeners,
ToTaskActivatedConverter taskActivatedConverter
) {
this.listeners = listeners;
this.taskActivatedConverter = taskActivatedConverter;
}
@Override
public void onEvent(ActivitiEvent event) {
|
if (event instanceof ActivitiEntityEvent) {
taskActivatedConverter
.from((ActivitiEntityEvent) event)
.ifPresent(convertedEvent -> {
for (TaskRuntimeEventListener<TaskActivatedEvent> listener : listeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TaskActivatedListenerDelegate.java
| 1
|
请完成以下Java代码
|
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
@Override
|
public @Nullable BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, @Nullable Object value) {
this.delegate.setVariable(name, value);
}
@Override
public @Nullable Object lookupVariable(String name) {
return this.delegate.lookupVariable(name);
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\expression\DelegatingEvaluationContext.java
| 1
|
请完成以下Java代码
|
private XMLTelecom createXmlTelecom(@NonNull final TelecomAddressType telecom)
{
return XMLTelecom.builder()
.phone(ImmutableList.copyOf(telecom.getPhone()))
.build();
}
private XMLCompany createXMLCompany(@NonNull final CompanyType company)
{
return XMLCompany.builder()
.companyName(company.getCompanyname())
.build();
}
private XMLParty createXmlParty(@NonNull final PartyType eanParty)
{
final XMLParty.XMLPartyBuilder partyBuilder = XMLParty.builder();
if (eanParty.getEanParty() != null)
{
partyBuilder.eanParty(eanParty.getEanParty());
}
return partyBuilder.build();
}
private XMLPatientAddress createXmlPatientAddress(@NonNull final PatientAddressType patient)
{
final XMLPatientAddress.XMLPatientAddressBuilder patientAddressBuilder = XMLPatientAddress.builder();
if (patient.getPerson() != null)
{
patientAddressBuilder.person(createXmlPersonType(patient.getPerson()));
}
return patientAddressBuilder.build();
}
private XMLPersonType createXmlPersonType(@NonNull final PersonType person)
{
return XMLPersonType.builder()
.familyName(person.getFamilyname())
.givenName(person.getGivenname())
.build();
|
}
private XmlRejected createXmlRejected(@NonNull final RejectedType rejected)
{
final XmlRejectedBuilder rejectedBuilder = XmlRejected.builder();
rejectedBuilder.explanation(rejected.getExplanation())
.statusIn(rejected.getStatusIn())
.statusOut(rejected.getStatusOut());
if (rejected.getError() != null && !rejected.getError().isEmpty())
{
rejectedBuilder.errors(createXmlErrors(rejected.getError()));
}
return rejectedBuilder.build();
}
private List<XmlError> createXmlErrors(@NonNull final List<ErrorType> error)
{
final ImmutableList.Builder<XmlError> errorsBuilder = ImmutableList.builder();
for (final ErrorType errorType : error)
{
final XmlError xmlError = XmlError
.builder()
.code(errorType.getCode())
.errorValue(errorType.getErrorValue())
.recordId(errorType.getRecordId())
.text(errorType.getText())
.validValue(errorType.getValidValue())
.build();
errorsBuilder.add(xmlError);
}
return errorsBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\Invoice440ToCrossVersionModelTool.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static DDOrderQuery ddOrdersAssignedToUser(@NonNull final DDOrderReferenceQuery query)
{
return ddOrdersAssignedToUser(query.getResponsibleId(), query.getSorting()).build();
}
public static DDOrderQueryBuilder ddOrdersAssignedToUser(@NonNull final UserId responsibleId)
{
return ddOrdersAssignedToUser(responsibleId, DistributionJobSorting.DEFAULT);
}
private static DDOrderQueryBuilder ddOrdersAssignedToUser(@NonNull final UserId responsibleId, @NonNull DistributionJobSorting sorting)
{
return newDDOrdersQuery()
.orderBys(sorting.toDDOrderQueryOrderBys())
.responsibleId(ValueRestriction.equalsTo(responsibleId));
}
public static DDOrderQuery toActiveNotAssignedDDOrderQuery(final @NonNull DDOrderReferenceQuery query)
{
final DistributionFacetIdsCollection activeFacetIds = query.getActiveFacetIds();
final InSetPredicate<WarehouseId> warehouseToIds = extractWarehouseToIds(query);
return newDDOrdersQuery()
.orderBys(query.getSorting().toDDOrderQueryOrderBys())
.responsibleId(ValueRestriction.isNull())
.warehouseFromIds(activeFacetIds.getWarehouseFromIds())
.warehouseToIds(warehouseToIds)
.locatorToIds(InSetPredicate.onlyOrAny(query.getLocatorToId()))
.salesOrderIds(activeFacetIds.getSalesOrderIds())
.manufacturingOrderIds(activeFacetIds.getManufacturingOrderIds())
.datesPromised(activeFacetIds.getDatesPromised())
.productIds(activeFacetIds.getProductIds())
.qtysEntered(activeFacetIds.getQuantities())
.plantIds(activeFacetIds.getPlantIds())
.build();
|
}
@Nullable
private static InSetPredicate<WarehouseId> extractWarehouseToIds(final @NotNull DDOrderReferenceQuery query)
{
final Set<WarehouseId> facetWarehouseToIds = query.getActiveFacetIds().getWarehouseToIds();
final WarehouseId onlyWarehouseToId = query.getWarehouseToId();
if (onlyWarehouseToId != null)
{
if (facetWarehouseToIds.isEmpty() || facetWarehouseToIds.contains(onlyWarehouseToId))
{
return InSetPredicate.only(onlyWarehouseToId);
}
else
{
return InSetPredicate.none();
}
}
else if (!facetWarehouseToIds.isEmpty())
{
return InSetPredicate.only(facetWarehouseToIds);
}
else
{
return InSetPredicate.any();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobQueries.java
| 2
|
请完成以下Java代码
|
public String getCamundaProcessBinding() {
return camundaProcessBindingAttribute.getValue(this);
}
public void setCamundaProcessBinding(String camundaProcessBinding) {
camundaProcessBindingAttribute.setValue(this, camundaProcessBinding);
}
public String getCamundaProcessVersion() {
return camundaProcessVersionAttribute.getValue(this);
}
public void setCamundaProcessVersion(String camundaProcessVersion) {
camundaProcessVersionAttribute.setValue(this, camundaProcessVersion);
}
public String getCamundaProcessTenantId() {
return camundaProcessTenantIdAttribute.getValue(this);
}
public void setCamundaProcessTenantId(String camundaProcessTenantId) {
camundaProcessTenantIdAttribute.setValue(this, camundaProcessTenantId);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ProcessTask.class, CMMN_ELEMENT_PROCESS_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<ProcessTask>() {
public ProcessTask newInstance(ModelTypeInstanceContext instanceContext) {
return new ProcessTaskImpl(instanceContext);
}
});
processRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PROCESS_REF)
.build();
/** camunda extensions */
camundaProcessBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_BINDING)
.namespace(CAMUNDA_NS)
.build();
|
camundaProcessVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaProcessTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PROCESS_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
processRefExpressionChild = sequenceBuilder.element(ProcessRefExpression.class)
.minOccurs(0)
.maxOccurs(1)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessTaskImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class I18NRestController
{
public static final String ENDPOINT = WebConfig.ENDPOINT_ROOT + "/i18n";
private final IMsgBL msgBL = Services.get(IMsgBL.class);
private final UserSession userSession;
private static final String AD_MESSAGE_PREFIX = "webui.";
public I18NRestController(
@NonNull final UserSession userSession)
{
this.userSession = userSession;
}
@GetMapping("/messages")
public Map<String, Object> getMessages(@RequestParam(name = "filter", required = false) final String filterString,
@RequestParam(name = "lang", required = false) final String adLanguageParam)
{
final String adLanguage = StringUtils.trimBlankToOptional(adLanguageParam).orElseGet(userSession::getAD_Language);
|
final AdMessagesTree messagesTree = msgBL.messagesTree()
.adMessagePrefix(AD_MESSAGE_PREFIX)
.filterAdMessageStartingWithIgnoringCase(filterString)
.removePrefix(true)
.load(adLanguage);
return toJson(messagesTree);
}
private static Map<String, Object> toJson(@NonNull final AdMessagesTree messagesTree)
{
final LinkedHashMap<String, Object> json = new LinkedHashMap<>();
json.put("_language", messagesTree.getAdLanguage());
json.putAll(messagesTree.getMap());
return json;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\i18n\I18NRestController.java
| 2
|
请完成以下Java代码
|
public class BpmnEdgeParser implements BpmnXMLConstants {
public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
String id = xtr.getAttributeValue(null, ATTRIBUTE_DI_BPMNELEMENT);
List<GraphicInfo> wayPointList = new ArrayList<>();
String sourceDockerX = xtr.getAttributeValue(null, ATTRIBUTE_DI_SOURCE_DOCKER_X);
String sourceDockerY = xtr.getAttributeValue(null, ATTRIBUTE_DI_SOURCE_DOCKER_Y);
String targetDockerX = xtr.getAttributeValue(null, ATTRIBUTE_DI_TARGET_DOCKER_X);
String targetDockerY = xtr.getAttributeValue(null, ATTRIBUTE_DI_TARGET_DOCKER_Y);
if (StringUtils.isNotEmpty(sourceDockerX) && StringUtils.isNotEmpty(sourceDockerY) &&
StringUtils.isNotEmpty(targetDockerX) && StringUtils.isNotEmpty(targetDockerY)) {
BpmnDiEdge edgeInfo = new BpmnDiEdge();
edgeInfo.setWaypoints(wayPointList);
GraphicInfo sourceDockerInfo = new GraphicInfo();
sourceDockerInfo.setX(Double.valueOf(sourceDockerX).intValue());
sourceDockerInfo.setY(Double.valueOf(sourceDockerY).intValue());
edgeInfo.setSourceDockerInfo(sourceDockerInfo);
GraphicInfo targetDockerInfo = new GraphicInfo();
targetDockerInfo.setX(Double.valueOf(targetDockerX).intValue());
targetDockerInfo.setY(Double.valueOf(targetDockerY).intValue());
edgeInfo.setTargetDockerInfo(targetDockerInfo);
model.addEdgeInfo(id, edgeInfo);
}
while (xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement() && ELEMENT_DI_LABEL.equalsIgnoreCase(xtr.getLocalName())) {
BpmnXMLUtil.parseLabelElement(xtr, model, id);
} else if (xtr.isStartElement() && ELEMENT_DI_WAYPOINT.equalsIgnoreCase(xtr.getLocalName())) {
GraphicInfo graphicInfo = new GraphicInfo();
|
BpmnXMLUtil.addXMLLocation(graphicInfo, xtr);
graphicInfo.setX(Double.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_DI_X)).intValue());
graphicInfo.setY(Double.valueOf(xtr.getAttributeValue(null, ATTRIBUTE_DI_Y)).intValue());
wayPointList.add(graphicInfo);
} else if (xtr.isEndElement() && ELEMENT_DI_EDGE.equalsIgnoreCase(xtr.getLocalName())) {
break;
}
}
model.addFlowGraphicInfoList(id, wayPointList);
}
public BaseElement parseElement() {
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\parser\BpmnEdgeParser.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCollectType() {
return collectType;
}
/**
* 汇总类型(参考枚举:SettDailyCollectTypeEnum)
*
* @param collectType
*/
public void setCollectType(String collectType) {
this.collectType = collectType;
}
/**
* 结算批次号(结算之后再回写过来)
*
* @return
*/
public String getBatchNo() {
return batchNo;
}
/**
* 结算批次号(结算之后再回写过来)
*
* @param batchNo
*/
public void setBatchNo(String batchNo) {
this.batchNo = batchNo == null ? null : batchNo.trim();
}
/**
* 交易总金额
*
* @return
*/
public BigDecimal getTotalAmount() {
return totalAmount;
}
/**
* 交易总金额
*
* @param totalAmount
*/
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
/**
* 交易总笔数
*
* @return
*/
public Integer getTotalCount() {
return totalCount;
}
/**
* 交易总笔数
*
* @param totalCount
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
|
/**
* 结算状态(参考枚举:SettDailyCollectStatusEnum)
*
* @return
*/
public String getSettStatus() {
return settStatus;
}
/**
* 结算状态(参考枚举:SettDailyCollectStatusEnum)
*
* @param settStatus
*/
public void setSettStatus(String settStatus) {
this.settStatus = settStatus;
}
/**
* 风险预存期
*/
public Integer getRiskDay() {
return riskDay;
}
/**
* 风险预存期
*/
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettDailyCollect.java
| 2
|
请完成以下Java代码
|
public Object getModel()
{
return getModel(PlainContextAware.newWithThreadInheritedTrx());
}
/**
* Deprecated: pls use appropriate DAO/Repository for loading models
* e.g. ModelDAO.getById({@link TableRecordReference#getIdAssumingTableName(String, IntFunction)})
*/
@Deprecated
@Override
public <T> T getModel(final Class<T> modelClass)
{
return getModel(PlainContextAware.newWithThreadInheritedTrx(), modelClass);
}
@NonNull
public <T> T getModelNonNull(@NonNull final Class<T> modelClass)
{
return getModelNonNull(PlainContextAware.newWithThreadInheritedTrx(), modelClass);
}
public static <T> List<T> getModels(
|
@NonNull final Collection<? extends ITableRecordReference> references,
@NonNull final Class<T> modelClass)
{
return references
.stream()
.map(ref -> ref.getModel(modelClass))
.collect(ImmutableList.toImmutableList());
}
public boolean isOfType(@NonNull final Class<?> modelClass)
{
final String modelTableName = InterfaceWrapperHelper.getTableNameOrNull(modelClass);
return modelTableName != null && modelTableName.equals(getTableName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\lang\impl\TableRecordReference.java
| 1
|
请完成以下Java代码
|
public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request)
{
throw new IllegalStateException("Not supported");
}
@Override
public void invalidateCandidatesFor(final Object model)
{
final I_M_Inventory inventory = InterfaceWrapperHelper.create(model, I_M_Inventory.class);
invalidateCandidatesForInventory(inventory);
}
private void invalidateCandidatesForInventory(final I_M_Inventory inventory)
{
final InventoryId inventoryId = InventoryId.ofRepoId(inventory.getM_Inventory_ID());
//
// Retrieve inventory line handlers
final Properties ctx = InterfaceWrapperHelper.getCtx(inventory);
final List<IInvoiceCandidateHandler> inventoryLineHandlers = Services.get(IInvoiceCandidateHandlerBL.class).retrieveImplementationsForTable(ctx, I_M_InventoryLine.Table_Name);
for (final IInvoiceCandidateHandler handler : inventoryLineHandlers)
{
for (final I_M_InventoryLine line : inventoryDAO.retrieveLinesForInventoryId(inventoryId))
{
handler.invalidateCandidatesFor(line);
}
}
}
@Override
public String getSourceTable()
{
return I_M_Inventory.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 void setBPartnerData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\M_Inventory_Handler.java
| 1
|
请完成以下Java代码
|
public final class RelationEntity implements ToData<EntityRelation> {
@Id
@Column(name = RELATION_FROM_ID_PROPERTY, columnDefinition = "uuid")
private UUID fromId;
@Id
@Column(name = RELATION_FROM_TYPE_PROPERTY)
private String fromType;
@Id
@Column(name = RELATION_TO_ID_PROPERTY, columnDefinition = "uuid")
private UUID toId;
@Id
@Column(name = RELATION_TO_TYPE_PROPERTY)
private String toType;
@Id
@Column(name = RELATION_TYPE_GROUP_PROPERTY)
private String relationTypeGroup;
@Id
@Column(name = RELATION_TYPE_PROPERTY)
private String relationType;
@Column(name = VERSION_COLUMN)
private Long version;
@Convert(converter = JsonConverter.class)
@Column(name = ADDITIONAL_INFO_PROPERTY)
private JsonNode additionalInfo;
public RelationEntity() {
super();
}
|
public RelationEntity(EntityRelation relation) {
if (relation.getTo() != null) {
this.toId = relation.getTo().getId();
this.toType = relation.getTo().getEntityType().name();
}
if (relation.getFrom() != null) {
this.fromId = relation.getFrom().getId();
this.fromType = relation.getFrom().getEntityType().name();
}
this.relationType = relation.getType();
this.relationTypeGroup = relation.getTypeGroup().name();
this.additionalInfo = relation.getAdditionalInfo();
}
@Override
public EntityRelation toData() {
EntityRelation relation = new EntityRelation();
if (toId != null && toType != null) {
relation.setTo(EntityIdFactory.getByTypeAndUuid(toType, toId));
}
if (fromId != null && fromType != null) {
relation.setFrom(EntityIdFactory.getByTypeAndUuid(fromType, fromId));
}
relation.setType(relationType);
relation.setTypeGroup(RelationTypeGroup.valueOf(relationTypeGroup));
relation.setVersion(version);
relation.setAdditionalInfo(additionalInfo);
return relation;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\RelationEntity.java
| 1
|
请完成以下Java代码
|
private ReportableException createException(String url, ClassicHttpResponse httpResponse) {
StatusLine statusLine = new StatusLine(httpResponse);
String message = "Initializr service call failed using '" + url + "' - service returned "
+ statusLine.getReasonPhrase();
String error = extractMessage(httpResponse.getEntity());
if (StringUtils.hasText(error)) {
message += ": '" + error + "'";
}
else {
int statusCode = statusLine.getStatusCode();
message += " (unexpected " + statusCode + " error)";
}
throw new ReportableException(message);
}
private @Nullable String extractMessage(@Nullable HttpEntity entity) {
if (entity != null) {
try {
JSONObject error = getContentAsJson(entity);
if (error.has("message")) {
return error.getString("message");
}
}
catch (Exception ex) {
// Ignore
}
}
return null;
}
private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException {
return new JSONObject(getContent(entity));
}
private String getContent(HttpEntity entity) throws IOException {
|
ContentType contentType = ContentType.create(entity.getContentType());
Charset charset = contentType.getCharset();
charset = (charset != null) ? charset : StandardCharsets.UTF_8;
byte[] content = FileCopyUtils.copyToByteArray(entity.getContent());
return new String(content, charset);
}
private @Nullable String extractFileName(@Nullable Header header) {
if (header != null) {
String value = header.getValue();
int start = value.indexOf(FILENAME_HEADER_PREFIX);
if (start != -1) {
value = value.substring(start + FILENAME_HEADER_PREFIX.length());
int end = value.indexOf('\"');
if (end != -1) {
return value.substring(0, end);
}
}
}
return null;
}
}
|
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\init\InitializrService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected List<JobInfoEntity> offerJobs(List<? extends JobInfoEntity> acquiredJobs) {
List<JobInfoEntity> rejected = new ArrayList<>();
for (JobInfoEntity job : acquiredJobs) {
boolean jobSuccessFullyOffered = asyncExecutor.executeAsyncJob(job);
if (!jobSuccessFullyOffered) {
rejected.add(job);
}
}
return rejected;
}
public void stop() {
synchronized (MONITOR) {
isInterrupted = true;
if (isWaiting.compareAndSet(true, false)) {
MONITOR.notifyAll();
}
}
}
protected void sleep(long millisToWait) {
if (millisToWait > 0) {
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("async job acquisition for engine {}, thread sleeping for {} millis", getEngineName(), millisToWait);
}
synchronized (MONITOR) {
if (!isInterrupted) {
isWaiting.set(true);
lifecycleListener.startWaiting(getEngineName(), millisToWait);
MONITOR.wait(millisToWait);
}
}
|
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("async job acquisition for engine {}, thread woke up", getEngineName());
}
} catch (InterruptedException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("async job acquisition for engine {}, wait interrupted", getEngineName());
}
} finally {
isWaiting.set(false);
}
}
}
protected String getEngineName() {
return asyncExecutor.getJobServiceConfiguration().getEngineName();
}
public AcquireAsyncJobsDueLifecycleListener getLifecycleListener() {
return lifecycleListener;
}
public void setLifecycleListener(AcquireAsyncJobsDueLifecycleListener lifecycleListener) {
this.lifecycleListener = lifecycleListener;
}
public void setConfiguration(AcquireJobsRunnableConfiguration configuration) {
this.configuration = configuration;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AcquireAsyncJobsDueRunnable.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PackageLabels
{
private final OrderId orderId;
private final PackageLabelType defaultLabelType;
@Getter(AccessLevel.NONE)
private final ImmutableMap<PackageLabelType, PackageLabel> labels;
@Builder
private PackageLabels(
@NonNull final OrderId orderId,
@NonNull final PackageLabelType defaultLabelType,
@NonNull @Singular final ImmutableList<PackageLabel> labels)
{
Check.assumeNotEmpty(labels, "labels is not empty");
this.orderId = orderId;
this.defaultLabelType = defaultLabelType;
this.labels = Maps.uniqueIndex(labels, PackageLabel::getType);
Check.assume(this.labels.containsKey(defaultLabelType), "defaultLabelType={} shall be present in {}", defaultLabelType, labels);
|
}
public Set<PackageLabelType> getLabelTypes()
{
return labels.keySet();
}
public PackageLabel getPackageLabel(final PackageLabelType type)
{
final PackageLabel packageLabel = labels.get(type);
Check.assumeNotNull(packageLabel, "package label of type={} shall exist in {}", type, labels);
return packageLabel;
}
public PackageLabel getDefaultPackageLabel()
{
return getPackageLabel(getDefaultLabelType());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\model\PackageLabels.java
| 2
|
请完成以下Java代码
|
public IInOutProducerFromShipmentScheduleWithHU setCreatePackingLines(final boolean createPackingLines)
{
this.createPackingLines = createPackingLines;
return this;
}
@Override
public IInOutProducerFromShipmentScheduleWithHU computeShipmentDate(final CalculateShippingDateRule calculateShippingDateRule)
{
this.calculateShippingDateRule = calculateShippingDateRule;
return this;
}
@Override
public IInOutProducerFromShipmentScheduleWithHU setScheduleIdToExternalInfo(@NonNull final ImmutableMap<ShipmentScheduleId, ShipmentScheduleExternalInfo> scheduleId2ExternalInfo)
|
{
this.scheduleId2ExternalInfo.putAll(scheduleId2ExternalInfo);
return this;
}
@Override
public String toString()
{
return "InOutProducerFromShipmentSchedule [result=" + result
+ ", shipmentScheduleKeyBuilder=" + shipmentScheduleKeyBuilder + ", huShipmentScheduleKeyBuilder=" + huShipmentScheduleKeyBuilder
+ ", processorCtx=" + processorCtx + ", currentShipment=" + currentShipment
+ ", currentShipmentLineBuilder=" + currentShipmentLineBuilder + ", currentCandidates=" + currentCandidates
+ ", lastItem=" + lastItem + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\spi\impl\InOutProducerFromShipmentScheduleWithHU.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public RuleNodeInfo getLastVisitedRuleNode(UUID id) {
return lastRuleNodeMap.get(id);
}
public void printProfilerStats() {
if (profilerEnabled) {
log.debug("Top Rule Nodes by max execution time:");
ruleNodeProfilerMap.values().stream()
.sorted(Comparator.comparingLong(TbRuleNodeProfilerInfo::getMaxExecutionTime).reversed()).limit(5)
.forEach(info -> log.debug("[{}][{}] max execution time: {}. {}", queueName, info.getRuleNodeId(), info.getMaxExecutionTime(), info.getLabel()));
log.info("Top Rule Nodes by avg execution time:");
ruleNodeProfilerMap.values().stream()
.sorted(Comparator.comparingDouble(TbRuleNodeProfilerInfo::getAvgExecutionTime).reversed()).limit(5)
.forEach(info -> log.info("[{}][{}] avg execution time: {}. {}", queueName, info.getRuleNodeId(), info.getAvgExecutionTime(), info.getLabel()));
log.info("Top Rule Nodes by execution count:");
ruleNodeProfilerMap.values().stream()
.sorted(Comparator.comparingInt(TbRuleNodeProfilerInfo::getExecutionCount).reversed()).limit(5)
|
.forEach(info -> log.info("[{}][{}] execution count: {}. {}", queueName, info.getRuleNodeId(), info.getExecutionCount(), info.getLabel()));
}
}
public void cleanup() {
canceled = true;
pendingMap.clear();
successMap.clear();
failedMap.clear();
}
public boolean isCanceled() {
return skipTimeoutMsgsPossible && canceled;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbMsgPackProcessingContext.java
| 2
|
请完成以下Java代码
|
public class CursorPager<T extends Node> {
private List<T> data;
private boolean next;
private boolean previous;
public CursorPager(List<T> data, Direction direction, boolean hasExtra) {
this.data = data;
if (direction == Direction.NEXT) {
this.previous = false;
this.next = hasExtra;
} else {
this.next = false;
this.previous = hasExtra;
}
}
public boolean hasNext() {
return next;
}
public boolean hasPrevious() {
|
return previous;
}
public PageCursor getStartCursor() {
return data.isEmpty() ? null : data.get(0).getCursor();
}
public PageCursor getEndCursor() {
return data.isEmpty() ? null : data.get(data.size() - 1).getCursor();
}
public enum Direction {
PREV,
NEXT
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\CursorPager.java
| 1
|
请完成以下Java代码
|
public Text getText() {
return textChild.getChild(this);
}
public void setText(Text text) {
textChild.setChild(this, text);
}
public TextAnnotationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(TextAnnotation.class, DMN_ELEMENT_TEXT_ANNOTATION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Artifact.class)
.instanceProvider(new ModelTypeInstanceProvider<TextAnnotation>() {
public TextAnnotation newInstance(ModelTypeInstanceContext instanceContext) {
|
return new TextAnnotationImpl(instanceContext);
}
});
textFormatAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TEXT_FORMAT)
.defaultValue("text/plain")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
textChild = sequenceBuilder.element(Text.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\TextAnnotationImpl.java
| 1
|
请完成以下Java代码
|
public class Chunk {
/**
* 当前文件块,从1开始
*/
private Integer chunkNumber;
/**
* 分块大小
*/
private Long chunkSize;
/**
* 当前分块大小
*/
private Long currentChunkSize;
/**
* 总大小
*/
private Long totalSize;
|
/**
* 文件名
*/
private String filename;
/**
* 总块数
*/
private Integer totalChunks;
/**
* 分块文件内容
*/
private MultipartFile file;
}
|
repos\springboot-demo-master\file\src\main\java\com\et\bean\Chunk.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ProductPriceSettings getProductPriceSettings(@NonNull final I_M_ProductPrice productPrice, @Nullable final Quantity qty)
{
if (qty == null)
{
return ProductPriceSettings.of(productPrice);
}
final ScalePriceUsage scalePriceUsage = ScalePriceUsage.ofCode(productPrice.getUseScalePrice());
if (!scalePriceUsage.useScalePrice())
{
return ProductPriceSettings.of(productPrice);
}
final BigDecimal qtyInProductPriceUom = getQtyInProductPriceUOM(productPrice, qty);
final I_M_ProductScalePrice scalePrice = productPA.retrieveScalePrices(productPrice.getM_ProductPrice_ID(), qtyInProductPriceUom, ITrx.TRXNAME_None);
if (scalePrice != null)
{
return ProductPriceSettings.of(scalePrice);
}
else if (scalePriceUsage.allowFallbackToProductPrice())
{
return ProductPriceSettings.of(productPrice);
}
else
{
return null;
}
}
@NonNull
private BigDecimal getQtyInProductPriceUOM(@NonNull final I_M_ProductPrice productPrice, @NonNull final Quantity quantity)
{
final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID());
final UomId productPriceUomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
return uomConversionBL.convertQty(productId, quantity.toBigDecimal(), quantity.getUomId(), productPriceUomId);
|
}
@Value
public static class ProductPriceSettings
{
@NonNull
BigDecimal priceStd;
@NonNull
BigDecimal priceLimit;
@NonNull
BigDecimal priceList;
public static ProductPriceSettings of(@NonNull final I_M_ProductPrice productPrice)
{
return new ProductPriceSettings(productPrice.getPriceStd(), productPrice.getPriceLimit(), productPrice.getPriceList());
}
public static ProductPriceSettings of(@NonNull final I_M_ProductScalePrice productScalePrice)
{
return new ProductPriceSettings(productScalePrice.getPriceStd(), productScalePrice.getPriceLimit(), productScalePrice.getPriceList());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\ProductScalePriceService.java
| 2
|
请完成以下Java代码
|
public void markAsDone() {
done = true;
completedOn = new Date();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean getDone() {
return done;
}
public Date getCreatedOn() {
return createdOn;
}
public Date getCompletedOn() {
return completedOn;
}
public void setDone(boolean done) {
this.done = done;
}
|
public void setCompletedOn(Date completedOn) {
this.completedOn = completedOn;
}
public long doneSince() {
return done ? Duration
.between(createdOn.toInstant(), completedOn.toInstant())
.toMinutes() : 0;
}
public Function<Object, Object> handleDone() {
return (obj) -> done ? String.format("<small>Done %s minutes ago<small>", obj) : "";
}
}
|
repos\tutorials-master\mustache\src\main\java\com\baeldung\mustache\model\Todo.java
| 1
|
请完成以下Java代码
|
public static String getSqlInjectTableName(String table) {
if(oConvertUtils.isEmpty(table)){
return table;
}
// 代码逻辑说明: 表单设计器列表翻译存在表名带条件,导致翻译出问题----
int index = table.toLowerCase().indexOf(" where ");
if (index != -1) {
table = table.substring(0, index);
log.info("截掉where之后的新表名:" + table);
}
table = table.trim();
/**
* 检验表名是否合法
*
* 表名只能由字母、数字和下划线组成。
* 表名必须以字母开头。
* 表名长度通常有限制,例如最多为 64 个字符。
*/
boolean isValidTableName = tableNamePattern.matcher(table).matches();
if (!isValidTableName) {
String errorMsg = "表名不合法,存在SQL注入风险!--->" + table;
log.error(errorMsg);
throw new JeecgSqlInjectionException(errorMsg);
}
//进一步验证是否存在SQL注入风险
filterContentMulti(table);
return table;
}
/**
* 返回查询字段
* <p>
* sql注入过滤处理,遇到注入关键字抛异常
*
* @param field
*/
static final Pattern fieldPattern = Pattern.compile("^[a-zA-Z0-9_]+$");
public static String getSqlInjectField(String field) {
if(oConvertUtils.isEmpty(field)){
return field;
}
field = field.trim();
if (field.contains(SymbolConstant.COMMA)) {
return getSqlInjectField(field.split(SymbolConstant.COMMA));
}
/**
* 校验表字段是否有效
*
* 字段定义只能是是字母 数字 下划线的组合(不允许有空格、转义字符串等)
*/
boolean isValidField = fieldPattern.matcher(field).matches();
if (!isValidField) {
String errorMsg = "字段不合法,存在SQL注入风险!--->" + field;
log.error(errorMsg);
throw new JeecgSqlInjectionException(errorMsg);
}
//进一步验证是否存在SQL注入风险
filterContentMulti(field);
return field;
}
/**
* 获取多个字段
* 返回: 逗号拼接
*
* @param fields
* @return
*/
public static String getSqlInjectField(String... fields) {
for (String s : fields) {
getSqlInjectField(s);
}
return String.join(SymbolConstant.COMMA, fields);
}
/**
|
* 获取排序字段
* 返回:字符串
*
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortField 排序字段
* @return
*/
public static String getSqlInjectSortField(String sortField) {
String field = SqlInjectionUtil.getSqlInjectField(oConvertUtils.camelToUnderline(sortField));
return field;
}
/**
* 获取多个排序字段
* 返回:数组
*
* 1.将驼峰命名转化成下划线
* 2.限制sql注入
* @param sortFields 多个排序字段
* @return
*/
public static List getSqlInjectSortFields(String... sortFields) {
List list = new ArrayList<String>();
for (String sortField : sortFields) {
list.add(getSqlInjectSortField(sortField));
}
return list;
}
/**
* 获取 orderBy type
* 返回:字符串
* <p>
* 1.检测是否为 asc 或 desc 其中的一个
* 2.限制sql注入
*
* @param orderType
* @return
*/
public static String getSqlInjectOrderType(String orderType) {
if (orderType == null) {
return null;
}
orderType = orderType.trim();
if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) {
return CommonConstant.ORDER_TYPE_ASC;
} else {
return CommonConstant.ORDER_TYPE_DESC;
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\SqlInjectionUtil.java
| 1
|
请完成以下Java代码
|
public void collectAll(@NonNull final ISqlQueryFilter sqlQueryFilter)
{
final List<Object> sqlParams = sqlQueryFilter.getSqlParams(Env.getCtx());
collectAll(sqlParams);
}
/**
* Directly append the given {@code sqlParams}. Please prefer using {@link #placeholder(Object)} instead.<br>
* "Package" scope because currently this method is needed only by {@link SqlDefaultDocumentFilterConverter}.
*
* Please avoid using it. It's used mainly to adapt with old code
*
* @param sqlParams
*/
public void collectAll(@Nullable final Collection<? extends Object> sqlParams)
{
if (sqlParams == null || sqlParams.isEmpty())
{
return;
}
if (params == null)
{
throw new IllegalStateException("Cannot append " + sqlParams + " to not collecting params");
}
params.addAll(sqlParams);
}
public void collect(@NonNull final SqlParamsCollector from)
{
collectAll(from.params);
}
/**
* Collects given SQL value and returns an SQL placeholder, i.e. "?"
*
* In case this is in non-collecting mode, the given SQL value will be converted to SQL code and it will be returned.
* The internal list won't be affected, because it does not exist.
*/
public String placeholder(@Nullable final Object sqlValue)
|
{
if (params == null)
{
return DB.TO_SQL(sqlValue);
}
else
{
params.add(sqlValue);
return "?";
}
}
/** @return readonly live list */
public List<Object> toList()
{
return paramsRO;
}
/** @return read/write live list */
public List<Object> toLiveList()
{
return params;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlParamsCollector.java
| 1
|
请完成以下Java代码
|
protected Color getCellForegroundColor(final int modelRowIndex, final int modelColumnIndex)
{
final ModelType row = getRow(modelRowIndex);
BigDecimal multiplier = row.getMultiplierAP();
if (row.isCreditMemo())
{
multiplier = multiplier.negate();
}
if (multiplier.signum() < 0)
{
return AdempierePLAF.getTextColor_Issue(); // Red
}
return null;
}
/** @return sum of {@link IAllocableDocRow#getAppliedAmt()} (AP Adjusted) of all selected rows */
public final BigDecimal getTotalAppliedAmt()
{
return calculateTotalAppliedAmt(getRowsInnerList());
}
@VisibleForTesting
public static final BigDecimal calculateTotalAppliedAmt(final Iterable<? extends IAllocableDocRow> rows)
{
BigDecimal totalAppliedAmt = BigDecimal.ZERO;
for (final IAllocableDocRow row : rows)
{
if (!row.isSelected())
{
continue;
}
final BigDecimal rowAppliedAmt = row.getAppliedAmt_APAdjusted();
totalAppliedAmt = totalAppliedAmt.add(rowAppliedAmt);
}
return totalAppliedAmt;
}
/** @return latest {@link IAllocableDocRow#getDocumentDate()} of all selected rows */
public final Date getLatestDocumentDate()
{
Date latestDocumentDate = null;
for (final IAllocableDocRow row : getRowsInnerList())
{
if (!row.isSelected())
{
|
continue;
}
final Date documentDate = row.getDocumentDate();
latestDocumentDate = TimeUtil.max(latestDocumentDate, documentDate);
}
return latestDocumentDate;
}
/** @return latest {@link IAllocableDocRow#getDateAcct()} of all selected rows */
public final Date getLatestDateAcct()
{
Date latestDateAcct = null;
for (final IAllocableDocRow row : getRowsInnerList())
{
if (!row.isSelected())
{
continue;
}
final Date dateAcct = row.getDateAcct();
latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct);
}
return latestDateAcct;
}
public final List<ModelType> getRowsSelected()
{
return FluentIterable.from(getRowsInnerList())
.filter(IAllocableDocRow.PREDICATE_Selected)
.toList();
}
public final List<ModelType> getRowsSelectedNoTaboo()
{
return FluentIterable.from(getRowsInnerList())
.filter(IAllocableDocRow.PREDICATE_Selected)
.filter(IAllocableDocRow.PREDICATE_NoTaboo)
.toList();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\AbstractAllocableDocTableModel.java
| 1
|
请完成以下Java代码
|
protected String getResourcesRootDirectory() {
return "org/flowable/idm/db/";
}
@Override
protected String getPropertyTable() {
return IDM_PROPERTY_TABLE;
}
@Override
protected String getUpgradeStartVersion() {
return "5.99.0.0";
}
@Override
protected void internalDbSchemaCreate() {
// User and Group tables can already have been created by the process engine in an earlier version
if (isIdmGroupTablePresent()) {
schemaUpdate();
} else {
super.internalDbSchemaCreate();
}
}
@Override
protected boolean isUpdateNeeded() {
boolean propertyTablePresent = isTablePresent(IDM_PROPERTY_TABLE);
if (!propertyTablePresent) {
return isIdmGroupTablePresent();
}
return true;
}
public boolean isIdmGroupTablePresent() {
return isTablePresent("ACT_ID_GROUP");
}
@Override
public void schemaCheckVersion() {
try {
String dbVersion = getSchemaVersion();
if (!IdmEngine.VERSION.equals(dbVersion)) {
throw new FlowableWrongDbException(IdmEngine.VERSION, dbVersion);
}
String errorMessage = null;
|
if (!isTablePresent(IDM_PROPERTY_TABLE)) {
errorMessage = addMissingComponent(errorMessage, "engine");
}
if (errorMessage != null) {
throw new FlowableException("Flowable IDM database problem: " + errorMessage);
}
} catch (Exception e) {
if (isMissingTablesException(e)) {
throw new FlowableException(
"no flowable tables in db. set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in flowable.cfg.xml for automatic schema creation",
e);
} else {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new FlowableException("couldn't get db schema version", e);
}
}
}
logger.debug("flowable idm db schema check successful");
}
protected String addMissingComponent(String missingComponents, String component) {
if (missingComponents == null) {
return "Tables missing for component(s) " + component;
}
return missingComponents + ", " + component;
}
@Override
public String getContext() {
return SCHEMA_COMPONENT;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\db\IdmDbSchemaManager.java
| 1
|
请完成以下Java代码
|
public InputStream execute(final CommandContext commandContext) {
this.commandContext = commandContext;
checkAuthorization();
final FormData formData = getFormData();
String formKey = formData.getFormKey();
CamundaFormRef camundaFormRef = formData.getCamundaFormRef();
if (formKey != null) {
return getResourceForFormKey(formData, formKey);
} else if(camundaFormRef != null && camundaFormRef.getKey() != null) {
return getResourceForCamundaFormRef(camundaFormRef, formData.getDeploymentId());
} else {
throw new BadUserRequestException("One of the attributes 'formKey' and 'camunda:formRef' must be supplied but none were set.");
}
}
protected InputStream getResourceForFormKey(FormData formData, String formKey) {
String resourceName = formKey;
if (resourceName.startsWith(EMBEDDED_KEY)) {
resourceName = resourceName.substring(EMBEDDED_KEY_LENGTH, resourceName.length());
} else if (resourceName.startsWith(CAMUNDA_FORMS_KEY)) {
resourceName = resourceName.substring(CAMUNDA_FORMS_KEY_LENGTH, resourceName.length());
}
if (!resourceName.startsWith(DEPLOYMENT_KEY)) {
throw new BadUserRequestException("The form key '" + formKey + "' does not reference a deployed form.");
}
resourceName = resourceName.substring(DEPLOYMENT_KEY_LENGTH, resourceName.length());
|
return getDeploymentResource(formData.getDeploymentId(), resourceName);
}
protected InputStream getResourceForCamundaFormRef(CamundaFormRef camundaFormRef,
String deploymentId) {
CamundaFormDefinition definition = commandContext.runWithoutAuthorization(
new GetCamundaFormDefinitionCmd(camundaFormRef, deploymentId));
if (definition == null) {
throw new NotFoundException("No Camunda Form Definition was found for Camunda Form Ref: " + camundaFormRef);
}
return getDeploymentResource(definition.getDeploymentId(), definition.getResourceName());
}
protected InputStream getDeploymentResource(String deploymentId, String resourceName) {
GetDeploymentResourceCmd getDeploymentResourceCmd = new GetDeploymentResourceCmd(deploymentId, resourceName);
try {
return commandContext.runWithoutAuthorization(getDeploymentResourceCmd);
} catch (DeploymentResourceNotFoundException e) {
throw new NotFoundException("The form with the resource name '" + resourceName + "' cannot be found in deployment with id " + deploymentId, e);
}
}
protected abstract FormData getFormData();
protected abstract void checkAuthorization();
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractGetDeployedFormCmd.java
| 1
|
请完成以下Java代码
|
public void clear() {
throw new UnsupportedOperationException("decision output is immutable");
}
@Override
public Set<Entry<String, Object>> entrySet() {
Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>();
for (Entry<String, TypedValue> typedEntry : outputValues.entrySet()) {
DmnDecisionRuleOutputEntry entry = new DmnDecisionRuleOutputEntry(typedEntry.getKey(), typedEntry.getValue());
entrySet.add(entry);
}
return entrySet;
}
protected class DmnDecisionRuleOutputEntry implements Entry<String, Object> {
protected final String key;
protected final TypedValue typedValue;
public DmnDecisionRuleOutputEntry(String key, TypedValue typedValue) {
this.key = key;
this.typedValue = typedValue;
}
@Override
public String getKey() {
|
return key;
}
@Override
public Object getValue() {
if (typedValue != null) {
return typedValue.getValue();
} else {
return null;
}
}
@Override
public Object setValue(Object value) {
throw new UnsupportedOperationException("decision output entry is immutable");
}
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultEntriesImpl.java
| 1
|
请完成以下Java代码
|
public void updateAttributesOnSubProducerChanged(final Properties ctx,
final IAttributeSet attributeSet,
final boolean subProducerJustInitialized)
{
// Set the Marke ADR from the subproducer
recalculateADR(ctx, attributeSet, subProducerJustInitialized);
}
private void recalculateADR(final Properties ctx,
final IAttributeSet attributeSet,
final boolean subProducerJustInitialized)
{
final I_M_Attribute attr_MarkeADR = adrAttributeDAO.retrieveADRAttribute(ctx);
if (attr_MarkeADR == null)
{
return;
}
final IAttributeStorage attributeStorage = (IAttributeStorage)attributeSet;
if (!attributeStorage.hasAttribute(attr_MarkeADR))
{
return; // skip if the attribute storage does not have the ADR attribute
}
if (subProducerJustInitialized && attributeStorage.getValue(attr_MarkeADR) != null)
{
return; // task 08782: the sub-producer was set only now, so we keep the pre-existing ADR value.
}
// This variable will keep the partner for who we want to compute the ADR Region attribute
// It can be either the sub-producer,if it exists, or the partner if it doesn't
I_C_BPartner partner = getSubProducerBPartnerOrNull(attributeStorage);
if (partner == null)
{
final I_M_HU hu = huAttributesBL.getM_HU_OrNull(attributeSet); // attributeset might also belong to e.g. an inventory line and have no HU
if (hu != null)
{
partner = InterfaceWrapperHelper.create(IHandlingUnitsBL.extractBPartnerOrNull(hu), I_C_BPartner.class);
}
// If there is no BPartner we have to set the ADR attribute to null
if (partner == null)
{
Check.assume(!subProducerJustInitialized, "partner=null for attributeSet={}, therefore subProducerJustInitialized is false", attributeSet);
attributeStorage.setValueToNull(attr_MarkeADR);
return;
}
|
}
// isSoTrx = false because we only need it in Wareneingang POS
// TODO: Check if this will be needed somewhere else and fix accordingly
final boolean isSOTrx = false;
final AttributeListValue markeADR = adrAttributeBL.getCreateAttributeValue(ctx, partner, isSOTrx, ITrx.TRXNAME_None);
final String markeADRValue = markeADR == null ? null : markeADR.getValue();
attributeStorage.setValue(attr_MarkeADR, markeADRValue);
}
@Nullable
private I_C_BPartner getSubProducerBPartnerOrNull(final IAttributeSet attributeStorage)
{
final AttributeId subProducerAttributeId = attributeDAO.retrieveActiveAttributeIdByValueOrNull(HUAttributeConstants.ATTR_SubProducerBPartner_Value);
if (subProducerAttributeId == null)
{
return null;
}
final I_M_Attribute subProducerAttribute = attributeDAO.getAttributeRecordById(subProducerAttributeId);
final BigDecimal subProducerIdBD = attributeStorage.getValueAsBigDecimal(subProducerAttribute);
final int subProducerID = subProducerIdBD.intValueExact();
if (subProducerID <= 0)
{
return null;
}
return bpartnerDAO.getById(subProducerID, I_C_BPartner.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\SubProducerAttributeBL.java
| 1
|
请完成以下Java代码
|
public class DynamicProgramming implements RestoreIPAddress {
public List<String> restoreIPAddresses(String s) {
int n = s.length();
if (n < 4 || n > 12) return new ArrayList<>();
List<String>[][] dp = new ArrayList[n + 1][5];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= 4; j++) {
dp[i][j] = new ArrayList<>();
}
}
dp[0][0].add("");
for (int i = 1; i <= n; i++) {
for (int k = 1; k <= 4; k++) {
for (int j = 1; j <= 3 && i - j >= 0; j++) {
String segment = s.substring(i - j, i);
|
if (isValid(segment)) {
for (String prefix : dp[i - j][k - 1]) {
dp[i][k].add(prefix.isEmpty() ? segment : prefix + "." + segment);
}
}
}
}
}
return dp[n][4];
}
private boolean isValid(String part) {
if (part.length() > 1 && part.startsWith("0")) return false;
int num = Integer.parseInt(part);
return num >= 0 && num <= 255;
}
}
|
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-3\src\main\java\com\baeldung\restoreipaddress\DynamicProgramming.java
| 1
|
请完成以下Java代码
|
public class MatchPODAO implements IMatchPODAO
{
@Override
public List<I_M_MatchPO> getByOrderLineAndInvoiceLine(
@NonNull final OrderLineId orderLineId,
@NonNull final InvoiceAndLineId invoiceAndLineId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_MatchPO.class)
.addEqualsFilter(I_M_MatchPO.COLUMN_C_OrderLine_ID, orderLineId)
.addEqualsFilter(I_M_MatchPO.COLUMN_C_InvoiceLine_ID, invoiceAndLineId)
.create()
.listImmutable(I_M_MatchPO.class);
}
@Override
public List<I_M_MatchPO> getByReceiptId(final InOutId inOutId)
{
final String sql = "SELECT * FROM M_MatchPO m"
+ " INNER JOIN M_InOutLine l ON (m.M_InOutLine_ID=l.M_InOutLine_ID) "
+ "WHERE l.M_InOut_ID=?";
final List<Object> sqlParams = Collections.singletonList(inOutId);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
final List<I_M_MatchPO> result = new ArrayList<>();
while (rs.next())
{
result.add(new MMatchPO(Env.getCtx(), rs, ITrx.TRXNAME_ThreadInherited));
}
return result;
}
catch (final Exception e)
{
throw new DBException(e, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
} // getInOut
@Override
public List<I_M_MatchPO> getByInvoiceId(@NonNull final InvoiceId invoiceId)
{
final String sql = "SELECT * FROM M_MatchPO mi"
+ " INNER JOIN C_InvoiceLine il ON (mi.C_InvoiceLine_ID=il.C_InvoiceLine_ID) "
+ "WHERE il.C_Invoice_ID=?";
final List<Object> sqlParams = Arrays.asList(invoiceId);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
final List<I_M_MatchPO> result = new ArrayList<>();
while (rs.next())
|
{
result.add(new MMatchPO(Env.getCtx(), rs, ITrx.TRXNAME_ThreadInherited));
}
return result;
}
catch (final Exception e)
{
throw new DBException(e, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
}
@Override
public List<I_M_MatchPO> getByOrderLineId(final OrderLineId orderLineId)
{
if (orderLineId == null)
{
return ImmutableList.of();
}
return Services.get(IQueryBL.class)
.createQueryBuilder(I_M_MatchPO.class)
.addEqualsFilter(I_M_MatchPO.COLUMN_C_OrderLine_ID, orderLineId)
.orderBy(I_M_MatchPO.COLUMN_C_OrderLine_ID)
.create()
.listImmutable(I_M_MatchPO.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\MatchPODAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Command addArea(final Area area)
{
super.addArea(area);
if (_area == null)
{
_area = area;
}
else
{
throw new IllegalArgumentException("Adding more than one area is not allowed");
}
return this;
}
private Area getArea()
{
Check.assumeNotNull(_area, "area not null");
return _area;
}
@Override
public Size applyAt(final CellRef cellRef, final Context context)
{
//
// Process area
final Area area = getArea();
final Size size = area.applyAt(cellRef, context);
//
// If given condition is evaluated as true, hide given columns
if (isConditionTrue(context))
{
logger.debug("Hiding column of {} because condition '{}' was evaluated as true", cellRef, condition);
hideColumn(cellRef);
}
else
{
logger.debug("Skip hiding column of {} because condition '{}' was evaluated as false", cellRef, condition);
}
//
return size;
}
private void hideColumn(final CellRef cellRef)
{
final Transformer transformer = getTransformer();
if (transformer instanceof PoiTransformer)
{
final PoiTransformer poiTransformer = (PoiTransformer)transformer;
final Workbook poiWorkbook = poiTransformer.getWorkbook();
if (poiWorkbook == null)
{
logger.warn("Cannot hide column of {} because there is no workbook found", cellRef);
return;
|
}
final String sheetName = cellRef.getSheetName();
final Sheet poiSheet = poiWorkbook.getSheet(sheetName);
if (poiSheet == null)
{
logger.warn("Cannot hide column of {} because there is no sheet found", cellRef);
return;
}
final AreaRef areaRef = getArea().getAreaRef();
final CellRef areaFirstCell = areaRef.getFirstCellRef();
final CellRef areaLastCell = areaRef.getLastCellRef();
final int firstColumn = Math.min(areaFirstCell.getCol(), areaLastCell.getCol());
final int lastColumn = Math.max(areaFirstCell.getCol(), areaLastCell.getCol());
for (int col = firstColumn; col <= lastColumn; col++)
{
poiSheet.setColumnHidden(col, true);
// poiSheet.setColumnWidth(cellRef.getCol(), 0);
logger.debug("Column of {} was hidden", cellRef);
}
}
else
{
logger.warn("Cannot hide column of {} because transformer {} is not supported", transformer);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\HideColumnIfCommand.java
| 2
|
请完成以下Java代码
|
public class ApiResponse implements Serializable {
private static final long serialVersionUID = 8993485788201922830L;
/**
* 状态码
*/
private Integer code;
/**
* 返回内容
*/
private String message;
/**
* 返回数据
*/
private Object data;
/**
* 无参构造函数
*/
private ApiResponse() {
}
/**
* 全参构造函数
*
* @param code 状态码
* @param message 返回内容
* @param data 返回数据
*/
private ApiResponse(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 构造一个自定义的API返回
*
* @param code 状态码
* @param message 返回内容
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse of(Integer code, String message, Object data) {
return new ApiResponse(code, message, data);
}
/**
* 构造一个成功且不带数据的API返回
*
* @return ApiResponse
*/
public static ApiResponse ofSuccess() {
return ofSuccess(null);
}
/**
* 构造一个成功且带数据的API返回
*
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse ofSuccess(Object data) {
return ofStatus(Status.SUCCESS, data);
}
/**
|
* 构造一个成功且自定义消息的API返回
*
* @param message 返回内容
* @return ApiResponse
*/
public static ApiResponse ofMessage(String message) {
return of(Status.SUCCESS.getCode(), message, null);
}
/**
* 构造一个有状态的API返回
*
* @param status 状态 {@link Status}
* @return ApiResponse
*/
public static ApiResponse ofStatus(Status status) {
return ofStatus(status, null);
}
/**
* 构造一个有状态且带数据的API返回
*
* @param status 状态 {@link IStatus}
* @param data 返回数据
* @return ApiResponse
*/
public static ApiResponse ofStatus(IStatus status, Object data) {
return of(status.getCode(), status.getMessage(), data);
}
/**
* 构造一个异常的API返回
*
* @param t 异常
* @param <T> {@link BaseException} 的子类
* @return ApiResponse
*/
public static <T extends BaseException> ApiResponse ofException(T t) {
return of(t.getCode(), t.getMessage(), t.getData());
}
}
|
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\common\ApiResponse.java
| 1
|
请完成以下Java代码
|
class RabbitDockerComposeConnectionDetailsFactory
extends DockerComposeConnectionDetailsFactory<RabbitConnectionDetails> {
private static final int RABBITMQ_PORT = 5672;
protected RabbitDockerComposeConnectionDetailsFactory() {
super("rabbitmq");
}
@Override
protected RabbitConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new RabbitDockerComposeConnectionDetails(source.getRunningService());
}
/**
* {@link RabbitConnectionDetails} backed by a {@code rabbitmq}
* {@link RunningService}.
*/
static class RabbitDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements RabbitConnectionDetails {
private final RabbitEnvironment environment;
private final List<Address> addresses;
protected RabbitDockerComposeConnectionDetails(RunningService service) {
super(service);
this.environment = new RabbitEnvironment(service.env());
this.addresses = List.of(new Address(service.host(), service.ports().get(RABBITMQ_PORT)));
}
|
@Override
public @Nullable String getUsername() {
return this.environment.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.environment.getPassword();
}
@Override
public String getVirtualHost() {
return "/";
}
@Override
public List<Address> getAddresses() {
return this.addresses;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\docker\compose\RabbitDockerComposeConnectionDetailsFactory.java
| 1
|
请完成以下Java代码
|
public X12DE355 getX12DE355ById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return X12DE355.ofCode(uom.getX12DE355());
}
@Override
public @NonNull I_C_UOM getByX12DE355(@NonNull final X12DE355 x12de355)
{
return getByX12DE355IfExists(x12de355)
.orElseThrow(() -> new AdempiereException("No UOM found for X12DE355=" + x12de355));
}
@Override
public Optional<I_C_UOM> getByX12DE355IfExists(@NonNull final X12DE355 x12de355)
{
return getUomIdByX12DE355IfExists(x12de355)
.map(this::getById);
}
@Override
public I_C_UOM getEachUOM()
{
return getByX12DE355(X12DE355.EACH);
}
@Override
public TemporalUnit getTemporalUnitByUomId(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return UOMUtil.toTemporalUnit(uom);
}
@Override
public I_C_UOM getByTemporalUnit(@NonNull final TemporalUnit temporalUnit)
{
final UomId uomId = getUomIdByTemporalUnit(temporalUnit);
return getById(uomId);
}
@Override
public UomId getUomIdByTemporalUnit(@NonNull final TemporalUnit temporalUnit)
{
final X12DE355 x12de355 = X12DE355.ofTemporalUnit(temporalUnit);
try
{
return getUomIdByX12DE355(x12de355);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("temporalUnit", temporalUnit)
.setParameter("x12de355", x12de355)
.setParameter("Suggestion", "Create an UOM for that X12DE355 code or activate it if already exists.")
.appendParametersToMessage();
}
}
@Override
public UOMPrecision getStandardPrecision(final UomId uomId)
{
if (uomId == null)
|
{
// NOTE: if there is no UOM specified, we assume UOM is Each => precision=0
return UOMPrecision.ZERO;
}
final I_C_UOM uom = getById(uomId);
return UOMPrecision.ofInt(uom.getStdPrecision());
}
@Override
public boolean isUOMForTUs(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return isUOMForTUs(uom);
}
public static boolean isUOMForTUs(@NonNull final I_C_UOM uom)
{
final X12DE355 x12de355 = X12DE355.ofCode(uom.getX12DE355());
return X12DE355.COLI.equals(x12de355) || X12DE355.TU.equals(x12de355);
}
@Override
public @NonNull UOMType getUOMTypeById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return UOMType.ofNullableCodeOrOther(uom.getUOMType());
}
@Override
public @NonNull Optional<I_C_UOM> getBySymbol(@NonNull final String uomSymbol)
{
return Optional.ofNullable(queryBL.createQueryBuilder(I_C_UOM.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_UOM.COLUMNNAME_UOMSymbol, uomSymbol)
.create()
.firstOnlyOrNull(I_C_UOM.class));
}
@Override
public ITranslatableString getUOMSymbolById(@NonNull final UomId uomId)
{
final I_C_UOM uom = getById(uomId);
return InterfaceWrapperHelper.getModelTranslationMap(uom).getColumnTrl(I_C_UOM.COLUMNNAME_UOMSymbol, uom.getUOMSymbol());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMDAO.java
| 1
|
请完成以下Java代码
|
protected Message createMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
try {
if (this.contentType != null) {
messageProperties.setContentType(this.contentType);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult(bos);
this.marshaller.marshal(object, streamResult);
return new Message(bos.toByteArray(), messageProperties);
}
catch (XmlMappingException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
catch (IOException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex);
}
}
/**
|
* Unmarshals the given {@link Message} into an object.
*/
@Override
public Object fromMessage(Message message) throws MessageConversionException {
try {
ByteArrayInputStream bis = new ByteArrayInputStream(message.getBody());
StreamSource source = new StreamSource(bis);
return this.unmarshaller.unmarshal(source);
}
catch (IOException ex) {
throw new MessageConversionException("Could not access message content: " + message, ex);
}
catch (XmlMappingException ex) {
throw new MessageConversionException("Could not unmarshal message: " + message, ex);
}
}
}
|
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\MarshallingMessageConverter.java
| 1
|
请完成以下Java代码
|
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Discount Amount.
@param DiscountAmt
Calculated amount of discount
*/
@Override
public void setDiscountAmt (java.math.BigDecimal DiscountAmt)
{
set_Value (COLUMNNAME_DiscountAmt, DiscountAmt);
}
/** Get Discount Amount.
@return Calculated amount of discount
*/
@Override
public java.math.BigDecimal getDiscountAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DiscountAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Generated.
@param IsGenerated
This Line is generated
*/
@Override
public void setIsGenerated (boolean IsGenerated)
{
set_ValueNoCheck (COLUMNNAME_IsGenerated, Boolean.valueOf(IsGenerated));
}
/** Get Generated.
@return This Line is generated
*/
@Override
public boolean isGenerated ()
{
Object oo = get_Value(COLUMNNAME_IsGenerated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
|
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Write-off Amount.
@param WriteOffAmt
Amount to write-off
*/
@Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Write-off Amount.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
| 1
|
请完成以下Java代码
|
public void setAD_InfoWindow_ID (int AD_InfoWindow_ID)
{
if (AD_InfoWindow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_InfoWindow_ID, Integer.valueOf(AD_InfoWindow_ID));
}
/** Get Info-Fenster.
@return Info and search/select Window
*/
@Override
public int getAD_InfoWindow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
|
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sql FROM.
@param FromClause
SQL FROM clause
*/
@Override
public void setFromClause (java.lang.String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
@Override
public java.lang.String getFromClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_FromClause);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow_From.java
| 1
|
请完成以下Java代码
|
public void validate(Object target, Errors errors, Object... validationHints) {
User user = (User) target;
if (validationHints.length > 0) {
if (validationHints[0] == "create") {
if (StringUtils.isEmpty(user.getName())) {
errors.rejectValue("name", "name.required","Name cannot be empty");
}
if (StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("email", "email.required" , "Invalid email format");
}
if (user.getAge() < 18 || user.getAge() > 65) {
errors.rejectValue("age", "user.age.outOfRange", new Object[]{18, 65}, "Age must be between 18 and 65");
}
} else if (validationHints[0] == "update") {
// Perform update-specific validation
|
if (StringUtils.isEmpty(user.getName()) && StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("name", "name.or.email.required", "Name or email cannot be empty");
}
}
} else {
// Perform default validation
if (StringUtils.isEmpty(user.getName())) {
errors.rejectValue("name", "name.required");
}
if (StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("email", "email.required");
}
}
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\springvalidator\UserValidator.java
| 1
|
请完成以下Java代码
|
public void setExportXML (java.lang.String ExportXML)
{
set_Value (COLUMNNAME_ExportXML, ExportXML);
}
/** Get Export to XML.
@return Export this record to XML
*/
@Override
public java.lang.String getExportXML ()
{
return (java.lang.String)get_Value(COLUMNNAME_ExportXML);
}
/** Set Defer Constraints.
@param IsDeferredConstraints Defer Constraints */
@Override
public void setIsDeferredConstraints (boolean IsDeferredConstraints)
{
set_Value (COLUMNNAME_IsDeferredConstraints, Boolean.valueOf(IsDeferredConstraints));
}
/** Get Defer Constraints.
@return Defer Constraints */
@Override
public boolean isDeferredConstraints ()
{
Object oo = get_Value(COLUMNNAME_IsDeferredConstraints);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Release No.
@param ReleaseNo
Internal Release Number
*/
@Override
public void setReleaseNo (java.lang.String ReleaseNo)
{
set_Value (COLUMNNAME_ReleaseNo, ReleaseNo);
}
/** Get Release No.
@return Internal Release Number
*/
@Override
public java.lang.String getReleaseNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_ReleaseNo);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
@Override
public void setSeqNo (int SeqNo)
{
|
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* StatusCode AD_Reference_ID=53311
* Reference name: AD_Migration Status
*/
public static final int STATUSCODE_AD_Reference_ID=53311;
/** Applied = A */
public static final String STATUSCODE_Applied = "A";
/** Unapplied = U */
public static final String STATUSCODE_Unapplied = "U";
/** Failed = F */
public static final String STATUSCODE_Failed = "F";
/** Partially applied = P */
public static final String STATUSCODE_PartiallyApplied = "P";
/** Set Status Code.
@param StatusCode Status Code */
@Override
public void setStatusCode (java.lang.String StatusCode)
{
set_Value (COLUMNNAME_StatusCode, StatusCode);
}
/** Get Status Code.
@return Status Code */
@Override
public java.lang.String getStatusCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_StatusCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_Migration.java
| 1
|
请完成以下Java代码
|
public PageData<Rpc> findAllByDeviceId(TenantId tenantId, DeviceId deviceId, PageLink pageLink) {
return DaoUtil.toPageData(rpcRepository.findAllByTenantIdAndDeviceId(tenantId.getId(), deviceId.getId(), DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<Rpc> findAllByDeviceIdAndStatus(TenantId tenantId, DeviceId deviceId, RpcStatus rpcStatus, PageLink pageLink) {
return DaoUtil.toPageData(rpcRepository.findAllByTenantIdAndDeviceIdAndStatus(tenantId.getId(), deviceId.getId(), rpcStatus, DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<Rpc> findAllRpcByTenantId(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(rpcRepository.findAllByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink)));
}
@Transactional
|
@Override
public int deleteOutdatedRpcByTenantId(TenantId tenantId, Long expirationTime) {
return rpcRepository.deleteOutdatedRpcByTenantId(tenantId.getId(), expirationTime);
}
@Override
public PageData<Rpc> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findAllRpcByTenantId(tenantId, pageLink);
}
@Override
public EntityType getEntityType() {
return EntityType.RPC;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\rpc\JpaRpcDao.java
| 1
|
请完成以下Java代码
|
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
|
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Category.
@param R_Category_ID
Request Category
*/
public void setR_Category_ID (int R_Category_ID)
{
if (R_Category_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Category_ID, Integer.valueOf(R_Category_ID));
}
/** Get Category.
@return Request Category
*/
public int getR_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_Category.java
| 1
|
请完成以下Java代码
|
public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
String stripped = StringUtils.stripStart(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) {
String stripped = StringUtils.stripEnd(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) {
String stripped = CharMatcher.is('0')
.trimLeadingFrom(s);
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) {
String stripped = CharMatcher.is('0')
.trimTrailingFrom(s);
|
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeLeadingZeroesWithRegex(String s) {
return s.replaceAll("^0+(?!$)", "");
}
public static String removeTrailingZeroesWithRegex(String s) {
return s.replaceAll("(?!^)0+$", "");
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\removeleadingtrailingchar\RemoveLeadingAndTrailingZeroes.java
| 1
|
请完成以下Java代码
|
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Referenz.
@param Reference
Reference for this record
*/
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Reference for this record
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set View ID.
@param ViewId View ID */
@Override
public void setViewId (java.lang.String ViewId)
{
set_Value (COLUMNNAME_ViewId, ViewId);
}
|
/** Get View ID.
@return View ID */
@Override
public java.lang.String getViewId ()
{
return (java.lang.String)get_Value(COLUMNNAME_ViewId);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
/**
* NotificationSeverity AD_Reference_ID=541947
* Reference name: NotificationSeverity
*/
public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947;
/** Notice = Notice */
public static final String NOTIFICATIONSEVERITY_Notice = "Notice";
/** Warning = Warning */
public static final String NOTIFICATIONSEVERITY_Warning = "Warning";
/** Error = Error */
public static final String NOTIFICATIONSEVERITY_Error = "Error";
@Override
public void setNotificationSeverity (final java.lang.String NotificationSeverity)
{
set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity);
}
@Override
public java.lang.String getNotificationSeverity()
{
return get_ValueAsString(COLUMNNAME_NotificationSeverity);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<Book> findById(@PathVariable Long id) {
return bookService.findById(id);
}
// create a book
@ResponseStatus(HttpStatus.CREATED) // 201
@PostMapping
public Book create(@RequestBody Book book) {
return bookService.save(book);
}
// update a book
@PutMapping
public Book update(@RequestBody Book book) {
return bookService.save(book);
}
// delete a book
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
@DeleteMapping("/{id}")
|
public void deleteById(@PathVariable Long id) {
bookService.deleteById(id);
}
@GetMapping("/find/title/{title}")
public List<Book> findByTitle(@PathVariable String title) {
return bookService.findByTitle(title);
}
@GetMapping("/find/date-after/{date}")
public List<Book> findByPublishedDateAfter(
@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
return bookService.findByPublishedDateAfter(date);
}
}
|
repos\spring-boot-master\spring-data-jpa-postgresql\src\main\java\com\mkyong\controller\BookController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getEntryCriterionId() {
return entryCriterionId;
}
public void setEntryCriterionId(String entryCriterionId) {
this.entryCriterionId = entryCriterionId;
}
public String getExitCriterionId() {
return exitCriterionId;
}
public void setExitCriterionId(String exitCriterionId) {
this.exitCriterionId = exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getCompletedBy() {
return completedBy;
}
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
public String getExtraValue() {
return extraValue;
}
|
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java
| 2
|
请完成以下Java代码
|
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getAttendCount() {
return attendCount;
}
public void setAttendCount(Integer attendCount) {
this.attendCount = attendCount;
}
public Integer getAttentionCount() {
return attentionCount;
}
public void setAttentionCount(Integer attentionCount) {
this.attentionCount = attentionCount;
}
public Integer getReadCount() {
return readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
public String getAwardName() {
return awardName;
}
public void setAwardName(String awardName) {
this.awardName = awardName;
}
public String getAttendType() {
return attendType;
}
public void setAttendType(String attendType) {
this.attendType = attendType;
}
|
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@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(", categoryId=").append(categoryId);
sb.append(", name=").append(name);
sb.append(", createTime=").append(createTime);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", attendCount=").append(attendCount);
sb.append(", attentionCount=").append(attentionCount);
sb.append(", readCount=").append(readCount);
sb.append(", awardName=").append(awardName);
sb.append(", attendType=").append(attendType);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopic.java
| 1
|
请完成以下Java代码
|
public static JsonMetasfreshId ofOrNull(@Nullable final Integer value)
{
if (isEmpty(value))
{
return null;
}
return new JsonMetasfreshId(value);
}
private static boolean isEmpty(@Nullable final Integer value)
{
return value == null || value < 0;
}
private JsonMetasfreshId(@NonNull final Integer value)
{
if (value < 0)
{
throw new RuntimeException("Given value=" + value + " needs to be >=0");
}
this.value = value;
}
@JsonValue
public int getValue()
{
return value;
}
public static boolean equals(@Nullable final JsonMetasfreshId id1, @Nullable final JsonMetasfreshId id2)
{
return Objects.equals(id1, id2);
}
@Nullable
public static Integer toValue(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return null;
}
return externalId.getValue();
}
public static int toValueInt(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return -1;
}
return externalId.getValue();
}
public static String toValueStr(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
|
{
return "-1";
}
return String.valueOf(externalId.getValue());
}
@NonNull
public static Optional<Integer> toValueOptional(@Nullable final JsonMetasfreshId externalId)
{
return Optional.ofNullable(toValue(externalId));
}
@Nullable
public static <T> T mapToOrNull(@Nullable final JsonMetasfreshId externalId, @NonNull final Function<Integer, T> mapper)
{
return toValueOptional(externalId).map(mapper).orElse(null);
}
@Nullable
public static String toValueStrOrNull(@Nullable final JsonMetasfreshId externalId)
{
if (externalId == null)
{
return null;
}
return String.valueOf(externalId.getValue());
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\common\JsonMetasfreshId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DesadvEnqueuer
{
private final IWorkPackageQueueFactory workPackageQueueFactory = Services.get(IWorkPackageQueueFactory.class);
private final ITrxItemProcessorExecutorService trxItemProcessorExecutorService = Services.get(ITrxItemProcessorExecutorService.class);
@NonNull
public EnqueueDesadvResult enqueue(@NonNull final EnqueueDesadvRequest enqueueDesadvRequest)
{
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(enqueueDesadvRequest.getCtx(), EDIWorkpackageProcessor.class);
final ImmutableList.Builder<I_EDI_Desadv> skippedDesadvCollector = ImmutableList.builder();
trxItemProcessorExecutorService
.<I_EDI_Desadv, Void>createExecutor()
.setContext(enqueueDesadvRequest.getCtx(), ITrx.TRXNAME_None)
.setExceptionHandler(FailTrxItemExceptionHandler.instance)
.setProcessor(new TrxItemProcessorAdapter<I_EDI_Desadv, Void>()
{
@Override
public void process(final I_EDI_Desadv desadv)
{
// make sure the desadvs that don't meet the sum percentage requirement won't get enqueued
final BigDecimal currentSumPercentage = desadv.getFulfillmentPercent();
if (currentSumPercentage.compareTo(desadv.getFulfillmentPercentMin()) < 0)
{
skippedDesadvCollector.add(desadv);
}
else
{
// note: in here, the desadv has the item processor's trxName (as of this task)
enqueueDesadv(enqueueDesadvRequest.getPInstanceId(), queue, desadv);
}
}
})
.process(enqueueDesadvRequest.getDesadvIterator());
|
return EnqueueDesadvResult.builder()
.skippedDesadvList(skippedDesadvCollector.build())
.build();
}
private void enqueueDesadv(
@Nullable final PInstanceId pInstanceId,
@NonNull final IWorkPackageQueue queue,
@NonNull final I_EDI_Desadv desadv)
{
final String trxName = InterfaceWrapperHelper.getTrxName(desadv);
queue
.newWorkPackage()
.setAD_PInstance_ID(pInstanceId)
.bindToTrxName(trxName)
.addElement(desadv)
.buildAndEnqueue();
desadv.setEDI_ExportStatus(X_EDI_Desadv.EDI_EXPORTSTATUS_Enqueued);
InterfaceWrapperHelper.save(desadv);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\export\enqueue\DesadvEnqueuer.java
| 2
|
请完成以下Java代码
|
public class Keyboard {
private String style;
private String layout;
public Keyboard(){
super();
}
public Keyboard(String style, String layout) {
this.style = style;
this.layout = layout;
}
public String getStyle() {
return style;
}
|
public void setStyle(String style) {
this.style = style;
}
public String getLayout() {
return layout;
}
public void setLayout(String layout) {
this.layout = layout;
}
@Override
public String toString() {
return "Keyboard{" + "style='" + style + '\'' + ", layout='" + layout + '\'' + '}';
}
}
|
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\jsonmerge\Keyboard.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.