instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private ExecutorService createExecutorOrNull(@NonNull final Topic topic)
{
// Setup EventBus executor
if (EventBusConfig.isEventBusPostAsync(topic))
{
return Executors.newSingleThreadExecutor(CustomizableThreadFactory.builder()
.setThreadNamePrefix(getClass().getName() + "-" + topic.getName() + "-AsyncExecutor")
.setDaemon(true)
.build());
}
else
{
return null;
}
}
private void destroyEventBus(@NonNull final EventBus eventBus)
{
eventBus.destroy();
}
@Override
public void registerGlobalEventListener(
@NonNull final Topic topic,
@NonNull final IEventListener listener)
{
// Register the listener to EventBus
getEventBus(topic).subscribe(listener);
// Add the listener to our global listeners-multimap.
// Note that getEventBus(topic) creates the bus on the fly if needed **and subscribes all global listeners to it**
// Therefore we need to add this listener to the global map *after* having gotten and possibly on-the-fly-created the event bus.
if (!globalEventListeners.put(topic, listener))
{
// listener already exists => do nothing
return;
}
logger.info("Registered global listener to {}: {}", topic, listener);
}
@Override
public void addAvailableUserNotificationsTopic(@NonNull final Topic topic)
{
final boolean added = availableUserNotificationsTopic.add(topic);
logger.info("Registered user notifications topic: {} (already registered: {})", topic, !added); | }
/**
* @return set of available topics on which user can subscribe for UI notifications
*/
private Set<Topic> getAvailableUserNotificationsTopics()
{
return ImmutableSet.copyOf(availableUserNotificationsTopic);
}
@Override
public void registerUserNotificationsListener(@NonNull final IEventListener listener)
{
getAvailableUserNotificationsTopics()
.stream()
.map(this::getEventBus)
.forEach(eventBus -> eventBus.subscribe(listener));
}
@Override
public void unregisterUserNotificationsListener(@NonNull final IEventListener listener)
{
getAvailableUserNotificationsTopics()
.stream()
.map(this::getEventBus)
.forEach(eventBus -> eventBus.unsubscribe(listener));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBusFactory.java | 1 |
请完成以下Java代码 | public void setM_Ingredients_ID (final int M_Ingredients_ID)
{
if (M_Ingredients_ID < 1)
set_Value (COLUMNNAME_M_Ingredients_ID, null);
else
set_Value (COLUMNNAME_M_Ingredients_ID, M_Ingredients_ID);
}
@Override
public int getM_Ingredients_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Ingredients_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Product_Ingredients_ID (final int M_Product_Ingredients_ID)
{
if (M_Product_Ingredients_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_Ingredients_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_Ingredients_ID, M_Product_Ingredients_ID);
}
@Override
public int getM_Product_Ingredients_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Ingredients_ID);
}
@Override
public void setNRV (final int NRV)
{
set_Value (COLUMNNAME_NRV, NRV);
}
@Override
public int getNRV()
{
return get_ValueAsInt(COLUMNNAME_NRV);
}
@Override
public org.compiere.model.I_M_Ingredients getParentElement()
{
return get_ValueAsPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class);
}
@Override
public void setParentElement(final org.compiere.model.I_M_Ingredients ParentElement)
{
set_ValueFromPO(COLUMNNAME_ParentElement_ID, org.compiere.model.I_M_Ingredients.class, ParentElement);
}
@Override
public void setParentElement_ID (final int ParentElement_ID) | {
if (ParentElement_ID < 1)
set_Value (COLUMNNAME_ParentElement_ID, null);
else
set_Value (COLUMNNAME_ParentElement_ID, ParentElement_ID);
}
@Override
public int getParentElement_ID()
{
return get_ValueAsInt(COLUMNNAME_ParentElement_ID);
}
@Override
public void setPrecision (final int Precision)
{
set_Value (COLUMNNAME_Precision, Precision);
}
@Override
public int getPrecision()
{
return get_ValueAsInt(COLUMNNAME_Precision);
}
@Override
public void setQty (final @Nullable java.lang.String Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public java.lang.String getQty()
{
return get_ValueAsString(COLUMNNAME_Qty);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Ingredients.java | 1 |
请完成以下Java代码 | public static LocalDate fromJsonToLocalDate(final String valueStr)
{
final JSONDateConfig config = JSONDateConfig.DEFAULT;
return LocalDate.parse(valueStr, config.getLocalDateFormatter());
}
@NonNull
public static LocalTime fromJsonToLocalTime(final String valueStr)
{
final JSONDateConfig config = JSONDateConfig.DEFAULT;
return LocalTime.parse(valueStr, config.getLocalTimeFormatter());
}
@NonNull
public static ZonedDateTime fromJsonToZonedDateTime(final String valueStr)
{
final JSONDateConfig config = JSONDateConfig.DEFAULT;
return ZonedDateTime.parse(valueStr, config.getZonedDateTimeFormatter());
}
@NonNull
public static Instant fromJsonToInstant(final String valueStr)
{
final JSONDateConfig config = JSONDateConfig.DEFAULT;
return ZonedDateTime.parse(valueStr, config.getTimestampFormatter())
.toInstant();
}
@Nullable
private static LocalDate fromObjectToLocalDate(final Object valueObj, final ZoneId zoneId)
{
return fromObjectTo(valueObj,
LocalDate.class,
DateTimeConverters::fromJsonToLocalDate,
(object) -> TimeUtil.asLocalDate(object, zoneId));
}
@Nullable
private static LocalTime fromObjectToLocalTime(final Object valueObj, final ZoneId zoneId)
{
return fromObjectTo(valueObj,
LocalTime.class,
DateTimeConverters::fromJsonToLocalTime,
(object) -> TimeUtil.asLocalTime(object, zoneId));
}
@Nullable
private static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj, final ZoneId zoneId)
{
return fromObjectTo(valueObj,
ZonedDateTime.class,
DateTimeConverters::fromJsonToZonedDateTime,
(object) -> TimeUtil.asZonedDateTime(object, zoneId));
} | @Nullable
private static Instant fromObjectToInstant(final Object valueObj, final ZoneId zoneId)
{
return fromObjectTo(valueObj,
Instant.class,
DateTimeConverters::fromJsonToInstant,
(object) -> TimeUtil.asInstant(object, zoneId));
}
@Nullable
private static <T> T fromObjectTo(
@NonNull final Object valueObj,
@NonNull final Class<T> type,
@NonNull final Function<String, T> fromJsonConverter,
@NonNull final Function<Object, T> fromObjectConverter)
{
if (type.isInstance(valueObj))
{
return type.cast(valueObj);
}
else if (valueObj instanceof CharSequence)
{
final String json = valueObj.toString().trim();
if (json.isEmpty())
{
return null;
}
if (json.length() == 21 && json.charAt(10) == ' ') // json string - possible in JDBC format (`2016-06-11 00:00:00.0`)
{
final Timestamp timestamp = Timestamp.valueOf(json);
return fromObjectConverter.apply(timestamp);
}
else
{
return fromJsonConverter.apply(json);
}
}
else
{
return fromObjectConverter.apply(valueObj);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\DateTimeConverters.java | 1 |
请完成以下Java代码 | public void requestCarrierAdvises(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds, final boolean isIncludeCarrierAdviseManual)
{
shipmentScheduleService.getByIds(shipmentScheduleIds)
.forEach(schedule -> requestCarrierAdvise(schedule, isIncludeCarrierAdviseManual));
}
public void requestCarrierAdvises(@NonNull final ShipmentScheduleQuery query)
{
shipmentScheduleService.getBy(query)
.forEach(schedule -> requestCarrierAdvise(schedule, false));
}
private void requestCarrierAdvise(@NonNull final ShipmentSchedule shipmentSchedule, final boolean isIncludeCarrierAdviseManual)
{
trxManager.runInThreadInheritedTrx(() -> {
if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(shipmentSchedule, isIncludeCarrierAdviseManual))
{
return;
}
shipmentSchedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Requested);
shipmentSchedule.setCarrierProductId(null); | shipmentScheduleService.save(shipmentSchedule);
});
}
public void updateEligibleShipmentSchedules(@NonNull final CarrierAdviseUpdateRequest request)
{
shipmentScheduleService.updateByQuery(request.getQuery(), schedule -> updateEligibleShipmentSchedule(schedule, request));
}
private void updateEligibleShipmentSchedule(@NonNull final ShipmentSchedule schedule, @NonNull final CarrierAdviseUpdateRequest request)
{
if (shipmentScheduleService.isNotEligibleForManualCarrierAdvise(schedule, request.isIncludeCarrierAdviseManual()))
{
return;
}
schedule.setCarrierAdvisingStatus(CarrierAdviseStatus.Manual);
schedule.setCarrierProductId(request.getCarrierProductId());
schedule.setCarrierGoodsTypeId(request.getCarrierGoodsTypeId());
schedule.setCarrierServices(request.getCarrierServiceIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\process\CarrierAdviseProcessService.java | 1 |
请完成以下Java代码 | public void setQuickInput_OpenButton_Caption (final @Nullable java.lang.String QuickInput_OpenButton_Caption)
{
set_Value (COLUMNNAME_QuickInput_OpenButton_Caption, QuickInput_OpenButton_Caption);
}
@Override
public java.lang.String getQuickInput_OpenButton_Caption()
{
return get_ValueAsString(COLUMNNAME_QuickInput_OpenButton_Caption);
}
@Override
public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic)
{
set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic);
}
@Override
public java.lang.String getReadOnlyLogic()
{
return get_ValueAsString(COLUMNNAME_ReadOnlyLogic);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTabLevel (final int TabLevel)
{
set_Value (COLUMNNAME_TabLevel, TabLevel);
}
@Override
public int getTabLevel()
{
return get_ValueAsInt(COLUMNNAME_TabLevel);
}
@Override
public org.compiere.model.I_AD_Tab getTemplate_Tab()
{
return get_ValueAsPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class);
}
@Override
public void setTemplate_Tab(final org.compiere.model.I_AD_Tab Template_Tab) | {
set_ValueFromPO(COLUMNNAME_Template_Tab_ID, org.compiere.model.I_AD_Tab.class, Template_Tab);
}
@Override
public void setTemplate_Tab_ID (final int Template_Tab_ID)
{
if (Template_Tab_ID < 1)
set_Value (COLUMNNAME_Template_Tab_ID, null);
else
set_Value (COLUMNNAME_Template_Tab_ID, Template_Tab_ID);
}
@Override
public int getTemplate_Tab_ID()
{
return get_ValueAsInt(COLUMNNAME_Template_Tab_ID);
}
@Override
public void setWhereClause (final @Nullable java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public java.lang.String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tab.java | 1 |
请完成以下Java代码 | public void setMD_Candidate(de.metas.material.dispo.model.I_MD_Candidate MD_Candidate)
{
set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate);
}
@Override
public void setMD_Candidate_ID (int MD_Candidate_ID)
{
if (MD_Candidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Candidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Candidate_ID, Integer.valueOf(MD_Candidate_ID));
}
@Override
public int getMD_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID);
}
@Override
public org.compiere.model.I_M_ForecastLine getM_ForecastLine()
{
return get_ValueAsPO(COLUMNNAME_M_ForecastLine_ID, org.compiere.model.I_M_ForecastLine.class);
}
@Override
public void setM_ForecastLine(org.compiere.model.I_M_ForecastLine M_ForecastLine)
{
set_ValueFromPO(COLUMNNAME_M_ForecastLine_ID, org.compiere.model.I_M_ForecastLine.class, M_ForecastLine);
}
@Override
public void setM_ForecastLine_ID (int M_ForecastLine_ID)
{
if (M_ForecastLine_ID < 1)
set_Value (COLUMNNAME_M_ForecastLine_ID, null);
else
set_Value (COLUMNNAME_M_ForecastLine_ID, Integer.valueOf(M_ForecastLine_ID));
}
@Override
public int getM_ForecastLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ForecastLine_ID);
}
@Override
public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
@Override
public int getM_ShipmentSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID);
} | @Override
public void setPlannedQty (java.math.BigDecimal PlannedQty)
{
set_Value (COLUMNNAME_PlannedQty, PlannedQty);
}
@Override
public java.math.BigDecimal getPlannedQty()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_InOutLine_ID (final int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, M_InOutLine_ID);
}
@Override
public int getM_InOutLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOutLine_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_Demand_Detail.java | 1 |
请完成以下Java代码 | public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(); | sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", pid=").append(pid);
sb.append(", name=").append(name);
sb.append(", value=").append(value);
sb.append(", icon=").append(icon);
sb.append(", type=").append(type);
sb.append(", uri=").append(uri);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsPermission.java | 1 |
请完成以下Java代码 | public AllowedValues getAllowedValues() {
return allowedValuesChild.getChild(this);
}
public void setAllowedValues(AllowedValues allowedValues) {
allowedValuesChild.setChild(this, allowedValues);
}
public Collection<ItemComponent> getItemComponents() {
return itemComponentCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ItemDefinition.class, DMN_ELEMENT_ITEM_DEFINITION)
.namespaceUri(LATEST_DMN_NS)
.extendsType(NamedElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ItemDefinition>() {
public ItemDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new ItemDefinitionImpl(instanceContext);
}
}); | typeLanguageAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_TYPE_LANGUAGE)
.build();
isCollectionAttribute = typeBuilder.booleanAttribute(DMN_ATTRIBUTE_IS_COLLECTION)
.defaultValue(false)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
typeRefChild = sequenceBuilder.element(TypeRef.class)
.build();
allowedValuesChild = sequenceBuilder.element(AllowedValues.class)
.build();
itemComponentCollection = sequenceBuilder.elementCollection(ItemComponent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\ItemDefinitionImpl.java | 1 |
请完成以下Java代码 | public Point getPoint0_0()
{
return m_point0_0;
} // getPoint0_0
/**
* @return Returns the x_AxisLabel.
*/
public String getX_AxisLabel ()
{
return builder.getXAxisLabel();
} // getX_AxisLabel
/**
* @param axisLabel The x_AxisLabel to set.
*/
public void setX_AxisLabel (String axisLabel)
{
builder.setXAxisLabel(axisLabel);
} // setX_AxisLabel
/**
* @return Returns the y_AxisLabel.
*/
public String getY_AxisLabel ()
{
return builder.getYAxisLabel();
} // getY_AxisLabel
/**
* @param axisLabel The y_AxisLabel to set.
*/
public void setY_AxisLabel (String axisLabel)
{
builder.setYAxisLabel(axisLabel);
} // setY_AxisLabel
/**
* @return Returns the y_TargetLabel.
*/
public String getY_TargetLabel ()
{
return m_Y_TargetLabel;
} // getY_TargetLabel
/**
* @param targetLabel The y_TargetLabel to set.
*/
public void setY_TargetLabel (String targetLabel, double target)
{
m_Y_TargetLabel = targetLabel;
m_Y_Target = target;
} // setY_TargetLabel
/**
* Get BarGraphColumn for ChartEntity
* @param event
* @return BarGraphColumn or null if not found
*/
private GraphColumn getGraphColumn(ChartMouseEvent event)
{
ChartEntity entity = event.getEntity();
String key = null;
if (entity instanceof CategoryItemEntity)
{
Comparable<?> colKey = ((CategoryItemEntity)entity).getColumnKey();
if (colKey != null)
{
key = colKey.toString();
}
}
else if (entity instanceof PieSectionEntity)
{
Comparable<?> sectionKey = ((PieSectionEntity)entity).getSectionKey();
if (sectionKey != null)
{
key = sectionKey.toString();
}
}
if (key == null)
{
return null;
}
for (int i = 0; i < list.size(); i++)
{
final String label = list.get(i).getLabel();
if (key.equals(label))
{
return list.get(i); | }
}
//
return null;
}
@Override
public void chartMouseClicked(ChartMouseEvent event)
{
if ((event.getEntity()!=null) && (event.getTrigger().getClickCount() > 1))
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
GraphColumn bgc = getGraphColumn(event);
if (bgc == null)
{
return;
}
MQuery query = bgc.getMQuery(builder.getMGoal());
if (query != null)
AEnv.zoom(query);
else
log.warn("Nothing to zoom to - " + bgc);
}
finally
{
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
}
@Override
public void chartMouseMoved(ChartMouseEvent event)
{
}
public GraphColumn[] getGraphColumnList()
{
return list.toArray(new GraphColumn[list.size()]);
}
} // BarGraph | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\adempiere\apps\graph\Graph.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ApiResponse<Users> getUserWithHttpInfo(String albertaApiKey, String _id) throws ApiException {
com.squareup.okhttp.Call call = getUserValidateBeforeCall(albertaApiKey, _id, null, null);
Type localVarReturnType = new TypeToken<Users>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Daten eines einzelnen Benutzers abrufen (asynchronously)
* Szenario - das WaWi fragt bei Alberta nach, wie die Daten eines Benutzers mit der angegebenen Id sind
* @param albertaApiKey (required)
* @param _id eindeutige id des Benutzers (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getUserAsync(String albertaApiKey, String _id, final ApiCallback<Users> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
}; | progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getUserValidateBeforeCall(albertaApiKey, _id, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<Users>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\UserApi.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static Date asDate()
{
return new Date(SystemTime.millis());
}
public static Timestamp asTimestamp()
{
return new Timestamp(SystemTime.millis());
}
private static TimeSource getTimeSource()
{
return SystemTime.timeSource == null ? SystemTime.defaultTimeSource : SystemTime.timeSource;
}
/**
* After invocation of this method, the time returned will be the system time again.
*/ | public static void resetTimeSource()
{
SystemTime.timeSource = null;
}
/**
*
* @param newTimeSource the given TimeSource will be used for the time returned by the methods of this class (unless it is null).
*
*/
public static void setTimeSource(final TimeSource newTimeSource)
{
SystemTime.timeSource = newTimeSource;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\SystemTime.java | 2 |
请完成以下Java代码 | public boolean isInitialized() {
return this.initialized;
}
/**
* Builder for {@link GroovyFieldDeclaration}.
*/
public static final class Builder {
private final String name;
private String returnType;
private int modifiers;
private Object value;
private boolean initialized;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
} | /**
* Sets the value.
* @param value the value
* @return this for method chaining
*/
public Builder value(Object value) {
this.value = value;
this.initialized = true;
return this;
}
/**
* Sets the return type.
* @param returnType the return type
* @return the field
*/
public GroovyFieldDeclaration returning(String returnType) {
this.returnType = returnType;
return new GroovyFieldDeclaration(this);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyFieldDeclaration.java | 1 |
请完成以下Java代码 | protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("StartDate"))
p_StartDate = (Timestamp)para[i].getParameter();
else if (name.equals("DateFormat"))
p_DateFormat = (String)para[i].getParameter();
else
log.error("Unknown Parameter: " + name);
}
p_C_Year_ID = getRecord_ID();
} // prepare | @Override
protected String doIt()
{
final I_C_Year year = load(p_C_Year_ID, I_C_Year.class);
if (year == null)
{
throw new AdempiereException("@NotFound@: @C_Year_ID@ - " + p_C_Year_ID);
}
log.info("Year: {}", year);
//
final Locale locale = null;
MYear.createStdPeriods(year, locale, p_StartDate, p_DateFormat);
return "@OK@";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\YearCreatePeriods.java | 1 |
请完成以下Java代码 | public void setMandatoryOnShipment (final @Nullable java.lang.String MandatoryOnShipment)
{
set_Value (COLUMNNAME_MandatoryOnShipment, MandatoryOnShipment);
}
@Override
public java.lang.String getMandatoryOnShipment()
{
return get_ValueAsString(COLUMNNAME_MandatoryOnShipment);
}
@Override
public void setM_Attribute_ID (final int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID);
}
@Override
public int getM_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Attribute_ID);
}
@Override
public org.compiere.model.I_M_AttributeSet getM_AttributeSet()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class);
}
@Override
public void setM_AttributeSet(final org.compiere.model.I_M_AttributeSet M_AttributeSet)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet);
}
@Override
public void setM_AttributeSet_ID (final int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID);
}
@Override
public int getM_AttributeSet_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID); | }
@Override
public void setM_AttributeUse_ID (final int M_AttributeUse_ID)
{
if (M_AttributeUse_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeUse_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeUse_ID, M_AttributeUse_ID);
}
@Override
public int getM_AttributeUse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeUse_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeUse.java | 1 |
请完成以下Java代码 | private static boolean isListener(Class<?> beanType) {
return GenericMessageListener.class.isAssignableFrom(beanType);
}
private static void checkType(@Nullable Type paramType, Set<Class<?>> avroTypes) {
if (paramType == null) {
return;
}
boolean container = isContainer(paramType);
if (!container && paramType instanceof Class) {
MergedAnnotations mergedAnnotations = MergedAnnotations.from((Class<?>) paramType);
if (mergedAnnotations.isPresent(AVRO_GENERATED_CLASS_NAME)) {
avroTypes.add((Class<?>) paramType);
}
}
else if (container && paramType instanceof ParameterizedType) {
Type[] generics = ((ParameterizedType) paramType).getActualTypeArguments();
if (generics.length > 0) {
checkAvro(generics[0], avroTypes);
}
if (generics.length == 2) {
checkAvro(generics[1], avroTypes);
}
}
}
private static void checkAvro(@Nullable Type generic, Set<Class<?>> avroTypes) { | if (generic instanceof Class) {
MergedAnnotations methodAnnotations = MergedAnnotations.from((Class<?>) generic);
if (methodAnnotations.isPresent(AVRO_GENERATED_CLASS_NAME)) {
avroTypes.add((Class<?>) generic);
}
}
}
private static boolean isContainer(Type paramType) {
if (paramType instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) paramType).getRawType();
return (rawType.equals(List.class))
|| rawType.getTypeName().equals(CONSUMER_RECORD_CLASS_NAME)
|| rawType.getTypeName().equals(CONSUMER_RECORDS_CLASS_NAME);
}
return false;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\aot\KafkaAvroBeanRegistrationAotProcessor.java | 1 |
请完成以下Java代码 | public class HistoricActivityStatisticsImpl implements HistoricActivityStatistics {
protected String id;
protected long instances;
protected long finished;
protected long canceled;
protected long completeScope;
protected long openIncidents;
protected long resolvedIncidents;
protected long deletedIncidents;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getInstances() {
return instances;
}
public void setInstances(long instances) {
this.instances = instances;
}
public long getFinished() {
return finished;
}
public void setFinished(long finished) {
this.finished = finished;
}
public long getCanceled() {
return canceled;
}
public void setCanceled(long canceled) {
this.canceled = canceled;
}
public long getCompleteScope() {
return completeScope;
}
public void setCompleteScope(long completeScope) {
this.completeScope = completeScope;
} | public long getOpenIncidents() {
return openIncidents;
}
public void setOpenIncidents(long openIncidents) {
this.openIncidents = openIncidents;
}
public long getResolvedIncidents() {
return resolvedIncidents;
}
public void setResolvedIncidents(long resolvedIncidents) {
this.resolvedIncidents = resolvedIncidents;
}
public long getDeletedIncidents() {
return deletedIncidents;
}
public void setDeletedIncidents(long closedIncidents) {
this.deletedIncidents = closedIncidents;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricActivityStatisticsImpl.java | 1 |
请完成以下Java代码 | public void setPort(int port) {
this.port = port;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Date getLastFetch() {
return lastFetch;
}
public void setLastFetch(Date lastFetch) {
this.lastFetch = lastFetch; | }
@Override
public String toString() {
return "MetricPositionEntity{" +
"id=" + id +
", gmtCreate=" + gmtCreate +
", gmtModified=" + gmtModified +
", app='" + app + '\'' +
", ip='" + ip + '\'' +
", port=" + port +
", hostname='" + hostname + '\'' +
", lastFetch=" + lastFetch +
'}';
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MetricPositionEntity.java | 1 |
请完成以下Java代码 | public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getCelestialObjectName() {
return celestialObjectName;
}
public void setCelestialObjectName(String celestialObjectName) {
this.celestialObjectName = celestialObjectName;
}
public ZonedDateTime getObservationStartTime() {
return observationStartTime;
}
public void setObservationStartTime(ZonedDateTime observationStartTime) {
this.observationStartTime = observationStartTime;
}
public OffsetDateTime getPeakVisibilityTime() {
return peakVisibilityTime;
}
public void setPeakVisibilityTime(OffsetDateTime peakVisibilityTime) { | this.peakVisibilityTime = peakVisibilityTime;
}
public Integer getPeakVisibilityTimeOffset() {
return peakVisibilityTimeOffset;
}
public void setPeakVisibilityTimeOffset(Integer peakVisibilityTimeOffset) {
this.peakVisibilityTimeOffset = peakVisibilityTimeOffset;
}
public ZonedDateTime getNextExpectedAppearance() {
return nextExpectedAppearance;
}
public void setNextExpectedAppearance(ZonedDateTime nextExpectedAppearance) {
this.nextExpectedAppearance = nextExpectedAppearance;
}
public OffsetDateTime getLastRecordedSighting() {
return lastRecordedSighting;
}
public void setLastRecordedSighting(OffsetDateTime lastRecordedSighting) {
this.lastRecordedSighting = lastRecordedSighting;
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\timezonestorage\AstronomicalObservation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PackingItemParts copy()
{
return new PackingItemParts(this);
}
public boolean isEmpty()
{
return partsMap.isEmpty();
}
public Object size()
{
return partsMap.size();
}
public <T> Stream<T> map(@NonNull final Function<PackingItemPart, T> mapper)
{
return partsMap
.values()
.stream()
.map(mapper);
}
public <T> Optional<T> mapReduce(@NonNull final Function<PackingItemPart, T> mapper)
{
final ImmutableSet<T> result = map(mapper)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
if (result.isEmpty())
{
return Optional.empty();
}
else if (result.size() == 1)
{
final T singleResult = result.iterator().next();
return Optional.of(singleResult);
}
else
{
throw new AdempiereException("Got more than one result: " + result);
}
}
public void setFrom(final PackingItemParts from)
{
partsMap.clear();
partsMap.putAll(from.partsMap);
}
public Optional<Quantity> getQtySum()
{
return map(PackingItemPart::getQty)
.reduce(Quantity::add);
}
public List<PackingItemPart> toList()
{
return ImmutableList.copyOf(partsMap.values());
}
public I_C_UOM getCommonUOM()
{
//validate that all qtys have the same UOM
mapReduce(part -> part.getQty().getUomId())
.orElseThrow(()-> new AdempiereException("Missing I_C_UOM!") | .appendParametersToMessage()
.setParameter("Parts", this));
return toList().get(0).getQty().getUOM();
}
@Override
public Iterator<PackingItemPart> iterator()
{
return toList().iterator();
}
public void clear()
{
partsMap.clear();
}
public void addQtys(final PackingItemParts partsToAdd)
{
partsToAdd.toList()
.forEach(this::addQty);
}
private void addQty(final PackingItemPart part)
{
partsMap.compute(part.getId(),
(id, existingPart) -> existingPart != null ? existingPart.addQty(part.getQty()) : part);
}
public void removePart(final PackingItemPart part)
{
partsMap.remove(part.getId(), part);
}
public void updatePart(@NonNull final PackingItemPart part)
{
partsMap.put(part.getId(), part);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemParts.java | 2 |
请完成以下Java代码 | public class Greeting {
private String msg;
private String name;
public Greeting() {
}
public Greeting(String msg, String name) {
this.msg = msg;
this.name = name;
}
public String getMsg() {
return msg;
} | public void setMsg(String msg) {
this.msg = msg;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return msg + ", " + name + "!";
}
} | repos\tutorials-master\spring-kafka\src\main\java\com\baeldung\kafka\retryable\Greeting.java | 1 |
请完成以下Java代码 | public Void call() throws Exception {
notifyTaskListener(delegateTask);
return null;
}
};
try {
performNotification(execution, notification);
} catch(Exception e) {
throw LOG.exceptionWhileNotifyingPaTaskListener(e);
}
}
}
protected void performNotification(final DelegateExecution execution, Callable<Void> notification) throws Exception {
final ProcessApplicationReference processApp = ProcessApplicationContextUtil.getTargetProcessApplication((ExecutionEntity) execution);
if (processApp == null) {
// ignore silently
LOG.noTargetProcessApplicationForExecution(execution);
} else {
if (ProcessApplicationContextUtil.requiresContextSwitch(processApp)) {
// this should not be necessary since context switch is already performed by OperationContext and / or DelegateInterceptor
Context.executeWithinProcessApplication(notification, processApp, new InvocationContext(execution));
} else {
// context switch already performed
notification.call();
}
}
}
protected void notifyExecutionListener(DelegateExecution execution) throws Exception {
ProcessApplicationReference processApp = Context.getCurrentProcessApplication();
try {
ProcessApplicationInterface processApplication = processApp.getProcessApplication();
ExecutionListener executionListener = processApplication.getExecutionListener();
if(executionListener != null) {
executionListener.notify(execution);
} else {
LOG.paDoesNotProvideExecutionListener(processApp.getName());
}
} catch (ProcessApplicationUnavailableException e) { | // Process Application unavailable => ignore silently
LOG.cannotInvokeListenerPaUnavailable(processApp.getName(), e);
}
}
protected void notifyTaskListener(DelegateTask task) throws Exception {
ProcessApplicationReference processApp = Context.getCurrentProcessApplication();
try {
ProcessApplicationInterface processApplication = processApp.getProcessApplication();
TaskListener taskListener = processApplication.getTaskListener();
if(taskListener != null) {
taskListener.notify(task);
} else {
LOG.paDoesNotProvideTaskListener(processApp.getName());
}
} catch (ProcessApplicationUnavailableException e) {
// Process Application unavailable => ignore silently
LOG.cannotInvokeListenerPaUnavailable(processApp.getName(), e);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\event\ProcessApplicationEventListenerDelegate.java | 1 |
请完成以下Java代码 | public abstract class DiagramImpl extends BpmnModelElementInstanceImpl implements Diagram {
protected static Attribute<String> nameAttribute;
protected static Attribute<String> documentationAttribute;
protected static Attribute<Double> resolutionAttribute;
protected static Attribute<String> idAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Diagram.class, DI_ELEMENT_DIAGRAM)
.namespaceUri(DI_NS)
.abstractType();
nameAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_NAME)
.build();
documentationAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_DOCUMENTATION)
.build();
resolutionAttribute = typeBuilder.doubleAttribute(DI_ATTRIBUTE_RESOLUTION)
.build();
idAttribute = typeBuilder.stringAttribute(DI_ATTRIBUTE_ID)
.idAttribute()
.build();
typeBuilder.build();
}
public DiagramImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
} | public String getDocumentation() {
return documentationAttribute.getValue(this);
}
public void setDocumentation(String documentation) {
documentationAttribute.setValue(this, documentation);
}
public double getResolution() {
return resolutionAttribute.getValue(this);
}
public void setResolution(double resolution) {
resolutionAttribute.setValue(this, resolution);
}
public String getId() {
return idAttribute.getValue(this);
}
public void setId(String id) {
idAttribute.setValue(this, id);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\di\DiagramImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
return "FixedBatchTrxItemProcessor["
+ "itemsPerBatch=" + itemsPerBatch + "/" + maxItemsPerBatch
+ ", " + processor
+ "]";
}
@Override
public void setTrxItemProcessorCtx(final ITrxItemProcessorContext processorCtx)
{
processor.setTrxItemProcessorCtx(processorCtx);
}
@Override
public RT getResult()
{
return processor.getResult();
}
@Override
public void process(final IT item) throws Exception
{
itemsPerBatch++;
processor.process(item);
}
@Override
public boolean isSameChunk(final IT item)
{
// If we are about to exceed the maximum number of items per batch
// => return false (we need a new chunk/batch)
if (itemsPerBatch >= maxItemsPerBatch)
{
return false;
} | //
// Ask processor is the item is on the same chunk, if this is allowed.
if (!ignoreProcessorIsSameChunkMethod)
{
return processor.isSameChunk(item);
}
// Consider this item on same chunk
return true;
}
@Override
public void newChunk(final IT item)
{
itemsPerBatch = 0;
processor.newChunk(item);
}
@Override
public void completeChunk()
{
processor.completeChunk();
}
@Override
public void cancelChunk()
{
processor.cancelChunk();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\FixedBatchTrxItemProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalSystemScriptedImportConversionHouseKeepingTask implements IStartupHouseKeepingTask
{
private static final Logger logger = LogManager.getLogger(ExternalSystemScriptedImportConversionHouseKeepingTask.class);
private final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
private final ExternalSystemConfigRepo externalSystemConfigDAO;
public ExternalSystemScriptedImportConversionHouseKeepingTask(@NonNull final ExternalSystemConfigRepo externalSystemConfigDAO)
{
this.externalSystemConfigDAO = externalSystemConfigDAO;
}
@Override
public void executeTask()
{
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClassIfUnique(
ExternalSystemProcesses.getExternalSystemProcessClassName(ExternalSystemType.ScriptedImportConversion));
if (processId == null) | {
Loggables.withLogger(logger, Level.DEBUG).addLog("Nothing to do!");
return;
}
final ImmutableList<ExternalSystemParentConfig> parentConfigList = externalSystemConfigDAO.getActiveByType(ExternalSystemType.ScriptedImportConversion);
parentConfigList
.stream()
.peek(config -> Loggables.withLogger(logger, Level.DEBUG).addLog("Firing process " + processId + " for ScriptedImportConversion config " + config.getChildConfig().getId()))
.forEach((config -> ProcessInfo.builder()
.setAD_Process_ID(processId)
.setAD_User_ID(UserId.METASFRESH.getRepoId())
.addParameter(PARAM_EXTERNAL_REQUEST, ScriptedImportConversionCommand.EnableRestAPI.getValue())
.addParameter(PARAM_CHILD_CONFIG_ID, config.getChildConfig().getId().getRepoId())
.buildAndPrepareExecution()
.executeSync()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedimportconversion\housekeeping\ExternalSystemScriptedImportConversionHouseKeepingTask.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class DataEntrySubTabBindingDescriptorBuilder implements DocumentEntityDataBindingDescriptorBuilder
{
private final DocumentEntityDataBindingDescriptor dataBinding;
@Getter
private final DataEntryWebuiTools dataEntryWebuiTools;
public DataEntrySubTabBindingDescriptorBuilder(
@NonNull final DataEntryRecordRepository dataEntryRecordRepository,
@NonNull final DataEntryWebuiTools dataEntryWebuiTools)
{
this.dataEntryWebuiTools = dataEntryWebuiTools;
final DataEntrySubTabBindingRepository dataEntrySubGroupBindingRepository //
= new DataEntrySubTabBindingRepository(dataEntryRecordRepository, dataEntryWebuiTools);
this.dataBinding = new DocumentEntityDataBindingDescriptor()
{
@Override | public DocumentsRepository getDocumentsRepository()
{
return dataEntrySubGroupBindingRepository;
}
};
}
@Override
public DocumentEntityDataBindingDescriptor getOrBuild()
{
return dataBinding;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntrySubTabBindingDescriptorBuilder.java | 2 |
请完成以下Java代码 | public URI getWebhookUrl() {
return webhookUrl;
}
public void setWebhookUrl(@Nullable URI webhookUrl) {
this.webhookUrl = webhookUrl;
}
public String getThemeColor() {
return themeColor.getExpressionString();
}
public void setThemeColor(String themeColor) {
this.themeColor = parser.parseExpression(themeColor, ParserContext.TEMPLATE_EXPRESSION);
}
public String getDeregisterActivitySubtitle() {
return deregisterActivitySubtitle.getExpressionString();
}
public void setDeregisterActivitySubtitle(String deregisterActivitySubtitle) {
this.deregisterActivitySubtitle = parser.parseExpression(deregisterActivitySubtitle,
ParserContext.TEMPLATE_EXPRESSION);
}
public String getRegisterActivitySubtitle() {
return registerActivitySubtitle.getExpressionString();
}
public void setRegisterActivitySubtitle(String registerActivitySubtitle) {
this.registerActivitySubtitle = parser.parseExpression(registerActivitySubtitle,
ParserContext.TEMPLATE_EXPRESSION);
}
public String getStatusActivitySubtitle() {
return statusActivitySubtitle.getExpressionString();
}
public void setStatusActivitySubtitle(String statusActivitySubtitle) {
this.statusActivitySubtitle = parser.parseExpression(statusActivitySubtitle, ParserContext.TEMPLATE_EXPRESSION);
}
@Data | @Builder
public static class Message {
private final String summary;
private final String themeColor;
private final String title;
@Builder.Default
private final List<Section> sections = new ArrayList<>();
}
@Data
@Builder
public static class Section {
private final String activityTitle;
private final String activitySubtitle;
@Builder.Default
private final List<Fact> facts = new ArrayList<>();
}
public record Fact(String name, @Nullable String value) {
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MicrosoftTeamsNotifier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AllergensAsEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "meal_id")
private Long mealId;
@OneToOne
@PrimaryKeyJoinColumn(name = "meal_id")
private MealAsSingleEntity meal;
@Column(name = "peanuts")
private boolean peanuts;
@Column(name = "celery")
private boolean celery;
@Column(name = "sesame_seeds")
private boolean sesameSeeds;
public MealAsSingleEntity getMeal() {
return meal;
}
public void setMeal(MealAsSingleEntity meal) {
this.meal = meal;
}
public boolean isPeanuts() {
return peanuts;
}
public void setPeanuts(boolean peanuts) {
this.peanuts = peanuts;
}
public boolean isCelery() {
return celery; | }
public void setCelery(boolean celery) {
this.celery = celery;
}
public boolean isSesameSeeds() {
return sesameSeeds;
}
public void setSesameSeeds(boolean sesameSeeds) {
this.sesameSeeds = sesameSeeds;
}
@Override
public String toString() {
return "AllergensAsEntity [peanuts=" + peanuts + ", celery=" + celery + ", sesameSeeds=" + sesameSeeds + "]";
}
} | repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\multipletables\multipleentities\AllergensAsEntity.java | 2 |
请完成以下Java代码 | final class CompositeTranslatableString implements ITranslatableString
{
private final ImmutableList<ITranslatableString> list;
private final String joinString;
private transient String defaultValue; // lazy
private transient ImmutableSet<String> adLanguages; // lazy
CompositeTranslatableString(final List<ITranslatableString> list, final String joinString)
{
this.list = ImmutableList.copyOf(list);
this.joinString = joinString != null ? joinString : "";
}
@Override
@Deprecated
public String toString()
{
return list.stream().map(ITranslatableString::toString).collect(Collectors.joining(joinString));
}
@Override
public String translate(final String adLanguage)
{
return list.stream().map(trl -> trl.translate(adLanguage)).collect(Collectors.joining(joinString));
}
@Override
public String getDefaultValue()
{
String defaultValue = this.defaultValue;
if (defaultValue == null)
{
this.defaultValue = defaultValue = list.stream().map(trl -> trl.getDefaultValue()).collect(Collectors.joining(joinString)); | }
return defaultValue;
}
@Override
public Set<String> getAD_Languages()
{
ImmutableSet<String> adLanguages = this.adLanguages;
if (adLanguages == null)
{
this.adLanguages = adLanguages = list.stream().flatMap(trl -> trl.getAD_Languages().stream()).collect(ImmutableSet.toImmutableSet());
}
return adLanguages;
}
@Override
public boolean isTranslatedTo(final String adLanguage)
{
return list.stream().anyMatch(trl -> trl.isTranslatedTo(adLanguage));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\CompositeTranslatableString.java | 1 |
请完成以下Java代码 | 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 Manual.
@param IsManual
This is a manual process
*/
public void setIsManual (boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual));
}
/** Get Manual.
@return This is a manual process
*/
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
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());
}
/** Set SLA Criteria.
@param PA_SLA_Criteria_ID
Service Level Agreement Criteria
*/
public void setPA_SLA_Criteria_ID (int PA_SLA_Criteria_ID)
{
if (PA_SLA_Criteria_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Criteria_ID, Integer.valueOf(PA_SLA_Criteria_ID));
}
/** Get SLA Criteria.
@return Service Level Agreement Criteria
*/
public int getPA_SLA_Criteria_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Criteria_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Criteria.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LineItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ManyToOne
private OrderRequest orderRequest;
public LineItem(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) | return true;
if (o == null || getClass() != o.getClass())
return false;
LineItem lineItem = (LineItem) o;
return Objects.equals(id, lineItem.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
protected LineItem() {
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\removal\LineItem.java | 2 |
请完成以下Java代码 | public BigDecimal getNumber()
{
if (m_abort)
{
return null;
}
return m_number;
} // getNumber
public boolean isDisposeOnEqual()
{
return p_disposeOnEqual;
}
public void setDisposeOnEqual(boolean b)
{
p_disposeOnEqual = b;
}
/*************************************************************************/
/**
* KeyPressed Listener
* @param e event
*/
@Override
public void keyPressed(KeyEvent e)
{
// sequence: pressed - typed(no KeyCode) - released
char input = e.getKeyChar();
int code = e.getKeyCode();
e.consume(); // does not work on JTextField
if (code == KeyEvent.VK_DELETE)
{
input = 'A';
}
else if (code == KeyEvent.VK_BACK_SPACE)
{
input = 'C';
} | else if (code == KeyEvent.VK_ENTER)
{
input = '=';
}
else if (code == KeyEvent.VK_CANCEL || code == KeyEvent.VK_ESCAPE)
{
m_abort = true;
dispose();
return;
}
handleInput(input);
}
/**
* KeyTyped Listener (nop)
* @param e event
*/
@Override
public void keyTyped(KeyEvent e) {}
/**
* KeyReleased Listener (nop)
* @param e event
*/
@Override
public void keyReleased(KeyEvent e) {}
} // Calculator | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\Calculator.java | 1 |
请完成以下Java代码 | public synchronized final Set<String> getDefinedColumnNames()
{
if (_definedColumnNames == null)
{
_definedColumnNames = findDefinedColumnNames();
}
return _definedColumnNames;
}
@SuppressWarnings("unchecked")
private final Set<String> findDefinedColumnNames()
{
//
// Collect all columnnames
final ImmutableSet.Builder<String> columnNamesBuilder = ImmutableSet.builder();
ReflectionUtils.getAllFields(modelClass, new Predicate<Field>()
{ | @Override
public boolean apply(final Field field)
{
final String fieldName = field.getName();
if (fieldName.startsWith("COLUMNNAME_"))
{
final String columnName = fieldName.substring("COLUMNNAME_".length());
columnNamesBuilder.add(columnName);
}
return false;
}
});
return columnNamesBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\ModelClassInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ClusterDataSourceConfig {
// 精确到 cluster 目录,以便跟其他数据源隔离
static final String PACKAGE = "org.spring.springboot.dao.cluster";
static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";
@Value("${cluster.datasource.url}")
private String url;
@Value("${cluster.datasource.username}")
private String user;
@Value("${cluster.datasource.password}")
private String password;
@Value("${cluster.datasource.driverClassName}")
private String driverClass;
@Bean(name = "clusterDataSource")
public DataSource clusterDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
} | @Bean(name = "clusterTransactionManager")
public DataSourceTransactionManager clusterTransactionManager() {
return new DataSourceTransactionManager(clusterDataSource());
}
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(clusterDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
return sessionFactory.getObject();
}
} | repos\springboot-learning-example-master\springboot-mybatis-mutil-datasource\src\main\java\org\spring\springboot\config\ds\ClusterDataSourceConfig.java | 2 |
请完成以下Java代码 | public void sensitivePointCut() {
}
@Around("sensitivePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
// 处理结果
Object result = point.proceed();
if(result == null){
return result;
}
Class resultClass = result.getClass();
log.debug(" resultClass = {}" , resultClass);
if(resultClass.isPrimitive()){
//是基本类型 直接返回 不需要处理
return result;
}
// 获取方法注解信息:是哪个实体、是加密还是解密
boolean isEncode = true;
Class entity = null;
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
SensitiveEncode encode = method.getAnnotation(SensitiveEncode.class);
if(encode==null){
SensitiveDecode decode = method.getAnnotation(SensitiveDecode.class);
if(decode!=null){
entity = decode.entity();
isEncode = false;
}
}else{
entity = encode.entity();
} | long startTime=System.currentTimeMillis();
if(resultClass.equals(entity) || entity.equals(Object.class)){
// 方法返回实体和注解的entity一样,如果注解没有申明entity属性则认为是(方法返回实体和注解的entity一样)
SensitiveInfoUtil.handlerObject(result, isEncode);
} else if(result instanceof List){
// 方法返回List<实体>
SensitiveInfoUtil.handleList(result, entity, isEncode);
}else{
// 方法返回一个对象
SensitiveInfoUtil.handleNestedObject(result, entity, isEncode);
}
long endTime=System.currentTimeMillis();
log.debug((isEncode ? "加密操作," : "解密操作,") + "Aspect程序耗时:" + (endTime - startTime) + "ms");
return result;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\desensitization\aspect\SensitiveDataAspect.java | 1 |
请完成以下Java代码 | public Collection<AutoDeploymentStrategy<EventRegistryEngine>> getDeploymentStrategies() {
return deploymentStrategies;
}
public void setDeploymentStrategies(Collection<AutoDeploymentStrategy<EventRegistryEngine>> deploymentStrategies) {
this.deploymentStrategies = deploymentStrategies;
}
@Override
public void start() {
synchronized (lifeCycleMonitor) {
if (!isRunning()) {
enginesBuild.forEach(name -> {
EventRegistryEngine eventRegistryEngine = EventRegistryEngines.getEventRegistryEngine(name);
eventRegistryEngine.handleDeployedChannelDefinitions();
createAndInitEventRegistryChangeDetectionExecutor();
autoDeployResources(eventRegistryEngine);
});
running = true;
}
}
}
@Override
public void initChangeDetectionExecutor() {
if (eventRegistryChangeDetectionExecutor == null) {
eventRegistryChangeDetectionExecutor = new DefaultSpringEventRegistryChangeDetectionExecutor(
eventRegistryChangeDetectionInitialDelayInMs, eventRegistryChangeDetectionDelayInMs);
}
} | protected void createAndInitEventRegistryChangeDetectionExecutor() {
if (enableEventRegistryChangeDetection && eventRegistryChangeDetectionExecutor != null) {
eventRegistryChangeDetectionExecutor.setEventRegistryChangeDetectionManager(eventRegistryChangeDetectionManager);
eventRegistryChangeDetectionExecutor.initialize();
}
}
@Override
public void stop() {
synchronized (lifeCycleMonitor) {
running = false;
}
}
@Override
public boolean isRunning() {
return running;
}
@Override
public int getPhase() {
return SpringEngineConfiguration.super.getPhase() - SpringEngineConfiguration.PHASE_DELTA * 2;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\SpringEventRegistryEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public WidgetTypeDetails save(WidgetTypeDetails entity, SecurityUser user) throws Exception {
return this.save(entity, false, user);
}
@Override
public WidgetTypeDetails save(WidgetTypeDetails widgetTypeDetails, boolean updateExistingByFqn, SecurityUser user) throws Exception {
TenantId tenantId = widgetTypeDetails.getTenantId();
if (widgetTypeDetails.getId() == null && StringUtils.isNotEmpty(widgetTypeDetails.getFqn()) && updateExistingByFqn) {
WidgetType widgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(tenantId, widgetTypeDetails.getFqn());
if (widgetType != null) {
widgetTypeDetails.setId(widgetType.getId());
}
}
if (CollectionUtils.isNotEmpty(widgetTypeDetails.getResources())) {
tbResourceService.importResources(widgetTypeDetails.getResources(), user);
}
ActionType actionType = widgetTypeDetails.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
try {
WidgetTypeDetails savedWidgetTypeDetails = checkNotNull(widgetTypeService.saveWidgetType(widgetTypeDetails));
autoCommit(user, savedWidgetTypeDetails.getId());
logEntityActionService.logEntityAction(tenantId, savedWidgetTypeDetails.getId(), savedWidgetTypeDetails,
null, actionType, user);
return savedWidgetTypeDetails;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.WIDGET_TYPE), widgetTypeDetails, actionType, user, e);
throw e;
}
} | @Override
public void delete(WidgetTypeDetails widgetTypeDetails, User user) {
ActionType actionType = ActionType.DELETED;
TenantId tenantId = widgetTypeDetails.getTenantId();
try {
widgetTypeService.deleteWidgetType(widgetTypeDetails.getTenantId(), widgetTypeDetails.getId());
logEntityActionService.logEntityAction(tenantId, widgetTypeDetails.getId(), widgetTypeDetails, null, actionType, user);
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.WIDGET_TYPE), actionType, user, e, widgetTypeDetails.getId());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\widgets\type\DefaultWidgetTypeService.java | 2 |
请完成以下Java代码 | public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setC_BPartner_Recent_V_ID (final int C_BPartner_Recent_V_ID)
{
if (C_BPartner_Recent_V_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Recent_V_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Recent_V_ID, C_BPartner_Recent_V_ID);
}
@Override
public int getC_BPartner_Recent_V_ID()
{ | return get_ValueAsInt(COLUMNNAME_C_BPartner_Recent_V_ID);
}
@Override
public void setExternalSystem (final @Nullable java.lang.String ExternalSystem)
{
set_ValueNoCheck (COLUMNNAME_ExternalSystem, ExternalSystem);
}
@Override
public java.lang.String getExternalSystem()
{
return get_ValueAsString(COLUMNNAME_ExternalSystem);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Recent_V.java | 1 |
请完成以下Java代码 | private void throwErrorNoHUsFoundIfNeeded(final IQuery<I_M_HU> query) throws HUException
{
if (!_errorIfNoHUs)
{
return;
}
String message;
if (!Check.isEmpty(_errorIfNoHUs_ADMessage))
{
message = "@" + _errorIfNoHUs_ADMessage + "@";
}
else
{
message = "@NotFound@ @M_HU_ID@";
}
// Add detailed info
if (Services.get(IDeveloperModeBL.class).isEnabled())
{
message += "\n\nQuery: " + query;
}
throw new HUException(message);
}
@Override
public HUQueryBuilder addOnlyHUValue(@NonNull final String huValue)
{
final HuId huId = HuId.ofHUValue(huValue);
return addOnlyHUIds(ImmutableSet.of(huId));
}
@Override
public HUQueryBuilder addOnlyHUIds(@Nullable final Collection<HuId> onlyHUIds)
{
if (onlyHUIds == null || onlyHUIds.isEmpty())
{
return this;
}
if (_onlyHUIds == null)
{
_onlyHUIds = new HashSet<>();
}
_onlyHUIds.addAll(onlyHUIds);
return this;
}
@Override
public HUQueryBuilder addHUIdsToExclude(final Collection<HuId> huIdsToExclude)
{
if (huIdsToExclude == null || huIdsToExclude.isEmpty())
{
return this;
}
this._huIdsToExclude.addAll(huIdsToExclude);
this._huIdsToAlwaysInclude.removeAll(huIdsToExclude);
return this;
}
@Override
public HUQueryBuilder addHUIdsToAlwaysInclude(final Collection<HuId> huIdsToAlwaysInclude)
{
if (huIdsToAlwaysInclude == null || huIdsToAlwaysInclude.isEmpty())
{
return this;
}
this._huIdsToAlwaysInclude.addAll(huIdsToAlwaysInclude);
this._huIdsToExclude.removeAll(huIdsToAlwaysInclude);
return this; | }
@Override
public HUQueryBuilder addPIVersionToInclude(@NonNull final HuPackingInstructionsVersionId huPIVersionId)
{
_huPIVersionIdsToInclude.add(huPIVersionId);
return this;
}
private Set<HuPackingInstructionsVersionId> getPIVersionIdsToInclude()
{
return _huPIVersionIdsToInclude;
}
@Override
public HUQueryBuilder setExcludeAfterPickingLocator(final boolean excludeAfterPickingLocator)
{
locators.setExcludeAfterPickingLocator(excludeAfterPickingLocator);
return this;
}
@Override
public HUQueryBuilder setIncludeAfterPickingLocator(final boolean includeAfterPickingLocator)
{
locators.setIncludeAfterPickingLocator(includeAfterPickingLocator);
return this;
}
@Override
public HUQueryBuilder setExcludeHUsOnPickingSlot(final boolean excludeHUsOnPickingSlot)
{
_excludeHUsOnPickingSlot = excludeHUsOnPickingSlot;
return this;
}
@Override
public IHUQueryBuilder setExcludeReservedToOtherThan(@Nullable final HUReservationDocRef documentRef)
{
_excludeReservedToOtherThanRef = documentRef;
return this;
}
@Override
public IHUQueryBuilder setExcludeReserved()
{
_excludeReserved = true;
return this;
}
@Override
public IHUQueryBuilder setIgnoreHUsScheduledInDDOrder(final boolean ignoreHUsScheduledInDDOrder)
{
this.ignoreHUsScheduledInDDOrder = ignoreHUsScheduledInDDOrder;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUQueryBuilder.java | 1 |
请完成以下Java代码 | public int compareTo(@NonNull final ContextPath other)
{
return toJson().compareTo(other.toJson());
}
}
@Value
class ContextPathElement
{
@NonNull String name;
int id;
@JsonCreator
public static ContextPathElement ofJson(@NonNull final String json)
{
try
{
final int idx = json.indexOf("/");
if (idx > 0)
{
String name = json.substring(0, idx);
int id = Integer.parseInt(json.substring(idx + 1));
return new ContextPathElement(name, id); | }
else
{
return new ContextPathElement(json, -1);
}
}
catch (final Exception ex)
{
throw new AdempiereException("Failed parsing: " + json, ex);
}
}
public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);}
public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return id > 0 ? name + "/" + id : name;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@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 Gültig ab. | @param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_BPartner_Allotment.java | 1 |
请完成以下Java代码 | public class GetRenderedStartFormCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
protected String formEngineName;
private static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER;
public GetRenderedStartFormCmd(String processDefinitionId, String formEngineName) {
this.processDefinitionId = processDefinitionId;
this.formEngineName = formEngineName;
}
public Object execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache();
ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
ensureNotNull("Process Definition '" + processDefinitionId + "' not found", "processDefinition", processDefinition);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkReadProcessDefinition(processDefinition);
} | StartFormHandler startFormHandler = processDefinition.getStartFormHandler();
if (startFormHandler == null) {
return null;
}
FormEngine formEngine = Context
.getProcessEngineConfiguration()
.getFormEngines()
.get(formEngineName);
ensureNotNull("No formEngine '" + formEngineName + "' defined process engine configuration", "formEngine", formEngine);
StartFormData startForm = startFormHandler.createStartFormData(processDefinition);
Object renderedStartForm = null;
try {
renderedStartForm = formEngine.renderStartForm(startForm);
} catch (ScriptEvaluationException e) {
LOG.exceptionWhenStartFormScriptEvaluation(processDefinitionId, e);
}
return renderedStartForm;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetRenderedStartFormCmd.java | 1 |
请完成以下Java代码 | public final void setParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
if (parametersConverter instanceof DefaultOAuth2TokenRequestParametersConverter) {
this.parametersConverter = parametersConverter;
}
else {
Converter<T, MultiValueMap<String, String>> defaultParametersConverter = new DefaultOAuth2TokenRequestParametersConverter<>();
this.parametersConverter = (authorizationGrantRequest) -> {
MultiValueMap<String, String> parameters = defaultParametersConverter
.convert(authorizationGrantRequest);
MultiValueMap<String, String> parametersToSet = parametersConverter.convert(authorizationGrantRequest);
if (parametersToSet != null) {
parameters.putAll(parametersToSet);
}
return parameters;
};
}
this.requestEntityConverter = this::populateRequest;
}
/**
* Add (compose) the provided {@code parametersConverter} to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* used in the OAuth 2.0 Access Token Request body.
* @param parametersConverter the {@link Converter} to add (compose) to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to a {@link MultiValueMap}
*/ | public final void addParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
Converter<T, MultiValueMap<String, String>> currentParametersConverter = this.parametersConverter;
this.parametersConverter = (authorizationGrantRequest) -> {
MultiValueMap<String, String> parameters = currentParametersConverter.convert(authorizationGrantRequest);
if (parameters == null) {
parameters = new LinkedMultiValueMap<>();
}
MultiValueMap<String, String> parametersToAdd = parametersConverter.convert(authorizationGrantRequest);
if (parametersToAdd != null) {
parameters.addAll(parametersToAdd);
}
return parameters;
};
this.requestEntityConverter = this::populateRequest;
}
/**
* Sets the {@link Consumer} used for customizing the OAuth 2.0 Access Token
* parameters, which allows for parameters to be added, overwritten or removed.
* @param parametersCustomizer the {@link Consumer} to customize the parameters
*/
public void setParametersCustomizer(Consumer<MultiValueMap<String, String>> parametersCustomizer) {
Assert.notNull(parametersCustomizer, "parametersCustomizer cannot be null");
this.parametersCustomizer = parametersCustomizer;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\AbstractRestClientOAuth2AccessTokenResponseClient.java | 1 |
请完成以下Java代码 | public class OAuth2AuthorizationConsentAuthenticationToken extends AbstractAuthenticationToken {
@Serial
private static final long serialVersionUID = -2111287271882598208L;
private final String authorizationUri;
private final String clientId;
private final Authentication principal;
private final String state;
private final Set<String> scopes;
private final Map<String, Object> additionalParameters;
/**
* Constructs an {@code OAuth2AuthorizationConsentAuthenticationToken} using the
* provided parameters.
* @param authorizationUri the authorization URI
* @param clientId the client identifier
* @param principal the {@code Principal} (Resource Owner)
* @param state the state
* @param scopes the requested (or authorized) scope(s)
* @param additionalParameters the additional parameters
*/
public OAuth2AuthorizationConsentAuthenticationToken(String authorizationUri, String clientId,
Authentication principal, String state, @Nullable Set<String> scopes,
@Nullable Map<String, Object> additionalParameters) {
super(Collections.emptyList());
Assert.hasText(authorizationUri, "authorizationUri cannot be empty");
Assert.hasText(clientId, "clientId cannot be empty");
Assert.notNull(principal, "principal cannot be null");
Assert.hasText(state, "state cannot be empty");
this.authorizationUri = authorizationUri;
this.clientId = clientId;
this.principal = principal;
this.state = state;
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
this.additionalParameters = Collections.unmodifiableMap(
(additionalParameters != null) ? new HashMap<>(additionalParameters) : Collections.emptyMap());
setAuthenticated(true);
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return "";
}
/**
* Returns the authorization URI.
* @return the authorization URI
*/
public String getAuthorizationUri() {
return this.authorizationUri;
}
/** | * Returns the client identifier.
* @return the client identifier
*/
public String getClientId() {
return this.clientId;
}
/**
* Returns the state.
* @return the state
*/
public String getState() {
return this.state;
}
/**
* Returns the requested (or authorized) scope(s).
* @return the requested (or authorized) scope(s), or an empty {@code Set} if not
* available
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Returns the additional parameters.
* @return the additional parameters, or an empty {@code Map} if not available
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationConsentAuthenticationToken.java | 1 |
请完成以下Java代码 | public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
public HistoricDecisionInstanceQuery rootDecisionInstanceId(String rootDecisionInstanceId) {
ensureNotNull(NotValidException.class, "rootDecisionInstanceId", rootDecisionInstanceId);
this.rootDecisionInstanceId = rootDecisionInstanceId;
return this;
}
public boolean isRootDecisionInstancesOnly() {
return rootDecisionInstancesOnly;
}
public HistoricDecisionInstanceQuery rootDecisionInstancesOnly() {
this.rootDecisionInstancesOnly = true;
return this;
}
@Override
public HistoricDecisionInstanceQuery decisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionId", decisionRequirementsDefinitionId);
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
return this;
}
@Override
public HistoricDecisionInstanceQuery decisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { | ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionKey", decisionRequirementsDefinitionKey);
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
return this;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDecisionInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.spring.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource restDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public HibernateTransactionManager transactionManager() {
final HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
} | @Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
} | repos\tutorials-master\spring-core-2\src\main\java\com\baeldung\spring\config\PersistenceConfig.java | 2 |
请完成以下Java代码 | public static void main(String[] args) {
SparkSession spark = SparkSession.builder()
.appName("Row-wise Concatenation Example")
.master("local[*]")
.getOrCreate();
try {
// Create sample data
List<Person> data1 = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob")
);
List<Person> data2 = Arrays.asList(
new Person(3, "Charlie"),
new Person(4, "Diana")
);
Dataset<Row> df1 = spark.createDataFrame(data1, Person.class);
Dataset<Row> df2 = spark.createDataFrame(data2, Person.class);
logger.info("First DataFrame:");
df1.show();
logger.info("Second DataFrame:");
df2.show();
// Row-wise concatenation using reusable method
Dataset<Row> combined = concatenateDataFrames(df1, df2);
logger.info("After row-wise concatenation:");
combined.show();
} finally {
spark.stop();
}
}
/**
* Concatenates two DataFrames row-wise using unionByName.
* This method is extracted for reusability and testing. | */
public static Dataset<Row> concatenateDataFrames(Dataset<Row> df1, Dataset<Row> df2) {
return df1.unionByName(df2);
}
public static class Person implements java.io.Serializable {
private int id;
private String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
} | repos\tutorials-master\apache-spark\src\main\java\com\baeldung\spark\dataframeconcat\ConcatRowsExample.java | 1 |
请完成以下Java代码 | public static final class Builder
{
private final MenuNode node;
private int maxDepth = Integer.MAX_VALUE;
private int maxChildrenPerNode = Integer.MAX_VALUE;
private int maxLeafNodes = Integer.MAX_VALUE;
private MenuNodeFavoriteProvider menuNodeFavoriteProvider;
private Builder(final MenuNode node)
{
this.node = node;
}
@Nullable
public JSONMenuNode build()
{
final MutableInt maxLeafNodes = new MutableInt(this.maxLeafNodes);
return newInstanceOrNull(node, maxDepth, maxChildrenPerNode, maxLeafNodes, menuNodeFavoriteProvider);
}
public Builder setMaxDepth(final int maxDepth)
{
this.maxDepth = maxDepth > 0 ? maxDepth : Integer.MAX_VALUE;
return this;
}
public Builder setMaxChildrenPerNode(final int maxChildrenPerNode)
{
this.maxChildrenPerNode = maxChildrenPerNode > 0 ? maxChildrenPerNode : Integer.MAX_VALUE; | return this;
}
public Builder setMaxLeafNodes(final int maxLeafNodes)
{
this.maxLeafNodes = maxLeafNodes > 0 ? maxLeafNodes : Integer.MAX_VALUE;
return this;
}
public Builder setIsFavoriteProvider(final MenuNodeFavoriteProvider menuNodeFavoriteProvider)
{
this.menuNodeFavoriteProvider = menuNodeFavoriteProvider;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\datatypes\json\JSONMenuNode.java | 1 |
请完成以下Java代码 | @Override public void enterAssign(LabeledExprParser.AssignContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAssign(LabeledExprParser.AssignContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterBlank(LabeledExprParser.BlankContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitBlank(LabeledExprParser.BlankContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterParens(LabeledExprParser.ParensContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitParens(LabeledExprParser.ParensContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterMulDiv(LabeledExprParser.MulDivContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitMulDiv(LabeledExprParser.MulDivContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAddSub(LabeledExprParser.AddSubContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAddSub(LabeledExprParser.AddSubContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterId(LabeledExprParser.IdContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitId(LabeledExprParser.IdContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/ | @Override public void enterInt(LabeledExprParser.IntContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitInt(LabeledExprParser.IntContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { }
} | repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprBaseListener.java | 1 |
请完成以下Java代码 | public String toString() {
return "Address{" +
"province='" + province + '\'' +
", area='" + area + '\'' +
", street='" + street + '\'' +
", num='" + num + '\'' +
'}';
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getArea() {
return area;
} | public void setArea(String area) {
this.area = area;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
} | repos\spring-boot-quick-master\quick-swagger\src\main\java\com\quick\po\Address.java | 1 |
请完成以下Java代码 | public Object getValueAt(final int rowIndex, final int columnIndex)
{
final IUserQueryRestriction row = getRow(rowIndex);
if (INDEX_JOIN == columnIndex)
{
return row.getJoin();
}
else if (INDEX_COLUMNNAME == columnIndex)
{
return row.getSearchField();
}
else if (INDEX_OPERATOR == columnIndex)
{
return row.getOperator();
}
else if (INDEX_VALUE == columnIndex)
{
return row.getValue();
}
else if (INDEX_VALUE2 == columnIndex)
{
return row.getValueTo();
}
else
{
throw new IllegalArgumentException("Invalid column index: " + columnIndex);
}
}
@Override
public boolean isCellEditable(final int rowIndex, final int columnIndex)
{
final IUserQueryRestriction row = getRow(rowIndex);
if (INDEX_JOIN == columnIndex)
{
return rowIndex > 0;
}
else if (INDEX_COLUMNNAME == columnIndex)
{
return true;
}
else if (INDEX_OPERATOR == columnIndex)
{
return row.getSearchField() != null;
}
else if (INDEX_VALUE == columnIndex)
{
return row.getSearchField() != null;
}
else if (INDEX_VALUE2 == columnIndex)
{
// TODO: and operator is BETWEEN
return row.getSearchField() != null;
}
else
{
throw new IllegalArgumentException("Invalid column index: " + columnIndex);
}
}
@Override
public void setValueAt(final Object value, final int rowIndex, final int columnIndex)
{
final IUserQueryRestriction row = getRow(rowIndex);
if (INDEX_JOIN == columnIndex)
{
final Join join = (Join)value;
row.setJoin(join);
}
else if (INDEX_COLUMNNAME == columnIndex)
{
final IUserQueryField searchField = (IUserQueryField)value;
row.setSearchField(searchField);
}
else if (INDEX_OPERATOR == columnIndex)
{
final Operator operator = Operator.cast(value);
row.setOperator(operator);
}
else if (INDEX_VALUE == columnIndex)
{
row.setValue(value);
}
else if (INDEX_VALUE2 == columnIndex)
{
row.setValueTo(value);
}
else
{
throw new IllegalArgumentException("Invalid column index: " + columnIndex);
}
} | public final void clear()
{
if (rows.isEmpty())
{
return;
}
final int lastRow = rows.size() - 1;
rows.clear();
fireTableRowsDeleted(0, lastRow);
}
public void setRows(final List<IUserQueryRestriction> rowsToSet)
{
rows.clear();
if (rowsToSet != null)
{
rows.addAll(rowsToSet);
}
fireTableDataChanged();
}
public List<IUserQueryRestriction> getRows()
{
return new ArrayList<>(rows);
}
private final void addRow(final IUserQueryRestriction rowToAdd)
{
rows.add(rowToAdd);
final int rowIndex = rows.size() - 1;
fireTableRowsInserted(rowIndex, rowIndex);
}
public IUserQueryRestriction newRow()
{
final IUserQueryRestriction row = IUserQueryRestriction.newInstance();
addRow(row);
return row;
}
public void removeRow(final int rowIndex)
{
rows.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindAdvancedSearchTableModel.java | 1 |
请完成以下Java代码 | private CurrencyCode getCurrencyCode(final PriceListVersionId priceListVersionId)
{
return currencyCodesByPriceListVersionId.computeIfAbsent(priceListVersionId, this::retrieveCurrencyCode);
}
private CurrencyCode retrieveCurrencyCode(final PriceListVersionId priceListVersionId)
{
final I_M_PriceList priceList = priceListsRepo.getPriceListByPriceListVersionId(priceListVersionId);
final CurrencyId currencyId = CurrencyId.ofRepoId(priceList.getC_Currency_ID());
return currenciesRepo.getCurrencyCodeById(currencyId);
}
private List<ProductsProposalRow> updateLastShipmentDays(final List<ProductsProposalRow> rows)
{
final Set<ProductId> productIds = rows.stream().map(ProductsProposalRow::getProductId).collect(ImmutableSet.toImmutableSet());
if (productIds.isEmpty())
{
return rows;
}
final Map<ProductId, BPartnerProductStats> statsByProductId = bpartnerProductStatsService.getByPartnerAndProducts(bpartnerId, productIds);
return rows.stream()
.map(row -> updateRowFromStats(row, statsByProductId.get(row.getProductId())))
.collect(ImmutableList.toImmutableList());
}
private ProductsProposalRow updateRowFromStats(
@NonNull final ProductsProposalRow row,
@Nullable final BPartnerProductStats stats)
{ | final Integer lastShipmentOrReceiptInDays = calculateLastShipmentOrReceiptInDays(stats);
return row.withLastShipmentDays(lastShipmentOrReceiptInDays);
}
@Nullable
private Integer calculateLastShipmentOrReceiptInDays(@Nullable final BPartnerProductStats stats)
{
if (stats == null)
{
return null;
}
else if (soTrx.isSales())
{
return stats.getLastShipmentInDays();
}
else
{
return stats.getLastReceiptInDays();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowsLoader.java | 1 |
请完成以下Java代码 | public String getTableNameOrNull(final DocumentId documentId)
{
return null;
}
@Override
public DocumentFilterList getFilters()
{
return filters;
}
@Override
public DocumentQueryOrderByList getDefaultOrderBys()
{
return DocumentQueryOrderByList.ofList(
ImmutableList.of(
DocumentQueryOrderBy.byFieldName(I_MD_Cockpit.COLUMNNAME_QtyStockEstimateSeqNo_AtDate),
DocumentQueryOrderBy.byFieldName(I_MD_Cockpit.COLUMNNAME_ProductValue))
);
}
@Override
protected boolean isEligibleInvalidateEvent(final TableRecordReference recordRef)
{ | final String tableName = recordRef.getTableName();
return I_MD_Cockpit.Table_Name.equals(tableName)
|| I_MD_Stock.Table_Name.equals(tableName);
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return relatedProcessDescriptors;
}
@Override
public ViewActionDescriptorsList getActions()
{
return ViewActionDescriptorsFactory.instance
.getFromClass(MD_Cockpit_DocumentDetail_Display.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitView.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_ChatType[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_Table getAD_Table() throws RuntimeException
{
return (I_AD_Table)MTable.get(getCtx(), I_AD_Table.Table_Name)
.getPO(getAD_Table_ID(), get_TrxName()); }
/** Set Table.
@param AD_Table_ID
Database Table information
*/
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Chat Type.
@param CM_ChatType_ID
Type of discussion / chat
*/
public void setCM_ChatType_ID (int CM_ChatType_ID)
{
if (CM_ChatType_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID));
}
/** Get Chat Type.
@return Type of discussion / chat
*/
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** ModerationType AD_Reference_ID=395 */
public static final int MODERATIONTYPE_AD_Reference_ID=395;
/** Not moderated = N */
public static final String MODERATIONTYPE_NotModerated = "N"; | /** Before Publishing = B */
public static final String MODERATIONTYPE_BeforePublishing = "B";
/** After Publishing = A */
public static final String MODERATIONTYPE_AfterPublishing = "A";
/** Set Moderation Type.
@param ModerationType
Type of moderation
*/
public void setModerationType (String ModerationType)
{
set_Value (COLUMNNAME_ModerationType, ModerationType);
}
/** Get Moderation Type.
@return Type of moderation
*/
public String getModerationType ()
{
return (String)get_Value(COLUMNNAME_ModerationType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatType.java | 1 |
请完成以下Java代码 | protected String getVariableLocalName(InjectionPoint ip) {
String variableName = ip.getAnnotated().getAnnotation(ProcessVariableLocal.class).value();
if (variableName.length() == 0) {
variableName = ip.getMember().getName();
}
return variableName;
}
protected String getVariableLocalTypedName(InjectionPoint ip) {
String variableName = ip.getAnnotated().getAnnotation(ProcessVariableLocalTyped.class).value();
if (variableName.length() == 0) {
variableName = ip.getMember().getName();
}
return variableName;
}
@Produces
@ProcessVariableLocal
protected Object getProcessVariableLocal(InjectionPoint ip) {
String processVariableName = getVariableLocalName(ip);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Getting local process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "].");
}
return businessProcess.getVariableLocal(processVariableName);
}
/**
* @since 7.3
*/
@Produces
@ProcessVariableLocalTyped
protected TypedValue getProcessVariableLocalTyped(InjectionPoint ip) { | String processVariableName = getVariableLocalTypedName(ip);
if (logger.isLoggable(Level.FINE)) {
logger.fine("Getting local typed process variable '" + processVariableName + "' from ProcessInstance[" + businessProcess.getProcessInstanceId() + "].");
}
return businessProcess.getVariableLocalTyped(processVariableName);
}
@Produces
@Named
protected Map<String, Object> processVariablesLocal() {
return processVariableLocalMap;
}
/**
* @since 7.3
*/
@Produces
@Named
protected VariableMap processVariableMapLocal() {
return processVariableLocalMap;
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\ProcessVariables.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer("MTax[")
.append(get_ID())
.append(", Name = ").append(getName())
.append(", SO/PO=").append(getSOPOType())
.append(", Rate=").append(getRate())
.append(", C_TaxCategory_ID=").append(getC_TaxCategory_ID())
.append(", Summary=").append(isSummary())
.append(", Parent=").append(getParent_Tax_ID())
.append(", Country=").append(getC_Country_ID()).append("|").append(getTo_Country_ID())
.append(", Region=").append(getC_Region_ID()).append("|").append(getTo_Region_ID())
.append("]");
return sb.toString();
} // toString
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord && success) | insert_Accounting("C_Tax_Acct", "C_AcctSchema_Default", null);
return success;
} // afterSave
/**
* Before Delete
* @return true
*/
@Override
protected boolean beforeDelete ()
{
return delete_Accounting("C_Tax_Acct");
} // beforeDelete
} // MTax | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTax.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LocationCreateReq extends AbsReq {
/** 详细地址 */
private String location;
/** 收货人姓名 */
private String name;
/** 收货人手机号 */
private String phone;
/** 邮编 */
private String postCode;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) { | this.phone = phone;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
@Override
public String toString() {
return "LocationCreateReq{" +
"location='" + location + '\'' +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
", postCode='" + postCode + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\LocationCreateReq.java | 2 |
请完成以下Java代码 | public Object percentageOfAmount(final PercentageCostCalculationMethodParams params)
{
record.setCostCalculation_Percentage(params.getPercentage().toBigDecimal());
return null;
}
});
record.setCostDistributionMethod(from.getDistributionMethod().getCode());
record.setC_Currency_ID(from.getCostAmount().getCurrencyId().getRepoId());
record.setCostAmount(from.getCostAmount().toBigDecimal());
record.setCreated_OrderLine_ID(OrderLineId.toRepoId(from.getCreatedOrderLineId()));
}
private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetail from)
{
record.setIsActive(true);
updateRecord(record, from.getOrderLineInfo());
record.setCostAmount(from.getCostAmount().toBigDecimal());
record.setQtyReceived(from.getInoutQty().toBigDecimal());
record.setCostAmountReceived(from.getInoutCostAmount().toBigDecimal());
}
private static void updateRecord(final I_C_Order_Cost_Detail record, final OrderCostDetailOrderLinePart from)
{
record.setC_OrderLine_ID(from.getOrderLineId().getRepoId());
record.setM_Product_ID(from.getProductId().getRepoId());
record.setC_UOM_ID(from.getUomId().getRepoId());
record.setQtyOrdered(from.getQtyOrdered().toBigDecimal()); | record.setC_Currency_ID(from.getCurrencyId().getRepoId());
record.setLineNetAmt(from.getOrderLineNetAmt().toBigDecimal());
}
public void changeByOrderLineId(
@NonNull final OrderLineId orderLineId,
@NonNull Consumer<OrderCost> consumer)
{
final List<OrderCost> orderCosts = getByOrderLineIds(ImmutableSet.of(orderLineId));
orderCosts.forEach(orderCost -> {
consumer.accept(orderCost);
saveUsingCache(orderCost);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostRepositorySession.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyCUsPerTU()
{
return ediDesadvPackItems.stream()
.map(EDIDesadvPackItem::getQtyCUsPerTU)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@NonNull
public BigDecimal getQtyCUsPerLU()
{
return ediDesadvPackItems.stream()
.map(EDIDesadvPackItem::getQtyCUsPerLU)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
@Value
@Builder
public static class EDIDesadvPackItem
{
@NonNull
EDIDesadvPackItemId ediDesadvPackItemId;
@NonNull
EDIDesadvPackId ediDesadvPackId;
@NonNull
EDIDesadvLineId ediDesadvLineId;
int line;
@NonNull
BigDecimal movementQty;
@Nullable
InOutId inOutId; | @Nullable
InOutLineId inOutLineId;
@Nullable
BigDecimal qtyItemCapacity;
@Nullable
Integer qtyTu;
@Nullable
BigDecimal qtyCUsPerTU;
@Nullable
BigDecimal qtyCUPerTUinInvoiceUOM;
@Nullable
BigDecimal qtyCUsPerLU;
@Nullable
BigDecimal qtyCUsPerLUinInvoiceUOM;
@Nullable
Timestamp bestBeforeDate;
@Nullable
String lotNumber;
@Nullable
PackagingCodeId huPackagingCodeTuId;
@Nullable
String gtinTuPackingMaterial;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\pack\EDIDesadvPack.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void removeDeptRoleUser(List<String> userIds, String depId) {
for(String userId : userIds){
List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(new QueryWrapper<SysDepartRole>().eq("depart_id",depId));
List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
if(roleIds != null && roleIds.size()>0){
QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
query.eq("user_id",userId).in("drole_id",roleIds);
this.remove(query);
}
}
}
/**
* 从diff中找出main中没有的元素
* @param main
* @param diff
* @return
*/
private List<String> getDiff(String main, String diff){
if(oConvertUtils.isEmpty(diff)) {
return null;
}
if(oConvertUtils.isEmpty(main)) { | return Arrays.asList(diff.split(","));
}
String[] mainArr = main.split(",");
String[] diffArr = diff.split(",");
Map<String, Integer> map = new HashMap(5);
for (String string : mainArr) {
map.put(string, 1);
}
List<String> res = new ArrayList<String>();
for (String key : diffArr) {
if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
res.add(key);
}
}
return res;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDepartRoleUserServiceImpl.java | 2 |
请完成以下Java代码 | public static int compute(char[] str1, char[] str2)
{
int substringLength1 = str1.length;
int substringLength2 = str2.length;
// 构造二维数组记录子问题A[i]和B[j]的LCS的长度
int[][] opt = new int[substringLength1 + 1][substringLength2 + 1];
// 从后向前,动态规划计算所有子问题。也可从前到后。
for (int i = substringLength1 - 1; i >= 0; i--)
{
for (int j = substringLength2 - 1; j >= 0; j--)
{
if (str1[i] == str2[j])
opt[i][j] = opt[i + 1][j + 1] + 1;// 状态转移方程
else
opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]);// 状态转移方程
}
}
// System.out.println("substring1:" + new String(str1));
// System.out.println("substring2:" + new String(str2));
// System.out.print("LCS:");
// int i = 0, j = 0;
// while (i < substringLength1 && j < substringLength2)
// {
// if (str1[i] == str2[j])
// {
// System.out.print(str1[i]); | // i++;
// j++;
// }
// else if (opt[i + 1][j] >= opt[i][j + 1])
// i++;
// else
// j++;
// }
// System.out.println();
return opt[0][0];
}
public static int compute(String str1, String str2)
{
return compute(str1.toCharArray(), str2.toCharArray());
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\LongestCommonSubsequence.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
@Override
public void setImportErrorMsg (final @Nullable java.lang.String ImportErrorMsg)
{
set_Value (COLUMNNAME_ImportErrorMsg, ImportErrorMsg);
} | @Override
public java.lang.String getImportErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ImportErrorMsg);
}
@Override
public void setJSONValue (final @Nullable java.lang.String JSONValue)
{
set_Value (COLUMNNAME_JSONValue, JSONValue);
}
@Override
public java.lang.String getJSONValue()
{
return get_ValueAsString(COLUMNNAME_JSONValue);
}
@Override
public void setS_FailedTimeBooking_ID (final int S_FailedTimeBooking_ID)
{
if (S_FailedTimeBooking_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, S_FailedTimeBooking_ID);
}
@Override
public int getS_FailedTimeBooking_ID()
{
return get_ValueAsInt(COLUMNNAME_S_FailedTimeBooking_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_FailedTimeBooking.java | 2 |
请完成以下Java代码 | public SqlLookupDescriptorProviderBuilder setCtxColumnName(@Nullable final String columnName)
{
this.ctxColumnName = columnName;
return this;
}
public SqlLookupDescriptorProviderBuilder setCtxTableName(@Nullable final String tableName)
{
this.ctxTableName = tableName;
return this;
}
public SqlLookupDescriptorProviderBuilder setDisplayType(final int displayType) {return setDisplayType(ReferenceId.ofRepoId(displayType));}
public SqlLookupDescriptorProviderBuilder setDisplayType(final ReferenceId displayType)
{
this.displayType = displayType;
return this;
}
public SqlLookupDescriptorProviderBuilder setWidgetType(final DocumentFieldWidgetType widgetType)
{
this.widgetType = widgetType;
return this;
}
public SqlLookupDescriptorProviderBuilder setAD_Reference_Value_ID(final ReferenceId AD_Reference_Value_ID)
{
this.AD_Reference_Value_ID = AD_Reference_Value_ID;
return this;
}
public SqlLookupDescriptorProviderBuilder setAD_Val_Rule_ID(@Nullable final AdValRuleId AD_Val_Rule_ID)
{ | return setAD_Val_Rule_ID(LookupDescriptorProvider.LookupScope.DocumentField, AD_Val_Rule_ID);
}
public SqlLookupDescriptorProviderBuilder setAD_Val_Rule_ID(@NonNull final LookupDescriptorProvider.LookupScope scope, @Nullable final AdValRuleId AD_Val_Rule_ID)
{
if (AD_Val_Rule_ID == null)
{
adValRuleIdByScope.remove(scope);
}
else
{
adValRuleIdByScope.put(scope, AD_Val_Rule_ID);
}
return this;
}
public SqlLookupDescriptorProviderBuilder addValidationRule(final IValidationRule validationRule)
{
additionalValidationRules.add(validationRule);
return this;
}
public SqlLookupDescriptorProviderBuilder setReadOnlyAccess()
{
this.requiredAccess = Access.READ;
return this;
}
public SqlLookupDescriptorProviderBuilder setPageLength(final Integer pageLength)
{
this.pageLength = pageLength;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorProviderBuilder.java | 1 |
请完成以下Java代码 | public void updateHandOverAddress(final I_C_Order order)
{
documentLocationBL.updateRenderedAddressAndCapturedLocation(OrderDocumentLocationAdapterFactory.handOverLocationAdapter(order));
}
@CalloutMethod(columnNames = I_C_Order.COLUMNNAME_HandOver_User_ID, skipIfCopying = true)
public void updateHandOverUserRenderedAddress(final I_C_Order order)
{
documentLocationBL.updateRenderedAddress(OrderDocumentLocationAdapterFactory.handOverLocationAdapter(order));
}
@CalloutMethod(columnNames = { I_C_Order.COLUMNNAME_C_BPartner_Location_ID, I_C_Order.COLUMNNAME_AD_User_ID })
public void setContactDetails(final I_C_Order order)
{
if (order.getC_BPartner_Location_ID() <= 0)
{
return;
}
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(order.getC_BPartner_ID(), order.getC_BPartner_Location_ID());
final I_C_BPartner_Location bPartnerLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(bPartnerLocationId);
Check.assumeNotNull(bPartnerLocationRecord, "C_BPartner_Location cannot be missing for webui selection! Id: {}", bPartnerLocationId);
final Optional<I_AD_User> userRecord = Optional.ofNullable(UserId.ofRepoIdOrNull(order.getAD_User_ID()))
.map(userDAO::getById);
if (userRecord.isPresent())
{
final I_AD_User user = userRecord.get();
order.setBPartnerName(firstNotBlank(user.getName(), bPartnerLocationRecord.getBPartnerName()));
order.setEMail(firstNotBlank(user.getEMail(), bPartnerLocationRecord.getEMail()));
order.setPhone(firstNotBlank(user.getPhone(), bPartnerLocationRecord.getPhone()));
}
else
{
order.setBPartnerName(bPartnerLocationRecord.getBPartnerName()); | order.setEMail(bPartnerLocationRecord.getEMail());
order.setPhone(bPartnerLocationRecord.getPhone());
}
}
@CalloutMethod(columnNames = {
I_C_Order.COLUMNNAME_M_Shipper_ID },
skipIfCopying = true)
public void updateDeliveryViaRule(final I_C_Order order)
{
final ShipperId shipperId = ShipperId.ofRepoIdOrNull(order.getM_Shipper_ID());
if (shipperId != null)
{
order.setDeliveryViaRule(X_C_Order.DELIVERYVIARULE_Shipper);
}
else
{
order.setDeliveryViaRule(X_C_Order.DELIVERYVIARULE_Pickup);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\callout\C_Order.java | 1 |
请完成以下Java代码 | public Builder setUser(final I_AD_User user)
{
setAttribute(VAR_AD_User, user);
setAttribute(VAR_AD_User_ID, user != null ? user.getAD_User_ID() : null);
return this;
}
public void setCCUser(final I_AD_User ccUser)
{
setAttribute(VAR_CC_User, ccUser);
setAttribute(VAR_CC_User_ID, ccUser != null ? ccUser.getAD_User_ID() : null);
}
public Builder setEmail(final String email)
{
setAttribute(VAR_EMail, email);
return this;
}
public Builder setCCEmail(final String ccEmail)
{
setAttribute(VAR_CC_EMail, ccEmail);
return this;
}
public Builder setAD_Org_ID(final int adOrgId)
{
setAttribute(VAR_AD_Org_ID, adOrgId);
return this;
}
public Builder setCustomAttribute(final String attributeName, final Object value)
{
setAttribute(attributeName, value);
return this;
}
}
}
public interface SourceDocument
{
String NAME = "__SourceDocument";
default int getWindowNo()
{
return Env.WINDOW_None;
}
boolean hasFieldValue(String fieldName);
Object getFieldValue(String fieldName);
default int getFieldValueAsInt(final String fieldName, final int defaultValue)
{
final Object value = getFieldValue(fieldName);
return value != null ? (int)value : defaultValue;
}
@Nullable
default <T extends RepoIdAware> T getFieldValueAsRepoId(final String fieldName, final Function<Integer, T> idMapper)
{
final int id = getFieldValueAsInt(fieldName, -1);
if (id > 0)
{
return idMapper.apply(id);
}
else
{
return null;
} | }
static SourceDocument toSourceDocumentOrNull(final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof SourceDocument)
{
return (SourceDocument)obj;
}
final PO po = getPO(obj);
return new POSourceDocument(po);
}
}
@AllArgsConstructor
private static final class POSourceDocument implements SourceDocument
{
@NonNull
private final PO po;
@Override
public boolean hasFieldValue(final String fieldName)
{
return po.get_ColumnIndex(fieldName) >= 0;
}
@Override
public Object getFieldValue(final String fieldName)
{
return po.get_Value(fieldName);
}
}
@AllArgsConstructor
private static final class GridTabSourceDocument implements SourceDocument
{
@NonNull
private final GridTab gridTab;
@Override
public boolean hasFieldValue(final String fieldName)
{
return gridTab.getField(fieldName) != null;
}
@Override
public Object getFieldValue(final String fieldName)
{
return gridTab.getValue(fieldName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java | 1 |
请完成以下Java代码 | static boolean saveDat()
{
return trie.save(path + Predefine.TRIE_EXT);
}
static boolean loadDat()
{
return trie.load(path + Predefine.TRIE_EXT);
}
/**
* 是否包含key
* @param key
* @return
*/
public static boolean containsKey(String key)
{ | return trie.containsKey(key);
}
/**
* 时报包含key,且key至少长length
* @param key
* @param length
* @return
*/
public static boolean containsKey(String key, int length)
{
if (!trie.containsKey(key)) return false;
return key.length() >= length;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\nr\TranslatedPersonDictionary.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
if (e.getSource() == mDelete)
{
m_value = null; // create new
}
//
final VLocationDialog ld = new VLocationDialog(SwingUtils.getFrame(this), Services.get(IMsgBL.class).getMsg(Env.getCtx(), "Location"), m_value);
ld.setVisible(true);
Object oldValue = getValue();
m_value = ld.getValue();
//
if (e.getSource() == mDelete)
;
else if (!ld.isChanged())
return;
// Data Binding
try
{
int C_Location_ID = 0;
if (m_value != null)
C_Location_ID = m_value.getC_Location_ID();
Integer ii = new Integer(C_Location_ID);
if (C_Location_ID > 0)
fireVetoableChange(m_columnName, oldValue, ii);
setValue(ii);
if (ii.equals(oldValue) && m_GridTab != null && m_GridField != null)
{
// force Change - user does not realize that embedded object is already saved.
m_GridTab.processFieldChange(m_GridField);
}
}
catch (PropertyVetoException pve)
{
log.error("VLocation.actionPerformed", pve);
}
} // actionPerformed
/**
* Action Listener Interface
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
m_text.addActionListener(listener);
} // addActionListener
@Override
public synchronized void addMouseListener(MouseListener l)
{
m_text.addMouseListener(l); | }
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField Model Field
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_GridField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField()
{
return m_GridField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VLocation | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLocation.java | 1 |
请完成以下Java代码 | public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
/**
* Does nothing, the code is commented out. See the javadoc of {@link #modelChange(PO, int)}.
*/
@Override
public void initialize(ModelValidationEngine engine, MClient client)
{
if (client != null)
m_AD_Client_ID = client.getAD_Client_ID();
//
// @formatter:off
// final Map<String, List<MIndexTable>> indexes = MIndexTable.getAllByTable(Env.getCtx(), true);
// for (Entry<String, List<MIndexTable>> e : indexes.entrySet())
// {
// String tableName = e.getKey();
// engine.addModelChange(tableName, this);
// }
// @formatter:on
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
return null;
}
/**
* Does nothing, the code is commented out for the time being. Probably the whole class will be removed.<br>
* Don't use this stuff. We have a physical DB-index, and if a DBUniqueConstraintException is thrown anywhere in ADempiere, the exception code will identify the MIndexTable (if any) and get its
* errorMsg (if any).
*/
@Override
public String modelChange(PO po, int type) throws Exception
{
// @formatter:off
// if (type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE)
// {
// final List<MIndexTable> indexes = MIndexTable.getAllByTable(po.getCtx(), false).get(po.get_TableName()); | // if (indexes != null)
// {
// final Properties ctx = po.getCtx();
// final String trxName = po.get_TrxName();
// final String poWhereClause = po.get_WhereClause(true);
//
// for (final MIndexTable index : indexes)
// {
// // Skip inactive indexes
// if (!index.isActive())
// {
// continue;
// }
//
// // Only UNIQUE indexes need to be validated
// if (!index.isUnique())
// {
// continue;
// }
//
// if (!index.isWhereClauseMatched(ctx, poWhereClause, trxName))
// {
// // there is no need to go with further validation since our PO is not subject of current index
// continue;
// }
//
// index.validateData(po, trxName);
// }
// }
// }
// @formatter:on
return null;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexValidator.java | 1 |
请完成以下Java代码 | public int getDerKurier_DeliveryOrderLine_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DerKurier_DeliveryOrderLine_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Package getM_Package() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(org.compiere.model.I_M_Package M_Package)
{
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
/** Set Packstück.
@param M_Package_ID
Shipment Package
*/
@Override
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1) | set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get Packstück.
@return Shipment Package
*/
@Override
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine_Package.java | 1 |
请完成以下Java代码 | public I_C_BP_BankAccount createNewC_BP_BankAccount(final IContextAware contextProvider, final int bpartnerId)
{
final PaymentString paymentString = getPaymentString();
final I_C_BP_BankAccount bpBankAccount = InterfaceWrapperHelper.newInstance(I_C_BP_BankAccount.class, contextProvider);
Check.assume(bpartnerId > 0, "We assume the bPartnerId to be greater than 0. This={}", this);
bpBankAccount.setC_BPartner_ID(bpartnerId);
// bpBankAccount.setC_Bank_ID(C_Bank_ID); // introduce a standard ESR-Dummy-Bank, or leave it empty
final Currency currency = Services.get(ICurrencyDAO.class).getByCurrencyCode(CurrencyCode.CHF); // CHF, because it's ESR
bpBankAccount.setC_Currency_ID(currency.getId().getRepoId());
bpBankAccount.setIsEsrAccount(true); // ..because we are creating this from an ESR string
bpBankAccount.setIsACH(true);
final String bPartnerName = Services.get(IBPartnerDAO.class).getBPartnerNameById(BPartnerId.ofRepoId(bpartnerId)); | bpBankAccount.setA_Name(bPartnerName);
bpBankAccount.setName(bPartnerName);
bpBankAccount.setAccountNo(paymentString.getInnerAccountNo());
bpBankAccount.setESR_RenderedAccountNo(paymentString.getPostAccountNo());
InterfaceWrapperHelper.save(bpBankAccount);
return bpBankAccount;
}
@Override
public String toString()
{
return String.format("ESRPaymentStringDataProvider [getPaymentString()=%s]", getPaymentString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\api\impl\ESRPaymentStringDataProvider.java | 1 |
请完成以下Java代码 | public Optional<AsyncBatchId> getAsyncBatchId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return Optional.ofNullable(AsyncBatchId.ofRepoIdOrNull(shipmentSchedule.getC_Async_Batch_ID()));
}
@Nullable
public ShipperId getShipperId(@Nullable final String shipperInternalName)
{
if (Check.isBlank(shipperInternalName))
{
return null;
}
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null
? ShipperId.ofRepoId(shipper.getM_Shipper_ID())
: null;
}
@Nullable
public String getTrackingURL(@NonNull final String shipperInternalName)
{
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null
? shipper.getTrackingURL()
: null;
}
@Nullable
private I_M_Shipper loadShipper(@NonNull final String shipperInternalName)
{
return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName);
}
public ProductId getProductId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()); | }
public ProductId getProductId(@NonNull final String productSearchKey, @NonNull final OrgId orgId)
{
final ProductQuery query = ProductQuery.builder()
.value(productSearchKey)
.orgId(orgId)
.includeAnyOrg(true) // include articles with org=*
.build();
return productIdsByQuery.computeIfAbsent(query, this::retrieveProductIdByQuery);
}
private ProductId retrieveProductIdByQuery(@NonNull final ProductQuery query)
{
final ProductId productId = productDAO.retrieveProductIdBy(query);
if (productId == null)
{
throw new AdempiereException("No product found for " + query);
}
return productId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShippingInfoCache.java | 1 |
请完成以下Java代码 | public String labelOf(int id)
{
return idToLabelMap[id];
}
public int build(TreeMap<String, Integer> keyValueMap)
{
idToLabelMap = new String[keyValueMap.size()];
for (Map.Entry<String, Integer> entry : keyValueMap.entrySet())
{
idToLabelMap[entry.getValue()] = entry.getKey();
}
return trie.build(keyValueMap);
}
/**
* label转id
* @param label
* @return
*/
public Integer idOf(char[] label)
{
return trie.get(label);
}
/**
* label转id
* @param label
* @return
*/
public Integer idOf(String label)
{
return trie.get(label);
}
/**
* 字母表大小
* @return
*/
public int size()
{
return trie.size(); | }
public void save(DataOutputStream out) throws Exception
{
out.writeInt(idToLabelMap.length);
for (String value : idToLabelMap)
{
TextUtility.writeString(value, out);
}
}
public boolean load(ByteArray byteArray)
{
idToLabelMap = new String[byteArray.nextInt()];
TreeMap<String, Integer> map = new TreeMap<String, Integer>();
for (int i = 0; i < idToLabelMap.length; i++)
{
idToLabelMap[i] = byteArray.nextString();
map.put(idToLabelMap[i], i);
}
return trie.build(map) == 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\Alphabet.java | 1 |
请完成以下Java代码 | protected String doIt()
{
final ClonePlan plan = getPlan(null).get();
final PO rowPO = plan.getRowPO();
final String rowTableName = rowPO.get_TableName();
CopyRecordFactory.getCopyRecordSupport(rowTableName)
.setAdWindowId(plan.getAdWindowId())
.setParentLink(plan.getHeaderPO(), plan.getRowPO_LinkColumnName())
.copyToNew(rowPO);
return MSG_OK;
}
private ExplainedOptional<ClonePlan> getPlan(final @Nullable IProcessPreconditionsContext preconditionsContext)
{
final Set<TableRecordReference> selectedRowRefs;
if (preconditionsContext != null)
{
if (preconditionsContext.getAdTabId() == null)
{
return ExplainedOptional.emptyBecause("No row(s) from a tab selected.");
}
selectedRowRefs = preconditionsContext.getSelectedIncludedRecords();
}
else
{
selectedRowRefs = getProcessInfo().getSelectedIncludedRecords();
}
if (selectedRowRefs.size() != 1)
{
return ExplainedOptional.emptyBecause("More or less than one row selected.");
}
final TableRecordReference rowRef = CollectionUtils.singleElement(selectedRowRefs);
if (!CopyRecordFactory.isEnabledForTableName(rowRef.getTableName()))
{
return ExplainedOptional.emptyBecause("CopyRecordFactory not enabled for the table the row belongs to.");
} | // we have e.g. in the C_BPartner-window two subtabs ("Customer" and "Vendor") that show a different view on the same C_BPartner record.
// There, cloning the subtab-line makes no sense
if (Objects.equals(getProcessInfo().getTableNameOrNull(), rowRef.getTableName()))
{
return ExplainedOptional.emptyBecause("The main-window has the same Record as the sub-tab, there can only be one line.");
}
final TableRecordReference headerRef = TableRecordReference.of(getTable_ID(), getRecord_ID());
final PO headerPO = headerRef.getModel(PlainContextAware.newWithThreadInheritedTrx(), PO.class);
final String headerPO_KeyColumName = headerPO.getPOInfo().getKeyColumnName();
if (headerPO_KeyColumName == null)
{
throw new AdempiereException("A document header which does not have a single primary key is not supported");
}
final PO rowPO = rowRef.getModel(PlainContextAware.newWithThreadInheritedTrx(), PO.class);
if (!rowPO.getPOInfo().hasColumnName(headerPO_KeyColumName))
{
throw new AdempiereException("Row which does not link to it's header via header's primary key is not supported");
}
return ExplainedOptional.of(
ClonePlan.builder()
.rowPO(rowPO)
.rowPO_LinkColumnName(headerPO_KeyColumName)
.headerPO(headerPO)
.adWindowId(getProcessInfo().getAdWindowId())
.build());
}
@Value
@Builder
private static class ClonePlan
{
@NonNull PO rowPO;
@NonNull String rowPO_LinkColumnName;
@NonNull PO headerPO;
@Nullable AdWindowId adWindowId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\WEBUI_CloneLine.java | 1 |
请完成以下Java代码 | public boolean isStatsMissing()
{
return countHUs == null;
}
public OptionalInt getCountHUs()
{
return countHUs != null ? OptionalInt.of(countHUs) : OptionalInt.empty();
}
public HUConsolidationJobReference withUpdatedStats(@NonNull final PickingSlotQueuesSummary summary)
{
final OptionalInt optionalCountHUs = summary.getCountHUs(pickingSlotIds);
if (optionalCountHUs.isPresent())
{
final int countHUsNew = optionalCountHUs.getAsInt(); | if (this.countHUs == null || this.countHUs != countHUsNew)
{
return toBuilder().countHUs(countHUsNew).build();
}
else
{
return this;
}
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobReference.java | 1 |
请完成以下Java代码 | public I_C_RfQResponseLine get()
{
final I_C_RfQResponseLine rfqResponseLine = createRfqResponseLine(response, rfqLine);
if (rfqResponseLine != null)
{
InterfaceWrapperHelper.save(rfqResponseLine);
}
return rfqResponseLine;
}
});
}
protected I_C_RfQResponseLine createRfqResponseLine(final Supplier<I_C_RfQResponse> responseSupplier, final I_C_RfQLine rfqLine)
{
final I_C_RfQResponse rfqResponse = responseSupplier.get();
final Properties ctx = InterfaceWrapperHelper.getCtx(rfqResponse);
final I_C_RfQResponseLine rfqResponseLine = InterfaceWrapperHelper.create(ctx, I_C_RfQResponseLine.class, ITrx.TRXNAME_ThreadInherited);
//
// Defaults
rfqResponseLine.setIsSelectedWinner(false);
rfqResponseLine.setIsSelfService(false);
rfqResponseLine.setDocStatus(rfqResponse.getDocStatus());
rfqResponseLine.setProcessed(rfqResponse.isProcessed());
//
// From RfQ Response header
rfqResponseLine.setC_RfQResponse(rfqResponse);
rfqResponseLine.setAD_Org_ID(rfqResponse.getAD_Org_ID());
rfqResponseLine.setC_BPartner_ID(rfqResponse.getC_BPartner_ID());
rfqResponseLine.setC_Currency_ID(rfqResponse.getC_Currency_ID());
//
// From RfQ header
final I_C_RfQ rfq = rfqLine.getC_RfQ();
rfqResponseLine.setC_RfQ(rfq);
rfqResponseLine.setDateResponse(rfq.getDateResponse());
rfqResponseLine.setDateWorkStart(rfq.getDateWorkStart());
rfqResponseLine.setDeliveryDays(rfq.getDeliveryDays()); | //
// From RfQ Line
rfqResponseLine.setC_RfQLine(rfqLine);
rfqResponseLine.setLine(rfqLine.getLine());
rfqResponseLine.setM_Product_ID(rfqLine.getM_Product_ID());
rfqResponseLine.setC_UOM_ID(rfqLine.getC_UOM_ID());
rfqResponseLine.setQtyRequiered(rfqLine.getQty());
rfqResponseLine.setDescription(rfqLine.getDescription());
rfqResponseLine.setUseLineQty(rfqLine.isUseLineQty());
// NOTE: don't save it!
return rfqResponseLine;
}
private I_C_RfQResponseLineQty createRfQResponseLineQty(final Supplier<I_C_RfQResponseLine> responseLineSupplier, final I_C_RfQLineQty lineQty)
{
final I_C_RfQResponseLine responseLine = responseLineSupplier.get();
final Properties ctx = InterfaceWrapperHelper.getCtx(responseLine);
final I_C_RfQResponseLineQty responseQty = InterfaceWrapperHelper.create(ctx, I_C_RfQResponseLineQty.class, ITrx.TRXNAME_ThreadInherited);
responseQty.setAD_Org_ID(responseLine.getAD_Org_ID());
responseQty.setC_RfQResponseLine(responseLine);
responseQty.setC_RfQLineQty(lineQty);
InterfaceWrapperHelper.save(responseQty);
return responseQty;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\DefaultRfQResponseProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JeecgGatewayApplication implements CommandLineRunner {
@Resource
private DynamicRouteLoader dynamicRouteLoader;
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(JeecgGatewayApplication.class, args);
//String userName = applicationContext.getEnvironment().getProperty("jeecg.test");
//System.err.println("user name :" +userName);
}
/**
* 容器初始化后加载路由
* @param strings
*/
@Override | public void run(String... strings) {
dynamicRouteLoader.refresh(null);
}
/**
* 接口地址(通过9999端口直接访问)
* 已使用knife4j-gateway支持该功能
* @param indexHtml
* @return
*/
@Bean
public RouterFunction<ServerResponse> indexRouter(@Value("classpath:/META-INF/resources/doc.html") final org.springframework.core.io.Resource indexHtml) {
return route(GET("/"), request -> ok().contentType(MediaType.TEXT_HTML).syncBody(indexHtml));
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\JeecgGatewayApplication.java | 2 |
请完成以下Java代码 | public Type getType() {
return typeChild.getChild(this);
}
public void setType(Type type) {
typeChild.setChild(this, type);
}
public OrganizationUnit getOwner() {
return ownerRef.getReferenceTargetElement(this);
}
public void setOwner(OrganizationUnit owner) {
ownerRef.setReferenceTargetElement(this, owner);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(KnowledgeSource.class, DMN_ELEMENT_KNOWLEDGE_SOURCE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DrgElement.class)
.instanceProvider(new ModelTypeInstanceProvider<KnowledgeSource>() {
public KnowledgeSource newInstance(ModelTypeInstanceContext instanceContext) {
return new KnowledgeSourceImpl(instanceContext); | }
});
locationUriAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LOCATION_URI)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class)
.build();
typeChild = sequenceBuilder.element(Type.class)
.build();
ownerRef = sequenceBuilder.element(OwnerReference.class)
.uriElementReference(OrganizationUnit.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\KnowledgeSourceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void buildAdminPermissionTree(String pId, StringBuffer treeBuf, List menuList) {
List<Map> listMap = getSonMenuListByPid(pId.toString(), menuList);
for (Map map : listMap) {
String id = map.get("id").toString();// id
String name = map.get("name").toString();// 名称
String isLeaf = map.get("isLeaf").toString();// 是否叶子
String level = map.get("level").toString();// 菜单层级(1、2、3、4)
String url = map.get("url").toString(); // ACTION访问地址
String navTabId = "";
if (!StringUtil.isEmpty(map.get("targetName"))) {
navTabId = map.get("targetName").toString(); // 用于刷新查询页面
}
if ("1".equals(level)) {
treeBuf.append("<div class='accordionHeader'>");
treeBuf.append("<h2> <span>Folder</span> " + name + "</h2>");
treeBuf.append("</div>");
treeBuf.append("<div class='accordionContent'>");
}
if ("YES".equals(isLeaf)) {
treeBuf.append("<li><a href='" + url + "' target='navTab' rel='" + navTabId + "'>" + name + "</a></li>");
} else {
if ("1".equals(level)) {
treeBuf.append("<ul class='tree treeFolder'>");
} else {
treeBuf.append("<li><a>" + name + "</a>");
treeBuf.append("<ul>");
}
buildAdminPermissionTree(id, treeBuf, menuList);
if ("1".equals(level)) {
treeBuf.append("</ul>");
} else {
treeBuf.append("</ul></li>");
}
}
if ("1".equals(level)) {
treeBuf.append("</div>");
}
} | }
/**
* 根据(pId)获取(menuList)中的所有子菜单集合.
*
* @param pId
* 父菜单ID.
* @param menuList
* 菜单集合.
* @return sonMenuList.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private List<Map> getSonMenuListByPid(String pId, List menuList) {
List sonMenuList = new ArrayList<Object>();
for (Object menu : menuList) {
Map map = (Map) menu;
if (map != null) {
String parentId = map.get("pId").toString();// 父id
if (parentId.equals(pId)) {
sonMenuList.add(map);
}
}
}
return sonMenuList;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\login\LoginController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Object execute(CommandContext commandContext) {
if (jobId == null) {
throw new FlowableIllegalArgumentException("JobId is null");
}
Job job = jobServiceConfiguration.getJobEntityManager().findById(jobId);
if (job == null) {
throw new JobNotFoundException(jobId);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Executing job {}", job.getId());
}
InternalJobCompatibilityManager internalJobCompatibilityManager = jobServiceConfiguration.getInternalJobCompatibilityManager();
if (internalJobCompatibilityManager != null && internalJobCompatibilityManager.isFlowable5Job(job)) {
internalJobCompatibilityManager.executeV5Job(job); | return null;
}
commandContext.addCloseListener(new FailedJobListener(jobServiceConfiguration.getCommandExecutor(), job, jobServiceConfiguration));
jobServiceConfiguration.getJobManager().execute(job);
return null;
}
public String getJobId() {
return jobId;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\ExecuteJobCmd.java | 2 |
请完成以下Java代码 | protected boolean isAuthCheckExecuted() {
Authentication currentAuthentication = getCurrentAuthentication();
CommandContext commandContext = Context.getCommandContext();
return isAuthorizationEnabled()
&& commandContext.isAuthorizationCheckEnabled()
&& currentAuthentication != null
&& currentAuthentication.getUserId() != null;
}
public boolean isEnsureSpecificVariablePermission() {
return Context.getProcessEngineConfiguration().isEnforceSpecificVariablePermission();
}
protected boolean isHistoricInstancePermissionsEnabled() {
return Context.getProcessEngineConfiguration().isEnableHistoricInstancePermissions();
}
public DbOperation addRemovalTimeToAuthorizationsByRootProcessInstanceId(String rootProcessInstanceId,
Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("rootProcessInstanceId", rootProcessInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(AuthorizationEntity.class,
"updateAuthorizationsByRootProcessInstanceId", parameters);
}
public DbOperation addRemovalTimeToAuthorizationsByProcessInstanceId(String processInstanceId,
Date removalTime, Integer batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("processInstanceId", processInstanceId);
parameters.put("removalTime", removalTime);
parameters.put("maxResults", batchSize);
return getDbEntityManager()
.updatePreserveOrder(AuthorizationEntity.class,
"updateAuthorizationsByProcessInstanceId", parameters); | }
public DbOperation deleteAuthorizationsByRemovalTime(Date removalTime, int minuteFrom,
int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(AuthorizationEntity.class, "deleteAuthorizationsByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AuthorizationManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<MenuVO> tree() {
return ForestNodeMerger.merge(baseMapper.tree());
}
@Override
public List<MenuVO> grantTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTree() : baseMapper.grantTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<MenuVO> grantDataScopeTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantDataScopeTree() : baseMapper.grantDataScopeTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> roleTreeKeys(String roleIds) {
List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.<RoleMenu>query().lambda().in(RoleMenu::getRoleId, Func.toLongList(roleIds)));
return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
}
@Override
public List<String> dataScopeTreeKeys(String roleIds) {
List<RoleScope> roleScopes = roleScopeService.list(Wrappers.<RoleScope>query().lambda().in(RoleScope::getRoleId, Func.toLongList(roleIds)));
return roleScopes.stream().map(roleScope -> Func.toStr(roleScope.getScopeId())).collect(Collectors.toList());
} | @Override
public List<Kv> authRoutes(BladeUser user) {
if (Func.isEmpty(user)) {
return null;
}
List<MenuDTO> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleId()));
List<Kv> list = new ArrayList<>();
routes.forEach(route -> list.add(Kv.init().set(route.getPath(), Kv.init().set("authority", Func.toStrArray(route.getAlias())))));
return list;
}
@Override
public List<MenuVO> grantTopTree(BladeUser user) {
return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTopTree() : baseMapper.grantTopTreeByRole(Func.toLongList(user.getRoleId())));
}
@Override
public List<String> topTreeKeys(String topMenuIds) {
List<TopMenuSetting> settings = topMenuSettingService.list(Wrappers.<TopMenuSetting>query().lambda().in(TopMenuSetting::getTopMenuId, Func.toLongList(topMenuIds)));
return settings.stream().map(setting -> Func.toStr(setting.getMenuId())).collect(Collectors.toList());
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\MenuServiceImpl.java | 2 |
请完成以下Java代码 | protected Object[] getArguments() {
return this.arguments;
}
@SuppressWarnings("unchecked")
protected <T> T getArgumentAt(int index) {
return (T) getArguments()[index];
}
@Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int index = 0;
@Override
public boolean hasNext() {
return this.index < InvocationArguments.this.getArguments().length;
} | @Override
public Object next() {
return InvocationArguments.this.getArguments()[this.index++];
}
};
}
public int size() {
return this.arguments.length;
}
@Override
public String toString() {
return Arrays.toString(getArguments());
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\util\function\InvocationArguments.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Consignment {
private String id;
private String source;
private String destination;
private boolean isDelivered;
private List<Item> items = new ArrayList<>();
private List<Checkin> checkins = new ArrayList<>();
@Id
@Column(name = "consignment_id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "source")
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Column(name = "destination")
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
} | @Column(name = "delivered", columnDefinition = "boolean")
public boolean isDelivered() {
return isDelivered;
}
public void setDelivered(boolean delivered) {
isDelivered = delivered;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_item", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "item_index")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_checkin", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "checkin_index")
public List<Checkin> getCheckins() {
return checkins;
}
public void setCheckins(List<Checkin> checkins) {
this.checkins = checkins;
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\Consignment.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CaseInstanceRestServiceImpl extends AbstractRestProcessEngineAware implements CaseInstanceRestService {
public CaseInstanceRestServiceImpl(String engineName, ObjectMapper objectMapper) {
super(engineName, objectMapper);
}
@Override
public CaseInstanceResource getCaseInstance(String caseInstanceId) {
return new CaseInstanceResourceImpl(getProcessEngine(), caseInstanceId, getObjectMapper());
}
@Override
public List<CaseInstanceDto> getCaseInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
CaseInstanceQueryDto queryDto = new CaseInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryCaseInstances(queryDto, firstResult, maxResults);
}
@Override
public List<CaseInstanceDto> queryCaseInstances(CaseInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
CaseInstanceQuery query = queryDto.toQuery(engine);
List<CaseInstance> matchingInstances = QueryUtil.list(query, firstResult, maxResults);
List<CaseInstanceDto> instanceResults = new ArrayList<CaseInstanceDto>();
for (CaseInstance instance : matchingInstances) { | CaseInstanceDto resultInstance = CaseInstanceDto.fromCaseInstance(instance);
instanceResults.add(resultInstance);
}
return instanceResults;
}
@Override
public CountResultDto getCaseInstancesCount(UriInfo uriInfo) {
CaseInstanceQueryDto queryDto = new CaseInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryCaseInstancesCount(queryDto);
}
@Override
public CountResultDto queryCaseInstancesCount(CaseInstanceQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
CaseInstanceQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseInstanceRestServiceImpl.java | 2 |
请完成以下Java代码 | public static OrgPermission ofResourceAndReadOnly(final OrgResource resource, final boolean readOnly)
{
final ImmutableSet.Builder<Access> accesses = ImmutableSet.builder();
// READ access: this is implied if we are here
accesses.add(Access.READ);
// WRITE access:
if (!readOnly)
{
accesses.add(Access.WRITE);
}
// LOGIN access:
if (!resource.isGroupingOrg())
{
accesses.add(Access.LOGIN);
}
return new OrgPermission(resource, accesses.build());
}
/**
*
*/
private static final long serialVersionUID = 6649713070452921967L;
private final OrgResource resource;
private final Set<Access> accesses;
public OrgPermission(final OrgResource resource, final Set<Access> accesses)
{
super();
Check.assumeNotNull(resource, "resource not null");
this.resource = resource;
this.accesses = ImmutableSet.copyOf(accesses);
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(resource)
.append(accesses)
.toHashcode();
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final OrgPermission other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(resource, other.resource)
.append(accesses, other.accesses)
.isEqual();
}
@Override
public String toString()
{
return resource + ", " + accesses;
}
@Override
public boolean hasAccess(Access access)
{
return accesses.contains(access);
} | public boolean isReadOnly()
{
return hasAccess(Access.READ) && !hasAccess(Access.WRITE);
}
public boolean isReadWrite()
{
return hasAccess(Access.WRITE);
}
public ClientId getClientId()
{
return resource.getClientId();
}
public OrgId getOrgId()
{
return resource.getOrgId();
}
@Override
public OrgResource getResource()
{
return resource;
}
@Override
public Permission mergeWith(final Permission permissionFrom)
{
final OrgPermission orgPermissionFrom = checkCompatibleAndCast(permissionFrom);
final ImmutableSet<Access> accesses = ImmutableSet.<Access> builder()
.addAll(this.accesses)
.addAll(orgPermissionFrom.accesses)
.build();
return new OrgPermission(resource, accesses);
}
/**
* Creates a copy of this permission but it will use the given resource.
*
* @return copy of this permission but having the given resource
*/
public OrgPermission copyWithResource(final OrgResource resource)
{
return new OrgPermission(resource, this.accesses);
}
} // OrgAccess | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermission.java | 1 |
请完成以下Java代码 | class ConstantQueryInsertFromColumn implements IQueryInsertFromColumn
{
private final Object constantValue;
public ConstantQueryInsertFromColumn(final Object constantValue)
{
super();
this.constantValue = constantValue;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public String getSql(List<Object> sqlParams)
{
// Case: we are not collecting parameters => render parameter inside the SQL query
if (sqlParams == null)
{ | return DB.TO_SQL(constantValue);
}
sqlParams.add(constantValue);
return "?";
}
@Override
public boolean update(final Object toModel, String toColumnName, final Object fromModel)
{
InterfaceWrapperHelper.setValue(toModel, toColumnName, constantValue);
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ConstantQueryInsertFromColumn.java | 1 |
请完成以下Java代码 | public String getOrderId() {
return orderId;
}
public void setOrderId(final String orderId) {
this.orderId = orderId;
}
public double getPrice() {
return price;
}
public void setPrice(final double price) {
this.price = price;
} | public int getQuantity() {
return quantity;
}
public void setQuantity(final int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", price=" + price + ", quantity=" + quantity + "]";
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\persistence\model\Order.java | 1 |
请完成以下Java代码 | public AccessorBuilder<?> withAnnotation(ClassName className) {
return withAnnotation(className, null);
}
/**
* Adds an annotation.
* @param className the class name of the annotation
* @param annotation configurer for the annotation
* @return this for method chaining
*/
public AccessorBuilder<?> withAnnotation(ClassName className, Consumer<Annotation.Builder> annotation) {
this.annotations.addSingle(className, annotation);
return this;
}
/**
* Sets the body.
* @param code the code for the body
* @return this for method chaining
*/
public AccessorBuilder<?> withBody(CodeBlock code) {
this.code = code;
return this;
}
/**
* Builds the accessor.
* @return the parent getter / setter
*/
public T buildAccessor() {
this.accessorFunction.accept(new Accessor(this)); | return this.parent;
}
}
static final class Accessor implements Annotatable {
private final AnnotationContainer annotations;
private final CodeBlock code;
Accessor(AccessorBuilder<?> builder) {
this.annotations = builder.annotations.deepCopy();
this.code = builder.code;
}
CodeBlock getCode() {
return this.code;
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinPropertyDeclaration.java | 1 |
请完成以下Java代码 | public int getC_DocType_ID(final Properties ctx, final int AD_Table_ID, final int Record_ID)
{
if (AD_Table_ID <= 0 || Record_ID <= 0)
return -1;
final POInfo poInfo = POInfo.getPOInfo(ctx, AD_Table_ID);
final String keyColumn = poInfo.getKeyColumnName();
if (keyColumn == null)
{
return -1;
}
final String tableName = poInfo.getTableName();
int C_DocType_ID = -1;
if (poInfo.hasColumnName("C_DocType_ID"))
{
final String sql = "SELECT C_DocType_ID FROM " + tableName + " WHERE " + keyColumn + "=?";
C_DocType_ID = DB.getSQLValueEx(ITrx.TRXNAME_None, sql, Record_ID);
}
if (C_DocType_ID <= 0 && poInfo.hasColumnName("C_DocTypeTarget_ID"))
{
final String sql = "SELECT C_DocTypeTarget_ID FROM " + tableName + " WHERE " + keyColumn + "=?";
C_DocType_ID = DB.getSQLValueEx(ITrx.TRXNAME_None, sql, Record_ID);
}
if (C_DocType_ID <= 0)
{
C_DocType_ID = -1;
}
return C_DocType_ID;
}
@Nullable
@Override
protected String retrieveString(final int adTableId, final int recordId, final String columnName)
{
if (adTableId <= 0 || recordId <= 0)
{
return null;
}
final POInfo poInfo = POInfo.getPOInfo(adTableId);
if (poInfo == null)
{
throw new AdempiereException("No POInfo found for AD_Table_ID=" + adTableId);
}
final String keyColumn = poInfo.getKeyColumnName();
if (keyColumn == null)
{
return null;
}
String value = null; | if (poInfo.hasColumnName(columnName))
{
final String sql = "SELECT " + columnName + " FROM " + poInfo.getTableName() + " WHERE " + keyColumn + "=?";
value = DB.getSQLValueStringEx(ITrx.TRXNAME_None, sql, recordId);
}
return value;
}
@Override
protected Object retrieveModelOrNull(final Properties ctx, final int adTableId, final int recordId)
{
final String tableName = Services.get(IADTableDAO.class).retrieveTableName(adTableId);
final String trxName = ITrx.TRXNAME_None;
return TableModelLoader.instance.getPO(ctx, tableName, recordId, trxName);
}
@Nullable
@Override
public LocalDate getDocumentDate(final Properties ctx, final int adTableID, final int recordId)
{
final Object model = retrieveModelOrNull(ctx, adTableID, recordId);
return getDocumentDate(model);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\DocumentBL.java | 1 |
请完成以下Java代码 | public I_PP_Order_Qty execute()
{
return huTrxBL.process(this::executeInTrx);
}
private I_PP_Order_Qty executeInTrx(final IHUContext huContext)
{
final I_M_HU hu = huDAO.getById(receiveFromHUId);
final I_PP_Order_Qty candidate = createReceiptCandidateOrNull(huContext, hu);
if (qtyPicked != null && qtyPicked.signum() != 0)
{
throw new AdempiereException("Could not receipt the whole quantity required. " + qtyPicked );
}
return candidate;
}
@Nullable
private I_PP_Order_Qty createReceiptCandidateOrNull(
@NonNull final IHUContext huContext,
@NonNull final I_M_HU hu)
{
final IHUProductStorage productStorage = retrieveProductStorage(huContext, hu);
if (productStorage == null)
{
return null;
}
// Actually create and save the candidate
final I_PP_Order_Qty candidate = createReceiptCandidateOrNull(hu, productStorage);
if (candidate == null)
{
return null;
}
return candidate;
}
@Nullable
private IHUProductStorage retrieveProductStorage(
@NonNull final IHUContext huContext,
@NonNull final I_M_HU hu)
{
final List<IHUProductStorage> productStorages = huContext.getHUStorageFactory()
.getStorage(hu)
.getProductStorages();
// Empty HU
if (productStorages.isEmpty())
{
logger.warn("{}: Skip {} from issuing because its storage is empty", this, hu);
return null; // no candidate
}
return productStorages.get(0);
}
@Nullable
private I_PP_Order_Qty createReceiptCandidateOrNull(
@NonNull final I_M_HU hu,
@NonNull final IHUProductStorage productStorage)
{
try
{
final ProductId productId = productStorage.getProductId();
final Quantity qtyPicked = substractQtyPicked(productStorage)
.switchToSourceIfMorePrecise();
if (qtyPicked.isZero())
{
return null;
}
final I_PP_Order_Qty candidate = huPPOrderQtyDAO.save(CreateReceiptCandidateRequest.builder()
.orderId(orderId)
.orgId(OrgId.ofRepoId(hu.getAD_Org_ID())) | //
.date(movementDate)
//
.locatorId(warehousesRepo.getLocatorIdByRepoIdOrNull(hu.getM_Locator_ID()))
.topLevelHUId(HuId.ofRepoId(hu.getM_HU_ID()))
.productId(productId)
//
.qtyToReceive(qtyPicked)
//
.build());
return candidate;
}
catch (final RuntimeException rte)
{
throw AdempiereException.wrapIfNeeded(rte)
.appendParametersToMessage()
.setParameter("M_HU", hu);
}
}
/**
* @return how much quantity to take "from"
*/
private Quantity substractQtyPicked(@NonNull final IHUProductStorage from)
{
if (qtyPicked != null)
{
final Quantity huStorageQty = from.getQty(qtyPicked.getUOM());
final Quantity qtyToPick = huStorageQty.min(qtyPicked);
qtyPicked = qtyPicked.subtract(qtyToPick);
return qtyToPick;
}
return from.getQty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\hu_pporder_issue_producer\CreatePickedReceiptCommand.java | 1 |
请完成以下Java代码 | public static Map<String, CmmnEngine> getCmmnEngines() {
return cmmnEngines;
}
/**
* closes all cmmn engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines);
cmmnEngines = new HashMap<>();
for (String cmmnEngineName : engines.keySet()) {
CmmnEngine cmmnEngine = engines.get(cmmnEngineName);
try {
cmmnEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e);
}
}
cmmnEngineInfosByName.clear(); | cmmnEngineInfosByResourceUrl.clear();
cmmnEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
CmmnEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java | 1 |
请完成以下Java代码 | public static Date dateAdd(Date date, int days) throws ServiceException {
if (date == null) {
throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
/**
* 增加月份。
*
* @param date
* @param months
* @return
* @throws ServiceException
*/
public static Date monthAdd(Date date, int months) throws ServiceException {
if (date == null) {
throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, months);
return calendar.getTime();
}
/**
* 获取两个日期之间的差值。
*
* @param one
* @param two
* @return
* @throws ServiceException
*/
public static int dateDiff(Date one, Date two) throws ServiceException {
if (one == null || two == null) {
throw new ServiceException(ARG_ERROR_CODE, ARG_ERROR);
}
long diff = Math.abs((one.getTime() - two.getTime()) / (1000 * 3600 * 24));
return new Long(diff).intValue();
}
/**
* 计算几天前的时间
*
* @param date 当前时间
* @param day 几天前
* @return
*/
public static Date getDateBefore(Date date, int day) {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
/**
* 获取当前月第一天 | *
* @return Date
* @throws ParseException
*/
public static Date getFirstAndLastOfMonth() {
LocalDate today = LocalDate.now();
LocalDate firstDay = LocalDate.of(today.getYear(),today.getMonth(),1);
ZoneId zone = ZoneId.systemDefault();
Instant instant = firstDay.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
}
/**
* 获取当前周第一天
*
* @return Date
* @throws ParseException
*/
public static Date getWeekFirstDate(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date date = cal.getTime();
return date;
}
} | repos\springBoot-master\abel-util\src\main\java\cn\abel\utils\DateTimeUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void onFailure(Throwable t) {
DefaultTransportService.this.transportCallbackExecutor.submit(() -> callback.onError(t));
}
}
private class ApiStatsProxyCallback<T> implements TransportServiceCallback<T> {
private final TenantId tenantId;
private final CustomerId customerId;
private final int dataPoints;
private final TransportServiceCallback<T> callback;
public ApiStatsProxyCallback(TenantId tenantId, CustomerId customerId, int dataPoints, TransportServiceCallback<T> callback) {
this.tenantId = tenantId;
this.customerId = customerId;
this.dataPoints = dataPoints;
this.callback = callback;
}
@Override
public void onSuccess(T msg) {
try {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_MSG_COUNT, 1);
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.TRANSPORT_DP_COUNT, dataPoints);
} finally {
callback.onSuccess(msg);
}
}
@Override
public void onError(Throwable e) {
callback.onError(e);
}
}
@Override
public ExecutorService getCallbackExecutor() {
return transportCallbackExecutor; | }
@Override
public boolean hasSession(TransportProtos.SessionInfoProto sessionInfo) {
return sessions.containsKey(toSessionId(sessionInfo));
}
@Override
public void createGaugeStats(String statsName, AtomicInteger number) {
statsFactory.createGauge(StatsType.TRANSPORT + "." + statsName, number);
statsMap.put(statsName, number);
}
@Scheduled(fixedDelayString = "${transport.stats.print-interval-ms:60000}")
public void printStats() {
if (statsEnabled && !statsMap.isEmpty()) {
String values = statsMap.entrySet().stream()
.map(kv -> kv.getKey() + " [" + kv.getValue() + "]").collect(Collectors.joining(", "));
log.info("Transport Stats: {}", values);
}
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportService.java | 2 |
请完成以下Java代码 | public String getDisplay()
{
Object o = super.getSelectedItem();
if (o == null)
return "";
return o.toString();
} // getDisplay
private final JButton getArrowButton()
{
final ComboBoxUI ui = getUI();
if (ui instanceof org.adempiere.plaf.AdempiereComboBoxUI)
{
final JButton b = ((org.adempiere.plaf.AdempiereComboBoxUI)ui).getArrowButton();
return b;
}
return null;
}
/**
* Add Mouse Listener - 1-4-0 Bug.
* Bug in 1.4.0 Metal: arrowButton gets Mouse Events, so add the JComboBox
* MouseListeners to the arrowButton - No context menu if right-click
* @see AdempiereComboBoxUI#installUI(JComponent)
* @param ml
*/
@Override
public void addMouseListener (MouseListener ml)
{
super.addMouseListener(ml);
final JButton arrowButton = getArrowButton();
if (arrowButton != null && !Trace.getCallerClass(1).startsWith("javax"))
{
arrowButton.addMouseListener(ml);
}
}
/**
* Remove Mouse Listener.
* @param ml
*/
@Override
public void removeMouseListener (MouseListener ml)
{
super.removeMouseListener(ml);
final JButton arrowButton = getArrowButton();
if (arrowButton != null)
{
arrowButton.removeMouseListener(ml);
}
} // removeMouseListener
/**
* Set Action Command
* @param actionCommand command
*/
@Override
public void setActionCommand (String actionCommand)
{
super.setActionCommand (actionCommand);
if (getName() == null && actionCommand != null && actionCommand.length() > 0)
setName(actionCommand);
} // setActionCommand
public boolean isSelectionNone()
{
final Object selectedItem = getSelectedItem();
if (selectedItem == null)
{
return true;
}
else
{
return Check.isEmpty(selectedItem.toString(), true);
}
} | @Override
public E getSelectedItem()
{
final Object selectedItemObj = super.getSelectedItem();
@SuppressWarnings("unchecked")
final E selectedItem = (E)selectedItemObj;
return selectedItem;
}
/**
* Enables auto completion (while user writes) on this combobox.
*
* @return combobox's auto-completion instance for further configurations
*/
public final ComboBoxAutoCompletion<E> enableAutoCompletion()
{
return ComboBoxAutoCompletion.enable(this);
}
/**
* Disable autocompletion on this combobox.
*
* If the autocompletion was not enabled, this method does nothing.
*/
public final void disableAutoCompletion()
{
ComboBoxAutoCompletion.disable(this);
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return JComboBoxCopyPasteSupportEditor.ofComponent(this);
}
} // CComboBox | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CComboBox.java | 1 |
请完成以下Java代码 | public class LivelockExample {
private Lock lock1 = new ReentrantLock(true);
private Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
LivelockExample livelock = new LivelockExample();
new Thread(livelock::operation1, "T1").start();
new Thread(livelock::operation2, "T2").start();
}
public void operation1() {
while (true) {
tryLock(lock1, 50);
print("lock1 acquired, trying to acquire lock2.");
sleep(50);
if (tryLock(lock2)) {
print("lock2 acquired.");
} else {
print("cannot acquire lock2, releasing lock1.");
lock1.unlock();
continue;
}
print("executing first operation.");
break;
}
lock2.unlock();
lock1.unlock();
}
public void operation2() {
while (true) {
tryLock(lock2, 50);
print("lock2 acquired, trying to acquire lock1.");
sleep(50);
if (tryLock(lock1)) {
print("lock1 acquired.");
} else {
print("cannot acquire lock1, releasing lock2.");
lock2.unlock();
continue;
}
print("executing second operation.");
break;
} | lock1.unlock();
lock2.unlock();
}
public void print(String message) {
System.out.println("Thread " + Thread.currentThread()
.getName() + ": " + message);
}
public void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void tryLock(Lock lock, long millis) {
try {
lock.tryLock(millis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean tryLock(Lock lock) {
return lock.tryLock();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\deadlockAndLivelock\LivelockExample.java | 1 |
请完成以下Java代码 | public QuadristateButtonModel getModel() {
return (QuadristateButtonModel) super.getModel();
}
public void setModel(QuadristateButtonModel model) {
super.setModel(model);
}
@Override
@Deprecated
public void setModel(ButtonModel model) {
// if (!(model instanceof TristateButtonModel))
// useless: Java always calls the most specific method
super.setModel(model);
}
/** No one may add mouse listeners, not even Swing! */
@Override
public void addMouseListener(MouseListener l) {
}
/** | * Set the new state to either CHECKED, UNCHECKED or GREY_CHECKED. If
* state == null, it is treated as GREY_CHECKED.
*/
public void setState(State state) {
getModel().setState(state);
}
/**
* Return the current state, which is determined by the selection status
* of the model.
*/
public State getState() {
return getModel().getState();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\QuadristateCheckbox.java | 1 |
请完成以下Java代码 | public static Result genSuccessResult(String message) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SUCCESS);
result.setMessage(message);
return result;
}
public static Result genSuccessResult(Object data) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SUCCESS);
result.setMessage(DEFAULT_SUCCESS_MESSAGE);
result.setData(data);
return result;
}
public static Result genFailResult(String message) {
Result result = new Result();
result.setResultCode(RESULT_CODE_SERVER_ERROR); | if (!StringUtils.hasText(message)) {
result.setMessage(DEFAULT_FAIL_MESSAGE);
} else {
result.setMessage(message);
}
return result;
}
public static Result genErrorResult(int code, String message) {
Result result = new Result();
result.setResultCode(code);
result.setMessage(message);
return result;
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\util\ResultGenerator.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
application:
name: zuul-application
cloud:
nacos:
# Nacos 作为注册中心的配置项
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
sentinel:
eager: true # 是否饥饿加载。默认为 false 关闭
transport:
dashboard: localhost:7070 # 是否饥饿加载。
# # 数据源的配置项
# datasource:
# ds1.file:
# file: "classpath: sentinel-gw-flow.json"
# ruleType: gw-flow
# ds2.file:
# file: "classpath: sentinel-gw-api-group.json"
# ruleType: gw-api-group
# Sentinel 对 Zuul 的专属配置项,对应 SentinelZuulProperties 类
zuul:
order:
pre: 10000 # 前置过滤器 SentinelZuulPreFilter 的顺序
| post: 1000 # 后置过滤器 SentinelZuulPostFilter 的顺序
error: -1 # 错误过滤器 SentinelZuulErrorFilter 的顺序
# Zuul 配置项,对应 ZuulProperties 配置类
zuul:
servlet-path: / # ZuulServlet 匹配的路径,默认为 /zuul
# 路由配置项,对应 ZuulRoute Map
routes:
yudaoyuanma: # 这是一个 Route 编号
path: /**
url: http://www.iocoder.cn | repos\SpringBoot-Labs-master\labx-21\labx-21-sc-zuul-demo07-sentinel\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public void cleanCache() {
cleanPdfCache();
cleanImgCache();
cleanPdfImgCache();
cleanMediaConvertCache();
}
@Override
public void addQueueTask(String url) {
RBlockingQueue<String> queue = redissonClient.getBlockingQueue(TASK_QUEUE_NAME);
queue.addAsync(url);
}
@Override
public String takeQueueTask() throws InterruptedException {
RBlockingQueue<String> queue = redissonClient.getBlockingQueue(TASK_QUEUE_NAME);
return queue.take();
}
private void cleanPdfCache() {
RMapCache<String, String> pdfCache = redissonClient.getMapCache(FILE_PREVIEW_PDF_KEY);
pdfCache.clear();
} | private void cleanImgCache() {
RMapCache<String, List<String>> imgCache = redissonClient.getMapCache(FILE_PREVIEW_IMGS_KEY);
imgCache.clear();
}
private void cleanPdfImgCache() {
RMapCache<String, Integer> pdfImg = redissonClient.getMapCache(FILE_PREVIEW_PDF_IMGS_KEY);
pdfImg.clear();
}
private void cleanMediaConvertCache() {
RMapCache<String, Integer> mediaConvertCache = redissonClient.getMapCache(FILE_PREVIEW_MEDIA_CONVERT_KEY);
mediaConvertCache.clear();
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRedisImpl.java | 2 |
请完成以下Java代码 | public boolean open(InputStream stream)
{
return true;
}
public void clear()
{
}
public int size()
{
return getMaxid_();
}
public int ysize()
{
return y_.size();
}
public int getMaxid_()
{
return maxid_;
}
public void setMaxid_(int maxid_)
{
this.maxid_ = maxid_;
}
public double[] getAlpha_()
{
return alpha_;
}
public void setAlpha_(double[] alpha_)
{
this.alpha_ = alpha_;
}
public float[] getAlphaFloat_()
{
return alphaFloat_;
}
public void setAlphaFloat_(float[] alphaFloat_)
{
this.alphaFloat_ = alphaFloat_;
}
public double getCostFactor_()
{
return costFactor_;
}
public void setCostFactor_(double costFactor_)
{
this.costFactor_ = costFactor_;
}
public int getXsize_()
{
return xsize_;
}
public void setXsize_(int xsize_)
{
this.xsize_ = xsize_;
}
public int getMax_xsize_()
{
return max_xsize_; | }
public void setMax_xsize_(int max_xsize_)
{
this.max_xsize_ = max_xsize_;
}
public int getThreadNum_()
{
return threadNum_;
}
public void setThreadNum_(int threadNum_)
{
this.threadNum_ = threadNum_;
}
public List<String> getUnigramTempls_()
{
return unigramTempls_;
}
public void setUnigramTempls_(List<String> unigramTempls_)
{
this.unigramTempls_ = unigramTempls_;
}
public List<String> getBigramTempls_()
{
return bigramTempls_;
}
public void setBigramTempls_(List<String> bigramTempls_)
{
this.bigramTempls_ = bigramTempls_;
}
public List<String> getY_()
{
return y_;
}
public void setY_(List<String> y_)
{
this.y_ = y_;
}
public List<List<Path>> getPathList_()
{
return pathList_;
}
public void setPathList_(List<List<Path>> pathList_)
{
this.pathList_ = pathList_;
}
public List<List<Node>> getNodeList_()
{
return nodeList_;
}
public void setNodeList_(List<List<Node>> nodeList_)
{
this.nodeList_ = nodeList_;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
try {
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId);
Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId()));
CustomerId customerId = publicCustomer.getId();
logEntityActionService.logEntityAction(tenantId, assetId, savedAsset, customerId, actionType, user,
assetId.toString(), customerId.toString(), publicCustomer.getName());
return savedAsset;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e, assetId.toString());
throw e;
}
}
@Override
public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_EDGE;
EdgeId edgeId = edge.getId();
try {
Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId));
logEntityActionService.logEntityAction(tenantId, assetId, savedAsset, savedAsset.getCustomerId(),
actionType, user, assetId.toString(), edgeId.toString(), edge.getName());
return savedAsset;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType,
user, e, assetId.toString(), edgeId.toString());
throw e;
}
} | @Override
public Asset unassignAssetFromEdge(TenantId tenantId, Asset asset, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE;
AssetId assetId = asset.getId();
EdgeId edgeId = edge.getId();
try {
Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId));
logEntityActionService.logEntityAction(tenantId, assetId, asset, asset.getCustomerId(),
actionType, user, assetId.toString(), edgeId.toString(), edge.getName());
return savedAsset;
} catch (Exception e) {
logEntityActionService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType,
user, e, assetId.toString(), edgeId.toString());
throw e;
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\asset\DefaultTbAssetService.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.