instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Set<String> getDependsOnFieldNames()
{
return dependsOnFieldNames;
}
@Override
public Optional<String> getLookupTableName()
{
return lookupTableName;
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final LookupValuesPage page = lookupValues.apply(evalCtx);
return page.getValues().getById(evalCtx.getSingleIdToFilterAsObject());
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
return lookupValues.apply(evalCtx);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
//
//
//
//
//
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static class Builder
{
private LookupSource lookupSourceType = LookupSource.list;
private boolean numericKey;
private Function<LookupDataSourceContext, LookupValuesPage> lookupValues;
private Set<String> dependsOnFieldNames; | private Optional<String> lookupTableName = Optional.empty();
private Builder()
{
}
public ListLookupDescriptor build()
{
return new ListLookupDescriptor(this);
}
public Builder setLookupSourceType(@NonNull final LookupSource lookupSourceType)
{
this.lookupSourceType = lookupSourceType;
return this;
}
public Builder setLookupValues(final boolean numericKey, final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
this.numericKey = numericKey;
this.lookupValues = lookupValues;
return this;
}
public Builder setIntegerLookupValues(final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
setLookupValues(true, lookupValues);
return this;
}
public Builder setDependsOnFieldNames(final String[] dependsOnFieldNames)
{
this.dependsOnFieldNames = ImmutableSet.copyOf(dependsOnFieldNames);
return this;
}
public Builder setLookupTableName(final String lookupTableName)
{
this.lookupTableName = Check.isEmpty(lookupTableName, true) ? Optional.empty() : Optional.of(lookupTableName);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\ListLookupDescriptor.java | 1 |
请完成以下Java代码 | public void preFlush(Iterator entities) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public void postFlush(Iterator entities) throws CallbackException {
// TODO Auto-generated method stub
}
@Override
public Boolean isTransient(Object entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
// TODO Auto-generated method stub
return null;
}
@Override
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getEntityName(Object object) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override | public Object getEntity(String entityName, Serializable id) throws CallbackException {
// TODO Auto-generated method stub
return null;
}
@Override
public void afterTransactionBegin(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public void beforeTransactionCompletion(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public void afterTransactionCompletion(Transaction tx) {
// TODO Auto-generated method stub
}
@Override
public String onPrepareStatement(String sql) {
// TODO Auto-generated method stub
return null;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\CustomInterceptorImpl.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArticleView that = (ArticleView) o;
return slug.equals(that.slug) && title.equals(that.title) && description.equals(that.description) && body.equals(that.body) && tagList.equals(that.tagList) && favorited.equals(that.favorited) && favoritesCount.equals(that.favoritesCount) && author.equals(that.author);
}
@Override
public int hashCode() {
return Objects.hash(slug, title, description, body, tagList, favorited, favoritesCount, author);
}
Boolean favorited;
Integer favoritesCount;
ProfileView author;
public static ArticleView toArticleView(Article article, ProfileView author, boolean favorited) {
return new ArticleView()
.setSlug(article.getSlug())
.setTitle(article.getTitle())
.setDescription(article.getDescription())
.setBody(article.getBody())
.setTagList(article.getTags())
.setCreatedAt(article.getCreatedAt())
.setUpdatedAt(article.getUpdatedAt())
.setFavorited(favorited) | .setFavoritesCount(article.getFavoritesCount())
.setAuthor(author);
}
public static ArticleView ofOwnArticle(Article article, User articleOwner) {
return toArticleViewForViewer(article, ProfileView.toOwnProfile(articleOwner), articleOwner);
}
public static ArticleView toArticleViewForViewer(Article article, ProfileView author, User user) {
return toArticleView(article, author, user.isFavoriteArticle(article));
}
public static ArticleView toUnfavoredArticleView(Article article, ProfileView author) {
return toArticleView(article, author, false);
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\article\dto\ArticleView.java | 1 |
请完成以下Java代码 | public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.rfq.model.I_C_RfQ_Topic getC_RfQ_Topic() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_RfQ_Topic_ID, de.metas.rfq.model.I_C_RfQ_Topic.class);
}
@Override
public void setC_RfQ_Topic(de.metas.rfq.model.I_C_RfQ_Topic C_RfQ_Topic)
{
set_ValueFromPO(COLUMNNAME_C_RfQ_Topic_ID, de.metas.rfq.model.I_C_RfQ_Topic.class, C_RfQ_Topic);
}
/** Set Ausschreibungs-Thema.
@param C_RfQ_Topic_ID
Topic for Request for Quotations
*/
@Override
public void setC_RfQ_Topic_ID (int C_RfQ_Topic_ID)
{
if (C_RfQ_Topic_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQ_Topic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQ_Topic_ID, Integer.valueOf(C_RfQ_Topic_ID));
}
/** Get Ausschreibungs-Thema.
@return Topic for Request for Quotations
*/
@Override
public int getC_RfQ_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set RfQ Subscriber.
@param C_RfQ_TopicSubscriber_ID
Request for Quotation Topic Subscriber
*/
@Override
public void setC_RfQ_TopicSubscriber_ID (int C_RfQ_TopicSubscriber_ID)
{
if (C_RfQ_TopicSubscriber_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQ_TopicSubscriber_ID, Integer.valueOf(C_RfQ_TopicSubscriber_ID));
} | /** Get RfQ Subscriber.
@return Request for Quotation Topic Subscriber
*/
@Override
public int getC_RfQ_TopicSubscriber_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQ_TopicSubscriber_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum der Abmeldung.
@param OptOutDate
Date the contact opted out
*/
@Override
public void setOptOutDate (java.sql.Timestamp OptOutDate)
{
set_Value (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Datum der Abmeldung.
@return Date the contact opted out
*/
@Override
public java.sql.Timestamp getOptOutDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
/** Set Anmeldung.
@param SubscribeDate
Date the contact actively subscribed
*/
@Override
public void setSubscribeDate (java.sql.Timestamp SubscribeDate)
{
set_Value (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Anmeldung.
@return Date the contact actively subscribed
*/
@Override
public java.sql.Timestamp getSubscribeDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java | 1 |
请完成以下Java代码 | public void setGrossRAmt (BigDecimal GrossRAmt)
{
set_Value (COLUMNNAME_GrossRAmt, GrossRAmt);
}
/** Get Gross Amount.
@return Gross Remuneration Amount
*/
public BigDecimal getGrossRAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrossRAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Gross Cost.
@param GrossRCost
Gross Remuneration Costs
*/
public void setGrossRCost (BigDecimal GrossRCost)
{
set_Value (COLUMNNAME_GrossRCost, GrossRCost);
}
/** Get Gross Cost.
@return Gross Remuneration Costs
*/
public BigDecimal getGrossRCost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrossRCost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Overtime Amount.
@param OvertimeAmt
Hourly Overtime Rate
*/
public void setOvertimeAmt (BigDecimal OvertimeAmt)
{
set_Value (COLUMNNAME_OvertimeAmt, OvertimeAmt);
}
/** Get Overtime Amount.
@return Hourly Overtime Rate
*/
public BigDecimal getOvertimeAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Overtime Cost.
@param OvertimeCost
Hourly Overtime Cost
*/
public void setOvertimeCost (BigDecimal OvertimeCost)
{
set_Value (COLUMNNAME_OvertimeCost, OvertimeCost);
}
/** Get Overtime Cost.
@return Hourly Overtime Cost
*/
public BigDecimal getOvertimeCost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost);
if (bd == null)
return Env.ZERO; | return bd;
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UserRemuneration.java | 1 |
请完成以下Java代码 | public class RateLimitProcessingFilter extends OncePerRequestFilter {
private final ThingsboardErrorResponseHandler errorResponseHandler;
private final RateLimitService rateLimitService;
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
SecurityUser user = getCurrentUser();
if (user != null && !user.isSystemAdmin()) {
try {
if (!rateLimitService.checkRateLimit(LimitedApi.REST_REQUESTS_PER_TENANT, user.getTenantId())) {
rateLimitExceeded(EntityType.TENANT, response);
return;
}
} catch (TenantProfileNotFoundException e) {
log.debug("[{}] Failed to lookup tenant profile", user.getTenantId());
errorResponseHandler.handle(new BadCredentialsException("Failed to lookup tenant profile"), response);
return;
}
if (user.isCustomerUser()) {
if (!rateLimitService.checkRateLimit(LimitedApi.REST_REQUESTS_PER_CUSTOMER, user.getTenantId(), user.getCustomerId())) {
rateLimitExceeded(EntityType.CUSTOMER, response);
return;
}
}
}
chain.doFilter(request, response);
}
@Override | protected boolean shouldNotFilterAsyncDispatch() {
return false;
}
@Override
protected boolean shouldNotFilterErrorDispatch() {
return false;
}
private void rateLimitExceeded(EntityType type, HttpServletResponse response) {
errorResponseHandler.handle(new TbRateLimitsException(type), response);
}
protected SecurityUser getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof SecurityUser) {
return (SecurityUser) authentication.getPrincipal();
} else {
return null;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\config\RateLimitProcessingFilter.java | 1 |
请完成以下Java代码 | public void setC_PaymentTerm_Break_ID (final int C_PaymentTerm_Break_ID)
{
if (C_PaymentTerm_Break_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PaymentTerm_Break_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PaymentTerm_Break_ID, C_PaymentTerm_Break_ID);
}
@Override
public int getC_PaymentTerm_Break_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_Break_ID);
}
@Override
public void setC_PaymentTerm_ID (final int C_PaymentTerm_ID)
{
if (C_PaymentTerm_ID < 1)
set_Value (COLUMNNAME_C_PaymentTerm_ID, null);
else
set_Value (COLUMNNAME_C_PaymentTerm_ID, C_PaymentTerm_ID);
}
@Override
public int getC_PaymentTerm_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setOffsetDays (final int OffsetDays)
{
set_Value (COLUMNNAME_OffsetDays, OffsetDays);
}
@Override
public int getOffsetDays()
{
return get_ValueAsInt(COLUMNNAME_OffsetDays);
}
@Override
public void setPercent (final int Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public int getPercent()
{
return get_ValueAsInt(COLUMNNAME_Percent);
}
/**
* ReferenceDateType AD_Reference_ID=541989
* Reference name: ReferenceDateType
*/ | public static final int REFERENCEDATETYPE_AD_Reference_ID=541989;
/** InvoiceDate = IV */
public static final String REFERENCEDATETYPE_InvoiceDate = "IV";
/** BLDate = BL */
public static final String REFERENCEDATETYPE_BLDate = "BL";
/** OrderDate = OD */
public static final String REFERENCEDATETYPE_OrderDate = "OD";
/** LCDate = LC */
public static final String REFERENCEDATETYPE_LCDate = "LC";
/** ETADate = ET */
public static final String REFERENCEDATETYPE_ETADate = "ET";
@Override
public void setReferenceDateType (final java.lang.String ReferenceDateType)
{
set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType);
}
@Override
public java.lang.String getReferenceDateType()
{
return get_ValueAsString(COLUMNNAME_ReferenceDateType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentTerm_Break.java | 1 |
请完成以下Java代码 | public int getM_Inventory_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Inventory_Candidate_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setProcessed (final boolean Processed) | {
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyToDispose (final BigDecimal QtyToDispose)
{
set_Value (COLUMNNAME_QtyToDispose, QtyToDispose);
}
@Override
public BigDecimal getQtyToDispose()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToDispose);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Inventory_Candidate.java | 1 |
请完成以下Java代码 | static <T, E extends Exception> Consumer<T> consumerWrapper(Consumer<T> consumer, Class<E> clazz) {
return i -> {
try {
consumer.accept(i);
} catch (Exception ex) {
try {
E exCast = clazz.cast(ex);
LOGGER.error("Exception occurred : {}", exCast.getMessage());
} catch (ClassCastException ccEx) {
throw ex;
}
}
};
}
public static <T> Consumer<T> throwingConsumerWrapper(ThrowingConsumer<T, Exception> throwingConsumer) {
return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
public static <T, E extends Exception> Consumer<T> handlingConsumerWrapper(ThrowingConsumer<T, E> throwingConsumer, Class<E> exceptionClass) { | return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
try {
E exCast = exceptionClass.cast(ex);
LOGGER.error("Exception occurred : {}", exCast.getMessage());
} catch (ClassCastException ccEx) {
throw new RuntimeException(ex);
}
}
};
}
} | repos\tutorials-master\core-java-modules\core-java-lambdas\src\main\java\com\baeldung\java8\lambda\exceptions\LambdaExceptionWrappers.java | 1 |
请完成以下Java代码 | protected void setLastTransactionState(TransactionState transactionState) {
this.lastTransactionState = transactionState;
}
private PersistenceSession getPersistenceProvider() {
return commandContext.getSession(PersistenceSession.class);
}
public void rollback() {
try {
try {
LOG.debugTransactionOperation("firing event rollback...");
fireTransactionEvent(TransactionState.ROLLINGBACK);
}
catch (Throwable exception) {
LOG.exceptionWhileFiringEvent(TransactionState.ROLLINGBACK, exception);
Context.getCommandInvocationContext().trySetThrowable(exception);
}
finally { | LOG.debugTransactionOperation("rolling back the persistence session...");
getPersistenceProvider().rollback();
}
}
catch (Throwable exception) {
LOG.exceptionWhileFiringEvent(TransactionState.ROLLINGBACK, exception);
Context.getCommandInvocationContext().trySetThrowable(exception);
}
finally {
LOG.debugFiringEventRolledBack();
fireTransactionEvent(TransactionState.ROLLED_BACK);
}
}
public boolean isTransactionActive() {
return !TransactionState.ROLLINGBACK.equals(lastTransactionState) && !TransactionState.ROLLED_BACK.equals(lastTransactionState);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\standalone\StandaloneTransactionContext.java | 1 |
请完成以下Java代码 | public List<HUConsolidationTarget> getAvailableTargets(@NonNull final HUConsolidationJob job)
{
return availableTargetsFinder.getAvailableTargets(job.getCustomerId());
}
public HUConsolidationJob setTarget(@NonNull final HUConsolidationJobId jobId, @Nullable final HUConsolidationTarget target, @NonNull UserId callerId)
{
return SetTargetCommand.builder()
.jobRepository(jobRepository)
//
.callerId(callerId)
.jobId(jobId)
.target(target)
//
.build().execute();
}
public HUConsolidationJob closeTarget(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId)
{
return jobRepository.updateById(jobId, job -> {
job.assertUserCanEdit(callerId);
return targetCloser.closeTarget(job);
});
}
public void printTargetLabel(@NonNull final HUConsolidationJobId jobId, @NotNull final UserId callerId)
{
final HUConsolidationJob job = jobRepository.getById(jobId);
final HUConsolidationTarget currentTarget = job.getCurrentTargetNotNull();
labelPrinter.printLabel(currentTarget);
}
public HUConsolidationJob consolidate(@NonNull final ConsolidateRequest request)
{
return ConsolidateCommand.builder() | .jobRepository(jobRepository)
.huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService)
.request(request)
.build()
.execute();
}
public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId)
{
return GetPickingSlotContentCommand.builder()
.jobRepository(jobRepository)
.huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService)
.jobId(jobId)
.pickingSlotId(pickingSlotId)
.build()
.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public I_C_LandedCost createLandedCost(String trxName)
{
throw new UnsupportedOperationException();
}
@Override
public I_C_InvoiceLine createInvoiceLine(String trxName)
{
throw new UnsupportedOperationException();
}
private List<I_C_AllocationLine> retrieveAllocationLines(final org.compiere.model.I_C_Invoice invoice)
{
Adempiere.assertUnitTestMode();
return db.getRecords(I_C_AllocationLine.class, pojo -> {
if (pojo == null)
{
return false;
}
if (pojo.getC_Invoice_ID() != invoice.getC_Invoice_ID())
{
return false;
}
return true;
});
}
private BigDecimal retrieveAllocatedAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor)
{
Adempiere.assertUnitTestMode();
final Properties ctx = InterfaceWrapperHelper.getCtx(invoice);
BigDecimal sum = BigDecimal.ZERO;
for (final I_C_AllocationLine line : retrieveAllocationLines(invoice))
{
final I_C_AllocationHdr ah = line.getC_AllocationHdr();
final BigDecimal lineAmt = amountAccessor.getValue(line);
if ((null != ah) && (ah.getC_Currency_ID() != invoice.getC_Currency_ID()))
{
final BigDecimal lineAmtConv = Services.get(ICurrencyBL.class).convert(
lineAmt, // Amt
CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID
CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID
ah.getDateTrx().toInstant(), // ConvDate
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()),
OrgId.ofRepoId(line.getAD_Org_ID()));
sum = sum.add(lineAmtConv);
} | else
{
sum = sum.add(lineAmt);
}
}
return sum;
}
public BigDecimal retrieveWriteOffAmt(final org.compiere.model.I_C_Invoice invoice)
{
Adempiere.assertUnitTestMode();
return retrieveAllocatedAmt(invoice, o -> {
final I_C_AllocationLine line = (I_C_AllocationLine)o;
return line.getWriteOffAmt();
});
}
@Override
public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\PlainInvoiceDAO.java | 2 |
请完成以下Java代码 | public void setPeriod_OpenHistory (final int Period_OpenHistory)
{
set_Value (COLUMNNAME_Period_OpenHistory, Period_OpenHistory);
}
@Override
public int getPeriod_OpenHistory()
{
return get_ValueAsInt(COLUMNNAME_Period_OpenHistory);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
/**
* TaxCorrectionType AD_Reference_ID=392
* Reference name: C_AcctSchema TaxCorrectionType
*/ | public static final int TAXCORRECTIONTYPE_AD_Reference_ID=392;
/** None = N */
public static final String TAXCORRECTIONTYPE_None = "N";
/** Write_OffOnly = W */
public static final String TAXCORRECTIONTYPE_Write_OffOnly = "W";
/** DiscountOnly = D */
public static final String TAXCORRECTIONTYPE_DiscountOnly = "D";
/** Write_OffAndDiscount = B */
public static final String TAXCORRECTIONTYPE_Write_OffAndDiscount = "B";
@Override
public void setTaxCorrectionType (final java.lang.String TaxCorrectionType)
{
set_Value (COLUMNNAME_TaxCorrectionType, TaxCorrectionType);
}
@Override
public java.lang.String getTaxCorrectionType()
{
return get_ValueAsString(COLUMNNAME_TaxCorrectionType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema.java | 1 |
请完成以下Java代码 | public Builder oidcUserInfoEndpoint(String oidcUserInfoEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_USER_INFO_ENDPOINT, oidcUserInfoEndpoint);
}
/**
* Sets the OpenID Connect 1.0 Logout endpoint.
* @param oidcLogoutEndpoint the OpenID Connect 1.0 Logout endpoint
* @return the {@link Builder} for further configuration
*/
public Builder oidcLogoutEndpoint(String oidcLogoutEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_LOGOUT_ENDPOINT, oidcLogoutEndpoint);
}
/**
* Builds the {@link AuthorizationServerSettings}.
* @return the {@link AuthorizationServerSettings} | */
@Override
public AuthorizationServerSettings build() {
AuthorizationServerSettings authorizationServerSettings = new AuthorizationServerSettings(getSettings());
if (authorizationServerSettings.getIssuer() != null
&& authorizationServerSettings.isMultipleIssuersAllowed()) {
throw new IllegalArgumentException("The issuer identifier (" + authorizationServerSettings.getIssuer()
+ ") cannot be set when isMultipleIssuersAllowed() is true.");
}
return authorizationServerSettings;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AuthorizationServerSettings.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected FailureAnalysis analyze(Throwable rootFailure, ConnectionFactoryBeanCreationException cause) {
return getFailureAnalysis(cause);
}
private FailureAnalysis getFailureAnalysis(ConnectionFactoryBeanCreationException cause) {
String description = getDescription(cause);
String action = getAction(cause);
return new FailureAnalysis(description, action, cause);
}
private String getDescription(ConnectionFactoryBeanCreationException cause) {
StringBuilder description = new StringBuilder();
description.append("Failed to configure a ConnectionFactory: ");
if (!StringUtils.hasText(cause.getUrl())) {
description.append("'url' attribute is not specified and ");
}
description.append(String.format("no embedded database could be configured.%n"));
description.append(String.format("%nReason: %s%n", cause.getMessage()));
return description.toString();
}
private String getAction(ConnectionFactoryBeanCreationException cause) {
StringBuilder action = new StringBuilder();
action.append(String.format("Consider the following:%n"));
if (EmbeddedDatabaseConnection.NONE == cause.getEmbeddedDatabaseConnection()) {
action.append(String.format("\tIf you want an embedded database (H2), please put it on the classpath.%n"));
}
else { | action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection()));
}
action
.append("\tIf you have database settings to be loaded from a particular "
+ "profile you may need to activate it")
.append(getActiveProfiles());
return action.toString();
}
private String getActiveProfiles() {
StringBuilder message = new StringBuilder();
String[] profiles = this.environment.getActiveProfiles();
if (ObjectUtils.isEmpty(profiles)) {
message.append(" (no profiles are currently active).");
}
else {
message.append(" (the profiles ");
message.append(StringUtils.arrayToCommaDelimitedString(profiles));
message.append(" are currently active).");
}
return message.toString();
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryBeanCreationFailureAnalyzer.java | 2 |
请完成以下Java代码 | public class MAlertProcessorLog extends X_AD_AlertProcessorLog
implements AdempiereProcessorLog
{
/**
*
*/
private static final long serialVersionUID = -6720267177398838915L;
/**
* Standard Constructor
* @param ctx context
* @param AD_AlertProcessorLog_ID id
* @param trxName transaction
*/
public MAlertProcessorLog (Properties ctx, int AD_AlertProcessorLog_ID, String trxName)
{
super (ctx, AD_AlertProcessorLog_ID, trxName);
} // MAlertProcessorLog
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MAlertProcessorLog (Properties ctx, ResultSet rs, String trxName)
{ | super(ctx, rs, trxName);
} // MAlertProcessorLog
/**
* Parent Constructor
* @param parent parent
* @param summary summary
*/
public MAlertProcessorLog (MAlertProcessor parent, String summary)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setAD_AlertProcessor_ID(parent.getAD_AlertProcessor_ID());
setSummary(summary);
} // MAlertProcessorLog
} // MAlertProcessorLog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertProcessorLog.java | 1 |
请完成以下Java代码 | public class TaskQueryVariableValue extends QueryVariableValue {
private static final long serialVersionUID = 1L;
protected boolean isProcessInstanceVariable;
/**
* <p>The parameters <code>isTaskVariable</code> and <code> isProcessInstanceVariable</code>
* have the following meaning:</p>
*
* <ul>
* <li>if <code>isTaskVariable == true</code>: only query after task variables</li>
* <li>if <code>isTaskVariable == false && isProcessInstanceVariable == true</code>:
* only query after process instance variables</li>
* <li>if <code>isTaskVariable == false && isProcessInstanceVariable == false</code>:
* only query after case instance variables</li> | * </ul>
*/
public TaskQueryVariableValue(String name, Object value, QueryOperator operator, boolean isTaskVariable, boolean isProcessInstanceVariable) {
this(name, value, operator, isTaskVariable, isProcessInstanceVariable, false, false);
}
public TaskQueryVariableValue(String name, Object value, QueryOperator operator, boolean isTaskVariable, boolean isProcessInstanceVariable, boolean variableNameIgnoreCase, boolean variableValueIgnoreCase) {
super(name, value, operator, isTaskVariable, variableNameIgnoreCase, variableValueIgnoreCase);
this.isProcessInstanceVariable = isProcessInstanceVariable;
}
public boolean isProcessInstanceVariable() {
return isProcessInstanceVariable;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskQueryVariableValue.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JobStatsProcessor {
private final JobService jobService;
private final TasksQueueConfig queueConfig;
private final QueueConsumerManager<TbProtoQueueMsg<JobStatsMsg>> jobStatsConsumer;
private final ExecutorService consumerExecutor;
public JobStatsProcessor(JobService jobService,
TasksQueueConfig queueConfig,
TbCoreQueueFactory queueFactory) {
this.jobService = jobService;
this.queueConfig = queueConfig;
this.consumerExecutor = Executors.newCachedThreadPool(ThingsBoardThreadFactory.forName("job-stats-consumer"));
this.jobStatsConsumer = QueueConsumerManager.<TbProtoQueueMsg<JobStatsMsg>>builder()
.name("job-stats")
.msgPackProcessor(this::processStats)
.pollInterval(queueConfig.getStatsPollInterval())
.consumerCreator(queueFactory::createJobStatsConsumer)
.consumerExecutor(consumerExecutor)
.build();
}
@AfterStartUp(order = AfterStartUp.REGULAR_SERVICE)
public void afterStartUp() {
jobStatsConsumer.subscribe();
jobStatsConsumer.launch();
}
@SneakyThrows
private void processStats(List<TbProtoQueueMsg<JobStatsMsg>> msgs, TbQueueConsumer<TbProtoQueueMsg<JobStatsMsg>> consumer) {
Map<JobId, JobStats> stats = new HashMap<>();
for (TbProtoQueueMsg<JobStatsMsg> msg : msgs) {
JobStatsMsg statsMsg = msg.getValue();
TenantId tenantId = TenantId.fromUUID(new UUID(statsMsg.getTenantIdMSB(), statsMsg.getTenantIdLSB()));
JobId jobId = new JobId(new UUID(statsMsg.getJobIdMSB(), statsMsg.getJobIdLSB()));
JobStats jobStats = stats.computeIfAbsent(jobId, __ -> new JobStats(tenantId, jobId)); | if (statsMsg.hasTaskResult()) {
TaskResult taskResult = JacksonUtil.fromString(statsMsg.getTaskResult().getValue(), TaskResult.class);
jobStats.getTaskResults().add(taskResult);
}
if (statsMsg.hasTotalTasksCount()) {
jobStats.setTotalTasksCount(statsMsg.getTotalTasksCount());
}
}
stats.forEach((jobId, jobStats) -> {
TenantId tenantId = jobStats.getTenantId();
try {
log.debug("[{}][{}] Processing job stats: {}", tenantId, jobId, stats);
jobService.processStats(tenantId, jobId, jobStats);
} catch (Exception e) {
log.error("[{}][{}] Failed to process job stats: {}", tenantId, jobId, jobStats, e);
}
});
consumer.commit();
Thread.sleep(queueConfig.getStatsProcessingInterval());
}
@PreDestroy
private void destroy() {
jobStatsConsumer.stop();
consumerExecutor.shutdownNow();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\job\JobStatsProcessor.java | 2 |
请完成以下Java代码 | private final OnRunnableFail getThreadInheritedOnRunnableFail(final OnRunnableFail onRunnableFailDefault)
{
final OnRunnableFail onRunnableFail = threadLocalOnRunnableFail.get();
return onRunnableFail == null ? onRunnableFailDefault : onRunnableFail;
}
@Override
public final boolean isDebugTrxCreateStacktrace()
{
return debugTrxCreateStacktrace;
}
@Override
public final void setDebugTrxCreateStacktrace(final boolean debugTrxCreateStacktrace)
{
this.debugTrxCreateStacktrace = debugTrxCreateStacktrace;
}
@Override
public final boolean isDebugTrxCloseStacktrace()
{
return debugTrxCloseStacktrace;
}
@Override
public final void setDebugTrxCloseStacktrace(final boolean debugTrxCloseStacktrace)
{
this.debugTrxCloseStacktrace = debugTrxCloseStacktrace;
}
@Override
public final void setDebugClosedTransactions(final boolean enabled)
{
trxName2trxLock.lock();
try
{
if (enabled)
{
if (debugClosedTransactionsList == null)
{
debugClosedTransactionsList = new ArrayList<>();
}
}
else
{
debugClosedTransactionsList = null;
}
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public final boolean isDebugClosedTransactions()
{
return debugClosedTransactionsList != null;
}
@Override
public final List<ITrx> getDebugClosedTransactions()
{
trxName2trxLock.lock();
try
{
if (debugClosedTransactionsList == null)
{ | return Collections.emptyList();
}
return new ArrayList<>(debugClosedTransactionsList);
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public void setDebugConnectionBackendId(boolean debugConnectionBackendId)
{
this.debugConnectionBackendId = debugConnectionBackendId;
}
@Override
public boolean isDebugConnectionBackendId()
{
return debugConnectionBackendId;
}
@Override
public String toString()
{
return "AbstractTrxManager [trxName2trx=" + trxName2trx + ", trxName2trxLock=" + trxName2trxLock + ", trxNameGenerator=" + trxNameGenerator + ", threadLocalTrx=" + threadLocalTrx + ", threadLocalOnRunnableFail=" + threadLocalOnRunnableFail + ", debugTrxCreateStacktrace=" + debugTrxCreateStacktrace + ", debugTrxCloseStacktrace=" + debugTrxCloseStacktrace + ", debugClosedTransactionsList="
+ debugClosedTransactionsList + ", debugConnectionBackendId=" + debugConnectionBackendId + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrxManager.java | 1 |
请完成以下Java代码 | private RelatedDocuments toRelatedDocuments(@NonNull final RelatedDocumentsCandidateGroup.RelatedDocumentsCandidateWithRecordsCount candidateWithRecordsCount)
{
final RelatedDocumentsCandidate candidate = candidateWithRecordsCount.getCandidate();
final int recordsCount = candidateWithRecordsCount.getRecordsCount();
final Duration recordsCountDuration = candidateWithRecordsCount.getRecordsCountDuration();
final TranslatableStringBuilder captionBuilder = TranslatableStrings.builder()
.append(candidate.getWindowCaption());
if (candidateWithRecordsCount.isAppendFilterByFieldCaption()
&& !TranslatableStrings.isBlank(candidate.getFilterByFieldCaption())
&& !Objects.equals(candidate.getWindowCaption(), candidate.getFilterByFieldCaption()))
{
captionBuilder.append(" / ").append(candidate.getFilterByFieldCaption());
}
final ITranslatableString caption = captionBuilder
.append(" (#").append(recordsCount).append(")")
.build();
final MQuery queryCopy = candidate.getQuerySupplier().getQuery().deepCopy();
queryCopy.setRecordCount(recordsCount, recordsCountDuration);
return RelatedDocuments.builder()
.id(candidate.getId())
.internalName(candidate.getInternalName()) | .targetWindow(candidate.getTargetWindow())
.priority(candidate.getPriority())
.caption(caption)
.filterByFieldCaption(candidate.getFilterByFieldCaption())
.query(queryCopy)
.build();
}
@Value
@Builder
private static class RelatedDocumentsCandidateWithRecordsCount
{
@Delegate
@NonNull RelatedDocumentsCandidate candidate;
int recordsCount;
Duration recordsCountDuration;
@With
boolean appendFilterByFieldCaption;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\RelatedDocumentsCandidateGroup.java | 1 |
请完成以下Java代码 | private CustomerInfo getCustomerInfoBlockEach(Long customerId) {
Customer customer = webClient.get()
.uri(uriBuilder -> uriBuilder.path(CustomerController.PATH_CUSTOMER)
.pathSegment(String.valueOf(customerId))
.build())
.retrieve()
.onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class)
.map(ApiGatewayException::new))
.bodyToMono(Customer.class)
.block();
Billing billing = webClient.get()
.uri(uriBuilder -> uriBuilder.path(BillingController.PATH_BILLING)
.pathSegment(String.valueOf(customerId))
.build())
.retrieve()
.onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class)
.map(ApiGatewayException::new))
.bodyToMono(Billing.class)
.block();
return new CustomerInfo(customer.getId(), customer.getName(), billing.getBalance());
}
private CustomerInfo getCustomerInfoBlockCombined(Long customerId) {
Mono<Customer> customerMono = webClient.get() | .uri(uriBuilder -> uriBuilder.path(CustomerController.PATH_CUSTOMER)
.pathSegment(String.valueOf(customerId))
.build())
.retrieve()
.onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class)
.map(ApiGatewayException::new))
.bodyToMono(Customer.class);
Mono<Billing> billingMono = webClient.get()
.uri(uriBuilder -> uriBuilder.path(BillingController.PATH_BILLING)
.pathSegment(String.valueOf(customerId))
.build())
.retrieve()
.onStatus(status -> status.is5xxServerError() || status.is4xxClientError(), response -> response.bodyToMono(String.class)
.map(ApiGatewayException::new))
.bodyToMono(Billing.class);
return Mono.zip(customerMono, billingMono, (customer, billing) -> new CustomerInfo(customer.getId(), customer.getName(), billing.getBalance()))
.block();
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive-client-2\src\main\java\com\baeldung\synchronous\gateway\CustomerInfoService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setValues(PreparedStatement ps, Book argument) throws SQLException {
ps.setString(1, argument.getName());
ps.setBigDecimal(2, argument.getPrice());
}
});
return updateCounts;
}
// https://www.postgresql.org/docs/7.3/jdbc-binary-data.html
// https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#jdbc-lob
@Override
public void saveImage(Long bookId, File image) {
try (InputStream imageInStream = new FileInputStream(image)) {
jdbcTemplate.execute(
"INSERT INTO book_image (book_id, filename, blob_image) VALUES (?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(lobHandler) {
protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
ps.setLong(1, 1L);
ps.setString(2, image.getName());
lobCreator.setBlobAsBinaryStream(ps, 3, imageInStream, (int) image.length());
}
}
);
} catch (IOException e) {
e.printStackTrace();
} | }
@Override
public List<Map<String, InputStream>> findImageByBookId(Long bookId) {
List<Map<String, InputStream>> result = jdbcTemplate.query(
"select id, book_id, filename, blob_image from book_image where book_id = ?",
new Object[]{bookId},
new RowMapper<Map<String, InputStream>>() {
public Map<String, InputStream> mapRow(ResultSet rs, int i) throws SQLException {
String fileName = rs.getString("filename");
InputStream blob_image_stream = lobHandler.getBlobAsBinaryStream(rs, "blob_image");
// byte array
//Map<String, Object> results = new HashMap<>();
//byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "blob_image");
//results.put("BLOB", blobBytes);
Map<String, InputStream> results = new HashMap<>();
results.put(fileName, blob_image_stream);
return results;
}
});
return result;
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\repository\JdbcBookRepository.java | 2 |
请完成以下Java代码 | public ImmutableList<DDOrderMoveSchedule> createSchedulesToMove(@NonNull final List<DDOrderMoveScheduleCreateRequest> requests)
{
return requests.stream()
.map(this::createScheduleToMove)
.collect(ImmutableList.toImmutableList());
}
public DDOrderMoveSchedule createScheduleToMove(@NonNull final DDOrderMoveScheduleCreateRequest request)
{
final I_DD_Order_MoveSchedule record = InterfaceWrapperHelper.newInstance(I_DD_Order_MoveSchedule.class);
//record.setAD_Org_ID(ddOrderline.getAD_Org_ID());
record.setDD_Order_ID(request.getDdOrderId().getRepoId());
record.setDD_OrderLine_ID(request.getDdOrderLineId().getRepoId());
record.setStatus(DDOrderMoveScheduleStatus.NOT_STARTED.getCode());
record.setM_Product_ID(request.getProductId().getRepoId());
//
// Pick From
record.setPickFrom_Warehouse_ID(request.getPickFromLocatorId().getWarehouseId().getRepoId());
record.setPickFrom_Locator_ID(request.getPickFromLocatorId().getRepoId());
record.setPickFrom_HU_ID(request.getPickFromHUId().getRepoId());
record.setC_UOM_ID(request.getQtyToPick().getUomId().getRepoId());
record.setQtyToPick(request.getQtyToPick().toBigDecimal());
record.setQtyPicked(BigDecimal.ZERO);
record.setIsPickWholeHU(request.isPickWholeHU());
//
// Drop To
record.setDropTo_Warehouse_ID(request.getDropToLocatorId().getWarehouseId().getRepoId());
record.setDropTo_Locator_ID(request.getDropToLocatorId().getRepoId());
//
InterfaceWrapperHelper.saveRecord(record);
addToCache(record, ImmutableList.of());
return fromRecord(record);
}
public DDOrderMoveSchedule updateById(final DDOrderMoveScheduleId id, Consumer<DDOrderMoveSchedule> updater) | {
warmUpById(id);
final I_DD_Order_MoveSchedule record = getRecordById(id);
final DDOrderMoveSchedule schedule = fromRecord(record);
updater.accept(schedule);
save(schedule);
return schedule;
}
public ImmutableList<DDOrderMoveSchedule> updateByIds(final Set<DDOrderMoveScheduleId> ids, Consumer<DDOrderMoveSchedule> updater)
{
warmUpByIds(ids);
ImmutableList.Builder<DDOrderMoveSchedule> result = ImmutableList.builder();
ids.forEach(id -> {
final I_DD_Order_MoveSchedule record = getRecordById(id);
final DDOrderMoveSchedule schedule = fromRecord(record);
updater.accept(schedule);
save(schedule);
result.add(schedule);
});
return result.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleLoaderAndSaver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void log(final SequenceChangeLog changeLog)
{
if (!changeLog.isChange())
{
return;
}
getLogger().addLog(changeLog.toString());
}
private void logError(final String tableName, final Throwable e)
{
getLogger().addLog("Sequence " + tableName + ": " + e.getLocalizedMessage());
log.warn(e.getLocalizedMessage(), e);
}
private static class SequenceChangeLog
{
private boolean newSequence = false;
private String sequenceName;
private String sequenceNameNew;
private int currentNext;
private int currentNextNew;
private int currentNextSys;
private int currentNextSysNew;
private boolean newValuesSet = false;
public SequenceChangeLog(final I_AD_Sequence sequence)
{
Check.assumeNotNull(sequence, "sequence not null");
this.newSequence = sequence.getAD_Sequence_ID() <= 0;
this.sequenceName = sequence.getName();
this.currentNext = sequence.getCurrentNext();
this.currentNextSys = sequence.getCurrentNextSys();
}
public void setNewValues(final I_AD_Sequence sequence)
{
Check.assumeNotNull(sequence, "sequence not null");
this.sequenceNameNew = sequence.getName();
this.currentNextNew = sequence.getCurrentNext();
this.currentNextSysNew = sequence.getCurrentNextSys();
this.newValuesSet = true;
}
public boolean isChange()
{
if (!newValuesSet)
{
return false;
}
if (newSequence)
{
return true;
}
if (!Objects.equals(this.sequenceName, this.sequenceNameNew))
{
return true;
}
if (currentNext != currentNextNew)
{
return true;
}
if (currentNextSys != currentNextSysNew)
{
return true;
}
return false;
}
@Override
public String toString()
{
final StringBuilder changes = new StringBuilder();
if (newValuesSet && !Objects.equals(sequenceName, sequenceNameNew))
{
if (changes.length() > 0)
{
changes.append(", "); | }
changes.append("Name(new)=").append(sequenceNameNew);
}
if (newValuesSet && currentNext != currentNextNew)
{
if (changes.length() > 0)
{
changes.append(", ");
}
changes.append("CurrentNext=").append(currentNext).append("->").append(currentNextNew);
}
if (newValuesSet && currentNextSys != currentNextSysNew)
{
if (changes.length() > 0)
{
changes.append(", ");
}
changes.append("CurrentNextSys=").append(currentNextSys).append("->").append(currentNextSysNew);
}
final StringBuilder sb = new StringBuilder();
sb.append("Sequence ").append(sequenceName);
if (newSequence)
{
sb.append(" (new)");
}
sb.append(": ");
if (changes.length() > 0)
{
sb.append(changes);
}
else if (newSequence)
{
sb.append("just created");
}
else
{
sb.append("no changes");
}
return sb.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\TableSequenceChecker.java | 2 |
请完成以下Java代码 | public static synchronized void destroy() {
if (isInitialized()) {
Map<String, IdmEngine> engines = new HashMap<>(idmEngines);
idmEngines = new HashMap<>();
for (String idmEngineName : engines.keySet()) {
IdmEngine idmEngine = engines.get(idmEngineName);
try {
idmEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (idmEngineName == null ? "the default idm engine" : "idm engine " + idmEngineName), e);
}
}
idmEngineInfosByName.clear(); | idmEngineInfosByResourceUrl.clear();
idmEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
IdmEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngines.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeferredResultController {
private final static Logger LOG = LoggerFactory.getLogger(DeferredResultController.class);
@GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
LOG.info("Received async-deferredresult request");
DeferredResult<ResponseEntity<?>> output = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
}
output.setResult(ResponseEntity.ok("ok"));
});
LOG.info("servlet thread freed");
return output;
}
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
LOG.info("Received async request with a configured timeout");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
deferredResult.onTimeout(new Runnable() {
@Override
public void run() {
deferredResult.setErrorResult(
ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timeout occurred."));
}
});
ForkJoinPool.commonPool().submit(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(600l);
deferredResult.setResult(ResponseEntity.ok("ok"));
} catch (InterruptedException e) {
LOG.info("Request processing interrupted");
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("INTERNAL_SERVER_ERROR occurred.")); | }
});
LOG.info("servlet thread freed");
return deferredResult;
}
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
ForkJoinPool.commonPool().submit(() -> {
try {
// Exception occurred in processing
throw new Exception();
} catch (Exception e) {
LOG.info("Request processing failed");
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("INTERNAL_SERVER_ERROR occurred."));
}
});
return deferredResult;
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http-2\src\main\java\com\baeldung\deffered\controllers\DeferredResultController.java | 2 |
请完成以下Java代码 | public java.lang.String getSEPA_MandateRefNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SEPA_MandateRefNo);
}
/** Set StructuredRemittanceInfo.
@param StructuredRemittanceInfo
Structured Remittance Information
*/
@Override
public void setStructuredRemittanceInfo (java.lang.String StructuredRemittanceInfo)
{
set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo);
}
/** Get StructuredRemittanceInfo.
@return Structured Remittance Information
*/
@Override
public java.lang.String getStructuredRemittanceInfo ()
{
return (java.lang.String)get_Value(COLUMNNAME_StructuredRemittanceInfo);
}
/** Set Swift code.
@param SwiftCode
Swift Code or BIC
*/
@Override
public void setSwiftCode (java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
/** Get Swift code.
@return Swift Code or BIC | */
@Override
public java.lang.String getSwiftCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_SwiftCode);
}
@Override
public void setIsGroupLine (final boolean IsGroupLine)
{
set_Value (COLUMNNAME_IsGroupLine, IsGroupLine);
}
@Override
public boolean isGroupLine()
{
return get_ValueAsBoolean(COLUMNNAME_IsGroupLine);
}
@Override
public void setNumberOfReferences (final int NumberOfReferences)
{
set_Value (COLUMNNAME_NumberOfReferences, NumberOfReferences);
}
@Override
public int getNumberOfReferences()
{
return get_ValueAsInt(COLUMNNAME_NumberOfReferences);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line.java | 1 |
请完成以下Java代码 | public boolean contains(@NonNull final EAN13ProductCode expectedProductNo, @Nullable final BPartnerId bpartnerId)
{
final GS1ProductCodes bpartnerCodes = bpartnerId != null ? codesByBPartnerId.get(bpartnerId) : null;
return (bpartnerCodes != null && bpartnerCodes.isMatching(expectedProductNo))
|| defaultCodes.isMatching(expectedProductNo);
}
private boolean endsWith(@NonNull final EAN13ProductCode expectedProductNo, @Nullable final BPartnerId bpartnerId)
{
final GS1ProductCodes bpartnerCodes = bpartnerId != null ? codesByBPartnerId.get(bpartnerId) : null;
return (bpartnerCodes != null && bpartnerCodes.endsWith(expectedProductNo))
|| defaultCodes.endsWith(expectedProductNo);
}
public boolean isValidProductNo(@NonNull final EAN13 ean13, @Nullable final BPartnerId bpartnerId)
{
final EAN13Prefix ean13Prefix = ean13.getPrefix();
final EAN13ProductCode ean13ProductNo = ean13.getProductNo();
// 28 - Variable-Weight barcodes
if (ean13Prefix.isVariableWeight())
{
return contains(ean13ProductNo, bpartnerId)
|| ean13ProductNo.isPrefixOf(productValue); | }
// 29 - Internal Use / Variable measure
else if (ean13Prefix.isInternalUseOrVariableMeasure())
{
return contains(ean13ProductNo, bpartnerId);
}
// Parse regular product codes for other prefixes
else
{
return endsWith(ean13ProductNo, bpartnerId);
}
}
public Optional<GS1ProductCodes> getEffectiveCodes(@Nullable final BPartnerId bpartnerId)
{
final GS1ProductCodes bpartnerCodes = bpartnerId != null ? codesByBPartnerId.get(bpartnerId) : null;
final GS1ProductCodes effectiveCodes = bpartnerCodes != null
? bpartnerCodes.fallbackTo(defaultCodes)
: defaultCodes;
return Optional.ofNullable(effectiveCodes.isEmpty() ? null : effectiveCodes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1ProductCodesCollection.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
@Autowired
private UsersRespository userRespository;
@ GetMapping("/")
private List<Users> getUsers(){
return userRespository.findAll();
}
@GetMapping("/{id}")
public Users getUsers(@PathVariable Integer id){
return (Users) userRespository.findById(id).orElse(null);
}
@PostMapping("/")
public Users PostUsers(@RequestBody Users users){ | return (Users) userRespository.save(users);
}
@PutMapping("/")
public Users PutUser(@RequestBody Users users) {
Users oldUser = (Users) userRespository.findById(users.getId()).orElse(null);
oldUser.setName(users.getName());
oldUser.setEmail(users.getEmail());
oldUser.setPassword(users.getPassword());
return (Users) userRespository.save(oldUser);
}
@DeleteMapping("/{id}")
public Integer DeleteUser(@PathVariable Integer id) {
userRespository.deleteById(id);
return id;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-3.SpringBoot-React-Docker-API\fullstack\backend\src\main\java\com\urunov\backend\UserController.java | 2 |
请完成以下Java代码 | public void setBenchmarkValue (BigDecimal BenchmarkValue)
{
set_Value (COLUMNNAME_BenchmarkValue, BenchmarkValue);
}
/** Get Value.
@return Benchmark Value
*/
public BigDecimal getBenchmarkValue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_BenchmarkValue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** 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 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 Benchmark Data.
@param PA_BenchmarkData_ID
Performance Benchmark Data Point
*/ | public void setPA_BenchmarkData_ID (int PA_BenchmarkData_ID)
{
if (PA_BenchmarkData_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_BenchmarkData_ID, Integer.valueOf(PA_BenchmarkData_ID));
}
/** Get Benchmark Data.
@return Performance Benchmark Data Point
*/
public int getPA_BenchmarkData_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_BenchmarkData_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Benchmark getPA_Benchmark() throws RuntimeException
{
return (I_PA_Benchmark)MTable.get(getCtx(), I_PA_Benchmark.Table_Name)
.getPO(getPA_Benchmark_ID(), get_TrxName()); }
/** Set Benchmark.
@param PA_Benchmark_ID
Performance Benchmark
*/
public void setPA_Benchmark_ID (int PA_Benchmark_ID)
{
if (PA_Benchmark_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID));
}
/** Get Benchmark.
@return Performance Benchmark
*/
public int getPA_Benchmark_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_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_PA_BenchmarkData.java | 1 |
请完成以下Java代码 | public I_M_Product getM_ProductBOM() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_ProductBOM_ID(), get_TrxName()); }
/** Set BOM Product.
@param M_ProductBOM_ID
Bill of Material Component Product
*/
public void setM_ProductBOM_ID (int M_ProductBOM_ID)
{
if (M_ProductBOM_ID < 1)
set_Value (COLUMNNAME_M_ProductBOM_ID, null);
else
set_Value (COLUMNNAME_M_ProductBOM_ID, Integer.valueOf(M_ProductBOM_ID));
}
/** Get BOM Product.
@return Bill of Material Component Product
*/
public int getM_ProductBOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductBOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_ProductOperation getM_ProductOperation() throws RuntimeException
{
return (I_M_ProductOperation)MTable.get(getCtx(), I_M_ProductOperation.Table_Name)
.getPO(getM_ProductOperation_ID(), get_TrxName()); }
/** Set Product Operation.
@param M_ProductOperation_ID
Product Manufacturing Operation
*/
public void setM_ProductOperation_ID (int M_ProductOperation_ID)
{
if (M_ProductOperation_ID < 1)
set_Value (COLUMNNAME_M_ProductOperation_ID, null); | else
set_Value (COLUMNNAME_M_ProductOperation_ID, Integer.valueOf(M_ProductOperation_ID));
}
/** Get Product Operation.
@return Product Manufacturing Operation
*/
public int getM_ProductOperation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductOperation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMProduct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(
this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(errorPage);
}
@Override
public int getOrder() {
return 0;
}
}
/**
* {@link BeanFactoryPostProcessor} to ensure that the target class of ErrorController
* MVC beans are preserved when using AOP.
*/
static class PreserveErrorControllerTargetClassPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { | String[] errorControllerBeans = beanFactory.getBeanNamesForType(ErrorController.class, false, false);
for (String errorControllerBean : errorControllerBeans) {
try {
beanFactory.getBeanDefinition(errorControllerBean)
.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
}
catch (Throwable ex) {
// Ignore
}
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\error\ErrorMvcAutoConfiguration.java | 2 |
请完成以下Java代码 | public class UserName {
@Column(name = "name", nullable = false)
private String name;
public UserName(String name) {
this.name = name;
}
protected UserName() {
}
@Override
public String toString() {
return name; | }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final var userName = (UserName) o;
return name.equals(userName.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\UserName.java | 1 |
请完成以下Java代码 | public class PvmAtomicOperationProcessEnd extends PvmAtomicOperationActivityInstanceEnd {
private final static PvmLogger LOG = PvmLogger.PVM_LOGGER;
protected ScopeImpl getScope(PvmExecutionImpl execution) {
return execution.getProcessDefinition();
}
protected String getEventName() {
return ExecutionListener.EVENTNAME_END;
}
@Override
protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
execution.leaveActivityInstance();
PvmExecutionImpl superExecution = execution.getSuperExecution();
CmmnActivityExecution superCaseExecution = execution.getSuperCaseExecution();
SubProcessActivityBehavior subProcessActivityBehavior = null;
TransferVariablesActivityBehavior transferVariablesBehavior = null;
// copy variables before destroying the ended sub process instance
if (superExecution != null) {
PvmActivity activity = superExecution.getActivity();
subProcessActivityBehavior = (SubProcessActivityBehavior) activity.getActivityBehavior();
try {
subProcessActivityBehavior.passOutputVariables(superExecution, execution);
} catch (RuntimeException e) {
LOG.exceptionWhileCompletingSupProcess(execution, e);
throw e;
} catch (Exception e) {
LOG.exceptionWhileCompletingSupProcess(execution, e);
throw new ProcessEngineException("Error while completing sub process of execution " + execution, e);
}
} else if (superCaseExecution != null) {
CmmnActivity activity = superCaseExecution.getActivity();
transferVariablesBehavior = (TransferVariablesActivityBehavior) activity.getActivityBehavior(); | try {
transferVariablesBehavior.transferVariables(execution, superCaseExecution);
} catch (RuntimeException e) {
LOG.exceptionWhileCompletingSupProcess(execution, e);
throw e;
} catch (Exception e) {
LOG.exceptionWhileCompletingSupProcess(execution, e);
throw new ProcessEngineException("Error while completing sub process of execution " + execution, e);
}
}
execution.destroy();
execution.remove();
// and trigger execution afterwards
if (superExecution != null) {
superExecution.setSubProcessInstance(null);
try {
subProcessActivityBehavior.completed(superExecution);
} catch (RuntimeException e) {
LOG.exceptionWhileCompletingSupProcess(execution, e);
throw e;
} catch (Exception e) {
LOG.exceptionWhileCompletingSupProcess(execution, e);
throw new ProcessEngineException("Error while completing sub process of execution " + execution, e);
}
} else if (superCaseExecution != null) {
superCaseExecution.complete();
}
}
public String getCanonicalName() {
return "process-end";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationProcessEnd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
if (persistentAuditEvent == null) {
return null;
}
return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
*
* @param data the data to convert
* @return a map of String, Object
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>(); | if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
results.put(entry.getKey(), Objects.toString(entry.getValue()));
}
}
}
return results;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\audit\AuditEventConverter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void start(PlatformServiceContainer mBeanServiceContainer) {
// no-op:
// job executor is lazy-started when first process engine is registered and jobExecutorActivate = true
// See: #CAM-4817
}
public void stop(PlatformServiceContainer mBeanServiceContainer) {
shutdown();
}
public void start() {
jobExecutor.start();
}
public void shutdown() {
jobExecutor.shutdown();
}
public int getWaitTimeInMillis() {
return jobExecutor.getWaitTimeInMillis();
}
public void setWaitTimeInMillis(int waitTimeInMillis) {
jobExecutor.setWaitTimeInMillis(waitTimeInMillis);
}
public int getLockTimeInMillis() {
return jobExecutor.getLockTimeInMillis();
}
public void setLockTimeInMillis(int lockTimeInMillis) {
jobExecutor.setLockTimeInMillis(lockTimeInMillis);
}
public String getLockOwner() {
return jobExecutor.getLockOwner();
}
public void setLockOwner(String lockOwner) {
jobExecutor.setLockOwner(lockOwner);
}
public int getMaxJobsPerAcquisition() { | return jobExecutor.getMaxJobsPerAcquisition();
}
public void setMaxJobsPerAcquisition(int maxJobsPerAcquisition) {
jobExecutor.setMaxJobsPerAcquisition(maxJobsPerAcquisition);
}
public String getName() {
return jobExecutor.getName();
}
public JobExecutor getValue() {
return jobExecutor;
}
public boolean isActive() {
return jobExecutor.isActive();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedJobExecutor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class WorkingTime
{
@NonNull Duration duration;
int cycles;
@NonNull WFDurationUnit activityTimeUnit;
@NonNull Duration durationPerOneUnit;
int unitsPerCycle;
@NonNull Quantity qty;
@Builder
public WorkingTime(
@NonNull final Duration durationPerOneUnit,
final int unitsPerCycle,
@NonNull final Quantity qty,
@NonNull final WFDurationUnit activityTimeUnit)
{
this.durationPerOneUnit = durationPerOneUnit;
this.unitsPerCycle = unitsPerCycle;
this.qty = qty;
this.activityTimeUnit = activityTimeUnit;
this.cycles = calculateCycles(unitsPerCycle, qty.toBigDecimal());
this.duration = durationPerOneUnit.multipliedBy(cycles); | }
/**
* @return how many cycles are needed for given qty and units per cycle
*/
private static int calculateCycles(final int unitsPerCycle, final BigDecimal qty)
{
if (unitsPerCycle > 0)
{
final BigDecimal unitsCycleBD = BigDecimal.valueOf(unitsPerCycle);
return qty.divide(unitsCycleBD, 0, RoundingMode.UP).intValueExact();
}
else
{
// consider unitsPerCycle = 1
return qty.setScale(0, RoundingMode.UP).intValueExact();
}
}
public BigDecimal toBigDecimalUsingActivityTimeUnit()
{
return activityTimeUnit.toBigDecimal(getDuration());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\WorkingTime.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public UserVO get(@RequestParam("id") Integer id) {
// 查询并返回用户
return new UserVO().setId(id).setUsername(UUID.randomUUID().toString());
}
@PostMapping("add")
@ApiOperation("添加用户")
public Integer add(UserAddDTO addDTO) {
// 插入用户记录,返回编号
Integer returnId = UUID.randomUUID().hashCode();
// 返回用户编号
return returnId;
}
@PostMapping("/update")
@ApiOperation("更新指定用户编号的用户")
public Boolean update(UserUpdateDTO updateDTO) {
// 更新用户记录 | Boolean success = true;
// 返回更新是否成功
return success;
}
@PostMapping("/delete")
@ApiOperation(value = "删除指定用户编号的用户")
@ApiImplicitParam(name = "id", value = "用户编号", paramType = "query", dataTypeClass = Integer.class, required = true, example = "1024")
public Boolean delete(@RequestParam("id") Integer id) {
// 删除用户记录
Boolean success = false;
// 返回是否更新成功
return success;
}
} | repos\SpringBoot-Labs-master\lab-24\lab-24-apidoc-swagger\src\main\java\cn\iocoder\springboot\lab24\apidoc\controller\UserController.java | 2 |
请完成以下Java代码 | private void cmd_reset()
{
//
// Simple search panel reset
{
for (VEditor editor : m_sEditors)
{
editor.setValue(null);
}
valueField.setText("");
nameField.setText("");
descriptionField.setText("");
docNoField.setText("");
searchField.setText("");
}
//
// Advanced search panel reset
{
advancedTable.getModel().clear();
fQueryName.setSelectedItem(null);
}
//
// Reset query
m_query = createNewQuery(null);
//
// Reset counters
m_total = 0;
}
/**
* @param maxRows acts as a "LIMIT" for the underlying SQL.
*/
private void executeQuery(final GridTabMaxRows maxRows)
{
final GridController gc = getGridController();
if (gc != null)
{
clientUI.invoke()
.setLongOperation(true)
.setParentComponentByWindowNo(m_targetWindowNo)
.setRunnable(new Runnable()
{
@Override
public void run()
{
// m_onlyCurrentRows = false; // search history too
// cmd_save(false);
m_query.setUserQuery(true);
gc.getMTab().setQuery(m_query);
final boolean onlyCurrentRows = false;
final int onlyCurrentDays = 0;
gc.query(onlyCurrentRows, onlyCurrentDays, maxRows); // autoSize
}
}).
invoke();
;
}
}
public void setActionListener(final FindPanelActionListener actionListener)
{
Check.assumeNotNull(actionListener, "actionListener not null");
this.actionListener = actionListener;
}
private void setDefaultButton()
{
setDefaultButton(confirmPanel.getOKButton());
}
private void setDefaultButton(final JButton button)
{
final Window frame = AEnv.getWindow(this);
if (frame instanceof RootPaneContainer)
{
final RootPaneContainer c = (RootPaneContainer)frame;
c.getRootPane().setDefaultButton(button);
}
}
/**
* Get Icon with name action
*
* @param name name
* @param small small
* @return Icon
*/
private final ImageIcon getIcon(String name)
{
final String fullName = name + (drawSmallButtons ? "16" : "24");
return Images.getImageIcon2(fullName);
}
/**
* @return true if the panel is visible and it has at least one field in simple search mode
*/
@Override
public boolean isFocusable() | {
if (!isVisible())
{
return false;
}
if (isSimpleSearchPanelActive())
{
return m_editorFirst != null;
}
return false;
}
@Override
public void setFocusable(final boolean focusable)
{
// ignore it
}
@Override
public void requestFocus()
{
if (isSimpleSearchPanelActive())
{
if (m_editorFirst != null)
{
m_editorFirst.requestFocus();
}
}
}
@Override
public boolean requestFocusInWindow()
{
if (isSimpleSearchPanelActive())
{
if (m_editorFirst != null)
{
return m_editorFirst.requestFocusInWindow();
}
}
return false;
}
private boolean disposed = false;
boolean isDisposed()
{
return disposed;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanel.java | 1 |
请完成以下Java代码 | protected String toString(ServiceInstance instance) {
String httpScheme = instance.isSecure() ? "https" : "http";
return String.format("serviceId=%s, instanceId=%s, url= %s://%s:%d", instance.getServiceId(),
instance.getInstanceId(), (instance.getScheme() != null) ? instance.getScheme() : httpScheme,
instance.getHost(), instance.getPort());
}
public void setConverter(ServiceInstanceConverter converter) {
this.converter = converter;
}
public void setIgnoredServices(Set<String> ignoredServices) {
this.ignoredServices = ignoredServices;
}
public Set<String> getIgnoredServices() {
return ignoredServices;
}
public Set<String> getServices() {
return services;
}
public void setServices(Set<String> services) {
this.services = services;
}
public Map<String, String> getInstancesMetadata() {
return instancesMetadata;
}
public void setInstancesMetadata(Map<String, String> instancesMetadata) {
this.instancesMetadata = instancesMetadata;
}
public Map<String, String> getIgnoredInstancesMetadata() {
return ignoredInstancesMetadata;
} | public void setIgnoredInstancesMetadata(Map<String, String> ignoredInstancesMetadata) {
this.ignoredInstancesMetadata = ignoredInstancesMetadata;
}
private boolean isInstanceAllowedBasedOnMetadata(ServiceInstance instance) {
if (instancesMetadata.isEmpty()) {
return true;
}
for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) {
if (isMapContainsEntry(instancesMetadata, metadata)) {
return true;
}
}
return false;
}
private boolean isInstanceIgnoredBasedOnMetadata(ServiceInstance instance) {
if (ignoredInstancesMetadata.isEmpty()) {
return false;
}
for (Map.Entry<String, String> metadata : instance.getMetadata().entrySet()) {
if (isMapContainsEntry(ignoredInstancesMetadata, metadata)) {
return true;
}
}
return false;
}
private boolean isMapContainsEntry(Map<String, String> map, Map.Entry<String, String> entry) {
String value = map.get(entry.getKey());
return value != null && value.equals(entry.getValue());
}
} | repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\InstanceDiscoveryListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getJndiName() {
return this.jndiName;
}
/**
* Allows the DataSource to be managed by the container and obtained through JNDI. The
* {@code URL}, {@code driverClassName}, {@code username} and {@code password} fields
* will be ignored when using JNDI lookups.
* @param jndiName the JNDI name
*/
public void setJndiName(@Nullable String jndiName) {
this.jndiName = jndiName;
}
public EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() {
return this.embeddedDatabaseConnection;
}
public void setEmbeddedDatabaseConnection(EmbeddedDatabaseConnection embeddedDatabaseConnection) {
this.embeddedDatabaseConnection = embeddedDatabaseConnection;
}
public ClassLoader getClassLoader() {
return this.classLoader;
}
public Xa getXa() {
return this.xa;
}
public void setXa(Xa xa) {
this.xa = xa;
}
/**
* XA Specific datasource settings.
*/
public static class Xa {
/**
* XA datasource fully qualified name.
*/
private @Nullable String dataSourceClassName;
/**
* Properties to pass to the XA data source.
*/
private Map<String, String> properties = new LinkedHashMap<>();
public @Nullable String getDataSourceClassName() {
return this.dataSourceClassName;
}
public void setDataSourceClassName(@Nullable String dataSourceClassName) {
this.dataSourceClassName = dataSourceClassName;
}
public Map<String, String> getProperties() {
return this.properties; | }
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
}
static class DataSourceBeanCreationException extends BeanCreationException {
private final DataSourceProperties properties;
private final EmbeddedDatabaseConnection connection;
DataSourceBeanCreationException(String message, DataSourceProperties properties,
EmbeddedDatabaseConnection connection) {
super(message);
this.properties = properties;
this.connection = connection;
}
DataSourceProperties getProperties() {
return this.properties;
}
EmbeddedDatabaseConnection getConnection() {
return this.connection;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final P050 other = (P050)obj;
if (joinP060P100Lines == null)
{
if (other.joinP060P100Lines != null)
{
return false;
}
}
else if (!joinP060P100Lines.equals(other.joinP060P100Lines))
{
return false;
}
if (levelNo == null)
{
if (other.levelNo != null)
{
return false;
}
}
else if (!levelNo.equals(other.levelNo))
{
return false;
}
if (messageNo == null)
{
if (other.messageNo != null)
{
return false;
}
}
else if (!messageNo.equals(other.messageNo))
{
return false;
}
if (p102Lines == null)
{
if (other.p102Lines != null)
{
return false;
}
}
else if (!p102Lines.equals(other.p102Lines)) | {
return false;
}
if (packageQty == null)
{
if (other.packageQty != null)
{
return false;
}
}
else if (!packageQty.equals(other.packageQty))
{
return false;
}
if (packageType == null)
{
if (other.packageType != null)
{
return false;
}
}
else if (!packageType.equals(other.packageType))
{
return false;
}
if (partner == null)
{
if (other.partner != null)
{
return false;
}
}
else if (!partner.equals(other.partner))
{
return false;
}
if (record == null)
{
if (other.record != null)
{
return false;
}
}
else if (!record.equals(other.record))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "P050 [record=" + record + ", partner=" + partner + ", messageNo=" + messageNo + ", levelNo=" + levelNo + ", packageQty=" + packageQty + ", packageType=" + packageType + ", p102Lines="
+ p102Lines + ", joinP060P100Lines=" + joinP060P100Lines + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\compudata\P050.java | 2 |
请完成以下Java代码 | public font addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public font addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the Element.
@param element adds and Element to the Element.
*/
public font addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/** | Adds an Element to the Element.
@param element adds and Element to the Element.
*/
public font addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public font removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\font.java | 1 |
请完成以下Java代码 | public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
} | /** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Workfile.java | 1 |
请完成以下Java代码 | protected ScopeImpl getScope(InterpretableExecution execution) {
return (ScopeImpl) execution.getActivity();
}
@Override
protected String getEventName() {
return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_START;
}
@Override
protected void eventNotificationsCompleted(InterpretableExecution execution) {
TransitionImpl transition = execution.getTransition();
ActivityImpl destination = null;
if (transition == null) { // this is null after async cont. -> transition is not stored in execution
destination = (ActivityImpl) execution.getActivity(); | } else {
destination = transition.getDestination();
}
ActivityImpl activity = (ActivityImpl) execution.getActivity();
if (activity != destination) {
ActivityImpl nextScope = AtomicOperationTransitionNotifyListenerTake.findNextScope(activity, destination);
execution.setActivity(nextScope);
execution.performOperation(TRANSITION_CREATE_SCOPE);
} else {
execution.setTransition(null);
execution.setActivity(destination);
execution.performOperation(ACTIVITY_EXECUTE);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationTransitionNotifyListenerStart.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void validateDataImpl(TenantId tenantId, WidgetTypeDetails widgetTypeDetails) {
validateString("Widgets type name", widgetTypeDetails.getName());
if (widgetTypeDetails.getDescriptor() == null || widgetTypeDetails.getDescriptor().size() == 0) {
throw new DataValidationException("Widgets type descriptor can't be empty!");
}
if (widgetTypeDetails.getTenantId() == null) {
widgetTypeDetails.setTenantId(TenantId.fromUUID(ModelConstants.NULL_UUID));
}
if (!widgetTypeDetails.getTenantId().getId().equals(ModelConstants.NULL_UUID)) {
if (!tenantService.tenantExists(widgetTypeDetails.getTenantId())) {
throw new DataValidationException("Widget type is referencing to non-existent tenant!");
}
}
}
@Override
protected void validateCreate(TenantId tenantId, WidgetTypeDetails widgetTypeDetails) {
String fqn = widgetTypeDetails.getFqn();
if (fqn == null || fqn.trim().isEmpty()) {
fqn = widgetTypeDetails.getName().toLowerCase().replaceAll("\\W+", "_");
}
String originalFqn = fqn;
int c = 1;
WidgetType withSameFqn;
do {
withSameFqn = widgetTypeDao.findByTenantIdAndFqn(widgetTypeDetails.getTenantId().getId(), fqn); | if (withSameFqn != null) {
fqn = originalFqn + (++c);
}
} while (withSameFqn != null);
widgetTypeDetails.setFqn(fqn);
}
@Override
protected WidgetTypeDetails validateUpdate(TenantId tenantId, WidgetTypeDetails widgetTypeDetails) {
WidgetTypeDetails storedWidgetType = widgetTypeDao.findById(tenantId, widgetTypeDetails.getId().getId());
if (!storedWidgetType.getTenantId().getId().equals(widgetTypeDetails.getTenantId().getId())) {
throw new DataValidationException("Can't move existing widget type to different tenant!");
}
if (!storedWidgetType.getFqn().equals(widgetTypeDetails.getFqn())) {
throw new DataValidationException("Update of widget type fqn is prohibited!");
}
return new WidgetTypeDetails(storedWidgetType);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\WidgetTypeDataValidator.java | 2 |
请完成以下Java代码 | void setDays(int day)
{
Day = day;
}
int getDays()
{
return Day;
}
void setCapacity(int capacity)
{
Capacity = capacity;
}
int getCapacity()
{
return Capacity;
}
void setLoad(int load)
{
Load = load;
}
int getLoad()
{
return Load;
}
int getDifference()
{
return Capacity - Load;
} | void setSummary(int summary)
{
Summary = summary;
}
int getSummary()
{
return Summary;
}
void setFrom(String from)
{
From = from;
}
String getFrom()
{
return From;
}
void setTo(String to)
{
To = to;
}
String getTo()
{
return To;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CRPSummary.java | 1 |
请完成以下Java代码 | public final class ContextPath {
/**
* The default context path.
*/
public static final ContextPath DEFAULT = ContextPath.of("");
private final String path;
private ContextPath(String path) {
this.path = path;
}
public static ContextPath of(String contextPath) {
Assert.notNull(contextPath, "'contextPath' must not be null");
if (!contextPath.isEmpty()) {
if ("/".equals(contextPath)) { | throw new IllegalArgumentException("Root context path must be specified using an empty string");
}
if (!contextPath.startsWith("/") || contextPath.endsWith("/")) {
throw new IllegalArgumentException("Context path must start with '/' and not end with '/'");
}
}
return new ContextPath(contextPath);
}
@Override
public String toString() {
return this.path;
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ContextPath.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void save(RegisteredClient registeredClient) {
log.info("Saving registered client: id={}, name={}",
registeredClient.getClientId(),
registeredClient.getClientName());
Set<String> scopes = ( registeredClient.getScopes() == null || registeredClient.getScopes().isEmpty())?
Set.of("openid","email","profile"):
registeredClient.getScopes();
// Disable PKCE & Consent
RegisteredClient modifiedClient = RegisteredClient.from(registeredClient)
.scopes(s -> s.addAll(scopes))
.clientSettings(ClientSettings
.withSettings(registeredClient.getClientSettings().getSettings())
.requireAuthorizationConsent(false)
.requireProofKey(false)
.build())
.build();
delegate.save(modifiedClient);
} | @Override
public RegisteredClient findById(String id) {
return delegate.findByClientId(id);
}
/**
* Returns the registered client identified by the provided {@code clientId},
* or {@code null} if not found.
*
* @param clientId
* the client identifier
* @return the {@link RegisteredClient} if found, otherwise {@code null}
*/
@Override
public RegisteredClient findByClientId(String clientId) {
return delegate.findByClientId(clientId);
}
} | repos\tutorials-master\spring-security-modules\spring-security-dynamic-registration\oauth2-authorization-server\src\main\java\com\baeldung\spring\security\authserver\repository\CustomRegisteredClientRepository.java | 2 |
请完成以下Java代码 | public static Process getProcess(String processDefinitionId) {
if (Context.getProcessEngineConfiguration() == null) {
return getProcessDefinitionHelper().getProcessDefinitionProcessObject(processDefinitionId);
} else {
DeploymentManager deploymentManager = Context.getProcessEngineConfiguration().getDeploymentManager();
// This will check the cache in the findDeployedProcessDefinitionById and resolveProcessDefinition method
ProcessDefinition processDefinitionEntity = deploymentManager.findDeployedProcessDefinitionById(
processDefinitionId
);
return deploymentManager.resolveProcessDefinition(processDefinitionEntity).getProcess();
}
}
public static BpmnModel getBpmnModel(String processDefinitionId) {
if (Context.getProcessEngineConfiguration() == null) {
return getProcessDefinitionHelper().getProcessDefinitionBpmnModel(processDefinitionId);
} else {
DeploymentManager deploymentManager = Context.getProcessEngineConfiguration().getDeploymentManager();
// This will check the cache in the findDeployedProcessDefinitionById and resolveProcessDefinition method
ProcessDefinition processDefinitionEntity = deploymentManager.findDeployedProcessDefinitionById(
processDefinitionId
);
return deploymentManager.resolveProcessDefinition(processDefinitionEntity).getBpmnModel();
}
}
public static BpmnModel getBpmnModelFromCache(String processDefinitionId) { | ProcessDefinitionCacheEntry cacheEntry = Context.getProcessEngineConfiguration()
.getProcessDefinitionCache()
.get(processDefinitionId);
if (cacheEntry != null) {
return cacheEntry.getBpmnModel();
}
return null;
}
public static boolean isProcessDefinitionSuspended(String processDefinitionId) {
ProcessDefinitionEntity processDefinition = getProcessDefinitionFromDatabase(processDefinitionId);
return processDefinition.isSuspended();
}
public static ProcessDefinitionEntity getProcessDefinitionFromDatabase(String processDefinitionId) {
ProcessDefinitionEntityManager processDefinitionEntityManager =
Context.getProcessEngineConfiguration().getProcessDefinitionEntityManager();
ProcessDefinitionEntity processDefinition = processDefinitionEntityManager.findById(processDefinitionId);
if (processDefinition == null) {
throw new ActivitiException("No process definition found with id " + processDefinitionId);
}
return processDefinition;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ProcessDefinitionUtil.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BankStatement_ID (final int C_BankStatement_ID)
{
if (C_BankStatement_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatement_ID, C_BankStatement_ID);
}
@Override
public int getC_BankStatement_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_ID);
}
@Override
public void setDateDoc (final @Nullable java.sql.Timestamp DateDoc)
{
set_ValueNoCheck (COLUMNNAME_DateDoc, DateDoc);
}
@Override
public java.sql.Timestamp getDateDoc()
{
return get_ValueAsTimestamp(COLUMNNAME_DateDoc);
} | @Override
public de.metas.payment.esr.model.I_ESR_Import getESR_Import()
{
return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class);
}
@Override
public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import)
{
set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import);
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_x_esr_import_in_c_bankstatement_v.java | 1 |
请完成以下Java代码 | public class Customer {
private String customerId;
private String customerName;
private String customerContact;
private String customerEmail;
public Customer() {
super();
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerContact() {
return customerContact; | }
public void setCustomerContact(String customerContact) {
this.customerContact = customerContact;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\domain\Customer.java | 1 |
请完成以下Java代码 | public I_C_DirectDebit getC_DirectDebit() throws Exception
{
return get_ValueAsPO(COLUMNNAME_C_DirectDebit_ID, org.compiere.model.I_C_DirectDebit.class);
}
/** Set C_DirectDebit_ID.
@param C_DirectDebit_ID C_DirectDebit_ID */
@Override
public void setC_DirectDebit_ID (int C_DirectDebit_ID)
{
if (C_DirectDebit_ID < 1)
throw new IllegalArgumentException ("C_DirectDebit_ID is mandatory.");
set_Value (COLUMNNAME_C_DirectDebit_ID, Integer.valueOf(C_DirectDebit_ID));
}
/** Get C_DirectDebit_ID.
@return C_DirectDebit_ID */
@Override
public int getC_DirectDebit_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebit_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set C_DirectDebitLine_ID.
@param C_DirectDebitLine_ID C_DirectDebitLine_ID */
@Override
public void setC_DirectDebitLine_ID (int C_DirectDebitLine_ID)
{
if (C_DirectDebitLine_ID < 1)
throw new IllegalArgumentException ("C_DirectDebitLine_ID is mandatory.");
set_ValueNoCheck (COLUMNNAME_C_DirectDebitLine_ID, Integer.valueOf(C_DirectDebitLine_ID));
}
/** Get C_DirectDebitLine_ID.
@return C_DirectDebitLine_ID */
@Override
public int getC_DirectDebitLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebitLine_ID);
if (ii == null)
return 0;
return ii.intValue();
} | @Override
public I_C_Invoice getC_Invoice() throws Exception
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
/** Set Invoice.
@param C_Invoice_ID
Invoice Identifier
*/
@Override
public void setC_Invoice_ID (int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
throw new IllegalArgumentException ("C_Invoice_ID is mandatory.");
set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID));
}
/** Get Invoice.
@return Invoice Identifier
*/
@Override
public int getC_Invoice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebitLine.java | 1 |
请完成以下Java代码 | public CardDataReading1Code getCardDataNtryMd() {
return cardDataNtryMd;
}
/**
* Sets the value of the cardDataNtryMd property.
*
* @param value
* allowed object is
* {@link CardDataReading1Code }
*
*/
public void setCardDataNtryMd(CardDataReading1Code value) {
this.cardDataNtryMd = value;
}
/**
* Gets the value of the fllbckInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFllbckInd() {
return fllbckInd;
}
/**
* Sets the value of the fllbckInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFllbckInd(Boolean value) {
this.fllbckInd = value;
}
/** | * Gets the value of the authntcnMtd property.
*
* @return
* possible object is
* {@link CardholderAuthentication2 }
*
*/
public CardholderAuthentication2 getAuthntcnMtd() {
return authntcnMtd;
}
/**
* Sets the value of the authntcnMtd property.
*
* @param value
* allowed object is
* {@link CardholderAuthentication2 }
*
*/
public void setAuthntcnMtd(CardholderAuthentication2 value) {
this.authntcnMtd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\PaymentContext3.java | 1 |
请完成以下Java代码 | public int getAD_Tree_Project_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_Project_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Tree getAD_Tree_SalesRegion() throws RuntimeException
{
return (I_AD_Tree)MTable.get(getCtx(), I_AD_Tree.Table_Name)
.getPO(getAD_Tree_SalesRegion_ID(), get_TrxName()); }
/** Set Sales Region Tree.
@param AD_Tree_SalesRegion_ID
Tree to determine sales regional hierarchy
*/
public void setAD_Tree_SalesRegion_ID (int AD_Tree_SalesRegion_ID)
{
if (AD_Tree_SalesRegion_ID < 1)
set_Value (COLUMNNAME_AD_Tree_SalesRegion_ID, null);
else
set_Value (COLUMNNAME_AD_Tree_SalesRegion_ID, Integer.valueOf(AD_Tree_SalesRegion_ID));
}
/** Get Sales Region Tree.
@return Tree to determine sales regional hierarchy
*/
public int getAD_Tree_SalesRegion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_SalesRegion_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 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 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 Reporting Hierarchy.
@param PA_Hierarchy_ID
Optional Reporting Hierarchy - If not selected the default hierarchy trees are used.
*/
public void setPA_Hierarchy_ID (int PA_Hierarchy_ID)
{
if (PA_Hierarchy_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Hierarchy_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Hierarchy_ID, Integer.valueOf(PA_Hierarchy_ID));
}
/** Get Reporting Hierarchy.
@return Optional Reporting Hierarchy - If not selected the default hierarchy trees are used.
*/
public int getPA_Hierarchy_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Hierarchy_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_PA_Hierarchy.java | 1 |
请完成以下Java代码 | public static void markReportedIfPossible(@NonNull final Throwable exception, @NonNull final AdIssueId adIssueId)
{
// NOTE: we are marking as reported all the causes downline because mainly all of those exceptions were reported in one shot.
Throwable currentEx = exception;
while (currentEx != null)
{
if (currentEx instanceof IIssueReportableAware)
{
final IIssueReportableAware issueReportable = (IIssueReportableAware)currentEx;
issueReportable.markIssueReported(adIssueId);
}
currentEx = currentEx.getCause();
}
}
/**
* Checks if given exception or any of it's causes was marked as reported.
*
* NOTE: We are also checking the causes downline because ADempiere's excesive exception wrapping.
*
* @param exception exceptions chain to be checked
* @return <code>true</code> if given exception was marked as reported.
*/
public static boolean isReported(@Nullable final Throwable exception)
{
Throwable currentEx = exception;
while (currentEx != null)
{
if (currentEx instanceof IIssueReportableAware)
{
final IIssueReportableAware issueReportable = (IIssueReportableAware)currentEx; | if (issueReportable.isIssueReported())
{
return true;
}
}
currentEx = currentEx.getCause();
}
return false;
}
@Nullable
public static AdIssueId getAdIssueIdOrNull(@NonNull final Throwable exception)
{
if (exception instanceof IIssueReportableAware)
{
final IIssueReportableAware issueReportable = (IIssueReportableAware)exception;
if (issueReportable.isIssueReported())
{
return issueReportable.getAdIssueId();
}
else
{
return null;
}
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\exceptions\IssueReportableExceptions.java | 1 |
请完成以下Java代码 | public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
public String getTenantId() {
return tenantId;
} | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Date getTime() {
return getStartTime();
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return (
"HistoricActivityInstanceEntity[id=" +
id +
", activityId=" +
activityId +
", activityName=" +
activityName +
"]"
);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricActivityInstanceEntityImpl.java | 1 |
请完成以下Java代码 | protected String getEventName() {
return ExecutionListener.EVENTNAME_START;
}
protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
super.eventNotificationsCompleted(execution);
execution.activityInstanceStarted();
ScopeInstantiationContext startContext = execution.getScopeInstantiationContext();
InstantiationStack instantiationStack = startContext.getInstantiationStack();
PvmExecutionImpl propagatingExecution = execution;
ActivityImpl activity = execution.getActivity();
if (activity.getActivityBehavior() instanceof ModificationObserverBehavior) {
ModificationObserverBehavior behavior = (ModificationObserverBehavior) activity.getActivityBehavior();
List<ActivityExecution> concurrentExecutions = behavior.initializeScope(propagatingExecution, 1);
propagatingExecution = (PvmExecutionImpl) concurrentExecutions.get(0);
}
// if the stack has been instantiated
if (instantiationStack.getActivities().isEmpty() && instantiationStack.getTargetActivity() != null) {
// as if we are entering the target activity instance id via a transition
propagatingExecution.setActivityInstanceId(null);
// execute the target activity with this execution
startContext.applyVariables(propagatingExecution);
propagatingExecution.setActivity(instantiationStack.getTargetActivity());
propagatingExecution.disposeScopeInstantiationContext();
propagatingExecution.performOperation(ACTIVITY_START_CREATE_SCOPE);
}
else if (instantiationStack.getActivities().isEmpty() && instantiationStack.getTargetTransition() != null) {
// as if we are entering the target activity instance id via a transition
propagatingExecution.setActivityInstanceId(null); | // execute the target transition with this execution
PvmTransition transition = instantiationStack.getTargetTransition();
startContext.applyVariables(propagatingExecution);
propagatingExecution.setActivity(transition.getSource());
propagatingExecution.setTransition((TransitionImpl) transition);
propagatingExecution.disposeScopeInstantiationContext();
propagatingExecution.performOperation(TRANSITION_START_NOTIFY_LISTENER_TAKE);
}
else {
// else instantiate the activity stack further
propagatingExecution.setActivity(null);
propagatingExecution.performOperation(ACTIVITY_INIT_STACK);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInitStackNotifyListenerStart.java | 1 |
请完成以下Java代码 | public class FieldAccessException extends GraphQlClientException {
private final ClientGraphQlResponse response;
private final ClientResponseField field;
/**
* Constructor with the request and response, and the accessed field.
* @param request the client request
* @param response the client response
* @param field the accessed field that caused the error
*/
public FieldAccessException(
ClientGraphQlRequest request, ClientGraphQlResponse response, ClientResponseField field) {
super(initDefaultMessage(field, response), null, request);
this.response = response;
this.field = field;
}
private static String initDefaultMessage(ClientResponseField field, ClientGraphQlResponse response) { | return "Invalid field '" + field.getPath() + "', errors: " +
(!field.getErrors().isEmpty() ? field.getErrors() : response.getErrors());
}
/**
* Return the [@code GraphQlResponse} for which the error occurred.
*/
public ClientGraphQlResponse getResponse() {
return this.response;
}
/**
* Return the field that needed to be accessed.
*/
public ClientResponseField getField() {
return this.field;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\FieldAccessException.java | 1 |
请完成以下Java代码 | public void setAmtsgericht(String value) {
this.amtsgericht = value;
}
/**
* Gets the value of the handelsregisternummer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHandelsregisternummer() {
return handelsregisternummer;
}
/**
* Sets the value of the handelsregisternummer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHandelsregisternummer(String value) {
this.handelsregisternummer = value;
}
/**
* Gets the value of the umsatzsteuerID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUmsatzsteuerID() {
return umsatzsteuerID;
}
/**
* Sets the value of the umsatzsteuerID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUmsatzsteuerID(String value) {
this.umsatzsteuerID = value;
}
/**
* Gets the value of the steuernummer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSteuernummer() {
return steuernummer;
}
/**
* Sets the value of the steuernummer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSteuernummer(String value) {
this.steuernummer = value;
}
/**
* Gets the value of the bankname property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getBankname() {
return bankname;
}
/**
* Sets the value of the bankname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankname(String value) {
this.bankname = value;
}
/**
* Gets the value of the bic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBIC() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBIC(String value) {
this.bic = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIBAN() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIBAN(String value) {
this.iban = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungType.java | 1 |
请完成以下Java代码 | public JSONLookupValuesPage getAttributeTypeahead(
@PathVariable("docId") final int docId,
@PathVariable("attributeName") final String attributeName,
@RequestParam(name = "query") final String query)
{
userSession.assertLoggedIn();
return addressRepo.getAddressDocumentForReading(docId)
.getFieldLookupValuesForQuery(attributeName, query)
.transform(page -> JSONLookupValuesPage.of(page, userSession.getAD_Language()));
}
@GetMapping("/{docId}/field/{attributeName}/dropdown")
public JSONLookupValuesList getAttributeDropdown(
@PathVariable("docId") final int docId,
@PathVariable("attributeName") final String attributeName)
{
userSession.assertLoggedIn();
return addressRepo.getAddressDocumentForReading(docId)
.getFieldLookupValues(attributeName) | .transform(list -> JSONLookupValuesList.ofLookupValuesList(list, userSession.getAD_Language()));
}
@PostMapping("/{docId}/complete")
public JSONLookupValue complete(
@PathVariable("docId") final int docId,
@RequestBody final JSONCompleteASIRequest request)
{
userSession.assertLoggedIn();
return Execution.callInNewExecution(
"complete",
() -> addressRepo.complete(docId, request.getEvents())
.transform(lookupValue -> JSONLookupValue.ofLookupValue(lookupValue, userSession.getAD_Language())));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRestController.java | 1 |
请完成以下Java代码 | public DistributionJobLine getLineById(@NonNull final DistributionJobLineId lineId)
{
return lines.stream()
.filter(line -> DistributionJobLineId.equals(line.getId(), lineId))
.findFirst()
.orElseThrow(() -> new AdempiereException("No line found for " + lineId));
}
@NonNull
public DistributionJobLine getLineByStepId(@NonNull final DistributionJobStepId stepId)
{
return lines.stream()
.filter(line -> line.getStepById(stepId).isPresent())
.findFirst()
.orElseThrow(() -> new AdempiereException("No line found for " + stepId));
}
@Nullable
public String getPlantName()
{
return plantInfo != null ? plantInfo.getCaption() : null;
}
public Stream<DistributionJobStep> streamSteps()
{
return lines.stream().flatMap(line -> line.getSteps().stream());
}
public boolean isFullyMoved()
{
return lines.stream().allMatch(DistributionJobLine::isFullyMoved);
}
public boolean isInTransit()
{
return lines.stream().anyMatch(DistributionJobLine::isInTransit);
}
@Nullable
public LocatorId getSinglePickFromLocatorIdOrNull()
{
return lines.stream()
.map(DistributionJobLine::getPickFromLocatorId)
.distinct()
.collect(GuavaCollectors.singleElementOrNull());
}
public Optional<LocatorInfo> getSinglePickFromLocator()
{
return lines.stream()
.map(DistributionJobLine::getPickFromLocator)
.distinct()
.collect(GuavaCollectors.singleElementOrEmpty()); | }
@Nullable
public LocatorId getSingleDropToLocatorIdOrNull()
{
return lines.stream()
.map(DistributionJobLine::getDropToLocatorId)
.distinct()
.collect(GuavaCollectors.singleElementOrNull());
}
public Optional<LocatorInfo> getSingleDropToLocator()
{
return lines.stream()
.map(DistributionJobLine::getDropToLocator)
.distinct()
.collect(GuavaCollectors.singleElementOrEmpty());
}
@Nullable
public ProductId getSingleProductIdOrNull()
{
return lines.stream()
.map(DistributionJobLine::getProductId)
.distinct()
.collect(GuavaCollectors.singleElementOrNull());
}
@Nullable
public Quantity getSingleUnitQuantityOrNull()
{
final MixedQuantity qty = lines.stream()
.map(DistributionJobLine::getQtyToMove)
.distinct()
.collect(MixedQuantity.collectAndSum());
return qty.toNoneOrSingleValue().orElse(null);
}
public Optional<DistributionJobLineId> getNextEligiblePickFromLineId(@NonNull final ProductId productId)
{
return lines.stream()
.filter(line -> ProductId.equals(line.getProductId(), productId))
.filter(DistributionJobLine::isEligibleForPicking)
.map(DistributionJobLine::getId)
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJob.java | 1 |
请完成以下Java代码 | public boolean isTransactionActive() {
return TransactionSynchronizationManager.isActualTransactionActive() &&
!TransactionState.ROLLED_BACK.equals(lastTransactionState) &&
!TransactionState.ROLLINGBACK.equals(lastTransactionState);
}
protected abstract class TransactionSynchronizationAdapter implements TransactionSynchronization {
public void suspend() {
}
public void resume() {
}
public void flush() {
} | public void beforeCommit(boolean readOnly) {
}
public void beforeCompletion() {
}
public void afterCommit() {
}
public void afterCompletion(int status) {
}
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\SpringTransactionContext.java | 1 |
请完成以下Java代码 | public static double calculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) {
double U1 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude1)));
double U2 = Math.atan((1 - FLATTENING) * Math.tan(Math.toRadians(latitude2)));
double sinU1 = Math.sin(U1);
double cosU1 = Math.cos(U1);
double sinU2 = Math.sin(U2);
double cosU2 = Math.cos(U2);
double longitudeDifference = Math.toRadians(longitude2 - longitude1);
double previousLongitudeDifference;
double sinSigma, cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM;
do {
sinSigma = Math.sqrt(Math.pow(cosU2 * Math.sin(longitudeDifference), 2) +
Math.pow(cosU1 * sinU2 - sinU1 * cosU2 * Math.cos(longitudeDifference), 2));
cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * Math.cos(longitudeDifference);
sigma = Math.atan2(sinSigma, cosSigma);
sinAlpha = cosU1 * cosU2 * Math.sin(longitudeDifference) / sinSigma;
cosSqAlpha = 1 - Math.pow(sinAlpha, 2);
cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
if (Double.isNaN(cos2SigmaM)) {
cos2SigmaM = 0;
}
previousLongitudeDifference = longitudeDifference;
double C = FLATTENING / 16 * cosSqAlpha * (4 + FLATTENING * (4 - 3 * cosSqAlpha)); | longitudeDifference = Math.toRadians(longitude2 - longitude1) + (1 - C) * FLATTENING * sinAlpha *
(sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2))));
} while (Math.abs(longitudeDifference - previousLongitudeDifference) > ERROR_TOLERANCE);
double uSq = cosSqAlpha * (Math.pow(SEMI_MAJOR_AXIS_MT, 2) - Math.pow(SEMI_MINOR_AXIS_MT, 2)) / Math.pow(SEMI_MINOR_AXIS_MT, 2);
double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)) -
B / 6 * cos2SigmaM * (-3 + 4 * Math.pow(sinSigma, 2)) * (-3 + 4 * Math.pow(cos2SigmaM, 2))));
double distanceMt = SEMI_MINOR_AXIS_MT * A * (sigma - deltaSigma);
return distanceMt / 1000;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-1\src\main\java\com\baeldung\algorithms\latlondistance\VincentyDistance.java | 1 |
请完成以下Java代码 | public List<String> getAllUserNames() {
List<String> userNames = new ArrayList<>();
try (CqlSession session = CqlSession.builder().build()) {
String query = String.format("select * from %s.%s",keySpaceName,tableName);
ResultSet rs = session.execute(query);
for (Row r : rs.all())
userNames.add(r.getString("name"));
}
return userNames;
}
public List<User> getUsersByUserName(String userName) {
List<User> userList = new ArrayList<>();
try (CqlSession session = CqlSession.builder().build()) {
Select query = selectFrom(keySpaceName, tableName).all()
.whereColumn("name")
.isEqualTo(literal(userName))
.allowFiltering();
SimpleStatement statement = query.build();
ResultSet rs = session.execute(statement);
for (Row r : rs) | userList.add(new User(r.getLong("id"), r.getString("name")));
}
return userList;
}
public boolean addNewUser(User user) {
boolean response = false;
try (CqlSession session = CqlSession.builder().build()) {
InsertInto insert = insertInto(keySpaceName, tableName);
SimpleStatement statement = insert.value("id", literal(user.getId()))
.value("name", literal(user.getName()))
.build();
ResultSet rs = session.execute(statement);
response = null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty();
}
return response;
}
} | repos\tutorials-master\persistence-modules\scylladb\src\main\java\com\baeldung\scylladb\ScylladbApplication.java | 1 |
请完成以下Java代码 | protected boolean ignoreApplicationContext(WebApplicationContext webApplicationContext) {
return false;
}
/**
* Method that can be implemented by subclasses that wish to initialize items the
* first time that the matcher is called. This method will be called only once and
* only if {@link #ignoreApplicationContext(WebApplicationContext)} returns
* {@code false}. Note that the supplied context will be based on the
* <strong>first</strong> request sent to the matcher.
* @param context a supplier for the initialized context (may throw an exception)
* @see #ignoreApplicationContext(WebApplicationContext)
*/
protected void initialized(Supplier<C> context) {
}
/**
* Decides whether the rule implemented by the strategy matches the supplied request.
* @param request the source request
* @param context a supplier for the initialized context (may throw an exception)
* @return if the request matches
*/
protected abstract boolean matches(HttpServletRequest request, Supplier<C> context);
/**
* Returns {@code true} if the specified context is a
* {@link WebServerApplicationContext} with a matching server namespace.
* @param context the context to check
* @param serverNamespace the server namespace to match against
* @return {@code true} if the server namespace of the context matches | * @since 4.0.1
*/
protected final boolean hasServerNamespace(@Nullable ApplicationContext context, String serverNamespace) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return false;
}
return WebServerApplicationContext.hasServerNamespace(context, serverNamespace);
}
/**
* Returns the server namespace if the specified context is a
* {@link WebServerApplicationContext}.
* @param context the context
* @return the server namespace or {@code null} if the context is not a
* {@link WebServerApplicationContext}
* @since 4.0.1
*/
protected final @Nullable String getServerNamespace(@Nullable ApplicationContext context) {
if (!ClassUtils.isPresent(WEB_SERVER_CONTEXT_CLASS, null)) {
return null;
}
return WebServerApplicationContext.getServerNamespace(context);
}
} | repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\web\servlet\ApplicationContextRequestMatcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AppDeploymentResourceCollectionResource {
@Autowired
protected AppRestResponseFactory appResponseFactory;
@Autowired
protected ContentTypeResolver contentTypeResolver;
@Autowired
protected AppRepositoryService repositoryService;
@Autowired(required=false)
protected AppRestApiInterceptor restApiInterceptor;
@ApiOperation(value = "List resources in a deployment", tags = { "App Deployments" }, nickname="listDeploymentResources",
notes = "The dataUrl property in the resulting JSON for a single resource contains the actual URL to use for retrieving the binary resource.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the deployment was found and the resource list has been returned."),
@ApiResponse(code = 404, message = "Indicates the requested deployment was not found.") | })
@GetMapping(value = "/app-repository/deployments/{deploymentId}/resources", produces = "application/json")
public List<AppDeploymentResourceResponse> getDeploymentResources(@ApiParam(name = "deploymentId") @PathVariable String deploymentId) {
// Check if deployment exists
AppDeployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
if (deployment == null) {
throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", AppDeployment.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessDeploymentById(deployment);
}
List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId);
return appResponseFactory.createDeploymentResourceResponseList(deploymentId, resourceList, contentTypeResolver);
}
} | repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\service\api\repository\AppDeploymentResourceCollectionResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class FileService {
/**
* Read a file.
*
* @param path the file path
* @return the contents.
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static String read(final Path path) throws MojoExecutionException {
try {
return new String(Files.readAllBytes(path));
} catch (IOException e) {
throw new MojoExecutionException("Unable to read file " + path, e);
}
}
/**
* Write to a file.
*
* @param path the file path
* @param contents the contents to write
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static void write(final Path path, final String contents) throws MojoExecutionException {
try { | Files.write(path, contents.getBytes());
} catch (IOException e) {
throw new MojoExecutionException("Unable to write file " + path, e);
}
}
/**
* Load a file into properties.
*
* @param path the path
* @param properties the properties to mutate
* @throws org.apache.maven.plugin.MojoExecutionException if any.
*/
public static void load(final Path path, final Properties properties)
throws MojoExecutionException {
try {
properties.load(Files.newInputStream(path));
} catch (IOException e) {
throw new MojoExecutionException("Unable to load file " + path, e);
}
}
} | repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\FileService.java | 2 |
请完成以下Java代码 | public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processing Tag.
@param ProcessingTag Processing Tag */
@Override
public void setProcessingTag (java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
/** Get Processing Tag.
@return Processing Tag */
@Override
public java.lang.String getProcessingTag ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProcessingTag);
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty) | {
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_Log.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** TokenType AD_Reference_ID=397 */
public static final int TOKENTYPE_AD_Reference_ID=397;
/** SQL Command = Q */
public static final String TOKENTYPE_SQLCommand = "Q"; | /** Internal Link = I */
public static final String TOKENTYPE_InternalLink = "I";
/** External Link = E */
public static final String TOKENTYPE_ExternalLink = "E";
/** Style = S */
public static final String TOKENTYPE_Style = "S";
/** Set TokenType.
@param TokenType
Wiki Token Type
*/
public void setTokenType (String TokenType)
{
set_Value (COLUMNNAME_TokenType, TokenType);
}
/** Get TokenType.
@return Wiki Token Type
*/
public String getTokenType ()
{
return (String)get_Value(COLUMNNAME_TokenType);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WikiToken.java | 1 |
请完成以下Java代码 | public int retrieveLastLineNo(DocumentQuery query)
{
return 0;
}
private static final class DataEntryDocumentValuesSupplier implements DocumentValuesSupplier
{
private final DataEntryRecord dataEntryRecord;
private final DataEntryWebuiTools dataEntryWebuiTools;
private DataEntryDocumentValuesSupplier(
@NonNull final DataEntryRecord dataEntryRecord,
@NonNull DataEntryWebuiTools dataEntryWebuiTools)
{
this.dataEntryWebuiTools = dataEntryWebuiTools;
this.dataEntryRecord = dataEntryRecord;
}
@Override
public DocumentId getDocumentId()
{ | final DocumentId documentId = DataEntrySubTabBindingRepository.createDocumentId(
dataEntryRecord.getDataEntrySubTabId(),
dataEntryRecord.getMainRecord());
return documentId;
}
@Override
public String getVersion()
{
return VERSION_DEFAULT;
}
@Override
public Object getValue(@NonNull final DocumentFieldDescriptor fieldDescriptor)
{
return dataEntryWebuiTools.extractDataEntryValueForField(dataEntryRecord, fieldDescriptor);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntrySubTabBindingRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomWebSecurityConfigurer {
public AuthenticationConverter authenticationConverter() {
return new BasicAuthenticationConverter();
}
public AuthenticationManagerResolver<HttpServletRequest> resolver() {
return request -> {
if (request
.getPathInfo()
.startsWith("/employee")) {
return employeesAuthenticationManager();
}
return customersAuthenticationManager();
};
}
public AuthenticationManager customersAuthenticationManager() {
return authentication -> {
if (isCustomer(authentication)) {
return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
}
throw new UsernameNotFoundException(authentication
.getPrincipal()
.toString());
};
}
private boolean isCustomer(Authentication authentication) {
return (authentication
.getPrincipal()
.toString()
.startsWith("customer"));
}
private boolean isEmployee(Authentication authentication) {
return (authentication
.getPrincipal()
.toString()
.startsWith("employee"));
}
private AuthenticationFilter authenticationFilter() {
AuthenticationFilter filter = new AuthenticationFilter(
resolver(), authenticationConverter());
filter.setSuccessHandler((request, response, auth) -> {}); | return filter;
}
private AuthenticationManager employeesAuthenticationManager() {
return authentication -> {
if (isEmployee(authentication)) {
return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
}
throw new UsernameNotFoundException(authentication
.getPrincipal()
.toString());
};
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterBefore(authenticationFilter(), BasicAuthenticationFilter.class);
return http.build();
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\authresolver\CustomWebSecurityConfigurer.java | 2 |
请完成以下Java代码 | private class POReturningAfterInsertLoader implements ISqlUpdateReturnProcessor
{
private final List<String> columnNames;
private final StringBuilder sqlReturning;
public POReturningAfterInsertLoader()
{
this.columnNames = new ArrayList<>();
this.sqlReturning = new StringBuilder();
}
public void addColumnName(final String columnName)
{
// Make sure column was not already added
if (columnNames.contains(columnName))
{
return;
}
columnNames.add(columnName);
if (sqlReturning.length() > 0)
{
sqlReturning.append(", ");
}
sqlReturning.append(columnName);
}
public String getSqlReturning()
{
return sqlReturning.toString();
}
public boolean hasColumnNames()
{
return !columnNames.isEmpty();
}
@Override | public void process(final ResultSet rs) throws SQLException
{
for (final String columnName : columnNames)
{
final Object value = rs.getObject(columnName);
// NOTE: it is also setting the ID if applies
set_ValueNoCheck(columnName, value);
}
}
@Override
public String toString()
{
return "POReturningAfterInsertLoader [columnNames=" + columnNames + "]";
}
}
} // PO | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\PO.java | 1 |
请完成以下Java代码 | public ImmutableList<WebuiPickHUResult> pick(final List<ProductsToPickRow> selectedRows)
{
return streamRowsEligibleForPicking(selectedRows)
.map(row -> {
final PickHUResult result = pickingCandidateService.pickHU(createPickRequest(row));
return WebuiPickHUResult.of(row.getId(), result.getPickingCandidate());
})
.collect(ImmutableList.toImmutableList());
}
public ImmutableList<WebuiPickHUResult> setPackingInstruction(final List<ProductsToPickRow> selectedRows, final PackToSpec packToSpec)
{
final Map<PickingCandidateId, DocumentId> rowIdsByPickingCandidateId = streamRowsEligibleForPacking(selectedRows)
.collect(ImmutableMap.toImmutableMap(ProductsToPickRow::getPickingCandidateId, ProductsToPickRow::getId));
final Set<PickingCandidateId> pickingCandidateIds = rowIdsByPickingCandidateId.keySet();
final List<PickingCandidate> pickingCandidates = pickingCandidateService.setHuPackingInstructionId(pickingCandidateIds, packToSpec);
return pickingCandidates.stream()
.map(cand -> WebuiPickHUResult.of(rowIdsByPickingCandidateId.get(cand.getId()), cand))
.collect(ImmutableList.toImmutableList());
}
public boolean anyRowsEligibleForPacking(final List<ProductsToPickRow> selectedRows)
{
return streamRowsEligibleForPacking(selectedRows).findAny().isPresent();
}
private Stream<ProductsToPickRow> streamRowsEligibleForPacking(final List<ProductsToPickRow> selectedRows)
{
return selectedRows
.stream() | .filter(ProductsToPickRow::isEligibleForPacking);
}
public boolean noRowsEligibleForPicking(final List<ProductsToPickRow> selectedRows)
{
return !streamRowsEligibleForPicking(selectedRows).findAny().isPresent();
}
@NonNull
private Stream<ProductsToPickRow> streamRowsEligibleForPicking(final List<ProductsToPickRow> selectedRows)
{
return selectedRows
.stream()
.filter(ProductsToPickRow::isEligibleForPicking);
}
private PickRequest createPickRequest(final ProductsToPickRow row)
{
final PickingConfigV2 pickingConfig = getPickingConfig();
return createPickRequest(row, pickingConfig.isPickingReviewRequired());
}
protected final PickingConfigV2 getPickingConfig()
{
return pickingConfigRepo.getPickingConfig();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\rows\ProductsToPickRowsService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getLastServiceDate() {
return lastServiceDate;
}
public void setLastServiceDate(String lastServiceDate) {
this.lastServiceDate = lastServiceDate;
}
public DeviceToCreateMaintenances nextServiceDate(String nextServiceDate) {
this.nextServiceDate = nextServiceDate;
return this;
}
/**
* Nächste Prüfung
* @return nextServiceDate
**/
@Schema(example = "01.12.2020", description = "Nächste Prüfung")
public String getNextServiceDate() {
return nextServiceDate;
}
public void setNextServiceDate(String nextServiceDate) {
this.nextServiceDate = nextServiceDate;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceToCreateMaintenances deviceToCreateMaintenances = (DeviceToCreateMaintenances) o;
return Objects.equals(this.maintenanceCode, deviceToCreateMaintenances.maintenanceCode) &&
Objects.equals(this.maintenanceInterval, deviceToCreateMaintenances.maintenanceInterval) && | Objects.equals(this.lastServiceDate, deviceToCreateMaintenances.lastServiceDate) &&
Objects.equals(this.nextServiceDate, deviceToCreateMaintenances.nextServiceDate);
}
@Override
public int hashCode() {
return Objects.hash(maintenanceCode, maintenanceInterval, lastServiceDate, nextServiceDate);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceToCreateMaintenances {\n");
sb.append(" maintenanceCode: ").append(toIndentedString(maintenanceCode)).append("\n");
sb.append(" maintenanceInterval: ").append(toIndentedString(maintenanceInterval)).append("\n");
sb.append(" lastServiceDate: ").append(toIndentedString(lastServiceDate)).append("\n");
sb.append(" nextServiceDate: ").append(toIndentedString(nextServiceDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceToCreateMaintenances.java | 2 |
请完成以下Java代码 | public static <T> ConstantQueryFilter<T> of(final boolean value)
{
return (ConstantQueryFilter<T>)(value ? TRUE : FALSE);
}
/* package */static final String SQL_TRUE = "1=1";
/* package */static final String SQL_FALSE = "1=0";
private final boolean value;
private ConstantQueryFilter(final boolean value)
{
this.value = value;
}
@Override
public String toString()
{
return String.valueOf(value);
}
@Override
public String getSql()
{
return value ? SQL_TRUE : SQL_FALSE;
}
@Override | public List<Object> getSqlParams(final Properties ctx)
{
return getSqlParams();
}
public List<Object> getSqlParams()
{
return Collections.emptyList();
}
@Override
public boolean accept(final T model)
{
return value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\ConstantQueryFilter.java | 1 |
请完成以下Java代码 | public List<I_C_RfQResponseLine> retrieveAllActiveResponseLines(final Properties ctx)
{
return retrieveActiveResponseLinesQuery(ctx)
.create()
.list(I_C_RfQResponseLine.class);
}
private IQueryBuilder<I_C_RfQResponseLine> retrieveActiveResponseLinesQuery(final Properties ctx)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_RfQResponseLine.class, ctx, ITrx.TRXNAME_ThreadInherited)
.addOnlyActiveRecordsFilter()
.addInArrayOrAllFilter(I_C_RfQResponseLine.COLUMNNAME_DocStatus, X_C_RfQResponseLine.DOCSTATUS_Drafted)
.orderBy()
.addColumn(I_C_RfQResponseLine.COLUMNNAME_C_RfQResponse_ID)
.addColumn(I_C_RfQResponseLine.COLUMNNAME_Line)
.addColumn(I_C_RfQResponseLine.COLUMNNAME_C_RfQResponseLine_ID)
.endOrderBy();
} | @Override
public List<I_C_RfQResponseLine> retrieveResponseLines(final I_C_RfQResponse rfqResponse)
{
return Services.get(IRfqDAO.class).retrieveResponseLines(rfqResponse, I_C_RfQResponseLine.class);
}
@Override
public List<I_C_RfQResponseLineQty> retrieveResponseLineQtys(de.metas.rfq.model.I_C_RfQResponseLine rfqResponseLine)
{
return Services.get(IRfqDAO.class).retrieveResponseQtys(rfqResponseLine);
}
@Override
public I_C_RfQResponseLineQty retrieveResponseLineQty(de.metas.rfq.model.I_C_RfQResponseLine rfqResponseLine, final Date date)
{
return Services.get(IRfqDAO.class).retrieveResponseQty(rfqResponseLine, date);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\PMM_RfQ_DAO.java | 1 |
请完成以下Java代码 | public class X_U_RoleMenu extends PO implements I_U_RoleMenu, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_U_RoleMenu (Properties ctx, int U_RoleMenu_ID, String trxName)
{
super (ctx, U_RoleMenu_ID, trxName);
/** if (U_RoleMenu_ID == 0)
{
setAD_Role_ID (0);
setU_RoleMenu_ID (0);
setU_WebMenu_ID (0);
} */
}
/** Load Constructor */
public X_U_RoleMenu (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_U_RoleMenu[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_Role getAD_Role() throws RuntimeException
{
return (I_AD_Role)MTable.get(getCtx(), I_AD_Role.Table_Name)
.getPO(getAD_Role_ID(), get_TrxName()); }
/** Set Role.
@param AD_Role_ID
Responsibility Role
*/
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Role.
@return Responsibility Role
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Role Menu.
@param U_RoleMenu_ID Role Menu */
public void setU_RoleMenu_ID (int U_RoleMenu_ID)
{
if (U_RoleMenu_ID < 1)
set_ValueNoCheck (COLUMNNAME_U_RoleMenu_ID, null);
else
set_ValueNoCheck (COLUMNNAME_U_RoleMenu_ID, Integer.valueOf(U_RoleMenu_ID));
}
/** Get Role Menu.
@return Role Menu */
public int getU_RoleMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_RoleMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_U_WebMenu getU_WebMenu() throws RuntimeException
{
return (I_U_WebMenu)MTable.get(getCtx(), I_U_WebMenu.Table_Name)
.getPO(getU_WebMenu_ID(), get_TrxName()); }
/** Set Web Menu.
@param U_WebMenu_ID Web Menu */
public void setU_WebMenu_ID (int U_WebMenu_ID)
{
if (U_WebMenu_ID < 1)
set_Value (COLUMNNAME_U_WebMenu_ID, null);
else
set_Value (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID));
}
/** Get Web Menu.
@return Web Menu */
public int getU_WebMenu_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_RoleMenu.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof BasicStudent))
return false;
BasicStudent student = (BasicStudent) o;
return Objects.equals(name, student.name) && Objects.equals(major, student.major) && Objects.equals(concentration, student.concentration);
}
@Override
public int hashCode() {
return Objects.hash(name, major, concentration);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public String getConcentration() {
return concentration;
}
public void setConcentration(String concentration) {
this.concentration = concentration;
}
} | repos\tutorials-master\json-modules\gson-2\src\main\java\com\baeldung\gson\multiplefields\BasicStudent.java | 1 |
请完成以下Java代码 | public int getDataEntry_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.dataentry.model.I_DataEntry_Section getDataEntry_Section() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class);
}
@Override
public void setDataEntry_Section(de.metas.dataentry.model.I_DataEntry_Section DataEntry_Section)
{
set_ValueFromPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class, DataEntry_Section);
}
/** Set Sektion.
@param DataEntry_Section_ID Sektion */
@Override
public void setDataEntry_Section_ID (int DataEntry_Section_ID)
{
if (DataEntry_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, Integer.valueOf(DataEntry_Section_ID));
}
/** Get Sektion.
@return Sektion */
@Override | public int getDataEntry_Section_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Section_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Line.java | 1 |
请完成以下Java代码 | public Method getReadMethod()
{
return readMethod;
}
@Override
public Method getWriteMethod()
{
return writeMethod;
}
void setWriteMethod(final Method writeMethod)
{
this.writeMethod = writeMethod;
}
void setSeqNo(final int seqNo)
{
this.seqNo = seqNo;
}
@Override
public int getSeqNo()
{
return seqNo;
}
@Override
public String getLookupTableName()
{
return lookupTableName;
}
void setLookupTableName(final String lookupTableName)
{
this.lookupTableName = lookupTableName;
}
@Override
public String getLookupColumnName()
{
return lookupColumnName;
}
void setLookupColumnName(final String lookupColumnName)
{
this.lookupColumnName = lookupColumnName; | }
@Override
public String getPrototypeValue()
{
return prototypeValue;
}
void setPrototypeValue(final String prototypeValue)
{
this.prototypeValue = prototypeValue;
}
public int getDisplayType(final int defaultDisplayType)
{
return displayType > 0 ? displayType : defaultDisplayType;
}
public int getDisplayType()
{
return displayType;
}
void setDisplayType(int displayType)
{
this.displayType = displayType;
}
public boolean isSelectionColumn()
{
return selectionColumn;
}
public void setSelectionColumn(boolean selectionColumn)
{
this.selectionColumn = selectionColumn;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableColumnInfo.java | 1 |
请完成以下Java代码 | public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Tags.
@param Tags Tags */
@Override
public void setTags (java.lang.String Tags)
{
set_Value (COLUMNNAME_Tags, Tags);
}
/** Get Tags.
@return Tags */
@Override
public java.lang.String getTags ()
{
return (java.lang.String)get_Value(COLUMNNAME_Tags);
}
/**
* Type AD_Reference_ID=540751
* Reference name: AD_AttachmentEntry_Type
*/
public static final int TYPE_AD_Reference_ID=540751;
/** Data = D */
public static final String TYPE_Data = "D";
/** URL = U */
public static final String TYPE_URL = "U";
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */ | @Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
@Override
public void setURL (java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
@Override
public java.lang.String getURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_Log.java | 1 |
请完成以下Java代码 | public Builder setUser1_ID(final int user1_ID)
{
setSegmentValue(AcctSegmentType.UserList1, user1_ID);
return this;
}
public Builder setUser2_ID(final int user2_ID)
{
setSegmentValue(AcctSegmentType.UserList2, user2_ID);
return this;
}
public Builder setUserElement1_ID(final int userElement1_ID)
{
setSegmentValue(AcctSegmentType.UserElement1, userElement1_ID);
return this;
}
public Builder setUserElement2_ID(final int userElement2_ID)
{
setSegmentValue(AcctSegmentType.UserElement2, userElement2_ID);
return this;
}
public Builder setUserElementString1(final String userElementString1)
{
setSegmentValue(AcctSegmentType.UserElementString1, userElementString1);
return this;
}
public Builder setUserElementString2(final String userElementString2)
{
setSegmentValue(AcctSegmentType.UserElementString2, userElementString2);
return this; | }
public Builder setUserElementString3(final String userElementString3)
{
setSegmentValue(AcctSegmentType.UserElementString3, userElementString3);
return this;
}
public Builder setUserElementString4(final String userElementString4)
{
setSegmentValue(AcctSegmentType.UserElementString4, userElementString4);
return this;
}
public Builder setUserElementString5(final String userElementString5)
{
setSegmentValue(AcctSegmentType.UserElementString5, userElementString5);
return this;
}
public Builder setUserElementString6(final String userElementString6)
{
setSegmentValue(AcctSegmentType.UserElementString6, userElementString6);
return this;
}
public Builder setUserElementString7(final String userElementString7)
{
setSegmentValue(AcctSegmentType.UserElementString7, userElementString7);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountDimension.java | 1 |
请完成以下Java代码 | public int getAD_PrinterRouting_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterRouting_ID);
}
@Override
public void setC_Print_Job_Detail_ID (int C_Print_Job_Detail_ID)
{
if (C_Print_Job_Detail_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Print_Job_Detail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Print_Job_Detail_ID, Integer.valueOf(C_Print_Job_Detail_ID));
}
@Override
public int getC_Print_Job_Detail_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Detail_ID);
}
@Override
public de.metas.printing.model.I_C_Print_Job_Line getC_Print_Job_Line()
{
return get_ValueAsPO(COLUMNNAME_C_Print_Job_Line_ID, de.metas.printing.model.I_C_Print_Job_Line.class);
}
@Override
public void setC_Print_Job_Line(de.metas.printing.model.I_C_Print_Job_Line C_Print_Job_Line)
{
set_ValueFromPO(COLUMNNAME_C_Print_Job_Line_ID, de.metas.printing.model.I_C_Print_Job_Line.class, C_Print_Job_Line);
} | @Override
public void setC_Print_Job_Line_ID (int C_Print_Job_Line_ID)
{
if (C_Print_Job_Line_ID < 1)
set_Value (COLUMNNAME_C_Print_Job_Line_ID, null);
else
set_Value (COLUMNNAME_C_Print_Job_Line_ID, Integer.valueOf(C_Print_Job_Line_ID));
}
@Override
public int getC_Print_Job_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Print_Job_Line_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Detail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LocalEdqsStateService implements EdqsStateService {
private final EdqsRocksDb db;
private final DiscoveryService discoveryService;
@Autowired @Lazy
private EdqsProcessor processor;
private PartitionedQueueConsumerManager<TbProtoQueueMsg<ToEdqsMsg>> eventConsumer;
private List<PartitionedQueueConsumerManager<?>> otherConsumers;
private boolean ready = false;
@Override
public void init(PartitionedQueueConsumerManager<TbProtoQueueMsg<ToEdqsMsg>> eventConsumer, List<PartitionedQueueConsumerManager<?>> otherConsumers) {
this.eventConsumer = eventConsumer;
this.otherConsumers = otherConsumers;
}
@Override
public void process(Set<TopicPartitionInfo> partitions) {
if (!ready) {
db.forEach((key, value) -> {
try {
ToEdqsMsg edqsMsg = ToEdqsMsg.parseFrom(value);
log.trace("[{}] Restored msg from RocksDB: {}", key, edqsMsg);
processor.process(edqsMsg, false);
} catch (Exception e) {
log.error("[{}] Failed to restore value", key, e);
}
});
log.info("Restore completed");
}
ready = true;
discoveryService.setReady(true);
eventConsumer.update(withTopic(partitions, eventConsumer.getTopic()));
for (PartitionedQueueConsumerManager<?> consumer : otherConsumers) { | consumer.update(withTopic(partitions, consumer.getTopic()));
}
}
@Override
public void save(TenantId tenantId, ObjectType type, String key, EdqsEventType eventType, ToEdqsMsg msg) {
log.trace("Save to RocksDB: {} {} {} {}", tenantId, type, key, msg);
try {
if (eventType == EdqsEventType.DELETED) {
db.delete(key);
} else {
db.put(key, msg.toByteArray());
}
} catch (Exception e) {
log.error("[{}] Failed to save event {}", key, msg, e);
}
}
@Override
public boolean isReady() {
return ready;
}
@Override
public void stop() {
}
} | repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\state\LocalEdqsStateService.java | 2 |
请完成以下Java代码 | public void start() throws Exception {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#stop()
*/
@Override
public void stop() throws Exception {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#destroy()
*/
@Override
public void destroy() {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#getServer()
*/
@Override
public Server getServer() {
return null;
}
/* | * (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
* org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
LOG.info("Received a new request");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
* Server)
*/
@Override
public void setServer(Server server) {
}
} | repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\jetty\programmatic\LoggingRequestHandler.java | 1 |
请完成以下Java代码 | public static void setBaseLanguage()
{
Language.setBaseLanguage(() -> Services.get(ILanguageDAO.class).retrieveBaseLanguage());
//
// Try to initialize the base language, if possible.
try
{
Language.getBaseLanguage();
}
catch (Exception e)
{
s_log.warn("Cannot initialize base language. Skip.", e);
}
}
// metas: end
public MLanguage(final Properties ctx, final int AD_Language_ID, final String trxName)
{
super(ctx, AD_Language_ID, trxName);
}
public MLanguage(final Properties ctx, final ResultSet rs, final String trxName)
{
super(ctx, rs, trxName);
}
@Override
public String toString()
{
return "MLanguage[" + getAD_Language() + "-" + getName()
+ ",Language=" + getLanguageISO() + ",Country=" + getCountryCode()
+ "]";
}
@Override
protected boolean beforeSave(final boolean newRecord)
{
if (is_ValueChanged(COLUMNNAME_DatePattern))
{ | assertValidDatePattern(this);
}
return true;
}
private static final void assertValidDatePattern(I_AD_Language language)
{
final String datePattern = language.getDatePattern();
if (Check.isEmpty(datePattern))
{
return; // OK
}
if (datePattern.indexOf("MM") == -1)
{
throw new AdempiereException("@Error@ @DatePattern@ - No Month (MM)");
}
if (datePattern.indexOf("dd") == -1)
{
throw new AdempiereException("@Error@ @DatePattern@ - No Day (dd)");
}
if (datePattern.indexOf("yy") == -1)
{
throw new AdempiereException("@Error@ @DatePattern@ - No Year (yy)");
}
final Locale locale = new Locale(language.getLanguageISO(), language.getCountryCode());
final SimpleDateFormat dateFormat = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale);
try
{
dateFormat.applyPattern(datePattern);
}
catch (final Exception e)
{
throw new AdempiereException("@Error@ @DatePattern@ - " + e.getMessage(), e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLanguage.java | 1 |
请完成以下Java代码 | public class PollingTask implements Runnable, Delayed {
private static final Logger LOG = LoggerFactory.getLogger(PollingTask.class);
private long executeTime;
private PollingPersist pollingPersist = AppOrderPollingApplication.cachePollingPersist;
private RpOrderResultQueryVo rpOrderResultQueryVo;
public PollingTask() {
}
public PollingTask(RpOrderResultQueryVo rpOrderResultQueryVo) {
super();
this.rpOrderResultQueryVo = rpOrderResultQueryVo;
this.executeTime = getExecuteTime(rpOrderResultQueryVo);
}
/**
* 计算任务允许执行的开始时间(executeTime).<br/>
*
* @param rpOrderResultQueryVo
* @return
*/
private long getExecuteTime(RpOrderResultQueryVo rpOrderResultQueryVo) {
long lastNotifyTime = rpOrderResultQueryVo.getLastNotifyTime().getTime(); // 最后通知时间(上次通知时间)
Integer notifyTimes = rpOrderResultQueryVo.getNotifyTimes(); // 已通知次数
LOG.info("===>pollingTimes:{}", notifyTimes);
//Integer nextNotifyTimeInterval = pollingParam.getNotifyParams().get(notifyTimes + 1); // 当前发送次数对应的时间间隔数(分钟数)
Integer nextNotifyTimeInterval = rpOrderResultQueryVo.getNotifyRuleMap().get(notifyTimes + 1); // 当前发送次数对应的时间间隔数(分钟数)
long nextNotifyTime = (nextNotifyTimeInterval == null ? 0 : nextNotifyTimeInterval * 1000) + lastNotifyTime;
LOG.info("===>notify id:{}, nextNotifyTime:{}", rpOrderResultQueryVo.getId(), DateUtils.formatDate(new Date(nextNotifyTime), "yyyy-MM-dd HH:mm:ss SSS"));
return nextNotifyTime;
} | /**
* 比较当前时间(task.executeTime)与任务允许执行的开始时间(executeTime).<br/>
* 如果当前时间到了或超过任务允许执行的开始时间,那么就返回-1,可以执行。
*/
public int compareTo(Delayed o) {
PollingTask task = (PollingTask) o;
return executeTime > task.executeTime ? 1 : (executeTime < task.executeTime ? -1 : 0);
}
public long getDelay(TimeUnit unit) {
return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
/**
* 执行通知处理.
*/
public void run() {
pollingPersist.getOrderResult(rpOrderResultQueryVo);
}
} | repos\roncoo-pay-master\roncoo-pay-app-order-polling\src\main\java\com\roncoo\pay\app\polling\core\PollingTask.java | 1 |
请完成以下Java代码 | abstract class AbstractExpressionBasedMethodConfigAttribute implements ConfigAttribute {
private final @Nullable Expression filterExpression;
private final @Nullable Expression authorizeExpression;
/**
* Parses the supplied expressions as Spring-EL.
*/
AbstractExpressionBasedMethodConfigAttribute(String filterExpression, String authorizeExpression)
throws ParseException {
Assert.isTrue(filterExpression != null || authorizeExpression != null,
"Filter and authorization Expressions cannot both be null");
SpelExpressionParser parser = new SpelExpressionParser();
this.filterExpression = (filterExpression != null) ? parser.parseExpression(filterExpression) : null;
this.authorizeExpression = (authorizeExpression != null) ? parser.parseExpression(authorizeExpression) : null;
}
AbstractExpressionBasedMethodConfigAttribute(Expression filterExpression, Expression authorizeExpression)
throws ParseException {
Assert.isTrue(filterExpression != null || authorizeExpression != null,
"Filter and authorization Expressions cannot both be null");
this.filterExpression = (filterExpression != null) ? filterExpression : null;
this.authorizeExpression = (authorizeExpression != null) ? authorizeExpression : null; | }
Expression getFilterExpression() {
return this.filterExpression;
}
Expression getAuthorizeExpression() {
return this.authorizeExpression;
}
@Override
public @Nullable String getAttribute() {
return null;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\expression\method\AbstractExpressionBasedMethodConfigAttribute.java | 1 |
请完成以下Java代码 | public static ShipmentCosts extractAccountableFrom(@NonNull final CostDetailCreateResultsList results, @NonNull final AcctSchema acctSchema)
{
return builder()
.shippedButNotNotified(Objects.requireNonNull(results.getAmtAndQtyToPost(CostAmountType.MAIN, acctSchema).map(CostAmountAndQty::negate).orElse(null)))
.build();
}
public static ShipmentCosts extractFrom(@NonNull final CostDetailCreateRequest request)
{
final CostAmountAndQty amtAndQty = CostAmountAndQty.of(request.getAmt(), request.getQty());
final ShipmentCosts shipmentCosts;
if (request.getAmtType() == CostAmountType.MAIN)
{
shipmentCosts = builder().shippedButNotNotified(amtAndQty.negate()).build();
}
else
{
throw new IllegalArgumentException();
} | return shipmentCosts;
}
public interface CostAmountAndQtyAndTypeMapper
{
CostDetailCreateResult shippedButNotNotified(CostAmountAndQty amtAndQty, CostAmountType type);
}
public CostDetailCreateResultsList toCostDetailCreateResultsList(@NonNull final CostAmountAndQtyAndTypeMapper mapper)
{
final ArrayList<CostDetailCreateResult> resultsList = new ArrayList<>();
{
final CostDetailCreateResult result = mapper.shippedButNotNotified(shippedButNotNotified, CostAmountType.MAIN);
resultsList.add(Check.assumeNotNull(result, "result shall not be null"));
}
return CostDetailCreateResultsList.ofList(resultsList);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\ShipmentCosts.java | 1 |
请完成以下Java代码 | public static void throwIfPortBindingException(Exception ex, IntSupplier port) {
ifPortBindingException(ex, (bindException) -> {
throw new PortInUseException(port.getAsInt(), ex);
});
}
/**
* Perform an action if the given exception was caused by a "port in use"
* {@link BindException}.
* @param ex the source exception
* @param action the action to perform
* @since 2.2.7
*/
public static void ifPortBindingException(Exception ex, Consumer<BindException> action) {
ifCausedBy(ex, BindException.class, (bindException) -> {
// bind exception can be also thrown because an address can't be assigned
String message = bindException.getMessage();
if (message != null && message.toLowerCase(Locale.ROOT).contains("in use")) {
action.accept(bindException);
}
});
}
/**
* Perform an action if the given exception was caused by a specific exception type.
* @param <E> the cause exception type
* @param ex the source exception | * @param causedBy the required cause type
* @param action the action to perform
* @since 2.2.7
*/
@SuppressWarnings("unchecked")
public static <E extends Exception> void ifCausedBy(Exception ex, Class<E> causedBy, Consumer<E> action) {
Throwable candidate = ex;
while (candidate != null) {
if (causedBy.isInstance(candidate)) {
action.accept((E) candidate);
return;
}
candidate = candidate.getCause();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\PortInUseException.java | 1 |
请完成以下Java代码 | @Override public T visitProg(LabeledExprParser.ProgContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPrintExpr(LabeledExprParser.PrintExprContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAssign(LabeledExprParser.AssignContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitBlank(LabeledExprParser.BlankContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitParens(LabeledExprParser.ParensContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMulDiv(LabeledExprParser.MulDivContext ctx) { return visitChildren(ctx); } | /**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAddSub(LabeledExprParser.AddSubContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitId(LabeledExprParser.IdContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitInt(LabeledExprParser.IntContext ctx) { return visitChildren(ctx); }
} | repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprBaseVisitor.java | 1 |
请完成以下Java代码 | public int calculateUsingSwitch(int a, int b, String operator) {
int result = 0;
switch (operator) {
case "add":
result = a + b;
break;
case "multiply":
result = a * b;
break;
case "divide":
result = a / b;
break;
case "subtract":
result = a - b;
break;
case "modulo":
result = a % b;
break;
default:
result = Integer.MIN_VALUE;
}
return result;
}
public int calculateUsingSwitch(int a, int b, Operator operator) {
int result = 0;
switch (operator) {
case ADD:
result = a + b;
break;
case MULTIPLY:
result = a * b;
break;
case DIVIDE:
result = a / b;
break;
case SUBTRACT:
result = a - b;
break;
case MODULO:
result = a % b;
break; | default:
result = Integer.MIN_VALUE;
}
return result;
}
public int calculate(int a, int b, Operator operator) {
return operator.apply(a, b);
}
public int calculateUsingFactory(int a, int b, String operation) {
Operation targetOperation = OperatorFactory.getOperation(operation)
.orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
return targetOperation.apply(a, b);
}
public int calculate(Command command) {
return command.execute();
}
} | repos\tutorials-master\patterns-modules\design-patterns-creational\src\main\java\com\baeldung\reducingIfElse\Calculator.java | 1 |
请完成以下Java代码 | public int getErrorCode() {
return errorCode;
}
public String getErrorCodes() {
return errorCodes;
}
public ServiceException(InfoCode infoCode){
super(infoCode.getMsg());
this.errorCode = infoCode.getStatus();
}
public ServiceException(int errorCode, String msg) {
super(msg);
this.errorCode = errorCode;
} | public ServiceException(String errorCode, String msg) {
super(msg);
this.errorCodes = errorCode;
}
public ServiceException(int errorCode, String msg, Throwable e) {
super(msg, e);
this.errorCode = errorCode;
}
public ServiceException(int errorCode, Throwable e) {
super(e);
this.errorCode = errorCode;
}
} | repos\springBoot-master\abel-util\src\main\java\cn\abel\exception\ServiceException.java | 1 |
请完成以下Java代码 | public static boolean isAuthenticated() {
return getSubject() != null && getSubject().isAuthenticated();
}
/**
* 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。。
*
* @return 没有通过身份验证:true,否则false
*/
public static boolean notAuthenticated() {
return !isAuthenticated();
}
/**
* 认证通过或已记住的用户。与guset搭配使用。
*
* @return 用户:true,否则 false
*/
public static boolean isUser() {
return getSubject() != null && getSubject().getPrincipal() != null;
}
/**
* 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用
*
* @return 访客:true,否则false
*/
public static boolean isGuest() { | return !isUser();
}
/**
* 输出当前用户信息,通常为登录帐号信息。
*
* @return 当前用户信息
*/
public static String principal() {
if (getSubject() != null) {
Object principal = getSubject().getPrincipal();
return principal.toString();
}
return "";
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\shiro\ShiroKit.java | 1 |
请完成以下Java代码 | protected static void addFeature(String feature, FeatureMap featureMap, List<Integer> featureList)
{
int featureId = featureMap.idOf(feature);
if (featureId != -1)
featureList.add(featureId);
}
/**
* 样本
*/
static class Instance
{
/**
* 特征向量
*/
List<Integer> x;
/**
* 标签
*/
int y;
public Instance(List<Integer> x, int y)
{
this.x = x;
this.y = y;
}
}
/**
* 准确率度量
*/ | static class BinaryClassificationFMeasure
{
float P, R, F1;
public BinaryClassificationFMeasure(float p, float r, float f1)
{
P = p;
R = r;
F1 = f1;
}
@Override
public String toString()
{
return String.format("P=%.2f R=%.2f F1=%.2f", P, R, F1);
}
}
public LinearModel getModel()
{
return model;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronClassifier.java | 1 |
请完成以下Java代码 | private Function<DynamicMessage, Object> serialiseGRPCResponse() {
return gRPCResponse -> {
try {
return objectReader
.readValue(JsonFormat.printer().omittingInsignificantWhitespace().print(gRPCResponse));
}
catch (IOException e) {
throw new RuntimeException(e);
}
};
}
private Flux<JsonNode> deserializeJSONRequest() {
return exchange.getRequest().getBody().mapNotNull(dataBufferBody -> {
if (dataBufferBody.capacity() == 0) {
return objectNode;
}
ResolvableType targetType = ResolvableType.forType(JsonNode.class);
return new JacksonJsonDecoder().decode(dataBufferBody, targetType, null, null);
}).cast(JsonNode.class);
}
private Function<Object, DataBuffer> wrapGRPCResponse() { | return jsonResponse -> new NettyDataBufferFactory(new PooledByteBufAllocator())
.wrap(Objects.requireNonNull(new ObjectMapper().writeValueAsBytes(jsonResponse)));
}
// We are creating this on every call, should optimize?
private ManagedChannel createChannelChannel(String host, int port) {
NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port);
try {
return grpcSslConfigurer.configureSsl(nettyChannelBuilder);
}
catch (SSLException e) {
throw new RuntimeException(e);
}
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\JsonToGrpcGatewayFilterFactory.java | 1 |
请完成以下Java代码 | 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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | public org.eevolution.model.I_HR_Process getReversal() throws RuntimeException
{
return (org.eevolution.model.I_HR_Process)MTable.get(getCtx(), org.eevolution.model.I_HR_Process.Table_Name)
.getPO(getReversal_ID(), get_TrxName()); }
/** Set Reversal ID.
@param Reversal_ID
ID of document reversal
*/
public void setReversal_ID (int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Integer.valueOf(Reversal_ID));
}
/** Get Reversal ID.
@return ID of document reversal
*/
public int getReversal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Reversal_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\eevolution\model\X_HR_Process.java | 1 |
请完成以下Java代码 | class SolarEvent {
@JsonProperty("event_name")
private String eventName;
@JsonProperty("date")
private String date;
@JsonProperty("coordinates")
private Coordinates coordinates;
@JsonProperty("type")
private String type;
@JsonProperty("class")
private String eventClass;
@JsonProperty("size")
private String size;
@JsonProperty("speed_km_per_s")
private int speedKmPerS;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEventClass() {
return eventClass;
}
public void setEventClass(String eventClass) {
this.eventClass = eventClass;
} | public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getSpeedKmPerS() {
return speedKmPerS;
}
public void setSpeedKmPerS(int speedKmPerS) {
this.speedKmPerS = speedKmPerS;
}
}
class Coordinates {
@JsonProperty("latitude")
private double latitude;
@JsonProperty("longitude")
private double longitude;
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
} | repos\tutorials-master\json-modules\json-operations\src\main\java\com\baeldung\sorting\SolarEvent.java | 1 |
请完成以下Java代码 | public List<DocumentType> getDocument() {
if (document == null) {
document = new ArrayList<DocumentType>();
}
return this.document;
}
/**
* Gets the value of the number property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumber() {
return number; | }
/**
* Sets the value of the number property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumber(BigInteger value) {
this.number = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DocumentsType.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.