instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class NettyServerHandlerInitializer extends ChannelInitializer<Channel> {
/**
* 心跳超时时间
*/
private static final Integer READ_TIMEOUT_SECONDS = 3 * 60;
@Autowired
private MessageDispatcher messageDispatcher;
@Autowired
private NettyServerHandler nettyServerHandler;
@Override
protected void initChannel(Channel ch) {
// 获得 Channel 对应的 ChannelPipeline
ChannelPipeline channelPipeline = ch.pipeline();
// 添加一堆 NettyServerHandler 到 ChannelPipeline 中
|
channelPipeline
// 空闲检测
.addLast(new ReadTimeoutHandler(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS))
// 编码器
.addLast(new InvocationEncoder())
// 解码器
.addLast(new InvocationDecoder())
// 消息分发器
.addLast(messageDispatcher)
// 服务端处理器
.addLast(nettyServerHandler)
;
}
}
|
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-server\src\main\java\cn\iocoder\springboot\lab67\nettyserverdemo\server\handler\NettyServerHandlerInitializer.java
| 2
|
请完成以下Java代码
|
public class WeightHUCommand
{
private final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
private final HUQtyService huQtyService;
private final HuId huId;
private final PlainWeightable targetWeight;
@Builder
private WeightHUCommand(
@NonNull final HUQtyService huQtyService,
//
@NonNull final HuId huId,
@NonNull final IWeightable targetWeight)
{
this.huQtyService = huQtyService;
this.huId = huId;
this.targetWeight = PlainWeightable.copyOf(targetWeight);
}
public Optional<InventoryId> execute()
{
final Inventory inventoryHeader = createAndCompleteInventory();
if (inventoryHeader == null)
{
return Optional.empty();
}
updateHUWeights();
return Optional.of(inventoryHeader.getId());
}
@Nullable
private Inventory createAndCompleteInventory()
{
final Quantity targetWeightNet = Quantity.of(targetWeight.getWeightNet(), targetWeight.getWeightNetUOM());
final UpdateHUQtyRequest updateHUQtyRequest = UpdateHUQtyRequest.builder()
.qty(targetWeightNet)
.huId(huId)
.build();
return huQtyService.updateQty(updateHUQtyRequest);
|
}
private void updateHUWeights()
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IWeightable huAttributes = getHUAttributes(hu);
huAttributes.setWeightTareAdjust(targetWeight.getWeightTareAdjust());
huAttributes.setWeightGross(targetWeight.getWeightGross());
huAttributes.setWeightNet(targetWeight.getWeightNet());
huAttributes.setWeightNetNoPropagate(targetWeight.getWeightNet());
}
private IWeightable getHUAttributes(final I_M_HU hu)
{
final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class);
final IAttributeStorage huAttributes = huContextFactory
.createMutableHUContext()
.getHUAttributeStorageFactory()
.getAttributeStorage(hu);
huAttributes.setSaveOnChange(true);
return Weightables.wrap(huAttributes);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\weighting\WeightHUCommand.java
| 1
|
请完成以下Java代码
|
public class DataObjectImpl extends FlowElementImpl implements DataObject {
protected static AttributeReference<ItemDefinition> itemSubjectRefAttribute;
protected static Attribute<Boolean> isCollectionAttribute;
protected static ChildElement<DataState> dataStateChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DataObject.class, BPMN_ELEMENT_DATA_OBJECT)
.namespaceUri(BPMN20_NS)
.extendsType(FlowElement.class)
.instanceProvider(new ModelTypeInstanceProvider<DataObject>() {
public DataObject newInstance(ModelTypeInstanceContext instanceContext) {
return new DataObjectImpl(instanceContext);
}
});
itemSubjectRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ITEM_SUBJECT_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
isCollectionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_COLLECTION)
.defaultValue(false)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
dataStateChild = sequenceBuilder.element(DataState.class)
.build();
typeBuilder.build();
}
public DataObjectImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
@Override
public ItemDefinition getItemSubject() {
return itemSubjectRefAttribute.getReferenceTargetElement(this);
}
@Override
public void setItemSubject(ItemDefinition itemSubject) {
itemSubjectRefAttribute.setReferenceTargetElement(this, itemSubject);
}
|
@Override
public DataState getDataState() {
return dataStateChild.getChild(this);
}
@Override
public void setDataState(DataState dataState) {
dataStateChild.setChild(this, dataState);
}
@Override
public boolean isCollection() {
return isCollectionAttribute.getValue(this);
}
@Override
public void setCollection(boolean isCollection) {
isCollectionAttribute.setValue(this, isCollection);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\DataObjectImpl.java
| 1
|
请完成以下Java代码
|
public class FullResponseBuilder {
public static String getFullResponse(HttpURLConnection con) throws IOException {
StringBuilder fullResponseBuilder = new StringBuilder();
fullResponseBuilder.append(con.getResponseCode())
.append(" ")
.append(con.getResponseMessage())
.append("\n");
con.getHeaderFields()
.entrySet()
.stream()
.filter(entry -> entry.getKey() != null)
.forEach(entry -> {
fullResponseBuilder.append(entry.getKey())
.append(": ");
List<String> headerValues = entry.getValue();
Iterator<String> it = headerValues.iterator();
if (it.hasNext()) {
fullResponseBuilder.append(it.next());
while (it.hasNext()) {
fullResponseBuilder.append(", ")
.append(it.next());
}
}
fullResponseBuilder.append("\n");
});
|
Reader streamReader = null;
if (con.getResponseCode() > 299) {
streamReader = new InputStreamReader(con.getErrorStream());
} else {
streamReader = new InputStreamReader(con.getInputStream());
}
BufferedReader in = new BufferedReader(streamReader);
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
fullResponseBuilder.append("Response: ")
.append(content);
return fullResponseBuilder.toString();
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\httprequest\FullResponseBuilder.java
| 1
|
请完成以下Java代码
|
public void setDebug(boolean debug) {
this.debug = debug;
}
public void setMultiTier(boolean multiTier) {
this.multiTier = multiTier;
}
private static final class LoginConfig extends Configuration {
private boolean debug;
private LoginConfig(boolean debug) {
super();
this.debug = debug;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put("storeKey", "true");
if (this.debug) {
options.put("debug", "true");
}
return new AppConfigurationEntry[] {
new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), };
}
}
static final class KerberosClientCallbackHandler implements CallbackHandler {
private String username;
private String password;
private KerberosClientCallbackHandler(String username, String password) {
this.username = username;
|
this.password = password;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback ncb = (NameCallback) callback;
ncb.setName(this.username);
}
else if (callback instanceof PasswordCallback) {
PasswordCallback pwcb = (PasswordCallback) callback;
pwcb.setPassword(this.password.toCharArray());
}
else {
throw new UnsupportedCallbackException(callback,
"We got a " + callback.getClass().getCanonicalName()
+ ", but only NameCallback and PasswordCallback is supported");
}
}
}
}
}
|
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\SunJaasKerberosClient.java
| 1
|
请完成以下Java代码
|
public String getPlaceholder() {
return PasswordPolicyUserDataRuleImpl.PLACEHOLDER;
}
@Override
public Map<String, String> getParameters() {
return null;
}
@Override
public boolean execute(String password) {
return false;
}
@Override
public boolean execute(String candidatePassword, User user) {
if (candidatePassword.isEmpty() || user == null) {
return true;
} else {
candidatePassword = upperCase(candidatePassword);
String id = upperCase(user.getId());
|
String firstName = upperCase(user.getFirstName());
String lastName = upperCase(user.getLastName());
String email = upperCase(user.getEmail());
return !(isNotBlank(id) && candidatePassword.contains(id) ||
isNotBlank(firstName) && candidatePassword.contains(firstName) ||
isNotBlank(lastName) && candidatePassword.contains(lastName) ||
isNotBlank(email) && candidatePassword.contains(email));
}
}
public String upperCase(String string) {
return string == null ? null : string.toUpperCase();
}
public boolean isNotBlank(String value) {
return value != null && !value.isEmpty();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\PasswordPolicyUserDataRuleImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<TaskDTO> getTasks() {
return tasks;
}
/**
* Get tasks for specific taskid
*
* @param taskId
* @return
*/
@RequestMapping(value = "{taskId}", method = RequestMethod.GET, headers = "Accept=application/json")
public TaskDTO getTaskByTaskId(@PathVariable("taskId") String taskId) {
TaskDTO taskToReturn = null;
for (TaskDTO currentTask : tasks) {
if (currentTask.getTaskId().equalsIgnoreCase(taskId)) {
taskToReturn = currentTask;
break;
}
}
if (taskToReturn != null) {
taskToReturn.setComments(this.commentsService.getCommentsForTask(taskId));
}
|
return taskToReturn;
}
/**
* Get tasks for specific user that is passed in
*
* @param taskId
* @return
*/
@RequestMapping(value = "/usertask/{userName}", method = RequestMethod.GET, headers = "Accept=application/json")
public List<TaskDTO> getTasksByUserName(@PathVariable("userName") String userName) {
List<TaskDTO> taskListToReturn = new ArrayList<TaskDTO>();
for (TaskDTO currentTask : tasks) {
if (currentTask.getUserName().equalsIgnoreCase(userName)) {
taskListToReturn.add(currentTask);
}
}
return taskListToReturn;
}
}
|
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\apis\TaskController.java
| 2
|
请完成以下Java代码
|
public void setM_Shipment_Declaration_Correction_ID (int M_Shipment_Declaration_Correction_ID)
{
if (M_Shipment_Declaration_Correction_ID < 1)
set_Value (COLUMNNAME_M_Shipment_Declaration_Correction_ID, null);
else
set_Value (COLUMNNAME_M_Shipment_Declaration_Correction_ID, Integer.valueOf(M_Shipment_Declaration_Correction_ID));
}
/** Get M_Shipment_Declaration_Correction_ID.
@return M_Shipment_Declaration_Correction_ID */
@Override
public int getM_Shipment_Declaration_Correction_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Correction_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Abgabemeldung.
@param M_Shipment_Declaration_ID Abgabemeldung */
@Override
public void setM_Shipment_Declaration_ID (int M_Shipment_Declaration_ID)
{
if (M_Shipment_Declaration_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_ID, Integer.valueOf(M_Shipment_Declaration_ID));
}
/** Get Abgabemeldung.
@return Abgabemeldung */
@Override
public int getM_Shipment_Declaration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
|
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_ChargeType[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Charge Type.
@param C_ChargeType_ID Charge Type */
public void setC_ChargeType_ID (int C_ChargeType_ID)
{
if (C_ChargeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, Integer.valueOf(C_ChargeType_ID));
}
/** Get Charge Type.
@return Charge Type */
public int getC_ChargeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
|
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ChargeType.java
| 1
|
请完成以下Java代码
|
public Builder setDetailId(final String detailIdStr)
{
setDetailId(DetailId.fromJson(detailIdStr));
return this;
}
public Builder setDetailId(final DetailId detailId)
{
this.detailId = detailId;
return this;
}
public Builder setRowId(final String rowIdStr)
{
final DocumentId rowId = DocumentId.ofStringOrEmpty(rowIdStr);
setRowId(rowId);
return this;
}
public Builder setRowId(@Nullable final DocumentId rowId)
{
rowIds.clear();
if (rowId != null)
{
rowIds.add(rowId);
}
return this;
}
public Builder setRowIdsList(final String rowIdsListStr)
{
return setRowIds(DocumentIdsSelection.ofCommaSeparatedString(rowIdsListStr));
}
public Builder setRowIds(final DocumentIdsSelection rowIds)
{
this.rowIds.clear();
|
this.rowIds.addAll(rowIds.toSet());
return this;
}
public Builder allowNullRowId()
{
rowId_allowNull = true;
return this;
}
public Builder allowNewRowId()
{
rowId_allowNew = true;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentPath.java
| 1
|
请完成以下Java代码
|
public void setPaymentRule (final @Nullable java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
@Override
public java.lang.String getPaymentRule()
{
return get_ValueAsString(COLUMNNAME_PaymentRule);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPO_PaymentTerm_ID (final int PO_PaymentTerm_ID)
{
if (PO_PaymentTerm_ID < 1)
set_Value (COLUMNNAME_PO_PaymentTerm_ID, null);
else
set_Value (COLUMNNAME_PO_PaymentTerm_ID, PO_PaymentTerm_ID);
}
@Override
public int getPO_PaymentTerm_ID()
{
return get_ValueAsInt(COLUMNNAME_PO_PaymentTerm_ID);
}
@Override
public void setPO_PricingSystem_ID (final int PO_PricingSystem_ID)
{
if (PO_PricingSystem_ID < 1)
set_Value (COLUMNNAME_PO_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_PO_PricingSystem_ID, PO_PricingSystem_ID);
}
@Override
public int getPO_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_PO_PricingSystem_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
|
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setReferrer (final @Nullable java.lang.String Referrer)
{
set_Value (COLUMNNAME_Referrer, Referrer);
}
@Override
public java.lang.String getReferrer()
{
return get_ValueAsString(COLUMNNAME_Referrer);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_QuickInput.java
| 1
|
请完成以下Java代码
|
public record SearchHotelsResult(List<HotelService.HotelOffer> offers) {
}
public static class SearchHotels implements Functional {
@JsonPropertyDescription("City name, for example: Tokyo")
@JsonProperty(required = true)
public String city;
@JsonPropertyDescription("Check-in date in ISO-8601 format, for example: 2026-01-10")
@JsonProperty(required = true)
public String checkIn;
@JsonPropertyDescription("Number of nights to stay")
@JsonProperty(required = true)
public int nights;
@JsonPropertyDescription("Number of guests")
@JsonProperty(required = true)
public int guests;
@Override
public Object execute() {
List<HotelService.HotelOffer> offers =
HOTEL_SERVICE.searchOffers(city, checkIn, nights, guests);
return new SearchHotelsResult(offers);
}
}
public static class CreateBooking implements Functional {
@JsonPropertyDescription("Hotel identifier returned by search_hotels")
@JsonProperty(required = true)
public String hotelId;
@JsonPropertyDescription("Check-in date in ISO-8601 format, for example: 2026-01-10")
@JsonProperty(required = true)
|
public String checkIn;
@JsonPropertyDescription("Number of nights to stay")
@JsonProperty(required = true)
public int nights;
@JsonPropertyDescription("Number of guests")
@JsonProperty(required = true)
public int guests;
@JsonPropertyDescription("Guest full name for the booking")
@JsonProperty(required = true)
public String guestName;
@Override
public Object execute() {
return HOTEL_SERVICE.createBooking(hotelId, checkIn, nights, guests, guestName);
}
}
}
|
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\simpleopenai\HotelFunctions.java
| 1
|
请完成以下Java代码
|
public List<AppDeploymentResourceResponse> createDeploymentResourceResponseList(String deploymentId, List<String> resourceList, ContentTypeResolver contentTypeResolver) {
AppRestUrlBuilder urlBuilder = createUrlBuilder();
// Add additional metadata to the artifact-strings before returning
List<AppDeploymentResourceResponse> responseList = new ArrayList<>(resourceList.size());
for (String resourceId : resourceList) {
String contentType = contentTypeResolver.resolveContentType(resourceId);
responseList.add(createDeploymentResourceResponse(deploymentId, resourceId, contentType, urlBuilder));
}
return responseList;
}
public AppDeploymentResourceResponse createDeploymentResourceResponse(String deploymentId, String resourceId, String contentType) {
return createDeploymentResourceResponse(deploymentId, resourceId, contentType, createUrlBuilder());
}
public AppDeploymentResourceResponse createDeploymentResourceResponse(String deploymentId, String resourceId, String contentType, AppRestUrlBuilder urlBuilder) {
// Create URL's
|
String resourceUrl = urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT_RESOURCE, deploymentId, resourceId);
String resourceContentUrl = urlBuilder.buildUrl(AppRestUrls.URL_DEPLOYMENT_RESOURCE_CONTENT, deploymentId, resourceId);
// Determine type
String type = "resource";
if (resourceId.endsWith(".app")) {
type = "appDefinition";
}
return new AppDeploymentResourceResponse(resourceId, resourceUrl, resourceContentUrl, contentType, type);
}
protected AppRestUrlBuilder createUrlBuilder() {
return AppRestUrlBuilder.fromCurrentRequest();
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine-rest\src\main\java\org\flowable\app\rest\AppRestResponseFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
ApplicationListener<ClassPathChangedEvent> liveReloadTriggeringClassPathChangedEventListener(
OptionalLiveReloadServer optionalLiveReloadServer) {
return (event) -> {
String url = this.remoteUrl + this.properties.getRemote().getContextPath();
this.executor.execute(
new DelayedLiveReloadTrigger(optionalLiveReloadServer, this.clientHttpRequestFactory, url));
};
}
@Bean
OptionalLiveReloadServer optionalLiveReloadServer(ObjectProvider<LiveReloadServer> liveReloadServer) {
return new OptionalLiveReloadServer(liveReloadServer.getIfAvailable());
}
final ExecutorService getExecutor() {
return this.executor;
}
}
/**
* Client configuration for remote update and restarts.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty(name = "spring.devtools.remote.restart.enabled", matchIfMissing = true)
static class RemoteRestartClientConfiguration {
private final DevToolsProperties properties;
RemoteRestartClientConfiguration(DevToolsProperties properties) {
this.properties = properties;
}
@Bean
ClassPathFileSystemWatcher classPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory,
ClassPathRestartStrategy classPathRestartStrategy) {
DefaultRestartInitializer restartInitializer = new DefaultRestartInitializer();
URL[] urls = restartInitializer.getInitialUrls(Thread.currentThread());
if (urls == null) {
urls = new URL[0];
}
return new ClassPathFileSystemWatcher(fileSystemWatcherFactory, classPathRestartStrategy, urls);
}
|
@Bean
FileSystemWatcherFactory getFileSystemWatcherFactory() {
return this::newFileSystemWatcher;
}
private FileSystemWatcher newFileSystemWatcher() {
Restart restartProperties = this.properties.getRestart();
FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(),
restartProperties.getQuietPeriod());
String triggerFile = restartProperties.getTriggerFile();
if (StringUtils.hasLength(triggerFile)) {
watcher.setTriggerFilter(new TriggerFileFilter(triggerFile));
}
return watcher;
}
@Bean
ClassPathRestartStrategy classPathRestartStrategy() {
return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude());
}
@Bean
ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory,
@Value("${remoteUrl}") String remoteUrl) {
String url = remoteUrl + this.properties.getRemote().getContextPath() + "/restart";
return new ClassPathChangeUploader(url, requestFactory);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\RemoteClientConfiguration.java
| 2
|
请完成以下Java代码
|
protected String doIt()
{
Check.assume(p_AD_User_ID > 0, "User should not be empty! ");
final int targetUser_ID = getRecord_ID();
Check.assume(targetUser_ID > 0, "There is no record selected! ");
final I_AD_User targetUser = Services.get(IUserDAO.class).getById(targetUser_ID);
Check.assume(targetUser.isSystemUser(), "Selected user is not system user! ");
final String whereClause = I_AD_TreeBar.COLUMNNAME_AD_User_ID + " = ? ";
final List<I_AD_TreeBar> treBars = new TypedSqlQuery<I_AD_TreeBar>(getCtx(), I_AD_TreeBar.class, whereClause, get_TrxName())
.setOnlyActiveRecords(true)
.setParameters(p_AD_User_ID)
.list();
int cnt = 0;
for (final I_AD_TreeBar treeBar : treBars)
{
if (!existsAlready(targetUser_ID, treeBar.getNode_ID()))
{
final I_AD_TreeBar tb = InterfaceWrapperHelper.create(getCtx(), I_AD_TreeBar.class, get_TrxName());
tb.setAD_Org_ID(treeBar.getAD_Org_ID());
tb.setNode_ID(treeBar.getNode_ID());
tb.setAD_User_ID(targetUser_ID);
InterfaceWrapperHelper.save(tb);
cnt++;
}
|
}
return "Count: " + cnt;
}
/**
* check if the TreeBar already exists
*/
private boolean existsAlready(final int AD_User_ID, final int Node_ID)
{
final String whereClause = I_AD_TreeBar.COLUMNNAME_AD_User_ID + " = ? AND "
+ I_AD_TreeBar.COLUMNNAME_Node_ID + " = ?";
return new TypedSqlQuery<I_AD_TreeBar>(getCtx(), I_AD_TreeBar.class, whereClause, get_TrxName())
.setOnlyActiveRecords(true)
.setParameters(AD_User_ID, Node_ID)
.anyMatch();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_CopyFavoritesPanel.java
| 1
|
请完成以下Java代码
|
public class DepositAccountAsyncEvent implements AccountAsyncEvent {
private final String id;
private final String accountId;
private final Integer credit;
@JsonCreator
public DepositAccountAsyncEvent(@JsonProperty("id") String id,
@JsonProperty("account") String accountId,
@JsonProperty("credit") Integer credit) {
this.id = id;
this.accountId = accountId;
this.credit = credit;
}
@Override
public String getId() {
return id;
|
}
@Override
public String keyMessageKey() {
return accountId;
}
public String getAccountId() {
return accountId;
}
public Integer getCredit() {
return credit;
}
}
|
repos\spring-examples-java-17\spring-kafka\kafka-common\src\main\java\itx\examples\spring\kafka\events\DepositAccountAsyncEvent.java
| 1
|
请完成以下Java代码
|
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;
}
public Division getDivision() {
return division;
|
}
public void setDivision(Division division) {
this.division = division;
}
public Date getStartDt() {
return startDt;
}
public void setStartDt(Date startDt) {
this.startDt = startDt;
}
}
|
repos\tutorials-master\mapstruct\src\main\java\com\baeldung\entity\Employee.java
| 1
|
请完成以下Java代码
|
private ADReferenceService adReferenceService()
{
ADReferenceService adReferenceService = this._adReferenceService;
if (adReferenceService == null)
{
adReferenceService = this._adReferenceService = ADReferenceService.get();
}
return adReferenceService;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isPerfMonActive()
{
return getSysConfigBooleanValue(PM_SYSCONFIG_NAME, PM_SYS_CONFIG_DEFAULT_VALUE);
}
public void performanceMonitoringServiceSaveEx(@NonNull final Runnable runnable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
performanceMonitoringService.monitor(runnable, PM_METADATA_SAVE_EX);
}
public boolean performanceMonitoringServiceLoad(@NonNull final Callable<Boolean> callable)
{
final PerformanceMonitoringService performanceMonitoringService = performanceMonitoringService();
return performanceMonitoringService.monitor(callable, PM_METADATA_LOAD);
}
private PerformanceMonitoringService performanceMonitoringService()
{
PerformanceMonitoringService performanceMonitoringService = _performanceMonitoringService;
if (performanceMonitoringService == null || performanceMonitoringService instanceof NoopPerformanceMonitoringService)
{
performanceMonitoringService = _performanceMonitoringService = SpringContextHolder.instance.getBeanOr(
PerformanceMonitoringService.class,
NoopPerformanceMonitoringService.INSTANCE);
}
return performanceMonitoringService;
}
//
//
//
public boolean isDeveloperMode()
{
return developerModeBL().isEnabled();
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue, final int ad_client_id, final int ad_org_id)
{
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue, ad_client_id, ad_org_id);
}
public boolean getSysConfigBooleanValue(final String sysConfigName, final boolean defaultValue)
{
|
return sysConfigBL().getBooleanValue(sysConfigName, defaultValue);
}
public boolean isChangeLogEnabled()
{
return sessionBL().isChangeLogEnabled();
}
public String getInsertChangeLogType(final int adClientId)
{
return sysConfigBL().getValue("SYSTEM_INSERT_CHANGELOG", "N", adClientId);
}
public void saveChangeLogs(final List<ChangeLogRecord> changeLogRecords)
{
sessionDAO().saveChangeLogs(changeLogRecords);
}
public void logMigration(final MFSession session, final PO po, final POInfo poInfo, final String actionType)
{
migrationLogger().logMigration(session, po, poInfo, actionType);
}
public void fireDocumentNoChange(final PO po, final String value)
{
documentNoBL().fireDocumentNoChange(po, value); // task 09776
}
public ADRefList getRefListById(@NonNull final ReferenceId referenceId)
{
return adReferenceService().getRefListById(referenceId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POServicesFacade.java
| 1
|
请完成以下Java代码
|
private boolean evaluateAsStrings(final Object valueObj, final String value1S, final String value2S)
{
final String valueObjS = String.valueOf(valueObj);
//
if (X_AD_WF_NextCondition.OPERATION_Eq.equals(operation))
return valueObjS.compareTo(value1S) == 0;
else if (X_AD_WF_NextCondition.OPERATION_Gt.equals(operation))
return valueObjS.compareTo(value1S) > 0;
else if (X_AD_WF_NextCondition.OPERATION_GtEq.equals(operation))
return valueObjS.compareTo(value1S) >= 0;
else if (X_AD_WF_NextCondition.OPERATION_Le.equals(operation))
return valueObjS.compareTo(value1S) < 0;
else if (X_AD_WF_NextCondition.OPERATION_LeEq.equals(operation))
return valueObjS.compareTo(value1S) <= 0;
else if (X_AD_WF_NextCondition.OPERATION_Like.equals(operation))
return valueObjS.compareTo(value1S) == 0;
else if (X_AD_WF_NextCondition.OPERATION_NotEq.equals(operation))
return valueObjS.compareTo(value1S) != 0;
//
else if (X_AD_WF_NextCondition.OPERATION_Sql.equals(operation))
throw new IllegalArgumentException("SQL not Implemented");
//
else if (X_AD_WF_NextCondition.OPERATION_X.equals(operation))
{
if (valueObjS.compareTo(value1S) < 0)
return false;
// To
return valueObjS.compareTo(value2S) <= 0;
}
//
throw new IllegalArgumentException("Unknown Operation=" + operation);
} // compareString
/**
* Compare Boolean
*
* @param valueObj comparator
* @param value1S first value
* @return true if operation
|
*/
private boolean evaluateAsBooleans(final Boolean valueObj, final String value1S)
{
final Boolean value1B = StringUtils.toBoolean(value1S);
//
if (X_AD_WF_NextCondition.OPERATION_Eq.equals(operation))
{
return valueObj.equals(value1B);
}
else if (X_AD_WF_NextCondition.OPERATION_NotEq.equals(operation))
{
return !valueObj.equals(value1B);
}
else
{
throw new AdempiereException("Not Supported =" + operation);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFNodeTransitionCondition.java
| 1
|
请完成以下Java代码
|
public void postHandleSingleHistoryEventCreated(HistoryEvent event) {
((ExternalTaskEntity) externalTask).setLastFailureLogId(event.getId());
}
});
}
}
public void fireExternalTaskSuccessfulEvent(final ExternalTask externalTask) {
if (isHistoryEventProduced(HistoryEventTypes.EXTERNAL_TASK_SUCCESS, externalTask)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricExternalTaskLogSuccessfulEvt(externalTask);
}
});
}
}
public void fireExternalTaskDeletedEvent(final ExternalTask externalTask) {
if (isHistoryEventProduced(HistoryEventTypes.EXTERNAL_TASK_DELETE, externalTask)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
|
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricExternalTaskLogDeletedEvt(externalTask);
}
});
}
}
// helper /////////////////////////////////////////////////////////
protected boolean isHistoryEventProduced(HistoryEventType eventType, ExternalTask externalTask) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
return historyLevel.isHistoryEventProduced(eventType, externalTask);
}
protected void configureQuery(HistoricExternalTaskLogQueryImpl query) {
getAuthorizationManager().configureHistoricExternalTaskLogQuery(query);
getTenantManager().configureQuery(query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricExternalTaskLogManager.java
| 1
|
请完成以下Java代码
|
public class FlowableEventListenerValidator extends ProcessLevelValidator {
@Override
protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
List<EventListener> eventListeners = process.getEventListeners();
if (eventListeners != null) {
for (EventListener eventListener : eventListeners) {
if (eventListener.getImplementationType() != null && eventListener.getImplementationType().equals(ImplementationType.IMPLEMENTATION_TYPE_INVALID_THROW_EVENT)) {
addError(errors, Problems.EVENT_LISTENER_INVALID_THROW_EVENT_TYPE, process, eventListener, "Invalid or unsupported throw event type on event listener");
} else if (eventListener.getImplementationType() == null || eventListener.getImplementationType().length() == 0) {
addError(errors, Problems.EVENT_LISTENER_IMPLEMENTATION_MISSING, process, eventListener, "Element 'class', 'delegateExpression' or 'throwEvent' is mandatory on eventListener");
} else if (eventListener.getImplementationType() != null) {
|
if (!ImplementationType.IMPLEMENTATION_TYPE_CLASS.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_SIGNAL_EVENT.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_GLOBAL_SIGNAL_EVENT.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_MESSAGE_EVENT.equals(eventListener.getImplementationType())
&& !ImplementationType.IMPLEMENTATION_TYPE_THROW_ERROR_EVENT.equals(eventListener.getImplementationType())) {
addError(errors, Problems.EVENT_LISTENER_INVALID_IMPLEMENTATION, process, eventListener, "Unsupported implementation type for event listener");
}
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\impl\FlowableEventListenerValidator.java
| 1
|
请完成以下Java代码
|
public static MContainerElement get(Properties ctx, int CM_ContainerElement_ID, String trxName) {
MContainerElement thisContainerElement = null;
String sql = "SELECT * FROM CM_Container_Element WHERE CM_Container_Element_ID=?";
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
pstmt.setInt(1, CM_ContainerElement_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
thisContainerElement = (new MContainerElement(ctx, rs, trxName));
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
s_log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
return thisContainerElement;
}
/***************************************************************************
* Standard Constructor
*
* @param ctx context
* @param CM_Container_Element_ID id
* @param trxName transaction
*/
public MContainerElement (Properties ctx, int CM_Container_Element_ID, String trxName)
{
super (ctx, CM_Container_Element_ID, trxName);
if (CM_Container_Element_ID == 0)
{
setIsValid(false);
}
} // MContainerElement
/**
* Load Constructor
*
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MContainerElement (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MContainerElement
|
/** Parent */
private MContainer m_parent = null;
/**
* Get Container get's related Container
* @return MContainer
*/
public MContainer getParent()
{
if (m_parent == null)
m_parent = new MContainer (getCtx(), getCM_Container_ID(), get_TrxName());
return m_parent;
/** No reason to do this ?? - should never return null - always there - JJ
int[] thisContainer = MContainer.getAllIDs("CM_Container","CM_Container_ID=" + this.getCM_Container_ID(), get_TrxName());
if (thisContainer != null)
{
if (thisContainer.length==1)
return new MContainer(getCtx(), thisContainer[0], get_TrxName());
}
return null;
**/
} // getContainer
/**
* After Save.
* Insert
* - create / update index
* @param newRecord insert
* @param success save success
* @return true if saved
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
reIndex(newRecord);
return success;
} // afterSave
/**
* reIndex
* @param newRecord
*/
public void reIndex(boolean newRecord)
{
int CMWebProjectID = 0;
if (getParent()!=null)
CMWebProjectID = getParent().getCM_WebProject_ID();
String [] toBeIndexed = new String[3];
toBeIndexed[0] = this.getName();
toBeIndexed[1] = this.getDescription();
toBeIndexed[2] = this.getContentHTML();
MIndex.reIndex (newRecord, toBeIndexed, getCtx(),
getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated());
} // reIndex
} // MContainerElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContainerElement.java
| 1
|
请完成以下Java代码
|
public List<InvoiceRow> getInvoiceRowsListByInvoiceId(
@NonNull final Collection<InvoiceId> invoiceIds,
@NonNull final ZonedDateTime evaluationDate)
{
if (invoiceIds.isEmpty())
{
return ImmutableList.of();
}
final InvoiceToAllocateQuery query = InvoiceToAllocateQuery.builder()
.evaluationDate(evaluationDate)
.onlyInvoiceIds(invoiceIds)
.build();
final List<InvoiceToAllocate> invoiceToAllocates = paymentAllocationRepo.retrieveInvoicesToAllocate(query);
return toInvoiceRowsList(invoiceToAllocates, evaluationDate);
}
public Optional<InvoiceRow> getInvoiceRowByInvoiceId(
@NonNull final InvoiceId invoiceId,
@NonNull final ZonedDateTime evaluationDate)
{
final List<InvoiceRow> invoiceRows = getInvoiceRowsListByInvoiceId(ImmutableList.of(invoiceId), evaluationDate);
if (invoiceRows.isEmpty())
{
return Optional.empty();
}
else if (invoiceRows.size() == 1)
{
return Optional.of(invoiceRows.get(0));
}
else
{
throw new AdempiereException("Expected only one row for " + invoiceId + " but got " + invoiceRows);
}
}
public List<PaymentRow> getPaymentRowsListByPaymentId(
@NonNull final Collection<PaymentId> paymentIds,
@NonNull final ZonedDateTime evaluationDate)
{
if (paymentIds.isEmpty())
{
return ImmutableList.of();
}
final PaymentToAllocateQuery query = PaymentToAllocateQuery.builder()
.evaluationDate(evaluationDate)
.additionalPaymentIdsToInclude(paymentIds)
.build();
return paymentAllocationRepo.retrievePaymentsToAllocate(query)
.stream()
.map(this::toPaymentRow)
.collect(ImmutableList.toImmutableList());
}
|
public Optional<PaymentRow> getPaymentRowByPaymentId(
@NonNull final PaymentId paymentId,
@NonNull final ZonedDateTime evaluationDate)
{
final List<PaymentRow> paymentRows = getPaymentRowsListByPaymentId(ImmutableList.of(paymentId), evaluationDate);
if (paymentRows.isEmpty())
{
return Optional.empty();
}
else if (paymentRows.size() == 1)
{
return Optional.of(paymentRows.get(0));
}
else
{
throw new AdempiereException("Expected only one row for " + paymentId + " but got " + paymentRows);
}
}
@Value
@Builder
private static class InvoiceRowLoadingContext
{
@NonNull ZonedDateTime evaluationDate;
@NonNull ImmutableSet<InvoiceId> invoiceIdsWithServiceInvoiceAlreadyGenetated;
public boolean isServiceInvoiceAlreadyGenerated(@NonNull final InvoiceId invoiceId)
{
return invoiceIdsWithServiceInvoiceAlreadyGenetated.contains(invoiceId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\PaymentAndInvoiceRowsRepo.java
| 1
|
请完成以下Java代码
|
private MInOutLine[] createShipmentLines(MRMA rma, MInOut shipment)
{
ArrayList<MInOutLine> shipLineList = new ArrayList<MInOutLine>();
MRMALine rmaLines[] = rma.getLines(true);
for (MRMALine rmaLine : rmaLines)
{
if (rmaLine.getM_InOutLine_ID() != 0)
{
MInOutLine shipLine = new MInOutLine(shipment);
shipLine.setM_RMALine_ID(rmaLine.get_ID());
shipLine.setLine(rmaLine.getLine());
shipLine.setDescription(rmaLine.getDescription());
shipLine.setM_Product_ID(rmaLine.getM_Product_ID());
Services.get(IAttributeSetInstanceBL.class).cloneASI(shipLine, rmaLine);
// shipLine.setM_AttributeSetInstance_ID(rmaLine.getM_AttributeSetInstance_ID());
shipLine.setC_UOM_ID(rmaLine.getC_UOM_ID());
shipLine.setQty(rmaLine.getQty());
shipLine.setM_Locator_ID(rmaLine.getM_Locator_ID());
shipLine.setC_Project_ID(rmaLine.getC_Project_ID());
shipLine.setC_Campaign_ID(rmaLine.getC_Campaign_ID());
shipLine.setC_Activity_ID(rmaLine.getC_Activity_ID());
shipLine.setC_Order_ID(rmaLine.getC_Order_ID());
shipLine.setC_ProjectPhase_ID(rmaLine.getC_ProjectPhase_ID());
shipLine.setC_ProjectTask_ID(rmaLine.getC_ProjectTask_ID());
shipLine.setUser1_ID(rmaLine.getUser1_ID());
shipLine.setUser2_ID(rmaLine.getUser2_ID());
shipLine.saveEx();
shipLineList.add(shipLine);
//
// Link to corresponding Invoice Line (if any) - teo_sarca [ 2818523 ]
// The MMatchInv records will be automatically generated on MInOut.completeIt()
final MInvoiceLine invoiceLine = new Query(shipment.getCtx(), MInvoiceLine.Table_Name,
MInvoiceLine.COLUMNNAME_M_RMALine_ID + "=?",
shipment.get_TrxName())
.setParameters(new Object[] { rmaLine.getM_RMALine_ID() })
.firstOnly(MInvoiceLine.class);
if (invoiceLine != null)
{
invoiceLine.setM_InOutLine_ID(shipLine.getM_InOutLine_ID());
invoiceLine.saveEx();
}
}
}
MInOutLine shipLines[] = new MInOutLine[shipLineList.size()];
shipLineList.toArray(shipLines);
return shipLines;
}
private void generateShipment(int M_RMA_ID)
{
MRMA rma = new MRMA(getCtx(), M_RMA_ID, get_TrxName());
MInOut shipment = createShipment(rma);
|
MInOutLine shipmentLines[] = createShipmentLines(rma, shipment);
if (shipmentLines.length == 0)
{
log.warn("No shipment lines created: M_RMA_ID="
+ M_RMA_ID + ", M_InOut_ID=" + shipment.get_ID());
}
StringBuffer processMsg = new StringBuffer(shipment.getDocumentNo());
if (!shipment.processIt(p_docAction))
{
processMsg.append(" (NOT Processed)");
log.warn("Shipment Processing failed: " + shipment + " - " + shipment.getProcessMsg());
}
if (!shipment.save())
{
throw new IllegalStateException("Could not update shipment");
}
// Add processing information to process log
addLog(shipment.getM_InOut_ID(), shipment.getMovementDate(), null, processMsg.toString());
m_created++;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\process\InOutGenerateRMA.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAdminId() {
return adminId;
}
public void setAdminId(Long adminId) {
this.adminId = adminId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUserAgent() {
return userAgent;
}
|
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", adminId=").append(adminId);
sb.append(", createTime=").append(createTime);
sb.append(", ip=").append(ip);
sb.append(", address=").append(address);
sb.append(", userAgent=").append(userAgent);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsAdminLoginLog.java
| 1
|
请完成以下Java代码
|
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Prefix.
@param Prefix
Prefix before the sequence number
*/
public void setPrefix (String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix);
}
/** Get Prefix.
@return Prefix before the sequence number
*/
public String getPrefix ()
{
return (String)get_Value(COLUMNNAME_Prefix);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Remote Client.
@param Remote_Client_ID
Remote Client to be used to replicate / synchronize data with.
*/
public void setRemote_Client_ID (int Remote_Client_ID)
{
if (Remote_Client_ID < 1)
set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Remote_Client_ID, Integer.valueOf(Remote_Client_ID));
}
|
/** Get Remote Client.
@return Remote Client to be used to replicate / synchronize data with.
*/
public int getRemote_Client_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Client_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Remote Organization.
@param Remote_Org_ID
Remote Organization to be used to replicate / synchronize data with.
*/
public void setRemote_Org_ID (int Remote_Org_ID)
{
if (Remote_Org_ID < 1)
set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Remote_Org_ID, Integer.valueOf(Remote_Org_ID));
}
/** Get Remote Organization.
@return Remote Organization to be used to replicate / synchronize data with.
*/
public int getRemote_Org_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Remote_Org_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Replication.java
| 1
|
请完成以下Java代码
|
public User findById(Long id) {
return userRepo.findOne(id);
}
@Override
public User findBySample(User sample) {
return userRepo.findOne(whereSpec(sample));
}
@Override
public List<User> findAll() {
return userRepo.findAll();
}
@Override
public List<User> findAll(User sample) {
return userRepo.findAll(whereSpec(sample));
}
@Override
public Page<User> findAll(PageRequest pageRequest) {
return userRepo.findAll(pageRequest);
}
@Override
public Page<User> findAll(User sample, PageRequest pageRequest) {
return userRepo.findAll(whereSpec(sample), pageRequest);
}
private Specification<User> whereSpec(final User sample){
return (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
if (sample.getId()!=null){
|
predicates.add(cb.equal(root.<Long>get("id"), sample.getId()));
}
if (StringUtils.hasLength(sample.getUsername())){
predicates.add(cb.equal(root.<String>get("username"),sample.getUsername()));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User sample = new User();
sample.setUsername(username);
User user = findBySample(sample);
if( user == null ){
throw new UsernameNotFoundException(String.format("User with username=%s was not found", username));
}
return user;
}
}
|
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\UserService.java
| 1
|
请完成以下Java代码
|
public class CachingAndArtifactsManager {
/**
* Ensures that the definition is cached in the appropriate places, including the deployment's collection of deployed artifacts and the deployment manager's cache.
*/
public void updateCachingAndArtifacts(ParsedDeployment parsedDeployment) {
final DmnEngineConfiguration dmnEngineConfiguration = CommandContextUtil.getDmnEngineConfiguration();
DeploymentCache<DecisionCacheEntry> decisionCache = dmnEngineConfiguration.getDeploymentManager().getDecisionCache();
DmnDeploymentEntity deployment = parsedDeployment.getDeployment();
for (DecisionEntity decisionEntity : parsedDeployment.getAllDecisions()) {
DmnDefinition dmnDefinition = parsedDeployment.getDmnDefinitionForDecision(decisionEntity);
DecisionCacheEntry cacheEntry;
if (!dmnDefinition.getDecisionServices().isEmpty()) {
|
DecisionService decisionService = parsedDeployment.getDecisionServiceForDecisionEntity(decisionEntity);
cacheEntry = new DecisionCacheEntry(decisionEntity, dmnDefinition, decisionService);
} else {
Decision decision = parsedDeployment.getDecisionForDecisionEntity(decisionEntity);
cacheEntry = new DecisionCacheEntry(decisionEntity, dmnDefinition, decision);
}
decisionCache.add(decisionEntity.getId(), cacheEntry);
// Add to deployment for further usage
deployment.addDeployedArtifact(decisionEntity);
deployment.addDecisionCacheEntry(decisionEntity.getId(), cacheEntry);
}
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\deployer\CachingAndArtifactsManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Clob createClob() throws SQLException
{
return delegate.createClob();
}
@Override
public Blob createBlob() throws SQLException
{
return delegate.createBlob();
}
@Override
public NClob createNClob() throws SQLException
{
return delegate.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException
{
return delegate.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException
{
return delegate.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException
{
delegate.setClientInfo(name, value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
delegate.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException
{
return delegate.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException
{
return delegate.getClientInfo();
|
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException
{
return delegate.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
return delegate.createStruct(typeName, attributes);
}
@Override
public void setSchema(String schema) throws SQLException
{
delegate.setSchema(schema);
}
@Override
public String getSchema() throws SQLException
{
return delegate.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException
{
delegate.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
delegate.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException
{
return delegate.getNetworkTimeout();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperJdbcConnection.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public I_AD_Sequence retrieveTableSequenceOrNull(@NonNull final Properties ctx, @NonNull final String tableName, @Nullable final String trxName)
{
final IQueryBuilder<I_AD_Sequence> queryBuilder = queryBL
.createQueryBuilder(I_AD_Sequence.class, ctx, trxName);
final ICompositeQueryFilter<I_AD_Sequence> filters = queryBuilder.getCompositeFilter();
filters.addEqualsFilter(I_AD_Sequence.COLUMNNAME_Name, tableName, UpperCaseQueryFilterModifier.instance);
filters.addEqualsFilter(I_AD_Sequence.COLUMNNAME_IsTableID, true);
filters.addEqualsFilter(I_AD_Sequence.COLUMNNAME_AD_Client_ID, IClientDAO.SYSTEM_CLIENT_ID);
return queryBuilder.create()
.firstOnly(I_AD_Sequence.class);
}
@Nullable
@Override
public I_AD_Sequence retrieveTableSequenceOrNull(@NonNull final Properties ctx, @NonNull final String tableName)
{
final String trxName = ITrx.TRXNAME_None;
return retrieveTableSequenceOrNull(ctx, tableName, trxName);
}
@Override
public ITableSequenceChecker createTableSequenceChecker(final Properties ctx)
{
return new TableSequenceChecker(ctx);
}
@Override
public void renameTableSequence(final Properties ctx, final String tableNameOld, final String tableNameNew)
{
//
// Rename the AD_Sequence
final I_AD_Sequence adSequence = retrieveTableSequenceOrNull(ctx, tableNameOld, ITrx.TRXNAME_ThreadInherited);
if (adSequence != null)
{
adSequence.setName(tableNameNew);
InterfaceWrapperHelper.save(adSequence);
}
//
// Rename the database native sequence
{
|
final String dbSequenceNameOld = DB.getTableSequenceName(tableNameOld);
final String dbSequenceNameNew = DB.getTableSequenceName(tableNameNew);
DB.getDatabase().renameSequence(dbSequenceNameOld, dbSequenceNameNew);
}
}
@Override
@NonNull
public Optional<I_AD_Sequence> retrieveSequenceByName(@NonNull final String sequenceName, @NonNull final ClientId clientId)
{
return queryBL
.createQueryBuilder(I_AD_Sequence.class)
.addEqualsFilter(I_AD_Sequence.COLUMNNAME_Name, sequenceName)
.addEqualsFilter(I_AD_Sequence.COLUMNNAME_AD_Client_ID, clientId)
.addEqualsFilter(I_AD_Sequence.COLUMNNAME_IsTableID, false)
.addOnlyActiveRecordsFilter()
.create()
.firstOptional(I_AD_Sequence.class);
}
@Override
public DocSequenceId cloneToOrg(@NonNull final DocSequenceId fromDocSequenceId, @NonNull final OrgId toOrgId)
{
final I_AD_Sequence fromSequence = InterfaceWrapperHelper.load(fromDocSequenceId, I_AD_Sequence.class);
final I_AD_Sequence newSequence = InterfaceWrapperHelper.copy()
.setFrom(fromSequence)
.setSkipCalculatedColumns(true)
.copyToNew(I_AD_Sequence.class);
newSequence.setAD_Org_ID(toOrgId.getRepoId());
newSequence.setCurrentNext(100000);
InterfaceWrapperHelper.save(newSequence);
return DocSequenceId.ofRepoId(newSequence.getAD_Sequence_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\SequenceDAO.java
| 2
|
请完成以下Java代码
|
protected void setLocalizationProperty(
String language,
String id,
String propertyName,
String propertyValue,
ObjectNode infoNode
) {
ObjectNode localizationNode = createOrGetLocalizationNode(infoNode);
if (!localizationNode.has(language)) {
localizationNode.putObject(language);
}
ObjectNode languageNode = (ObjectNode) localizationNode.get(language);
if (!languageNode.has(id)) {
languageNode.putObject(id);
|
}
((ObjectNode) languageNode.get(id)).put(propertyName, propertyValue);
}
protected ObjectNode createOrGetLocalizationNode(ObjectNode infoNode) {
if (!infoNode.has(LOCALIZATION_NODE)) {
infoNode.putObject(LOCALIZATION_NODE);
}
return (ObjectNode) infoNode.get(LOCALIZATION_NODE);
}
protected ObjectNode getLocalizationNode(ObjectNode infoNode) {
return (ObjectNode) infoNode.get(LOCALIZATION_NODE);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DynamicBpmnServiceImpl.java
| 1
|
请完成以下Java代码
|
public void apply(final Document document, final JSONDocumentField jsonField)
{
if (!jsonField.isReadonly())
{
if (isReadonly(document))
{
jsonField.setReadonly(true, "no document access");
return;
}
}
// TODO: check column level access
}
public void apply(final DocumentPath documentPath, final JSONDocumentField jsonField)
{
// TODO: apply JSONDocumentPermissions to fields
// atm it's not so important because user cannot reach in that situation,
// because he/she cannot update the document in that case.
}
public void apply(final Document document, final JSONIncludedTabInfo jsonIncludedTabInfo)
{
if (isReadonly(document))
{
jsonIncludedTabInfo.setAllowCreateNew(false, "no document access");
jsonIncludedTabInfo.setAllowDelete(false, "no document access");
}
}
public void apply(final DocumentPath documentPath, final JSONIncludedTabInfo jsonIncludedTabInfo)
{
// TODO: implement... but it's not so critical atm
}
private boolean isReadonly(@NonNull final Document document)
{
return readonlyDocuments.computeIfAbsent(document.getDocumentPath(), documentPath -> !DocumentPermissionsHelper.canEdit(document, permissions));
}
public DocumentFieldLogicExpressionResultRevaluator getLogicExpressionResultRevaluator()
{
DocumentFieldLogicExpressionResultRevaluator logicExpressionRevaluator = this.logicExpressionRevaluator;
if (logicExpressionRevaluator == null)
{
logicExpressionRevaluator = this.logicExpressionRevaluator = DocumentFieldLogicExpressionResultRevaluator.using(permissions);
}
return logicExpressionRevaluator;
}
public Set<DocumentStandardAction> getStandardActions(@NonNull final Document document)
{
final HashSet<DocumentStandardAction> standardActions = new HashSet<>(document.getStandardActions());
Boolean allowWindowEdit = null;
|
Boolean allowDocumentEdit = null;
for (final Iterator<DocumentStandardAction> it = standardActions.iterator(); it.hasNext(); )
{
final DocumentStandardAction action = it.next();
if (action.isDocumentWriteAccessRequired())
{
if (allowDocumentEdit == null)
{
allowDocumentEdit = DocumentPermissionsHelper.canEdit(document, permissions);
}
if (!allowDocumentEdit)
{
it.remove();
continue;
}
}
if (action.isWindowWriteAccessRequired())
{
if (allowWindowEdit == null)
{
final DocumentEntityDescriptor entityDescriptor = document.getEntityDescriptor();
final AdWindowId adWindowId = entityDescriptor.getDocumentType().isWindow()
? entityDescriptor.getWindowId().toAdWindowId()
: null;
allowWindowEdit = adWindowId != null && permissions.checkWindowPermission(adWindowId).hasWriteAccess();
}
if (!allowWindowEdit)
{
it.remove();
//noinspection UnnecessaryContinue
continue;
}
}
}
return ImmutableSet.copyOf(standardActions);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPermissions.java
| 1
|
请完成以下Java代码
|
public void deployResources(final String deploymentNameHint, final Resource[] resources, final RepositoryService repositoryService) {
// Create a deployment for each distinct parent folder using the name
// hint
// as a prefix
final Map<String, Set<Resource>> resourcesMap = createMap(resources);
for (final Entry<String, Set<Resource>> group : resourcesMap.entrySet()) {
final String deploymentName = determineDeploymentName(deploymentNameHint, group.getKey());
final DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentName);
for (final Resource resource : group.getValue()) {
final String resourceName = determineResourceName(resource);
try {
if (resourceName.endsWith(".bar") || resourceName.endsWith(".zip") || resourceName.endsWith(".jar")) {
deploymentBuilder.addZipInputStream(new ZipInputStream(resource.getInputStream()));
} else {
deploymentBuilder.addInputStream(resourceName, resource.getInputStream());
}
} catch (IOException e) {
throw new ActivitiException("couldn't auto deploy resource '" + resource + "': " + e.getMessage(), e);
}
}
deploymentBuilder.deploy();
}
}
private Map<String, Set<Resource>> createMap(final Resource[] resources) {
final Map<String, Set<Resource>> resourcesMap = new HashMap<>();
for (final Resource resource : resources) {
final String parentFolderName = determineGroupName(resource);
if (resourcesMap.get(parentFolderName) == null) {
resourcesMap.put(parentFolderName, new HashSet<>());
}
resourcesMap.get(parentFolderName).add(resource);
}
return resourcesMap;
}
|
private String determineGroupName(final Resource resource) {
String result = determineResourceName(resource);
try {
if (resourceParentIsDirectory(resource)) {
result = resource.getFile().getParentFile().getName();
}
} catch (IOException e) {
// no-op, fallback to resource name
}
return result;
}
private boolean resourceParentIsDirectory(final Resource resource) throws IOException {
return resource.getFile() != null && resource.getFile().getParentFile() != null && resource.getFile().getParentFile().isDirectory();
}
private String determineDeploymentName(final String deploymentNameHint, final String groupName) {
return String.format(DEPLOYMENT_NAME_PATTERN, deploymentNameHint, groupName);
}
}
|
repos\flowable-engine-main\modules\flowable5-spring\src\main\java\org\activiti\spring\autodeployment\ResourceParentFolderAutoDeploymentStrategy.java
| 1
|
请完成以下Java代码
|
public @Nullable Set<Session.SessionTrackingMode> getTrackingModes() {
return this.trackingModes;
}
public void setTrackingModes(@Nullable Set<Session.SessionTrackingMode> trackingModes) {
this.trackingModes = trackingModes;
}
/**
* Return whether to persist session data between restarts.
* @return {@code true} to persist session data between restarts.
*/
public boolean isPersistent() {
return this.persistent;
}
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
/**
* Return the directory used to store session data.
* @return the session data store directory
*/
public @Nullable File getStoreDir() {
return this.storeDir;
}
public void setStoreDir(@Nullable File storeDir) {
this.sessionStoreDirectory.setDirectory(storeDir);
this.storeDir = storeDir;
}
public Cookie getCookie() {
return this.cookie;
}
public SessionStoreDirectory getSessionStoreDirectory() {
return this.sessionStoreDirectory;
}
/**
|
* Available session tracking modes (mirrors
* {@link jakarta.servlet.SessionTrackingMode}).
*/
public enum SessionTrackingMode {
/**
* Send a cookie in response to the client's first request.
*/
COOKIE,
/**
* Rewrite the URL to append a session ID.
*/
URL,
/**
* Use SSL build-in mechanism to track the session.
*/
SSL
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\Session.java
| 1
|
请完成以下Java代码
|
private static void handleRequests(List<ClientConnection> clientConnections) {
Iterator<ClientConnection> iterator = clientConnections.iterator();
while (iterator.hasNext()) {
ClientConnection client = iterator.next();
if (client.getSocket()
.isClosed()) {
logger.info("Client disconnected: {}", client.getSocket()
.getInetAddress());
iterator.remove();
continue;
}
try {
BufferedReader reader = client.getReader();
if (reader.ready()) {
String request = reader.readLine();
if (request != null) {
new ThreadPerRequest(client.getWriter(), request).start();
}
|
}
} catch (IOException e) {
logger.error("Error reading from client {}", client.getSocket()
.getInetAddress(), e);
}
}
}
private static void closeClientConnection(List<ClientConnection> clientConnections) {
for (ClientConnection client : clientConnections) {
try {
client.close();
} catch (IOException e) {
logger.error("Error closing client connection", e);
}
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-sockets\src\main\java\com\baeldung\threading\request\ThreadPerRequestServer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public TaskResponse getTaskById(@PathVariable("id") String id) {
Task task = taskRepository.getTaskById(id);
if (task == null) {
throw new UnknownTaskException();
}
return buildResponse(task);
}
private TaskResponse buildResponse(Task task) {
return new TaskResponse(task.id(), task.title(), task.created(), getUser(task.createdBy()), getUser(task.assignedTo()), task.status());
}
private UserResponse getUser(String userId) {
if (userId == null) {
return null;
|
}
var user = userRepository.getUserById(userId);
if (user == null) {
return null;
}
return new UserResponse(user.id(), user.name());
}
@ExceptionHandler(UnknownTaskException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleUnknownTask() {
}
}
|
repos\tutorials-master\lightrun\lightrun-api-service\src\main\java\com\baeldung\apiservice\adapters\http\TasksController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public R submit(@Valid @RequestBody Role role, BladeUser user) {
CacheUtil.clear(SYS_CACHE);
if (Func.isEmpty(role.getId())) {
role.setTenantId(user.getTenantId());
}
return R.status(roleService.saveOrUpdate(role));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 6)
@Operation(summary = "删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
|
CacheUtil.clear(SYS_CACHE);
return R.status(roleService.removeByIds(Func.toLongList(ids)));
}
/**
* 设置菜单权限
*/
@PostMapping("/grant")
@ApiOperationSupport(order = 7)
@Operation(summary = "权限设置", description = "传入roleId集合以及menuId集合")
public R grant(@RequestBody GrantVO grantVO) {
CacheUtil.clear(SYS_CACHE);
boolean temp = roleService.grant(grantVO.getRoleIds(), grantVO.getMenuIds(), grantVO.getDataScopeIds());
return R.status(temp);
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RoleController.java
| 2
|
请完成以下Java代码
|
private static void mergeIfPossible(Map<String, Object> source, MutablePropertySources sources,
Map<String, Object> resultingSource) {
PropertySource<?> existingSource = sources.get(NAME);
if (existingSource != null) {
Object underlyingSource = existingSource.getSource();
if (underlyingSource instanceof Map) {
resultingSource.putAll((Map<String, Object>) underlyingSource);
}
resultingSource.putAll(source);
}
}
/**
* Move the 'defaultProperties' property source so that it's the last source in the
* given {@link ConfigurableEnvironment}.
* @param environment the environment to update
*/
public static void moveToEnd(ConfigurableEnvironment environment) {
|
moveToEnd(environment.getPropertySources());
}
/**
* Move the 'defaultProperties' property source so that it's the last source in the
* given {@link MutablePropertySources}.
* @param propertySources the property sources to update
*/
public static void moveToEnd(MutablePropertySources propertySources) {
PropertySource<?> propertySource = propertySources.remove(NAME);
if (propertySource != null) {
propertySources.addLast(propertySource);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\DefaultPropertiesPropertySource.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private @Nullable String cleanContextPath(@Nullable String contextPath) {
String candidate = null;
if (StringUtils.hasLength(contextPath)) {
candidate = contextPath.strip();
}
if (StringUtils.hasText(candidate) && candidate.endsWith("/")) {
return candidate.substring(0, candidate.length() - 1);
}
return candidate;
}
public String getApplicationDisplayName() {
return this.applicationDisplayName;
}
public void setApplicationDisplayName(String displayName) {
this.applicationDisplayName = displayName;
}
public boolean isRegisterDefaultServlet() {
return this.registerDefaultServlet;
}
public void setRegisterDefaultServlet(boolean registerDefaultServlet) {
this.registerDefaultServlet = registerDefaultServlet;
}
public Map<String, String> getContextParameters() {
return this.contextParameters;
}
public Encoding getEncoding() {
return this.encoding;
}
public Jsp getJsp() {
return this.jsp;
}
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie();
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
|
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ValidatingItemProcessorDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private ListItemReader<TestData> simpleReader;
@Bean
public Job validatingItemProcessorJob() {
return jobBuilderFactory.get("validatingItemProcessorJob")
.start(step())
.build();
}
private Step step() {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(simpleReader)
.processor(validatingItemProcessor())
|
.writer(list -> list.forEach(System.out::println))
.build();
}
private ValidatingItemProcessor<TestData> validatingItemProcessor() {
ValidatingItemProcessor<TestData> processor = new ValidatingItemProcessor<>();
processor.setValidator(value -> {
// 对每一条数据进行校验
if ("".equals(value.getField3())) {
// 如果field3的值为空串,则抛异常
throw new ValidationException("field3的值不合法");
}
});
return processor;
}
}
|
repos\SpringAll-master\70.spring-batch-itemprocessor\src\main\java\cc\mrbird\batch\entity\job\ValidatingItemProcessorDemo.java
| 2
|
请完成以下Spring Boot application配置
|
spring.profiles.active=dev
logging.level.org.springframework.web.servlet=DEBUG
app.name=in28Minutes
welcome.message=Welcome message from property file! Welcome to ${a
|
pp.name}
basic.value=true
basic.message=Dynamic Message
basic.number=100
|
repos\spring-boot-examples-master\spring-boot-kotlin-basics-configuration\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public class CommissionSettlementShare
{
/** a settlement share doesn't make sense without a sales commission share. */
private CommissionShareId salesCommissionShareId;
@Setter(AccessLevel.NONE)
private CommissionPoints pointsToSettleSum;
@Setter(AccessLevel.NONE)
private CommissionPoints settledPointsSum;
/** Chronological list of facts that make it clear what happened when */
private final ArrayList<CommissionSettlementFact> facts;
@JsonCreator
@Builder
private CommissionSettlementShare(
@JsonProperty("salesCommissionShareId") @NonNull final CommissionShareId salesCommissionShareId,
@JsonProperty("facts") @NonNull final List<CommissionSettlementFact> facts)
{
this.salesCommissionShareId = salesCommissionShareId;
this.facts = new ArrayList<>();
this.pointsToSettleSum = CommissionPoints.ZERO;
this.settledPointsSum = CommissionPoints.ZERO;
for (final CommissionSettlementFact fact : facts)
{
addFact(fact);
}
}
public CommissionSettlementShare addFact(@NonNull final CommissionSettlementFact fact)
{
facts.add(fact);
switch (fact.getState())
{
|
case TO_SETTLE:
pointsToSettleSum = pointsToSettleSum.add(fact.getPoints());
break;
case SETTLED:
settledPointsSum = settledPointsSum.add(fact.getPoints());
break;
default:
throw new AdempiereException("fact has unsupported state " + fact.getState())
.appendParametersToMessage()
.setParameter("fact", fact);
}
return this;
}
public ImmutableList<CommissionSettlementFact> getFacts()
{
return ImmutableList.copyOf(facts);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\settlement\CommissionSettlementShare.java
| 1
|
请完成以下Java代码
|
private void validateUOM(@NonNull final I_C_OLCand olCand)
{
final ProductId productId = olCandEffectiveValuesBL.getM_Product_Effective_ID(olCand);
final I_C_UOM targetUOMRecord = olCandEffectiveValuesBL.getC_UOM_Effective(olCand);
if (uomsDAO.isUOMForTUs(UomId.ofRepoId(targetUOMRecord.getC_UOM_ID())))
{
if (olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand).signum() <= 0)
{
throw new AdempiereException(ERR_ITEM_CAPACITY_NOT_FOUND);
}
return;
}
final BigDecimal convertedQty = uomConversionBL.convertToProductUOM(
|
productId,
targetUOMRecord,
olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand));
if (convertedQty == null)
{
final String productName = productBL.getProductName(productId);
final String productValue = productBL.getProductValue(productId);
final String productX12de355 = productBL.getStockUOM(productId).getX12DE355();
final String targetX12de355 = targetUOMRecord.getX12DE355();
throw new AdempiereException(MSG_NO_UOM_CONVERSION, productValue + "_" + productName, productX12de355, targetX12de355).markAsUserValidationError();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\DefaultOLCandValidator.java
| 1
|
请完成以下Java代码
|
public ModificationBuilder createModification(String processDefinitionId) {
return new ModificationBuilderImpl(commandExecutor, processDefinitionId);
}
@Override
public RestartProcessInstanceBuilder restartProcessInstances(String processDefinitionId) {
return new RestartProcessInstanceBuilderImpl(commandExecutor, processDefinitionId);
}
@Override
public Incident createIncident(String incidentType, String executionId, String configuration) {
return createIncident(incidentType, executionId, configuration, null);
}
@Override
public Incident createIncident(String incidentType, String executionId, String configuration, String message) {
return commandExecutor.execute(new CreateIncidentCmd(incidentType, executionId, configuration, message));
}
|
@Override
public void resolveIncident(String incidentId) {
commandExecutor.execute(new ResolveIncidentCmd(incidentId));
}
@Override
public void setAnnotationForIncidentById(String incidentId, String annotation) {
commandExecutor.execute(new SetAnnotationForIncidentCmd(incidentId, annotation));
}
@Override
public void clearAnnotationForIncidentById(String incidentId) {
commandExecutor.execute(new SetAnnotationForIncidentCmd(incidentId, null));
}
@Override
public ConditionEvaluationBuilder createConditionEvaluation() {
return new ConditionEvaluationBuilderImpl(commandExecutor);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RuntimeServiceImpl.java
| 1
|
请完成以下Java代码
|
private CountryId getCountryId(@NonNull final TaxQuery taxQuery)
{
if (taxQuery.getShippingCountryId() != null)
{
return taxQuery.getShippingCountryId();
}
final BPartnerLocationAndCaptureId bpartnerLocationId = taxQuery.getBPartnerLocationId();
if (bpartnerLocationId == null)
{
throw new AdempiereException("Invalid TaxQuery! None of TaxQuery.ShippingCountryId or TaxQuery.BPartnerLocationId set!")
.appendParametersToMessage()
.setParameter("TaxQuery", taxQuery);
}
if (bpartnerLocationId.getLocationCaptureId() != null)
{
return locationDAO.getCountryIdByLocationId(bpartnerLocationId.getLocationCaptureId());
}
final I_C_BPartner_Location bpartnerLocation = bPartnerDAO.getBPartnerLocationByIdEvenInactive(bpartnerLocationId.getBpartnerLocationId());
if (bpartnerLocation == null)
{
throw new AdempiereException("No location found for bpartnerLocationId: " + bpartnerLocationId);
}
|
return locationDAO.getCountryIdByLocationId(LocationId.ofRepoId(bpartnerLocation.getC_Location_ID()));
}
@Override
public Optional<TaxId> getIdByName(@NonNull final String name, @NonNull final ClientId clientId)
{
return queryBL.createQueryBuilder(I_C_Tax.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Tax.COLUMNNAME_Name, name)
.addEqualsFilter(I_C_Tax.COLUMNNAME_AD_Client_ID, clientId)
.create()
.firstIdOnlyOptional(TaxId::ofRepoIdOrNull);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\impl\TaxDAO.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) {
this.withoutProcessInstanceId = withoutProcessInstanceId;
}
public String getTaskCandidateGroup() {
return taskCandidateGroup;
}
public void setTaskCandidateGroup(String taskCandidateGroup) {
this.taskCandidateGroup = taskCandidateGroup;
}
public boolean isIgnoreTaskAssignee() {
return ignoreTaskAssignee;
}
public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) {
this.ignoreTaskAssignee = ignoreTaskAssignee;
}
public String getPlanItemInstanceId() {
return planItemInstanceId;
}
public void setPlanItemInstanceId(String planItemInstanceId) {
this.planItemInstanceId = planItemInstanceId;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
|
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceQueryRequest.java
| 2
|
请完成以下Java代码
|
public class SimpleObjectSerializer
{
private static final SimpleObjectSerializer INSTANCE = new SimpleObjectSerializer();
private final ObjectMapper objectMapper;
private SimpleObjectSerializer()
{
objectMapper = JsonObjectMapperHolder.newJsonObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static SimpleObjectSerializer get()
{
return INSTANCE;
}
public String serialize(final Object event)
{
try
{
return objectMapper.writeValueAsString(event);
|
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
public <T> T deserialize(final String eventJson, final Class<T> clazz)
{
try
{
return objectMapper.readValue(eventJson, clazz);
}
catch (final IOException e)
{
throw new RuntimeException(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\SimpleObjectSerializer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonAlbertaOrderLineInfo
{
@JsonProperty("externalId")
@NonNull
String externalId;
@JsonProperty("salesLineId")
@Nullable
String salesLineId;
@JsonProperty("unit")
@Nullable
String unit;
@JsonProperty("isPrivateSale")
@Nullable
Boolean isPrivateSale;
@JsonProperty("isRentalEquipment")
|
@Nullable
Boolean isRentalEquipment;
@JsonProperty("updated")
@Nullable
Instant updated;
@JsonProperty("durationAmount")
@Nullable
BigDecimal durationAmount;
@JsonProperty("timePeriod")
@Nullable
BigDecimal timePeriod;
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-ordercandidates\src\main\java\de\metas\common\ordercandidates\v2\request\alberta\JsonAlbertaOrderLineInfo.java
| 2
|
请完成以下Java代码
|
public class ProcessEngineFactory {
protected ProcessEngineConfiguration processEngineConfiguration;
protected Bundle bundle;
protected ProcessEngineImpl processEngine;
public void init() throws Exception {
ClassLoader previous = Thread.currentThread().getContextClassLoader();
try {
ClassLoader cl = new BundleDelegatingClassLoader(bundle);
Thread.currentThread().setContextClassLoader(new ClassLoaderWrapper(cl, ProcessEngineFactory.class.getClassLoader(), ProcessEngineConfiguration.class.getClassLoader(), previous));
processEngineConfiguration.setClassLoader(cl);
processEngine = (ProcessEngineImpl) processEngineConfiguration.buildProcessEngine();
} finally {
Thread.currentThread().setContextClassLoader(previous);
}
}
public void destroy() throws Exception {
if (processEngine != null) {
processEngine.close();
|
}
}
public ProcessEngine getObject() throws Exception {
return processEngine;
}
public ProcessEngineConfiguration getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfiguration processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
public Bundle getBundle() {
return bundle;
}
public void setBundle(Bundle bundle) {
this.bundle = bundle;
}
}
|
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\blueprint\ProcessEngineFactory.java
| 1
|
请完成以下Java代码
|
public final class ReachabilityMetadataProperties {
/**
* Location of the properties file. Must be formatted using
* {@link String#format(String, Object...)} with the group id, artifact id and version
* of the dependency.
*/
public static final String REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE = "META-INF/native-image/%s/%s/%s/reachability-metadata.properties";
private final Properties properties;
private ReachabilityMetadataProperties(Properties properties) {
this.properties = properties;
}
/**
* Returns if the dependency has been overridden.
* @return true if the dependency has been overridden
*/
public boolean isOverridden() {
return Boolean.parseBoolean(this.properties.getProperty("override"));
}
/**
* Constructs a new instance from the given {@code InputStream}.
* @param inputStream {@code InputStream} to load the properties from
* @return loaded properties
* @throws IOException if loading from the {@code InputStream} went wrong
|
*/
public static ReachabilityMetadataProperties fromInputStream(InputStream inputStream) throws IOException {
Properties properties = new Properties();
properties.load(inputStream);
return new ReachabilityMetadataProperties(properties);
}
/**
* Returns the location of the properties for the given coordinates.
* @param coordinates library coordinates for which the property file location should
* be returned
* @return location of the properties
*/
public static String getLocation(LibraryCoordinates coordinates) {
return REACHABILITY_METADATA_PROPERTIES_LOCATION_TEMPLATE.formatted(coordinates.getGroupId(),
coordinates.getArtifactId(), coordinates.getVersion());
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\ReachabilityMetadataProperties.java
| 1
|
请完成以下Java代码
|
public void submitRejectedBatch(String engineName, List<String> jobIds) {
CollectionUtil.addToMapOfLists(rejectedJobBatchesByEngine, engineName, jobIds);
}
public void submitAcquiredJobs(String engineName, AcquiredJobs acquiredJobs) {
acquiredJobsByEngine.put(engineName, acquiredJobs);
}
public void submitAdditionalJobBatch(String engineName, List<String> jobIds) {
CollectionUtil.addToMapOfLists(additionalJobBatchesByEngine, engineName, jobIds);
}
public void reset() {
additionalJobBatchesByEngine.clear();
// jobs that were rejected in the previous acquisition cycle
// are to be resubmitted for execution in the current cycle
additionalJobBatchesByEngine.putAll(rejectedJobBatchesByEngine);
rejectedJobBatchesByEngine.clear();
acquiredJobsByEngine.clear();
acquisitionException = null;
acquisitionTime = 0;
isJobAdded = false;
}
/**
* @return true, if for all engines there were less jobs acquired than requested
*/
public boolean areAllEnginesIdle() {
for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) {
int jobsAcquired = acquiredJobs.getJobIdBatches().size() + acquiredJobs.getNumberOfJobsFailedToLock();
if (jobsAcquired >= acquiredJobs.getNumberOfJobsAttemptedToAcquire()) {
return false;
}
}
return true;
}
/**
* true if at least one job could not be locked, regardless of engine
*/
public boolean hasJobAcquisitionLockFailureOccurred() {
for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) {
if (acquiredJobs.getNumberOfJobsFailedToLock() > 0) {
return true;
}
}
return false;
}
// getters and setters
public void setAcquisitionTime(long acquisitionTime) {
this.acquisitionTime = acquisitionTime;
}
public long getAcquisitionTime() {
return acquisitionTime;
}
/**
* Jobs that were acquired in the current acquisition cycle.
* @return
*/
|
public Map<String, AcquiredJobs> getAcquiredJobsByEngine() {
return acquiredJobsByEngine;
}
/**
* Jobs that were rejected from execution in the acquisition cycle
* due to lacking execution resources.
* With an execution thread pool, these jobs could not be submitted due to
* saturation of the underlying job queue.
*/
public Map<String, List<List<String>>> getRejectedJobsByEngine() {
return rejectedJobBatchesByEngine;
}
/**
* Jobs that have been acquired in previous cycles and are supposed to
* be re-submitted for execution
*/
public Map<String, List<List<String>>> getAdditionalJobsByEngine() {
return additionalJobBatchesByEngine;
}
public void setAcquisitionException(Exception e) {
this.acquisitionException = e;
}
public Exception getAcquisitionException() {
return acquisitionException;
}
public void setJobAdded(boolean isJobAdded) {
this.isJobAdded = isJobAdded;
}
public boolean isJobAdded() {
return isJobAdded;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobAcquisitionContext.java
| 1
|
请完成以下Java代码
|
public abstract class TableItemImpl extends CmmnElementImpl implements TableItem {
protected static AttributeReferenceCollection<ApplicabilityRule> applicabilityRuleRefCollection;
protected static AttributeReferenceCollection<Role> authorizedRoleRefCollection;
public TableItemImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<ApplicabilityRule> getApplicabilityRule() {
return applicabilityRuleRefCollection.getReferenceTargetElements(this);
}
public Collection<Role> getAuthorizedRoles() {
return authorizedRoleRefCollection.getReferenceTargetElements(this);
}
public static void registerType(ModelBuilder modelBuilder) {
|
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(TableItem.class, CMMN_ELEMENT_TABLE_ITEM)
.namespaceUri(CMMN11_NS)
.abstractType()
.extendsType(CmmnElement.class);
applicabilityRuleRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_APPLICABILITY_RULE_REFS)
.idAttributeReferenceCollection(ApplicabilityRule.class, CmmnAttributeElementReferenceCollection.class)
.build();
authorizedRoleRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHORIZED_ROLE_REFS)
.idAttributeReferenceCollection(Role.class, CmmnAttributeElementReferenceCollection.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\TableItemImpl.java
| 1
|
请完成以下Java代码
|
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public TemplateType getType() {
return type;
}
public void setType(TemplateType type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TemplateDefinition that = (TemplateDefinition) o;
return (
Objects.equals(from, that.from) &&
Objects.equals(subject, that.subject) &&
type == that.type &&
|
Objects.equals(value, that.value)
);
}
@Override
public int hashCode() {
return Objects.hash(from, subject, type, value);
}
@Override
public String toString() {
return (
"TemplateDefinition{" +
"from='" +
from +
'\'' +
", subject='" +
subject +
'\'' +
", type=" +
type +
", value='" +
value +
'\'' +
'}'
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplateDefinition.java
| 1
|
请完成以下Java代码
|
private I_M_ProductPrice toProductPriceRecord(@NonNull final ProductPrice request)
{
final I_M_ProductPrice record = getRecordById(request.getProductPriceId());
record.setAD_Org_ID(request.getOrgId().getRepoId());
record.setM_Product_ID(request.getProductId().getRepoId());
record.setM_PriceList_Version_ID(request.getPriceListVersionId().getRepoId());
record.setPriceLimit(request.getPriceLimit());
record.setPriceList(request.getPriceList());
record.setPriceStd(request.getPriceStd());
record.setC_UOM_ID(request.getUomId().getRepoId());
record.setC_TaxCategory_ID(request.getTaxCategoryId().getRepoId());
record.setSeqNo(request.getSeqNo());
record.setIsActive(request.getIsActive());
return record;
}
|
@NonNull
private I_M_ProductPrice getRecordById(@NonNull final ProductPriceId productPriceId)
{
return queryBL
.createQueryBuilder(I_M_ProductPrice.class)
.addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_ProductPrice_ID, productPriceId.getRepoId())
.create()
.firstOnlyNotNull(I_M_ProductPrice.class);
}
@NonNull
public <T extends I_M_ProductPrice> T getRecordById(@NonNull final ProductPriceId productPriceId, @NonNull final Class<T> productPriceClass)
{
return InterfaceWrapperHelper.load(productPriceId, productPriceClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\productprice\ProductPriceRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RuleEngineTbQueueAdminFactory {
@Autowired(required = false)
private TbKafkaTopicConfigs kafkaTopicConfigs;
@Autowired(required = false)
private TbKafkaSettings kafkaSettings;
@ConditionalOnExpression("'${queue.type:null}'=='kafka'")
@Bean
public TbQueueAdmin createKafkaAdmin() {
return new TbKafkaAdmin(kafkaSettings, kafkaTopicConfigs.getRuleEngineConfigs());
}
@ConditionalOnExpression("'${queue.type:null}'=='in-memory'")
@Bean
public TbQueueAdmin createInMemoryAdmin() {
return new TbQueueAdmin() {
|
@Override
public void createTopicIfNotExists(String topic, String properties, boolean force) {
}
@Override
public void deleteTopic(String topic) {
}
@Override
public void destroy() {
}
};
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\RuleEngineTbQueueAdminFactory.java
| 2
|
请完成以下Java代码
|
public abstract class AbstractHitPolicy implements ContinueEvaluatingBehavior, ComposeRuleResultBehavior, ComposeDecisionResultBehavior {
protected boolean multipleResults = false;
public AbstractHitPolicy() {
}
public AbstractHitPolicy(boolean multipleResults) {
this.multipleResults = multipleResults;
}
/**
* Returns the name for the specific Hit Policy behavior
*/
public abstract String getHitPolicyName();
/**
* Default behavior for ContinueEvaluating behavior
*/
@Override
public boolean shouldContinueEvaluating(boolean ruleResult) {
return true;
}
/**
* Default behavior for ComposeRuleOutput behavior
*/
@Override
public void composeRuleResult(int ruleNumber, String outputName, Object outputValue, ELExecutionContext executionContext) {
executionContext.addRuleResult(ruleNumber, outputName, outputValue);
}
/**
|
* Default behavior for ComposeRuleOutput behavior
*/
@Override
public void composeDecisionResults(ELExecutionContext executionContext) {
List<Map<String, Object>> decisionResults = new ArrayList<>(executionContext.getRuleResults().values());
updateStackWithDecisionResults(decisionResults, executionContext);
DecisionExecutionAuditContainer auditContainer = executionContext.getAuditContainer();
auditContainer.setDecisionResult(decisionResults);
auditContainer.setMultipleResults(multipleResults);
}
@Override
public void updateStackWithDecisionResults(List<Map<String, Object>> decisionResults, ELExecutionContext executionContext) {
decisionResults.forEach(result -> result.forEach((k, v) -> executionContext.getStackVariables().put(k, v)));
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\AbstractHitPolicy.java
| 1
|
请完成以下Java代码
|
public class SendTask extends TaskWithFieldExtensions {
protected String type;
protected String implementationType;
protected String operationRef;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getOperationRef() {
return operationRef;
}
public void setOperationRef(String operationRef) {
this.operationRef = operationRef;
}
|
public SendTask clone() {
SendTask clone = new SendTask();
clone.setValues(this);
return clone;
}
public void setValues(SendTask otherElement) {
super.setValues(otherElement);
setType(otherElement.getType());
setImplementationType(otherElement.getImplementationType());
setOperationRef(otherElement.getOperationRef());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SendTask.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* Gets the value of the party property.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getParty() {
return party;
}
/**
* Sets the value of the party property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setParty(String value) {
this.party = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\GroupDescriptionType.java
| 2
|
请完成以下Java代码
|
public static IAutoCloseable temporaryForceSendingChangeEventsIf(final boolean condition)
{
return forceSendChangeEventsThreadLocal.temporarySetToTrueIf(condition);
}
private static boolean isForceSendingChangeEvents()
{
return forceSendChangeEventsThreadLocal.isTrue();
}
private IEventBus getEventBus() {return eventBusFactory.getEventBus(EVENTS_TOPIC);}
private void handleEvent(@NonNull final SumUpTransactionStatusChangedEvent event)
{
fireLocalListeners(event);
}
private void fireLocalListeners(final @NonNull SumUpTransactionStatusChangedEvent event)
{
try (final IAutoCloseable ignored = Env.switchContext(newTemporaryCtx(event)))
{
statusChangedListeners.forEach(listener -> listener.onStatusChanged(event));
}
}
private static Properties newTemporaryCtx(final @NonNull SumUpTransactionStatusChangedEvent event)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, event.getClientId());
Env.setOrgId(ctx, event.getOrgId());
return ctx;
}
private void fireLocalAndRemoteListenersAfterTrxCommit(final @NonNull SumUpTransactionStatusChangedEvent event)
{
trxManager.accumulateAndProcessAfterCommit(
SumUpEventsDispatcher.class.getSimpleName(),
ImmutableList.of(event),
this::fireLocalAndRemoteListenersNow);
}
private void fireLocalAndRemoteListenersNow(@NonNull final List<SumUpTransactionStatusChangedEvent> events)
{
final IEventBus eventBus = getEventBus();
// NOTE: we don't have to fireLocalListeners
// because we assume we will also get back this event and then we will handle it
events.forEach(eventBus::enqueueObject);
}
|
public void fireNewTransaction(@NonNull final SumUpTransaction trx)
{
fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofNewTransaction(trx));
}
public void fireStatusChangedIfNeeded(
@NonNull final SumUpTransaction trx,
@NonNull final SumUpTransaction trxPrev)
{
if (!isForceSendingChangeEvents() && hasChanges(trx, trxPrev))
{
return;
}
fireLocalAndRemoteListenersAfterTrxCommit(SumUpTransactionStatusChangedEvent.ofChangedTransaction(trx, trxPrev));
}
private static boolean hasChanges(final @NonNull SumUpTransaction trx, final @NonNull SumUpTransaction trxPrev)
{
return SumUpTransactionStatus.equals(trx.getStatus(), trxPrev.getStatus())
&& trx.isRefunded() == trxPrev.isRefunded();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\SumUpEventsDispatcher.java
| 1
|
请完成以下Java代码
|
public String getSalt() {
return salt;
}
/**
* 设置 md5密码盐.
*
* @param salt md5密码盐.
*/
public void setSalt(String salt) {
this.salt = salt;
}
/**
* 获取 联系电话.
*
* @return 联系电话.
*/
public String getPhone() {
return phone;
}
/**
* 设置 联系电话.
*
* @param phone 联系电话.
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* 获取 备注.
*
* @return 备注.
*/
public String getTips() {
return tips;
}
/**
* 设置 备注.
*
* @param tips 备注.
*/
public void setTips(String tips) {
this.tips = tips;
}
/**
* 获取 状态 1:正常 2:禁用.
*
* @return 状态 1:正常 2:禁用.
*/
public Integer getState() {
return state;
}
/**
|
* 设置 状态 1:正常 2:禁用.
*
* @param state 状态 1:正常 2:禁用.
*/
public void setState(Integer state) {
this.state = state;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
}
|
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Manager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JobInitializer implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private ApplicationJobRepository jobRepository;
@Autowired
private Scheduler scheduler;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
for (ApplicationJob job : jobRepository.findAll()) {
if (job.isEnabled() && (job.getCompleted() == null || !job.getCompleted())) {
JobDetail detail = JobBuilder.newJob(SampleJob.class)
.withIdentity(job.getName(), "appJobs")
.storeDurably()
.build();
|
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(detail)
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(30)
.repeatForever())
.build();
try {
scheduler.scheduleJob(detail, trigger);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
}
}
}
}
|
repos\tutorials-master\spring-quartz\src\main\java\org\baeldung\recovery\custom\JobInitializer.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPrefrenceAreaId() {
return prefrenceAreaId;
}
public void setPrefrenceAreaId(Long prefrenceAreaId) {
this.prefrenceAreaId = prefrenceAreaId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
|
this.productId = productId;
}
@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(", prefrenceAreaId=").append(prefrenceAreaId);
sb.append(", productId=").append(productId);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceAreaProductRelation.java
| 1
|
请完成以下Java代码
|
private Optional<ExternalSystemLeichMehlConfigProductMapping> matchProductMappingConfig(
@NonNull final I_PP_Order ppOrder,
@NonNull final PLUType pluType)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoIdOrNull(ppOrder.getC_BPartner_ID());
final ProductId ppOrderProductId = ProductId.ofRepoId(ppOrder.getM_Product_ID());
return externalSystemLeichMehlConfigProductMappingRepository.getByQuery(ExternalSystemLeichConfigProductMappingQuery.builder()
.productId(ppOrderProductId)
.bPartnerId(bPartnerId)
.pluType(pluType)
.build());
}
@NonNull
private static String toJsonProductMapping(@NonNull final String pluFile, @NonNull final ProductId productId)
{
final JsonMetasfreshId jsonProductId = JsonMetasfreshId.of(productId.getRepoId());
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper()
.writeValueAsString(
JsonExternalSystemLeichMehlConfigProductMapping.builder()
.pluFile(pluFile)
.productId(jsonProductId)
.build());
}
catch (final JsonProcessingException e)
|
{
throw AdempiereException.wrapIfNeeded(e);
}
}
@NonNull
private static String toJsonPluFileConfig(@NonNull final List<ExternalSystemLeichMehlPluFileConfig> configs)
{
final List<JsonExternalSystemLeichMehlPluFileConfig> jsonConfigs = configs.stream()
.map(config -> JsonExternalSystemLeichMehlPluFileConfig.builder()
.targetFieldName(config.getTargetFieldName())
.targetFieldType(JsonTargetFieldType.ofCode(config.getTargetFieldType().getCode()))
.replacePattern(config.getReplaceRegExp())
.replacement(config.getReplacement())
.replacementSource(JsonReplacementSource.ofCode(config.getReplacementSource().getCode()))
.build())
.collect(ImmutableList.toImmutableList());
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper()
.writeValueAsString(JsonExternalSystemLeichMehlPluFileConfigs.builder()
.pluFileConfigs(jsonConfigs)
.build());
}
catch (final JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\leichmehl\ExportPPOrderToLeichMehlService.java
| 1
|
请完成以下Java代码
|
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Single Row Layout.
@param IsSingleRow
Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public void setIsSingleRow (boolean IsSingleRow)
{
set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow));
}
/** Get Single Row Layout.
@return Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public boolean isSingleRow ()
{
Object oo = get_Value(COLUMNNAME_IsSingleRow);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Tab.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setC_Flatrate_DataEntry_IncludedT (final @Nullable java.lang.String C_Flatrate_DataEntry_IncludedT)
{
set_Value (COLUMNNAME_C_Flatrate_DataEntry_IncludedT, C_Flatrate_DataEntry_IncludedT);
}
@Override
public java.lang.String getC_Flatrate_DataEntry_IncludedT()
{
return get_ValueAsString(COLUMNNAME_C_Flatrate_DataEntry_IncludedT);
}
@Override
public void setC_Flatrate_Data_ID (final int C_Flatrate_Data_ID)
{
if (C_Flatrate_Data_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Data_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Data_ID, C_Flatrate_Data_ID);
|
}
@Override
public int getC_Flatrate_Data_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Data_ID);
}
@Override
public void setHasContracts (final boolean HasContracts)
{
set_Value (COLUMNNAME_HasContracts, HasContracts);
}
@Override
public boolean isHasContracts()
{
return get_ValueAsBoolean(COLUMNNAME_HasContracts);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Data.java
| 1
|
请完成以下Java代码
|
public BigDecimal getOvertimeCost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OvertimeCost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
|
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_UserRemuneration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void run(String... args) throws JobExecutionException {
logger.info("Running default command line with: " + Arrays.asList(args));
Properties properties = StringUtils.splitArrayElementsIntoProperties(args, "=");
launchJobFromProperties((properties != null) ? properties : new Properties());
}
protected void launchJobFromProperties(Properties properties) throws JobExecutionException {
JobParameters jobParameters = this.converter.getJobParameters(properties);
executeLocalJobs(jobParameters);
executeRegisteredJobs(jobParameters);
}
private boolean isLocalJob(String jobName) {
return this.jobs.stream().anyMatch((job) -> job.getName().equals(jobName));
}
private boolean isRegisteredJob(String jobName) {
return this.jobRegistry != null && this.jobRegistry.getJobNames().contains(jobName);
}
private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException {
for (Job job : this.jobs) {
if (StringUtils.hasText(this.jobName)) {
if (!this.jobName.equals(job.getName())) {
logger.debug(LogMessage.format("Skipped job: %s", job.getName()));
continue;
|
}
}
execute(job, jobParameters);
}
}
private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException {
if (this.jobRegistry != null && StringUtils.hasText(this.jobName)) {
if (!isLocalJob(this.jobName)) {
Job job = this.jobRegistry.getJob(this.jobName);
Assert.notNull(job, () -> "No job found with name '" + this.jobName + "'");
execute(job, jobParameters);
}
}
}
protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException, InvalidJobParametersException {
JobExecution execution = this.jobOperator.start(job, jobParameters);
if (this.publisher != null) {
this.publisher.publishEvent(new JobExecutionEvent(execution));
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-batch\src\main\java\org\springframework\boot\batch\autoconfigure\JobLauncherApplicationRunner.java
| 2
|
请完成以下Java代码
|
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
|
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDisabled() {
return disabled;
}
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public Integer getIsLdap() {
return isLdap;
}
public void setIsLdap(Integer isLdap) {
this.isLdap = isLdap;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
|
repos\springBoot-master\springboot-jpa\src\main\java\com\us\example\bean\User.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExternalSystemStatusRepository
{
@NonNull
public ExternalSystemStatus create(@NonNull final ExternalSystemServiceInstanceId instanceId, @NonNull final StoreExternalSystemStatusRequest request)
{
final I_ExternalSystem_Status record = newInstance(I_ExternalSystem_Status.class);
record.setExternalSystem_Service_Instance_ID(instanceId.getRepoId());
record.setExternalSystemStatus(request.getStatus().getCode());
record.setExternalSystemMessage(request.getMessage());
record.setAD_PInstance_ID(PInstanceId.toRepoId(request.getPInstanceId()));
record.setAD_Issue_ID(AdIssueId.toRepoId(request.getAdIssueId()));
saveRecord(record);
return ofStatusRecord(record);
|
}
@NonNull
public ExternalSystemStatus ofStatusRecord(@NonNull final I_ExternalSystem_Status record)
{
return ExternalSystemStatus.builder()
.id(ExternalSystemStatusId.ofRepoId(record.getExternalSystem_Status_ID()))
.instanceId(ExternalSystemServiceInstanceId.ofRepoId(record.getExternalSystem_Service_Instance_ID()))
.status(ExternalStatus.ofCode(record.getExternalSystemStatus()))
.issueId(AdIssueId.ofRepoIdOrNull(record.getAD_Issue_ID()))
.pInstanceId(PInstanceId.ofRepoIdOrNull(record.getAD_PInstance_ID()))
.message(record.getExternalSystemMessage())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\status\ExternalSystemStatusRepository.java
| 2
|
请完成以下Java代码
|
public String getTitle()
{
final String name = getName();
if (Check.isEmpty(name, true))
{
return null;
}
return Services.get(IMsgBL.class).translate(Env.getCtx(), name);
}
/** @return action's name (not translated) */
protected abstract String getName();
public final VEditor getEditor()
{
if (context == null)
{
return null;
}
return context.getEditor();
}
public final GridField getGridField()
{
final VEditor editor = getEditor();
if (editor == null)
{
return null;
}
final GridField gridField = editor.getField();
return gridField;
}
public final GridTab getGridTab()
{
final GridField gridField = getGridField();
if (gridField == null)
{
return null;
}
return gridField.getGridTab();
}
@Override
public List<IContextMenuAction> getChildren()
{
return Collections.emptyList();
}
@Override
public boolean isLongOperation()
{
return false;
}
@Override
public boolean isHideWhenNotRunnable()
{
return true; // hide when not runnable - backward compatibility
}
protected final String getColumnName()
{
final GridField gridField = getGridField();
if (gridField == null)
{
return null;
}
final String columnName = gridField.getColumnName();
return columnName;
}
protected final Object getFieldValue()
{
final IContextMenuActionContext context = getContext();
if (context == null)
{
return null;
}
//
// Get value when in Grid Mode
final VTable vtable = context.getVTable();
final int row = context.getViewRow();
final int column = context.getViewColumn();
if (vtable != null && row >= 0 && column >= 0)
{
final Object value = vtable.getValueAt(row, column);
return value;
}
|
// Get value when in single mode
else
{
final GridField gridField = getGridField();
if (gridField == null)
{
return null;
}
final Object value = gridField.getValue();
return value;
}
}
protected final GridController getGridController()
{
final IContextMenuActionContext context = getContext();
if (context == null)
{
return null;
}
final VTable vtable = context.getVTable();
final Component comp;
if (vtable != null)
{
comp = vtable;
}
else
{
final VEditor editor = getEditor();
if (editor instanceof Component)
{
comp = (Component)editor;
}
else
{
comp = null;
}
}
Component p = comp;
while (p != null)
{
if (p instanceof GridController)
{
return (GridController)p;
}
p = p.getParent();
}
return null;
}
protected final boolean isGridMode()
{
final GridController gc = getGridController();
if (gc == null)
{
return false;
}
final boolean gridMode = !gc.isSingleRow();
return gridMode;
}
@Override
public KeyStroke getKeyStroke()
{
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\AbstractContextMenuAction.java
| 1
|
请完成以下Java代码
|
public void setRemindDays (int RemindDays)
{
set_Value (COLUMNNAME_RemindDays, Integer.valueOf(RemindDays));
}
/** Get Reminder Days.
@return Days between sending Reminder Emails for a due or inactive Document
*/
public int getRemindDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RemindDays);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_User getSupervisor() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSupervisor_ID(), get_TrxName()); }
/** Set Supervisor.
@param Supervisor_ID
Supervisor for this user/organization - used for escalation and approval
*/
|
public void setSupervisor_ID (int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Integer.valueOf(Supervisor_ID));
}
/** Get Supervisor.
@return Supervisor for this user/organization - used for escalation and approval
*/
public int getSupervisor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Supervisor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WorkflowProcessor.java
| 1
|
请完成以下Java代码
|
public static <T extends Spin<?>> T S(Object input) {
return SpinFactory.INSTANCE.createSpin(input);
}
/**
* Creates a spin wrapper for a data input. The data format of the
* input is assumed to be XML.
*
* @param input the input to wrap
* @return the spin wrapper for the input
*
* @throws IllegalArgumentException in case an argument of illegal type is provided (such as 'null')
*/
public static SpinXmlElement XML(Object input) {
return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());
}
/**
* Creates a spin wrapper for a data input. The data format of the
* input is assumed to be JSON.
*
* @param input the input to wrap
* @return the spin wrapper for the input
*
* @throws IllegalArgumentException in case an argument of illegal type is provided (such as 'null')
*/
public static SpinJsonNode JSON(Object input) {
return SpinFactory.INSTANCE.createSpin(input, DataFormats.json());
}
/**
* Provides the name of the dataformat used by this spin.
*
* @return the name of the dataformat used by this Spin.
*/
public abstract String getDataFormatName();
/**
* Return the wrapped object. The return type of this method
* depends on the concrete data format.
*
* @return the object wrapped by this wrapper.
*/
public abstract Object unwrap();
/**
* Returns the wrapped object as string representation.
*
* @return the string representation
*/
public abstract String toString();
|
/**
* Writes the wrapped object to a existing writer.
*
* @param writer the writer to write to
*/
public abstract void writeToWriter(Writer writer);
/**
* Maps the wrapped object to an instance of a java class.
*
* @param type the java class to map to
* @return the mapped object
*/
public abstract <C> C mapTo(Class<C> type);
/**
* Maps the wrapped object to a java object.
* The object is determined based on the configuration string
* which is data format specific.
*
* @param type the class name to map to
* @return the mapped object
*/
public abstract <C> C mapTo(String type);
}
|
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\Spin.java
| 1
|
请完成以下Java代码
|
public void registerType(ModelElementType modelElementType, Class<? extends ModelElementInstance> instanceType) {
QName qName = ModelUtil.getQName(modelElementType.getTypeNamespace(), modelElementType.getTypeName());
typesByName.put(qName, modelElementType);
typesByClass.put(instanceType, modelElementType);
}
public String getModelName() {
return modelName;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((modelName == null) ? 0 : modelName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
|
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ModelImpl other = (ModelImpl) obj;
if (modelName == null) {
if (other.modelName != null) {
return false;
}
} else if (!modelName.equals(other.modelName)) {
return false;
}
return true;
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelImpl.java
| 1
|
请完成以下Java代码
|
public void onAttributeValueChanged(
@NonNull final IAttributeValueContext attributeValueContext,
@NonNull final IAttributeStorage storage,
IAttributeValue attributeValue,
Object valueOld)
{
final AbstractHUAttributeStorage huAttributeStorage = AbstractHUAttributeStorage.castOrNull(storage);
final boolean storageIsAboutHUs = huAttributeStorage != null;
if (!storageIsAboutHUs)
{
return;
}
if (!storage.hasAttribute(HUAttributeConstants.ATTR_Quarantine))
{
return;
}
|
final AttributeCode attributeCode = attributeValue.getAttributeCode();
final boolean relevantAttributeHasChanged = AttributeConstants.ATTR_LotNumber.equals(attributeCode);
if (!relevantAttributeHasChanged)
{
return;
}
if (lotNumberQuarantineService.isQuarantineLotNumber(huAttributeStorage))
{
storage.setValue(HUAttributeConstants.ATTR_Quarantine, HUAttributeConstants.ATTR_Quarantine_Value_Quarantine);
}
else
{
storage.setValue(HUAttributeConstants.ATTR_Quarantine, null);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\quarantine\QuarantineAttributeStorageListener.java
| 1
|
请完成以下Java代码
|
protected final String doIt() throws Exception
{
final I_M_ReceiptSchedule receiptSchedule = getM_ReceiptSchedule();
final IMutableHUContext huContextInitial = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(getCtx(), ClientAndOrgId.ofClientAndOrg(receiptSchedule.getAD_Client_ID(), receiptSchedule.getAD_Org_ID()));
final ReceiptScheduleHUGenerator huGenerator = ReceiptScheduleHUGenerator.newInstance(huContextInitial)
.addM_ReceiptSchedule(receiptSchedule)
.setUpdateReceiptScheduleDefaultConfiguration(isUpdateReceiptScheduleDefaultConfiguration());
//
// Get/Create the initial LU/TU configuration
final I_M_HU_LUTU_Configuration lutuConfigurationOrig = getCurrentLUTUConfiguration(receiptSchedule);
//
// Create the effective LU/TU configuration
final I_M_HU_LUTU_Configuration lutuConfiguration = createM_HU_LUTU_Configuration(lutuConfigurationOrig);
Services.get(ILUTUConfigurationFactory.class).save(lutuConfiguration);
huGenerator.setM_HU_LUTU_Configuration(lutuConfiguration);
//
// Calculate the target CUs that we want to allocate
final ILUTUProducerAllocationDestination lutuProducer = huGenerator.getLUTUProducerAllocationDestination();
final Quantity qtyCUsTotal = lutuProducer.calculateTotalQtyCU();
if (qtyCUsTotal.isInfinite())
{
throw new AdempiereException("LU/TU configuration is resulting to infinite quantity: " + lutuConfiguration);
}
huGenerator.setQtyToAllocateTarget(qtyCUsTotal);
|
//
// Generate the HUs
final List<I_M_HU> hus = huGenerator.generateWithinOwnTransaction();
hus.forEach(hu -> {
updateAttributes(hu, receiptSchedule);
});
openHUsToReceive(hus);
return MSG_OK;
}
protected final I_M_ReceiptSchedule getM_ReceiptSchedule()
{
return getRecord(I_M_ReceiptSchedule.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_Base.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getEdition() {
return edition;
|
}
public void setEdition(String edition) {
this.edition = edition;
}
public InternalsImpl getInternals() {
return internals;
}
public void setInternals(InternalsImpl internals) {
this.internals = internals;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\ProductImpl.java
| 1
|
请完成以下Java代码
|
public class EDIFillMandatoryException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = 9074980284529933724L;
/**
* NOTE: fields are considered not translated and they will be translated
*
* @param fields
*/
public EDIFillMandatoryException(final Collection<String> fields)
{
this(null, null, fields.toArray(new String[fields.size()]));
}
/**
* NOTE: fields are considered not translated and they will be translated
*
* @param recordName
* @param recordIdentifier
* @param fields
*/
public EDIFillMandatoryException(final String recordName, final String recordIdentifier, final String... fields)
{
super("@FillMandatory@ " + buildSubRecordIdentifier(recordName, recordIdentifier) + buildMessage(fields));
}
/**
* NOTE: fields are considered not translated and they will be translated
*
* @param recordName
* @param recordIdentifier
* @param fields
*/
public EDIFillMandatoryException(final String recordName, final String recordIdentifier, final Collection<String> fields)
{
this(recordName, recordIdentifier, fields.toArray(new String[fields.size()]));
}
private static String buildSubRecordIdentifier(final String recordName, final String recordIdentifier)
|
{
if (Check.isEmpty(recordName))
{
return "";
}
final StringBuilder sb = new StringBuilder()
.append("[@").append(recordName).append("@");
if (!Check.isEmpty(recordIdentifier))
{
sb.append(" (").append(recordIdentifier).append(")");
}
sb.append("] ");
return sb.toString();
}
private static final String buildMessage(final String... fields)
{
if (Check.isEmpty(fields))
{
return "";
}
final StringBuilder sb = new StringBuilder();
for (final String f : fields)
{
if (Check.isEmpty(f, true))
{
continue;
}
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append("@").append(f).append("@");
}
return sb.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\exception\EDIFillMandatoryException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CorsOnMethodsController {
@PutMapping("/cors-disabled-endpoint")
public Mono<String> corsDisabledEndpoint() {
return Mono.just("CORS disabled endpoint");
}
@CrossOrigin
@PutMapping("/cors-enabled-endpoint")
public Mono<String> corsEnabledEndpoint() {
return Mono.just("CORS enabled endpoint");
}
@CrossOrigin({ "http://allowed-origin.com" })
@PutMapping("/cors-enabled-origin-restrictive-endpoint")
public Mono<String> corsEnabledOriginRestrictiveEndpoint() {
return Mono.just("CORS enabled endpoint - Origin Restrictive");
}
@CrossOrigin(allowedHeaders = { "Baeldung-Allowed" })
@PutMapping("/cors-enabled-header-restrictive-endpoint")
|
public Mono<String> corsEnabledHeaderRestrictiveEndpoint() {
return Mono.just("CORS enabled endpoint - Header Restrictive");
}
@CrossOrigin(exposedHeaders = { "Baeldung-Exposed" })
@PutMapping("/cors-enabled-exposed-header-endpoint")
public Mono<String> corsEnabledExposedHeadersEndpoint() {
return Mono.just("CORS enabled endpoint - Exposed Header");
}
@PutMapping("/cors-enabled-mixed-config-endpoint")
@CrossOrigin(allowedHeaders = { "Baeldung-Allowed", "Baeldung-Other-Allowed" }, exposedHeaders = { "Baeldung-Allowed", "Baeldung-Exposed" }, maxAge = 3600)
public Mono<String> corsEnabledHeaderExposedEndpoint() {
return Mono.just("CORS enabled endpoint - Mixed Config");
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-security\src\main\java\com\baeldung\reactive\cors\annotated\controllers\CorsOnMethodsController.java
| 2
|
请完成以下Java代码
|
public class Company implements Serializable {
private String companyName;
private Integer label;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getLabel() {
|
return label;
}
public void setLabel(Integer label) {
this.label = label;
}
@Override
public String toString() {
return "Company{" +
"companyName='" + companyName + '\'' +
", label=" + label +
'}';
}
}
|
repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\entity\Company.java
| 1
|
请完成以下Java代码
|
public static String decrypt(String value)
{
if (value == null)
return null;
if (s_engine == null)
init(System.getProperties());
boolean inQuotes = value.startsWith("'") && value.endsWith("'");
if (inQuotes)
value = value.substring(1, value.length() - 1);
String retValue = null;
if (value.startsWith(SecureInterface.CLEARVALUE_START) && value.endsWith(SecureInterface.CLEARVALUE_END))
retValue = value.substring(SecureInterface.CLEARVALUE_START.length(), value.length() - SecureInterface.CLEARVALUE_END.length());
else
retValue = s_engine.implementation.decrypt(value);
if (inQuotes)
return "'" + retValue + "'";
return retValue;
} // decrypt
/**
* Encryption.
* The methods must recognize clear values
*
* @param value clear value
* @return encrypted String
*/
public static Object encrypt(Object value)
{
if (value instanceof String)
return encrypt((String)value);
return value;
} // encrypt
/**
* Decryption.
* The methods must recognize clear values
*
* @param value encrypted value
* @return decrypted String
*/
public static Object decrypt(Object value)
{
if (value instanceof String)
return decrypt((String)value);
return value;
} // decrypt
/** Test String */
private static final String TEST = "This is a 0123456789 .,; -= Test!";
/** Secure Engine */
private static SecureEngine s_engine = null;
/** The real Engine */
private SecureInterface implementation = null;
/** Logger */
private static final Logger log = LogManager.getLogger(SecureEngine.class);
/**
* SecureEngine constructor
*
* @param className class name if null defaults to org.compiere.util.Secure
*/
private SecureEngine(String className)
{
|
String realClass = className;
if (realClass == null || realClass.length() == 0)
realClass = SecureInterface.METASFRESH_SECURE_DEFAULT;
Exception cause = null;
try
{
final Class<?> clazz = Class.forName(realClass);
implementation = (SecureInterface)clazz.newInstance();
}
catch (Exception e)
{
cause = e;
}
if (implementation == null)
{
String msg = "Could not initialize: " + realClass + " - " + cause.toString()
+ "\nCheck start script parameter: " + SecureInterface.METASFRESH_SECURE;
log.error(msg);
System.err.println(msg);
System.exit(10);
}
// See if it works
String testE = implementation.encrypt(TEST);
String testC = implementation.decrypt(testE);
if (!testC.equals(TEST))
throw new IllegalStateException(realClass
+ ": " + TEST
+ "->" + testE + "->" + testC);
log.info("{} initialized - {}", realClass, implementation);
} // SecureEngine
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\SecureEngine.java
| 1
|
请完成以下Java代码
|
public void handleDependentEventSubscriptions(MigratingActivityInstance migratingInstance, List<EventSubscriptionEntity> eventSubscriptions) {
parser.getDependentEventSubscriptionHandler().handle(this, migratingInstance, eventSubscriptions);
}
public void handleDependentVariables(MigratingProcessElementInstance migratingInstance, List<VariableInstanceEntity> variables) {
parser.getDependentVariablesHandler().handle(this, migratingInstance, variables);
}
public void handleTransitionInstance(TransitionInstance transitionInstance) {
parser.getTransitionInstanceHandler().handle(this, transitionInstance);
}
public void validateNoEntitiesLeft(MigratingProcessInstanceValidationReportImpl processInstanceReport) {
processInstanceReport.setProcessInstanceId(migratingProcessInstance.getProcessInstanceId());
ensureNoEntitiesAreLeft("tasks", tasks, processInstanceReport);
ensureNoEntitiesAreLeft("externalTask", externalTasks, processInstanceReport);
|
ensureNoEntitiesAreLeft("incidents", incidents, processInstanceReport);
ensureNoEntitiesAreLeft("jobs", jobs, processInstanceReport);
ensureNoEntitiesAreLeft("event subscriptions", eventSubscriptions, processInstanceReport);
ensureNoEntitiesAreLeft("variables", variables, processInstanceReport);
}
public void ensureNoEntitiesAreLeft(String entityName, Collection<? extends DbEntity> dbEntities, MigratingProcessInstanceValidationReportImpl processInstanceReport) {
if (!dbEntities.isEmpty()) {
processInstanceReport.addFailure("Process instance contains not migrated " + entityName + ": [" + StringUtil.joinDbEntityIds(dbEntities) + "]");
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\MigratingInstanceParseContext.java
| 1
|
请完成以下Java代码
|
private String parseString(final String info)
{
if (info == null || info.isEmpty())
{
return null;
}
String retValue = info;
// Length restriction
if (maxLength > 0 && retValue.length() > maxLength)
{
retValue = retValue.substring(0, maxLength);
}
// copy characters (we need to look through anyway)
final StringBuilder out = new StringBuilder(retValue.length());
for (int i = 0; i < retValue.length(); i++)
{
char c = retValue.charAt(i);
if (c == '\'')
{
out.append("''");
}
else if (c == '\\')
{
out.append("\\\\");
}
else
{
out.append(c);
}
}
return out.toString();
}
private BigDecimal parseNumber(@Nullable final String valueStr)
{
if (valueStr == null || valueStr.isEmpty())
{
return null;
}
try
{
final String numberStringNormalized = normalizeNumberString(valueStr);
BigDecimal bd = new BigDecimal(numberStringNormalized);
if (divideBy100)
{
// NOTE: assumed two decimal scale
bd = bd.divide(Env.ONEHUNDRED, 2, BigDecimal.ROUND_HALF_UP);
}
return bd;
}
catch (final NumberFormatException ex)
{
throw new AdempiereException("@Invalid@ @Number@: " + valueStr, ex);
}
}
private boolean parseYesNo(String valueStr)
{
return StringUtils.toBoolean(valueStr, false);
}
private String normalizeNumberString(String info)
{
if (Check.isEmpty(info, true))
|
{
return "0";
}
final boolean hasPoint = info.indexOf('.') != -1;
boolean hasComma = info.indexOf(',') != -1;
// delete thousands
if (hasComma && decimalSeparator.isDot())
{
info = info.replace(',', ' ');
}
if (hasPoint && decimalSeparator.isComma())
{
info = info.replace('.', ' ');
}
hasComma = info.indexOf(',') != -1;
// replace decimal
if (hasComma && decimalSeparator.isComma())
{
info = info.replace(',', '.');
}
// remove everything but digits & '.' & '-'
char[] charArray = info.toCharArray();
final StringBuilder sb = new StringBuilder();
for (char element : charArray)
{
if (Character.isDigit(element) || element == '.' || element == '-')
{
sb.append(element);
}
}
final String numberStringNormalized = sb.toString().trim();
if (numberStringNormalized.isEmpty())
{
return "0";
}
return numberStringNormalized;
}
} // ImpFormatFow
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatColumn.java
| 1
|
请完成以下Java代码
|
private void insertBPLocationExternalRefIfMissing(
@NonNull final List<JsonRequestLocationUpsertItem> requestItems,
@NonNull final Map<ExternalId, JsonMetasfreshId> externalLocationId2MetasfreshId,
@Nullable final String orgCode)
{
requestItems.stream()
.map(JsonRequestLocationUpsertItem::getLocationExternalRef)
.filter(Objects::nonNull)
.map(locationExternalRef -> {
final ExternalId locationExternalId = ExternalId.of(locationExternalRef.getExternalReferenceItem().getLookupItem().getId());
return Optional.ofNullable(externalLocationId2MetasfreshId.get(locationExternalId))
.map(locationMFId -> buildExternalRefWithMetasfreshId(locationExternalRef, locationMFId))
.orElseGet(() -> {
logger.warn("*** WARN in insertBPLocationExternalRefIfMissing: no metasfreshId was found for the externalId: {}! "
+ "If this happened, something went wrong while upserting the bPartnerLocations", locationExternalId);
return null;
});
})
.filter(Objects::nonNull)
.forEach(createExternalRefReq -> externalReferenceRestControllerService.performInsertIfMissing(createExternalRefReq, orgCode));
}
@NonNull
private JsonSingleExternalReferenceCreateReq buildExternalRefWithMetasfreshId(
|
@NonNull final JsonSingleExternalReferenceCreateReq externalReferenceCreateReq,
@NonNull final JsonMetasfreshId metasfreshId)
{
final JsonExternalReferenceItem referenceItemWithMFId = JsonExternalReferenceItem
.builder()
.metasfreshId(metasfreshId)
.version(externalReferenceCreateReq.getExternalReferenceItem().getVersion())
.lookupItem(externalReferenceCreateReq.getExternalReferenceItem().getLookupItem())
.build();
return JsonSingleExternalReferenceCreateReq.builder()
.systemName(externalReferenceCreateReq.getSystemName())
.externalReferenceItem(referenceItemWithMFId)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\bpartnercomposite\jsonpersister\JsonPersisterService.java
| 1
|
请完成以下Java代码
|
private List<GenericZoomIntoTableWindow> retrieveTableWindows(
final @NonNull String tableName,
final boolean ignoreExcludeFromZoomTargetsFlag)
{
String sql = "SELECT * FROM ad_table_windows_v where TableName=?";
if(!ignoreExcludeFromZoomTargetsFlag)
{
sql += " AND IsExcludeFromZoomTargets='N'";
}
final @NonNull List<GenericZoomIntoTableWindow> windows = DB.retrieveRows(
sql,
ImmutableList.of(tableName),
this::retrieveTableWindow);
return windows;
}
private GenericZoomIntoTableWindow retrieveTableWindow(final ResultSet rs) throws SQLException
{
return GenericZoomIntoTableWindow.builder()
.priority(rs.getInt("priority"))
.adWindowId(AdWindowId.ofRepoId(rs.getInt("AD_Window_ID")))
.isDefaultSOWindow(StringUtils.toBoolean(rs.getString("IsDefaultSOWindow")))
.isDefaultPOWindow(StringUtils.toBoolean(rs.getString("IsDefaultPOWindow")))
.tabSqlWhereClause(StringUtils.trimBlankToNull(rs.getString("tab_whereClause")))
.build();
}
@Value
@Builder
private static class ParentLink
{
@NonNull String linkColumnName;
@NonNull String parentTableName;
}
@Nullable
private ParentLink getParentLink_HeaderForLine(@NonNull final POInfo poInfo)
{
final String tableName = poInfo.getTableName();
if (!tableName.endsWith("Line"))
{
return null;
}
final String parentTableName = tableName.substring(0, tableName.length() - "Line".length());
final String parentLinkColumnName = parentTableName + "_ID";
if (!poInfo.hasColumnName(parentLinkColumnName))
{
|
return null;
}
// virtual column parent link is not supported
if (poInfo.isVirtualColumn(parentLinkColumnName))
{
return null;
}
return ParentLink.builder()
.linkColumnName(parentLinkColumnName)
.parentTableName(parentTableName)
.build();
}
@Nullable
private ParentLink getParentLink_SingleParentColumn(@NonNull final POInfo poInfo)
{
final String parentLinkColumnName = poInfo.getSingleParentColumnName().orElse(null);
if (parentLinkColumnName == null)
{
return null;
}
// virtual column parent link is not supported
if (poInfo.isVirtualColumn(parentLinkColumnName))
{
return null;
}
final String parentTableName = poInfo.getReferencedTableNameOrNull(parentLinkColumnName);
if (parentTableName == null)
{
return null;
}
return ParentLink.builder()
.linkColumnName(parentLinkColumnName)
.parentTableName(parentTableName)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\DefaultGenericZoomIntoTableInfoRepository.java
| 1
|
请完成以下Java代码
|
public void extractKeyParts(final CacheKeyBuilder keyBuilder, final Object targetObject, final Object[] params)
{
final Object ctxObj = params[parameterIndex];
if (ctxObj == null)
{
keyBuilder.setSkipCaching();
final CacheGetException ex = new CacheGetException("Got null context parameter.")
.setTargetObject(targetObject)
.setMethodArguments(params)
.setInvalidParameter(parameterIndex, ctxObj)
.setAnnotation(CacheCtx.class);
logger.warn("Got null context object. Skip caching", ex);
return;
}
Properties ctx = null;
boolean error = false;
Exception errorException = null;
if (isModel)
{
try
{
ctx = InterfaceWrapperHelper.getCtx(ctxObj);
}
catch (final Exception ex)
{
error = true;
errorException = ex;
}
}
else if (ctxObj instanceof Properties)
{
ctx = (Properties)ctxObj;
}
else
{
error = true;
}
if (error)
{
keyBuilder.setSkipCaching();
final CacheGetException ex = new CacheGetException("Invalid parameter type.")
.addSuppressIfNotNull(errorException)
.setTargetObject(targetObject)
.setMethodArguments(params)
.setInvalidParameter(parameterIndex, ctxObj)
.setAnnotation(CacheCtx.class);
logger.warn("Invalid parameter type for @CacheCtx annotation. Skip caching.", ex);
return;
}
final ArrayKey key = buildCacheKey(ctx);
keyBuilder.add(key);
}
private static final ArrayKey buildCacheKey(final Properties ctx)
{
return new ArrayKey(
Env.getAD_Client_ID(ctx),
Env.getAD_Role_ID(ctx),
Env.getAD_User_ID(ctx),
Env.getAD_Language(ctx));
}
|
/**
* Method used to compare if to contexts are considered to be equal from caching perspective.
* Equality from caching perspective means that the following is equal:
* <ul>
* <li>AD_Client_ID
* <li>AD_Role_ID
* <li>AD_User_ID
* <li>AD_Language
* </ul>
*
* @param ctx1
* @param ctx2
* @return true if given contexts shall be considered equal from caching perspective
*/
public static final boolean isSameCtx(final Properties ctx1, final Properties ctx2)
{
if (ctx1 == ctx2)
{
return true;
}
if (ctx1 == null || ctx2 == null)
{
return false;
}
return buildCacheKey(ctx1).equals(buildCacheKey(ctx2));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheCtxParamDescriptor.java
| 1
|
请完成以下Java代码
|
public void completed(Integer result, ByteBuffer attachment) {
if (attachment.hasRemaining()) {
channel.write(attachment, attachment, this);
} else {
//读取客户端传回的数据
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
//异步读数据
channel.read(readBuffer, readBuffer,
new AioReadHandler(channel));
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
channel.close();
} catch (IOException e) {
|
e.printStackTrace();
}
}
});
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
this.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
repos\spring-boot-student-master\spring-boot-student-netty\src\main\java\com\xiaolyuh\aio\server\AioReadHandler.java
| 1
|
请完成以下Java代码
|
protected void instantiateScopes(
MigratingScopeInstance ancestorScopeInstance,
MigratingScopeInstanceBranch executionBranch,
List<ScopeImpl> scopesToInstantiate) {
if (scopesToInstantiate.isEmpty()) {
return;
}
ExecutionEntity ancestorScopeExecution = ancestorScopeInstance.resolveRepresentativeExecution();
ExecutionEntity parentExecution = ancestorScopeExecution;
for (ScopeImpl scope : scopesToInstantiate) {
ExecutionEntity compensationScopeExecution = parentExecution.createExecution();
compensationScopeExecution.setScope(true);
compensationScopeExecution.setEventScope(true);
|
compensationScopeExecution.setActivity((PvmActivity) scope);
compensationScopeExecution.setActive(false);
compensationScopeExecution.activityInstanceStarting();
compensationScopeExecution.enterActivityInstance();
EventSubscriptionEntity eventSubscription = EventSubscriptionEntity.createAndInsert(parentExecution, EventType.COMPENSATE, (ActivityImpl) scope);
eventSubscription.setConfiguration(compensationScopeExecution.getId());
executionBranch.visited(new MigratingEventScopeInstance(eventSubscription, compensationScopeExecution, scope));
parentExecution = compensationScopeExecution;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigrationCompensationInstanceVisitor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProductService {
public Product manualClone(Product original) {
Product clone = new Product();
clone.setName(original.getName());
clone.setCategory(original.getCategory());
clone.setPrice(original.getPrice());
return clone;
}
public Product manualDeepClone(Product original) {
Product clone = new Product();
clone.setName(original.getName());
clone.setPrice(original.getPrice());
if (original.getCategory() != null) {
Category categoryClone = new Category();
categoryClone.setName(original.getCategory()
.getName());
clone.setCategory(categoryClone);
}
return clone;
}
public Product cloneUsingSerialization(Product original) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(original);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in = new ObjectInputStream(byteIn);
Product clone = (Product) in.readObject();
in.close();
clone.setId(null);
|
return clone; // Return deep clone
}
public Product cloneUsingBeanUtils(Product original) throws InvocationTargetException, IllegalAccessException {
Product clone = new Product();
BeanUtils.copyProperties(original, clone);
clone.setId(null);
return clone;
}
public Product cloneUsingModelMapper(Product original) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration()
.setDeepCopyEnabled(true);
Product clone = modelMapper.map(original, Product.class);
clone.setId(null);
return clone;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\cloneentity\ProductService.java
| 2
|
请完成以下Java代码
|
public Map<String, LDAPGroupCacheEntry> getGroupCache() {
return groupCache;
}
public void setGroupCache(Map<String, LDAPGroupCacheEntry> groupCache) {
this.groupCache = groupCache;
}
public long getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(long expirationTime) {
this.expirationTime = expirationTime;
}
public LDAPGroupCacheListener getLdapCacheListener() {
return ldapCacheListener;
}
public void setLdapCacheListener(LDAPGroupCacheListener ldapCacheListener) {
this.ldapCacheListener = ldapCacheListener;
}
// Helper classes ////////////////////////////////////
static class LDAPGroupCacheEntry {
protected Date timestamp;
protected List<Group> groups;
public LDAPGroupCacheEntry() {
}
public LDAPGroupCacheEntry(Date timestamp, List<Group> groups) {
this.timestamp = timestamp;
this.groups = groups;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public List<Group> getGroups() {
|
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
}
// Cache listeners. Currently not yet exposed (only programmatically for the
// moment)
// Experimental stuff!
public static interface LDAPGroupCacheListener {
void cacheHit(String userId);
void cacheMiss(String userId);
void cacheEviction(String userId);
void cacheExpired(String userId);
}
}
|
repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\LDAPGroupCache.java
| 1
|
请完成以下Java代码
|
public char skipTo(char to) throws JSONException {
char c;
try {
int startIndex = this.index;
int startCharacter = this.character;
int startLine = this.line;
reader.mark(Integer.MAX_VALUE);
do {
c = next();
if (c == 0) {
reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
back();
return c;
}
/**
* Make a JSONException to signal a syntax error.
|
*
* @param message
* The error message.
* @return A JSONException object, suitable for throwing
*/
public JSONException syntaxError(String message) {
return new JSONException(message + toString());
}
/**
* Make a printable string of this JSONTokener.
*
* @return " at {index} [character {character} line {line}]"
*/
public String toString() {
return " at " + index + " [character " + this.character + " line " + this.line + "]";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\JSONTokener.java
| 1
|
请完成以下Java代码
|
public boolean reActivateIt()
{
log.info(toString());
// Before reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE);
if (m_processMsg != null)
return false;
setProcessed(false);
setDocAction(DOCACTION_Complete);
// Note:
// setting and saving the doc status here, because the model validator updates an invoice candidate, which in
// term will make sure that this data entry is not completed
setDocStatus(DOCSTATUS_InProgress);
Check.assume(get_TrxName() != null, this + " has trxName!=null");
saveEx();
// After reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE);
if (m_processMsg != null)
return false;
return true;
} // reActivateIt
@Override
public boolean rejectIt()
{
return true;
}
@Override
public boolean reverseAccrualIt()
{
log.info(toString());
// Before reverseAccrual
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL);
if (m_processMsg != null)
return false;
// After reverseAccrual
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL);
if (m_processMsg != null)
return false;
|
return true;
} // reverseAccrualIt
@Override
public boolean reverseCorrectIt()
{
log.info(toString());
// Before reverseCorrect
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT);
if (m_processMsg != null)
return false;
// After reverseCorrect
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT);
if (m_processMsg != null)
return false;
return true;
}
/**
* Unlock Document.
*
* @return true if success
*/
@Override
public boolean unlockIt()
{
log.info(toString());
setProcessing(false);
return true;
} // unlockIt
@Override
public boolean voidIt()
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateDataEntry.java
| 1
|
请完成以下Java代码
|
public String getPrefix() {
return "graphql";
}
@Override
public Class<? extends ObservationConvention<? extends Observation.Context>> getDefaultConvention() {
return DefaultDataLoaderObservationConvention.class;
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return DataLoaderLowCardinalityKeyNames.values();
}
@Override
public KeyName[] getHighCardinalityKeyNames() {
return DataLoaderHighCardinalityKeyNames.values();
}
};
public enum ExecutionRequestLowCardinalityKeyNames implements KeyName {
/**
* Outcome of the GraphQL request.
*/
OUTCOME {
@Override
public String asString() {
return "graphql.outcome";
}
},
/**
* GraphQL {@link graphql.language.OperationDefinition.Operation Operation type}.
*/
OPERATION_TYPE {
@Override
public String asString() {
return "graphql.operation.type";
}
}
}
public enum ExecutionRequestHighCardinalityKeyNames implements KeyName {
/**
* GraphQL Operation name.
*/
OPERATION_NAME {
@Override
public String asString() {
return "graphql.operation.name";
}
},
/**
* {@link graphql.execution.ExecutionId} of the GraphQL request.
*/
EXECUTION_ID {
@Override
public String asString() {
return "graphql.execution.id";
}
}
}
public enum DataFetcherLowCardinalityKeyNames implements KeyName {
/**
* Outcome of the GraphQL data fetching operation.
*/
OUTCOME {
@Override
public String asString() {
return "graphql.outcome";
}
},
/**
* Name of the field being fetched.
*/
FIELD_NAME {
@Override
public String asString() {
return "graphql.field.name";
}
},
|
/**
* Class name of the data fetching error.
*/
ERROR_TYPE {
@Override
public String asString() {
return "graphql.error.type";
}
}
}
public enum DataFetcherHighCardinalityKeyNames implements KeyName {
/**
* Path to the field being fetched.
*/
FIELD_PATH {
@Override
public String asString() {
return "graphql.field.path";
}
}
}
public enum DataLoaderLowCardinalityKeyNames implements KeyName {
/**
* Class name of the data fetching error.
*/
ERROR_TYPE {
@Override
public String asString() {
return "graphql.error.type";
}
},
/**
* {@link DataLoader#getName()} of the data loader.
*/
LOADER_NAME {
@Override
public String asString() {
return "graphql.loader.name";
}
},
/**
* Outcome of the GraphQL data fetching operation.
*/
OUTCOME {
@Override
public String asString() {
return "graphql.outcome";
}
}
}
public enum DataLoaderHighCardinalityKeyNames implements KeyName {
/**
* Size of the list of elements returned by the data loading operation.
*/
LOADER_SIZE {
@Override
public String asString() {
return "graphql.loader.size";
}
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\GraphQlObservationDocumentation.java
| 1
|
请完成以下Spring Boot application配置
|
logging:
level:
org.springframework.cloud.gateway: INFO
reactor.netty.http.client: INFO
spring:
redis:
host: localhost
port: 6379
cloud:
gateway:
filter:
local-response-cache:
enabled: true
timeToLive: 20m
size: 6MB
routes:
- id: request_header_route
uri: https://httpbin.org
predicates:
- Path=/get/**
filters:
- AddRequestHeader=My-Header-Good,Good
- AddRequestHeader=My-Header-Remove,Remove
- AddRequestHeadersIfNotPresent=My-Header-Absent:Absent
- AddRequestParameter=var, good
- AddRequestParameter=var2, remove
- MapRequestHeader=My-Header-Good, My-Header-Bad
- MapRequestHeader=My-Header-Set, My-Header-Bad
- SetRequestHeader=My-Header-Set, Set
- RemoveRequestHeader=My-Header-Remove
- RemoveRequestParameter=var2
- PreserveHostHeader
- id: response_header_route
uri: https://httpbin.org
predicates:
- Path=/header/post/**
filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
- SetResponseHeader=My-Header-Set, Set
- RemoveResponseHeader=My-Header-Remove
- RewriteResponseHeader=My-Header-Rewrite, password=[^&]+, password=***
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
- RemoveJsonAttributesResponseBody=form,Accept,true
- AddResponseHeader=My-Header-Good,Good
- AddResponseHeader=My-Header-Set,Good
- AddResponseHeader=My-Header-Remove,Remove
- AddResponseHeader=My-Header-Rewrite,password=12345678
- StripPrefix=1
- id: path_route
uri: https://httpbin.org
predicates:
- Path=/new/post/**
filters:
- RewritePath=/new(?<segment>/?.*), $\{segment}
- SetPath=/post
- id: redirect_route
uri: https://httpbin.org
predicates:
- Path=/fake/post/**
filters:
- RedirectTo=302, https://httpbin.org
- id: status_route
uri: https://httpbin.org
predicates:
- Path=/delete/**
filters:
- SetStatus=401
- id: size_route
uri: https://httpbin.org
predicates:
- Path=/anything
filters:
- name: RequestSize
args:
maxSize: 5000000
- id: retry_test
uri: https://httpbin.org
predicates:
- Path=/status/502
filters:
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY
methods: GET,POST
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor
|
: 2
basedOnPreviousValue: false
- id: circuitbreaker_route
uri: https://httpbin.org
predicates:
- Path=/status/504
filters:
- name: CircuitBreaker
args:
name: myCircuitBreaker
fallbackUri: forward:/anything
- RewritePath=/status/504, /anything
- id: request_rate_limiter
uri: https://httpbin.org
predicates:
- Path=/redis/get/**
filters:
- StripPrefix=1
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 5
redis-rate-limiter.requestedTokens: 1
key-resolver: "#{@userKeyResolver}"
- id: cache_request_body_route
uri: https://httpbin.org
predicates:
- Path=/cache/post/**
filters:
- StripPrefix=1
- name: CacheRequestBody
args:
bodyClass: java.lang.String
- id: cache_response_body_route
uri: https://httpbin.org
predicates:
- Path=/cache/get/**
filters:
- StripPrefix=1
- LocalResponseCache=10s,20MB
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\resources\application-webfilters.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class EventConfig {
private Logger logger = LoggerFactory.getLogger(getClass());
@OnTransition(target = "UNPAID")
public void create() {
logger.info("订单创建,待支付");
}
@OnTransition(source = "UNPAID", target = "WAITING_FOR_RECEIVE")
public void pay() {
logger.info("用户完成支付,待收货");
}
@OnTransitionStart(source = "UNPAID", target = "WAITING_FOR_RECEIVE")
|
public void payStart() {
logger.info("用户完成支付,待收货: start");
}
@OnTransitionEnd(source = "UNPAID", target = "WAITING_FOR_RECEIVE")
public void payEnd() {
logger.info("用户完成支付,待收货: end");
}
@OnTransition(source = "WAITING_FOR_RECEIVE", target = "DONE")
public void receive() {
logger.info("用户已收货,订单完成");
}
}
|
repos\SpringBoot-Learning-master\1.x\Chapter6-1-1\src\main\java\com\didispace\EventConfig.java
| 2
|
请完成以下Java代码
|
public static BinTrie<CoreDictionary.Attribute> getTrie()
{
return DEFAULT.getTrie();
}
/**
* 解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构)
*
* @param text 文本
* @param processor 处理器
*/
public static void parseText(char[] text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor)
{
DEFAULT.parseText(text, processor);
}
/**
* 解析一段文本(目前采用了BinTrie+DAT的混合储存形式,此方法可以统一两个数据结构)
*
* @param text 文本
* @param processor 处理器
*/
public static void parseText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor)
{
DEFAULT.parseText(text, processor);
}
/**
|
* 最长匹配
*
* @param text 文本
* @param processor 处理器
*/
public static void parseLongestText(String text, AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute> processor)
{
DEFAULT.parseLongestText(text, processor);
}
/**
* 热更新(重新加载)<br>
* 集群环境(或其他IOAdapter)需要自行删除缓存文件(路径 = HanLP.Config.CustomDictionaryPath[0] + Predefine.BIN_EXT)
*
* @return 是否加载成功
*/
public static boolean reload()
{
return DEFAULT.reload();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CustomDictionary.java
| 1
|
请完成以下Java代码
|
void sendAttachmentAsEmail(
@NonNull final Mailbox mailBox,
@NonNull final EMailAddress mailTo,
@NonNull final AttachmentEntry attachmentEntry)
{
final byte[] data = attachmentEntryService.retrieveData(attachmentEntry.getId());
final String csvDataString = new String(data, DerKurierConstants.CSV_DATA_CHARSET);
final String subject = msgBL.getMsg(Env.getCtx(), SYSCONFIG_DerKurier_DeliveryOrder_EmailSubject);
final String message = msgBL.getMsg(Env.getCtx(), SYSCONFIG_DerKurier_DeliveryOrder_EmailMessage, new Object[] { csvDataString });
mailService.sendEMail(EMailRequest.builder()
.mailbox(mailBox)
.to(mailTo)
.subject(subject)
.message(message)
|
.html(false)
.build());
// we don't have an AD_Archive..
// final I_AD_User user = loadOutOfTrx(Env.getAD_User_ID(), I_AD_User.class);
// final IArchiveEventManager archiveEventManager = Services.get(IArchiveEventManager.class);
// archiveEventManager.fireEmailSent(
// null,
// X_C_Doc_Outbound_Log_Line.ACTION_EMail,
// user,
// null/* from */,
// mailTo,
// null /* cc */,
// null /* bcc */,
// IArchiveEventManager.STATUS_MESSAGE_SENT);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\DerKurierDeliveryOrderEmailer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AsyncSecurPharmActionsDispatcher implements SecurPharmActionsDispatcher
{
private static final Topic TOPIC = Topic.distributed("de.metas.vertical.pharma.securpharm.actions");
private static final Logger logger = LogManager.getLogger(AsyncSecurPharmActionsDispatcher.class);
private final IEventBus eventBus;
private final Executor executor;
private final ImmutableList<SecurPharmActionsHandler> handlers;
public AsyncSecurPharmActionsDispatcher(
@NonNull final IEventBusFactory eventBusFactory,
@NonNull Optional<List<SecurPharmActionsHandler>> handlers)
{
this.eventBus = eventBusFactory.getEventBus(TOPIC);
this.executor = createAsyncExecutor();
this.handlers = handlers.map(ImmutableList::copyOf).orElseGet(ImmutableList::of);
this.handlers.forEach(handler -> {
final AsyncSecurPharmActionsHandler asyncHandler = new AsyncSecurPharmActionsHandler(handler, executor);
eventBus.subscribeOn(SecurPharmaActionRequest.class, asyncHandler::handleActionRequest);
logger.info("Registered: {}", asyncHandler);
});
}
private static Executor createAsyncExecutor()
{
final CustomizableThreadFactory asyncThreadFactory = new CustomizableThreadFactory(SecurPharmActionProcessor.class.getSimpleName());
asyncThreadFactory.setDaemon(true);
return Executors.newSingleThreadExecutor(asyncThreadFactory);
}
|
@Override
public void setSecurPharmService(@NonNull final SecurPharmService securPharmService)
{
this.handlers.forEach(handler -> handler.setSecurPharmService(securPharmService));
}
@Override
public void post(@NonNull final SecurPharmaActionRequest request)
{
eventBus.enqueueObject(request);
}
@ToString(of = "delegate")
private static class AsyncSecurPharmActionsHandler
{
private final SecurPharmActionsHandler delegate;
private final Executor executor;
private AsyncSecurPharmActionsHandler(
@NonNull final SecurPharmActionsHandler delegate,
@NonNull final Executor executor)
{
this.delegate = delegate;
this.executor = executor;
}
public void handleActionRequest(@NonNull final SecurPharmaActionRequest request)
{
executor.execute(() -> delegate.handleActionRequest(request));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\actions\AsyncSecurPharmActionsDispatcher.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UmsMenuServiceImpl implements UmsMenuService {
@Autowired
private UmsMenuMapper menuMapper;
@Override
public int create(UmsMenu umsMenu) {
umsMenu.setCreateTime(new Date());
updateLevel(umsMenu);
return menuMapper.insert(umsMenu);
}
/**
* 修改菜单层级
*/
private void updateLevel(UmsMenu umsMenu) {
if (umsMenu.getParentId() == 0) {
//没有父菜单时为一级菜单
umsMenu.setLevel(0);
} else {
//有父菜单时为父菜单的level+1
UmsMenu parentMenu = menuMapper.selectByPrimaryKey(umsMenu.getParentId());
if (parentMenu != null) {
umsMenu.setLevel(parentMenu.getLevel() + 1);
} else {
umsMenu.setLevel(0);
}
}
}
@Override
public int update(Long id, UmsMenu umsMenu) {
umsMenu.setId(id);
updateLevel(umsMenu);
return menuMapper.updateByPrimaryKeySelective(umsMenu);
}
@Override
public UmsMenu getItem(Long id) {
return menuMapper.selectByPrimaryKey(id);
}
@Override
public int delete(Long id) {
return menuMapper.deleteByPrimaryKey(id);
}
@Override
public List<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum, pageSize);
UmsMenuExample example = new UmsMenuExample();
|
example.setOrderByClause("sort desc");
example.createCriteria().andParentIdEqualTo(parentId);
return menuMapper.selectByExample(example);
}
@Override
public List<UmsMenuNode> treeList() {
List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
List<UmsMenuNode> result = menuList.stream()
.filter(menu -> menu.getParentId().equals(0L))
.map(menu -> covertMenuNode(menu, menuList))
.collect(Collectors.toList());
return result;
}
@Override
public int updateHidden(Long id, Integer hidden) {
UmsMenu umsMenu = new UmsMenu();
umsMenu.setId(id);
umsMenu.setHidden(hidden);
return menuMapper.updateByPrimaryKeySelective(umsMenu);
}
/**
* 将UmsMenu转化为UmsMenuNode并设置children属性
*/
private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
UmsMenuNode node = new UmsMenuNode();
BeanUtils.copyProperties(menu, node);
List<UmsMenuNode> children = menuList.stream()
.filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
.map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
node.setChildren(children);
return node;
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsMenuServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Company {
private Integer id;
private String name;
public Company(){}
public Company(Integer id, String name){
this.id = id;
this.name =name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId(){
|
return id;
}
public void setId(Integer id){
this.id =id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-5 Spring Boot Web Application\SpringMVC+DB\src\main\java\spring\mvc\domain\Company.java
| 2
|
请完成以下Java代码
|
public class PPOrderUserNotificationsProducer
{
public static final Topic USER_NOTIFICATIONS_TOPIC = Topic.builder()
.name("de.metas.manufacturing.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
private static final AdMessageKey MSG_Event_PPOrderGenerated = AdMessageKey.of("EVENT_PP_Order_Generated");
private final transient INotificationBL notificationBL = Services.get(INotificationBL.class);
private PPOrderUserNotificationsProducer()
{
}
public static PPOrderUserNotificationsProducer newInstance()
{
return new PPOrderUserNotificationsProducer();
}
public PPOrderUserNotificationsProducer notifyGenerated(final Collection<? extends I_PP_Order> ppOrders)
{
if (ppOrders == null || ppOrders.isEmpty())
{
return this;
}
postNotifications(ppOrders.stream()
.map(this::createUserNotification)
.collect(ImmutableList.toImmutableList()));
return this;
}
public final PPOrderUserNotificationsProducer notifyGenerated(@NonNull final I_PP_Order ppOrder)
{
notifyGenerated(ImmutableList.of(ppOrder));
return this;
}
|
private UserNotificationRequest createUserNotification(@NonNull final I_PP_Order ppOrder)
{
final UserId recipientUserId = getNotificationRecipientUserId(ppOrder);
final TableRecordReference ppOrderRef = TableRecordReference.of(ppOrder);
return newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(MSG_Event_PPOrderGenerated)
.contentADMessageParam(ppOrderRef)
.targetAction(TargetRecordAction.of(ppOrderRef))
.build();
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private UserId getNotificationRecipientUserId(final I_PP_Order ppOrder)
{
return UserId.ofRepoId(ppOrder.getCreatedBy());
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\event\PPOrderUserNotificationsProducer.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.