instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class ProgrammaticBeanLookup {
@SuppressWarnings("unchecked")
public static <T> T lookup(Class<T> clazz, BeanManager bm) {
Iterator<Bean<?>> iter = bm.getBeans(clazz).iterator();
if (!iter.hasNext()) {
throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + clazz.getName());
}
Bean<T> bean = (Bean<T>) iter.next();
CreationalContext<T> ctx = bm.createCreationalContext(bean);
T dao = (T) bm.getReference(bean, clazz, ctx);
return dao;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object lookup(String name, BeanManager bm) {
Set<Bean<?>> beans = bm.getBeans(name);
if (beans.isEmpty()) {
throw new IllegalStateException("CDI BeanManager cannot find an instance of requested type '" + name + "'"); | }
Bean bean = bm.resolve(beans);
CreationalContext ctx = bm.createCreationalContext(bean);
// select one beantype randomly. A bean has a non-empty set of
// beantypes.
Type type = (Type) bean.getTypes().iterator().next();
return bm.getReference(bean, type, ctx);
}
public static <T> T lookup(Class<T> clazz) {
BeanManager bm = BeanManagerLookup.getBeanManager();
return lookup(clazz, bm);
}
public static Object lookup(String name) {
BeanManager bm = BeanManagerLookup.getBeanManager();
return lookup(name, bm);
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\util\ProgrammaticBeanLookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class NursingHome {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" fax: ").append(toIndentedString(fax)).append("\n"); | sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\NursingHome.java | 2 |
请完成以下Java代码 | public class MonitoringEventProducer {
private static final Logger logger = LoggerFactory.getLogger(MonitoringEventProducer.class);
static HollowProducer.Publisher publisher;
static HollowProducer.Announcer announcer;
static HollowProducer producer;
static HollowObjectMapper mapper;
final static long POLL_INTERVAL_MILLISECONDS = 30000;
static MonitoringDataService dataService;
public static void main(String[] args) {
initialize(getSnapshotFilePath());
pollEvents();
}
private static void initialize(final Path snapshotPath) {
publisher = new HollowFilesystemPublisher(snapshotPath);
announcer = new HollowFilesystemAnnouncer(snapshotPath);
producer = HollowProducer.withPublisher(publisher)
.withAnnouncer(announcer)
.build();
dataService = new MonitoringDataService();
mapper = new HollowObjectMapper(producer.getWriteEngine());
}
private static void pollEvents() {
while (true) {
List<MonitoringEvent> events = dataService.retrieveEvents();
events.forEach(mapper::add);
producer.runCycle(task -> {
events.forEach(task::add);
});
producer.getWriteEngine().prepareForNextCycle();
sleep(POLL_INTERVAL_MILLISECONDS);
}
}
private static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); | }
}
private static Path getSnapshotFilePath() {
String moduleDir = System.getProperty("user.dir");
String snapshotDir = moduleDir + "/.hollow/snapshots";
logger.info("snapshot data directory: {}", snapshotDir);
Path snapshotPath = Paths.get(snapshotDir);
// Create directories if they don't exist
try {
Files.createDirectories(snapshotPath);
} catch (java.io.IOException e) {
throw new RuntimeException("Failed to create snapshot directory: " + snapshotDir, e);
}
return snapshotPath;
}
} | repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\producer\MonitoringEventProducer.java | 1 |
请完成以下Java代码 | public java.lang.String getUserName ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserName);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.lang.String Version)
{
set_ValueNoCheck (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.lang.String getVersion ()
{
return (java.lang.String)get_Value(COLUMNNAME_Version);
} | /** Set ZK WebUI URL.
@param WebUI_URL
ZK WebUI root URL
*/
@Override
public void setWebUI_URL (java.lang.String WebUI_URL)
{
set_Value (COLUMNNAME_WebUI_URL, WebUI_URL);
}
/** Get ZK WebUI URL.
@return ZK WebUI root URL
*/
@Override
public java.lang.String getWebUI_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_WebUI_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_System.java | 1 |
请完成以下Java代码 | public Method load(Method interfaceMethod) throws Exception
{
final Method implMethod = findMethodImplementationOrNull(interfaceMethod);
return implMethod == null ? NullMethod.NULL : implMethod;
}
});
public ProxyClassMethodBindings(final Class<?> interfaceClass, final Class<?> implClass)
{
super();
// NOTE: both parameters are not always not null, but we are not checking them for optimization reasons
// this.interfaceClass = interfaceClass;
this.implClass = implClass;
}
private final Method findMethodImplementationOrNull(final Method interfaceMethod)
{
try
{
final String name = interfaceMethod.getName();
final Class<?>[] parameterTypes = interfaceMethod.getParameterTypes();
final Method implMethod = implClass.getMethod(name, parameterTypes);
return implMethod;
}
catch (SecurityException e)
{
throw new IllegalStateException("Cannot get implementation method for " + implClass + ", interfaceMethod=" + interfaceMethod, e);
}
catch (NoSuchMethodException e)
{
return null;
} | }
public Method getMethodImplementation(final Method interfaceMethod)
{
try
{
final Method implMethod = interfaceMethod2implMethod.get(interfaceMethod);
if (implMethod == null || implMethod == NullMethod.NULL)
{
return null;
}
return implMethod;
}
catch (ExecutionException e)
{
// NOTE: shall not happen
final String message = "Error while trying to find implementation method"
+ "\n Interface method: " + interfaceMethod
+ "\n Implementation class: " + implClass;
throw new RuntimeException(message, e.getCause());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\ProxyClassMethodBindings.java | 1 |
请完成以下Java代码 | public BigDecimal convertAmount(final BigDecimal amount)
{
return convertAmount(amount, toCurrencyPrecision);
}
@NonNull
public BigDecimal convertAmount(@NonNull final BigDecimal amount, @NonNull final CurrencyPrecision precisionOverride)
{
final BigDecimal rate = getConversionRate();
final BigDecimal amountConv = rate.multiply(amount);
return precisionOverride.roundIfNeeded(amountConv);
}
/**
* Convert Money from "fromCurrency" to "toCurrency".
* <p>
* Example:
* <pre>
* this.fromCurrency = EUR
* this.toCurrency = CHF
* this.conversionRate = X
*
* amount = Money in EUR
* </pre>
* This method converts the amount from EUR to CHF using the conversionRate.
*
* @param amount amount in {@link #fromCurrencyId}
*/
public Money convertAmount(@NonNull final Money amount)
{
if (amount.getCurrencyId().equals(toCurrencyId))
{
return amount;
}
if (!amount.getCurrencyId().equals(fromCurrencyId))
{
throw new AdempiereException("Cannot convert " + amount + " to " + toCurrencyId + " using " + this);
}
final BigDecimal convertedAmount = convertAmount(amount.toBigDecimal());
return Money.of(convertedAmount, toCurrencyId);
}
/**
* Convert Money from "toCurrency" to "fromCurrency" (ie. do the reverse conversion).
* <p>
* Example:
* <pre>
* this.fromCurrency = EUR
* this.toCurrency = CHF | * this.conversionRate = X
*
* amount = Money in CHF
* </pre>
* This method converts the amount from CHF to EUR using the conversionRate of EUR->CHF. The precision and rounding are those of EUR, for correctness.
*
* @param amount amount in {@link #toCurrencyId}
*/
public Money reverseConvertAmount(@NonNull final Money amount)
{
if (amount.getCurrencyId().equals(fromCurrencyId))
{
return amount;
}
if (!amount.getCurrencyId().equals(toCurrencyId))
{
throw new AdempiereException("Cannot convert " + amount + " to " + fromCurrencyId + " using " + this);
}
final BigDecimal convertedAmount = amount.toBigDecimal().divide(conversionRate, fromCurrencyPrecision.toInt(), fromCurrencyPrecision.getRoundingMode());
return Money.of(convertedAmount, fromCurrencyId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyRate.java | 1 |
请完成以下Java代码 | public ViewRowIdsOrderedSelection createSelection(
@NonNull final ViewEvaluationCtx viewEvalCtx,
final ViewId viewId,
final DocumentFilterList filters,
final DocumentQueryOrderByList orderBys,
@NonNull final SqlDocumentFilterConverterContext filterConverterCtx)
{
final boolean applySecurityRestrictions = true;
return viewSelectionFactory.createOrderedSelection(viewEvalCtx, viewId, filters, orderBys, applySecurityRestrictions, filterConverterCtx);
}
@Override
public ViewRowIdsOrderedSelection createSelectionFromSelection(
@NonNull final ViewEvaluationCtx viewEvalCtx,
final ViewRowIdsOrderedSelection fromSelection,
final DocumentQueryOrderByList orderBys)
{
return viewSelectionFactory.createOrderedSelectionFromSelection(
viewEvalCtx,
fromSelection,
DocumentFilterList.EMPTY,
orderBys,
SqlDocumentFilterConverterContext.builder()
.userRolePermissionsKey(viewEvalCtx.getPermissionsKey())
.build());
}
@Override
public ViewRowIdsOrderedSelection addRowIdsToSelection(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIdsToAdd)
{
return viewSelectionFactory.addRowIdsToSelection(selection, rowIdsToAdd);
}
@Override
public ViewRowIdsOrderedSelection removeRowIdsFromSelection(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIdsToRemove)
{
return viewSelectionFactory.removeRowIdsFromSelection(selection, rowIdsToRemove);
}
@Override
public boolean containsAnyOfRowIds(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds)
{
return viewSelectionFactory.containsAnyOfRowIds(selection, rowIds);
}
@Override
public void deleteSelection(final ViewRowIdsOrderedSelection selection)
{
viewSelectionFactory.deleteSelection(selection.getSelectionId());
}
@Override
public SqlViewRowsWhereClause buildSqlWhereClause(final ViewRowIdsOrderedSelection selection, final DocumentIdsSelection rowIds)
{
return SqlViewSelectionQueryBuilder.prepareSqlWhereClause()
.sqlTableAlias(I_M_HU.Table_Name)
.keyColumnNamesMap(SqlViewKeyColumnNamesMap.ofIntKeyField(I_M_HU.COLUMNNAME_M_HU_ID))
.selectionId(selection.getSelectionId()) | .rowIds(rowIds)
.rowIdsConverter(getRowIdsConverter())
.build();
}
@Override
public void warmUp(@NonNull final Set<HuId> huIds)
{
InterfaceWrapperHelper.loadByRepoIdAwares(huIds, I_M_HU.class); // caches the given HUs with one SQL query
huReservationService.warmup(huIds);
}
@Nullable
private JSONLookupValue getHUClearanceStatusLookupValue(@NonNull final I_M_HU hu)
{
final ClearanceStatus huClearanceStatus = ClearanceStatus.ofNullableCode(hu.getClearanceStatus());
if (huClearanceStatus == null)
{
return null;
}
final ITranslatableString huClearanceStatusCaption = handlingUnitsBL.getClearanceStatusCaption(huClearanceStatus);
return JSONLookupValue.of(huClearanceStatus.getCode(), huClearanceStatusCaption.translate(Env.getAD_Language()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\SqlHUEditorViewRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRespondByDate()
{
return respondByDate;
}
public void setRespondByDate(String respondByDate)
{
this.respondByDate = respondByDate;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PaymentDisputeSummary paymentDisputeSummary = (PaymentDisputeSummary)o;
return Objects.equals(this.amount, paymentDisputeSummary.amount) &&
Objects.equals(this.buyerUsername, paymentDisputeSummary.buyerUsername) &&
Objects.equals(this.closedDate, paymentDisputeSummary.closedDate) &&
Objects.equals(this.openDate, paymentDisputeSummary.openDate) &&
Objects.equals(this.orderId, paymentDisputeSummary.orderId) &&
Objects.equals(this.paymentDisputeId, paymentDisputeSummary.paymentDisputeId) &&
Objects.equals(this.paymentDisputeStatus, paymentDisputeSummary.paymentDisputeStatus) &&
Objects.equals(this.reason, paymentDisputeSummary.reason) &&
Objects.equals(this.respondByDate, paymentDisputeSummary.respondByDate);
}
@Override
public int hashCode()
{
return Objects.hash(amount, buyerUsername, closedDate, openDate, orderId, paymentDisputeId, paymentDisputeStatus, reason, respondByDate);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class PaymentDisputeSummary {\n"); | sb.append(" amount: ").append(toIndentedString(amount)).append("\n");
sb.append(" buyerUsername: ").append(toIndentedString(buyerUsername)).append("\n");
sb.append(" closedDate: ").append(toIndentedString(closedDate)).append("\n");
sb.append(" openDate: ").append(toIndentedString(openDate)).append("\n");
sb.append(" orderId: ").append(toIndentedString(orderId)).append("\n");
sb.append(" paymentDisputeId: ").append(toIndentedString(paymentDisputeId)).append("\n");
sb.append(" paymentDisputeStatus: ").append(toIndentedString(paymentDisputeStatus)).append("\n");
sb.append(" reason: ").append(toIndentedString(reason)).append("\n");
sb.append(" respondByDate: ").append(toIndentedString(respondByDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PaymentDisputeSummary.java | 2 |
请完成以下Java代码 | public String getSourceRef() {
return sourceRef;
}
public void setSourceRef(String sourceRef) {
this.sourceRef = sourceRef;
}
public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
}
public String getTransformation() {
return transformation;
}
public void setTransformation(String transformation) {
this.transformation = transformation;
}
public List<Assignment> getAssignments() {
return assignments;
} | public void setAssignments(List<Assignment> assignments) {
this.assignments = assignments;
}
public DataAssociation clone() {
DataAssociation clone = new DataAssociation();
clone.setValues(this);
return clone;
}
public void setValues(DataAssociation otherAssociation) {
setSourceRef(otherAssociation.getSourceRef());
setTargetRef(otherAssociation.getTargetRef());
setTransformation(otherAssociation.getTransformation());
assignments = new ArrayList<Assignment>();
if (otherAssociation.getAssignments() != null && !otherAssociation.getAssignments().isEmpty()) {
for (Assignment assignment : otherAssociation.getAssignments()) {
assignments.add(assignment.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\DataAssociation.java | 1 |
请完成以下Java代码 | public abstract class WEBUI_PP_Order_HUEditor_ProcessBase extends HUEditorProcessTemplate
{
protected final Stream<HUEditorRow> retrieveSelectedAndEligibleHUEditorRows()
{
final HUEditorView huEditorView = HUEditorView.cast(super.getView());
final Stream<HUEditorRow> huEditorRows = huEditorView.streamByIds(getSelectedRowIds());
return retrieveEligibleHUEditorRows(huEditorRows);
}
protected static Stream<HUEditorRow> retrieveEligibleHUEditorRows(@NonNull final Stream<HUEditorRow> inputStream)
{
final SourceHUsService sourceHuService = SourceHUsService.get();
return inputStream
.filter(HUEditorRow::isHUStatusActive)
.filter(huRow -> !sourceHuService.isHuOrAnyParentSourceHu(huRow.getHuId()));
}
protected Optional<PPOrderLinesView> getPPOrderView()
{
final ViewId parentViewId = getView().getParentViewId();
if (parentViewId == null)
{
return Optional.empty();
}
final PPOrderLinesView ppOrderView = getViewsRepo().getView(parentViewId, PPOrderLinesView.class); | return Optional.of(ppOrderView);
}
@Nullable
protected PPOrderBOMLineId getSelectedOrderBOMLineId()
{
final DocumentId documentId = getView().getParentRowId();
if (documentId == null)
{
return null;
}
return PPOrderLineRowId.fromDocumentId(documentId)
.getPPOrderBOMLineIdIfApplies()
.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_HUEditor_ProcessBase.java | 1 |
请完成以下Java代码 | protected ComboPopup createPopup()
{
final AdempiereComboPopup popup = new AdempiereComboPopup(comboBox);
popup.getAccessibleContext().setAccessibleParent(comboBox);
return popup;
}
public ComboPopup getComboPopup()
{
return popup;
}
public static final ComboPopup getComboPopup(final JComboBox<?> comboBox)
{
final ComboBoxUI comboBoxUI = comboBox.getUI();
if (comboBoxUI instanceof AdempiereComboBoxUI)
{
return ((AdempiereComboBoxUI)comboBoxUI).getComboPopup();
}
//
// Fallback:
// Back door our way to finding the inner JList.
//
// it is unknown whether this functionality will work outside of Sun's
// implementation, but the code is safe and will "fail gracefully" on
// other systems
//
// see javax.swing.plaf.basic.BasicComboBoxUI.getAccessibleChild(JComponent, int)
final Accessible a = comboBoxUI.getAccessibleChild(comboBox, 0);
if (a instanceof ComboPopup)
{
return (ComboPopup)a;
}
else
{
return null;
}
} | public static class AdempiereComboPopup extends BasicComboPopup
{
private static final long serialVersionUID = 3226003169560939486L;
public AdempiereComboPopup(final JComboBox<Object> combo)
{
super(combo);
}
@Override
protected int getPopupHeightForRowCount(final int maxRowCount)
{
// ensure the combo box sized for the amount of data to be displayed
final int itemCount = comboBox.getItemCount();
int rows = itemCount < maxRowCount ? itemCount : maxRowCount;
if (rows <= 0)
rows = 1;
return super.getPopupHeightForRowCount(1) * rows;
}
@Override
protected void configureScroller()
{
super.configureScroller();
// In case user scrolls inside a combobox popup, we want to prevent closing the popup no matter if it could be scrolled or not.
scroller.putClientProperty(AdempiereScrollPaneUI.PROPERTY_DisableWheelEventForwardToParent, true);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereComboBoxUI.java | 1 |
请完成以下Java代码 | public int getC_RfQResponseLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQResponseLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set RfQ Response Line Qty.
@param C_RfQResponseLineQty_ID
Request for Quotation Response Line Quantity
*/
@Override
public void setC_RfQResponseLineQty_ID (int C_RfQResponseLineQty_ID)
{
if (C_RfQResponseLineQty_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_RfQResponseLineQty_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_RfQResponseLineQty_ID, Integer.valueOf(C_RfQResponseLineQty_ID));
}
/** Get RfQ Response Line Qty.
@return Request for Quotation Response Line Quantity
*/
@Override
public int getC_RfQResponseLineQty_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RfQResponseLineQty_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Zugesagter Termin.
@param DatePromised
Zugesagter Termin für diesen Auftrag
*/
@Override
public void setDatePromised (java.sql.Timestamp DatePromised)
{
set_Value (COLUMNNAME_DatePromised, DatePromised);
}
/** Get Zugesagter Termin.
@return Zugesagter Termin für diesen Auftrag
*/
@Override
public java.sql.Timestamp getDatePromised ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DatePromised);
}
/** Set Rabatt %.
@param Discount
Discount in percent
*/
@Override
public void setDiscount (java.math.BigDecimal Discount)
{
set_Value (COLUMNNAME_Discount, Discount);
}
/** Get Rabatt %.
@return Discount in percent
*/
@Override
public java.math.BigDecimal getDiscount ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Discount); | if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Zusagbar.
@param QtyPromised Zusagbar */
@Override
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ranking.
@param Ranking
Relative Rank Number
*/
@Override
public void setRanking (int Ranking)
{
set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty.java | 1 |
请完成以下Java代码 | public static Map<String, byte[]> findResources(ClassLoader classLoader, String paResourceRootPath, URL metaFileUrl, String[] additionalResourceSuffixes) {
ProcessApplicationScanner scanner = null;
try {
// check if we must use JBoss VFS
classLoader.loadClass("org.jboss.vfs.VFS");
scanner = new VfsProcessApplicationScanner();
}
catch (Throwable t) {
scanner = new ClassPathProcessApplicationScanner();
}
return scanner.findResources(classLoader, paResourceRootPath, metaFileUrl, additionalResourceSuffixes);
}
public static boolean isDeployable(String filename) {
return hasSuffix(filename, BpmnDeployer.BPMN_RESOURCE_SUFFIXES)
|| hasSuffix(filename, CmmnDeployer.CMMN_RESOURCE_SUFFIXES)
|| hasSuffix(filename, DecisionDefinitionDeployer.DMN_RESOURCE_SUFFIXES);
}
public static boolean isDeployable(String filename, String[] additionalResourceSuffixes) {
return isDeployable(filename) || hasSuffix(filename, additionalResourceSuffixes);
}
public static boolean hasSuffix(String filename, String[] suffixes) {
if (suffixes == null || suffixes.length == 0) {
return false;
} else {
for (String suffix : suffixes) {
if (filename.endsWith(suffix)) {
return true;
}
}
return false;
}
}
public static boolean isDiagram(String fileName, String modelFileName) {
// process resources
boolean isBpmnDiagram = checkDiagram(fileName, modelFileName, BpmnDeployer.DIAGRAM_SUFFIXES, BpmnDeployer.BPMN_RESOURCE_SUFFIXES);
// case resources
boolean isCmmnDiagram = checkDiagram(fileName, modelFileName, CmmnDeployer.DIAGRAM_SUFFIXES, CmmnDeployer.CMMN_RESOURCE_SUFFIXES);
// decision resources
boolean isDmnDiagram = checkDiagram(fileName, modelFileName, DecisionDefinitionDeployer.DIAGRAM_SUFFIXES, DecisionDefinitionDeployer.DMN_RESOURCE_SUFFIXES); | return isBpmnDiagram || isCmmnDiagram || isDmnDiagram;
}
/**
* Checks, whether a filename is a diagram for the given modelFileName.
*
* @param fileName filename to check.
* @param modelFileName model file name.
* @param diagramSuffixes suffixes of the diagram files.
* @param modelSuffixes suffixes of model files.
* @return true, if a file is a diagram for the model.
*/
protected static boolean checkDiagram(String fileName, String modelFileName, String[] diagramSuffixes, String[] modelSuffixes) {
for (String modelSuffix : modelSuffixes) {
if (modelFileName.endsWith(modelSuffix)) {
String caseFilePrefix = modelFileName.substring(0, modelFileName.length() - modelSuffix.length());
if (fileName.startsWith(caseFilePrefix)) {
for (String diagramResourceSuffix : diagramSuffixes) {
if (fileName.endsWith(diagramResourceSuffix)) {
return true;
}
}
}
}
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\scanning\ProcessApplicationScanningUtil.java | 1 |
请完成以下Java代码 | public synchronized void reset() throws IOException {
wrappedReader.reset();
}
public long skip(long n) throws IOException {
return wrappedReader.skip(n);
}
/**
* Rewinds the reader such that the initial characters are returned when invoking read().
*
* Throws an exception if more than the buffering limit has already been read.
* @throws IOException
*/
public void rewind() throws IOException {
if (!rewindable) {
throw LOG.unableToRewindReader();
} | wrappedReader.unread(buffer, 0, pos);
pos = 0;
}
public int getRewindBufferSize() {
return buffer.length;
}
/**
*
* @return the number of characters that can still be read and rewound.
*/
public int getCurrentRewindableCapacity() {
return buffer.length - pos;
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\RewindableReader.java | 1 |
请完成以下Java代码 | public void setDescription_PrintFormatItem_ID (int Description_PrintFormatItem_ID)
{
if (Description_PrintFormatItem_ID < 1)
set_Value (COLUMNNAME_Description_PrintFormatItem_ID, null);
else
set_Value (COLUMNNAME_Description_PrintFormatItem_ID, Integer.valueOf(Description_PrintFormatItem_ID));
}
/** Get Description Column.
@return Description Column for Pie/Line/Bar Charts
*/
public int getDescription_PrintFormatItem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Description_PrintFormatItem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** GraphType AD_Reference_ID=265 */
public static final int GRAPHTYPE_AD_Reference_ID=265;
/** Pie Chart = P */
public static final String GRAPHTYPE_PieChart = "P";
/** Line Chart = L */
public static final String GRAPHTYPE_LineChart = "L";
/** Bar Chart = B */
public static final String GRAPHTYPE_BarChart = "B";
/** Set Graph Type.
@param GraphType
Type of graph to be painted
*/
public void setGraphType (String GraphType)
{
set_Value (COLUMNNAME_GraphType, GraphType); | }
/** Get Graph Type.
@return Type of graph to be painted
*/
public String getGraphType ()
{
return (String)get_Value(COLUMNNAME_GraphType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintGraph.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean getAsyncCount() {
return asyncCount;
}
public void setAsyncCount(Boolean asyncCount) {
this.asyncCount = asyncCount;
Optional.ofNullable(asyncCount).ifPresent(v -> properties.setProperty("asyncCount", v.toString()));
}
public String getCountSqlParser() {
return countSqlParser;
}
public void setCountSqlParser(String countSqlParser) {
this.countSqlParser = countSqlParser;
Optional.ofNullable(countSqlParser).ifPresent(v -> properties.setProperty("countSqlParser", v));
}
public String getOrderBySqlParser() {
return orderBySqlParser; | }
public void setOrderBySqlParser(String orderBySqlParser) {
this.orderBySqlParser = orderBySqlParser;
Optional.ofNullable(orderBySqlParser).ifPresent(v -> properties.setProperty("orderBySqlParser", v));
}
public String getSqlServerSqlParser() {
return sqlServerSqlParser;
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
this.sqlServerSqlParser = sqlServerSqlParser;
Optional.ofNullable(sqlServerSqlParser).ifPresent(v -> properties.setProperty("sqlServerSqlParser", v));
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperStandardProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class InOutLineId implements RepoIdAware
{
@JsonCreator
public static InOutLineId ofRepoId(final int repoId)
{
return new InOutLineId(repoId);
}
public static InOutLineId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new InOutLineId(repoId) : null;
}
public static int toRepoId(@Nullable final InOutLineId id)
{
return id != null ? id.getRepoId() : -1;
} | int repoId;
private InOutLineId(final int repoId)
{
Check.assumeGreaterThanZero(repoId, "M_InOutLine_ID");
this.repoId = repoId;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\InOutLineId.java | 2 |
请完成以下Java代码 | public Integer getMigrateToCaseDefinitionVersion() {
return this.migrateToCaseDefinitionVersion;
}
@Override
public String getMigrateToCaseDefinitionTenantId() {
return this.migrateToCaseDefinitionTenantId;
}
@Override
public List<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitionMappings() {
return activatePlanItemDefinitionMappings;
}
@Override
public List<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitionMappings() {
return terminatePlanItemDefinitionMappings;
}
@Override
public List<MoveToAvailablePlanItemDefinitionMapping> getMoveToAvailablePlanItemDefinitionMappings() {
return moveToAvailablePlanItemDefinitionMappings;
}
@Override
public List<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitionMappings() {
return waitingForRepetitionPlanItemDefinitionMappings;
}
@Override
public List<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitionMappings() {
return removeWaitingForRepetitionPlanItemDefinitionMappings;
}
@Override
public List<ChangePlanItemIdMapping> getChangePlanItemIdMappings() {
return changePlanItemIdMappings;
}
@Override
public List<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdWithDefinitionIdMappings() {
return changePlanItemIdWithDefinitionIdMappings;
}
@Override
public List<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIdsMappings() { | return changePlanItemDefinitionWithNewTargetIdsMappings;
}
@Override
public String getPreUpgradeExpression() {
return preUpgradeExpression;
}
@Override
public String getPostUpgradeExpression() {
return postUpgradeExpression;
}
@Override
public Map<String, Map<String, Object>> getPlanItemLocalVariables() {
return this.planItemLocalVariables;
}
@Override
public Map<String, Object> getCaseInstanceVariables() {
return this.caseInstanceVariables;
}
@Override
public String asJsonString() {
return CaseInstanceMigrationDocumentConverter.convertToJsonString(this);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\CaseInstanceMigrationDocumentImpl.java | 1 |
请完成以下Java代码 | public void setGreetingStandardType (final @Nullable java.lang.String GreetingStandardType)
{
set_Value (COLUMNNAME_GreetingStandardType, GreetingStandardType);
}
@Override
public java.lang.String getGreetingStandardType()
{
return get_ValueAsString(COLUMNNAME_GreetingStandardType);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setIsFirstNameOnly (final boolean IsFirstNameOnly)
{
set_Value (COLUMNNAME_IsFirstNameOnly, IsFirstNameOnly);
} | @Override
public boolean isFirstNameOnly()
{
return get_ValueAsBoolean(COLUMNNAME_IsFirstNameOnly);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Greeting.java | 1 |
请完成以下Java代码 | public class UserProjector {
UserReadRepository readRepository = new UserReadRepository();
public UserProjector(UserReadRepository readRepository) {
this.readRepository = readRepository;
}
public void project(User user) {
UserContact userContact = Optional.ofNullable(readRepository.getUserContact(user.getUserid()))
.orElse(new UserContact());
Map<String, Set<Contact>> contactByType = new HashMap<>();
for (Contact contact : user.getContacts()) {
Set<Contact> contacts = Optional.ofNullable(contactByType.get(contact.getType()))
.orElse(new HashSet<>());
contacts.add(contact);
contactByType.put(contact.getType(), contacts);
}
userContact.setContactByType(contactByType); | readRepository.addUserContact(user.getUserid(), userContact);
UserAddress userAddress = Optional.ofNullable(readRepository.getUserAddress(user.getUserid()))
.orElse(new UserAddress());
Map<String, Set<Address>> addressByRegion = new HashMap<>();
for (Address address : user.getAddresses()) {
Set<Address> addresses = Optional.ofNullable(addressByRegion.get(address.getState()))
.orElse(new HashSet<>());
addresses.add(address);
addressByRegion.put(address.getState(), addresses);
}
userAddress.setAddressByRegion(addressByRegion);
readRepository.addUserAddress(user.getUserid(), userAddress);
}
} | repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\cqrs\projectors\UserProjector.java | 1 |
请完成以下Java代码 | private String replaceContent(SysUser user,String content){
if (content.indexOf(realNameExp) > 0) {
content = content.replace("$"+realNameExp,user.getRealname()).replace(realNameExp, user.getRealname());
}
if (content.indexOf(CommonConstant.LOGIN_TOKEN) > 0) {
String token = getToken(user);
try {
content = content.replace(CommonConstant.LOGIN_TOKEN, URLEncoder.encode(token, "UTF-8"));
} catch (UnsupportedEncodingException e) {
log.error("邮件消息token编码失败", e.getMessage());
}
}
return content;
}
/**
* 获取token
* @param user
* @return
*/
private String getToken(SysUser user) {
// 生成token
String token = JwtUtil.sign(user.getUsername(), user.getPassword(), CommonConstant.CLIENT_TYPE_PC);
redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
// 设置超时时间 1个小时
redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 1 / 1000);
return token;
}
/**
* 是否定时发送邮箱
* @param toUser | * @param title
* @param content
* @return
*/
private boolean isTimeJobSendEmail(String toUser, String title, String content) {
StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
Boolean timeJobSend = staticConfig.getTimeJobSend();
if(null != timeJobSend && timeJobSend){
this.addSysSmsSend(toUser,title,content);
return true;
}
return false;
}
/**
* 保存到短信发送表
*/
private void addSysSmsSend(String toUser, String title, String content) {
SysMessage sysMessage = new SysMessage();
sysMessage.setEsTitle(title);
sysMessage.setEsContent(content);
sysMessage.setEsReceiver(toUser);
sysMessage.setEsSendStatus("0");
sysMessage.setEsSendNum(0);
sysMessage.setEsType(MessageTypeEnum.YJ.getType());
sysMessageMapper.insert(sysMessage);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\handle\impl\EmailSendMsgHandle.java | 1 |
请完成以下Java代码 | private Class<?> load(Class<?> clazz, Properties properties) {
if (properties != null) {
String className = properties.getProperty(clazz.getName());
if (className != null) {
ClassLoader loader;
try {
loader = Thread.currentThread().getContextClassLoader();
} catch (Exception e) {
throw new ELException("Could not get context class loader", e);
}
try {
return loader == null ? Class.forName(className) : loader.loadClass(className);
} catch (ClassNotFoundException e) {
throw new ELException("Class " + className + " not found", e);
} catch (Exception e) {
throw new ELException("Class " + className + " could not be instantiated", e);
}
}
}
return null;
}
@Override
public final <T> T coerceToType(Object obj, Class<T> targetType) {
return converter.convert(obj, targetType);
}
@Override
public final ObjectValueExpression createValueExpression(Object instance, Class<?> expectedType) {
return new ObjectValueExpression(converter, instance, expectedType);
}
@Override
public final TreeValueExpression createValueExpression(
ELContext context,
String expression,
Class<?> expectedType
) {
return new TreeValueExpression(
store,
context.getFunctionMapper(),
context.getVariableMapper(),
converter,
expression, | expectedType
);
}
@Override
public final TreeMethodExpression createMethodExpression(
ELContext context,
String expression,
Class<?> expectedReturnType,
Class<?>[] expectedParamTypes
) {
return new TreeMethodExpression(
store,
context.getFunctionMapper(),
context.getVariableMapper(),
converter,
expression,
expectedReturnType,
expectedParamTypes
);
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\ExpressionFactoryImpl.java | 1 |
请完成以下Java代码 | public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalDate) {
this.removalTime = removalDate;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getProcessInstanceId() { | return this.processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public static CommentDto fromComment(Comment comment) {
CommentDto dto = new CommentDto();
dto.id = comment.getId();
dto.userId = comment.getUserId();
dto.time = comment.getTime();
dto.taskId = comment.getTaskId();
dto.message = comment.getFullMessage();
dto.removalTime = comment.getRemovalTime();
dto.rootProcessInstanceId = comment.getRootProcessInstanceId();
dto.processInstanceId = comment.getProcessInstanceId();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\CommentDto.java | 1 |
请完成以下Java代码 | protected void prepare()
{
if (I_ESR_Import.Table_Name.equals(getTableName()))
{
esrImportId = ESRImportId.ofRepoId(getRecord_ID());
}
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final I_ESR_Import esrImport = esrImportBL.getById(esrImportId);
Check.errorUnless(esrImport.isValid(), "The document can not be processed, since it is not valid.");
final String description = getProcessInfo().getTitle() + " #" + getPinstanceId().getRepoId();
esrImportBL.complete(esrImport, description);
return "";
}
@Override
protected void postProcess(final boolean success)
{
if (success) | {
final I_ESR_Import esrImport = esrImportBL.getById(esrImportId);
final boolean processed = Services.get(IESRImportBL.class).isProcessed(esrImport);
if (processed)
{
getResult().addSummary(Services.get(IMsgBL.class).parseTranslation(getCtx(), "@ESR_Complete_Process_postProcess@"));
}
else
{
getResult().addSummary(Services.get(IMsgBL.class).parseTranslation(getCtx(), "@" + ESRConstants.ERR_ESR_LINE_WITH_NO_PAYMENT_ACTION + "@"));
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\process\ESR_Complete_Process.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public XMLGregorianCalendar getFromDate() {
return fromDate;
}
/**
* Sets the value of the fromDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setFromDate(XMLGregorianCalendar value) {
this.fromDate = value;
}
/**
* Delivery period - to date.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getToDate() { | return toDate;
}
/**
* Sets the value of the toDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setToDate(XMLGregorianCalendar value) {
this.toDate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\PeriodType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskAssignee() {
return taskAssignee;
}
public void setTaskAssignee(String taskAssignee) {
this.taskAssignee = taskAssignee;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
} | public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public Set<String> getCalledProcessInstanceIds() {
return calledProcessInstanceIds;
}
public void setCalledProcessInstanceIds(Set<String> calledProcessInstanceIds) {
this.calledProcessInstanceIds = calledProcessInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceQueryRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Hints {
private final List<ValueHint> keyHints = new ArrayList<>();
private final List<ValueProvider> keyProviders = new ArrayList<>();
private final List<ValueHint> valueHints = new ArrayList<>();
private final List<ValueProvider> valueProviders = new ArrayList<>();
/**
* The list of well-defined keys, if any. Only applicable if the type of the related
* item is a {@link java.util.Map}. If no extra {@link ValueProvider provider} is
* specified, these values are to be considered a closed-set of the available keys for
* the map.
* @return the key hints
*/
public List<ValueHint> getKeyHints() {
return this.keyHints;
}
/**
* The value providers that are applicable to the keys of this item. Only applicable
* if the type of the related item is a {@link java.util.Map}. Only one
* {@link ValueProvider} is enabled for a key: the first in the list that is supported
* should be used.
* @return the key providers
*/
public List<ValueProvider> getKeyProviders() {
return this.keyProviders;
} | /**
* The list of well-defined values, if any. If no extra {@link ValueProvider provider}
* is specified, these values are to be considered a closed-set of the available
* values for this item.
* @return the value hints
*/
public List<ValueHint> getValueHints() {
return this.valueHints;
}
/**
* The value providers that are applicable to this item. Only one
* {@link ValueProvider} is enabled for an item: the first in the list that is
* supported should be used.
* @return the value providers
*/
public List<ValueProvider> getValueProviders() {
return this.valueProviders;
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\Hints.java | 2 |
请完成以下Java代码 | protected void paintTitleBackground(JXTaskPane group, Graphics g)
{
if (group.isSpecial())
{
g.setColor(specialTitleBackground);
g.fillRoundRect(
0,
0,
group.getWidth(),
getRoundHeight() * 2,
getRoundHeight(),
getRoundHeight());
g.fillRect(
0,
getRoundHeight(),
group.getWidth(),
getTitleHeight(group) - getRoundHeight());
}
else
{
Paint oldPaint = ((Graphics2D)g).getPaint();
GradientPaint gradient = new GradientPaint(
0f,
group.getWidth() / 2,
group.getComponentOrientation().isLeftToRight() ? titleBackgroundGradientStart : titleBackgroundGradientEnd,
group.getWidth(),
getTitleHeight(group),
group.getComponentOrientation().isLeftToRight() ? titleBackgroundGradientEnd : titleBackgroundGradientStart);
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
((Graphics2D)g).setPaint(gradient);
g.fillRoundRect(
0,
0,
group.getWidth(),
getRoundHeight() * 2,
getRoundHeight(),
getRoundHeight());
g.fillRect(
0,
getRoundHeight(),
group.getWidth(),
getTitleHeight(group) - getRoundHeight());
((Graphics2D)g).setPaint(oldPaint);
}
} | @Override
protected void paintExpandedControls(JXTaskPane group, Graphics g, int x, int y, int width, int height)
{
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
paintOvalAroundControls(group, g, x, y, width, height);
g.setColor(getPaintColor(group));
paintChevronControls(group, g, x, y, width, height);
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
}
@Override
protected boolean isMouseOverBorder()
{
return true;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereTaskPaneUI.java | 1 |
请完成以下Java代码 | public void setPrintPackageInfos(List<PrintPackageInfo> printPackageInfos)
{
this.printPackageInfos = printPackageInfos;
}
public String getPrintJobInstructionsID()
{
return printJobInstructionsID;
}
public void setPrintJobInstructionsID(String printJobInstructionsID)
{
this.printJobInstructionsID = printJobInstructionsID;
}
public int getCopies()
{
return copies;
}
public void setCopies(final int copies)
{
this.copies = copies;
}
@Override
public String toString()
{
return String.format("PrintPackage [transactionId=%s, printPackageId=%s, pageCount=%s, copies=%s, format=%s, printPackageInfos=%s, printJobInstructionsID=%s]", transactionId, printPackageId,
pageCount, copies, format, printPackageInfos, printJobInstructionsID);
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + copies;
result = prime * result + ((format == null) ? 0 : format.hashCode());
result = prime * result + pageCount;
result = prime * result + ((printJobInstructionsID == null) ? 0 : printJobInstructionsID.hashCode());
result = prime * result + ((printPackageId == null) ? 0 : printPackageId.hashCode());
result = prime * result + ((printPackageInfos == null) ? 0 : printPackageInfos.hashCode());
result = prime * result + ((transactionId == null) ? 0 : transactionId.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintPackage other = (PrintPackage)obj;
if (copies != other.copies)
return false;
if (format == null)
{
if (other.format != null)
return false;
} | else if (!format.equals(other.format))
return false;
if (pageCount != other.pageCount)
return false;
if (printJobInstructionsID == null)
{
if (other.printJobInstructionsID != null)
return false;
}
else if (!printJobInstructionsID.equals(other.printJobInstructionsID))
return false;
if (printPackageId == null)
{
if (other.printPackageId != null)
return false;
}
else if (!printPackageId.equals(other.printPackageId))
return false;
if (printPackageInfos == null)
{
if (other.printPackageInfos != null)
return false;
}
else if (!printPackageInfos.equals(other.printPackageInfos))
return false;
if (transactionId == null)
{
if (other.transactionId != null)
return false;
}
else if (!transactionId.equals(other.transactionId))
return false;
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String getId(T item) {
try {
return PropertyUtils.getProperty(item, "id").toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 获取上传文件对象
MultipartFile file = entity.getValue();
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
// 代码逻辑说明: 批量插入数据
long start = System.currentTimeMillis();
service.saveBatch(list); | //400条 saveBatch消耗时间1592毫秒 循环插入消耗时间1947毫秒
//1200条 saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
return Result.ok("文件导入成功!数据行数:" + list.size());
} catch (Exception e) {
// 代码逻辑说明: 导入数据重复增加提示
String msg = e.getMessage();
log.error(msg, e);
if(msg!=null && msg.indexOf("Duplicate entry")>=0){
return Result.error("文件导入失败:有重复数据!");
}else{
return Result.error("文件导入失败:" + e.getMessage());
}
} finally {
try {
file.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Result.error("文件导入失败!");
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\base\controller\JeecgController.java | 2 |
请完成以下Java代码 | public IScriptsRegistry getScriptsRegistry()
{
return scriptsRegistry;
}
@Override
public Connection getConnection()
{
//
// First time => driver initialization
if (conn == null)
{
final ISQLDatabaseDriver dbDriver = SQLDatabaseDriverFactory.get().getSQLDatabaseDriver(dbType);
if (dbDriver == null)
{
throw new IllegalStateException("No driver found for database type: " + dbType);
}
}
try
{
if (conn != null && !conn.isClosed()) | {
return conn;
}
final ISQLDatabaseDriver dbDriver = SQLDatabaseDriverFactory.get().getSQLDatabaseDriver(dbType);
conn = dbDriver.getConnection(dbHostname, dbPort, dbName, dbUser, dbPassword);
conn.setAutoCommit(true);
}
catch (final SQLException e)
{
throw new RuntimeException("Failed to get a JDBC connection. Please check your config for : " + this, e);
}
return conn;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\SQLDatabase.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ContactController {
@GetMapping
public List<Contact> getContacts() {
List<Contact> contacts = new ArrayList<>();
Contact contact1 = new Contact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact2 = new Contact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
Contact contact3 = new Contact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/javaUtilDate")
public List<ContactWithJavaUtilDate> getContactsWithJavaUtilDate() {
List<ContactWithJavaUtilDate> contacts = new ArrayList<>();
ContactWithJavaUtilDate contact1 = new ContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact2 = new ContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
ContactWithJavaUtilDate contact3 = new ContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plain")
public List<PlainContact> getPlainContacts() {
List<PlainContact> contacts = new ArrayList<>(); | PlainContact contact1 = new PlainContact("John Doe", "123 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact2 = new PlainContact("John Doe 2", "124 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
PlainContact contact3 = new PlainContact("John Doe 3", "125 Sesame Street", "123-456-789", LocalDate.now(), LocalDateTime.now());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
@GetMapping("/plainWithJavaUtilDate")
public List<PlainContactWithJavaUtilDate> getPlainContactsWithJavaUtilDate() {
List<PlainContactWithJavaUtilDate> contacts = new ArrayList<>();
PlainContactWithJavaUtilDate contact1 = new PlainContactWithJavaUtilDate("John Doe", "123 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact2 = new PlainContactWithJavaUtilDate("John Doe 2", "124 Sesame Street", "123-456-789", new Date(), new Date());
PlainContactWithJavaUtilDate contact3 = new PlainContactWithJavaUtilDate("John Doe 3", "125 Sesame Street", "123-456-789", new Date(), new Date());
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
return contacts;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\jsondateformat\ContactController.java | 2 |
请完成以下Java代码 | public QueueStats findQueueStatsById(TenantId tenantId, QueueStatsId queueStatsId) {
log.trace("Executing findQueueStatsById [{}]", queueStatsId);
validateId(queueStatsId, id -> "Incorrect queueStatsId " + id);
return queueStatsDao.findById(tenantId, queueStatsId.getId());
}
@Override
public List<QueueStats> findQueueStatsByIds(TenantId tenantId, List<QueueStatsId> queueStatsIds) {
log.trace("Executing findQueueStatsByIds, tenantId [{}], queueStatsIds [{}]", tenantId, queueStatsIds);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateIds(queueStatsIds, ids -> "Incorrect queueStatsIds " + ids);
return queueStatsDao.findByIds(tenantId, queueStatsIds);
}
@Override
public QueueStats findByTenantIdAndNameAndServiceId(TenantId tenantId, String queueName, String serviceId) {
log.trace("Executing findByTenantIdAndNameAndServiceId, tenantId: [{}], queueName: [{}], serviceId: [{}]", tenantId, queueName, serviceId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
return queueStatsDao.findByTenantIdQueueNameAndServiceId(tenantId, queueName, serviceId);
}
@Override
public PageData<QueueStats> findByTenantId(TenantId tenantId, PageLink pageLink) {
log.trace("Executing findByTenantId, tenantId: [{}]", tenantId);
Validator.validatePageLink(pageLink);
return queueStatsDao.findAllByTenantId(tenantId, pageLink);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
queueStatsDao.deleteByTenantId(tenantId);
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
queueStatsDao.removeById(tenantId, id.getId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build()); | }
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findQueueStatsById(tenantId, new QueueStatsId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(queueStatsDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.QUEUE_STATS;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\queue\BaseQueueStatsService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomerDetailRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public Customer getCustomerDetail(Integer customerId) {
String customerQuery = "select * from customer where customerid = ? ";
Customer customer = new Customer();
jdbcTemplate.query(customerQuery, new Object[] { customerId }, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
customer.setCustomerId(rs.getInt("customerid"));
customer.setCustomerName(rs.getString("customername"));
}
});
return customer;
}
public List<Order> getCustomerOrders(Integer customerId) { | String customerOrderQuery = "select * from orderdetail where customerid = ? ";
List<Order> orders = new ArrayList<Order>();
jdbcTemplate.query(customerOrderQuery, new Object[] { customerId }, new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
Order order = new Order();
order.setCustomerId(rs.getInt("customerid"));
order.setItemId(rs.getInt("orderid"));
order.setOrderId(rs.getInt("orderid"));
order.setQuantity(rs.getInt("quantity"));
orders.add(order);
}
});
return orders;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\multiplecachemanager\repository\CustomerDetailRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) {
return new RestTemplate(Arrays.asList(hmc));
}
@Bean
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
@Bean
public CourseRepository createTestCourses() {
Map<Integer, Course> courses = new HashMap<>();
Course course1 = Course.newBuilder().setId(1).setCourseName("REST with Spring").addAllStudent(createTestStudents()).build();
Course course2 = Course.newBuilder().setId(2).setCourseName("Learn Spring Security").addAllStudent(new ArrayList<>()).build();
courses.put(course1.getId(), course1);
courses.put(course2.getId(), course2);
return new CourseRepository(courses);
} | private List<Student> createTestStudents() {
PhoneNumber phone1 = createPhone("123456", PhoneType.MOBILE);
Student student1 = createStudent(1, "John", "Doe", "john.doe@baeldung.com", Arrays.asList(phone1));
PhoneNumber phone2 = createPhone("234567", PhoneType.LANDLINE);
Student student2 = createStudent(2, "Richard", "Roe", "richard.roe@baeldung.com", Arrays.asList(phone2));
PhoneNumber phone3_1 = createPhone("345678", PhoneType.MOBILE);
PhoneNumber phone3_2 = createPhone("456789", PhoneType.LANDLINE);
Student student3 = createStudent(3, "Jane", "Doe", "jane.doe@baeldung.com", Arrays.asList(phone3_1, phone3_2));
return Arrays.asList(student1, student2, student3);
}
private Student createStudent(int id, String firstName, String lastName, String email, List<PhoneNumber> phones) {
return Student.newBuilder().setId(id).setFirstName(firstName).setLastName(lastName).setEmail(email).addAllPhone(phones).build();
}
private PhoneNumber createPhone(String number, PhoneType type) {
return PhoneNumber.newBuilder().setNumber(number).setType(type).build();
}
} | repos\tutorials-master\spring-remoting-modules\spring-protobuf\src\main\java\com\baeldung\protobuf\Application.java | 2 |
请完成以下Java代码 | protected Class<NotificationTemplateEntity> getEntityClass() {
return NotificationTemplateEntity.class;
}
@Override
public PageData<NotificationTemplate> findByTenantIdAndNotificationTypesAndPageLink(TenantId tenantId, List<NotificationType> notificationTypes, PageLink pageLink) {
return DaoUtil.toPageData(notificationTemplateRepository.findByTenantIdAndNotificationTypesAndSearchText(tenantId.getId(),
notificationTypes, pageLink.getTextSearch(), DaoUtil.toPageable(pageLink)));
}
@Override
public int countByTenantIdAndNotificationTypes(TenantId tenantId, Collection<NotificationType> notificationTypes) {
return notificationTemplateRepository.countByTenantIdAndNotificationTypes(tenantId.getId(), notificationTypes);
}
@Override
public void removeByTenantId(TenantId tenantId) {
notificationTemplateRepository.deleteByTenantId(tenantId.getId());
}
@Override
public NotificationTemplate findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public NotificationTemplate findByTenantIdAndName(UUID tenantId, String name) {
return DaoUtil.getData(notificationTemplateRepository.findByTenantIdAndName(tenantId, name));
} | @Override
public PageData<NotificationTemplate> findByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.toPageData(notificationTemplateRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink)));
}
@Override
public NotificationTemplateId getExternalIdByInternal(NotificationTemplateId internalId) {
return DaoUtil.toEntityId(notificationTemplateRepository.getExternalIdByInternal(internalId.getId()), NotificationTemplateId::new);
}
@Override
public PageData<NotificationTemplate> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
protected JpaRepository<NotificationTemplateEntity, UUID> getRepository() {
return notificationTemplateRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TEMPLATE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationTemplateDao.java | 1 |
请完成以下Java代码 | public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{ | return new KeyNamePair(get_ID(), getName());
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SalesRegion.java | 1 |
请完成以下Java代码 | public Builder audience(List<String> audience) {
return claim(JwtClaimNames.AUD, audience);
}
/**
* Sets the expiration time {@code (exp)} claim, which identifies the time on or
* after which the JWT MUST NOT be accepted for processing.
* @param expiresAt the time on or after which the JWT MUST NOT be accepted for
* processing
* @return the {@link Builder}
*/
public Builder expiresAt(Instant expiresAt) {
return claim(JwtClaimNames.EXP, expiresAt);
}
/**
* Sets the not before {@code (nbf)} claim, which identifies the time before which
* the JWT MUST NOT be accepted for processing.
* @param notBefore the time before which the JWT MUST NOT be accepted for
* processing
* @return the {@link Builder}
*/
public Builder notBefore(Instant notBefore) {
return claim(JwtClaimNames.NBF, notBefore);
}
/**
* Sets the issued at {@code (iat)} claim, which identifies the time at which the
* JWT was issued.
* @param issuedAt the time at which the JWT was issued
* @return the {@link Builder}
*/
public Builder issuedAt(Instant issuedAt) {
return claim(JwtClaimNames.IAT, issuedAt);
}
/**
* Sets the JWT ID {@code (jti)} claim, which provides a unique identifier for the
* JWT.
* @param jti the unique identifier for the JWT
* @return the {@link Builder}
*/
public Builder id(String jti) {
return claim(JwtClaimNames.JTI, jti);
}
/**
* Sets the claim.
* @param name the claim name
* @param value the claim value
* @return the {@link Builder}
*/
public Builder claim(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.put(name, value);
return this; | }
/**
* A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove.
* @param claimsConsumer a {@code Consumer} of the claims
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Builds a new {@link JwtClaimsSet}.
* @return a {@link JwtClaimsSet}
*/
public JwtClaimsSet build() {
Assert.notEmpty(this.claims, "claims cannot be empty");
// The value of the 'iss' claim is a String or URL (StringOrURI).
// Attempt to convert to URL.
Object issuer = this.claims.get(JwtClaimNames.ISS);
if (issuer != null) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class);
if (convertedValue != null) {
this.claims.put(JwtClaimNames.ISS, convertedValue);
}
}
return new JwtClaimsSet(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimsSet.java | 1 |
请完成以下Java代码 | public List<JsonInventoryLineHU> toJsonInventoryLineHUs(@NonNull final InventoryLine line)
{
return line.getInventoryLineHUs()
.stream()
.filter(lineHU -> lineHU.getId() != null)
.map(lineHU -> toJson(lineHU, line))
.collect(ImmutableList.toImmutableList());
}
public JsonInventoryLineHU toJson(final InventoryLineHU lineHU, InventoryLine line)
{
final ProductInfo product = products.getById(line.getProductId());
final HuId huId = lineHU.getHuId();
final String productName = product.getProductName().translate(adLanguage);
final String huDisplayName = huId != null ? handlingUnits.getDisplayName(huId) : null;
return JsonInventoryLineHU.builder()
.id(lineHU.getIdNotNull())
.caption(CoalesceUtil.firstNotBlank(huDisplayName, productName))
.productId(product.getProductId())
.productNo(product.getProductNo())
.productName(productName)
.locatorId(line.getLocatorId().getRepoId())
.locatorName(warehouses.getLocatorName(line.getLocatorId()))
.huId(huId)
.huDisplayName(huDisplayName) | .uom(lineHU.getUOMSymbol())
.qtyBooked(lineHU.getQtyBook().toBigDecimal())
.qtyCount(lineHU.getQtyCount().toBigDecimal())
.countStatus(computeCountStatus(lineHU))
.attributes(loadAllDetails ? JsonAttribute.of(asis.getById(lineHU.getAsiId()), adLanguage) : null)
.build();
}
public JsonInventoryLineHU toJson(final InventoryLine line, final InventoryLineHUId lineHUId)
{
final InventoryLineHU lineHU = line.getInventoryLineHUById(lineHUId);
return toJson(lineHU, line);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\mappers\JsonInventoryJobMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DynamicInsertConfig {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.hibernate.dynamicinsert.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager; | }
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto")));
properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect")));
properties.setProperty("hibernate.show_sql", "false");
return properties;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\dynamicinsert\DynamicInsertConfig.java | 2 |
请完成以下Java代码 | default boolean waitForAssignment(Duration duration) throws InterruptedException {
throw new UnsupportedOperationException();
}
/**
* Send a request message and receive a reply message with the default timeout.
* @param message the message to send.
* @return a RequestReplyMessageFuture.
* @since 2.7
*
*/
default RequestReplyMessageFuture<K, V> sendAndReceive(Message<?> message) {
throw new UnsupportedOperationException();
}
/**
* Send a request message and receive a reply message.
* @param message the message to send.
* @param replyTimeout the reply timeout; if null, the default will be used.
* @return a RequestReplyMessageFuture.
* @since 2.7
*/
default RequestReplyMessageFuture<K, V> sendAndReceive(Message<?> message, @Nullable Duration replyTimeout) {
throw new UnsupportedOperationException();
}
/**
* Send a request message and receive a reply message.
* @param message the message to send.
* @param returnType a hint to the message converter for the reply payload type.
* @param <P> the reply payload type.
* @return a RequestReplyMessageFuture.
* @since 2.7
*/
default <P> RequestReplyTypedMessageFuture<K, V, P> sendAndReceive(Message<?> message,
ParameterizedTypeReference<P> returnType) {
throw new UnsupportedOperationException();
}
/**
* Send a request message and receive a reply message.
* @param message the message to send.
* @param replyTimeout the reply timeout; if null, the default will be used.
* @param returnType a hint to the message converter for the reply payload type.
* @param <P> the reply payload type.
* @return a RequestReplyMessageFuture.
* @since 2.7
*/
default <P> RequestReplyTypedMessageFuture<K, V, P> sendAndReceive(Message<?> message, Duration replyTimeout, | @Nullable ParameterizedTypeReference<P> returnType) {
throw new UnsupportedOperationException();
}
/**
* Send a request and receive a reply with the default timeout.
* @param record the record to send.
* @return a RequestReplyFuture.
*/
RequestReplyFuture<K, V, R> sendAndReceive(ProducerRecord<K, V> record);
/**
* Send a request and receive a reply.
* @param record the record to send.
* @param replyTimeout the reply timeout; if null, the default will be used.
* @return a RequestReplyFuture.
* @since 2.3
*/
RequestReplyFuture<K, V, R> sendAndReceive(ProducerRecord<K, V> record, Duration replyTimeout);
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\requestreply\ReplyingKafkaOperations.java | 1 |
请完成以下Java代码 | public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Overtime Amount.
@param OvertimeAmt
Hourly Overtime Rate
*/
public void setOvertimeAmt (BigDecimal OvertimeAmt)
{
set_Value (COLUMNNAME_OvertimeAmt, OvertimeAmt);
}
/** Get Overtime Amount.
@return Hourly Overtime Rate
*/
public BigDecimal getOvertimeAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Overtime Cost.
@param OvertimeCost
Hourly Overtime Cost
*/
public void setOvertimeCost (BigDecimal OvertimeCost)
{
set_Value (COLUMNNAME_OvertimeCost, OvertimeCost);
}
/** Get Overtime Cost.
@return Hourly Overtime Cost
*/
public BigDecimal getOvertimeCost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** RemunerationType AD_Reference_ID=346 */
public static final int REMUNERATIONTYPE_AD_Reference_ID=346;
/** Hourly = H */
public static final String REMUNERATIONTYPE_Hourly = "H";
/** Daily = D */
public static final String REMUNERATIONTYPE_Daily = "D";
/** Weekly = W */
public static final String REMUNERATIONTYPE_Weekly = "W";
/** Monthly = M */
public static final String REMUNERATIONTYPE_Monthly = "M"; | /** Twice Monthly = T */
public static final String REMUNERATIONTYPE_TwiceMonthly = "T";
/** Bi-Weekly = B */
public static final String REMUNERATIONTYPE_Bi_Weekly = "B";
/** Set Remuneration Type.
@param RemunerationType
Type of Remuneration
*/
public void setRemunerationType (String RemunerationType)
{
set_Value (COLUMNNAME_RemunerationType, RemunerationType);
}
/** Get Remuneration Type.
@return Type of Remuneration
*/
public String getRemunerationType ()
{
return (String)get_Value(COLUMNNAME_RemunerationType);
}
/** Set Standard Hours.
@param StandardHours
Standard Work Hours based on Remuneration Type
*/
public void setStandardHours (int StandardHours)
{
set_Value (COLUMNNAME_StandardHours, Integer.valueOf(StandardHours));
}
/** Get Standard Hours.
@return Standard Work Hours based on Remuneration Type
*/
public int getStandardHours ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StandardHours);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Remuneration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void applyProperties(MailProperties properties, JavaMailSenderImpl sender,
@Nullable SslBundles sslBundles) {
sender.setHost(properties.getHost());
if (properties.getPort() != null) {
sender.setPort(properties.getPort());
}
sender.setUsername(properties.getUsername());
sender.setPassword(properties.getPassword());
sender.setProtocol(properties.getProtocol());
if (properties.getDefaultEncoding() != null) {
sender.setDefaultEncoding(properties.getDefaultEncoding().name());
}
Properties javaMailProperties = asProperties(properties.getProperties());
String protocol = properties.getProtocol();
protocol = (!StringUtils.hasLength(protocol)) ? "smtp" : protocol;
Ssl ssl = properties.getSsl();
if (ssl.isEnabled()) {
javaMailProperties.setProperty("mail." + protocol + ".ssl.enable", "true");
} | if (ssl.getBundle() != null) {
Assert.state(sslBundles != null, "'sslBundles' must not be null");
SslBundle sslBundle = sslBundles.getBundle(ssl.getBundle());
javaMailProperties.put("mail." + protocol + ".ssl.socketFactory",
sslBundle.createSslContext().getSocketFactory());
}
if (!javaMailProperties.isEmpty()) {
sender.setJavaMailProperties(javaMailProperties);
}
}
private Properties asProperties(Map<String, String> source) {
Properties properties = new Properties();
properties.putAll(source);
return properties;
}
} | repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailSenderPropertiesConfiguration.java | 2 |
请完成以下Java代码 | public static HUTraceResultExtender createForRepositoryAndconverter(
@NonNull final HUTraceRepository huTraceRepository,
@NonNull final SqlDocumentFilterConverter converter)
{
return new HUTraceResultExtender(huTraceRepository, converter);
}
private final HUTraceRepository huTraceRepository;
private final SqlDocumentFilterConverter converter;
private HUTraceResultExtender(
@NonNull final HUTraceRepository huTraceRepository,
@NonNull final SqlDocumentFilterConverter converter)
{
this.huTraceRepository = huTraceRepository;
this.converter = converter;
}
@Override
public boolean canConvert(final String filterId)
{
return true;
}
@Override
public FilterSql getSql(
@NonNull final DocumentFilter filter,
@NonNull final SqlOptions sqlOpts,
@NonNull final SqlDocumentFilterConverterContext context)
{
if (!filter.hasParameters() || isSQLOnly(filter))
{ | return converter.getSql(filter, sqlOpts, context); // do whatever the system usually does
}
else
{
final HUTraceEventQuery huTraceQuery = HuTraceQueryCreator.createTraceQueryFromDocumentFilter(filter);
final PInstanceId selectionId = huTraceRepository.queryToSelection(huTraceQuery);
return FilterSql.ofWhereClause(WHERE_IN_T_SELECTION, selectionId);
}
}
private static boolean isSQLOnly(final @NonNull DocumentFilter filter)
{
return filter.getParameters().stream().allMatch(DocumentFilterParam::isSqlFilter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\trace\HUTraceResultExtender.java | 1 |
请完成以下Java代码 | private String lookForAttachedRef(String boundaryEventId, JsonNode childShapesNode) {
String attachedRefId = null;
if (childShapesNode != null) {
for (JsonNode childNode : childShapesNode) {
ArrayNode outgoingNode = (ArrayNode) childNode.get("outgoing");
if (outgoingNode != null && outgoingNode.size() > 0) {
for (JsonNode outgoingChildNode : outgoingNode) {
JsonNode resourceNode = outgoingChildNode.get(EDITOR_SHAPE_ID);
if (resourceNode != null && boundaryEventId.equals(resourceNode.asText())) {
attachedRefId = BpmnJsonConverterUtil.getElementId(childNode);
break;
}
} | if (attachedRefId != null) {
break;
}
}
attachedRefId = lookForAttachedRef(boundaryEventId, childNode.get(EDITOR_CHILD_SHAPES));
if (attachedRefId != null) {
break;
}
}
}
return attachedRefId;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BoundaryEventJsonConverter.java | 1 |
请完成以下Java代码 | public SpinXmlDataFormatException unableToMapInput(Object parameter, Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("027", "Unable to map object '{}' to xml element", parameter.toString()), cause);
}
public SpinXmlDataFormatException unableToDeserialize(Object node, String canonicalClassName, Throwable cause) {
return new SpinXmlDataFormatException(
exceptionMessage("028", "Cannot deserialize '{}...' to java class '{}'", node.toString(), canonicalClassName), cause);
}
public SpinXmlDataFormatException unableToCreateMarshaller(Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("029", "Cannot create marshaller"), cause);
}
public SpinXmlDataFormatException unableToCreateContext(Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("030", "Cannot create context"), cause);
}
public SpinXmlDataFormatException unableToCreateUnmarshaller(Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("031", "Cannot create unmarshaller"), cause);
}
public SpinXmlDataFormatException unableToSetEventHandler(String className, Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("032", "Cannot set event handler to '{}'", className), cause);
}
public SpinXmlDataFormatException unableToSetProperty(String propertyName, String className, Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("033", "Cannot set property '{}' to '{}'", propertyName, className), cause);
}
public SpinXPathException notAllowedXPathExpression(String expression) {
return new SpinXPathException(exceptionMessage("034", "XPath expression '{}' not allowed", expression)); | }
public SpinXPathException unableToFindXPathExpression(String expression) {
return new SpinXPathException(exceptionMessage("035", "Unable to find XPath expression '{}'", expression));
}
public SpinXmlElementException elementIsNotChildOfThisElement(SpinXmlElement existingChildElement, SpinXmlElement parentDomElement) {
return new SpinXmlElementException(exceptionMessage("036", "The element with namespace '{}' and name '{}' " +
"is not a child element of the element with namespace '{}' and name '{}'",
existingChildElement.namespace(), existingChildElement.name(),
parentDomElement.namespace(), parentDomElement.name()
));
}
public SpinXmlDataFormatException unableToFindStripSpaceXsl(String expression) {
return new SpinXmlDataFormatException(exceptionMessage("037", "No formatting configuration defined and unable to find the default '{}'", expression));
}
public SpinXmlDataFormatException unableToLoadFormattingTemplates(Throwable cause) {
return new SpinXmlDataFormatException(exceptionMessage("038", "Failed to get formatting templates"), cause);
}
} | repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlLogger.java | 1 |
请完成以下Java代码 | public static Object encrypt(Object value)
{
if (value instanceof String)
return encrypt((String)value);
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear values
*
* @param value encrypted value
* @return decrypted String
*/
public static Object decrypt(Object value)
{
if (value instanceof String)
return decrypt((String)value);
return value;
} // decrypt
/** Test String */
private static final String TEST = "This is a 0123456789 .,; -= Test!";
/** Secure Engine */
private static SecureEngine s_engine = null;
/** The real Engine */
private SecureInterface implementation = null;
/** Logger */
private static final Logger log = LogManager.getLogger(SecureEngine.class);
/**
* SecureEngine constructor
* | * @param className class name if null defaults to org.compiere.util.Secure
*/
private SecureEngine(String className)
{
String realClass = className;
if (realClass == null || realClass.length() == 0)
realClass = SecureInterface.METASFRESH_SECURE_DEFAULT;
Exception cause = null;
try
{
final Class<?> clazz = Class.forName(realClass);
implementation = (SecureInterface)clazz.newInstance();
}
catch (Exception e)
{
cause = e;
}
if (implementation == null)
{
String msg = "Could not initialize: " + realClass + " - " + cause.toString()
+ "\nCheck start script parameter: " + SecureInterface.METASFRESH_SECURE;
log.error(msg);
System.err.println(msg);
System.exit(10);
}
// See if it works
String testE = implementation.encrypt(TEST);
String testC = implementation.decrypt(testE);
if (!testC.equals(TEST))
throw new IllegalStateException(realClass
+ ": " + TEST
+ "->" + testE + "->" + testC);
log.info("{} initialized - {}", realClass, implementation);
} // SecureEngine
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\SecureEngine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateTaskTenantIdForDeployment(String deploymentId, String tenantId) {
getTaskEntityManager().updateTaskTenantIdForDeployment(deploymentId, tenantId);
}
@Override
public void updateTask(TaskEntity taskEntity, boolean fireUpdateEvent) {
getTaskEntityManager().update(taskEntity, fireUpdateEvent);
}
@Override
public void updateAllTaskRelatedEntityCountFlags(boolean configProperty) {
getTaskEntityManager().updateAllTaskRelatedEntityCountFlags(configProperty);
}
@Override
public TaskEntity createTask() {
return getTaskEntityManager().create();
}
@Override
public void insertTask(TaskEntity taskEntity, boolean fireCreateEvent) {
getTaskEntityManager().insert(taskEntity, fireCreateEvent);
} | @Override
public void deleteTask(TaskEntity task, boolean fireEvents) {
getTaskEntityManager().delete(task, fireEvents);
}
@Override
public void deleteTasksByExecutionId(String executionId) {
getTaskEntityManager().deleteTasksByExecutionId(executionId);
}
public TaskEntityManager getTaskEntityManager() {
return configuration.getTaskEntityManager();
}
@Override
public TaskEntity createTask(TaskBuilder taskBuilder) {
return getTaskEntityManager().createTask(taskBuilder);
}
protected VariableServiceConfiguration getVariableServiceConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (VariableServiceConfiguration) engineConfiguration.getServiceConfigurations().get(EngineConfigurationConstants.KEY_VARIABLE_SERVICE_CONFIG);
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskServiceImpl.java | 2 |
请完成以下Java代码 | public void setA_Table_Rate_Type (String A_Table_Rate_Type)
{
set_ValueNoCheck (COLUMNNAME_A_Table_Rate_Type, A_Table_Rate_Type);
}
/** Get Type.
@return Type */
public String getA_Table_Rate_Type ()
{
return (String)get_Value(COLUMNNAME_A_Table_Rate_Type);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); | }
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Table_Detail.java | 1 |
请完成以下Java代码 | public abstract class JsonUnsettableValue
{
public boolean computeUnsetValue(@NonNull final SyncAdvise syncAdvise)
{
final boolean explicitlyUnsetDiscount = coalesce(this.getUnsetValue(), false);
if (explicitlyUnsetDiscount)
{
return true;
}
final boolean implicitlyUnsetPrice = this.getValue() == null && syncAdvise.getIfExists().isUpdateRemove();
if (implicitlyUnsetPrice)
{
return true;
}
return false;
}
public boolean computeSetValue(@NonNull final SyncAdvise syncAdvise)
{
final IfExists isExistsAdvise = syncAdvise.getIfExists();
final boolean dontChangeAtAll = !isExistsAdvise.isUpdate();
if (dontChangeAtAll)
{ | return false;
}
final boolean dontChangeIfNotSet = dontChangeAtAll || isExistsAdvise.isUpdateMerge();
final boolean implicitlyDontSetPrice = this.getValue() == null && dontChangeIfNotSet;
if (implicitlyDontSetPrice)
{
return false;
}
return true;
}
protected abstract Object getValue();
protected abstract Boolean getUnsetValue();
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-rest_api\src\main\java\de\metas\common\rest_api\v1\JsonUnsettableValue.java | 1 |
请完成以下Java代码 | public class DelegatingAuthenticationFailureHandler implements AuthenticationFailureHandler {
private final LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers;
private final AuthenticationFailureHandler defaultHandler;
/**
* Creates a new instance
* @param handlers a map of the {@link AuthenticationException} class to the
* {@link AuthenticationFailureHandler} that should be used. Each is considered in the
* order they are specified and only the first {@link AuthenticationFailureHandler} is
* ued. This parameter cannot specify null or empty.
* @param defaultHandler the default {@link AuthenticationFailureHandler} that should
* be used if none of the handlers matches. This parameter cannot specify null.
* @throws IllegalArgumentException if invalid argument is specified
*/
public DelegatingAuthenticationFailureHandler(
LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers,
AuthenticationFailureHandler defaultHandler) {
Assert.notEmpty(handlers, "handlers cannot be null or empty");
Assert.notNull(defaultHandler, "defaultHandler cannot be null");
this.handlers = handlers; | this.defaultHandler = defaultHandler;
}
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
for (Map.Entry<Class<? extends AuthenticationException>, AuthenticationFailureHandler> entry : this.handlers
.entrySet()) {
Class<? extends AuthenticationException> handlerMappedExceptionClass = entry.getKey();
if (handlerMappedExceptionClass.isAssignableFrom(exception.getClass())) {
AuthenticationFailureHandler handler = entry.getValue();
handler.onAuthenticationFailure(request, response, exception);
return;
}
}
this.defaultHandler.onAuthenticationFailure(request, response, exception);
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\DelegatingAuthenticationFailureHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserNotificationsConfig
{
@NonNull UserId userId;
@Nullable String userADLanguage; // might be null
@NonNull ClientId clientId;
@NonNull OrgId orgId;
@NonNull @Getter(AccessLevel.NONE) ImmutableList<UserNotificationsGroup> userNotificationGroups; // needed for toBuilder()
@NonNull ImmutableMap<NotificationGroupName, UserNotificationsGroup> userNotificationGroupsByInternalName;
@NonNull UserNotificationsGroup defaults;
EMailAddress email;
UserId userInChargeId;
@Builder(toBuilder = true)
private UserNotificationsConfig(
@NonNull final UserId userId,
final String userADLanguage,
final ClientId clientId,
final OrgId orgId,
@NonNull @Singular final Collection<UserNotificationsGroup> userNotificationGroups,
@NonNull final UserNotificationsGroup defaults,
final EMailAddress email,
final UserId userInChargeId)
{
this.userId = userId;
this.userADLanguage = Check.isEmpty(userADLanguage) ? null : userADLanguage;
this.clientId = clientId != null ? clientId : ClientId.SYSTEM;
this.orgId = orgId != null ? orgId : OrgId.ANY;
this.userNotificationGroups = ImmutableList.copyOf(userNotificationGroups);
this.userNotificationGroupsByInternalName = Maps.uniqueIndex(userNotificationGroups, UserNotificationsGroup::getGroupInternalName);
this.defaults = defaults;
this.email = email;
this.userInChargeId = userInChargeId;
}
public UserNotificationsGroup getGroupByName(@NonNull final NotificationGroupName groupName)
{
return userNotificationGroupsByInternalName.getOrDefault(groupName, defaults);
} | public String getUserADLanguageOrGet(@NonNull final Supplier<String> defaultLanguageSupplier)
{
final String adLanguage = getUserADLanguage();
return adLanguage != null ? adLanguage : defaultLanguageSupplier.get();
}
public boolean isUserInChargeSet()
{
return userInChargeId != null;
}
public UserNotificationsConfig deriveWithNotificationGroups(final List<UserNotificationsGroup> notificationGroups)
{
if (notificationGroups.isEmpty())
{
return this;
}
final Map<NotificationGroupName, UserNotificationsGroup> newUserNotificationGroupsByInternalName = new HashMap<>(userNotificationGroupsByInternalName);
notificationGroups.forEach(notificationGroup -> newUserNotificationGroupsByInternalName.put(notificationGroup.getGroupInternalName(), notificationGroup));
return toBuilder()
.clearUserNotificationGroups()
.userNotificationGroups(newUserNotificationGroupsByInternalName.values())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationsConfig.java | 2 |
请完成以下Java代码 | public int getIntercompanyDueFrom_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueFrom_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getIntercompanyDueTo_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getIntercompanyDueTo_Acct(), get_TrxName()); }
/** Set Intercompany Due To Acct.
@param IntercompanyDueTo_Acct
Intercompany Due To / Payable Account
*/
public void setIntercompanyDueTo_Acct (int IntercompanyDueTo_Acct) | {
set_Value (COLUMNNAME_IntercompanyDueTo_Acct, Integer.valueOf(IntercompanyDueTo_Acct));
}
/** Get Intercompany Due To Acct.
@return Intercompany Due To / Payable Account
*/
public int getIntercompanyDueTo_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueTo_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InterOrg_Acct.java | 1 |
请完成以下Java代码 | private static CassandraKeyspace findAnnotation(ExtensionContext context) {
var testClass = context.getRequiredTestClass();
var annotation = AnnotationUtils.findAnnotation(testClass, CassandraKeyspace.class);
return annotation.orElseThrow(() -> new IllegalStateException("Test class not annotated with @Cassandra"));
}
private CassandraContainer runTestcontainer() {
if (container != null) {
return container;
} | container = new CassandraContainer(getCassandraDockerImageName());
container.withReuse(true);
container.withCopyFileToContainer(MountableFile.forClasspathResource("/cassandra.yml"),
"/etc/cassandra/cassandra.yaml");
container.start();
return container;
}
private String getCassandraDockerImageName() {
return String.format("cassandra:%s",
Optional.ofNullable(System.getenv("CASSANDRA_VERSION")).filter(StringUtils::hasText).orElse("5.0.6"));
}
} | repos\spring-data-examples-main\cassandra\util\src\main\java\example\springdata\cassandra\util\CassandraExtension.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CreateExportDirectoriesProcessor implements Processor
{
private final ProcessLogger processLogger;
public CreateExportDirectoriesProcessor(@NonNull final ProcessLogger processLogger)
{
this.processLogger = processLogger;
}
@Override
public void process(final Exchange exchange) throws Exception
{
final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class);
createBPartnerExportDirectories(routeContext);
}
private void createBPartnerExportDirectories(@NonNull final ExportBPartnerRouteContext routeContext)
{
final JsonExportDirectorySettings jsonExportDirectorySettings = routeContext.getJsonExportDirectorySettings();
final String bpartnerCode = routeContext.getJsonResponseComposite().getBpartner().getCode();
if (jsonExportDirectorySettings == null)
{
processLogger.logMessage("No export directories settings found for C_BPartner.Value: " + bpartnerCode, routeContext.getPinstanceId());
return;
}
jsonExportDirectorySettings.getDirectoriesPath(bpartnerCode)
.forEach(CreateExportDirectoriesProcessor::createDirectory);
routeContext.setBPartnerBasePath(bpartnerCode);
} | private static void createDirectory(@NonNull final Path directoryPath)
{
final File directory = directoryPath.toFile();
if (directory.exists())
{
return;
}
if (!directory.mkdirs())
{
throw new RuntimeException("Could not create directory with path: " + directoryPath);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\CreateExportDirectoriesProcessor.java | 2 |
请完成以下Java代码 | public final BigDecimal getTotalAppliedAmt()
{
return calculateTotalAppliedAmt(getRowsInnerList());
}
@VisibleForTesting
public static final BigDecimal calculateTotalAppliedAmt(final Iterable<? extends IAllocableDocRow> rows)
{
BigDecimal totalAppliedAmt = BigDecimal.ZERO;
for (final IAllocableDocRow row : rows)
{
if (!row.isSelected())
{
continue;
}
final BigDecimal rowAppliedAmt = row.getAppliedAmt_APAdjusted();
totalAppliedAmt = totalAppliedAmt.add(rowAppliedAmt);
}
return totalAppliedAmt;
}
/** @return latest {@link IAllocableDocRow#getDocumentDate()} of all selected rows */
public final Date getLatestDocumentDate()
{
Date latestDocumentDate = null;
for (final IAllocableDocRow row : getRowsInnerList())
{
if (!row.isSelected())
{
continue;
}
final Date documentDate = row.getDocumentDate();
latestDocumentDate = TimeUtil.max(latestDocumentDate, documentDate);
}
return latestDocumentDate;
}
/** @return latest {@link IAllocableDocRow#getDateAcct()} of all selected rows */
public final Date getLatestDateAcct()
{
Date latestDateAcct = null;
for (final IAllocableDocRow row : getRowsInnerList())
{
if (!row.isSelected())
{
continue; | }
final Date dateAcct = row.getDateAcct();
latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct);
}
return latestDateAcct;
}
public final List<ModelType> getRowsSelected()
{
return FluentIterable.from(getRowsInnerList())
.filter(IAllocableDocRow.PREDICATE_Selected)
.toList();
}
public final List<ModelType> getRowsSelectedNoTaboo()
{
return FluentIterable.from(getRowsInnerList())
.filter(IAllocableDocRow.PREDICATE_Selected)
.filter(IAllocableDocRow.PREDICATE_NoTaboo)
.toList();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\AbstractAllocableDocTableModel.java | 1 |
请完成以下Java代码 | public void negateAmounts()
{
setQtysToInvoice(getQtysToInvoice().negate());
setNetLineAmt(getNetLineAmt().negate());
}
@Override
public int getC_Activity_ID()
{
return activityID;
}
@Override
public void setC_Activity_ID(final int activityID)
{
this.activityID = activityID;
}
@Override
public Tax getC_Tax()
{
return tax;
}
@Override
public void setC_Tax(final Tax tax)
{
this.tax = tax;
}
@Override
public boolean isPrinted()
{
return printed;
}
@Override
public void setPrinted(final boolean printed)
{
this.printed = printed;
}
@Override
public int getLineNo()
{
return lineNo;
}
@Override
public void setLineNo(final int lineNo)
{
this.lineNo = lineNo;
}
@Override
public void setInvoiceLineAttributes(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributes)
{ | this.invoiceLineAttributes = ImmutableList.copyOf(invoiceLineAttributes);
}
@Override
public List<IInvoiceLineAttribute> getInvoiceLineAttributes()
{
return invoiceLineAttributes;
}
@Override
public List<InvoiceCandidateInOutLineToUpdate> getInvoiceCandidateInOutLinesToUpdate()
{
return iciolsToUpdate;
}
@Override
public int getC_PaymentTerm_ID()
{
return C_PaymentTerm_ID;
}
@Override
public void setC_PaymentTerm_ID(final int paymentTermId)
{
C_PaymentTerm_ID = paymentTermId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineImpl.java | 1 |
请完成以下Java代码 | public void setEXP_ProcessorParameter_ID (int EXP_ProcessorParameter_ID)
{
if (EXP_ProcessorParameter_ID < 1)
set_ValueNoCheck (COLUMNNAME_EXP_ProcessorParameter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EXP_ProcessorParameter_ID, Integer.valueOf(EXP_ProcessorParameter_ID));
}
/** Get Processor Parameter.
@return Processor Parameter */
public int getEXP_ProcessorParameter_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_EXP_ProcessorParameter_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{ | return (String)get_Value(COLUMNNAME_Name);
}
/** Set Parameter Value.
@param ParameterValue Parameter Value */
public void setParameterValue (String ParameterValue)
{
set_Value (COLUMNNAME_ParameterValue, ParameterValue);
}
/** Get Parameter Value.
@return Parameter Value */
public String getParameterValue ()
{
return (String)get_Value(COLUMNNAME_ParameterValue);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_ProcessorParameter.java | 1 |
请完成以下Java代码 | public void parseCallActivity(Element callActivityElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseReceiveTask(Element receiveTaskElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseEventBasedGateway(Element eventBasedGwElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { | addListeners(activity);
}
public void parseIntermediateCatchEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) {
addListeners(activity);
}
public void parseBoundaryEvent(Element boundaryEventElement, ScopeImpl scopeElement, ActivityImpl activity) {
addListeners(activity);
}
public void parseMultiInstanceLoopCharacteristics(Element activityElement, Element multiInstanceLoopCharacteristicsElement, ActivityImpl activity) {
addListeners(activity);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\parser\MetricsBpmnParseListener.java | 1 |
请完成以下Java代码 | public int getRfQ_Win_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_MailText_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_PrintFormat getRfQ_Win_PrintFormat() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class);
}
@Override
public void setRfQ_Win_PrintFormat(org.compiere.model.I_AD_PrintFormat RfQ_Win_PrintFormat)
{
set_ValueFromPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, RfQ_Win_PrintFormat);
}
/** Set RfQ Won Druck - Format.
@param RfQ_Win_PrintFormat_ID RfQ Won Druck - Format */
@Override
public void setRfQ_Win_PrintFormat_ID (int RfQ_Win_PrintFormat_ID)
{
if (RfQ_Win_PrintFormat_ID < 1)
set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, null);
else
set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, Integer.valueOf(RfQ_Win_PrintFormat_ID));
}
/** Get RfQ Won Druck - Format.
@return RfQ Won Druck - Format */
@Override
public int getRfQ_Win_PrintFormat_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_PrintFormat_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* RfQType AD_Reference_ID=540661
* Reference name: RfQType
*/
public static final int RFQTYPE_AD_Reference_ID=540661;
/** Default = D */
public static final String RFQTYPE_Default = "D";
/** Procurement = P */
public static final String RFQTYPE_Procurement = "P";
/** Set Ausschreibung Art.
@param RfQType Ausschreibung Art */
@Override
public void setRfQType (java.lang.String RfQType)
{
set_Value (COLUMNNAME_RfQType, RfQType);
}
/** Get Ausschreibung Art.
@return Ausschreibung Art */
@Override
public java.lang.String getRfQType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RfQType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_Topic.java | 1 |
请完成以下Java代码 | public void enqueueSelection(@NonNull final DDOrderCandidateEnqueueRequest request)
{
getQueue().newWorkPackage()
.parameter(WP_PARAM_request, toJsonString(request))
.setElementsLocker(toWorkPackageElementsLocker(request))
.bindToThreadInheritedTrx()
.buildAndEnqueue();
}
private IWorkPackageQueue getQueue()
{
return workPackageQueueFactory.getQueueForEnqueuing(Env.getCtx(), GenerateDDOrderFromDDOrderCandidate.class);
}
private ILockCommand toWorkPackageElementsLocker(final @NonNull DDOrderCandidateEnqueueRequest request)
{
final PInstanceId selectionId = request.getSelectionId();
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, selectionId.getRepoId());
return lockManager
.lock()
.setOwner(lockOwner)
.setAutoCleanup(false)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_DD_Order_Candidate.class, selectionId);
}
private static String toJsonString(@NonNull final DDOrderCandidateEnqueueRequest request)
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(request);
}
catch (final JsonProcessingException e) | {
throw new AdempiereException("Cannot convert to json: " + request, e);
}
}
public static DDOrderCandidateEnqueueRequest extractRequest(@NonNull final IParams params)
{
final String jsonString = params.getParameterAsString(WP_PARAM_request);
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(jsonString, DDOrderCandidateEnqueueRequest.class);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Cannot read json: " + jsonString, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\async\DDOrderCandidateEnqueueService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ImmutableSetMultimap<OrderAndLineId, HuId> getVhuIdsByProposalLineId(final Set<OrderAndLineId> proposalLineIds)
{
return projectService
.getCostCollectorsByQuotationLineIds(proposalLineIds)
.stream()
.filter(costCollector -> costCollector.getVhuId() != null)
.collect(ImmutableSetMultimap.toImmutableSetMultimap(
ServiceRepairProjectCostCollector::getCustomerQuotationLineId,
ServiceRepairProjectCostCollector::getVhuId));
}
public Optional<RepairSalesProposalInfo> extractSalesProposalInfo(@NonNull final I_C_Order orderRecord)
{
final ProjectId projectId = ProjectId.ofRepoIdOrNull(orderRecord.getC_Project_ID());
if (projectId == null)
{
return Optional.empty();
}
if (!orderBL.isSalesProposalOrQuotation(orderRecord))
{
return Optional.empty();
}
return Optional.of(RepairSalesProposalInfo.builder()
.proposalId(OrderId.ofRepoId(orderRecord.getC_Order_ID()))
.projectId(projectId)
.build());
}
public void transferVHUsFromProjectToSalesOrderLine(@NonNull final RepairSalesOrderInfo salesOrderInfo)
{
for (final RepairSalesOrderLineInfo line : salesOrderInfo.getLines())
{
if (line.getSparePartsVHUIds().isEmpty())
{
continue;
}
projectService.transferVHUsFromProjectToSalesOrderLine(
salesOrderInfo.getProjectId(),
line.getSalesOrderLineId(), | line.getSparePartsVHUIds());
}
}
public void transferVHUsFromSalesOrderToProject(final RepairSalesOrderInfo salesOrderInfo)
{
projectService.transferVHUsFromSalesOrderToProject(
salesOrderInfo.getSalesOrderLineIds(),
salesOrderInfo.getProjectId());
}
public void unlinkProposalFromProject(@NonNull final RepairSalesProposalInfo proposalInfo)
{
projectService.unlinkQuotationFromProject(proposalInfo.getProjectId(), proposalInfo.getProposalId());
}
public void unlinkProposalLineFromProject(@NonNull final OrderAndLineId proposalLineId)
{
projectService.unlinkProposalLineFromProject(proposalLineId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\sales_order\RepairSalesOrderService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ItemService {
List<Item> db = new ArrayList<>();
public Item insert(Item item) {
if (item.getId() == null) {
item.setId(UUID.randomUUID()
.toString());
}
db.add(item);
return item;
}
public List<Item> findAll() {
return db;
}
public List<Item> findAllByName(String name) {
return db.stream()
.filter(i -> i.getName()
.equals(name))
.toList(); | }
public Item findById(String id) {
return db.stream()
.filter(i -> i.getId()
.equals(id))
.findFirst()
.orElseThrow(EntityNotFoundException::new);
}
public void deleteById(String id) {
Item item = findById(id);
db.remove(item);
}
public List<Item> deleteAllByName(String name) {
List<Item> allByName = findAllByName(name);
db.removeAll(allByName);
return allByName;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\cats\service\ItemService.java | 2 |
请完成以下Java代码 | private static final class WebuiEmailEntry
{
private WebuiEmail email;
public WebuiEmailEntry(@NonNull final WebuiEmail email)
{
this.email = email;
}
public synchronized WebuiEmail getEmail()
{
return email;
}
public synchronized WebuiEmailChangeResult compute(final UnaryOperator<WebuiEmail> modifier)
{
final WebuiEmail emailOld = email;
final WebuiEmail emailNew = modifier.apply(emailOld); | if (emailNew == null)
{
throw new NullPointerException("email");
}
email = emailNew;
return WebuiEmailChangeResult.builder().email(emailNew).originalEmail(emailOld).build();
}
}
@Value
@AllArgsConstructor
public static class WebuiEmailRemovedEvent
{
@NonNull WebuiEmail email;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailRepository.java | 1 |
请完成以下Java代码 | public List<HistoricTaskInstance> findHistoricTaskInstancesByQueryCriteria(
HistoricTaskInstanceQueryImpl historicTaskInstanceQuery
) {
if (getHistoryManager().isHistoryEnabled()) {
return historicTaskInstanceDataManager.findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery);
}
return emptyList();
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricTaskInstance> findHistoricTaskInstancesAndVariablesByQueryCriteria(
HistoricTaskInstanceQueryImpl historicTaskInstanceQuery
) {
if (getHistoryManager().isHistoryEnabled()) {
return historicTaskInstanceDataManager.findHistoricTaskInstancesAndVariablesByQueryCriteria(
historicTaskInstanceQuery
);
}
return emptyList();
}
@Override
public void delete(String id) {
if (getHistoryManager().isHistoryEnabled()) {
HistoricTaskInstanceEntity historicTaskInstance = findById(id);
if (historicTaskInstance != null) {
deleteInternal(id, historicTaskInstance);
}
}
}
protected void deleteInternal(String id, HistoricTaskInstanceEntity historicTaskInstance) {
List<HistoricTaskInstanceEntity> subTasks = historicTaskInstanceDataManager.findHistoricTasksByParentTaskId(
historicTaskInstance.getId()
);
for (HistoricTaskInstance subTask : subTasks) {
delete(subTask.getId());
}
getHistoricDetailEntityManager().deleteHistoricDetailsByTaskId(id);
getHistoricVariableInstanceEntityManager().deleteHistoricVariableInstancesByTaskId(id);
getCommentEntityManager().deleteCommentsByTaskId(id);
getAttachmentEntityManager().deleteAttachmentsByTaskId(id); | getHistoricIdentityLinkEntityManager().deleteHistoricIdentityLinksByTaskId(id);
delete(historicTaskInstance);
}
@Override
public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicTaskInstanceDataManager.findHistoricTaskInstancesByNativeQuery(
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicTaskInstanceDataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap);
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return historicTaskInstanceDataManager;
}
public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.historicTaskInstanceDataManager = historicTaskInstanceDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityManagerImpl.java | 1 |
请完成以下Java代码 | public void commit(int relation, float score, int relationSize, Configuration config)
{
ArcEager.shift(config.state);
config.addAction(ordinal());
config.setScore(score);
}
},
Reduce
{
@Override
public void commit(int relation, float score, int relationSize, Configuration config)
{
ArcEager.reduce(config.state);
config.addAction(ordinal());
config.setScore(score);
}
},
Unshift
{
@Override
public void commit(int relation, float score, int relationSize, Configuration config)
{
ArcEager.unShift(config.state);
config.addAction(ordinal()); | config.setScore(score);
}
},
RightArc
{
@Override
public void commit(int relation, float score, int relationSize, Configuration config)
{
ArcEager.rightArc(config.state, relation);
config.addAction(ordinal() + relation);
config.setScore(score);
}
},
LeftArc
{
@Override
public void commit(int relation, float score, int relationSize, Configuration config)
{
ArcEager.leftArc(config.state, relation);
config.addAction(ordinal() + relationSize + relation);
config.setScore(score);
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\parser\Action.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ClassFilter getClassFilter() {
return this.classFilter;
}
@Override
public MethodMatcher getMethodMatcher() {
return this;
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return matches(this.methodPrefix, method.getName());
}
@Override
public boolean isRuntime() {
return false;
}
@Override
public boolean matches(Method method, Class<?> targetClass, Object... args) { | return matches(this.methodPrefix, method.getName());
}
private boolean matches(String mappedName, String methodName) {
boolean equals = methodName.equals(mappedName);
return equals || prefixMatches(mappedName, methodName) || suffixMatches(mappedName, methodName);
}
private boolean prefixMatches(String mappedName, String methodName) {
return mappedName.endsWith("*") && methodName.startsWith(mappedName.substring(0, mappedName.length() - 1));
}
private boolean suffixMatches(String mappedName, String methodName) {
return mappedName.startsWith("*") && methodName.endsWith(mappedName.substring(1));
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\PrefixBasedMethodMatcher.java | 2 |
请完成以下Java代码 | public void setJasperProcess_ID (int JasperProcess_ID)
{
if (JasperProcess_ID < 1)
set_Value (COLUMNNAME_JasperProcess_ID, null);
else
set_Value (COLUMNNAME_JasperProcess_ID, Integer.valueOf(JasperProcess_ID));
}
/** Get Jasper Process.
@return The Jasper Process used by the printengine if any process defined
*/
@Override
public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Betreff.
@param Subject
Mail Betreff
*/
@Override
public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject); | }
/** Get Betreff.
@return Mail Betreff
*/
@Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
/** Set Text.
@param TextSnippet Text */
@Override
public void setTextSnippet (java.lang.String TextSnippet)
{
set_Value (COLUMNNAME_TextSnippet, TextSnippet);
}
/** Get Text.
@return Text */
@Override
public java.lang.String getTextSnippet ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextSnippet);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected static class ResourceBundleCondition extends SpringBootCondition {
private static final ConcurrentReferenceHashMap<String, ConditionOutcome> cache = new ConcurrentReferenceHashMap<>();
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");
ConditionOutcome outcome = cache.get(basename);
if (outcome == null) {
outcome = getMatchOutcomeForBasename(context, basename);
cache.put(basename, outcome);
}
return outcome;
}
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle");
for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) {
return ConditionOutcome.match(message.found("bundle").items(resource));
}
}
}
return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
}
private Resource[] getResources(@Nullable ClassLoader classLoader, String name) {
String target = name.replace('.', '/');
try { | return new PathMatchingResourcePatternResolver(classLoader)
.getResources("classpath*:" + target + ".properties");
}
catch (Exception ex) {
return NO_RESOURCES;
}
}
}
static class MessageSourceRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("messages.properties").registerPattern("messages_*.properties");
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\context\MessageSourceAutoConfiguration.java | 2 |
请完成以下Java代码 | public final class OAuth2DeviceAuthorizationRequestAuthenticationConverter implements AuthenticationConverter {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc8628#section-3.1";
@Override
public Authentication convert(HttpServletRequest request) {
Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getFormParameters(request);
String authorizationUri = request.getRequestURL().toString();
// scope (OPTIONAL)
String scope = parameters.getFirst(OAuth2ParameterNames.SCOPE);
if (StringUtils.hasText(scope) && parameters.get(OAuth2ParameterNames.SCOPE).size() != 1) {
OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.SCOPE, ERROR_URI);
} | Set<String> requestedScopes = null;
if (StringUtils.hasText(scope)) {
requestedScopes = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
}
Map<String, Object> additionalParameters = new HashMap<>();
parameters.forEach((key, value) -> {
if (!key.equals(OAuth2ParameterNames.CLIENT_ID) && !key.equals(OAuth2ParameterNames.SCOPE)) {
additionalParameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0]));
}
});
return new OAuth2DeviceAuthorizationRequestAuthenticationToken(clientPrincipal, authorizationUri,
requestedScopes, additionalParameters);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\OAuth2DeviceAuthorizationRequestAuthenticationConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ErpelBusinessDocumentHeaderType getErpelBusinessDocumentHeader() {
return erpelBusinessDocumentHeader;
}
/**
* Sets the value of the erpelBusinessDocumentHeader property.
*
* @param value
* allowed object is
* {@link ErpelBusinessDocumentHeaderType }
*
*/
public void setErpelBusinessDocumentHeader(ErpelBusinessDocumentHeaderType value) {
this.erpelBusinessDocumentHeader = value;
}
/**
* Gets the value of the document property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the document property.
* | * <p>
* For example, to add a new item, do as follows:
* <pre>
* getDocument().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentType }
*
*
*/
public List<DocumentType> getDocument() {
if (document == null) {
document = new ArrayList<DocumentType>();
}
return this.document;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\message\ErpelMessageType.java | 2 |
请完成以下Java代码 | public boolean isHasExpenseLoading() {
if (hasExpenseLoading == null) {
return true;
} else {
return hasExpenseLoading;
}
}
/**
* Sets the value of the hasExpenseLoading property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setHasExpenseLoading(Boolean value) {
this.hasExpenseLoading = value;
}
/**
* Gets the value of the doCostAssessment property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isDoCostAssessment() { | if (doCostAssessment == null) {
return false;
} else {
return doCostAssessment;
}
}
/**
* Sets the value of the doCostAssessment property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setDoCostAssessment(Boolean value) {
this.doCostAssessment = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\XtraStationaryType.java | 1 |
请完成以下Java代码 | public void setAD_Scheduler_ID (int AD_Scheduler_ID)
{
if (AD_Scheduler_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, Integer.valueOf(AD_Scheduler_ID));
}
/** Get Ablaufsteuerung.
@return Schedule Processes
*/
@Override
public int getAD_Scheduler_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Scheduler_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Empfänger.
@param AD_SchedulerRecipient_ID
Recipient of the Scheduler Notification
*/
@Override
public void setAD_SchedulerRecipient_ID (int AD_SchedulerRecipient_ID)
{
if (AD_SchedulerRecipient_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, Integer.valueOf(AD_SchedulerRecipient_ID));
}
/** Get Empfänger.
@return Recipient of the Scheduler Notification
*/
@Override
public int getAD_SchedulerRecipient_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_SchedulerRecipient_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class);
} | @Override
public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerRecipient.java | 1 |
请完成以下Java代码 | public Long getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((branchId == null) ? 0 : branchId.hashCode());
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) { | if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (branchId == null) {
if (other.branchId != null)
return false;
} else if (!branchId.equals(other.branchId))
return false;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-vault\src\main\java\com\baeldung\spring\cloud\vaultsample\domain\Account.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getStatementLineDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate);
}
@Override
public void setStmtAmt (final @Nullable BigDecimal StmtAmt)
{
set_Value (COLUMNNAME_StmtAmt, StmtAmt);
}
@Override
public BigDecimal getStmtAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTrxAmt (final @Nullable BigDecimal TrxAmt)
{
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
@Override
public BigDecimal getTrxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* TrxType AD_Reference_ID=215
* Reference name: C_Payment Trx Type
*/
public static final int TRXTYPE_AD_Reference_ID=215;
/** Sales = S */ | public static final String TRXTYPE_Sales = "S";
/** DelayedCapture = D */
public static final String TRXTYPE_DelayedCapture = "D";
/** CreditPayment = C */
public static final String TRXTYPE_CreditPayment = "C";
/** VoiceAuthorization = F */
public static final String TRXTYPE_VoiceAuthorization = "F";
/** Authorization = A */
public static final String TRXTYPE_Authorization = "A";
/** Void = V */
public static final String TRXTYPE_Void = "V";
/** Rückzahlung = R */
public static final String TRXTYPE_Rueckzahlung = "R";
@Override
public void setTrxType (final @Nullable java.lang.String TrxType)
{
set_Value (COLUMNNAME_TrxType, TrxType);
}
@Override
public java.lang.String getTrxType()
{
return get_ValueAsString(COLUMNNAME_TrxType);
}
@Override
public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate)
{
set_Value (COLUMNNAME_ValutaDate, ValutaDate);
}
@Override
public java.sql.Timestamp getValutaDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValutaDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java | 1 |
请完成以下Java代码 | public List<I_M_HU_Trx_Line> retrieveTrxLines(final I_M_HU_Item huItem)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(huItem);
final String trxName = InterfaceWrapperHelper.getTrxName(huItem);
final IHUTrxQuery huTrxQuery = createHUTrxQuery();
huTrxQuery.setM_HU_Item_ID(huItem.getM_HU_Item_ID());
return retrieveTrxLines(ctx, huTrxQuery, trxName);
}
@Override
public I_M_HU_Trx_Line retrieveCounterpartTrxLine(final I_M_HU_Trx_Line trxLine)
{
final I_M_HU_Trx_Line trxLineCounterpart = trxLine.getParent_HU_Trx_Line();
if (trxLineCounterpart == null)
{
throw new AdempiereException("Counterpart transaction was not found for " + trxLine);
}
if (HUConstants.DEBUG_07277_saveHUTrxLine && trxLineCounterpart.getM_HU_Trx_Line_ID() <= 0)
{
throw new AdempiereException("Counterpart transaction was not saved for " + trxLine
+ "\nCounterpart trx: " + trxLineCounterpart);
}
return trxLineCounterpart;
}
@Override
public List<I_M_HU_Trx_Line> retrieveReferencingTrxLinesForHuId(@NonNull final HuId huId)
{
final IHUTrxQuery huTrxQuery = createHUTrxQuery();
huTrxQuery.setM_HU_ID(huId.getRepoId()); | return retrieveTrxLines(Env.getCtx(), huTrxQuery, ITrx.TRXNAME_ThreadInherited);
}
@Override
@Deprecated
public List<I_M_HU_Trx_Line> retrieveReferencingTrxLinesForHU(final I_M_HU hu)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(hu);
final String trxName = InterfaceWrapperHelper.getTrxName(hu);
final IHUTrxQuery huTrxQuery = createHUTrxQuery();
huTrxQuery.setM_HU_ID(hu.getM_HU_ID());
return retrieveTrxLines(ctx, huTrxQuery, trxName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomerServiceImpl implements CustomerService {
@PersistenceContext private EntityManager em;
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findById(java.lang.Long)
*/
@Override
public Customer findById(Long id) {
return em.find(Customer.class, id);
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findAll()
*/
@Override
public List<Customer> findAll() {
return em.createQuery("select c from Customer c", Customer.class).getResultList();
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findAll(int, int)
*/
@Override
public List<Customer> findAll(int page, int pageSize) {
var query = em.createQuery("select c from Customer c", Customer.class);
query.setFirstResult(page * pageSize);
query.setMaxResults(pageSize);
return query.getResultList();
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#save(example.springdata.jpa.showcase.core.Customer)
*/
@Override
@Transactional
public Customer save(Customer customer) {
// Is new?
if (customer.getId() == null) { | em.persist(customer);
return customer;
} else {
return em.merge(customer);
}
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findByLastname(java.lang.String, int, int)
*/
@Override
public List<Customer> findByLastname(String lastname, int page, int pageSize) {
var query = em.createQuery("select c from Customer c where c.lastname = ?1", Customer.class);
query.setParameter(1, lastname);
query.setFirstResult(page * pageSize);
query.setMaxResults(pageSize);
return query.getResultList();
}
} | repos\spring-data-examples-main\jpa\showcase\src\main\java\example\springdata\jpa\showcase\before\CustomerServiceImpl.java | 2 |
请完成以下Java代码 | public void setDLM_Partition_Config_Line_ID(final int DLM_Partition_Config_Line_ID)
{
if (DLM_Partition_Config_Line_ID < 1)
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_Line_ID, null);
}
else
{
set_ValueNoCheck(COLUMNNAME_DLM_Partition_Config_Line_ID, Integer.valueOf(DLM_Partition_Config_Line_ID));
}
}
/**
* Get DLM Partitionierungskonfigzeile.
*
* @return DLM Partitionierungskonfigzeile
*/
@Override
public int getDLM_Partition_Config_Line_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_Line_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Table getDLM_Referencing_Table() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class);
}
@Override
public void setDLM_Referencing_Table(final org.compiere.model.I_AD_Table DLM_Referencing_Table)
{
set_ValueFromPO(COLUMNNAME_DLM_Referencing_Table_ID, org.compiere.model.I_AD_Table.class, DLM_Referencing_Table);
}
/**
* Set Referenzierende Tabelle.
*
* @param DLM_Referencing_Table_ID Referenzierende Tabelle
*/
@Override
public void setDLM_Referencing_Table_ID(final int DLM_Referencing_Table_ID)
{
if (DLM_Referencing_Table_ID < 1)
{
set_Value(COLUMNNAME_DLM_Referencing_Table_ID, null);
}
else
{
set_Value(COLUMNNAME_DLM_Referencing_Table_ID, Integer.valueOf(DLM_Referencing_Table_ID));
}
}
/**
* Get Referenzierende Tabelle.
* | * @return Referenzierende Tabelle
*/
@Override
public int getDLM_Referencing_Table_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Referencing_Table_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set DLM aktiviert.
*
* @param IsDLM
* Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public void setIsDLM(final boolean IsDLM)
{
throw new IllegalArgumentException("IsDLM is virtual column");
}
/**
* Get DLM aktiviert.
*
* @return Die Datensätze einer Tabelle mit aktiviertem DLM können vom System unterschiedlichen DLM-Levels zugeordnet werden
*/
@Override
public boolean isDLM()
{
final Object oo = get_Value(COLUMNNAME_IsDLM);
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.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config_Line.java | 1 |
请完成以下Java代码 | public boolean isCamundaAsync() {
return camundaAsyncAttribute.getValue(this);
}
/**
* @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead.
*/
@Deprecated
public void setCamundaAsync(boolean isCamundaAsync) {
camundaAsyncAttribute.setValue(this, isCamundaAsync);
}
public String getCamundaFormHandlerClass() {
return camundaFormHandlerClassAttribute.getValue(this);
}
public void setCamundaFormHandlerClass(String camundaFormHandlerClass) {
camundaFormHandlerClassAttribute.setValue(this, camundaFormHandlerClass);
}
public String getCamundaFormKey() {
return camundaFormKeyAttribute.getValue(this);
}
public void setCamundaFormKey(String camundaFormKey) {
camundaFormKeyAttribute.setValue(this, camundaFormKey);
}
public String getCamundaFormRef() {
return camundaFormRefAttribute.getValue(this);
} | public void setCamundaFormRef(String camundaFormRef) {
camundaFormRefAttribute.setValue(this, camundaFormRef);
}
public String getCamundaFormRefBinding() {
return camundaFormRefBindingAttribute.getValue(this);
}
public void setCamundaFormRefBinding(String camundaFormRefBinding) {
camundaFormRefBindingAttribute.setValue(this, camundaFormRefBinding);
}
public String getCamundaFormRefVersion() {
return camundaFormRefVersionAttribute.getValue(this);
}
public void setCamundaFormRefVersion(String camundaFormRefVersion) {
camundaFormRefVersionAttribute.setValue(this, camundaFormRefVersion);
}
public String getCamundaInitiator() {
return camundaInitiatorAttribute.getValue(this);
}
public void setCamundaInitiator(String camundaInitiator) {
camundaInitiatorAttribute.setValue(this, camundaInitiator);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\StartEventImpl.java | 1 |
请完成以下Java代码 | public PostalAddressSEPA getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link PostalAddressSEPA }
*
*/
public void setPstlAdr(PostalAddressSEPA value) {
this.pstlAdr = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link PartySEPAChoice }
*
*/ | public PartySEPAChoice getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link PartySEPAChoice }
*
*/
public void setId(PartySEPAChoice value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PartyIdentificationSEPA2.java | 1 |
请完成以下Java代码 | public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
} | public String getConfirmEmail() {
return confirmEmail;
}
public void setConfirmEmail(String confirmEmail) {
this.confirmEmail = confirmEmail;
}
public Boolean getTerms() {
return terms;
}
public void setTerms(Boolean terms) {
this.terms = terms;
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Registration-Page\src\main\java\aspera\registration\web\dto\UserRegistrationDto.java | 1 |
请完成以下Java代码 | public boolean isValidProductNo(@NonNull final EAN13 ean13, @Nullable final BPartnerId bpartnerId)
{
final EAN13Prefix ean13Prefix = ean13.getPrefix();
final EAN13ProductCode ean13ProductNo = ean13.getProductNo();
// 28 - Variable-Weight barcodes
if (ean13Prefix.isVariableWeight())
{
return contains(ean13ProductNo, bpartnerId)
|| ean13ProductNo.isPrefixOf(productValue);
}
// 29 - Internal Use / Variable measure
else if (ean13Prefix.isInternalUseOrVariableMeasure())
{
return contains(ean13ProductNo, bpartnerId);
}
// Parse regular product codes for other prefixes | else
{
return endsWith(ean13ProductNo, bpartnerId);
}
}
public Optional<GS1ProductCodes> getEffectiveCodes(@Nullable final BPartnerId bpartnerId)
{
final GS1ProductCodes bpartnerCodes = bpartnerId != null ? codesByBPartnerId.get(bpartnerId) : null;
final GS1ProductCodes effectiveCodes = bpartnerCodes != null
? bpartnerCodes.fallbackTo(defaultCodes)
: defaultCodes;
return Optional.ofNullable(effectiveCodes.isEmpty() ? null : effectiveCodes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\GS1ProductCodesCollection.java | 1 |
请完成以下Java代码 | public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getSourceCaseDefinitionId() {
return sourceCaseDefinitionId;
} | public void setSourceCaseDefinitionId(String sourceCaseDefinitionId) {
this.sourceCaseDefinitionId = sourceCaseDefinitionId;
}
public String getTargetCaseDefinitionId() {
return targetCaseDefinitionId;
}
public void setTargetCaseDefinitionId(String targetCaseDefinitionId) {
this.targetCaseDefinitionId = targetCaseDefinitionId;
}
public String getMigrationMessage() {
return migrationMessage;
}
public void setMigrationMessage(String migrationMessage) {
this.migrationMessage = migrationMessage;
}
public String getMigrationStacktrace() {
return migrationStacktrace;
}
public void setMigrationStacktrace(String migrationStacktrace) {
this.migrationStacktrace = migrationStacktrace;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-api\src\main\java\org\flowable\cmmn\api\migration\CaseInstanceBatchMigrationPartResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getDOCUMENTID() {
return documentid;
}
/**
* Sets the value of the documentid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDOCUMENTID(String value) {
this.documentid = value;
}
/**
* Gets the value of the addinfo property.
*
* @return
* possible object is
* {@link String }
* | */
public String getADDINFO() {
return addinfo;
}
/**
* Sets the value of the addinfo property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setADDINFO(String value) {
this.addinfo = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\HADDI1.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class WEBUI_M_HU_ReverseReceipt extends WEBUI_M_HU_Receipt_Base implements IProcessPrecondition
{
@Autowired
private IViewsRepository viewsRepo;
@Autowired
private DocumentCollection documentsCollection;
/**
* Only allows rows whose HUs are in the "active" status.
*/
@Override
final ProcessPreconditionsResolution rejectResolutionOrNull(final HUEditorRow document)
{
if (!document.isHUStatusActive())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Only active HUs can be reversed");
}
final List<I_M_ReceiptSchedule> receiptSchedules = getM_ReceiptSchedules();
if(receiptSchedules.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Thre are no receipt schedules");
}
return null;
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final List<I_M_ReceiptSchedule> receiptSchedules = getM_ReceiptSchedules();
final List<HuId> huIdsToReverse = retrieveHUsToReverse();
boolean hasChanges = false;
try
{
for (final I_M_ReceiptSchedule receiptSchedule : receiptSchedules)
{
final ReceiptCorrectHUsProcessor processor = ReceiptCorrectHUsProcessor.builder()
.setM_ReceiptSchedule(receiptSchedule)
.tolerateNoHUsFound()
.build();
if (processor.isNoHUsFound())
{
continue;
}
final List<Integer> asRepoIds = RepoIdAwares.asRepoIds(huIdsToReverse);
final List<I_M_InOut> receiptsToReverse = processor.getReceiptsToReverseFromHUIds(asRepoIds);
if (receiptsToReverse.isEmpty())
{
continue;
}
processor.reverseReceipts(receiptsToReverse);
hasChanges = true;
}
}
finally
{
if (hasChanges)
{
// Reset the view's affected HUs
getView().removeHUIdsAndInvalidate(huIdsToReverse);
// Notify all active views that given receipt schedules were changed | viewsRepo.notifyRecordsChangedAsync(TableRecordReferenceSet.of(TableRecordReference.ofSet(receiptSchedules)));
}
}
if (!hasChanges)
{
throw new AdempiereException("@NotFound@ @M_InOut_ID@");
}
return MSG_OK;
}
@Override
protected HUEditorView getView()
{
return getView(HUEditorView.class);
}
private List<I_M_ReceiptSchedule> getM_ReceiptSchedules()
{
return getView()
.getReferencingDocumentPaths().stream()
.map(referencingDocumentPath -> documentsCollection.getTableRecordReference(referencingDocumentPath).getModel(this, I_M_ReceiptSchedule.class))
.collect(GuavaCollectors.toImmutableList());
}
private List<HuId> retrieveHUsToReverse()
{
// gh #1955: prevent an OutOfMemoryError
final IQueryFilter<I_M_HU> processFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
return Services.get(IQueryBL.class).createQueryBuilder(I_M_HU.class, this)
.filter(processFilter)
.addOnlyActiveRecordsFilter()
.create()
.listIds()
.stream()
.map(HuId::ofRepoId)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReverseReceipt.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public IHUQRCode parse(@NonNull final ScannedCode scannedCode)
{
final PickOnTheFlyQRCode pickOnTheFlyQRCode = PickOnTheFlyQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (pickOnTheFlyQRCode != null)
{
return pickOnTheFlyQRCode;
}
final GlobalQRCode globalQRCode = scannedCode.toGlobalQRCodeIfMatching().orNullIfError();
if (globalQRCode != null)
{
if (HUQRCode.isHandled(globalQRCode))
{
return HUQRCode.fromGlobalQRCode(globalQRCode);
}
else if (LMQRCode.isHandled(globalQRCode))
{
return LMQRCode.fromGlobalQRCode(globalQRCode);
}
}
final CustomHUQRCode customHUQRCode = scannableCodeFormatService.parse(scannedCode)
.map(CustomHUQRCode::ofParsedScannedCode)
.orElse(null);
if (customHUQRCode != null)
{
return customHUQRCode;
}
// M_HU.Value / ExternalBarcode attribute
{
final HuId huId = handlingUnitsBL.getHUIdByValueOrExternalBarcode(scannedCode).orElse(null);
if (huId != null)
{
return getFirstQRCodeByHuId(huId); | }
}
final GS1HUQRCode gs1HUQRCode = GS1HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (gs1HUQRCode != null)
{
return gs1HUQRCode;
}
final EAN13HUQRCode ean13HUQRCode = EAN13HUQRCode.fromScannedCodeOrNullIfNotHandled(scannedCode);
if (ean13HUQRCode != null)
{
return ean13HUQRCode;
}
throw new AdempiereException("QR code is not handled: " + scannedCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\service\HUQRCodesService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Packaging unit type of the contained packages. If customer's and supplier's packaging unit type is different this should be used for customer's packaging unit type.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnit() {
return unit;
}
/**
* Sets the value of the unit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnit(String value) {
this.unit = value;
}
/**
* Packaging unit type used by the supplier. If customer's and supplier's packaging unit type is different this should be used for suppliers's packaging unit type.
*
* @return
* possible object is
* {@link String } | *
*/
public String getSupplierUnit() {
return supplierUnit;
}
/**
* Sets the value of the supplierUnit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSupplierUnit(String value) {
this.supplierUnit = value;
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ConsignmentPackagingSequenceType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getStock(String key) {
Integer stock = (Integer) redisTemplate.opsForValue().get(key);
return stock == null ? -1 : stock;
}
/**
* 扣库存
*
* @param key 库存key
* @param num 扣减库存数量
* @return 扣减之后剩余的库存【-3:库存未初始化; -2:库存不足; -1:不限库存; 大于等于0:扣减库存之后的剩余库存】
*/
private Long stock(String key, int num) {
// 脚本里的KEYS参数
List<String> keys = new ArrayList<>();
keys.add(key);
// 脚本里的ARGV参数
List<String> args = new ArrayList<>();
args.add(Integer.toString(num));
long result = redisTemplate.execute(new RedisCallback<Long>() { | @Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
Object nativeConnection = connection.getNativeConnection();
// 集群模式和单机模式虽然执行脚本的方法一样,但是没有共同的接口,所以只能分开执行
// 集群模式
if (nativeConnection instanceof JedisCluster) {
return (Long) ((JedisCluster) nativeConnection).eval(STOCK_LUA, keys, args);
}
// 单机模式
else if (nativeConnection instanceof Jedis) {
return (Long) ((Jedis) nativeConnection).eval(STOCK_LUA, keys, args);
}
return UNINITIALIZED_STOCK;
}
});
return result;
}
} | repos\spring-boot-student-master\spring-boot-student-stock-redis\src\main\java\com\xiaolyuh\service\StockService.java | 2 |
请完成以下Java代码 | public RemittanceAmount1 getRfrdDocAmt() {
return rfrdDocAmt;
}
/**
* Sets the value of the rfrdDocAmt property.
*
* @param value
* allowed object is
* {@link RemittanceAmount1 }
*
*/
public void setRfrdDocAmt(RemittanceAmount1 value) {
this.rfrdDocAmt = value;
}
/**
* Gets the value of the cdtrRefInf property.
*
* @return
* possible object is
* {@link CreditorReferenceInformation2 }
*
*/
public CreditorReferenceInformation2 getCdtrRefInf() {
return cdtrRefInf;
}
/**
* Sets the value of the cdtrRefInf property.
*
* @param value
* allowed object is
* {@link CreditorReferenceInformation2 }
*
*/
public void setCdtrRefInf(CreditorReferenceInformation2 value) {
this.cdtrRefInf = value;
}
/**
* Gets the value of the invcr property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/
public PartyIdentification32 getInvcr() {
return invcr;
}
/**
* Sets the value of the invcr property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setInvcr(PartyIdentification32 value) {
this.invcr = value;
}
/**
* Gets the value of the invcee property.
*
* @return
* possible object is
* {@link PartyIdentification32 }
*
*/ | public PartyIdentification32 getInvcee() {
return invcee;
}
/**
* Sets the value of the invcee property.
*
* @param value
* allowed object is
* {@link PartyIdentification32 }
*
*/
public void setInvcee(PartyIdentification32 value) {
this.invcee = value;
}
/**
* Gets the value of the addtlRmtInf property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the addtlRmtInf property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAddtlRmtInf().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getAddtlRmtInf() {
if (addtlRmtInf == null) {
addtlRmtInf = new ArrayList<String>();
}
return this.addtlRmtInf;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\StructuredRemittanceInformation7.java | 1 |
请完成以下Java代码 | public class SetLicenseKeyCmd extends LicenseCmd implements Command<Object> {
protected String licenseKey;
public SetLicenseKeyCmd(final String licenseKey) {
this.licenseKey = licenseKey;
}
@Override
public Object execute(CommandContext commandContext) {
EnsureUtil.ensureNotNull("licenseKey", licenseKey);
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkSetLicenseKey);
final ResourceManager resourceManager = commandContext.getResourceManager();
ResourceEntity key = resourceManager.findLicenseKeyResource();
if (key != null) {
new DeleteLicenseKeyCmd(false, false).execute(commandContext);
}
key = new ResourceEntity();
key.setName(LICENSE_KEY_PROPERTY_NAME);
key.setBytes(licenseKey.getBytes(StandardCharsets.UTF_8));
// set license key as byte array BLOB
resourceManager.insertResource(key); | // set license key byte array id property
commandContext.runWithoutAuthorization(new SetPropertyCmd(LICENSE_KEY_BYTE_ARRAY_ID, key.getId()));
// cleanup legacy property
commandContext.runWithoutAuthorization(new DeletePropertyCmd(LICENSE_KEY_PROPERTY_NAME));
// add raw license to diagnostics data if not there already
ManagementServiceImpl managementService = (ManagementServiceImpl) commandContext.getProcessEngineConfiguration().getManagementService();
LicenseKeyDataImpl currentLicenseData = managementService.getLicenseKeyFromDiagnostics();
// only report license body without signature
LicenseKeyDataImpl licenseKeyData = LicenseKeyDataImpl.fromRawString(licenseKey);
if (currentLicenseData == null || !licenseKeyData.getRaw().equals(currentLicenseData.getRaw())) {
managementService.setLicenseKeyForDiagnostics(licenseKeyData);
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetLicenseKeyCmd.java | 1 |
请完成以下Java代码 | public abstract class BaseAssetProcessor extends BaseEdgeProcessor {
@Autowired
private DataValidator<Asset> assetValidator;
protected Pair<Boolean, Boolean> saveOrUpdateAsset(TenantId tenantId, AssetId assetId, AssetUpdateMsg assetUpdateMsg) {
boolean created = false;
boolean assetNameUpdated = false;
assetCreationLock.lock();
try {
Asset asset = JacksonUtil.fromString(assetUpdateMsg.getEntity(), Asset.class, true);
if (asset == null) {
throw new RuntimeException("[{" + tenantId + "}] assetUpdateMsg {" + assetUpdateMsg + " } cannot be converted to asset");
}
Asset assetById = edgeCtx.getAssetService().findAssetById(tenantId, assetId);
if (assetById == null) {
created = true;
asset.setId(null);
} else {
asset.setId(assetId);
}
if (isSaveRequired(assetById, asset)) {
assetNameUpdated = updateAssetNameIfDuplicateExists(tenantId, assetId, asset);
setCustomerId(tenantId, created ? null : assetById.getCustomerId(), asset, assetUpdateMsg);
assetValidator.validate(asset, Asset::getTenantId);
if (created) {
asset.setId(assetId);
}
edgeCtx.getAssetService().saveAsset(asset, false);
}
} catch (Exception e) {
log.error("[{}] Failed to process asset update msg [{}]", tenantId, assetUpdateMsg, e);
throw e;
} finally {
assetCreationLock.unlock(); | }
return Pair.of(created, assetNameUpdated);
}
private boolean updateAssetNameIfDuplicateExists(TenantId tenantId, AssetId assetId, Asset asset) {
Asset assetByName = edgeCtx.getAssetService().findAssetByTenantIdAndName(tenantId, asset.getName());
return generateUniqueNameIfDuplicateExists(tenantId, assetId, asset, assetByName).map(uniqueName -> {
asset.setName(uniqueName);
return true;
}).orElse(false);
}
protected abstract void setCustomerId(TenantId tenantId, CustomerId customerId, Asset asset, AssetUpdateMsg assetUpdateMsg);
protected void deleteAsset(TenantId tenantId, AssetId assetId) {
deleteAsset(tenantId, null, assetId);
}
protected void deleteAsset(TenantId tenantId, Edge edge, AssetId assetId) {
Asset assetById = edgeCtx.getAssetService().findAssetById(tenantId, assetId);
if (assetById != null) {
edgeCtx.getAssetService().deleteAsset(tenantId, assetId);
pushEntityEventToRuleEngine(tenantId, edge, assetById, TbMsgType.ENTITY_DELETED);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\asset\BaseAssetProcessor.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final I_C_Order existentOrder = getRecord(I_C_Order.class);
final I_C_Order newOrder = ExtendContractOrder.extend(existentOrder);
final int adWindowId = getProcessInfo().getAD_Window_ID();
final TableRecordReference ref = TableRecordReference.of(newOrder);
if (adWindowId > 0 && !Ini.isSwingClient())
{
getResult().setRecordToOpen(ref, adWindowId, OpenTarget.SingleDocument);
}
else
{
getResult().setRecordToSelectAfterExecution(ref);
}
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(IProcessPreconditionsContext context)
{ | if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
if (!I_C_Order.Table_Name.equals(context.getTableName()))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("The process only runs with C_Order table");
}
if (!contractOrderService.isContractSalesOrder( OrderId.ofRepoId(context.getSingleSelectedRecordId())))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("The process only runs with a contract order");
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\process\C_Order_Copy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ConnectionInfo parseForwardedInfo(ConnectionInfo connectionInfo, String forwardedHeader) {
String forwarded = forwardedHeader.split(",", 2)[0];
Matcher protoMatcher = FORWARDED_PROTO_PATTERN.matcher(forwarded);
if (protoMatcher.find()) {
connectionInfo = connectionInfo.withScheme(protoMatcher.group(1).trim());
}
Matcher hostMatcher = FORWARDED_HOST_PATTERN.matcher(forwarded);
if (hostMatcher.find()) {
connectionInfo = connectionInfo.withHostAddress(AddressUtils.parseAddress(hostMatcher.group(1),
getDefaultHostPort(connectionInfo.getScheme()), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
Matcher forMatcher = FORWARDED_FOR_PATTERN.matcher(forwarded);
if (forMatcher.find()) {
connectionInfo = connectionInfo.withRemoteAddress(AddressUtils.parseAddress(forMatcher.group(1).trim(),
connectionInfo.getRemoteAddress().getPort(), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
return connectionInfo;
}
private ConnectionInfo parseXForwardedInfo(ConnectionInfo connectionInfo, HttpRequest request) {
String ipHeader = request.headers().get(X_FORWARDED_IP_HEADER);
if (ipHeader != null) {
connectionInfo = connectionInfo.withRemoteAddress(
AddressUtils.parseAddress(ipHeader.split(",", 2)[0], connectionInfo.getRemoteAddress().getPort()));
}
String protoHeader = request.headers().get(X_FORWARDED_PROTO_HEADER);
if (protoHeader != null) {
connectionInfo = connectionInfo.withScheme(protoHeader.split(",", 2)[0].trim());
}
String hostHeader = request.headers().get(X_FORWARDED_HOST_HEADER);
if (hostHeader != null) { | connectionInfo = connectionInfo
.withHostAddress(AddressUtils.parseAddress(hostHeader.split(",", 2)[0].trim(),
getDefaultHostPort(connectionInfo.getScheme()), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
String portHeader = request.headers().get(X_FORWARDED_PORT_HEADER);
if (portHeader != null && !portHeader.isEmpty()) {
String portStr = portHeader.split(",", 2)[0].trim();
if (portStr.chars().allMatch(Character::isDigit)) {
int port = Integer.parseInt(portStr);
connectionInfo = connectionInfo.withHostAddress(
AddressUtils.createUnresolved(connectionInfo.getHostAddress().getHostString(), port),
connectionInfo.getHostName(), port);
}
else if (DEFAULT_FORWARDED_HEADER_VALIDATION) {
throw new IllegalArgumentException("Failed to parse a port from " + portHeader);
}
}
return connectionInfo;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\DefaultNettyHttpForwardedHeaderHandler.java | 2 |
请完成以下Java代码 | public void setDataEntry_Line_ID (int DataEntry_Line_ID)
{
if (DataEntry_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Line_ID, Integer.valueOf(DataEntry_Line_ID));
}
/** Get Zeile.
@return Zeile */
@Override
public int getDataEntry_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.dataentry.model.I_DataEntry_Section getDataEntry_Section() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class);
}
@Override
public void setDataEntry_Section(de.metas.dataentry.model.I_DataEntry_Section DataEntry_Section)
{
set_ValueFromPO(COLUMNNAME_DataEntry_Section_ID, de.metas.dataentry.model.I_DataEntry_Section.class, DataEntry_Section);
}
/** Set Sektion.
@param DataEntry_Section_ID Sektion */
@Override
public void setDataEntry_Section_ID (int DataEntry_Section_ID)
{
if (DataEntry_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Section_ID, Integer.valueOf(DataEntry_Section_ID));
} | /** Get Sektion.
@return Sektion */
@Override
public int getDataEntry_Section_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Section_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Line.java | 1 |
请完成以下Java代码 | private boolean isRowIdIncluded(final Set<HUEditorRowId> parentRowIds, final HUEditorRowId childRowId)
{
if (parentRowIds == null || parentRowIds.isEmpty())
{
return false;
}
// Iterate child row's up-stream (up to the root row)
HUEditorRowId currentChildId = childRowId;
while (currentChildId != null)
{
final HUEditorRowId currentParentRowId = rowId2parentId.get(currentChildId);
if (currentParentRowId == null)
{
// => not included (currentChildId is a top level row)
return false;
}
if (parentRowIds.contains(currentParentRowId))
{
// => included (current child is included in our parents list)
return true;
}
currentChildId = currentParentRowId;
}
return false;
}
public Stream<HUEditorRow> stream()
{
return rows.stream();
}
public Stream<HUEditorRow> streamRecursive()
{
return stream()
.flatMap(HUEditorRow::streamRecursive)
.map(HUEditorRow::cast);
}
public long size()
{
return rows.size();
} | private static ImmutableMap<DocumentId, HUEditorRow> buildRowsByIdMap(final List<HUEditorRow> rows)
{
if (rows.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableMap.Builder<DocumentId, HUEditorRow> rowsById = ImmutableMap.builder();
rows.forEach(row -> indexByIdRecursively(rowsById, row));
return rowsById.build();
}
private static void indexByIdRecursively(final ImmutableMap.Builder<DocumentId, HUEditorRow> collector, final HUEditorRow row)
{
collector.put(row.getId(), row);
row.getIncludedRows()
.forEach(includedRow -> indexByIdRecursively(collector, includedRow));
}
private static ImmutableMap<HUEditorRowId, HUEditorRowId> buildRowId2ParentIdMap(final List<HUEditorRow> rows)
{
if (rows.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId = ImmutableMap.builder();
rows.forEach(row -> buildRowId2ParentIdMap(rowId2parentId, row));
return rowId2parentId.build();
}
private static void buildRowId2ParentIdMap(final ImmutableMap.Builder<HUEditorRowId, HUEditorRowId> rowId2parentId, final HUEditorRow parentRow)
{
final HUEditorRowId parentId = parentRow.getHURowId();
parentRow.getIncludedRows()
.forEach(includedRow -> rowId2parentId.put(includedRow.getHURowId(), parentId));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuffer_FullyCached.java | 1 |
请完成以下Java代码 | public void setIsAscending (boolean IsAscending)
{
set_Value (COLUMNNAME_IsAscending, Boolean.valueOf(IsAscending));
}
/** Get Aufsteigender.
@return Aufsteigender */
@Override
public boolean isAscending ()
{
Object oo = get_Value(COLUMNNAME_IsAscending);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst | */
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_SortPref_Line.java | 1 |
请完成以下Java代码 | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Version.
@param Version | Version of the table definition
*/
public void setVersion (String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
public String getVersion ()
{
return (String)get_Value(COLUMNNAME_Version);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Modification.java | 1 |
请完成以下Java代码 | public static boolean equals(final HuPackingInstructionsItemId o1, final HuPackingInstructionsItemId o2)
{
return Objects.equals(o1, o2);
}
public boolean isTemplate()
{
return isTemplateRepoId(repoId);
}
public static boolean isTemplateRepoId(final int repoId)
{
return repoId == TEMPLATE_MATERIAL_ITEM.repoId
|| repoId == TEMPLATE_PACKING_ITEM.repoId;
}
public boolean isVirtual()
{
return isVirtualRepoId(repoId);
}
public static boolean isVirtualRepoId(final int repoId)
{ | return repoId == VIRTUAL.repoId;
}
public boolean isRealPackingInstructions()
{
return isRealPackingInstructionsRepoId(repoId);
}
public static boolean isRealPackingInstructionsRepoId(final int repoId)
{
return repoId > 0
&& !isTemplateRepoId(repoId)
&& !isVirtualRepoId(repoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HuPackingInstructionsItemId.java | 1 |
请完成以下Java代码 | public int getTabLevel()
{
try
{
Integer ll = (Integer)getClientProperty(AdempiereLookAndFeel.TABLEVEL);
if (ll != null)
return ll.intValue();
}
catch (Exception e)
{
System.err.println("ClientProperty: " + e.getMessage());
}
return 0;
} // getTabLevel
/************************************************************************** | * String representation
* @return String representation
*/
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("CPanel [");
sb.append(super.toString());
MFColor bg = getBackgroundColor();
if (bg != null)
sb.append(bg.toString());
sb.append("]");
return sb.toString();
} // toString
} // CPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPanel.java | 1 |
请完成以下Java代码 | public class EntityNotFoundException extends AdempiereException
{
public static final EntityNotFoundException wrapIfNeeded(@NonNull final Throwable throwable)
{
if (throwable instanceof EntityNotFoundException)
{
return (EntityNotFoundException)throwable;
}
final Throwable cause = extractCause(throwable);
if (cause != throwable)
{
return wrapIfNeeded(cause);
}
return new EntityNotFoundException(extractMessage(throwable), cause);
} | public EntityNotFoundException(final String message)
{
super(message);
}
public EntityNotFoundException(final ITranslatableString message)
{
super(message);
}
public EntityNotFoundException(final String message, final Throwable cause)
{
super(message, cause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\exceptions\EntityNotFoundException.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.