instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
// Add HTTP to HTTPS redirect
tomcat.addAdditionalTomcatConnectors(httpToHttpRedirectConnector());
return tomcat;
}
/*
* We need redirect from HTTP to HTTPS. Without SSL, this application used port 8082. With SSL it will use port 8443.
* SO, any request for 8082 needs to be redirected to HTTPS on 8443. | * */
@Value("${server.port.http}")
private int serverPortHttp;
@Value("${server.port}")
private int serverPortHttps;
private Connector httpToHttpRedirectConnector(){
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(serverPortHttp);
connector.setSecure(false);
connector.setRedirectPort(serverPortHttps);
return connector;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\HttpsConfiguration.java | 1 |
请完成以下Java代码 | public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_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 setQtyDeliveredInInvoiceUOM (final @Nullable BigDecimal QtyDeliveredInInvoiceUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInInvoiceUOM, QtyDeliveredInInvoiceUOM);
}
@Override
public BigDecimal getQtyDeliveredInInvoiceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInInvoiceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyDeliveredInStockingUOM (final BigDecimal QtyDeliveredInStockingUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInStockingUOM, QtyDeliveredInStockingUOM);
} | @Override
public BigDecimal getQtyDeliveredInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyDeliveredInUOM (final BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInBPartnerUOM (final @Nullable BigDecimal QtyEnteredInBPartnerUOM)
{
set_Value (COLUMNNAME_QtyEnteredInBPartnerUOM, QtyEnteredInBPartnerUOM);
}
@Override
public BigDecimal getQtyEnteredInBPartnerUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInBPartnerUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine_InOutLine.java | 1 |
请完成以下Java代码 | public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
Integer heuristicValue;
heuristicValue = currentState.stream()
.mapToInt(stack -> {
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
})
.sum();
return heuristicValue;
}
/**
* This method returns heuristics value for a particular stack
*/
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
int stackHeuristics = 0; | boolean isPositioneCorrect = true;
int goalStartIndex = 0;
for (String currentBlock : stack) {
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
stackHeuristics += goalStartIndex;
} else {
stackHeuristics -= goalStartIndex;
isPositioneCorrect = false;
}
goalStartIndex++;
}
return stackHeuristics;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\hillclimbing\HillClimbing.java | 1 |
请完成以下Java代码 | private BigDecimal getBOMQty(final I_PP_Product_BOMLine bomLine)
{
if (bomLine.getQty_Attribute_ID() > 0)
{
final AttributeId attributeId = AttributeId.ofRepoId(bomLine.getQty_Attribute_ID());
final String attributeCode = attributesRepo.getAttributeCodeById(attributeId);
final BigDecimal qty = getAttributeValueAsBigDecimal(attributeCode, null);
if (qty != null)
{
return qty;
}
}
final BigDecimal qty = bomsBL.computeQtyMultiplier(bomLine, bomProductId);
return qty;
}
private BigDecimal getAttributeValueAsBigDecimal(final String attributeCode, final BigDecimal defaultValue)
{
if (asiAware == null)
{
return defaultValue;
}
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiAware.getM_AttributeSetInstance_ID());
if (asiId == null)
{
return defaultValue;
}
final ImmutableAttributeSet asi = asiBL.getImmutableAttributeSetById(asiId);
if (!asi.hasAttribute(attributeCode))
{
return defaultValue;
}
final BigDecimal value = asi.getValueAsBigDecimal(attributeCode);
return value != null ? value : defaultValue;
}
private List<I_PP_Product_BOMLine> getBOMLines()
{ | final I_PP_Product_BOM bom = getBOMIfEligible();
if (bom == null)
{
return ImmutableList.of();
}
return bomsRepo.retrieveLines(bom);
}
private I_PP_Product_BOM getBOMIfEligible()
{
final I_M_Product bomProduct = productsRepo.getById(bomProductId);
if (!bomProduct.isBOM())
{
return null;
}
return bomsRepo.getDefaultBOMByProductId(bomProductId)
.filter(this::isEligible)
.orElse(null);
}
private boolean isEligible(final I_PP_Product_BOM bom)
{
final BOMType bomType = BOMType.ofNullableCode(bom.getBOMType());
return BOMType.MakeToOrder.equals(bomType);
}
//
//
// ---
//
//
public static class BOMPriceCalculatorBuilder
{
public Optional<BOMPrices> calculate()
{
return build().calculate();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\BOMPriceCalculator.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setM_Product_AlbertaTherapy_ID (final int M_Product_AlbertaTherapy_ID)
{
if (M_Product_AlbertaTherapy_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaTherapy_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_AlbertaTherapy_ID, M_Product_AlbertaTherapy_ID);
}
@Override
public int getM_Product_AlbertaTherapy_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_AlbertaTherapy_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
/**
* Therapy AD_Reference_ID=541282
* Reference name: Therapy
*/
public static final int THERAPY_AD_Reference_ID=541282;
/** Unknown = 0 */
public static final String THERAPY_Unknown = "0";
/** ParenteralNutrition = 1 */
public static final String THERAPY_ParenteralNutrition = "1";
/** EnteralNutrition = 2 */
public static final String THERAPY_EnteralNutrition = "2";
/** Stoma = 3 */
public static final String THERAPY_Stoma = "3";
/** Tracheostoma = 4 */
public static final String THERAPY_Tracheostoma = "4";
/** Inkontinenz ableitend = 5 */
public static final String THERAPY_InkontinenzAbleitend = "5";
/** Wundversorgung = 6 */
public static final String THERAPY_Wundversorgung = "6";
/** IV-Therapien = 7 */
public static final String THERAPY_IV_Therapien = "7";
/** Beatmung = 8 */
public static final String THERAPY_Beatmung = "8";
/** Sonstiges = 9 */
public static final String THERAPY_Sonstiges = "9";
/** OSA = 10 */
public static final String THERAPY_OSA = "10";
/** Hustenhilfen = 11 */
public static final String THERAPY_Hustenhilfen = "11";
/** Absaugung = 12 */
public static final String THERAPY_Absaugung = "12";
/** Patientenüberwachung = 13 */
public static final String THERAPY_Patientenueberwachung = "13";
/** Sauerstoff = 14 */ | public static final String THERAPY_Sauerstoff = "14";
/** Inhalations- und Atemtherapie = 15 */
public static final String THERAPY_Inhalations_UndAtemtherapie = "15";
/** Lagerungshilfsmittel = 16 */
public static final String THERAPY_Lagerungshilfsmittel = "16";
/** Schmerztherapie = 17 */
public static final String THERAPY_Schmerztherapie = "17";
@Override
public void setTherapy (final String Therapy)
{
set_Value (COLUMNNAME_Therapy, Therapy);
}
@Override
public String getTherapy()
{
return get_ValueAsString(COLUMNNAME_Therapy);
}
@Override
public void setValue (final @Nullable String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_M_Product_AlbertaTherapy.java | 1 |
请完成以下Java代码 | private I_M_InOutLine getCreateInOutLineInDispute(final I_M_InOutLine originInOutLine, final ProductId productId)
{
final I_M_InOutLine originInOutLineInDispute = InterfaceWrapperHelper.create(inOutDAO.retrieveLineWithQualityDiscount(originInOutLine), I_M_InOutLine.class);
if (originInOutLineInDispute == null)
{
return null;
}
final I_M_InOutLine inoutLineInDispute = getCreateInOutLine(originInOutLineInDispute, productId);
inoutLineInDispute.setIsInDispute(true);
inoutLineInDispute.setQualityDiscountPercent(originInOutLineInDispute.getQualityDiscountPercent());
inoutLineInDispute.setQualityNote(originInOutLineInDispute.getQualityNote());
return inoutLineInDispute;
} | public Collection<I_M_InOutLine> getInOutLines()
{
return _inOutLines.values();
}
/**
* Make a unique key for the given product. This will serve in mapping the inout lines to their products.
*/
private static ArrayKey mkInOutLineKey(final I_M_InOutLine originInOutLine, @NonNull final ProductId productId)
{
return Util.mkKey(originInOutLine.getM_InOutLine_ID(), productId);
}
public boolean isEmpty()
{
return _inOutLines.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\AbstractQualityReturnsInOutLinesBuilder.java | 1 |
请完成以下Java代码 | public int getM_ProductPrice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductPrice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set packingmaterialname.
@param packingmaterialname packingmaterialname */
@Override
public void setpackingmaterialname (java.lang.String packingmaterialname)
{
set_ValueNoCheck (COLUMNNAME_packingmaterialname, packingmaterialname);
}
/** Get packingmaterialname.
@return packingmaterialname */
@Override
public java.lang.String getpackingmaterialname ()
{
return (java.lang.String)get_Value(COLUMNNAME_packingmaterialname);
}
/** Set Standardpreis.
@param PriceStd
Standardpreis
*/
@Override
public void setPriceStd (java.math.BigDecimal PriceStd)
{
set_ValueNoCheck (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standardpreis.
@return Standardpreis
*/
@Override
public java.math.BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Produktname.
@param ProductName
Name des Produktes
*/
@Override
public void setProductName (java.lang.String ProductName)
{ | set_ValueNoCheck (COLUMNNAME_ProductName, ProductName);
}
/** Get Produktname.
@return Name des Produktes
*/
@Override
public java.lang.String getProductName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductName);
}
/** Set Produktschlüssel.
@param ProductValue
Schlüssel des Produktes
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{
set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Produktschlüssel.
@return Schlüssel des Produktes
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (java.lang.String SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo);
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public java.lang.String getSeqNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_M_PriceList_V.java | 1 |
请完成以下Java代码 | public void setQty_Reported (final @Nullable BigDecimal Qty_Reported)
{
set_Value (COLUMNNAME_Qty_Reported, Qty_Reported);
}
@Override
public BigDecimal getQty_Reported()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty_Reported);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* Type AD_Reference_ID=540263
* Reference name: C_Flatrate_DataEntry Type
*/
public static final int TYPE_AD_Reference_ID=540263;
/** Invoicing_PeriodBased = IP */
public static final String TYPE_Invoicing_PeriodBased = "IP"; | /** Correction_PeriodBased = CP */
public static final String TYPE_Correction_PeriodBased = "CP";
/** Procurement_PeriodBased = PC */
public static final String TYPE_Procurement_PeriodBased = "PC";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_DataEntry.java | 1 |
请完成以下Java代码 | public boolean deleteAdminSettingsByTenantIdAndKey(TenantId tenantId, String key) {
log.trace("Executing deleteAdminSettings, tenantId [{}], key [{}]", tenantId, key);
Validator.validateString(key, k -> "Incorrect key " + k);
return adminSettingsDao.removeByTenantIdAndKey(tenantId.getId(), key);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
adminSettingsDao.removeByTenantId(tenantId.getId());
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
adminSettingsDao.removeById(tenantId, id.getId());
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(adminSettingsDao.findById(tenantId, entityId.getId()));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(adminSettingsDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
} | @Override
public EntityType getEntityType() {
return EntityType.ADMIN_SETTINGS;
}
private void dropTokenIfProviderInfoChanged(JsonNode newJsonValue, JsonNode oldJsonValue) {
if (newJsonValue.has("enableOauth2") && newJsonValue.get("enableOauth2").asBoolean()) {
if (!newJsonValue.get("providerId").equals(oldJsonValue.get("providerId")) ||
!newJsonValue.get("clientId").equals(oldJsonValue.get("clientId")) ||
!newJsonValue.get("clientSecret").equals(oldJsonValue.get("clientSecret")) ||
!newJsonValue.get("redirectUri").equals(oldJsonValue.get("redirectUri")) ||
(newJsonValue.has("providerTenantId") && !newJsonValue.get("providerTenantId").equals(oldJsonValue.get("providerTenantId")))) {
((ObjectNode) newJsonValue).put("tokenGenerated", false);
((ObjectNode) newJsonValue).remove("refreshToken");
((ObjectNode) newJsonValue).remove("refreshTokenExpires");
}
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\settings\AdminSettingsServiceImpl.java | 1 |
请完成以下Java代码 | public void setCalY(final int calY)
{
this.calY = calY;
}
/**
* Prints the PDF for the given printing context, moving it according to what was set with {@link #setCalX(int)} and {@link #setCalY(int)}.
* <p>
* Generally don't resize the PDF to fit to the page format. The jasper was made to have a particular size.<br>
* However, as we always scaled to the page format in the past and some jaspers might rely on it, we do scale *down* if the PDF is bigger than the page format. Note that we only scale if both the
* page format's height *and* width are smaller.
* <p>
* Originally taken from http://www.javaworld.com/javaworld/jw-06-2008/jw-06-opensourcejava-pdf-renderer.html?page=5
*/
@Override
public int print(final Graphics g, final PageFormat format, final int index) throws PrinterException
{
final int pagenum = index + 1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages())
{
return NO_SUCH_PAGE;
}
final PDFPage pdfPage = pdfFile.getPage(pagenum);
// task 08618: generally don't resize the PDF to fit to the page format. The jasper was made to have a particular size.
//
// However, as we always scaled to the page format and some jaspers might rely on it,
// we do scale *down* if the PDF is bigger than the page format.
// note that we only scale if both the page format's height *and* width are smaller
final Dimension scaledToPageFormat = pdfPage.getUnstretchedSize(
(int)format.getImageableWidth(),
(int)format.getImageableHeight(),
pdfPage.getPageBox());
final int widthToUse;
final int heightToUse;
if (scaledToPageFormat.getWidth() <= pdfPage.getWidth()
&& scaledToPageFormat.getHeight() <= pdfPage.getHeight())
{
// scale down to fit the page format
widthToUse = (int)scaledToPageFormat.getWidth();
heightToUse = (int)scaledToPageFormat.getHeight();
}
else
{
// *don't* scale up to fit the page format
widthToUse = (int)pdfPage.getWidth();
heightToUse = (int)pdfPage.getHeight(); | }
final Rectangle bounds = new Rectangle(
(int)format.getImageableX() + calX,
(int)format.getImageableY() + calY,
widthToUse,
heightToUse);
final Graphics2D g2d = (Graphics2D)g;
final PDFRenderer pdfRenderer = new PDFRenderer(
pdfPage,
g2d,
bounds,
null, // Rectangle2D clip
null // Color bgColor
);
try
{
pdfPage.waitForFinish();
pdfRenderer.run();
}
catch (final InterruptedException ie)
{
throw new RuntimeException(ie);
}
// debugging: print a rectangle around the whole thing
// g2d.draw(new Rectangle2D.Double(
// format.getImageableX(),
// format.getImageableY(),
// format.getImageableWidth(),
// format.getImageableHeight()));
return PAGE_EXISTS;
}
public int getNumPages()
{
return pdfFile.getNumPages();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintablePDF.java | 1 |
请完成以下Java代码 | public class TerminatePlanItemInstanceOperation extends AbstractMovePlanItemInstanceToTerminalStateOperation {
protected String exitType;
protected String exitEventType;
public TerminatePlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity, String exitType, String exitEventType) {
super(commandContext, planItemInstanceEntity);
this.exitType = exitType;
this.exitEventType = exitEventType;
}
@Override
public String getNewState() {
return PlanItemInstanceState.TERMINATED;
}
@Override
public String getLifeCycleTransition() {
return PlanItemTransition.TERMINATE;
}
@Override
public boolean isEvaluateRepetitionRule() {
return false;
}
@Override
protected boolean shouldAggregateForSingleInstance() {
return false;
}
@Override
protected boolean shouldAggregateForMultipleInstances() {
return false;
}
@Override
protected void internalExecute() {
planItemInstanceEntity.setEndedTime(getCurrentTime(commandContext));
planItemInstanceEntity.setTerminatedTime(planItemInstanceEntity.getEndedTime());
CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceTerminated(planItemInstanceEntity);
}
@Override
protected Map<String, String> getAsyncLeaveTransitionMetadata() {
Map<String, String> metadata = new HashMap<>();
metadata.put(OperationSerializationMetadata.FIELD_PLAN_ITEM_INSTANCE_ID, planItemInstanceEntity.getId()); | metadata.put(OperationSerializationMetadata.FIELD_EXIT_TYPE, exitType);
metadata.put(OperationSerializationMetadata.FIELD_EXIT_EVENT_TYPE, exitEventType);
return metadata;
}
@Override
public boolean abortOperationIfNewStateEqualsOldState() {
return true;
}
@Override
public String getOperationName() {
return "[Terminate plan item]";
}
public String getExitType() {
return exitType;
}
public void setExitType(String exitType) {
this.exitType = exitType;
}
public String getExitEventType() {
return exitEventType;
}
public void setExitEventType(String exitEventType) {
this.exitEventType = exitEventType;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TerminatePlanItemInstanceOperation.java | 1 |
请完成以下Java代码 | public I_M_Locator getM_Locator()
{
return locator;
}
private int getM_Locator_ID()
{
final int locatorId = locator == null ? -1 : locator.getM_Locator_ID();
return locatorId > 0 ? locatorId : -1;
}
public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1;
}
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID()
|| getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{ | throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different
addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java | 1 |
请完成以下Java代码 | public class Lane implements HasDIBounds, Serializable {
private static final long serialVersionUID = 1L;
protected String id;
protected String name;
protected List<String> flowNodeIds;
protected int x = -1;
protected int y = -1;
protected int width = -1;
protected int height = -1;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int getX() {
return x;
}
@Override
public void setX(int x) {
this.x = x;
}
@Override
public int getY() { | return y;
}
@Override
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
}
public List<String> getFlowNodeIds() {
if (flowNodeIds == null) {
flowNodeIds = new ArrayList<>();
}
return flowNodeIds;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\Lane.java | 1 |
请完成以下Java代码 | public Optional<String> getStrValue() {
return Optional.ofNullable(value);
}
@Override
public Object getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StringDataEntry))
return false;
if (!super.equals(o))
return false;
StringDataEntry that = (StringDataEntry) o;
return Objects.equals(value, that.value);
} | @Override
public int hashCode() {
return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "StringDataEntry{" + "value='" + value + '\'' + "} " + super.toString();
}
@Override
public String getValueAsString() {
return value;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\StringDataEntry.java | 1 |
请完成以下Java代码 | public void hit(int begin, int end, String value)
{
StringBuilder sbName = new StringBuilder();
for (int i = begin; i < end; ++i)
{
sbName.append(wordArray[i].realWord);
}
String name = sbName.toString();
// 对一些bad case做出调整
if (isBadCase(name)) return;
// 正式算它是一个名字
if (HanLP.Config.DEBUG)
{
System.out.printf("识别出地名:%s %s\n", name, value);
}
int offset = 0;
for (int i = 0; i < begin; ++i)
{
offset += wordArray[i].realWord.length();
}
wordNetOptimum.insert(offset, new Vertex(Predefine.TAG_PLACE, name, ATTRIBUTE, WORD_ID), wordNetAll); | }
});
}
/**
* 因为任何算法都无法解决100%的问题,总是有一些bad case,这些bad case会以“盖公章 A 1”的形式加入词典中<BR>
* 这个方法返回是否是bad case
*
* @param name
* @return
*/
static boolean isBadCase(String name)
{
EnumItem<NS> nrEnumItem = dictionary.get(name);
if (nrEnumItem == null) return false;
return nrEnumItem.containsLabel(NS.Z);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\ns\PlaceDictionary.java | 1 |
请完成以下Java代码 | public String getDisplay()
{
if (m_value == null)
return "";
return m_value.getDbHost();
} // getDisplay
/**
* Update Display with Connection info
*/
public void setDisplay()
{
m_text.setText(getDisplay());
final boolean isDatabaseOK = m_value != null && m_value.isDatabaseOK();
// Mark the text field as error if both AppsServer and DB connections are not established
setBackground(!isDatabaseOK);
// Mark the connection indicator button as error if any of AppsServer or DB connection is not established.
btnConnection.setBackground(isDatabaseOK ? AdempierePLAF.getFieldBackground_Normal() : AdempierePLAF.getFieldBackground_Error());
}
/**
* Add Action Listener
*/
public synchronized void addActionListener(final ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
/**
* Fire Action Performed
*/
private void fireActionPerformed()
{
ActionEvent e = null;
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
for (int i = 0; i < listeners.length; i++)
{
if (e == null)
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "actionPerformed");
listeners[i].actionPerformed(e);
}
} // fireActionPerformed
private void actionEditConnection()
{
if (!isEnabled() || !m_rw)
{
return;
} | setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
final CConnection connection = getValue();
final CConnectionDialog dialog = new CConnectionDialog(connection);
if (dialog.isCancel())
{
return;
}
final CConnection connectionNew = dialog.getConnection();
setValue(connectionNew);
DB.setDBTarget(connectionNew);
fireActionPerformed();
}
finally
{
setCursor(Cursor.getDefaultCursor());
}
}
/**
* MouseListener
*/
private class CConnectionEditor_MouseListener extends MouseAdapter
{
/** Mouse Clicked - Open connection editor */
@Override
public void mouseClicked(final MouseEvent e)
{
if (m_active)
return;
m_active = true;
try
{
actionEditConnection();
}
finally
{
m_active = false;
}
}
private boolean m_active = false;
}
} // CConnectionEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionEditor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HistoryJobQuery jobWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public HistoryJobQuery lockOwner(String lockOwner) {
this.lockOwner = lockOwner;
return this;
}
@Override
public HistoryJobQuery locked() {
this.onlyLocked = true;
return this;
}
@Override
public HistoryJobQuery unlocked() {
this.onlyUnlocked = true;
return this;
}
@Override
public HistoryJobQuery withoutScopeType() {
this.withoutScopeType = true;
return this;
}
// sorting //////////////////////////////////////////
@Override
public HistoryJobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
@Override
public HistoryJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
@Override
public HistoryJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobCountByQueryCriteria(this);
}
@Override
public List<HistoryJob> executeList(CommandContext commandContext) {
return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobsByQueryCriteria(this);
}
// getters //////////////////////////////////////////
public String getHandlerType() {
return this.handlerType;
}
public Collection<String> getHandlerTypes() {
return handlerTypes;
}
public Date getNow() {
return jobServiceConfiguration.getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getScopeType() {
return scopeType; | }
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getLockOwner() {
return lockOwner;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Result deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysCheckRuleService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "编码校验规则-通过id查询")
@Operation(summary = "编码校验规则-通过id查询")
@GetMapping(value = "/queryById")
public Result queryById(@RequestParam(name = "id", required = true) String id) {
SysCheckRule sysCheckRule = sysCheckRuleService.getById(id);
return Result.ok(sysCheckRule);
}
/**
* 导出excel
*
* @param request | * @param sysCheckRule
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysCheckRule sysCheckRule) {
return super.exportXls(request, sysCheckRule, SysCheckRule.class, "编码校验规则");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysCheckRule.class);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCheckRuleController.java | 2 |
请完成以下Java代码 | private PInstanceRequest createPInstanceRequest()
{
return PInstanceRequest.builder()
.processId(getPrintFormat().getReportProcessId())
.processParams(ImmutableList.of(
ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId()),
ProcessInfoParameter.of("AD_PrintFormat_ID", printFormatId)))
.build();
}
private String buildFilename()
{
final String instance = String.valueOf(getPinstanceId().getRepoId());
final String title = getProcessInfo().getTitle();
return Joiner.on("_").skipNulls().join(instance, title) + ".pdf";
} | private PrintFormat getPrintFormat()
{
return pfRepo.getById(PrintFormatId.ofRepoId(printFormatId));
}
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (Objects.equals(I_M_Product.COLUMNNAME_M_Product_ID, parameter.getColumnName()))
{
return retrieveSelectedProductIDs().stream().findFirst().orElse(null);
}
return DEFAULT_VALUE_NOTAVAILABLE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_PrintLabel.java | 1 |
请完成以下Java代码 | public void setAD_Session_ID (int AD_Session_ID)
{
if (AD_Session_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Session_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID));
}
/** Get Session.
@return User Session Online or Web
*/
public int getAD_Session_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Session_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Public.
@param IsPublic
Public can read entry
*/
public void setIsPublic (boolean IsPublic)
{
set_Value (COLUMNNAME_IsPublic, Boolean.valueOf(IsPublic));
}
/** Get Public.
@return Public can read entry
*/
public boolean isPublic ()
{
Object oo = get_Value(COLUMNNAME_IsPublic);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Entry Comment.
@param K_Comment_ID
Knowledge Entry Comment
*/
public void setK_Comment_ID (int K_Comment_ID)
{
if (K_Comment_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Comment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Comment_ID, Integer.valueOf(K_Comment_ID));
}
/** Get Entry Comment.
@return Knowledge Entry Comment
*/
public int getK_Comment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Comment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_Comment_ID()));
}
public I_K_Entry getK_Entry() throws RuntimeException
{
return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name)
.getPO(getK_Entry_ID(), get_TrxName()); }
/** Set Entry.
@param K_Entry_ID
Knowledge Entry
*/
public void setK_Entry_ID (int K_Entry_ID)
{
if (K_Entry_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); | else
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID));
}
/** Get Entry.
@return Knowledge Entry
*/
public int getK_Entry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Comment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Captcha getCaptcha() {
Captcha captcha;
switch (codeType) {
case ARITHMETIC:
// 算术类型 https://gitee.com/whvse/EasyCaptcha
captcha = new FixedArithmeticCaptcha(width, height);
// 几位数运算,默认是两位
captcha.setLen(length);
break;
case CHINESE:
captcha = new ChineseCaptcha(width, height);
captcha.setLen(length);
break;
case CHINESE_GIF:
captcha = new ChineseGifCaptcha(width, height);
captcha.setLen(length);
break;
case GIF:
captcha = new GifCaptcha(width, height);
captcha.setLen(length);
break;
case SPEC:
captcha = new SpecCaptcha(width, height);
captcha.setLen(length);
break;
default:
throw new BadRequestException("验证码配置信息错误!正确配置查看 LoginCodeEnum ");
}
if(StringUtils.isNotBlank(fontName)){ | captcha.setFont(new Font(fontName, Font.PLAIN, fontSize));
}
return captcha;
}
static class FixedArithmeticCaptcha extends ArithmeticCaptcha {
public FixedArithmeticCaptcha(int width, int height) {
super(width, height);
}
@Override
protected char[] alphas() {
// 生成随机数字和运算符
int n1 = num(1, 10), n2 = num(1, 10);
int opt = num(3);
// 计算结果
int res = new int[]{n1 + n2, n1 - n2, n1 * n2}[opt];
// 转换为字符运算符
char optChar = "+-x".charAt(opt);
this.setArithmeticString(String.format("%s%c%s=?", n1, optChar, n2));
this.chars = String.valueOf(res);
return chars.toCharArray();
}
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\config\CaptchaConfig.java | 2 |
请完成以下Java代码 | class ConnectionFactoryOptionsBuilder {
private static final String PARAMETERS_LABEL = "org.springframework.boot.r2dbc.parameters";
private final String driver;
private final int sourcePort;
/**
* Create a new {@link ConnectionFactoryOptionsBuilder} instance.
* @param driver the driver
* @param containerPort the source container port
*/
ConnectionFactoryOptionsBuilder(String driver, int containerPort) {
Assert.notNull(driver, "'driver' must not be null");
this.driver = driver;
this.sourcePort = containerPort;
}
ConnectionFactoryOptions build(RunningService service, String database, @Nullable String user,
@Nullable String password) {
Assert.notNull(service, "'service' must not be null");
Assert.notNull(database, "'database' must not be null");
ConnectionFactoryOptions.Builder builder = ConnectionFactoryOptions.builder()
.option(ConnectionFactoryOptions.DRIVER, this.driver)
.option(ConnectionFactoryOptions.HOST, service.host())
.option(ConnectionFactoryOptions.PORT, service.ports().get(this.sourcePort))
.option(ConnectionFactoryOptions.DATABASE, database);
if (StringUtils.hasLength(user)) {
builder.option(ConnectionFactoryOptions.USER, user);
}
if (StringUtils.hasLength(password)) {
builder.option(ConnectionFactoryOptions.PASSWORD, password);
}
applyParameters(service, builder);
return builder.build();
}
private void applyParameters(RunningService service, ConnectionFactoryOptions.Builder builder) { | String parameters = service.labels().get(PARAMETERS_LABEL);
try {
if (StringUtils.hasText(parameters)) {
parseParameters(parameters).forEach((name, value) -> builder.option(Option.valueOf(name), value));
}
}
catch (RuntimeException ex) {
throw new IllegalStateException(
"Unable to apply R2DBC label parameters '%s' defined on service %s".formatted(parameters, service));
}
}
private Map<String, String> parseParameters(String parameters) {
Map<String, String> result = new LinkedHashMap<>();
for (String parameter : StringUtils.commaDelimitedListToStringArray(parameters)) {
String[] parts = parameter.split("=");
Assert.state(parts.length == 2, () -> "'parameters' [%s] must contain parsable value".formatted(parameter));
result.put(parts[0], parts[1]);
}
return Collections.unmodifiableMap(result);
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\ConnectionFactoryOptionsBuilder.java | 1 |
请完成以下Java代码 | public int getC_Fiscal_Representation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Fiscal_Representation_ID);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public org.compiere.model.I_C_Country getTo_Country()
{
return get_ValueAsPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setTo_Country(final org.compiere.model.I_C_Country To_Country)
{
set_ValueFromPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class, To_Country);
}
@Override
public void setTo_Country_ID (final int To_Country_ID)
{
if (To_Country_ID < 1)
set_Value (COLUMNNAME_To_Country_ID, null);
else
set_Value (COLUMNNAME_To_Country_ID, To_Country_ID);
}
@Override
public int getTo_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Country_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom); | }
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setVATaxID (final java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Fiscal_Representation.java | 1 |
请完成以下Java代码 | public int vote(Authentication authentication, Message<T> message, Collection<ConfigAttribute> attributes) {
Assert.notNull(authentication, "authentication must not be null");
Assert.notNull(message, "message must not be null");
Assert.notNull(attributes, "attributes must not be null");
MessageExpressionConfigAttribute attr = findConfigAttribute(attributes);
if (attr == null) {
return ACCESS_ABSTAIN;
}
EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication, message);
ctx = attr.postProcess(ctx, message);
return ExpressionUtils.evaluateAsBoolean(attr.getAuthorizeExpression(), ctx) ? ACCESS_GRANTED : ACCESS_DENIED;
}
private @Nullable MessageExpressionConfigAttribute findConfigAttribute(Collection<ConfigAttribute> attributes) {
for (ConfigAttribute attribute : attributes) {
if (attribute instanceof MessageExpressionConfigAttribute) {
return (MessageExpressionConfigAttribute) attribute;
}
}
return null;
} | @Override
public boolean supports(ConfigAttribute attribute) {
return attribute instanceof MessageExpressionConfigAttribute;
}
@Override
public boolean supports(Class<?> clazz) {
return Message.class.isAssignableFrom(clazz);
}
public void setExpressionHandler(SecurityExpressionHandler<Message<T>> expressionHandler) {
Assert.notNull(expressionHandler, "expressionHandler cannot be null");
this.expressionHandler = expressionHandler;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\messaging\access\expression\MessageExpressionVoter.java | 1 |
请完成以下Java代码 | protected String resolve(String value) {
if (value == null) {
return null;
} else if (embeddedValueResolver != null) {
return embeddedValueResolver.resolveStringValue(value);
} else {
return value;
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableListableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
this.resolver = ((ConfigurableListableBeanFactory) beanFactory).getBeanExpressionResolver();
this.expressionContext = new BeanExpressionContext((ConfigurableListableBeanFactory) beanFactory, null);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext() == this.applicationContext) {
this.contextRefreshed = true;
}
}
public RabbitOperations getRabbitOperations() {
return rabbitOperations; | }
public void setRabbitOperations(RabbitOperations rabbitOperations) {
this.rabbitOperations = rabbitOperations;
}
public RabbitListenerEndpointRegistry getEndpointRegistry() {
return endpointRegistry;
}
public void setEndpointRegistry(RabbitListenerEndpointRegistry endpointRegistry) {
this.endpointRegistry = endpointRegistry;
}
public String getContainerFactoryBeanName() {
return containerFactoryBeanName;
}
public void setContainerFactoryBeanName(String containerFactoryBeanName) {
this.containerFactoryBeanName = containerFactoryBeanName;
}
public RabbitListenerContainerFactory<?> getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(RabbitListenerContainerFactory<?> containerFactory) {
this.containerFactory = containerFactory;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\rabbit\RabbitChannelDefinitionProcessor.java | 1 |
请完成以下Java代码 | public java.lang.String getFullPaymentString ()
{
return (java.lang.String)get_Value(COLUMNNAME_FullPaymentString);
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
@Override
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
@Override
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenz. | @param Reference
Bezug für diesen Eintrag
*/
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Bezug für diesen Eintrag
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_Payment_Request.java | 1 |
请完成以下Java代码 | public IQueryBuilder<I_PMM_PurchaseCandidate_OrderLine> retrivePurchaseCandidateOrderLines(final I_C_Order order)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_OrderLine.class, order)
.addEqualsFilter(I_C_OrderLine.COLUMN_C_Order_ID, order.getC_Order_ID())
.andCollectChildren(I_PMM_PurchaseCandidate_OrderLine.COLUMN_C_OrderLine_ID, I_PMM_PurchaseCandidate_OrderLine.class);
}
@Override
public I_PMM_PurchaseCandidate retrieveFor(final PMMPurchaseCandidateSegment pmmSegment, final Date day)
{
return queryFor(pmmSegment, day, NullQueryFilterModifier.instance)
.create()
.firstOnly(I_PMM_PurchaseCandidate.class);
}
@Override
public boolean hasRecordsForWeek(final PMMPurchaseCandidateSegment pmmSegment, final Date weekDate)
{
return queryFor(pmmSegment, weekDate, DateTruncQueryFilterModifier.WEEK)
.create()
.anyMatch();
} | private final IQueryBuilder<I_PMM_PurchaseCandidate> queryFor(final PMMPurchaseCandidateSegment pmmSegment, final Date day, final IQueryFilterModifier dayModifier)
{
Check.assumeNotNull(pmmSegment, "pmmSegment not null");
Check.assumeNotNull(day, "day not null");
final PlainContextAware context = PlainContextAware.newWithThreadInheritedTrx();
return Services.get(IQueryBL.class)
.createQueryBuilder(I_PMM_PurchaseCandidate.class, context)
.addOnlyActiveRecordsFilter()
//
// Segment
.addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_C_BPartner_ID, pmmSegment.getC_BPartner_ID() > 0 ? pmmSegment.getC_BPartner_ID() : null)
.addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_M_Product_ID, pmmSegment.getM_Product_ID() > 0 ? pmmSegment.getM_Product_ID() : null)
.addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_M_AttributeSetInstance_ID, pmmSegment.getM_AttributeSetInstance_ID() > 0 ? pmmSegment.getM_AttributeSetInstance_ID() : null)
.addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_M_HU_PI_Item_Product_ID, pmmSegment.getM_HU_PI_Item_Product_ID() > 0 ? pmmSegment.getM_HU_PI_Item_Product_ID() : null)
.addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_C_Flatrate_DataEntry_ID, pmmSegment.getC_Flatrate_DataEntry_ID() > 0 ? pmmSegment.getC_Flatrate_DataEntry_ID() : null)
//
// Date
.addEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, day, dayModifier);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPurchaseCandidateDAO.java | 1 |
请完成以下Java代码 | public static <T extends CustomResource<?,?>> ObjectMetaBuilder fromPrimary(T primary, String component) {
return new ObjectMetaBuilder()
.withNamespace(primary.getMetadata().getNamespace())
.withManagedFields((List<ManagedFieldsEntry>)null)
.addToLabels("component", component)
.addToLabels("name", primary.getMetadata().getName())
.withName(primary.getMetadata().getName() + "-" + component)
.addToLabels("ManagedBy", Constants.OPERATOR_NAME);
}
public static <T> T loadTemplate(Class<T> clazz, String resource) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if ( cl == null ) {
cl = BuilderHelper.class.getClassLoader(); | }
try (InputStream is = cl.getResourceAsStream(resource)){
return loadTemplate(clazz, is);
}
catch(IOException ioe) {
throw new RuntimeException("Unable to load classpath resource '" + resource + "': " + ioe.getMessage());
}
}
public static <T> T loadTemplate(Class<T> clazz, InputStream is) throws IOException{
return om.readValue(is, clazz);
}
} | repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\BuilderHelper.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public ProductCacheObject setId(Integer id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public ProductCacheObject setName(String name) {
this.name = name;
return this;
}
public Integer getCid() { | return cid;
}
public ProductCacheObject setCid(Integer cid) {
this.cid = cid;
return this;
}
@Override
public String toString() {
return "ProductCacheObject{" +
"id=" + id +
", name='" + name + '\'' +
", cid=" + cid +
'}';
}
} | repos\SpringBoot-Labs-master\lab-11-spring-data-redis\lab-07-spring-data-redis-with-jedis\src\main\java\cn\iocoder\springboot\labs\lab10\springdatarediswithjedis\cacheobject\ProductCacheObject.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private List<String> collectPropertyNames(AnnotationAttributes annotationAttributes) {
String prefix = getPrefix(annotationAttributes);
String[] names = getNames(annotationAttributes);
return Arrays.stream(names).map(name -> prefix + name).collect(Collectors.toList());
}
private String[] getNames(AnnotationAttributes annotationAttributes) {
String[] names = annotationAttributes.getStringArray("name");
String[] values = annotationAttributes.getStringArray("value");
Assert.isTrue(names.length > 0 || values.length > 0,
String.format("The name or value attribute of @%s is required",
ConditionalOnMissingProperty.class.getSimpleName()));
// TODO remove; not needed when using @AliasFor.
/*
Assert.isTrue(names.length * values.length == 0,
String.format("The name and value attributes of @%s are exclusive",
ConditionalOnMissingProperty.class.getSimpleName()));
*/
return names.length > 0 ? names : values;
}
private String getPrefix(AnnotationAttributes annotationAttributes) {
String prefix = annotationAttributes.getString("prefix"); | return StringUtils.hasText(prefix) ? prefix.trim().endsWith(".") ? prefix.trim() : prefix.trim() + "." : "";
}
private Collection<String> findMatchingProperties(PropertyResolver propertyResolver, List<String> propertyNames) {
return propertyNames.stream().filter(propertyResolver::containsProperty).collect(Collectors.toSet());
}
private ConditionOutcome determineConditionOutcome(Collection<String> matchingProperties) {
if (!matchingProperties.isEmpty()) {
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingProperty.class)
.found("property already defined", "properties already defined")
.items(matchingProperties));
}
return ConditionOutcome.match();
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\condition\OnMissingPropertyCondition.java | 2 |
请完成以下Java代码 | private static Optional<Integer> extractExternalRequestHeader(@NonNull final HttpHeadersWrapper requestHeaders, @NonNull final String headerName)
{
try
{
return Optional.ofNullable(requestHeaders.getHeaderSingleValue(headerName))
.filter(Check::isNotBlank)
.map(Integer::parseInt);
}
catch (final Exception exception)
{
logger.error("Exception encountered while trying to read '" + headerName + "' header!", exception);
throw new AdempiereException("Invalid '" + headerName + "' header : " + requestHeaders.getHeaderSingleValue(headerName), exception);
}
}
private void validateExternalRequestHeaders(@NonNull final HttpHeadersWrapper requestHeaders)
{
final Integer pInstanceId = extractExternalRequestHeader(requestHeaders, HEADER_PINSTANCE_ID).orElse(null);
if (pInstanceId != null && pInstanceDAO.getByIdOrNull(PInstanceId.ofRepoId(pInstanceId)) == null)
{
throw new AdempiereException("No AD_PInstance record found for '" + HEADER_PINSTANCE_ID + "':" + pInstanceId);
}
final Integer externalSystemConfigId = extractExternalRequestHeader(requestHeaders, HEADER_EXTERNALSYSTEM_CONFIG_ID).orElse(null);
// TableRecordReference is used here in order to avoid circular dependencies that would emerge from using I_ExternalSystem_Config and it's repository
if (externalSystemConfigId != null && TableRecordReference.of("ExternalSystem_Config", externalSystemConfigId).getModel() == null)
{
throw new AdempiereException("No IExternalSystemChildConfigId record found for '" + HEADER_EXTERNALSYSTEM_CONFIG_ID + "':" + externalSystemConfigId);
}
}
@Value | @Builder
private static class FutureCompletionContext
{
@NonNull
ApiAuditLoggable apiAuditLoggable;
@NonNull
ApiRequestAudit apiRequestAudit;
@NonNull
OrgId orgId;
@NonNull
ApiAuditConfig apiAuditConfig;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ApiAuditService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getScopeId() {
return this.scopeId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return this.scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String getParentElementId() {
return parentElementId;
}
@Override
public void setParentElementId(String parentElementId) {
this.parentElementId = parentElementId;
}
@Override
public String getReferenceScopeId() {
return referenceScopeId;
}
@Override
public void setReferenceScopeId(String referenceScopeId) {
this.referenceScopeId = referenceScopeId;
}
@Override
public String getReferenceScopeType() {
return referenceScopeType;
}
@Override
public void setReferenceScopeType(String referenceScopeType) {
this.referenceScopeType = referenceScopeType;
}
@Override | public String getReferenceScopeDefinitionId() {
return referenceScopeDefinitionId;
}
@Override
public void setReferenceScopeDefinitionId(String referenceScopeDefinitionId) {
this.referenceScopeDefinitionId = referenceScopeDefinitionId;
}
@Override
public String getRootScopeId() {
return rootScopeId;
}
@Override
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
@Override
public String getRootScopeType() {
return rootScopeType;
}
@Override
public void setRootScopeType(String rootScopeType) {
this.rootScopeType = rootScopeType;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String getHierarchyType() {
return hierarchyType;
}
@Override
public void setHierarchyType(String hierarchyType) {
this.hierarchyType = hierarchyType;
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\EntityLinkEntityImpl.java | 2 |
请完成以下Java代码 | public Builder setSqlValueClass(final Class<?> sqlValueClass)
{
this._sqlValueClass = sqlValueClass;
return this;
}
private Class<?> getSqlValueClass()
{
if (_sqlValueClass != null)
{
return _sqlValueClass;
}
return getValueClass();
}
public Builder setLookupDescriptor(@Nullable final LookupDescriptor lookupDescriptor)
{
this._lookupDescriptor = lookupDescriptor;
return this;
}
public OptionalBoolean getNumericKey()
{
return _numericKey;
}
public Builder setKeyColumn(final boolean keyColumn)
{
this.keyColumn = keyColumn;
return this;
}
public Builder setEncrypted(final boolean encrypted)
{
this.encrypted = encrypted;
return this;
}
/** | * Sets ORDER BY priority and direction (ascending/descending)
*
* @param priority priority; if positive then direction will be ascending; if negative then direction will be descending
*/
public Builder setDefaultOrderBy(final int priority)
{
if (priority >= 0)
{
orderByPriority = priority;
orderByAscending = true;
}
else
{
orderByPriority = -priority;
orderByAscending = false;
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDocumentFieldDataBindingDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_Invoice_Candidate
{
private final C_Invoice_CandidateFacadeService invoiceCandidateFacadeService;
public C_Invoice_Candidate(@NonNull final C_Invoice_CandidateFacadeService invoiceCandidateFacadeService)
{
this.invoiceCandidateFacadeService = invoiceCandidateFacadeService;
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, // we aren't interested in "after-new", because prior to the first revalidation, the ICs isn't in a valid state anyways
ifColumnsChanged = { /* keep in sync with the columns from InvoiceCandidateRecordHelper */
I_C_Invoice_Candidate.COLUMNNAME_NetAmtInvoiced,
I_C_Invoice_Candidate.COLUMNNAME_NetAmtToInvoice,
I_C_Invoice_Candidate.COLUMNNAME_QtyToInvoiceInUOM,
I_C_Invoice_Candidate.COLUMNNAME_QtyInvoicedInUOM,
I_C_Invoice_Candidate.COLUMNNAME_PriceActual })
public void createOrUpdateCommissionInstance(@NonNull final I_C_Invoice_Candidate icRecord)
{ | try (final MDCCloseable icRecordMDC = TableRecordMDC.putTableRecordReference(icRecord))
{
invoiceCandidateFacadeService.syncICToCommissionInstance(icRecord, false/* candidateDeleted */);
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteCommissionInstance(@NonNull final I_C_Invoice_Candidate icRecord)
{
try (final MDCCloseable icRecordMDC = TableRecordMDC.putTableRecordReference(icRecord))
{
invoiceCandidateFacadeService.syncICToCommissionInstance(icRecord, true/* candidateDeleted */);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\interceptor\C_Invoice_Candidate.java | 2 |
请完成以下Java代码 | public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
@Override | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", adminId=").append(adminId);
sb.append(", createTime=").append(createTime);
sb.append(", ip=").append(ip);
sb.append(", address=").append(address);
sb.append(", userAgent=").append(userAgent);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminLoginLog.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JSONDocumentReferencesGroupsAggregator addAll(@NonNull final Collection<WebuiDocumentReference> documentReferences)
{
documentReferences.forEach(this::add);
return this;
}
public JSONDocumentReferencesGroupsAggregator add(@NonNull final WebuiDocumentReference documentReference)
{
final JSONDocumentReference jsonDocumentReference = JSONDocumentReference.of(documentReference, jsonOpts);
if (jsonDocumentReference == null)
{
return this;
}
final MenuNode topLevelMenuGroup = menuTree.getTopLevelMenuGroupOrNull(documentReference.getTargetWindow().getWindowId());
final String topLevelMenuGroupId = topLevelMenuGroup != null ? topLevelMenuGroup.getId() : othersGroupId;
final JSONDocumentReferencesGroupBuilder groupBuilder = groupsBuilders.computeIfAbsent(topLevelMenuGroupId, k -> {
final boolean isMiscGroup = topLevelMenuGroup == null;
final String caption = topLevelMenuGroup != null ? topLevelMenuGroup.getCaption() : othersMenuCaption;
return JSONDocumentReferencesGroup.builder().caption(caption).isMiscGroup(isMiscGroup);
});
groupBuilder.reference(jsonDocumentReference);
return this;
}
private ImmutableList<JSONDocumentReferencesGroup> flushGroups()
{
if (groupsBuilders.isEmpty())
{
return ImmutableList.of();
}
final ImmutableList<JSONDocumentReferencesGroup> groups = groupsBuilders.values() | .stream()
.map(JSONDocumentReferencesGroupBuilder::build)
.filter(group -> !group.isEmpty())
.sorted(sorting)
.collect(ImmutableList.toImmutableList());
groupsBuilders.clear();
return groups;
}
public void addAndPublish(
@NonNull final List<WebuiDocumentReference> documentReferences,
@NonNull final JSONDocumentReferencesEventPublisher publisher)
{
addAll(documentReferences);
publish(publisher);
}
private void publish(final @NonNull JSONDocumentReferencesEventPublisher publisher)
{
final ImmutableList<JSONDocumentReferencesGroup> groups = flushGroups();
publisher.publishPartialResults(groups);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\controller\JSONDocumentReferencesGroupsAggregator.java | 2 |
请完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValidUntil() {
return validUntil;
}
public void setValidUntil(String validUntil) {
this.validUntil = validUntil;
}
public Boolean isUnlimited() {
return isUnlimited;
}
public void setUnlimited(Boolean isUnlimited) {
this.isUnlimited = isUnlimited;
}
public Map<String, String> getFeatures() {
return features;
}
public void setFeatures(Map<String, String> features) { | this.features = features;
}
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
public static LicenseKeyDataDto fromEngineDto(LicenseKeyData other) {
return new LicenseKeyDataDto(
other.getCustomer(),
other.getType(),
other.getValidUntil(),
other.isUnlimited(),
other.getFeatures(),
other.getRaw());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\LicenseKeyDataDto.java | 1 |
请完成以下Java代码 | public PageData<User> findAllByAuthority(Authority authority, PageLink pageLink) {
return DaoUtil.toPageData(userRepository.findAllByAuthority(authority, DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<User> findByAuthorityAndTenantsIds(Authority authority, List<TenantId> tenantsIds, PageLink pageLink) {
return DaoUtil.toPageData(userRepository.findByAuthorityAndTenantIdIn(authority, DaoUtil.toUUIDs(tenantsIds), DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<User> findByAuthorityAndTenantProfilesIds(Authority authority, List<TenantProfileId> tenantProfilesIds, PageLink pageLink) {
return DaoUtil.toPageData(userRepository.findByAuthorityAndTenantProfilesIds(authority, DaoUtil.toUUIDs(tenantProfilesIds),
DaoUtil.toPageable(pageLink)));
}
@Override
public UserAuthDetails findUserAuthDetailsByUserId(UUID tenantId, UUID userId) {
TbPair<UserEntity, Boolean> result = userRepository.findUserAuthDetailsByUserId(userId);
return result != null ? new UserAuthDetails(result.getFirst().toData(), result.getSecond()) : null;
}
@Override
public int countTenantAdmins(UUID tenantId) {
return userRepository.countByTenantIdAndAuthority(tenantId, Authority.TENANT_ADMIN);
}
@Override
public List<User> findUsersByTenantIdAndIds(UUID tenantId, List<UUID> userIds) {
return DaoUtil.convertDataList(userRepository.findUsersByTenantIdAndIdIn(tenantId, userIds));
}
@Override | public Long countByTenantId(TenantId tenantId) {
return userRepository.countByTenantId(tenantId.getId());
}
@Override
public PageData<User> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<UserFields> findNextBatch(UUID id, int batchSize) {
return userRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.USER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HistoryJobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
@Override
public HistoryJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
@Override
public HistoryJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobCountByQueryCriteria(this);
}
@Override
public List<HistoryJob> executeList(CommandContext commandContext) {
return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobsByQueryCriteria(this);
}
// getters //////////////////////////////////////////
public String getHandlerType() {
return this.handlerType;
}
public Collection<String> getHandlerTypes() {
return handlerTypes;
}
public Date getNow() {
return jobServiceConfiguration.getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId; | }
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getLockOwner() {
return lockOwner;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private UserDetailsService getUserDetailsService(H http) {
if (this.userDetailsService == null) {
this.userDetailsService = getSharedOrBean(http, UserDetailsService.class);
}
Assert.state(this.userDetailsService != null,
() -> "userDetailsService cannot be null. Invoke " + RememberMeConfigurer.class.getSimpleName()
+ "#userDetailsService(UserDetailsService) or see its javadoc for alternative approaches.");
return this.userDetailsService;
}
/**
* Gets the key to use for validating remember me tokens. If a value was passed into
* {@link #key(String)}, then that is returned. Alternatively, if a key was specified
* in the {@link #rememberMeServices(RememberMeServices)}}, then that is returned. If
* no key was specified in either of those cases, then a secure random string is
* generated.
* @return the remember me key to use
*/
private String getKey() {
if (this.key == null) {
if (this.rememberMeServices instanceof AbstractRememberMeServices) {
this.key = ((AbstractRememberMeServices) this.rememberMeServices).getKey();
} | else {
this.key = UUID.randomUUID().toString();
}
}
return this.key;
}
private <C> C getSharedOrBean(H http, Class<C> type) {
C shared = http.getSharedObject(type);
if (shared != null) {
return shared;
}
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
if (context == null) {
return null;
}
return context.getBeanProvider(type).getIfUnique();
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\RememberMeConfigurer.java | 2 |
请完成以下Java代码 | public ProcessInstanceMigrationDocumentBuilder addEnableActivityMapping(EnableActivityMapping enableActivityMapping) {
this.enableActivityMappings.add(enableActivityMapping);
return this;
}
@Override
public ProcessInstanceMigrationDocumentBuilder addProcessInstanceVariable(String variableName, Object variableValue) {
this.processInstanceVariables.put(variableName, variableValue);
return this;
}
@Override
public ProcessInstanceMigrationDocumentBuilder addProcessInstanceVariables(Map<String, Object> processInstanceVariables) {
this.processInstanceVariables.putAll(processInstanceVariables);
return this;
}
@Override
public ProcessInstanceMigrationDocument build() {
if (migrateToProcessDefinitionId == null) {
if (migrateToProcessDefinitionKey == null) {
throw new FlowableException("Process definition key cannot be null");
}
if (migrateToProcessDefinitionVersion != null && migrateToProcessDefinitionVersion < 0) {
throw new FlowableException("Process definition version must be a positive number");
}
}
ProcessInstanceMigrationDocumentImpl document = new ProcessInstanceMigrationDocumentImpl(); | document.setMigrateToProcessDefinitionId(migrateToProcessDefinitionId);
document.setMigrateToProcessDefinition(migrateToProcessDefinitionKey, migrateToProcessDefinitionVersion, migrateToProcessDefinitionTenantId);
if (preUpgradeScript != null) {
document.setPreUpgradeScript(preUpgradeScript);
}
if (preUpgradeJavaDelegate != null) {
document.setPreUpgradeJavaDelegate(preUpgradeJavaDelegate);
}
if (preUpgradeJavaDelegateExpression != null) {
document.setPreUpgradeJavaDelegateExpression(preUpgradeJavaDelegateExpression);
}
if (postUpgradeScript != null) {
document.setPostUpgradeScript(postUpgradeScript);
}
if (postUpgradeJavaDelegate != null) {
document.setPostUpgradeJavaDelegate(postUpgradeJavaDelegate);
}
if (postUpgradeJavaDelegateExpression != null) {
document.setPostUpgradeJavaDelegateExpression(postUpgradeJavaDelegateExpression);
}
document.setActivityMigrationMappings(activityMigrationMappings);
document.setEnableActivityMappings(enableActivityMappings);
document.setProcessInstanceVariables(processInstanceVariables);
return document;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\migration\ProcessInstanceMigrationDocumentBuilderImpl.java | 1 |
请完成以下Java代码 | public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (log.isDebugEnabled()) {
log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/** | * 发布事件
*
* @param event 事件
*/
public static void publishEvent(ApplicationEvent event) {
if (applicationContext == null) {
return;
}
applicationContext.publishEvent(event);
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() {
SpringUtil.clearHolder();
}
} | repos\spring-boot-demo-master\demo-dynamic-datasource\src\main\java\com\xkcoding\dynamic\datasource\utils\SpringUtil.java | 1 |
请完成以下Java代码 | public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId; | }
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getDetailType() {
return detailType;
}
public void setDetailType(String detailType) {
this.detailType = detailType;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricDetailEntityImpl.java | 1 |
请完成以下Java代码 | public String getTableName()
{
return tableName;
}
/**
* Gets a set of column names on which this callout instance is listening
*
* @return set of column names
*/
public Set<String> getColumnNames()
{
return columnNames;
}
@Override
public String getId()
{
return id;
}
@Override
public void execute(final ICalloutExecutor executor, final ICalloutField field)
{
final String columnName = field.getColumnName();
final CalloutMethodPointcutKey pointcutKey = CalloutMethodPointcutKey.of(columnName);
final List<CalloutMethodPointcut> pointcutsForKey = mapPointcuts.get(pointcutKey);
if (pointcutsForKey.isEmpty())
{
return;
}
for (final ICalloutMethodPointcut pointcut : pointcutsForKey)
{
executePointcut(pointcut, executor, field);
}
}
private void executePointcut(@NonNull final ICalloutMethodPointcut pointcut, @NonNull final ICalloutExecutor executor, @NonNull final ICalloutField field)
{
// Skip executing this callout if we were asked to skip when record copying mode is active
if (pointcut.isSkipIfCopying() && field.isRecordCopyingMode())
{
logger.info("Skip invoking callout because we are in copying mode: {}", pointcut.getMethod());
return;
}
if (pointcut.isSkipIfIndirectlyCalled() && executor.getActiveCalloutInstancesCount() > 1)
{
logger.info("Skip invoking callout because it is called via another callout: {}", pointcut.getMethod());
return;
} | try
{
final Method method = pointcut.getMethod();
final Object model = field.getModel(pointcut.getModelClass());
// make sure the method can be executed
if (!method.isAccessible())
{
method.setAccessible(true);
}
if (pointcut.isParamCalloutFieldRequired())
{
method.invoke(annotatedObject, model, field);
}
else
{
method.invoke(annotatedObject, model);
}
}
catch (final CalloutExecutionException e)
{
throw e;
}
catch (final Exception e)
{
throw CalloutExecutionException.wrapIfNeeded(e)
.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\AnnotatedCalloutInstance.java | 1 |
请完成以下Java代码 | private static int[][] reverse(int[][] input) {
int[][] result = new int[input.length][];
for (int x = 0; x < input.length; ++x) {
result[x] = new int[input[0].length];
for (int y = 0; y < input[0].length; ++y) {
result[x][y] = input[x][input.length - y - 1];
}
}
return result;
}
@Override
public String toString() {
return Arrays.deepToString(board);
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Board board1 = (Board) o;
return Arrays.deepEquals(board, board1.board);
}
@Override
public int hashCode() {
return Arrays.deepHashCode(board);
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\play2048\Board.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ExecutableElement getSetter() {
return this.setter;
}
@Override
protected boolean isMarkedAsNested(MetadataGenerationEnvironment environment) {
return environment.getNestedConfigurationPropertyAnnotation(this.field) != null
|| environment.getNestedConfigurationPropertyAnnotation(getGetter()) != null;
}
@Override
protected String resolveDescription(MetadataGenerationEnvironment environment) {
return environment.getTypeUtils().getJavaDoc(this.field);
}
@Override
protected Object resolveDefaultValue(MetadataGenerationEnvironment environment) {
return environment.getFieldDefaultValue(getDeclaringElement(), this.field); | }
@Override
protected ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment) {
return resolveItemDeprecation(environment, getGetter(), this.setter, this.field, this.factoryMethod);
}
@Override
public boolean isProperty(MetadataGenerationEnvironment env) {
boolean isCollection = env.getTypeUtils().isCollectionOrMap(getType());
boolean hasGetter = getGetter() != null;
boolean hasSetter = getSetter() != null;
return !env.isExcluded(getType()) && hasGetter && (hasSetter || isCollection);
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\JavaBeanPropertyDescriptor.java | 2 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false
spring.datasource.initializatio | n-mode=always
spring.datasource.platform=mysql
spring.jpa.properties.hibernate.session_factory.statement_inspector=com.bookstore.interceptor.SqlInspector | repos\Hibernate-SpringBoot-master\HibernateSpringBootInterceptSql\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public Timestamp decrypt(Timestamp value)
{
return value;
} // decrypt
/**
* Convert String to Digest.
* JavaScript version see - http://pajhome.org.uk/crypt/md5/index.html
*
* @param value message
* @return HexString of message (length = 32 characters)
*/
@Override
public String getDigest(String value)
{
if (m_md == null)
{
try
{
m_md = MessageDigest.getInstance("MD5");
// m_md = MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException nsae)
{
nsae.printStackTrace();
}
}
// Reset MessageDigest object
m_md.reset();
// Convert String to array of bytes
byte[] input = value.getBytes(StandardCharsets.UTF_8);
// feed this array of bytes to the MessageDigest object
m_md.update(input);
// Get the resulting bytes after the encryption process
byte[] output = m_md.digest();
m_md.reset();
//
return convertToHexString(output);
} // getDigest
/**
* Checks, if value is a valid digest
*
* @param value digest string
* @return true if valid digest
*/ | @Override
public boolean isDigest(String value)
{
if (value == null || value.length() != 32)
return false;
// needs to be a hex string, so try to convert it
return (convertHexString(value) != null);
} // isDigest
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("cipher", m_cipher)
.toString();
}
} // Secure | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Secure.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_Year[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_Calendar getC_Calendar() throws RuntimeException
{
return (I_C_Calendar)MTable.get(getCtx(), I_C_Calendar.Table_Name)
.getPO(getC_Calendar_ID(), get_TrxName()); }
/** Set Calendar.
@param C_Calendar_ID
Accounting Calendar Name
*/
public void setC_Calendar_ID (int C_Calendar_ID)
{
if (C_Calendar_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Calendar_ID, Integer.valueOf(C_Calendar_ID));
}
/** Get Calendar.
@return Accounting Calendar Name
*/
public int getC_Calendar_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Calendar_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Year.
@param C_Year_ID
Calendar Year
*/
public void setC_Year_ID (int C_Year_ID)
{
if (C_Year_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Year_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Year_ID, Integer.valueOf(C_Year_ID));
}
/** Get Year.
@return Calendar Year
*/
public int getC_Year_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Year_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 Year.
@param FiscalYear
The Fiscal Year
*/
public void setFiscalYear (String FiscalYear)
{
set_Value (COLUMNNAME_FiscalYear, FiscalYear);
}
/** Get Year.
@return The Fiscal Year
*/
public String getFiscalYear ()
{
return (String)get_Value(COLUMNNAME_FiscalYear);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getFiscalYear());
}
/** 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_C_Year.java | 1 |
请完成以下Java代码 | public static class PayPalCreateLogRequestBuilder
{
public PayPalCreateLogRequestBuilder request(@NonNull final HttpRequest<?> request)
{
requestPath(request.path());
requestMethod(request.verb());
requestHeaders(toMap(request.headers()));
requestBodyAsJson(toJsonString(request.requestBody()));
return this;
}
public PayPalCreateLogRequestBuilder response(@NonNull final HttpResponse<?> response)
{
responseStatusCode(response.statusCode());
responseHeaders(toMap(response.headers()));
responseBodyAsJson(toJsonString(response.result()));
return this;
}
public PayPalCreateLogRequestBuilder response(@NonNull final Throwable ex)
{
if (ex instanceof HttpException)
{
final HttpException httpException = (HttpException)ex;
responseStatusCode(httpException.statusCode());
responseHeaders(toMap(httpException.headers()));
responseBodyAsJson(httpException.getMessage());
}
else
{
responseStatusCode(0);
responseHeaders(ImmutableMap.of());
responseBodyAsJson(Util.dumpStackTraceToString(ex));
}
return this;
}
private static ImmutableMap<String, String> toMap(final Headers headers)
{
if (headers == null)
{
return ImmutableMap.of(); | }
final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
for (final String header : headers)
{
final String value = headers.header(header);
final String headerNorm = CoalesceUtil.coalesce(header, "");
final String valueNorm = CoalesceUtil.coalesce(value, "");
builder.put(headerNorm, valueNorm);
}
return builder.build();
}
private static String toJsonString(final Object obj)
{
if (obj == null)
{
return "";
}
try
{
return new Json().serialize(obj);
}
catch (final Exception ex)
{
return obj.toString();
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\logs\PayPalCreateLogRequest.java | 1 |
请完成以下Java代码 | private void actionEditConnection()
{
if (!isEnabled() || !m_rw)
{
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
final CConnection connection = getValue();
final CConnectionDialog dialog = new CConnectionDialog(connection);
if (dialog.isCancel())
{
return;
}
final CConnection connectionNew = dialog.getConnection();
setValue(connectionNew);
DB.setDBTarget(connectionNew);
fireActionPerformed();
}
finally
{
setCursor(Cursor.getDefaultCursor());
}
}
/**
* MouseListener
*/
private class CConnectionEditor_MouseListener extends MouseAdapter
{ | /** Mouse Clicked - Open connection editor */
@Override
public void mouseClicked(final MouseEvent e)
{
if (m_active)
return;
m_active = true;
try
{
actionEditConnection();
}
finally
{
m_active = false;
}
}
private boolean m_active = false;
}
} // CConnectionEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionEditor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public <S extends ServerResponse> RouterFunction<S> filter(
HandlerFilterFunction<ServerResponse, S> filterFunction) {
return this.provider.getRouterFunction().filter(filterFunction);
}
@Override
public void accept(RouterFunctions.Visitor visitor) {
this.provider.getRouterFunction().accept(visitor);
}
@Override
public RouterFunction<ServerResponse> withAttribute(String name, Object value) {
return this.provider.getRouterFunction().withAttribute(name, value);
}
@Override | public RouterFunction<ServerResponse> withAttributes(Consumer<Map<String, Object>> attributesConsumer) {
return this.provider.getRouterFunction().withAttributes(attributesConsumer);
}
@Override
public Optional<HandlerFunction<ServerResponse>> route(ServerRequest request) {
return this.provider.getRouterFunction().route(request);
}
@Override
public String toString() {
return this.provider.getRouterFunction().toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\GatewayMvcPropertiesBeanDefinitionRegistrar.java | 2 |
请完成以下Java代码 | public PurchaseRow getById(@NonNull final DocumentId rowId) throws EntityNotFoundException
{
return getById(PurchaseRowId.fromDocumentId(rowId));
}
public PurchaseRow getById(@NonNull final PurchaseRowId rowId) throws EntityNotFoundException
{
if (rowId.isGroupRowId())
{
return getToplevelRowById(rowId);
}
else if (rowId.isLineRowId())
{
return getToplevelRowById(rowId.toGroupRowId())
.getIncludedRowById(rowId);
}
else
{
return getToplevelRowById(rowId.toGroupRowId())
.getIncludedRowById(rowId.toLineRowId())
.getIncludedRowById(rowId);
}
}
private PurchaseRow getToplevelRowById(@NonNull final PurchaseRowId topLevelRowId)
{
final PurchaseRow topLevelRow = topLevelRowsById.get(topLevelRowId);
if (topLevelRow != null)
{
return topLevelRow;
}
throw new EntityNotFoundException("topLevelRow not found")
.appendParametersToMessage()
.setParameter("topLevelRowId", topLevelRowId);
}
public Stream<? extends IViewRow> streamTopLevelRowsByIds(@NonNull final DocumentIdsSelection rowIds)
{
if (rowIds.isAll())
{
return topLevelRowsById.values().stream();
}
return rowIds.stream().map(this::getById);
}
void patchRow(
@NonNull final PurchaseRowId idOfRowToPatch,
@NonNull final PurchaseRowChangeRequest request)
{
final PurchaseGroupRowEditor editorToUse = PurchaseRow::changeIncludedRow;
updateRow(idOfRowToPatch, request, editorToUse);
} | private void updateRow(
@NonNull final PurchaseRowId idOfRowToPatch,
@NonNull final PurchaseRowChangeRequest request,
@NonNull final PurchaseGroupRowEditor editor)
{
topLevelRowsById.compute(idOfRowToPatch.toGroupRowId(), (groupRowId, groupRow) -> {
if (groupRow == null)
{
throw new EntityNotFoundException("Row not found").appendParametersToMessage().setParameter("rowId", groupRowId);
}
final PurchaseRow newGroupRow = groupRow.copy();
if (idOfRowToPatch.isGroupRowId())
{
final PurchaseRowId includedRowId = null;
editor.edit(newGroupRow, includedRowId, request);
}
else
{
final PurchaseRowId includedRowId = idOfRowToPatch;
editor.edit(newGroupRow, includedRowId, request);
}
return newGroupRow;
});
}
@FunctionalInterface
private static interface PurchaseGroupRowEditor
{
void edit(final PurchaseRow editableGroupRow, final PurchaseRowId includedRowId, final PurchaseRowChangeRequest request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowsCollection.java | 1 |
请完成以下Java代码 | public class Scopifier extends BeanDefinitionVisitor {
private final boolean proxyTargetClass;
private final BeanDefinitionRegistry registry;
private final String scope;
private final boolean scoped;
public static BeanDefinitionHolder createScopedProxy(String beanName, BeanDefinition definition, BeanDefinitionRegistry registry, boolean proxyTargetClass) {
BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(new BeanDefinitionHolder(definition, beanName), registry, proxyTargetClass);
registry.registerBeanDefinition(beanName, proxyHolder.getBeanDefinition());
return proxyHolder;
}
public Scopifier(BeanDefinitionRegistry registry, String scope, boolean proxyTargetClass, boolean scoped) {
super(new StringValueResolver() {
public String resolveStringValue(String value) {
return value;
}
});
this.registry = registry;
this.proxyTargetClass = proxyTargetClass;
this.scope = scope;
this.scoped = scoped;
}
@Override
protected Object resolveValue(Object value) {
BeanDefinition definition = null; | String beanName = null;
if (value instanceof BeanDefinition) {
definition = (BeanDefinition) value;
beanName = BeanDefinitionReaderUtils.generateBeanName(definition, registry);
} else if (value instanceof BeanDefinitionHolder) {
BeanDefinitionHolder holder = (BeanDefinitionHolder) value;
definition = holder.getBeanDefinition();
beanName = holder.getBeanName();
}
if (definition != null) {
boolean nestedScoped = scope.equals(definition.getScope());
boolean scopeChangeRequiresProxy = !scoped && nestedScoped;
if (scopeChangeRequiresProxy) {
// Exit here so that nested inner bean definitions are not
// analysed
return createScopedProxy(beanName, definition, registry, proxyTargetClass);
}
}
// Nested inner bean definitions are recursively analysed here
value = super.resolveValue(value);
return value;
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\aop\util\Scopifier.java | 1 |
请完成以下Java代码 | default ValidationEntry addError(String problem, String description) {
return addError(problem, null, null, null, description);
}
default ValidationEntry addError(String problem, Case caze, CaseElement caseElement, BaseElement baseElement, String description) {
return addEntry(problem, caze, caseElement, baseElement, description, ValidationEntry.Level.Error);
}
default ValidationEntry addWarning(String problem, String description) {
return addWarning(problem, null, null, null, description);
}
default ValidationEntry addWarning(String problem, Case caze, CaseElement caseElement, BaseElement baseElement, String description) {
return addEntry(problem, caze, caseElement, baseElement, description, ValidationEntry.Level.Warning);
}
default ValidationEntry addEntry(String problem, Case caze, CaseElement caseElement, BaseElement baseElement, String description,
ValidationEntry.Level level) {
ValidationEntry entry = new ValidationEntry();
entry.setLevel(level);
if (caze != null) {
entry.setCaseDefinitionId(caze.getId());
entry.setCaseDefinitionName(caze.getName());
} | if (baseElement != null) {
entry.setXmlLineNumber(baseElement.getXmlRowNumber());
entry.setXmlColumnNumber(baseElement.getXmlColumnNumber());
}
entry.setProblem(problem);
entry.setDefaultDescription(description);
if (caseElement == null && baseElement instanceof CaseElement) {
caseElement = (CaseElement) baseElement;
}
if (caseElement != null) {
entry.setItemId(caseElement.getId());
entry.setItemName(caseElement.getName());
}
return addEntry(entry);
}
ValidationEntry addEntry(ValidationEntry entry);
} | repos\flowable-engine-main\modules\flowable-case-validation\src\main\java\org\flowable\cmmn\validation\CaseValidationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmailData implements Serializable {
private String emailSubject;
private String emailBody;
private String emailLocale;
private String emailAddress1;
private String emailAddress2;
public EmailData() {
this.emailSubject = "You have received a new message";
this.emailBody = "Good morning !";
this.emailLocale = "en-US";
this.emailAddress1 = "jhon.doe@example.com";
this.emailAddress2 = "mark.jakob@example.com";
}
public String getEmailSubject() {
return this.emailSubject;
}
public String getEmailBody() {
return this.emailBody;
}
public String getEmailLocale() { | return this.emailLocale;
}
public String getEmailAddress1() {
return this.emailAddress1;
}
public String getEmailAddress2() {
return this.emailAddress2;
}
public List<String> getEmailAddresses() {
List<String> emailAddresses = new ArrayList<>();
emailAddresses.add(getEmailAddress1());
emailAddresses.add(getEmailAddress2());
return emailAddresses;
}
} | repos\tutorials-master\spring-web-modules\spring-thymeleaf-4\src\main\java\com\baeldung\thymeleaf\mvcdata\repository\EmailData.java | 2 |
请完成以下Java代码 | public boolean supports(AuthenticationToken token) {
return token instanceof JWTToken;
}
/**
* 认证信息(身份验证)
* Authentication 是用来验证用户身份
*
* @param auth
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth)
throws AuthenticationException {
_logger.info("MyShiroRealm.doGetAuthenticationInfo()");
String token = (String) auth.getCredentials();
// 解密获得username,用于和数据库进行对比
String username = JWTUtil.getUsername(token);
if (username == null) {
throw new AuthenticationException("token invalid");
}
//通过username从数据库中查找 ManagerInfo对象
//实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
ManagerInfo managerInfo = managerInfoService.findByUsername(username);
if (managerInfo == null) {
throw new AuthenticationException("用户不存在!");
}
if (!JWTUtil.verify(token, username, managerInfo.getPassword())) {
throw new AuthenticationException("Token认证失败");
}
return new SimpleAuthenticationInfo(token, token, "my_realm");
}
/**
* 此方法调用hasRole,hasPermission的时候才会进行回调.
* <p>
* 权限信息.(授权):
* 1、如果用户正常退出,缓存自动清空;
* 2、如果用户非正常退出,缓存自动清空;
* 3、如果我们修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
* (需要手动编程进行实现;放在service进行调用)
* 在权限修改后调用realm中的方法,realm已经由spring管理,所以从spring中获取realm实例,调用clearCached方法; | * :Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。
*
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
/*
* 当没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行,
* 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理;
* 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了,
* 缓存过期之后会再次执行。
*/
_logger.info("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
String username = JWTUtil.getUsername(principals.toString());
// 下面的可以使用缓存提升速度
ManagerInfo managerInfo = managerInfoService.findByUsername(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//设置相应角色的权限信息
for (SysRole role : managerInfo.getRoles()) {
//设置角色
authorizationInfo.addRole(role.getRole());
for (Permission p : role.getPermissions()) {
//设置权限
authorizationInfo.addStringPermission(p.getPermission());
}
}
return authorizationInfo;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\shiro\MyShiroRealm.java | 1 |
请完成以下Java代码 | public static Channel openChannel(Session session, String type) throws JSchException {
if (!session.isConnected()) {
session.connect(SESSION_TIMEOUT);
}
return session.openChannel(type);
}
public static ChannelSftp openSftpChannel(Session session) throws JSchException {
return (ChannelSftp) openChannel(session, "sftp");
}
public static ChannelExec openExecChannel(Session session) throws JSchException {
return (ChannelExec) openChannel(session, "exec");
}
/**
* disconnect
*
* @param session
*/
public static void disconnect(Session session) {
if (session != null) {
if (session.isConnected()) {
try {
session.disconnect();
log.info("session disconnect successfully");
} catch (Exception e) {
log.error("JSch session disconnect error:", e);
}
}
}
}
/**
* close connection
*
* @param channel channel connection
*/
public static void disconnect(Channel channel) {
if (channel != null) {
if (channel.isConnected()) {
try {
channel.disconnect();
log.info("channel is closed already");
} catch (Exception e) {
log.error("JSch channel disconnect error:", e);
}
}
}
}
public static int checkAck(InputStream in) throws IOException {
int b = in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0) {
return b;
} | if (b == -1) {
return b;
}
if (b == 1 || b == 2) {
StringBuilder sb = new StringBuilder();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
if (b == 1) { // error
log.debug(sb.toString());
}
if (b == 2) { // fatal error
log.debug(sb.toString());
}
}
return b;
}
public static void closeInputStream(InputStream in) {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error("Close input stream error." + e.getMessage());
}
}
}
public static void closeOutputStream(OutputStream out) {
if (out != null) {
try {
out.close();
} catch (IOException e) {
log.error("Close output stream error." + e.getMessage());
}
}
}
} | repos\springboot-demo-master\JSch\src\main\java\com\et\jsch\util\JSchUtil.java | 1 |
请完成以下Java代码 | public Order status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Order Status
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Order Status")
@JsonProperty(JSON_PROPERTY_STATUS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public Order complete(Boolean complete) {
this.complete = complete;
return this;
}
/**
* Get complete
* @return complete
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_COMPLETE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(this.id, order.id) &&
Objects.equals(this.petId, order.petId) &&
Objects.equals(this.quantity, order.quantity) &&
Objects.equals(this.shipDate, order.shipDate) &&
Objects.equals(this.status, order.status) &&
Objects.equals(this.complete, order.complete);
}
@Override | public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).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\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Order.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class JacksonHttpMessageConvertersConfiguration {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JsonMapper.class)
@ConditionalOnBean(JsonMapper.class)
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jackson", matchIfMissing = true)
static class JacksonJsonHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(value = JacksonJsonHttpMessageConverter.class,
ignoredType = { "org.springframework.hateoas.server.mvc.TypeConstrainedJacksonJsonHttpMessageConverter",
"org.springframework.data.rest.webmvc.alps.AlpsJacksonJsonHttpMessageConverter" })
JacksonJsonHttpMessageConvertersCustomizer jacksonJsonHttpMessageConvertersCustomizer(JsonMapper jsonMapper) {
return new JacksonJsonHttpMessageConvertersCustomizer(jsonMapper);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(XmlMapper.class)
@ConditionalOnBean(XmlMapper.class)
protected static class JacksonXmlHttpMessageConverterConfiguration {
@Bean
@ConditionalOnMissingBean(JacksonXmlHttpMessageConverter.class)
JacksonXmlHttpMessageConvertersCustomizer jacksonXmlHttpMessageConvertersCustomizer(XmlMapper xmlMapper) {
return new JacksonXmlHttpMessageConvertersCustomizer(xmlMapper);
}
}
static class JacksonJsonHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final JsonMapper jsonMapper;
JacksonJsonHttpMessageConvertersCustomizer(JsonMapper jsonMapper) {
this.jsonMapper = jsonMapper;
} | @Override
public void customize(ClientBuilder builder) {
builder.withJsonConverter(new JacksonJsonHttpMessageConverter(this.jsonMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withJsonConverter(new JacksonJsonHttpMessageConverter(this.jsonMapper));
}
}
static class JacksonXmlHttpMessageConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final XmlMapper xmlMapper;
JacksonXmlHttpMessageConvertersCustomizer(XmlMapper xmlMapper) {
this.xmlMapper = xmlMapper;
}
@Override
public void customize(ClientBuilder builder) {
builder.withXmlConverter(new JacksonXmlHttpMessageConverter(this.xmlMapper));
}
@Override
public void customize(ServerBuilder builder) {
builder.withXmlConverter(new JacksonXmlHttpMessageConverter(this.xmlMapper));
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\JacksonHttpMessageConvertersConfiguration.java | 2 |
请完成以下Java代码 | public List<Comment> getCommentsByType(String type) {
return commandExecutor.execute(new GetTypeCommentsCmd(type));
}
@Override
public List<Event> getTaskEvents(String taskId) {
return commandExecutor.execute(new GetTaskEventsCmd(taskId));
}
@Override
public List<Comment> getProcessInstanceComments(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceCommentsCmd(processInstanceId));
}
@Override
public List<Comment> getProcessInstanceComments(String processInstanceId, String type) {
return commandExecutor.execute(new GetProcessInstanceCommentsCmd(processInstanceId, type));
}
@Override
public Attachment createAttachment(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, InputStream content) {
return commandExecutor.execute(new CreateAttachmentCmd(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription, content, null));
}
@Override
public Attachment createAttachment(String attachmentType, String taskId, String processInstanceId, String attachmentName, String attachmentDescription, String url) {
return commandExecutor.execute(new CreateAttachmentCmd(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription, null, url));
}
@Override
public InputStream getAttachmentContent(String attachmentId) {
return commandExecutor.execute(new GetAttachmentContentCmd(attachmentId));
}
@Override
public void deleteAttachment(String attachmentId) {
commandExecutor.execute(new DeleteAttachmentCmd(attachmentId));
}
@Override
public void deleteComments(String taskId, String processInstanceId) {
commandExecutor.execute(new DeleteCommentCmd(taskId, processInstanceId, null));
} | @Override
public void deleteComment(String commentId) {
commandExecutor.execute(new DeleteCommentCmd(null, null, commentId));
}
@Override
public Attachment getAttachment(String attachmentId) {
return commandExecutor.execute(new GetAttachmentCmd(attachmentId));
}
@Override
public List<Attachment> getTaskAttachments(String taskId) {
return commandExecutor.execute(new GetTaskAttachmentsCmd(taskId));
}
@Override
public List<Attachment> getProcessInstanceAttachments(String processInstanceId) {
return commandExecutor.execute(new GetProcessInstanceAttachmentsCmd(processInstanceId));
}
@Override
public void saveAttachment(Attachment attachment) {
commandExecutor.execute(new SaveAttachmentCmd(attachment));
}
@Override
public List<Task> getSubTasks(String parentTaskId) {
return commandExecutor.execute(new GetSubTasksCmd(parentTaskId));
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\TaskServiceImpl.java | 1 |
请完成以下Java代码 | public String getName() {
return TYPE_NAME;
}
public TypedValue convertValue(TypedValue propertyValue) {
if(propertyValue instanceof LongValue) {
return propertyValue;
}
else {
Object value = propertyValue.getValue();
if(value == null) {
return Variables.longValue(null, propertyValue.isTransient());
}
else if((value instanceof Number) || (value instanceof String)) {
return Variables.longValue(Long.valueOf(value.toString()), propertyValue.isTransient());
}
else {
throw new ProcessEngineException("Value '"+value+"' is not of type Long.");
}
}
}
// deprecated //////////////////////////////////////////// | public Object convertFormValueToModelValue(Object propertyValue) {
if (propertyValue==null || "".equals(propertyValue)) {
return null;
}
return Long.valueOf(propertyValue.toString());
}
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue==null) {
return null;
}
return modelValue.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\LongFormType.java | 1 |
请完成以下Java代码 | private void callDBFunctionUntilDone(final String dbFunctionName, final int maxUpdates, final boolean vacuum)
{
final Mutable<Boolean> done = new Mutable<>(false);
final Mutable<Integer> updates = new Mutable<>(0);
final Mutable<String> lastTableName = new Mutable<>();
final Mutable<Integer> lastTableUpdates = new Mutable<>(0);
do
{
Services.get(ITrxManager.class).runInNewTrx((TrxRunnable)localTrxName -> {
final CPreparedStatement stmt = DB.prepareStatement("select * from " + dbFunctionName + "();", localTrxName);
final Stopwatch stopWatch = Stopwatch.createStarted();
final ResultSet rs = stmt.executeQuery();
final String elapsedTime = stopWatch.stop().toString();
if (!rs.next())
{
done.setValue(true);
Loggables.addLog("{}: we are done", dbFunctionName);
return;
}
final String tablename = rs.getString("tablename");
final int updatecount = rs.getInt("updatecount");
final int massmigrate_id = rs.getInt("massmigrate_id");
Loggables.addLog("{}: MassMigrate_ID={}; elapsed time={}; Table={}; Updated={}", dbFunctionName, massmigrate_id, elapsedTime, tablename, updatecount);
updates.setValue(updates.getValue() + updatecount);
lastTableName.setValue(tablename);
lastTableUpdates.setValue(updatecount);
});
if (vacuum && !Check.isEmpty(lastTableName.getValue()) && lastTableUpdates.getValue() > 0)
{
// note that we can't include the vacuum calls in the DB function because of some transaction stuffs | final Stopwatch stopWatch = Stopwatch.createStarted();
DB.executeFunctionCallEx(ITrx.TRXNAME_None, "VACUUM ANALYZE " + lastTableName.getValue(), new Object[0]);
DB.executeFunctionCallEx(ITrx.TRXNAME_None, "VACUUM ANALYZE dlm.massmigrate_records", new Object[0]);
final String elapsedTime = stopWatch.stop().toString();
Loggables.addLog("{}: Vacuumed {} and dlm.massmigrate_records; elapsed time={}", dbFunctionName, lastTableName.getValue(), elapsedTime);
}
if (maxUpdates > 0 && updates.getValue() >= maxUpdates)
{
Loggables.addLog(
"{}: we now updated {} which is >= maxUpdates={}; Stopping now",
dbFunctionName, updates.getValue(), maxUpdates);
break;
}
}
while (!done.getValue());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\migrator\process\DLM_MassMigrate.java | 1 |
请完成以下Java代码 | public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(adminSettingsDao.findById(tenantId, entityId.getId()));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(adminSettingsDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.ADMIN_SETTINGS;
} | private void dropTokenIfProviderInfoChanged(JsonNode newJsonValue, JsonNode oldJsonValue) {
if (newJsonValue.has("enableOauth2") && newJsonValue.get("enableOauth2").asBoolean()) {
if (!newJsonValue.get("providerId").equals(oldJsonValue.get("providerId")) ||
!newJsonValue.get("clientId").equals(oldJsonValue.get("clientId")) ||
!newJsonValue.get("clientSecret").equals(oldJsonValue.get("clientSecret")) ||
!newJsonValue.get("redirectUri").equals(oldJsonValue.get("redirectUri")) ||
(newJsonValue.has("providerTenantId") && !newJsonValue.get("providerTenantId").equals(oldJsonValue.get("providerTenantId")))) {
((ObjectNode) newJsonValue).put("tokenGenerated", false);
((ObjectNode) newJsonValue).remove("refreshToken");
((ObjectNode) newJsonValue).remove("refreshTokenExpires");
}
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\settings\AdminSettingsServiceImpl.java | 1 |
请完成以下Java代码 | private IContextAware getContext()
{
return context;
}
private I_PP_Order getPP_Order()
{
// not null
return ppOrder;
}
/**
* Delete existing {@link I_PP_Order_Report}s lines linked to current manufacturing order.
*/
public void deleteReportLines()
{
final I_PP_Order ppOrder = getPP_Order();
queryBL.createQueryBuilder(I_PP_Order_Report.class, getContext())
.addEqualsFilter(org.eevolution.model.I_PP_Order_Report.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID())
.create() // create query
.delete(); // delete matching records
_createdReportLines.clear();
_seqNoNext = 10; // reset seqNo
}
/**
* Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} lines).
*
* @param qiLines
*/
public void save(final Collection<IQualityInspectionLine> qiLines)
{
if (qiLines == null || qiLines.isEmpty())
{
return;
}
final List<IQualityInspectionLine> qiLinesToSave = new ArrayList<>(qiLines);
//
// Discard not accepted lines and then sort them
if (reportLinesSorter != null)
{
reportLinesSorter.filterAndSort(qiLinesToSave);
}
//
// Iterate lines and save one by one
for (final IQualityInspectionLine qiLine : qiLinesToSave)
{
save(qiLine);
}
}
/**
* Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} line).
*
* @param qiLine
*/
private void save(final IQualityInspectionLine qiLine)
{
Check.assumeNotNull(qiLine, "qiLine not null");
final I_PP_Order ppOrder = getPP_Order();
final int seqNo = _seqNoNext;
BigDecimal qty = qiLine.getQty(); | if (qty != null && qiLine.isNegateQtyInReport())
{
qty = qty.negate();
}
//
// Create report line
final I_PP_Order_Report reportLine = InterfaceWrapperHelper.newInstance(I_PP_Order_Report.class, getContext());
reportLine.setPP_Order(ppOrder);
reportLine.setAD_Org_ID(ppOrder.getAD_Org_ID());
reportLine.setSeqNo(seqNo);
reportLine.setIsActive(true);
// reportLine.setQualityInspectionLineType(qiLine.getQualityInspectionLineType());
reportLine.setProductionMaterialType(qiLine.getProductionMaterialType());
reportLine.setM_Product(qiLine.getM_Product());
reportLine.setName(qiLine.getName());
reportLine.setQty(qty);
reportLine.setC_UOM(qiLine.getC_UOM());
reportLine.setPercentage(qiLine.getPercentage());
reportLine.setQtyProjected(qiLine.getQtyProjected());
reportLine.setComponentType(qiLine.getComponentType());
reportLine.setVariantGroup(qiLine.getVariantGroup());
//
// Save report line
InterfaceWrapperHelper.save(reportLine);
_createdReportLines.add(reportLine);
_seqNoNext += 10;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderReportWriter.java | 1 |
请完成以下Java代码 | public void failure(Object sample, String queue, String exception) {
Timer timer = this.timers.get(queue + exception);
if (timer == null) {
timer = buildTimer(this.listenerId, "failure", queue, exception);
}
((Sample) sample).stop(timer);
}
private Timer buildTimer(String aListenerId, String result, String queue, String exception) {
Builder builder = Timer.builder("spring.rabbitmq.listener")
.description("Spring RabbitMQ Listener")
.tag("listener.id", aListenerId)
.tag("queue", queue)
.tag("result", result) | .tag("exception", exception);
if (!CollectionUtils.isEmpty(this.tags)) {
this.tags.forEach(builder::tag);
}
Timer registeredTimer = builder.register(this.registry);
this.timers.put(queue + exception, registeredTimer);
return registeredTimer;
}
void destroy() {
this.timers.values().forEach(this.registry::remove);
this.timers.clear();
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\MicrometerHolder.java | 1 |
请完成以下Java代码 | public final List<I_C_BP_BankAccount> retrieveQRBPBankAccounts(@NonNull final String IBAN)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryFilter<I_C_BP_BankAccount> esrAccountmatichingIBANorQR_IBAN = queryBL.createCompositeQueryFilter(I_C_BP_BankAccount.class)
.setJoinOr()
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IBAN, IBAN)
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_QR_IBAN, IBAN);
return queryBL.createQueryBuilder(I_C_BP_BankAccount.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IsEsrAccount, true)
.filter(esrAccountmatichingIBANorQR_IBAN)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient() | .create()
.list();
}
@Override
public boolean isESRBankAccount(final int bpBankAccountId)
{
if (bpBankAccountId <= 0)
{
return false;
}
final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.load(bpBankAccountId, I_C_BP_BankAccount.class);
return bpBankAccount.isEsrAccount();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRBPBankAccountDAO.java | 1 |
请完成以下Java代码 | public boolean isNew() {
return isNew;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public String getKey() {
return null;
}
@Override
public String getDerivedFrom() {
return null;
}
@Override
public String getDerivedFromRoot() {
return null; | }
@Override
public String getEngineVersion() {
return null;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "DmnDeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DmnDeploymentEntityImpl.java | 1 |
请完成以下Java代码 | public class Main implements ModelValidator
{
private ModelValidationEngine engine;
private int m_AD_Client_ID = -1;
private final List<ReferenceNoGeneratorInstanceValidator> docValidators = new ArrayList<>();
@Override
public void initialize(final ModelValidationEngine engine, final MClient client)
{
this.engine = engine;
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
engine.addModelValidator(new C_ReferenceNo_Type(this), client);
engine.addModelValidator(new C_ReferenceNo_Type_Table(this), client);
engine.addModelValidator(new C_ReferenceNo(), client);
//
// Register all referenceNo generator instance interceptors
final List<I_C_ReferenceNo_Type> typeRecords = Services.get(IReferenceNoDAO.class).retrieveReferenceNoTypes();
for (final I_C_ReferenceNo_Type typeRecord : typeRecords)
{
registerInstanceValidator(typeRecord);
}
//
// Register Workflow execution/identification tracker
Services.get(IWFExecutionFactory.class).registerListener(new TrackingWFExecutionListener());
}
@Override
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing
return null;
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
// nothing
return null;
} | @Override
public String docValidate(final PO po, final int timing)
{
// nothing
return null;
}
private void registerInstanceValidator(final I_C_ReferenceNo_Type type)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(type);
final IReferenceNoGeneratorInstance instance = Services.get(IReferenceNoBL.class).getReferenceNoGeneratorInstance(ctx, type);
if (instance == null)
{
return;
}
final ReferenceNoGeneratorInstanceValidator validator = new ReferenceNoGeneratorInstanceValidator(instance);
engine.addModelValidator(validator);
docValidators.add(validator);
}
private void unregisterInstanceValidator(final I_C_ReferenceNo_Type type)
{
final Iterator<ReferenceNoGeneratorInstanceValidator> it = docValidators.iterator();
while (it.hasNext())
{
final ReferenceNoGeneratorInstanceValidator validator = it.next();
if (validator.getInstance().getType().getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID())
{
validator.unregister();
it.remove();
}
}
}
public void updateInstanceValidator(final I_C_ReferenceNo_Type type)
{
unregisterInstanceValidator(type);
registerInstanceValidator(type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\Main.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DictDetailController {
private final DictDetailService dictDetailService;
private static final String ENTITY_NAME = "dictDetail";
@ApiOperation("查询字典详情")
@GetMapping
public ResponseEntity<PageResult<DictDetailDto>> queryDictDetail(DictDetailQueryCriteria criteria,
@PageableDefault(sort = {"dictSort"}, direction = Sort.Direction.ASC) Pageable pageable){
return new ResponseEntity<>(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
}
@ApiOperation("查询多个字典详情")
@GetMapping(value = "/map")
public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){
String[] names = dictName.split("[,,]");
Map<String, List<DictDetailDto>> dictMap = new HashMap<>(16);
for (String name : names) {
dictMap.put(name, dictDetailService.getDictByName(name));
}
return new ResponseEntity<>(dictMap, HttpStatus.OK);
}
@Log("新增字典详情")
@ApiOperation("新增字典详情")
@PostMapping
@PreAuthorize("@el.check('dict:add')")
public ResponseEntity<Object> createDictDetail(@Validated @RequestBody DictDetail resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
dictDetailService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
} | @Log("修改字典详情")
@ApiOperation("修改字典详情")
@PutMapping
@PreAuthorize("@el.check('dict:edit')")
public ResponseEntity<Object> updateDictDetail(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){
dictDetailService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除字典详情")
@ApiOperation("删除字典详情")
@DeleteMapping(value = "/{id}")
@PreAuthorize("@el.check('dict:del')")
public ResponseEntity<Object> deleteDictDetail(@PathVariable Long id){
dictDetailService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DictDetailController.java | 2 |
请完成以下Java代码 | public int getM_Shipper_RoutingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_RoutingCode_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{
return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setPrevious_ID (final int Previous_ID)
{
if (Previous_ID < 1)
set_Value (COLUMNNAME_Previous_ID, null);
else
set_Value (COLUMNNAME_Previous_ID, Previous_ID);
}
@Override
public int getPrevious_ID()
{
return get_ValueAsInt(COLUMNNAME_Previous_ID);
}
@Override
public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No)
{
set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No);
}
@Override
public java.lang.String getSetup_Place_No()
{
return get_ValueAsString(COLUMNNAME_Setup_Place_No);
}
@Override | public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVisitorsAddress (final boolean VisitorsAddress)
{
set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress);
}
@Override
public boolean isVisitorsAddress()
{
return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location.java | 1 |
请完成以下Java代码 | public final class ALoginRes extends ListResourceBundle
{
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Connection" },
{ "Defaults", "Defaults" },
{ "Login", "Login" },
{ "File", "&File" },
{ "Exit", "Exit" },
{ "Help", "&Help" },
{ "About", "About" },
{ "Host", "&Server" },
{ "Database", "Database" },
{ "User", "&User ID" },
{ "EnterUser", "Enter Application User ID" },
{ "Password", "&Password" },
{ "EnterPassword", "Enter Application Password" },
{ "Language", "&Language" },
{ "SelectLanguage", "Select your language" },
{ "Role", "&Role" },
{ "Client", "&Client" },
{ "Organization", "&Organization" },
{ "Date", "&Date" },
{ "Warehouse", "&Warehouse" }, | { "Printer", "Prin&ter" },
{ "Connected", "Connected" },
{ "NotConnected", "Not Connected" },
{ "DatabaseNotFound", "Database not found" },
{ "UserPwdError", "User does not match password" },
{ "RoleNotFound", "Role not found/complete" },
{ "Authorized", "Authorized" },
{ "Ok", "&Ok" },
{ "Cancel", "&Cancel" },
{ "VersionConflict", "Version Conflict:" },
{ "VersionInfo", "Server <> Client" },
{ "PleaseUpgrade", "Please download new Version from Server" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CacheRestController extends CacheRestControllerTemplate
{
public static final String CACHE_RESET_PARAM_forgetNotSavedDocuments = "forgetNotSavedDocuments";
@NonNull private final UserSession userSession;
@NonNull private final DocumentCollection documentCollection;
@NonNull private final MenuTreeRepository menuTreeRepo;
@NonNull private final ProcessRestController processesController;
@NonNull private final LookupDataSourceFactory lookupDataSourceFactory;
@Override
protected void assertAuth() {userSession.assertLoggedIn();}
protected void resetAdditional(@NonNull final JsonCacheResetResponse response, @NonNull final JsonCacheResetRequest request)
{
{
final boolean forgetNotSavedDocuments = request.getValueAsBoolean(CACHE_RESET_PARAM_forgetNotSavedDocuments);
final String documentsResult = documentCollection.cacheReset(forgetNotSavedDocuments);
response.addLog("documents: " + documentsResult + " (" + CACHE_RESET_PARAM_forgetNotSavedDocuments + "=" + forgetNotSavedDocuments + ")");
}
{
menuTreeRepo.cacheReset();
response.addLog("menuTreeRepo: cache invalidated"); | }
{
processesController.cacheReset();
response.addLog("processesController: cache invalidated");
}
{
ViewColumnHelper.cacheReset();
response.addLog("viewColumnHelper: cache invalidated");
}
}
@GetMapping("/lookups/stats")
public JsonGetStatsResponse getLookupCacheStats()
{
assertAuth();
return lookupDataSourceFactory.getCacheStats()
.stream()
.sorted(DEFAULT_ORDER_BY)
.map(JsonCacheStats::of)
.collect(JsonGetStatsResponse.collect());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\admin\CacheRestController.java | 2 |
请完成以下Java代码 | private boolean retrieveEnabled(final UserId loggedUserId)
{
final AdWindowId windowId = AdWindowId.ofRepoIdOrNull(MTable.get(Env.getCtx(), I_AD_Field.Table_Name).getAD_Window_ID());
if (windowId == null)
{
return false;
}
final ClientId clientId = Env.getClientId();
final LocalDate date = Env.getLocalDate();
//
// Makes sure the logged in user has at least one role assigned which has read-write access to our window
return Services.get(IUserRolePermissionsDAO.class)
.matchUserRolesPermissionsForUser(
clientId,
loggedUserId,
date,
rolePermissions -> rolePermissions.checkWindowPermission(windowId).hasWriteAccess());
}
public void save(final GridTab gridTab)
{
Services.get(ITrxManager.class).runInNewTrx(() -> save0(gridTab));
}
private void save0(final GridTab gridTab)
{
Check.assumeNotNull(gridTab, "gridTab not null");
for (final GridField gridField : gridTab.getFields())
{
save(gridField);
}
} | private void save(final GridField gridField)
{
final GridFieldVO gridFieldVO = gridField.getVO();
final AdFieldId adFieldId = gridFieldVO.getAD_Field_ID();
if (adFieldId == null)
{
return;
}
final I_AD_Field adField = InterfaceWrapperHelper.load(adFieldId, I_AD_Field.class);
if (adField == null)
{
return;
}
adField.setIsDisplayedGrid(gridFieldVO.isDisplayedGrid());
adField.setSeqNoGrid(gridFieldVO.getSeqNoGrid());
adField.setColumnDisplayLength(gridFieldVO.getLayoutConstraints().getColumnDisplayLength());
InterfaceWrapperHelper.save(adField);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveStateModel.java | 1 |
请完成以下Java代码 | public class KafkaRecordSenderContext extends SenderContext<ProducerRecord<?, ?>> {
private final String beanName;
private final ProducerRecord<?, ?> record;
@SuppressWarnings("this-escape")
public KafkaRecordSenderContext(ProducerRecord<?, ?> record, String beanName, Supplier<String> clusterId) {
super((carrier, key, value) -> {
Headers headers = record.headers();
headers.remove(key);
headers.add(key, value == null ? null : value.getBytes(StandardCharsets.UTF_8));
});
setCarrier(record);
this.beanName = beanName;
this.record = record;
String cluster = clusterId.get();
setRemoteServiceName("Apache Kafka" + (cluster != null ? ": " + cluster : ""));
}
/**
* Return the template's bean name.
* @return the name.
*/
public String getBeanName() {
return this.beanName;
} | /**
* Return the destination topic.
* @return the topic.
*/
public String getDestination() {
return this.record.topic();
}
/**
* Return the producer record.
* @return the record.
* @since 3.0.6
*/
public ProducerRecord<?, ?> getRecord() {
return this.record;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaRecordSenderContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void setOwner(TenantId tenantId, DeviceProfile deviceProfile, IdProvider idProvider) {
deviceProfile.setTenantId(tenantId);
}
@Override
protected DeviceProfile prepare(EntitiesImportCtx ctx, DeviceProfile deviceProfile, DeviceProfile old, EntityExportData<DeviceProfile> exportData, IdProvider idProvider) {
deviceProfile.setDefaultRuleChainId(idProvider.getInternalId(deviceProfile.getDefaultRuleChainId()));
deviceProfile.setDefaultEdgeRuleChainId(idProvider.getInternalId(deviceProfile.getDefaultEdgeRuleChainId()));
deviceProfile.setDefaultDashboardId(idProvider.getInternalId(deviceProfile.getDefaultDashboardId()));
deviceProfile.setFirmwareId(idProvider.getInternalId(deviceProfile.getFirmwareId(), false));
deviceProfile.setSoftwareId(idProvider.getInternalId(deviceProfile.getSoftwareId(), false));
return deviceProfile;
}
@Override
protected DeviceProfile saveOrUpdate(EntitiesImportCtx ctx, DeviceProfile deviceProfile, EntityExportData<DeviceProfile> exportData, IdProvider idProvider, CompareResult compareResult) {
boolean toUpdate = ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds();
if (toUpdate) {
deviceProfile.setFirmwareId(idProvider.getInternalId(deviceProfile.getFirmwareId()));
deviceProfile.setSoftwareId(idProvider.getInternalId(deviceProfile.getSoftwareId()));
}
DeviceProfile saved = deviceProfileService.saveDeviceProfile(deviceProfile);
if (toUpdate) {
importCalculatedFields(ctx, saved, exportData, idProvider);
}
return saved;
}
@Override
protected void onEntitySaved(User user, DeviceProfile savedDeviceProfile, DeviceProfile oldDeviceProfile) {
logEntityActionService.logEntityAction(savedDeviceProfile.getTenantId(), savedDeviceProfile.getId(), savedDeviceProfile, | null, oldDeviceProfile == null ? ActionType.ADDED : ActionType.UPDATED, user);
}
@Override
protected DeviceProfile deepCopy(DeviceProfile deviceProfile) {
return new DeviceProfile(deviceProfile);
}
@Override
protected void cleanupForComparison(DeviceProfile deviceProfile) {
super.cleanupForComparison(deviceProfile);
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE_PROFILE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\DeviceProfileImportService.java | 2 |
请完成以下Java代码 | public class Product {
private String name;
private String type;
private String label;
public Product(String name, String type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
} | repos\tutorials-master\drools\src\main\java\com\baeldung\drools\model\Product.java | 1 |
请完成以下Java代码 | public class DocumentLayoutColumnDescriptor
{
public static Builder builder()
{
return new Builder();
}
private final String internalName;
@Getter private final List<DocumentLayoutElementGroupDescriptor> elementGroups;
private DocumentLayoutColumnDescriptor(final Builder builder)
{
internalName = builder.internalName;
elementGroups = ImmutableList.copyOf(builder.buildElementGroups());
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("elementGroups", elementGroups.isEmpty() ? null : elementGroups)
.toString();
}
public boolean hasElementGroups()
{
return !elementGroups.isEmpty();
}
public static final class Builder
{
private static final Logger logger = LogManager.getLogger(DocumentLayoutColumnDescriptor.Builder.class);
private String internalName;
private final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupsBuilders = new ArrayList<>();
private Builder()
{
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("elementGroups-count", elementGroupsBuilders.size())
.toString();
}
public DocumentLayoutColumnDescriptor build()
{
final DocumentLayoutColumnDescriptor result = new DocumentLayoutColumnDescriptor(this);
logger.trace("Built {} for {}", result, this);
return result; | }
private List<DocumentLayoutElementGroupDescriptor> buildElementGroups()
{
return elementGroupsBuilders
.stream()
.map(DocumentLayoutElementGroupDescriptor.Builder::build)
.filter(this::checkValid)
.collect(GuavaCollectors.toImmutableList());
}
private boolean checkValid(final DocumentLayoutElementGroupDescriptor elementGroup)
{
if(!elementGroup.hasElementLines())
{
logger.trace("Skip adding {} to {} because it does not have element line", elementGroup, this);
return false;
}
return true;
}
public Builder setInternalName(String internalName)
{
this.internalName = internalName;
return this;
}
public Builder addElementGroups(@NonNull final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupBuilders)
{
elementGroupsBuilders.addAll(elementGroupBuilders);
return this;
}
public Builder addElementGroup(@NonNull final DocumentLayoutElementGroupDescriptor.Builder elementGroupBuilder)
{
elementGroupsBuilders.add(elementGroupBuilder);
return this;
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementGroupsBuilders.stream().flatMap(DocumentLayoutElementGroupDescriptor.Builder::streamElementBuilders);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutColumnDescriptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static final class LogoutRequestParameters {
private final HttpServletRequest request;
private final RelyingPartyRegistration registration;
private final Authentication authentication;
private final LogoutRequest logoutRequest;
public LogoutRequestParameters(HttpServletRequest request, RelyingPartyRegistration registration,
Authentication authentication, LogoutRequest logoutRequest) {
this.request = request;
this.registration = registration;
this.authentication = authentication;
this.logoutRequest = logoutRequest;
}
LogoutRequestParameters(BaseOpenSamlLogoutRequestResolver.LogoutRequestParameters parameters) {
this(parameters.getRequest(), parameters.getRelyingPartyRegistration(), parameters.getAuthentication(),
parameters.getLogoutRequest());
}
public HttpServletRequest getRequest() {
return this.request;
} | public RelyingPartyRegistration getRelyingPartyRegistration() {
return this.registration;
}
public Authentication getAuthentication() {
return this.authentication;
}
public LogoutRequest getLogoutRequest() {
return this.logoutRequest;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\opensaml5Main\java\org\springframework\security\saml2\provider\service\web\authentication\logout\OpenSaml5LogoutRequestResolver.java | 2 |
请完成以下Java代码 | public FutureTask<String> fetchConfigTask(String configKey) {
return new FutureTask<>(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return String.format("%s.%d", configKey, new Random().nextInt(Integer.MAX_VALUE));
});
}
public ListenableFutureTask<String> fetchConfigListenableTask(String configKey) {
return ListenableFutureTask.create(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return String.format("%s.%d", configKey, new Random().nextInt(Integer.MAX_VALUE));
});
}
public ListenableFuture<Integer> succeedingTask() {
return Futures.immediateFuture(new Random().nextInt(Integer.MAX_VALUE));
}
public <T> ListenableFuture<T> failingTask() {
return Futures.immediateFailedFuture(new ListenableFutureException());
}
public ListenableFuture<Integer> getCartId() {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return new Random().nextInt(Integer.MAX_VALUE);
});
}
public ListenableFuture<String> getCustomerName() {
String[] names = new String[] { "Mark", "Jane", "June" };
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return names[new Random().nextInt(names.length)];
});
} | public ListenableFuture<List<String>> getCartItems() {
String[] items = new String[] { "Apple", "Orange", "Mango", "Pineapple" };
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
int noOfItems = new Random().nextInt(items.length);
if (noOfItems == 0) ++noOfItems;
return Arrays.stream(items, 0, noOfItems).collect(Collectors.toList());
});
}
public ListenableFuture<String> generateUsername(String firstName) {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
return firstName.replaceAll("[^a-zA-Z]+","")
.concat("@service.com");
});
}
public ListenableFuture<String> generatePassword(String username) {
return lExecService.submit(() -> {
TimeUnit.MILLISECONDS.sleep(500);
if (username.contains("@")) {
String[] parts = username.split("@");
return parts[0] + "123@" + parts[1];
} else {
return username + "123";
}
});
}
} | repos\tutorials-master\guava-modules\guava-concurrency\src\main\java\com\baeldung\guava\future\ListenableFutureService.java | 1 |
请完成以下Java代码 | private String computeSqlLikeString()
{
final StringBuilder sb = new StringBuilder();
sb.append("%");
boolean lastCharIsWildcard = true;
for (final AttributesKeyPartPattern partPattern : partPatterns)
{
final String partSqlLike = partPattern.getSqlLikePart();
if (lastCharIsWildcard)
{
if (partSqlLike.startsWith("%"))
{
sb.append(partSqlLike.substring(1));
}
else
{
sb.append(partSqlLike);
}
}
else
{
if (partSqlLike.startsWith("%"))
{
sb.append(partSqlLike);
}
else
{
sb.append("%").append(partSqlLike);
}
}
lastCharIsWildcard = partSqlLike.endsWith("%");
}
if (!lastCharIsWildcard)
{ | sb.append("%");
}
return sb.toString();
}
public boolean matches(@NonNull final AttributesKey attributesKey)
{
for (final AttributesKeyPartPattern partPattern : partPatterns)
{
boolean partPatternMatched = false;
if (AttributesKey.NONE.getAsString().equals(attributesKey.getAsString()))
{
partPatternMatched = partPattern.matches(AttributesKeyPart.NONE);
}
else
{
for (final AttributesKeyPart part : attributesKey.getParts())
{
if (partPattern.matches(part))
{
partPatternMatched = true;
break;
}
}
}
if (!partPatternMatched)
{
return false;
}
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPattern.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JpaEntityManagerFactory {
private final String DB_URL = "jdbc:mysql://databaseurl";
private final String DB_USER_NAME = "username";
private final String DB_PASSWORD = "password";
public EntityManager getEntityManager() {
return getEntityManagerFactory().createEntityManager();
}
protected EntityManagerFactory getEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<>();
return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
.build();
}
protected PersistenceUnitInfoImpl getPersistenceUnitInfo(String name) {
return new PersistenceUnitInfoImpl(name, getEntityClassNames(), getProperties());
}
protected List<String> getEntityClassNames() {
return Arrays.asList(getEntities())
.stream()
.map(Class::getName)
.collect(Collectors.toList());
}
protected Properties getProperties() {
Properties properties = new Properties(); | properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings", false);
properties.put("hibernate.connection.datasource", getMysqlDataSource());
return properties;
}
protected Class[] getEntities() {
return new Class[]{User.class};
}
protected DataSource getMysqlDataSource() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(DB_URL);
mysqlDataSource.setUser(DB_USER_NAME);
mysqlDataSource.setPassword(DB_PASSWORD);
return mysqlDataSource;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\daopattern\config\JpaEntityManagerFactory.java | 2 |
请完成以下Java代码 | public String getOrderId() {
return orderId;
}
public Map<String, Integer> getProducts() {
return products;
}
public OrderStatus getOrderStatus() {
return orderStatus;
}
public void addProduct(String productId) {
products.putIfAbsent(productId, 1);
}
public void incrementProductInstance(String productId) {
products.computeIfPresent(productId, (id, count) -> ++count);
}
public void decrementProductInstance(String productId) {
products.computeIfPresent(productId, (id, count) -> --count);
}
public void removeProduct(String productId) {
products.remove(productId);
}
public void setOrderConfirmed() {
this.orderStatus = OrderStatus.CONFIRMED;
} | public void setOrderShipped() {
this.orderStatus = OrderStatus.SHIPPED;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order that = (Order) o;
return Objects.equals(orderId, that.orderId) && Objects.equals(products, that.products) && orderStatus == that.orderStatus;
}
@Override
public int hashCode() {
return Objects.hash(orderId, products, orderStatus);
}
@Override
public String toString() {
return "Order{" + "orderId='" + orderId + '\'' + ", products=" + products + ", orderStatus=" + orderStatus + '}';
}
} | repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\coreapi\queries\Order.java | 1 |
请完成以下Java代码 | public final class TbMsgMetaData implements Serializable {
public static final TbMsgMetaData EMPTY = new TbMsgMetaData(0);
private final Map<String, String> data;
public TbMsgMetaData() {
data = new ConcurrentHashMap<>();
}
public TbMsgMetaData(Map<String, String> data) {
this.data = new ConcurrentHashMap<>();
data.forEach(this::putValue);
}
/**
* Internal constructor to create immutable TbMsgMetaData.EMPTY
* */
private TbMsgMetaData(int ignored) {
data = Collections.emptyMap();
}
public String getValue(String key) {
return data.get(key);
}
public void putValue(String key, String value) {
if (key != null && value != null) {
data.put(key, value);
} | }
public Map<String, String> values() {
return new HashMap<>(data);
}
public TbMsgMetaData copy() {
return new TbMsgMetaData(data);
}
@JsonIgnore
public boolean isEmpty() {
return data == null || data.isEmpty();
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsgMetaData.java | 1 |
请完成以下Java代码 | public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing to do
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
// nothing to do
return null;
}
@Override
public String modelChange(final PO po, int type)
{
onNewAndChangeAndDelete(po, type);
return null;
}
private void onNewAndChangeAndDelete(final PO po, int type)
{
if (!(type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE || type == TYPE_AFTER_DELETE))
{
return;
}
final I_C_OrderLine ol = InterfaceWrapperHelper.create(po, I_C_OrderLine.class);
//
// updating the freight cost amount, if necessary
final MOrder orderPO = (MOrder)ol.getC_Order();
final String dontUpdateOrder = Env.getContext(po.getCtx(), OrderFastInput.OL_DONT_UPDATE_ORDER + orderPO.get_ID()); | if (Check.isEmpty(dontUpdateOrder) || !"Y".equals(dontUpdateOrder))
{
final boolean newOrDelete = type == TYPE_AFTER_NEW || type == TYPE_AFTER_DELETE;
final boolean lineNetAmtChanged = po.is_ValueChanged(I_C_OrderLine.COLUMNNAME_LineNetAmt);
final FreightCostRule freightCostRule = FreightCostRule.ofCode(orderPO.getFreightCostRule());
final boolean isCopy = InterfaceWrapperHelper.isCopy(po); // metas: cg: task US215
if (!isCopy && (lineNetAmtChanged || freightCostRule.isNotFixPrice() || newOrDelete))
{
final OrderFreightCostsService orderFreightCostsService = Adempiere.getBean(OrderFreightCostsService.class);
if (orderFreightCostsService.isFreightCostOrderLine(ol))
{
final I_C_Order order = InterfaceWrapperHelper.create(orderPO, I_C_Order.class);
orderFreightCostsService.updateFreightAmt(order);
orderPO.saveEx();
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\OrderLine.java | 1 |
请完成以下Java代码 | public java.lang.String getI_IsImported ()
{
return (java.lang.String)get_Value(COLUMNNAME_I_IsImported);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (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 Window Internal Name.
@param WindowInternalName Window Internal Name */
@Override
public void setWindowInternalName (java.lang.String WindowInternalName)
{
set_Value (COLUMNNAME_WindowInternalName, WindowInternalName);
}
/** Get Window Internal Name.
@return Window Internal Name */
@Override
public java.lang.String getWindowInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_WindowInternalName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_I_DataEntry_Record.java | 1 |
请完成以下Java代码 | public List<String> getCaseKeyNotIn() {
return caseKeyNotIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
public Date getCreatedBefore() {
return createdBefore;
}
public Date getClosedAfter() {
return closedAfter;
}
public Date getClosedBefore() { | return closedBefore;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void setPricePO (BigDecimal PricePO)
{
set_Value (COLUMNNAME_PricePO, PricePO);
}
/** Get PO Price.
@return Price based on a purchase order
*/
public BigDecimal getPricePO ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PricePO);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quality Rating.
@param QualityRating
Method for rating vendors
*/
public void setQualityRating (int QualityRating)
{
set_Value (COLUMNNAME_QualityRating, Integer.valueOf(QualityRating));
}
/** Get Quality Rating.
@return Method for rating vendors
*/
public int getQualityRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_QualityRating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Royalty Amount.
@param RoyaltyAmt
(Included) Amount for copyright, etc.
*/
public void setRoyaltyAmt (BigDecimal RoyaltyAmt)
{
set_Value (COLUMNNAME_RoyaltyAmt, RoyaltyAmt);
}
/** Get Royalty Amount.
@return (Included) Amount for copyright, etc.
*/
public BigDecimal getRoyaltyAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RoyaltyAmt);
if (bd == null)
return Env.ZERO; | return bd;
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
public void setUPC (String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
public String getUPC ()
{
return (String)get_Value(COLUMNNAME_UPC);
}
/** Set Partner Category.
@param VendorCategory
Product Category of the Business Partner
*/
public void setVendorCategory (String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
/** Get Partner Category.
@return Product Category of the Business Partner
*/
public String getVendorCategory ()
{
return (String)get_Value(COLUMNNAME_VendorCategory);
}
/** Set Partner Product Key.
@param VendorProductNo
Product Key of the Business Partner
*/
public void setVendorProductNo (String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
/** Get Partner Product Key.
@return Product Key of the Business Partner
*/
public String getVendorProductNo ()
{
return (String)get_Value(COLUMNNAME_VendorProductNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_PO.java | 1 |
请完成以下Java代码 | class ArticleWithAuthor {
private String title;
private String authorFirstName;
private String authorLastName;
public ArticleWithAuthor(String title, String authorFirstName, String authorLastName) {
this.title = title;
this.authorFirstName = authorFirstName;
this.authorLastName = authorLastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthorFirstName() {
return authorFirstName; | }
public void setAuthorFirstName(String authorFirstName) {
this.authorFirstName = authorFirstName;
}
public String getAuthorLastName() {
return authorLastName;
}
public void setAuthorLastName(String authorLastName) {
this.authorLastName = authorLastName;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\joins\ArticleWithAuthor.java | 1 |
请完成以下Java代码 | public Set<Class<? extends Throwable>> usedForExceptions() {
return this.usedForExceptions;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Properties that = (Properties) o;
return this.delayMs == that.delayMs
&& this.maxAttempts == that.maxAttempts
&& this.numPartitions == that.numPartitions
&& this.suffix.equals(that.suffix)
&& this.type == that.type
&& this.dltStrategy == that.dltStrategy
&& this.kafkaOperations.equals(that.kafkaOperations);
}
@Override
public int hashCode() {
return Objects.hash(this.delayMs, this.suffix, this.type, this.maxAttempts, this.numPartitions,
this.dltStrategy, this.kafkaOperations);
}
@Override
public String toString() {
return "Properties{" +
"delayMs=" + this.delayMs +
", suffix='" + this.suffix + '\'' +
", type=" + this.type +
", maxAttempts=" + this.maxAttempts +
", numPartitions=" + this.numPartitions +
", dltStrategy=" + this.dltStrategy +
", kafkaOperations=" + this.kafkaOperations +
", shouldRetryOn=" + this.shouldRetryOn +
", timeout=" + this.timeout +
'}';
} | public boolean isMainEndpoint() {
return Type.MAIN.equals(this.type);
}
}
enum Type {
MAIN,
RETRY,
/**
* A retry topic reused along sequential retries
* with the same back off interval.
*
* @since 3.0.4
*/
REUSABLE_RETRY_TOPIC,
DLT,
NO_OPS
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopic.java | 1 |
请完成以下Java代码 | public boolean isFiniteTU() {return !id.isVirtualHU() && !isInfiniteCapacity();}
public boolean isInfiniteCapacity() {return qtyCUsPerTU == null;}
@NonNull
public Quantity getQtyCUsPerTU() {return Check.assumeNotNull(qtyCUsPerTU, "Expecting finite capacity: {}", this);}
private void assertProductMatches(@NonNull final ProductId productId)
{
if (this.productId != null && !ProductId.equals(this.productId, productId))
{
throw new AdempiereException("Product ID " + productId + " does not match the product of " + this);
}
}
@NonNull
public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId)
{
return computeQtyTUsOfTotalCUs(totalCUs, productId, QuantityUOMConverters.noConversion());
}
@NonNull
public QtyTU computeQtyTUsOfTotalCUs(@NonNull final Quantity totalCUs, @NonNull final ProductId productId, @NonNull final QuantityUOMConverter uomConverter)
{
assertProductMatches(productId);
if (totalCUs.signum() <= 0)
{
return QtyTU.ZERO;
}
// Infinite capacity
if (qtyCUsPerTU == null)
{
return QtyTU.ONE;
}
final Quantity totalCUsConv = uomConverter.convertQuantityTo(totalCUs, productId, qtyCUsPerTU.getUomId());
final BigDecimal qtyTUs = totalCUsConv.toBigDecimal().divide(qtyCUsPerTU.toBigDecimal(), 0, RoundingMode.UP); | return QtyTU.ofBigDecimal(qtyTUs);
}
@NonNull
public Quantity computeQtyCUsOfQtyTUs(@NonNull final QtyTU qtyTU)
{
if (qtyCUsPerTU == null)
{
throw new AdempiereException("Cannot calculate qty of CUs for infinite capacity");
}
return qtyTU.computeTotalQtyCUsUsingQtyCUsPerTU(qtyCUsPerTU);
}
public Capacity toCapacity()
{
if (productId == null)
{
throw new AdempiereException("Cannot convert to Capacity when no product is specified")
.setParameter("huPIItemProduct", this);
}
if (qtyCUsPerTU == null)
{
throw new AdempiereException("Cannot determine the UOM of " + this)
.setParameter("huPIItemProduct", this);
}
return Capacity.createCapacity(qtyCUsPerTU, productId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUPIItemProduct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "5")
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/5")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
@ApiModelProperty(example = "6")
public String getTaskId() {
return taskId;
} | public void setTaskId(String taskId) {
this.taskId = taskId;
}
public RestVariable getVariable() {
return variable;
}
public void setVariable(RestVariable variable) {
this.variable = variable;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceResponse.java | 2 |
请完成以下Java代码 | public int getM_HU_PackingMaterial_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PI_Item getM_HU_PI_Item()
{
return get_ValueAsPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class);
}
@Override
public void setM_HU_PI_Item(final de.metas.handlingunits.model.I_M_HU_PI_Item M_HU_PI_Item)
{
set_ValueFromPO(COLUMNNAME_M_HU_PI_Item_ID, de.metas.handlingunits.model.I_M_HU_PI_Item.class, M_HU_PI_Item);
}
@Override
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID)
{
if (M_HU_PI_Item_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID);
}
@Override | public int getM_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataSize getH2cMaxContentLength() {
return this.h2cMaxContentLength;
}
public void setH2cMaxContentLength(DataSize h2cMaxContentLength) {
this.h2cMaxContentLength = h2cMaxContentLength;
}
public DataSize getInitialBufferSize() {
return this.initialBufferSize;
}
public void setInitialBufferSize(DataSize initialBufferSize) {
this.initialBufferSize = initialBufferSize;
}
public DataSize getMaxInitialLineLength() {
return this.maxInitialLineLength;
}
public void setMaxInitialLineLength(DataSize maxInitialLineLength) {
this.maxInitialLineLength = maxInitialLineLength;
}
public @Nullable Integer getMaxKeepAliveRequests() {
return this.maxKeepAliveRequests;
}
public void setMaxKeepAliveRequests(@Nullable Integer maxKeepAliveRequests) {
this.maxKeepAliveRequests = maxKeepAliveRequests;
} | public boolean isValidateHeaders() {
return this.validateHeaders;
}
public void setValidateHeaders(boolean validateHeaders) {
this.validateHeaders = validateHeaders;
}
public @Nullable Duration getIdleTimeout() {
return this.idleTimeout;
}
public void setIdleTimeout(@Nullable Duration idleTimeout) {
this.idleTimeout = idleTimeout;
}
} | repos\spring-boot-4.0.1\module\spring-boot-reactor-netty\src\main\java\org\springframework\boot\reactor\netty\autoconfigure\NettyServerProperties.java | 2 |
请完成以下Java代码 | public class OrderConfigDO {
/**
* 编号
*/
private Integer id;
/**
* 支付超时时间
*
* 单位:分钟
*/
private Integer payTimeout;
public Integer getId() {
return id;
} | public OrderConfigDO setId(Integer id) {
this.id = id;
return this;
}
public Integer getPayTimeout() {
return payTimeout;
}
public OrderConfigDO setPayTimeout(Integer payTimeout) {
this.payTimeout = payTimeout;
return this;
}
} | repos\SpringBoot-Labs-master\lab-18\lab-18-sharding-datasource-01\src\main\java\cn\iocoder\springboot\lab18\shardingdatasource\dataobject\OrderConfigDO.java | 1 |
请完成以下Java代码 | public void setIsRentalEquipment (final boolean IsRentalEquipment)
{
set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment);
}
@Override
public boolean isRentalEquipment()
{
return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment);
}
@Override
public void setIsSeriesOrder (final boolean IsSeriesOrder)
{
set_Value (COLUMNNAME_IsSeriesOrder, IsSeriesOrder);
}
@Override
public boolean isSeriesOrder()
{
return get_ValueAsBoolean(COLUMNNAME_IsSeriesOrder);
}
@Override
public void setNextDelivery (final @Nullable java.sql.Timestamp NextDelivery)
{
set_Value (COLUMNNAME_NextDelivery, NextDelivery);
}
@Override
public java.sql.Timestamp getNextDelivery()
{
return get_ValueAsTimestamp(COLUMNNAME_NextDelivery);
}
@Override
public void setRootId (final @Nullable java.lang.String RootId)
{
set_Value (COLUMNNAME_RootId, RootId);
}
@Override
public java.lang.String getRootId()
{
return get_ValueAsString(COLUMNNAME_RootId);
}
@Override
public void setSalesLineId (final @Nullable java.lang.String SalesLineId) | {
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
@Override
public java.lang.String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable java.lang.String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public java.lang.String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaOrder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
public String getPayKey() {
return payKey;
}
public void setPayKey(String payKey) {
this.payKey = payKey;
}
public TradeStatusEnum getTradeStatus() {
return tradeStatus;
}
public void setTradeStatus(TradeStatusEnum tradeStatus) {
this.tradeStatus = tradeStatus;
} | public boolean isAuth() {
return isAuth;
}
public void setAuth(boolean auth) {
isAuth = auth;
}
public Map<String, PayTypeEnum> getPayTypeEnumMap() {
return payTypeEnumMap;
}
public void setPayTypeEnumMap(Map<String, PayTypeEnum> payTypeEnumMap) {
this.payTypeEnumMap = payTypeEnumMap;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthInitResultVo.java | 2 |
请完成以下Java代码 | public void focusGained (FocusEvent e)
{
log.info(e.paramString());
if (e.getSource() instanceof VMemo)
requestFocus();
else
m_oldText = getText();
} // focusGained
/**
* Data Binding to MTable (via GridController)
* @param e
*/
@Override
public void focusLost (FocusEvent e)
{
//log.info( "VMemo.focusLost " + e.getSource(), e.paramString());
// something changed?
return;
} // focusLost
/*************************************************************************/
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override | public GridField getField() {
return m_mField;
}
private class CInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
//NOTE: We return true no matter what since the InputVerifier is only introduced to fireVetoableChange in due time
if (getText() == null && m_oldText == null)
return true;
else if (getText().equals(m_oldText))
return true;
//
try
{
String text = getText();
fireVetoableChange(m_columnName, null, text);
m_oldText = text;
return true;
}
catch (PropertyVetoException pve) {}
return true;
} // verify
} // CInputVerifier
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VMemo | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VMemo.java | 1 |
请完成以下Java代码 | public class AllowedPickToStructures
{
public static final AllowedPickToStructures EMPTY = new AllowedPickToStructures(ImmutableMap.of());
public static final AllowedPickToStructures DEFAULT = new AllowedPickToStructures(ImmutableMap.<PickToStructure, Boolean>builder()
.put(PickToStructure.LU_TU, true)
.build());
@NonNull private final ImmutableMap<PickToStructure, Boolean> map;
@NonNull private final ImmutableSet<PickToStructure> allowed;
private AllowedPickToStructures(@NonNull final ImmutableMap<PickToStructure, Boolean> map)
{
this.map = map;
this.allowed = extractAllowed(map);
}
private static ImmutableSet<PickToStructure> extractAllowed(final @NotNull ImmutableMap<PickToStructure, Boolean> map)
{
final ImmutableSet.Builder<PickToStructure> resultBuilder = ImmutableSet.builder();
map.forEach((pickToStructure, allowedFlag) -> {
if (allowedFlag)
{
resultBuilder.add(pickToStructure);
}
});
return resultBuilder.build();
}
public static AllowedPickToStructures ofMap(@NonNull final Map<PickToStructure, Boolean> map)
{
if (map.isEmpty())
{
return EMPTY;
}
return new AllowedPickToStructures(ImmutableMap.copyOf(map));
}
public static AllowedPickToStructures ofAllowed(@NonNull final Set<PickToStructure> allowed)
{
if (allowed.isEmpty())
{
return EMPTY;
}
final ImmutableMap.Builder<PickToStructure, Boolean> mapBuilder = ImmutableMap.builder();
allowed.forEach(pickToStructure -> mapBuilder.put(pickToStructure, true));
return ofMap(mapBuilder.build());
}
public boolean isEmpty() {return map.isEmpty();}
public @NonNull AllowedPickToStructures fallbackTo(final @NonNull AllowedPickToStructures fallback)
{ | final HashMap<PickToStructure, Boolean> newMap = new HashMap<>();
for (final PickToStructure pickToStructure : PickToStructure.values())
{
if (map.containsKey(pickToStructure))
{
newMap.put(pickToStructure, map.get(pickToStructure));
}
else if (fallback.map.containsKey(pickToStructure))
{
newMap.put(pickToStructure, fallback.map.get(pickToStructure));
}
}
final AllowedPickToStructures result = ofMap(newMap);
return Objects.equals(this, result) ? this : result;
}
public boolean isStrictlyAllowed(@NonNull final PickToStructure pickToStructure)
{
return map.getOrDefault(pickToStructure, false);
}
public @NonNull ImmutableSet<PickToStructure> toAllowedSet() {return allowed;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\config\mobileui\AllowedPickToStructures.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} | public int getSold() {
return sold;
}
public void setSold(int sold) {
this.sold = sold;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", title=" + title + ", sold=" + sold + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootTopNRowsPerGroup\src\main\java\com\bookstore\entity\Author.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.